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
9cb2704217e2083c20258d1cbf209024dcb421e1
0
chrishantha/msf4j,chrishantha/msf4j,arunasujith/msf4j,thusithathilina/msf4j,callkalpa/product-mss,chrishantha/msf4j,arunasujith/msf4j,bsenduran/product-mss,thusithathilina/msf4j,sameera-jayasoma/product-mss,sameera-jayasoma/product-mss,tikaa/msf4j,sameera-jayasoma/product-mss,wso2/msf4j,callkalpa/product-mss,arunasujith/msf4j,wso2/product-mss,thusithathilina/msf4j,callkalpa/product-mss,wso2/msf4j,wso2/product-mss,callkalpa/product-mss,tikaa/msf4j,bsenduran/product-mss,tikaa/msf4j,tikaa/msf4j,arunasujith/msf4j,bsenduran/product-mss,chrishantha/msf4j,sameera-jayasoma/product-mss,thusithathilina/msf4j,bsenduran/product-mss,wso2/msf4j,wso2/product-mss,wso2/product-mss
/* * Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.wso2.msf4j.internal.swagger; import io.swagger.util.Json; import org.wso2.msf4j.internal.MicroservicesRegistry; import java.util.HashMap; import java.util.Map; import java.util.Optional; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; /** * This service returns the Swagger definition of all the APIs of the microservices deployed in this runtime. */ @Path("/swagger") public class SwaggerDefinitionService { private static final String GLOBAL = "global"; private Map<String, MSF4JBeanConfig> swaggerBeans = new HashMap<>(); private MicroservicesRegistry serviceRegistry; public SwaggerDefinitionService(MicroservicesRegistry serviceRegistry) { this.serviceRegistry = serviceRegistry; } @GET public Response getSwaggerDefinition(@QueryParam("path") String path) throws Exception { MSF4JBeanConfig msf4JBeanConfig; if (path == null) { msf4JBeanConfig = swaggerBeans.get(GLOBAL); if (msf4JBeanConfig == null) { MSF4JBeanConfig beanConfig = new MSF4JBeanConfig(); serviceRegistry.getHttpServices().stream(). forEach(service -> beanConfig.addServiceClass(service.getClass())); beanConfig.setScan(true); msf4JBeanConfig = beanConfig; swaggerBeans.put(GLOBAL, msf4JBeanConfig); } } else { msf4JBeanConfig = swaggerBeans.get(path); if (msf4JBeanConfig == null) { Optional<Object> service = serviceRegistry.getServiceWithBasePath(path); if (service.isPresent()) { MSF4JBeanConfig beanConfig = new MSF4JBeanConfig(); beanConfig.addServiceClass(service.get().getClass()); beanConfig.setScan(true); msf4JBeanConfig = beanConfig; swaggerBeans.put(path, msf4JBeanConfig); } } } return (msf4JBeanConfig == null) ? Response.status(Response.Status.NOT_FOUND). entity("No Swagger definition found for path " + path).build() : Response.status(Response.Status.OK). entity(Json.mapper(). writerWithDefaultPrettyPrinter().writeValueAsString(msf4JBeanConfig.getSwagger())). build(); } }
core/src/main/java/org/wso2/msf4j/internal/swagger/SwaggerDefinitionService.java
/* * Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.wso2.msf4j.internal.swagger; import io.swagger.util.Json; import org.wso2.msf4j.internal.MicroservicesRegistry; import java.util.HashMap; import java.util.Map; import java.util.Optional; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; /** * This service returns the Swagger definition of all the APIs of the microservices deployed in this runtime. */ @Path("/swagger") public class SwaggerDefinitionService { private static final String GLOBAL = "global"; private Map<String, MSF4JBeanConfig> swaggerBeans = new HashMap<>(); private MicroservicesRegistry serviceRegistry; public SwaggerDefinitionService(MicroservicesRegistry serviceRegistry) { this.serviceRegistry = serviceRegistry; } @GET public Response getSwaggerDefinition(@QueryParam("path") String path) throws Exception { MSF4JBeanConfig msf4JBeanConfig; if (path == null) { msf4JBeanConfig = swaggerBeans.get(GLOBAL); if (msf4JBeanConfig == null) { MSF4JBeanConfig beanConfig = new MSF4JBeanConfig(); serviceRegistry.getHttpServices().stream(). forEach(service -> beanConfig.addServiceClass(service.getClass())); beanConfig.setScan(true); msf4JBeanConfig = beanConfig; swaggerBeans.put(GLOBAL, msf4JBeanConfig); } } else { msf4JBeanConfig = swaggerBeans.get(path); if (msf4JBeanConfig == null) { Optional<Object> service = serviceRegistry.getServiceWithBasePath(path); if (service.isPresent()) { MSF4JBeanConfig beanConfig = new MSF4JBeanConfig(); beanConfig.addServiceClass(service.get().getClass()); beanConfig.setScan(true); msf4JBeanConfig = beanConfig; swaggerBeans.put(path, msf4JBeanConfig); } } } return (msf4JBeanConfig == null) ? Response.status(Response.Status.NOT_FOUND).build() : Response.status(Response.Status.OK). entity(Json.mapper(). writerWithDefaultPrettyPrinter().writeValueAsString(msf4JBeanConfig.getSwagger())). build(); } }
Added message when a 404 is sent
core/src/main/java/org/wso2/msf4j/internal/swagger/SwaggerDefinitionService.java
Added message when a 404 is sent
<ide><path>ore/src/main/java/org/wso2/msf4j/internal/swagger/SwaggerDefinitionService.java <ide> } <ide> } <ide> return (msf4JBeanConfig == null) ? <del> Response.status(Response.Status.NOT_FOUND).build() : <add> Response.status(Response.Status.NOT_FOUND). <add> entity("No Swagger definition found for path " + path).build() : <ide> Response.status(Response.Status.OK). <ide> entity(Json.mapper(). <ide> writerWithDefaultPrettyPrinter().writeValueAsString(msf4JBeanConfig.getSwagger())).
Java
apache-2.0
d18301cb1379250113946826e65919d7577563d6
0
GaryWKeim/ehcache3,ljacomet/ehcache3,wantstudy/ehcache3,lorban/ehcache3,jhouserizer/ehcache3,rkavanap/ehcache3,AbfrmBlr/ehcache3,lorban/ehcache3,292388900/ehcache3,CapeSepias/ehcache3,cljohnso/ehcache3,ehcache/ehcache3,ljacomet/ehcache3,chrisdennis/ehcache3,palmanojkumar/ehcache3,aurbroszniowski/ehcache3,mingyaaaa/ehcache3,alexsnaps/ehcache3,cschanck/ehcache3,ehcache/ehcache3,henri-tremblay/ehcache3,GaryWKeim/ehcache3,cljohnso/ehcache3,rkavanap/ehcache3,albinsuresh/ehcache3,sreekanth-r/ehcache3,cschanck/ehcache3,jhouserizer/ehcache3,AbfrmBlr/ehcache3,chrisdennis/ehcache3,akomakom/ehcache3,chenrui2014/ehcache3,kedar031/ehcache3,aurbroszniowski/ehcache3,albinsuresh/ehcache3,anthonydahanne/ehcache3,rishabhmonga/ehcache3
/* * Copyright Terracotta, 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.ehcache.internal.store; import org.ehcache.Cache; import org.ehcache.exceptions.CacheAccessException; import org.ehcache.function.BiFunction; import org.ehcache.function.Function; import org.ehcache.function.Predicate; import org.ehcache.function.Predicates; import org.ehcache.internal.concurrent.ConcurrentHashMap; import org.ehcache.spi.cache.Store; import org.ehcache.spi.service.ServiceConfiguration; import java.util.Collections; import java.util.Comparator; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.concurrent.TimeUnit; import org.ehcache.function.Comparables; /** * @author Alex Snaps */ public class OnHeapStore<K, V> implements Store<K, V> { private static final int ATTEMPT_RATIO = 4; private static final int EVICTION_RATIO = 2; private final ConcurrentHashMap<K, Store.ValueHolder<V>> map = new ConcurrentHashMap<K, ValueHolder<V>>(); private final Comparable<Long> capacityConstraint; private final Predicate<Map.Entry<K, ValueHolder<V>>> evictionVeto; private final Comparator<Map.Entry<K, ValueHolder<V>>> evictionPrioritizer; public OnHeapStore(final Configuration<K, V> config) { Comparable<Long> capacity = config.getCapacityConstraint(); if (capacity == null) { this.capacityConstraint = Comparables.biggest(); } else { this.capacityConstraint = config.getCapacityConstraint(); } this.evictionVeto = wrap(config.getEvictionVeto()); this.evictionPrioritizer = wrap(config.getEvictionPrioritizer()); } @Override public ValueHolder<V> get(final K key) throws CacheAccessException { return map.get(key); } @Override public boolean containsKey(final K key) throws CacheAccessException { return map.containsKey(key); } public void put(final K key, final V value) throws CacheAccessException { if (map.put(key, new OnHeapStoreValueHolder<V>(value)) == null) { enforceCapacity(1); } } @Override public void remove(final K key) throws CacheAccessException { map.remove(key); } @Override public ValueHolder<V> putIfAbsent(K key, V value) throws CacheAccessException { return map.putIfAbsent(key, new OnHeapStoreValueHolder<V>(value)); } @Override public boolean remove(K key, V value) throws CacheAccessException { return map.remove(key, new OnHeapStoreValueHolder<V>(value)); } @Override public ValueHolder<V> replace(K key, V value) throws CacheAccessException { return map.replace(key, new OnHeapStoreValueHolder<V>(value)); } @Override public boolean replace(K key, V oldValue, V newValue) throws CacheAccessException { return map.replace(key, new OnHeapStoreValueHolder<V>(oldValue), new OnHeapStoreValueHolder<V>(newValue)); } public void clear() throws CacheAccessException { map.clear(); } @Override public void destroy() throws CacheAccessException { map.clear(); } @Override public void close() { map.clear(); } @Override public Iterator<Cache.Entry<K, ValueHolder<V>>> iterator() { final java.util.Iterator<Map.Entry<K, ValueHolder<V>>> it = map.entrySet().iterator(); return new Iterator<Cache.Entry<K, ValueHolder<V>>>() { @Override public boolean hasNext() throws CacheAccessException { return it.hasNext(); } @Override public Cache.Entry<K, ValueHolder<V>> next() throws CacheAccessException { final Map.Entry<K, ValueHolder<V>> next = it.next(); return new Cache.Entry<K, ValueHolder<V>>() { @Override public K getKey() { return next.getKey(); } @Override public ValueHolder<V> getValue() { return next.getValue(); } @Override public long getCreationTime(TimeUnit unit) { return next.getValue().creationTime(unit); } @Override public long getLastAccessTime(TimeUnit unit) { return next.getValue().lastAccessTime(unit); } @Override public float getHitRate(TimeUnit unit) { return next.getValue().hitRate(unit); } }; } }; } @Override public ValueHolder<V> compute(final K key, final BiFunction<? super K, ? super V, ? extends V> remappingFunction) { return map.compute(key, new BiFunction<K, ValueHolder<V>, ValueHolder<V>>() { @Override public ValueHolder<V> apply(final K k, final ValueHolder<V> vValueHolder) { return nullSafeValueHolder(remappingFunction.apply(k, vValueHolder.value())); } }); } @Override public ValueHolder<V> computeIfAbsent(final K key, final Function<? super K, ? extends V> mappingFunction) { return map.computeIfAbsent(key, new Function<K, ValueHolder<V>>() { @Override public ValueHolder<V> apply(final K k) { return nullSafeValueHolder(mappingFunction.apply(k)); } }); } @Override public ValueHolder<V> computeIfPresent(final K key, final BiFunction<? super K, ? super V, ? extends V> remappingFunction) { return map.computeIfPresent(key, new BiFunction<K, ValueHolder<V>, ValueHolder<V>>() { @Override public ValueHolder<V> apply(final K k, final ValueHolder<V> vValueHolder) { return nullSafeValueHolder(remappingFunction.apply(k, vValueHolder.value())); } }); } private OnHeapStoreValueHolder<V> nullSafeValueHolder(final V value) { return value == null ? null : new OnHeapStoreValueHolder<V>(value); } private void enforceCapacity(int delta) { for (int attempts = 0, evicted = 0; attempts < ATTEMPT_RATIO * delta && evicted < EVICTION_RATIO * delta && capacityConstraint.compareTo((long) map.size()) < 0; attempts++) { if (evict()) { evicted++; } } } private boolean evict() { Set<Map.Entry<K, ValueHolder<V>>> values = map.getRandomValues(new Random(), 8, evictionVeto); if (values.isEmpty()) { return false; } else { Map.Entry<K, ValueHolder<V>> evict = Collections.max(values, evictionPrioritizer); if (map.remove(evict.getKey(), evict.getValue())) { //Eventually we'll need to fire a listener here. return true; } else { return false; } } } public static class Provider implements Store.Provider { @Override public <K, V> OnHeapStore<K, V> createStore(final Configuration<K, V> storeConfig, final ServiceConfiguration<?>... serviceConfigs) { return new OnHeapStore<K, V>(storeConfig); } @Override public void releaseStore(final Store<?, ?> resource) { try { resource.clear(); } catch (CacheAccessException e) { throw new RuntimeException(e); } } @Override public void stop() { // nothing to do } } private static <K, V> Predicate<Map.Entry<K, ValueHolder<V>>> wrap(final Predicate<Cache.Entry<K, V>> predicate) { if (predicate == null) { return Predicates.none(); } else { return new Predicate<Map.Entry<K, ValueHolder<V>>>() { @Override public boolean test(final Map.Entry<K, ValueHolder<V>> argument) { return predicate.test(wrap(argument)); } }; } } private static <K, V> Comparator<Map.Entry<K, ValueHolder<V>>> wrap(final Comparator<Cache.Entry<K, V>> comparator) { return new Comparator<Map.Entry<K, ValueHolder<V>>>() { @Override public int compare(Map.Entry<K, ValueHolder<V>> t, Map.Entry<K, ValueHolder<V>> u) { return comparator.compare(wrap(t), wrap(u)); } }; } private static <K, V> Cache.Entry<K, V> wrap(final Map.Entry<K, ValueHolder<V>> value) { return new Cache.Entry<K, V>() { @Override public K getKey() { return value.getKey(); } @Override public V getValue() { return value.getValue().value(); } @Override public long getCreationTime(TimeUnit unit) { return value.getValue().creationTime(unit); } @Override public long getLastAccessTime(TimeUnit unit) { return value.getValue().lastAccessTime(unit); } @Override public float getHitRate(TimeUnit unit) { return value.getValue().hitRate(unit); } }; } }
impl/src/main/java/org/ehcache/internal/store/OnHeapStore.java
/* * Copyright Terracotta, 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.ehcache.internal.store; import org.ehcache.Cache; import org.ehcache.exceptions.CacheAccessException; import org.ehcache.function.BiFunction; import org.ehcache.function.Function; import org.ehcache.function.Predicate; import org.ehcache.function.Predicates; import org.ehcache.internal.concurrent.ConcurrentHashMap; import org.ehcache.spi.cache.Store; import org.ehcache.spi.service.ServiceConfiguration; import java.util.Collections; import java.util.Comparator; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.concurrent.TimeUnit; import org.ehcache.function.Comparables; /** * @author Alex Snaps */ public class OnHeapStore<K, V> implements Store<K, V> { private static final int ATTEMPT_RATIO = 4; private static final int EVICTION_RATIO = 2; private final ConcurrentHashMap<K, Store.ValueHolder<V>> map = new ConcurrentHashMap<K, ValueHolder<V>>(); private final Comparable<Long> capacityConstraint; private final Predicate<Map.Entry<K, ValueHolder<V>>> evictionVeto; private final Comparator<Map.Entry<K, ValueHolder<V>>> evictionPrioritizer; public OnHeapStore(final Configuration<K, V> config) { Comparable<Long> capacity = config.getCapacityConstraint(); if (capacity == null) { this.capacityConstraint = Comparables.biggest(); } else { this.capacityConstraint = config.getCapacityConstraint(); } this.evictionVeto = wrap(config.getEvictionVeto()); this.evictionPrioritizer = wrap(config.getEvictionPrioritizer()); } @Override public ValueHolder<V> get(final K key) throws CacheAccessException { return map.get(key); } @Override public boolean containsKey(final K key) throws CacheAccessException { return map.containsKey(key); } public void put(final K key, final V value) throws CacheAccessException { if (map.put(key, new OnHeapStoreValueHolder<V>(value)) == null) { enforceCapacity(1); } } @Override public void remove(final K key) throws CacheAccessException { map.remove(key); } @Override public ValueHolder<V> putIfAbsent(K key, V value) throws CacheAccessException { return map.putIfAbsent(key, new OnHeapStoreValueHolder<V>(value)); } @Override public boolean remove(K key, V value) throws CacheAccessException { return map.remove(key, new OnHeapStoreValueHolder<V>(value)); } @Override public ValueHolder<V> replace(K key, V value) throws CacheAccessException { return map.replace(key, new OnHeapStoreValueHolder<V>(value)); } @Override public boolean replace(K key, V oldValue, V newValue) throws CacheAccessException { return map.replace(key, new OnHeapStoreValueHolder<V>(oldValue), new OnHeapStoreValueHolder<V>(newValue)); } public void clear() throws CacheAccessException { map.clear(); } @Override public void destroy() throws CacheAccessException { map.clear(); } @Override public void close() { map.clear(); } @Override public Iterator<Cache.Entry<K, ValueHolder<V>>> iterator() { final java.util.Iterator<Map.Entry<K, ValueHolder<V>>> it = map.entrySet().iterator(); return new Iterator<Cache.Entry<K, ValueHolder<V>>>() { @Override public boolean hasNext() throws CacheAccessException { return it.hasNext(); } @Override public Cache.Entry<K, ValueHolder<V>> next() throws CacheAccessException { final Map.Entry<K, ValueHolder<V>> next = it.next(); return new Cache.Entry<K, ValueHolder<V>>() { @Override public K getKey() { return next.getKey(); } @Override public ValueHolder<V> getValue() { return next.getValue(); } @Override public long getCreationTime(TimeUnit unit) { return next.getValue().creationTime(unit); } @Override public long getLastAccessTime(TimeUnit unit) { return next.getValue().lastAccessTime(unit); } @Override public float getHitRate(TimeUnit unit) { return next.getValue().hitRate(unit); } }; } }; } @Override public ValueHolder<V> compute(final K key, final BiFunction<? super K, ? super V, ? extends V> remappingFunction) { return map.compute(key, new BiFunction<K, ValueHolder<V>, ValueHolder<V>>() { @Override public ValueHolder<V> apply(final K k, final ValueHolder<V> vValueHolder) { return new OnHeapStoreValueHolder<V>(remappingFunction.apply(k, vValueHolder.value())); } }); } @Override public ValueHolder<V> computeIfAbsent(final K key, final Function<? super K, ? extends V> mappingFunction) { return map.computeIfAbsent(key, new Function<K, ValueHolder<V>>() { @Override public ValueHolder<V> apply(final K k) { return new OnHeapStoreValueHolder<V>(mappingFunction.apply(k)); } }); } @Override public ValueHolder<V> computeIfPresent(final K key, final BiFunction<? super K, ? super V, ? extends V> remappingFunction) { return map.computeIfPresent(key, new BiFunction<K, ValueHolder<V>, ValueHolder<V>>() { @Override public ValueHolder<V> apply(final K k, final ValueHolder<V> vValueHolder) { return new OnHeapStoreValueHolder<V>(remappingFunction.apply(k, vValueHolder.value())); } }); } private void enforceCapacity(int delta) { for (int attempts = 0, evicted = 0; attempts < ATTEMPT_RATIO * delta && evicted < EVICTION_RATIO * delta && capacityConstraint.compareTo((long) map.size()) < 0; attempts++) { if (evict()) { evicted++; } } } private boolean evict() { Set<Map.Entry<K, ValueHolder<V>>> values = map.getRandomValues(new Random(), 8, evictionVeto); if (values.isEmpty()) { return false; } else { Map.Entry<K, ValueHolder<V>> evict = Collections.max(values, evictionPrioritizer); if (map.remove(evict.getKey(), evict.getValue())) { //Eventually we'll need to fire a listener here. return true; } else { return false; } } } public static class Provider implements Store.Provider { @Override public <K, V> OnHeapStore<K, V> createStore(final Configuration<K, V> storeConfig, final ServiceConfiguration<?>... serviceConfigs) { return new OnHeapStore<K, V>(storeConfig); } @Override public void releaseStore(final Store<?, ?> resource) { try { resource.clear(); } catch (CacheAccessException e) { throw new RuntimeException(e); } } @Override public void stop() { // nothing to do } } private static <K, V> Predicate<Map.Entry<K, ValueHolder<V>>> wrap(final Predicate<Cache.Entry<K, V>> predicate) { if (predicate == null) { return Predicates.none(); } else { return new Predicate<Map.Entry<K, ValueHolder<V>>>() { @Override public boolean test(final Map.Entry<K, ValueHolder<V>> argument) { return predicate.test(wrap(argument)); } }; } } private static <K, V> Comparator<Map.Entry<K, ValueHolder<V>>> wrap(final Comparator<Cache.Entry<K, V>> comparator) { return new Comparator<Map.Entry<K, ValueHolder<V>>>() { @Override public int compare(Map.Entry<K, ValueHolder<V>> t, Map.Entry<K, ValueHolder<V>> u) { return comparator.compare(wrap(t), wrap(u)); } }; } private static <K, V> Cache.Entry<K, V> wrap(final Map.Entry<K, ValueHolder<V>> value) { return new Cache.Entry<K, V>() { @Override public K getKey() { return value.getKey(); } @Override public V getValue() { return value.getValue().value(); } @Override public long getCreationTime(TimeUnit unit) { return value.getValue().creationTime(unit); } @Override public long getLastAccessTime(TimeUnit unit) { return value.getValue().lastAccessTime(unit); } @Override public float getHitRate(TimeUnit unit) { return value.getValue().hitRate(unit); } }; } }
Issue #31 introduced method to deal with null producing Function and BiFunction
impl/src/main/java/org/ehcache/internal/store/OnHeapStore.java
Issue #31 introduced method to deal with null producing Function and BiFunction
<ide><path>mpl/src/main/java/org/ehcache/internal/store/OnHeapStore.java <ide> return map.compute(key, new BiFunction<K, ValueHolder<V>, ValueHolder<V>>() { <ide> @Override <ide> public ValueHolder<V> apply(final K k, final ValueHolder<V> vValueHolder) { <del> return new OnHeapStoreValueHolder<V>(remappingFunction.apply(k, vValueHolder.value())); <add> return nullSafeValueHolder(remappingFunction.apply(k, vValueHolder.value())); <ide> } <ide> }); <ide> } <ide> return map.computeIfAbsent(key, new Function<K, ValueHolder<V>>() { <ide> @Override <ide> public ValueHolder<V> apply(final K k) { <del> return new OnHeapStoreValueHolder<V>(mappingFunction.apply(k)); <add> return nullSafeValueHolder(mappingFunction.apply(k)); <ide> } <ide> }); <ide> } <ide> return map.computeIfPresent(key, new BiFunction<K, ValueHolder<V>, ValueHolder<V>>() { <ide> @Override <ide> public ValueHolder<V> apply(final K k, final ValueHolder<V> vValueHolder) { <del> return new OnHeapStoreValueHolder<V>(remappingFunction.apply(k, vValueHolder.value())); <add> return nullSafeValueHolder(remappingFunction.apply(k, vValueHolder.value())); <ide> } <ide> }); <add> } <add> <add> private OnHeapStoreValueHolder<V> nullSafeValueHolder(final V value) { <add> return value == null ? null : new OnHeapStoreValueHolder<V>(value); <ide> } <ide> <ide> private void enforceCapacity(int delta) {
Java
mit
90f300ed875cece84e320bab5a9e730c9b6f20e2
0
TheBrownMotie/finite-byte-field,TheBrownMotie/finite-byte-field
package com.nickww.finitefield; import static com.nickww.finitefield.FiniteByteField.*; import java.util.Arrays; /** * This class represents a 2d matrix of bytes, which exist in the finite field GF(2<sup>8</sup>). Instances of this * class are immutable and thread-safe. * * @author Nick Wuensch */ public final class FiniteByteFieldMatrix { /** * Creates the identity matrix of the given size. * * An identity matrix is a square matrix, such that multiplying it with any other matrix will result in the original * matrix. It is constructed with 1s on the diagonal and 0s everywhere else. * * @param size The size of the identity matrix to return. * @return The identity matrix for the given size. */ public static FiniteByteFieldMatrix identity(int size) { byte[][] identity = new byte[size][size]; for(int i = 0; i < size; i++) identity[i][i] = 1; return new FiniteByteFieldMatrix(identity); } /** * Constructs a new matrix of the given size, where each element is provided by the given function. The function * will be given a row and column 0-based index, and the result will be the value of the given matrix at that row * and column. The given function will never be passed null values, and will only be passed values from 0 * (inclusive) to the given row/column limit (exclusive). * * @param numRows The number of rows for the returned matrix. * @param numCols The number of columns for the returned matrix. * @param matrixElementFunction The function to produce the elements of the returned matrix. * @return The constructed matrix of the appropriate size, with values returned from the given function. * @throws NullPointerException if the given function to produce elements is null. * @throws IllegalArgumentException if the given numRows or numCols values are less than 1. */ public static FiniteByteFieldMatrix build(int numRows, int numCols, ToByteBiFunction<Integer, Integer> element) { if(numRows < 1 || numCols < 1) throw new IllegalArgumentException("The given bounds for the matrix must be greater than 0"); byte[][] data = new byte[numRows][numCols]; for(int row = 0; row < numRows; row++) for(int col = 0; col < numCols; col++) data[row][col] = element.applyAsByte(row, col); return new FiniteByteFieldMatrix(data); } private final byte[][] data; private final int rows; private final int cols; private volatile FiniteByteFieldMatrix transpose; private volatile FiniteByteFieldMatrix cofactor; private volatile FiniteByteFieldMatrix inverse; private volatile Byte determinant; /** * Creates a new matrix with the given byte data. This class is immutable - the array can be safely altered after * constructing this object without altering the object. * * @param data The byte data of this matrix. * @throws NullPointerException if the given array is null. * @throws IllegalArgumentException if the matrix has no rows, no columns, or the rows are not all the same length. */ public FiniteByteFieldMatrix(byte[][] data) { if(data.length == 0 || data[0].length == 0) throw new IllegalArgumentException("Both dimensions of matrix must be non-zero"); rows = data.length; cols = data[0].length; for(int i = 1; i < rows; i++) if(data[i].length != cols) throw new IllegalArgumentException("All rows in array must be the same length"); this.data = copy(data); } /** * Returns a matrix which has the same data as this matrix without the given row or column. In other words, a minor * <code>M<sub>ij</sub></code> of matrix <code>A</code> has all the data of <code>A</code> without row * <code>i</code> or column <code>j</code>. * * @param deletedRow The row of this matrix to exclude in the returned matrix. * @param deletedCol The column of this matrix to exclude in the returned matrix. * @return The sub-matrix of this matrix without the given row and column. * @throws IndexOutOfBoundsException if the given row or column is out of bounds for this matrix. */ public FiniteByteFieldMatrix minor(int deletedRow, int deletedCol) { if(deletedRow >= numRows() || deletedRow < 0) throw new IndexOutOfBoundsException("Row index out of bounds: " + deletedRow + " " + numRows()); if(deletedCol >= numCols() || deletedCol < 0) throw new IndexOutOfBoundsException("Column index out of bounds: " + deletedCol + " " + numCols()); byte[][] minor = new byte[numRows() - 1][numCols() - 1]; int minorRow = 0; int minorCol = 0; for(int row = 0; row < numRows(); row++) { if(row != deletedRow) { for(int col = 0; col < numCols(); col++) if(col != deletedCol) minor[minorRow][minorCol++] = data[row][col]; minorRow++; } minorCol = 0; } return new FiniteByteFieldMatrix(minor); } /** * Returns the determinant of this matrix. This is calculated recursively. A square matrix with one row and one * column only has one value, which is the determinant. Larger matrices are calculated recursively, by multiplying * each value in the first row with the determinant of the matrix without its first row or the column of the value * being multiplied, and then summing those products. * * @return The determinant of this matrix. * @throws IllegalStateException if this matrix is not a square matrix. */ public byte determinant() { if(!isSquare()) throw new IllegalStateException("Only a square matrix has a determinant"); if(determinant == null) this.determinant = calculateDeterminant(); return determinant; } /** * Returns the transpose of this matrix, which is the data "flipped", as though its rows were its columns and * vice-versa. * * @return The transposed matrix. */ public FiniteByteFieldMatrix transpose() { if(transpose == null) transpose = FiniteByteFieldMatrix.build(numCols(), numRows(), (r, c) -> data[c][r]); return transpose; } /** * Returns the cofactor of this matrix, which is a new matrix of the same size such that each element * <code>i, j</code> in the new matrix is the determinant of the {@link #minor(i, j)} of the original matrix. * * @return The cofactor of this matrix. */ public FiniteByteFieldMatrix cofactor() { if(cofactor == null) cofactor = FiniteByteFieldMatrix.build(numRows(), numCols(), (r, c) -> minor(r, c).determinant()); return cofactor; } /** * Returns a new matrix where each element is multiplied by the given constant. * * @param constant The constant to multiply each value with. * @return A new matrix, with each value multiplied by the given constant. * @see #divideBy(byte) */ public FiniteByteFieldMatrix times(final byte constant) { return FiniteByteFieldMatrix.build(numRows(), numCols(), (r, c) -> mul(data[r][c], constant)); } /** * Returns a new matrix, arrived at through the process of matrix multiplication. Matrix multiplication constructs a * new matrix, where each element at position <code>i, j</code> is arrived by the dot product of the first matrix's * row <code>i</code> and the second matrix's column <code>j</code>. Unlike typical arithmetic, order matters - the * number of rows of the second matrix must match the number of columns of the first matrix. <br/> * <br/> * Illustration: * * <pre> * [1 2] * [3 4] * | * v * [1, 2]--[->x] // x = [1, 2] -dot- [2, 4] * [3, 4] [ ] * [5, 6] [ ] * </pre> * * @param matrix The matrix to multiply with. * @return The product of this matrix with the given matrix. * @throws IllegalArgumentException if the number of rows of the given matrix doesn't match the number of columns of * this matrix. * @see #solve(FiniteByteFieldMatrix) */ public FiniteByteFieldMatrix times(FiniteByteFieldMatrix matrix) { byte[][] cols = this.transpose().data; byte[][] thatCols = matrix.transpose().data; if(cols.length != matrix.data.length) throw new IllegalArgumentException("Matrix dimensions must match to be multiplied"); return FiniteByteFieldMatrix.build(numRows(), matrix.numCols(), (r, c) -> dot(this.data[r], thatCols[c])); } /** * Returns a new matrix where each element is divided by the given constant. * * @param constant The constant to divide each value with. * @return A new matrix, with each value divided by the given constant. * @see #times(byte) */ public FiniteByteFieldMatrix divideBy(final byte constant) { return FiniteByteFieldMatrix.build(numRows(), numCols(), (r, c) -> div(data[r][c], constant)); } /** * Creates a new matrix which is the inverse of this matrix. A matrix is a true inverse if, when multiplied with the * original matrix, produces an identity matrix. Only a square matrix has a true inverse. * * @return The inverse of this matrix. * @throws IllegalStateException if this matrix is not a square matrix. */ public FiniteByteFieldMatrix inverse() { if(!isSquare()) throw new IllegalStateException("Only a square matrix has an inverse"); if(inverse == null) inverse = transpose().cofactor().divideBy(determinant()); return inverse; } /** * "Divides" the given matrix with this matrix, such that if this matrix were multiplied with the result, the * product would be the given matrix.<br/> * <br/> * In other words, this method provides a value for <code>x</code> which would satisfy the line: * <code>product = this.times(x)</code> * * @param product The value that would be the product of this matrix and the return value of this method. * @return The value that would construct the given parameter when multiplied with this matrix. * @see #times(FiniteByteFieldMatrix) */ public FiniteByteFieldMatrix solve(FiniteByteFieldMatrix product) { return this.inverse().times(product); } /** * Returns the number of rows in this matrix. * * @return The number of rows in this matrix. */ public int numRows() { return rows; } /** * Returns the number of columns in this matrix. * * @return The number of columns in this matrix. */ public int numCols() { return cols; } /** * Returns whether or not this matrix has the same number of rows as columns. * * @return True if the matrix is square, false otherwise. */ public boolean isSquare() { return numRows() == numCols(); } /** * {@inheritDoc} */ @Override public final boolean equals(Object o) { if(!(o instanceof FiniteByteFieldMatrix)) return false; FiniteByteFieldMatrix that = (FiniteByteFieldMatrix) o; return Arrays.deepEquals(this.data, that.data); } /** * {@inheritDoc} */ @Override public final int hashCode() { return Arrays.deepHashCode(this.data); } /** * {@inheritDoc} */ @Override public final String toString() { StringBuilder string = new StringBuilder(); for(int i = 0; i < this.data.length; i++) string.append(Arrays.toString(this.data[i])).append("\n"); return string.toString(); } /** * Creates a copy of the given array.<br/> * Precondition: the given array is not null or empty, and each column is the same size and not empty.<br/> * Postcondition: the given array is unaltered, and the returned array is a completely unattached copy. */ private byte[][] copy(byte[][] data) { byte[][] copy = new byte[data.length][data[0].length]; for(int row = 0; row < data.length; row++) for(int col = 0; col < data[0].length; col++) copy[row][col] = data[row][col]; return copy; } /** * Calculates the determinant.<br/> * Precondition: matrix is square. */ private byte calculateDeterminant() { int size = numRows(); if(size == 1) return data[0][0]; byte sum = 0; byte[] firstRow = data[0]; for(int col = 0; col < size; col++) sum = add(sum, mul(firstRow[col], minor(0, col).determinant())); return sum; } }
src/main/java/com/nickww/finitefield/FiniteByteFieldMatrix.java
package com.nickww.finitefield; import static com.nickww.finitefield.FiniteByteField.*; import java.util.Arrays; /** * This class represents a 2d matrix of bytes, which exist in the finite field GF(2<sup>8</sup>). Instances of this * class are immutable and thread-safe. * * @author Nick Wuensch */ public final class FiniteByteFieldMatrix { /** * Creates the identity matrix of the given size. * * An identity matrix is a square matrix, such that multiplying it with any other matrix will result in the original * matrix. It is constructed with 1s on the diagonal and 0s everywhere else. * * @param size The size of the identity matrix to return. * @return The identity matrix for the given size. */ public static FiniteByteFieldMatrix identity(int size) { byte[][] identity = new byte[size][size]; for(int i = 0; i < size; i++) identity[i][i] = 1; return new FiniteByteFieldMatrix(identity); } /** * Constructs a new matrix of the given size, where each element is provided by the given function. The function * will be given a row and column 0-based index, and the result will be the value of the given matrix at that row * and column. The given function will never be passed null values, and will only be passed values from 0 * (inclusive) to the given row/column limit (exclusive). * * @param numRows The number of rows for the returned matrix. * @param numCols The number of columns for the returned matrix. * @param matrixElementFunction The function to produce the elements of the returned matrix. * @return The constructed matrix of the appropriate size, with values returned from the given function. * @throws NullPointerException if the given function to produce elements is null. * @throws IllegalArgumentException if the given numRows or numCols values are less than 1. */ public static FiniteByteFieldMatrix build(int numRows, int numCols, ToByteBiFunction<Integer, Integer> element) { if(numRows < 1 || numCols < 1) throw new IllegalArgumentException("The given bounds for the matrix must be greater than 0"); byte[][] data = new byte[numRows][numCols]; for(int row = 0; row < numRows; row++) for(int col = 0; col < numCols; col++) data[row][col] = element.applyAsByte(row, col); return new FiniteByteFieldMatrix(data); } private final byte[][] data; private final int rows; private final int cols; private volatile FiniteByteFieldMatrix transpose; private volatile FiniteByteFieldMatrix cofactor; private volatile FiniteByteFieldMatrix inverse; private volatile Byte determinant; /** * Creates a new matrix with the given byte data. This class is immutable - the array can be safely altered after * constructing this object without altering the object. * * @param data The byte data of this matrix. * @throws NullPointerException if the given array is null. * @throws IllegalArgumentException if the matrix has no rows, no columns, or the rows are not all the same length. */ public FiniteByteFieldMatrix(byte[][] data) { if(data.length == 0 || data[0].length == 0) throw new IllegalArgumentException("Both dimensions of matrix must be non-zero"); rows = data.length; cols = data[0].length; for(int i = 1; i < rows; i++) if(data[i].length != cols) throw new IllegalArgumentException("All rows in array must be the same length"); this.data = copy(data); } /** * Returns a matrix which has the same data as this matrix without the given row or column. In other words, a minor * <code>M<sub>ij</sub></code> of matrix <code>A</code> has all the data of <code>A</code> without row * <code>i</code> or column <code>j</code>. * * @param deletedRow The row of this matrix to exclude in the returned matrix. * @param deletedCol The column of this matrix to exclude in the returned matrix. * @return The sub-matrix of this matrix without the given row and column. * @throws IndexOutOfBoundsException if the given row or column is out of bounds for this matrix. */ public FiniteByteFieldMatrix minor(int deletedRow, int deletedCol) { if(deletedRow >= numRows() || deletedRow < 0) throw new IndexOutOfBoundsException("Row index out of bounds: " + deletedRow + " " + numRows()); if(deletedCol >= numCols() || deletedCol < 0) throw new IndexOutOfBoundsException("Column index out of bounds: " + deletedCol + " " + numCols()); byte[][] minor = new byte[numRows() - 1][numCols() - 1]; int minorRow = 0; int minorCol = 0; for(int row = 0; row < numRows(); row++) { if(row != deletedRow) { for(int col = 0; col < numCols(); col++) { if(col != deletedCol) { minor[minorRow][minorCol] = data[row][col]; minorCol++; } } minorRow++; } minorCol = 0; } return new FiniteByteFieldMatrix(minor); } /** * Returns the determinant of this matrix. This is calculated recursively. A square matrix with one row and one * column only has one value, which is the determinant. Larger matrices are calculated recursively, by multiplying * each value in the first row with the determinant of the matrix without its first row or the column of the value * being multiplied, and then summing those products. * * @return The determinant of this matrix. * @throws IllegalStateException if this matrix is not a square matrix. */ public byte determinant() { if(!isSquare()) throw new IllegalStateException("Only a square matrix has a determinant"); if(determinant == null) this.determinant = calculateDeterminant(); return determinant; } /** * Returns the transpose of this matrix, which is the data "flipped", as though its rows were its columns and * vice-versa. * * @return The transposed matrix. */ public FiniteByteFieldMatrix transpose() { if(transpose == null) transpose = FiniteByteFieldMatrix.build(numCols(), numRows(), (r, c) -> data[c][r]); return transpose; } /** * Returns the cofactor of this matrix, which is a new matrix of the same size such that each element * <code>i, j</code> in the new matrix is the determinant of the {@link #minor(i, j)} of the original matrix. * * @return The cofactor of this matrix. */ public FiniteByteFieldMatrix cofactor() { if(cofactor == null) cofactor = FiniteByteFieldMatrix.build(numRows(), numCols(), (r, c) -> minor(r, c).determinant()); return cofactor; } /** * Returns a new matrix where each element is multiplied by the given constant. * * @param constant The constant to multiply each value with. * @return A new matrix, with each value multiplied by the given constant. * @see #divideBy(byte) */ public FiniteByteFieldMatrix times(final byte constant) { return FiniteByteFieldMatrix.build(numRows(), numCols(), (r, c) -> mul(data[r][c], constant)); } /** * Returns a new matrix, arrived at through the process of matrix multiplication. Matrix multiplication constructs a * new matrix, where each element at position <code>i, j</code> is arrived by the dot product of the first matrix's * row <code>i</code> and the second matrix's column <code>j</code>. Unlike typical arithmetic, order matters - the * number of rows of the second matrix must match the number of columns of the first matrix. <br/> * <br/> * Illustration: * * <pre> * [1 2] * [3 4] * | * v * [1, 2]--[->x] // x = [1, 2] -dot- [2, 4] * [3, 4] [ ] * [5, 6] [ ] * </pre> * * @param matrix The matrix to multiply with. * @return The product of this matrix with the given matrix. * @throws IllegalArgumentException if the number of rows of the given matrix doesn't match the number of columns of * this matrix. * @see #solve(FiniteByteFieldMatrix) */ public FiniteByteFieldMatrix times(FiniteByteFieldMatrix matrix) { byte[][] cols = this.transpose().data; byte[][] thatCols = matrix.transpose().data; if(cols.length != matrix.data.length) throw new IllegalArgumentException("Matrix dimensions must match to be multiplied"); return FiniteByteFieldMatrix.build(numRows(), matrix.numCols(), (r, c) -> dot(this.data[r], thatCols[c])); } /** * Returns a new matrix where each element is divided by the given constant. * * @param constant The constant to divide each value with. * @return A new matrix, with each value divided by the given constant. * @see #times(byte) */ public FiniteByteFieldMatrix divideBy(final byte constant) { return FiniteByteFieldMatrix.build(numRows(), numCols(), (r, c) -> div(data[r][c], constant)); } /** * Creates a new matrix which is the inverse of this matrix. A matrix is a true inverse if, when multiplied with the * original matrix, produces an identity matrix. Only a square matrix has a true inverse. * * @return The inverse of this matrix. * @throws IllegalStateException if this matrix is not a square matrix. */ public FiniteByteFieldMatrix inverse() { if(!isSquare()) throw new IllegalStateException("Only a square matrix has an inverse"); if(inverse == null) inverse = transpose().cofactor().divideBy(determinant()); return inverse; } /** * "Divides" the given matrix with this matrix, such that if this matrix were multiplied with the result, the * product would be the given matrix.<br/> * <br/> * In other words, this method provides a value for <code>x</code> which would satisfy the line: * <code>product = this.times(x)</code> * * @param product The value that would be the product of this matrix and the return value of this method. * @return The value that would construct the given parameter when multiplied with this matrix. * @see #times(FiniteByteFieldMatrix) */ public FiniteByteFieldMatrix solve(FiniteByteFieldMatrix product) { return this.inverse().times(product); } /** * Returns the number of rows in this matrix. * * @return The number of rows in this matrix. */ public int numRows() { return rows; } /** * Returns the number of columns in this matrix. * * @return The number of columns in this matrix. */ public int numCols() { return cols; } /** * Returns whether or not this matrix has the same number of rows as columns. * * @return True if the matrix is square, false otherwise. */ public boolean isSquare() { return numRows() == numCols(); } /** * {@inheritDoc} */ @Override public final boolean equals(Object o) { if(!(o instanceof FiniteByteFieldMatrix)) return false; FiniteByteFieldMatrix that = (FiniteByteFieldMatrix) o; return Arrays.deepEquals(this.data, that.data); } /** * {@inheritDoc} */ @Override public final int hashCode() { return Arrays.deepHashCode(this.data); } /** * {@inheritDoc} */ @Override public final String toString() { StringBuilder string = new StringBuilder(); for(int i = 0; i < this.data.length; i++) string.append(Arrays.toString(this.data[i])).append("\n"); return string.toString(); } /** * Creates a copy of the given array.<br/> * Precondition: the given array is not null or empty, and each column is the same size and not empty.<br/> * Postcondition: the given array is unaltered, and the returned array is a completely unattached copy. */ private byte[][] copy(byte[][] data) { byte[][] copy = new byte[data.length][data[0].length]; for(int row = 0; row < data.length; row++) for(int col = 0; col < data[0].length; col++) copy[row][col] = data[row][col]; return copy; } /** * Calculates the determinant.<br/> * Precondition: matrix is square. */ private byte calculateDeterminant() { int size = numRows(); if(size == 1) return data[0][0]; byte sum = 0; byte[] firstRow = data[0]; for(int col = 0; col < size; col++) sum = add(sum, mul(firstRow[col], minor(0, col).determinant())); return sum; } }
Refactor: housekeeping - fewer braces
src/main/java/com/nickww/finitefield/FiniteByteFieldMatrix.java
Refactor: housekeeping - fewer braces
<ide><path>rc/main/java/com/nickww/finitefield/FiniteByteFieldMatrix.java <ide> if(row != deletedRow) <ide> { <ide> for(int col = 0; col < numCols(); col++) <del> { <ide> if(col != deletedCol) <del> { <del> minor[minorRow][minorCol] = data[row][col]; <del> minorCol++; <del> } <del> } <add> minor[minorRow][minorCol++] = data[row][col]; <ide> minorRow++; <ide> } <ide> minorCol = 0;
JavaScript
bsd-2-clause
5b391e94e40ec041b6bd4b3a506f708fd45978eb
0
CIDARLAB/3DuF,CIDARLAB/3DuF
var RoundedRectLine = function(params){ let start = params["start"]; let end = params["end"]; let color = params["color"]; let width = params["width"]; let baseColor = params["baseColor"]; let startPoint = new paper.Point(start[0], start[1]); let endPoint = new paper.Point(end[0], end[1]); let vec = endPoint.subtract(startPoint); let rec = paper.Path.Rectangle({ size: [vec.length + width, width], point: start, radius: width/2, fillColor: color }); rec.translate([-width/2, -width / 2]); rec.rotate(vec.angle, start); return rec; } var EdgedRectLine = function(params){ let start = params["start"]; let end = params["end"]; let color = params["color"]; let width = params["width"]; let baseColor = params["baseColor"]; let startPoint = new paper.Point(start[0], start[1]); let endPoint = new paper.Point(end[0], end[1]); let vec = endPoint.subtract(startPoint); let rec = paper.Path.Rectangle({ size: [vec.length + width, width], point: start, // radius: width/2, fillColor: color }); rec.translate([-width/2, -width / 2]); rec.rotate(vec.angle, start); return rec; } var RoundedRect = function(params){ let start = params["start"]; let end = params["end"]; let borderWidth = params["borderWidth"]; let color = params["color"]; let baseColor = params["baseColor"]; let startX; let startY; let endX; let endY; if (start[0] < end[0]){ startX = start[0]; endX = end[0]; } else { startX = end[0]; endX = start[0]; } if (start[1] < end[1]){ startY = start[1]; endY = end[1]; } else { startY = end[1]; endY = start[1]; } startX -= borderWidth/2; startY -= borderWidth/2; endX += borderWidth/2; endY += borderWidth/2; let startPoint = new paper.Point(startX, startY); let endPoint = new paper.Point(endX, endY); let rec = paper.Path.Rectangle({ from: startPoint, to: endPoint, radius: borderWidth/2, fillColor: color }); return rec; } var EdgedRect = function(params){ let length = params["length"]; let width = params["width"]; let start = params["position"]; let borderWidth = params["borderWidth"]; let color = params["color"]; let baseColor = params["baseColor"]; let startX = start[0]; let startY = start[1]; let endX = startX + width; let endY = startY + length; // // if (start[0] < end[0]){ // startX = start[0]; // endX = end[0]; // } else { // startX = end[0]; // endX = start[0]; // } // if (start[1] < end[1]){ // startY = start[1]; // endY = end[1]; // } else { // startY = end[1]; // endY = start[1]; // } // startX -= borderWidth/2; // startY -= borderWidth/2; // endX += borderWidth/2; // endY += borderWidth/2; let startPoint = new paper.Point(startX, startY); let endPoint = new paper.Point(endX, endY); let rec = paper.Path.Rectangle({ from: startPoint, to: endPoint, // radius: borderWidth/2, fillColor: color }); return rec; } var GradientCircle = function(params){ let position = params["position"]; let radius1 = params["radius1"]; let radius2 = params["radius2"]; let color1 = params["color"]; let color2 = params["baseColor"]; let pos = new paper.Point(position[0], position[1]); let ratio = radius2 / radius1; let targetRatio; let targetRadius; if (ratio > 1) { targetRatio = 1; targetRadius = radius2; } else { targetRatio = ratio; targetRadius = radius1; } let outerCircle = new paper.Path.Circle(pos, targetRadius); outerCircle.fillColor = { gradient: { stops: [[color1, targetRatio], [color2, targetRatio]], radial: true }, origin: pos, destination: outerCircle.bounds.rightCenter }; return outerCircle; } var GroverValve = function(params){ let minRadiusInMicrometers = 8/paper.view.zoom; let position = params["position"]; let gap = params["gap"]; let radius = params["valveRadius"]; let color = params["color"]; let orientation = params["orientation"]; let center = new paper.Point(position[0], position[1]); // let h0p0, h0p1, h0p2, h1p0, h1p1, h1p2; var circ = new paper.Path.Circle(center, radius); //circ.fillColor = color; // if (String(color) == "3F51B5") { var cutout; if (orientation == "H") { cutout = paper.Path.Rectangle({ from: new paper.Point(position[0] - gap / 2, position[1] - radius), to: new paper.Point(position[0] + gap / 2, position[1] + radius) }); } else { cutout = paper.Path.Rectangle({ from: new paper.Point(position[0] - radius, position[1] - gap / 2), to: new paper.Point(position[0] + radius, position[1] + gap / 2) }); } //cutout.fillColor = "white"; var valve = new paper.CompoundPath(circ, cutout); valve.fillColor = color; valve.fillRule = 'evenodd'; //console.log(color); return valve; // } // else { // circ.FillColor = color; // return circ; // } } var CircleTarget = function(params){ let targetRadius; let radius1; let radius2; if (params.hasOwnProperty("diameter")) targetRadius = params["diameter"]/2; else { if (params.hasOwnProperty("portRadius")) { radius1 = portRadius; radius2 = portRadius; } else { radius1 = params["radius1"]; radius2 = params["radius2"]; if (radius1 > radius2) targetRadius = radius1; else targetRadius = radius2; } } let minSize = 8; //pixels let minSizeInMicrometers = 8/paper.view.zoom; let position = params["position"]; let color = params["color"]; let pos = new paper.Point(position[0], position[1]); if (targetRadius < minSizeInMicrometers) targetRadius = minSizeInMicrometers; let circ = new paper.Path.Circle(pos, targetRadius); circ.fillColor = color circ.fillColor.alpha = .5; circ.strokeColor = "#FFFFFF"; circ.strokeWidth = 3 / paper.view.zoom; if(circ.strokeWidth > targetRadius/2) circ.strokeWidth = targetRadius/2; return circ; } var Diamond = function(params){ let position = params["position"]; let px = position[0]; let py = position[1]; let cw = params["channelWidth"]; let l = params["length"]; let w = params["width"]; let orientation = params["orientation"]; let color = params["color"]; let p0, p1, p2, p3, p4, p5; if (orientation == "H"){ p0 = [px - l/2, py - cw/2]; p1 = [px - l/2, py + cw/2]; p2 = [px, py + w + cw/2]; p3 = [px + l/2, py + cw/2]; p4 = [px + l/2, py - cw/2]; p5 = [px, py - cw/2 - w]; } else{ p0 = [px - cw/2, py - l/2]; p1 = [px + cw/2, py - l/2]; p2 = [px + w + cw/2, py]; p3 = [px + cw/2, py + l/2]; p4 = [px - cw/2, py + l/2]; p5 = [px - cw/2 - w, py]; } var hex = new paper.Path(); hex.add(new paper.Point(p0)); hex.add(new paper.Point(p1)); hex.add(new paper.Point(p2)); hex.add(new paper.Point(p3)); hex.add(new paper.Point(p4)); hex.add(new paper.Point(p5)); hex.closed = true; hex.fillColor = color; return hex; } var DiamondTarget = function(params){ let position = params["position"]; let px = position[0]; let py = position[1]; let cw = params["channelWidth"]; let l = params["length"]; let w = params["width"]; let orientation = params["orientation"]; let color = params["color"]; let p0, p1, p2, p3, p4, p5; if (orientation == "H"){ p0 = [px - l/2, py - cw/2]; p1 = [px - l/2, py + cw/2]; p2 = [px, py + w + cw/2]; p3 = [px + l/2, py + cw/2]; p4 = [px + l/2, py - cw/2]; p5 = [px, py - cw/2 - w]; } else{ p0 = [px - cw/2, py - l/2]; p1 = [px + cw/2, py - l/2]; p2 = [px + w + cw/2, py]; p3 = [px + cw/2, py + l/2]; p4 = [px - cw/2, py + l/2]; p5 = [px - cw/2 - w, py]; } var hex = new paper.Path(); hex.add(new paper.Point(p0)); hex.add(new paper.Point(p1)); hex.add(new paper.Point(p2)); hex.add(new paper.Point(p3)); hex.add(new paper.Point(p4)); hex.add(new paper.Point(p5)); hex.closed = true; hex.fillColor = color; hex.fillColor.alpha = 0.5; hex.strokeColor = "#FFFFFF"; hex.strokeWidth = 3 / paper.view.zoom; if(hex.strokeWidth > w/2) hex.strokeWidth = w/2; //console.log(Math.ceil(Math.log2(7))); return hex; } var Mixer = function(params){ position = params["position"]; bendSpacing = params["bendSpacing"]; numBends = params["numberOfBends"]; channelWidth = params["channelWidth"]; bendLength = params["bendLength"]; orientation = params["orientation"]; let color = params["color"]; var serpentine = new paper.CompoundPath(); let startX, startY; if (orientation == "V"){ startX = position[0] + 0.5*(bendLength + channelWidth); startY = position[1] - 0.5 * channelWidth; serpentine.addChild(new paper.Path.Rectangle({ size: [0.5*bendLength + channelWidth, channelWidth], point: new paper.Point(startX - 0.5*bendLength - channelWidth, startY), fillColor: color })); //serpentine.add(new paper.Point(startX, startY)); for (i = 0; i < numBends - 1; i++) { serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, bendSpacing + channelWidth], point: new paper.Point(startX - 0.5*bendLength - channelWidth, startY + 2*i*(bendSpacing + channelWidth) + channelWidth), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [bendLength + channelWidth, channelWidth], point: new paper.Point(startX - 0.5*bendLength, startY + (2*i+1)*(bendSpacing + channelWidth)), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, bendSpacing + channelWidth], point: new paper.Point(startX + 0.5*bendLength, startY + (2*i+1)*(bendSpacing + channelWidth) + channelWidth), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [bendLength + channelWidth, channelWidth], point: new paper.Point(startX - 0.5*bendLength - channelWidth, startY + (2*i+2)*(bendSpacing + channelWidth)), fillColor: color })); } serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, bendSpacing + channelWidth], point: new paper.Point(startX - 0.5*bendLength - channelWidth, startY + 2*(numBends - 1)*(bendSpacing + channelWidth) + channelWidth), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [bendLength + channelWidth, channelWidth], point: new paper.Point(startX - 0.5*bendLength, startY + (2*(numBends - 1)+1)*(bendSpacing + channelWidth)), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, bendSpacing + channelWidth], point: new paper.Point(startX + 0.5*bendLength, startY + (2*(numBends - 1)+1)*(bendSpacing + channelWidth) + channelWidth), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [bendLength/2, channelWidth], point: new paper.Point(startX, startY + (2*(numBends - 1)+2)*(bendSpacing + channelWidth)), fillColor: color })); serpentine.scale(-1,1); } else { startX = position[0] - 0.5 * channelWidth; startY = position[1] + 0.5*(bendLength + channelWidth); //serpentine.add(new paper.Point(startX, startY)); serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, 0.5*bendLength + channelWidth], point: new paper.Point(startX, startY - 0.5*bendLength - channelWidth), fillColor: color })); for (i = 0; i < numBends - 1; i++) { serpentine.addChild(new paper.Path.Rectangle({ size: [bendSpacing + channelWidth, channelWidth], point: new paper.Point(startX + 2*i*(bendSpacing + channelWidth) + channelWidth, startY - 0.5*bendLength - channelWidth), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, bendLength + channelWidth], point: new paper.Point(startX + (2*i+1)*(bendSpacing + channelWidth), startY - 0.5*bendLength), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [bendSpacing + channelWidth, channelWidth], point: new paper.Point(startX + (2*i+1)*(bendSpacing + channelWidth) + channelWidth, startY + 0.5*bendLength), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, bendLength + channelWidth], point: new paper.Point(startX + (2*i+2)*(bendSpacing + channelWidth), startY - 0.5*bendLength - channelWidth), fillColor: color })); } serpentine.addChild(new paper.Path.Rectangle({ size: [bendSpacing + channelWidth, channelWidth], point: new paper.Point(startX + 2*(numBends - 1)*(bendSpacing + channelWidth) + channelWidth, startY - 0.5*bendLength - channelWidth), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, bendLength + channelWidth], point: new paper.Point(startX + (2*(numBends - 1)+1)*(bendSpacing + channelWidth), startY - 0.5*bendLength), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [bendSpacing + channelWidth, channelWidth], point: new paper.Point(startX + (2*(numBends - 1)+1)*(bendSpacing + channelWidth) + channelWidth, startY + 0.5*bendLength), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, bendLength/2], point: new paper.Point(startX + (2*(numBends - 1)+2)*(bendSpacing + channelWidth), startY), fillColor: color })); } serpentine.fillColor = color; return serpentine; } var MixerTarget = function(params){ position = params["position"]; bendSpacing = params["bendSpacing"]; numBends = params["numberOfBends"]; channelWidth = params["channelWidth"]; bendLength = params["bendLength"]; orientation = params["orientation"]; let color = params["color"]; var serpentine = new paper.CompoundPath(); let startX, startY; if (orientation == "V"){ startX = position[0] + 0.5*(bendLength + channelWidth); startY = position[1] - 0.5 * channelWidth; serpentine.addChild(new paper.Path.Rectangle({ size: [0.5*bendLength + channelWidth, channelWidth], point: new paper.Point(startX - 0.5*bendLength - channelWidth, startY), fillColor: color })); //serpentine.add(new paper.Point(startX, startY)); for (i = 0; i < numBends - 1; i++) { serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, bendSpacing + channelWidth], point: new paper.Point(startX - 0.5*bendLength - channelWidth, startY + 2*i*(bendSpacing + channelWidth) + channelWidth), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [bendLength + channelWidth, channelWidth], point: new paper.Point(startX - 0.5*bendLength, startY + (2*i+1)*(bendSpacing + channelWidth)), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, bendSpacing + channelWidth], point: new paper.Point(startX + 0.5*bendLength, startY + (2*i+1)*(bendSpacing + channelWidth) + channelWidth), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [bendLength + channelWidth, channelWidth], point: new paper.Point(startX - 0.5*bendLength - channelWidth, startY + (2*i+2)*(bendSpacing + channelWidth)), fillColor: color })); } serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, bendSpacing + channelWidth], point: new paper.Point(startX - 0.5*bendLength - channelWidth, startY + 2*(numBends - 1)*(bendSpacing + channelWidth) + channelWidth), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [bendLength + channelWidth, channelWidth], point: new paper.Point(startX - 0.5*bendLength, startY + (2*(numBends - 1)+1)*(bendSpacing + channelWidth)), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, bendSpacing + channelWidth], point: new paper.Point(startX + 0.5*bendLength, startY + (2*(numBends - 1)+1)*(bendSpacing + channelWidth) + channelWidth), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [bendLength/2, channelWidth], point: new paper.Point(startX, startY + (2*(numBends - 1)+2)*(bendSpacing + channelWidth)), fillColor: color })); serpentine.scale(-1,1); } else { startX = position[0] - 0.5 * channelWidth; startY = position[1] + 0.5*(bendLength + channelWidth); //serpentine.add(new paper.Point(startX, startY)); serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, 0.5*bendLength + channelWidth], point: new paper.Point(startX, startY - 0.5*bendLength - channelWidth), fillColor: color })); for (i = 0; i < numBends - 1; i++) { serpentine.addChild(new paper.Path.Rectangle({ size: [bendSpacing + channelWidth, channelWidth], point: new paper.Point(startX + 2*i*(bendSpacing + channelWidth) + channelWidth, startY - 0.5*bendLength - channelWidth), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, bendLength + channelWidth], point: new paper.Point(startX + (2*i+1)*(bendSpacing + channelWidth), startY - 0.5*bendLength), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [bendSpacing + channelWidth, channelWidth], point: new paper.Point(startX + (2*i+1)*(bendSpacing + channelWidth) + channelWidth, startY + 0.5*bendLength), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, bendLength + channelWidth], point: new paper.Point(startX + (2*i+2)*(bendSpacing + channelWidth), startY - 0.5*bendLength - channelWidth), fillColor: color })); } serpentine.addChild(new paper.Path.Rectangle({ size: [bendSpacing + channelWidth, channelWidth], point: new paper.Point(startX + 2*(numBends - 1)*(bendSpacing + channelWidth) + channelWidth, startY - 0.5*bendLength - channelWidth), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, bendLength + channelWidth], point: new paper.Point(startX + (2*(numBends - 1)+1)*(bendSpacing + channelWidth), startY - 0.5*bendLength), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [bendSpacing + channelWidth, channelWidth], point: new paper.Point(startX + (2*(numBends - 1)+1)*(bendSpacing + channelWidth) + channelWidth, startY + 0.5*bendLength), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, bendLength/2], point: new paper.Point(startX + (2*(numBends - 1)+2)*(bendSpacing + channelWidth), startY), fillColor: color })); } serpentine.fillColor = color; serpentine.fillColor.alpha = 0.5; return serpentine; } var Tree = function(params) { position = params["position"]; cw = params["flowChannelWidth"]; orientation = params["orientation"]; spacing = params["spacing"]; leafs = params["leafs"]; color = params["color"]; width = params["width"]; startX = position[0]; startY = position[1]; var pathList = []; var inNodes = []; var currentPath = new paper.Path(); if (orientation == "V") { for (i = 0; i < leafs; i++) { inNodes.push(new paper.Point(startX, startY + i*(cw + spacing))); } while (inNodes.length > 1) { var outNodes = []; for (i = 0; i < inNodes.length; i += 2) { currentPath.add(inNodes[i]); currentPath.add(new paper.Point(inNodes[i].x + 3*cw, inNodes[i].y)); currentPath.add(new paper.Point(inNodes[i+1].x + 3*cw, inNodes[i+1].y)); currentPath.add(new paper.Point(inNodes[i+1])); outNodes.push(new paper.Point((inNodes[i].x + 3*cw, inNodes[i].y + inNodes[i+1].y)/2)); } pathList.push(currentPath); currentPath = new paper.Path(); inNodes = outNodes; } pathList.push(new paper.Point(width, pathList[pathList.length-1].y)); } else { for (i = 0; i < leafs; i++) { inNodes.push(new paper.Point(startX + i * (cw + spacing), startY)); } while (inNodes.length > 1) { var outNodes = []; for (i = 0; i < inNodes.length; i += 2) { currentPath.add(inNodes[i]); currentPath.add(new paper.Point(inNodes[i].x, inNodes[i].y + 3 * cw)); currentPath.add(new paper.Point(inNodes[i + 1].x, inNodes[i + 1].y + 3 * cw)); currentPath.add(new paper.Point(inNodes[i + 1])); outNodes.push(new paper.Point((inNodes[i].x + inNodes[i + 1].x) / 2, inNodes[i].y + 3 * cw)); } pathList.push(currentPath); currentPath = new paper.Path(); inNodes = outNodes; } } tree_path = new paper.CompoundPath(pathList); tree_path.strokeColor = color; tree_path.strokeWidth = cw; return tree_path; } var TreeTarget = function(params) { position = params["position"]; cw = params["flowChannelWidth"]; orientation = params["orientation"]; spacing = params["spacing"]; leafs = params["leafs"]; color = params["color"]; startX = position[0]; startY = position[1]; var pathList = []; var inNodes = []; var currentPath = new paper.Path(); if (orientation == "V") { for (i = 0; i < leafs; i++) { inNodes.push(new paper.Point(startX, startY + i*(cw + spacing))); } while (inNodes.length > 1) { var outNodes = []; for (i = 0; i < inNodes.length; i += 2) { currentPath.add(inNodes[i]); currentPath.add(new paper.Point(inNodes[i].x + 3*cw, inNodes[i].y)); currentPath.add(new paper.Point(inNodes[i+1].x + 3*cw, inNodes[i+1].y)); currentPath.add(new paper.Point(inNodes[i+1])); outNodes.push(new paper.Point((inNodes[i].x + 3*cw, inNodes[i].y + inNodes[i+1].y)/2)); } pathList.push(currentPath); currentPath = new paper.Path(); inNodes = outNodes; } } else { for (i = 0; i < leafs; i++) { inNodes.push(new paper.Point(startX + i * (cw + spacing), startY)); } while (inNodes.length > 1) { var outNodes = []; for (i = 0; i < inNodes.length; i += 2) { currentPath.add(inNodes[i]); currentPath.add(new paper.Point(inNodes[i].x, inNodes[i].y + 3 * cw)); currentPath.add(new paper.Point(inNodes[i + 1].x, inNodes[i + 1].y + 3 * cw)); currentPath.add(new paper.Point(inNodes[i + 1])); outNodes.push(new paper.Point((inNodes[i].x + inNodes[i + 1].x) / 2, inNodes[i].y + 3 * cw)); } pathList.push(currentPath); currentPath = new paper.Path(); inNodes = outNodes; } } tree_path = new paper.CompoundPath(pathList); tree_path.strokeColor = color; tree_path.strokeColor.alpha = 0.5; tree_path.strokeWidth = cw; return tree_path; }; var CellTrapL = function(params) { let orientation = (params["orientation"] == "V"); let position = params["position"]; let chamberLength = params["chamberLength"]; let numChambers = params["numChambers"]; let chamberWidth = params["chamberWidth"]; let feedingChannelWidth = params["feedingChannelWidth"]; let chamberSpacing = params["chamberSpacing"]; let color = params["color"]; let x = position[0]; let y = position[1]; let chamberList = []; var rec; var traps; var channels; if (orientation) { for (i = 0; i < numChambers/2; i++) { rec = paper.Path.Rectangle({ size: [2*chamberLength + feedingChannelWidth, chamberWidth], point: [x, y + i*(chamberWidth + chamberSpacing)], fillColor: color }); chamberList.push(rec); } channels = paper.Path.Rectangle({ point: [x + chamberLength, y], size: [feedingChannelWidth, numChambers/2*(chamberWidth + chamberSpacing)], fillColor: color }); chamberList.push(channels); } else { for (i = 0; i < numChambers/2; i++) { rec = paper.Path.Rectangle({ size: [chamberWidth, 2*chamberLength + feedingChannelWidth], point: [x + i*(chamberWidth + chamberSpacing), y], fillColor: color }); chamberList.push(rec); } channels = paper.Path.Rectangle({ point: [x, y + chamberLength], size: [numChambers/2*(chamberWidth + chamberSpacing), feedingChannelWidth], fillColor: color }); chamberList.push(channels); } traps = new paper.CompoundPath(chamberList); traps.fillColor = color; return traps; }; var CellTrapLTarget = function(params) { let orientation = (params["orientation"] == "V"); let position = params["position"]; let chamberLength = params["chamberLength"]; let numChambers = params["numChambers"]; let chamberWidth = params["chamberWidth"]; let feedingChannelWidth = params["feedingChannelWidth"]; let chamberSpacing = params["chamberSpacing"]; let color = params["color"]; let x = position[0]; let y = position[1]; let chamberList = []; var rec; var traps; var channels; if (orientation) { for (i = 0; i < numChambers/2; i++) { rec = paper.Path.Rectangle({ size: [2*chamberLength + feedingChannelWidth, chamberWidth], point: [x, y + i*(chamberWidth + chamberSpacing)], fillColor: color }); chamberList.push(rec); } channels = paper.Path.Rectangle({ point: [x + chamberLength, y], size: [feedingChannelWidth, numChambers/2*(chamberWidth + chamberSpacing)], fillColor: color }); chamberList.push(channels); } else { for (i = 0; i < numChambers/2; i++) { rec = paper.Path.Rectangle({ size: [chamberWidth, 2*chamberLength + feedingChannelWidth], point: [x + i*(chamberWidth + chamberSpacing), y], fillColor: color }); chamberList.push(rec); } channels = paper.Path.Rectangle({ point: [x, y + chamberLength], size: [numChambers/2*(chamberWidth + chamberSpacing), feedingChannelWidth], fillColor: color }); chamberList.push(channels); } traps = new paper.CompoundPath(chamberList); traps.fillColor = color; traps.fillColor.alpha = 0.5; return traps; }; var DropletGen = function(params) { let pos = params["position"]; let color = params["color"]; let A = params["orificeSize"]; let B = 4.8*A; let C = 6.71*A; let D = 2.09*A; let E = 4.85*A; //var vertices = []; let v1, v2, v3, v4, v5, v6, v7, v8, v9, v10; v1 = [pos[0] - D/2, pos[1] - A/2]; v2 = [pos[0] - A/2, pos[1] - E/2]; v3 = [pos[0] + A/2, pos[1] - E/2]; v4 = [pos[0] + D/2, pos[1] - A/2]; v5 = [pos[0] + D/2 + C, pos[1] - B/2]; v6 = [pos[0] + D/2 + C, pos[1] + B/2]; v7 = [pos[0] + D/2, pos[1] + A/2]; v8 = [pos[0] + A/2, pos[1] + E/2]; v9 = [pos[0] - A/2, pos[1] + E/2]; v10 = [pos[0] - D/2, pos[1] + A/2]; var decahedron = new paper.Path(); decahedron.add(new paper.Point(v1)); decahedron.add(new paper.Point(v2)); decahedron.add(new paper.Point(v3)); decahedron.add(new paper.Point(v4)); decahedron.add(new paper.Point(v5)); decahedron.add(new paper.Point(v6)); decahedron.add(new paper.Point(v7)); decahedron.add(new paper.Point(v8)); decahedron.add(new paper.Point(v9)); decahedron.add(new paper.Point(v10)); decahedron.closed = true; decahedron.fillColor = color; //decahedron.strokeColor = "#FFFFFF"; //decahedron.strokeWidth = 3 / paper.view.zoom; return decahedron; }; var DropletGenTarget = function(params) { let pos = params["position"]; let color = params["color"]; let A = params["orificeSize"]; let B = 4.8*A; let C = 6.71*A; let D = 2.09*A; let E = 4.85*A; //var vertices = []; let v1, v2, v3, v4, v5, v6, v7, v8, v9, v10; v1 = [pos[0] - D/2, pos[1] - A/2]; v2 = [pos[0] - A/2, pos[1] - E/2]; v3 = [pos[0] + A/2, pos[1] - E/2]; v4 = [pos[0] + D/2, pos[1] - A/2]; v5 = [pos[0] + D/2 + C, pos[1] - B/2]; v6 = [pos[0] + D/2 + C, pos[1] + B/2]; v7 = [pos[0] + D/2, pos[1] + A/2]; v8 = [pos[0] + A/2, pos[1] + E/2]; v9 = [pos[0] - A/2, pos[1] + E/2]; v10 = [pos[0] - D/2, pos[1] + A/2]; var decahedron = new paper.Path(); decahedron.add(new paper.Point(v1)); decahedron.add(new paper.Point(v2)); decahedron.add(new paper.Point(v3)); decahedron.add(new paper.Point(v4)); decahedron.add(new paper.Point(v5)); decahedron.add(new paper.Point(v6)); decahedron.add(new paper.Point(v7)); decahedron.add(new paper.Point(v8)); decahedron.add(new paper.Point(v9)); decahedron.add(new paper.Point(v10)); decahedron.closed = true; decahedron.fillColor = color; decahedron.fillColor.alpha = 0.5; //decahedron.strokeColor = "#FFFFFF"; //decahedron.strokeWidth = 3 / paper.view.zoom; return decahedron; } module.exports.RoundedRectLine = RoundedRectLine; module.exports.EdgedRectLine = EdgedRectLine; module.exports.GradientCircle = GradientCircle; module.exports.RoundedRect = RoundedRect; module.exports.EdgedRect = EdgedRect; module.exports.CircleTarget = CircleTarget; module.exports.GroverValve = GroverValve; module.exports.Diamond = Diamond; module.exports.DiamondTarget = DiamondTarget; module.exports.Mixer = Mixer; module.exports.MixerTarget = MixerTarget; module.exports.EdgedRect = EdgedRect; module.exports.Tree = Tree; module.exports.TreeTarget = TreeTarget; module.exports.CellTrapL = CellTrapL; module.exports.CellTrapLTarget = CellTrapLTarget; module.exports.DropletGen = DropletGen; module.exports.DropletGenTarget = DropletGenTarget;
src/app/view/render2D/primitiveSets2D/basic2D.js
var RoundedRectLine = function(params){ let start = params["start"]; let end = params["end"]; let color = params["color"]; let width = params["width"]; let baseColor = params["baseColor"]; let startPoint = new paper.Point(start[0], start[1]); let endPoint = new paper.Point(end[0], end[1]); let vec = endPoint.subtract(startPoint); let rec = paper.Path.Rectangle({ size: [vec.length + width, width], point: start, radius: width/2, fillColor: color }); rec.translate([-width/2, -width / 2]); rec.rotate(vec.angle, start); return rec; } var EdgedRectLine = function(params){ let start = params["start"]; let end = params["end"]; let color = params["color"]; let width = params["width"]; let baseColor = params["baseColor"]; let startPoint = new paper.Point(start[0], start[1]); let endPoint = new paper.Point(end[0], end[1]); let vec = endPoint.subtract(startPoint); let rec = paper.Path.Rectangle({ size: [vec.length + width, width], point: start, // radius: width/2, fillColor: color }); rec.translate([-width/2, -width / 2]); rec.rotate(vec.angle, start); return rec; } var RoundedRect = function(params){ let start = params["start"]; let end = params["end"]; let borderWidth = params["borderWidth"]; let color = params["color"]; let baseColor = params["baseColor"]; let startX; let startY; let endX; let endY; if (start[0] < end[0]){ startX = start[0]; endX = end[0]; } else { startX = end[0]; endX = start[0]; } if (start[1] < end[1]){ startY = start[1]; endY = end[1]; } else { startY = end[1]; endY = start[1]; } startX -= borderWidth/2; startY -= borderWidth/2; endX += borderWidth/2; endY += borderWidth/2; let startPoint = new paper.Point(startX, startY); let endPoint = new paper.Point(endX, endY); let rec = paper.Path.Rectangle({ from: startPoint, to: endPoint, radius: borderWidth/2, fillColor: color }); return rec; } var EdgedRect = function(params){ let length = params["length"]; let width = params["width"]; let start = params["position"]; let borderWidth = params["borderWidth"]; let color = params["color"]; let baseColor = params["baseColor"]; let startX = start[0]; let startY = start[1]; let endX = startX + width; let endY = startY + length; // // if (start[0] < end[0]){ // startX = start[0]; // endX = end[0]; // } else { // startX = end[0]; // endX = start[0]; // } // if (start[1] < end[1]){ // startY = start[1]; // endY = end[1]; // } else { // startY = end[1]; // endY = start[1]; // } // startX -= borderWidth/2; // startY -= borderWidth/2; // endX += borderWidth/2; // endY += borderWidth/2; let startPoint = new paper.Point(startX, startY); let endPoint = new paper.Point(endX, endY); let rec = paper.Path.Rectangle({ from: startPoint, to: endPoint, // radius: borderWidth/2, fillColor: color }); return rec; } var GradientCircle = function(params){ let position = params["position"]; let radius1 = params["radius1"]; let radius2 = params["radius2"]; let color1 = params["color"]; let color2 = params["baseColor"]; let pos = new paper.Point(position[0], position[1]); let ratio = radius2 / radius1; let targetRatio; let targetRadius; if (ratio > 1) { targetRatio = 1; targetRadius = radius2; } else { targetRatio = ratio; targetRadius = radius1; } let outerCircle = new paper.Path.Circle(pos, targetRadius); outerCircle.fillColor = { gradient: { stops: [[color1, targetRatio], [color2, targetRatio]], radial: true }, origin: pos, destination: outerCircle.bounds.rightCenter }; return outerCircle; } var GroverValve = function(params){ let minRadiusInMicrometers = 8/paper.view.zoom; let position = params["position"]; let gap = params["gap"]; let radius = params["valveRadius"]; let color = params["color"]; let orientation = params["orientation"]; let center = new paper.Point(position[0], position[1]); // let h0p0, h0p1, h0p2, h1p0, h1p1, h1p2; var circ = new paper.Path.Circle(center, radius); //circ.fillColor = color; // if (String(color) == "3F51B5") { var cutout; if (orientation == "H") { cutout = paper.Path.Rectangle({ from: new paper.Point(position[0] - gap / 2, position[1] - radius), to: new paper.Point(position[0] + gap / 2, position[1] + radius) }); } else { cutout = paper.Path.Rectangle({ from: new paper.Point(position[0] - radius, position[1] - gap / 2), to: new paper.Point(position[0] + radius, position[1] + gap / 2) }); } //cutout.fillColor = "white"; var valve = new paper.CompoundPath(circ, cutout); valve.fillColor = color; valve.fillRule = 'evenodd'; //console.log(color); return valve; // } // else { // circ.FillColor = color; // return circ; // } } var CircleTarget = function(params){ let targetRadius; let radius1; let radius2; if (params.hasOwnProperty("diameter")) targetRadius = params["diameter"]/2; else { if (params.hasOwnProperty("portRadius")) { radius1 = portRadius; radius2 = portRadius; } else { radius1 = params["radius1"]; radius2 = params["radius2"]; if (radius1 > radius2) targetRadius = radius1; else targetRadius = radius2; } } let minSize = 8; //pixels let minSizeInMicrometers = 8/paper.view.zoom; let position = params["position"]; let color = params["color"]; let pos = new paper.Point(position[0], position[1]); if (targetRadius < minSizeInMicrometers) targetRadius = minSizeInMicrometers; let circ = new paper.Path.Circle(pos, targetRadius); circ.fillColor = color circ.fillColor.alpha = .5; circ.strokeColor = "#FFFFFF"; circ.strokeWidth = 3 / paper.view.zoom; if(circ.strokeWidth > targetRadius/2) circ.strokeWidth = targetRadius/2; return circ; } var Diamond = function(params){ let position = params["position"]; let px = position[0]; let py = position[1]; let cw = params["channelWidth"]; let l = params["length"]; let w = params["width"]; let orientation = params["orientation"]; let color = params["color"]; let p0, p1, p2, p3, p4, p5; if (orientation == "V"){ p0 = [px - cw/2, py - l/2]; p1 = [px + cw/2, py - l/2]; p2 = [px + w + cw/2, py]; p3 = [px + cw/2, py + l/2]; p4 = [px - cw/2, py + l/2]; p5 = [px - cw/2 - w, py]; } else{ p0 = [px - l/2, py - cw/2]; p1 = [px - l/2, py + cw/2]; p2 = [px, py + w + cw/2]; p3 = [px + l/2, py + cw/2]; p4 = [px + l/2, py - cw/2]; p5 = [px, py - cw/2 - w]; } var hex = new paper.Path(); hex.add(new paper.Point(p0)); hex.add(new paper.Point(p1)); hex.add(new paper.Point(p2)); hex.add(new paper.Point(p3)); hex.add(new paper.Point(p4)); hex.add(new paper.Point(p5)); hex.closed = true; hex.fillColor = color; return hex; } var DiamondTarget = function(params){ let position = params["position"]; let px = position[0]; let py = position[1]; let cw = params["channelWidth"]; let l = params["length"]; let w = params["width"]; let orientation = params["orientation"]; let color = params["color"]; let p0, p1, p2, p3, p4, p5; if (orientation == "V"){ p0 = [px - cw/2, py - l/2]; p1 = [px + cw/2, py - l/2]; p2 = [px + w + cw/2, py]; p3 = [px + cw/2, py + l/2]; p4 = [px - cw/2, py + l/2]; p5 = [px - cw/2 - w, py]; } else{ p0 = [px - l/2, py - cw/2]; p1 = [px - l/2, py + cw/2]; p2 = [px, py + w + cw/2]; p3 = [px + l/2, py + cw/2]; p4 = [px + l/2, py - cw/2]; p5 = [px, py - cw/2 - w]; } var hex = new paper.Path(); hex.add(new paper.Point(p0)); hex.add(new paper.Point(p1)); hex.add(new paper.Point(p2)); hex.add(new paper.Point(p3)); hex.add(new paper.Point(p4)); hex.add(new paper.Point(p5)); hex.closed = true; hex.fillColor = color; hex.fillColor.alpha = 0.5; hex.strokeColor = "#FFFFFF"; hex.strokeWidth = 3 / paper.view.zoom; if(hex.strokeWidth > w/2) hex.strokeWidth = w/2; //console.log(Math.ceil(Math.log2(7))); return hex; } var Mixer = function(params){ position = params["position"]; bendSpacing = params["bendSpacing"]; numBends = params["numberOfBends"]; channelWidth = params["channelWidth"]; bendLength = params["bendLength"]; orientation = params["orientation"]; let color = params["color"]; var serpentine = new paper.CompoundPath(); let startX, startY; if (orientation == "V"){ startX = position[0] + 0.5*(bendLength + channelWidth); startY = position[1] - 0.5 * channelWidth; serpentine.addChild(new paper.Path.Rectangle({ size: [0.5*bendLength + channelWidth, channelWidth], point: new paper.Point(startX - 0.5*bendLength - channelWidth, startY), fillColor: color })); //serpentine.add(new paper.Point(startX, startY)); for (i = 0; i < numBends - 1; i++) { serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, bendSpacing + channelWidth], point: new paper.Point(startX - 0.5*bendLength - channelWidth, startY + 2*i*(bendSpacing + channelWidth) + channelWidth), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [bendLength + channelWidth, channelWidth], point: new paper.Point(startX - 0.5*bendLength, startY + (2*i+1)*(bendSpacing + channelWidth)), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, bendSpacing + channelWidth], point: new paper.Point(startX + 0.5*bendLength, startY + (2*i+1)*(bendSpacing + channelWidth) + channelWidth), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [bendLength + channelWidth, channelWidth], point: new paper.Point(startX - 0.5*bendLength - channelWidth, startY + (2*i+2)*(bendSpacing + channelWidth)), fillColor: color })); } serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, bendSpacing + channelWidth], point: new paper.Point(startX - 0.5*bendLength - channelWidth, startY + 2*(numBends - 1)*(bendSpacing + channelWidth) + channelWidth), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [bendLength + channelWidth, channelWidth], point: new paper.Point(startX - 0.5*bendLength, startY + (2*(numBends - 1)+1)*(bendSpacing + channelWidth)), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, bendSpacing + channelWidth], point: new paper.Point(startX + 0.5*bendLength, startY + (2*(numBends - 1)+1)*(bendSpacing + channelWidth) + channelWidth), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [bendLength/2, channelWidth], point: new paper.Point(startX, startY + (2*(numBends - 1)+2)*(bendSpacing + channelWidth)), fillColor: color })); serpentine.scale(-1,1); } else { startX = position[0] - 0.5 * channelWidth; startY = position[1] + 0.5*(bendLength + channelWidth); //serpentine.add(new paper.Point(startX, startY)); serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, 0.5*bendLength + channelWidth], point: new paper.Point(startX, startY - 0.5*bendLength - channelWidth), fillColor: color })); for (i = 0; i < numBends - 1; i++) { serpentine.addChild(new paper.Path.Rectangle({ size: [bendSpacing + channelWidth, channelWidth], point: new paper.Point(startX + 2*i*(bendSpacing + channelWidth) + channelWidth, startY - 0.5*bendLength - channelWidth), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, bendLength + channelWidth], point: new paper.Point(startX + (2*i+1)*(bendSpacing + channelWidth), startY - 0.5*bendLength), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [bendSpacing + channelWidth, channelWidth], point: new paper.Point(startX + (2*i+1)*(bendSpacing + channelWidth) + channelWidth, startY + 0.5*bendLength), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, bendLength + channelWidth], point: new paper.Point(startX + (2*i+2)*(bendSpacing + channelWidth), startY - 0.5*bendLength - channelWidth), fillColor: color })); } serpentine.addChild(new paper.Path.Rectangle({ size: [bendSpacing + channelWidth, channelWidth], point: new paper.Point(startX + 2*(numBends - 1)*(bendSpacing + channelWidth) + channelWidth, startY - 0.5*bendLength - channelWidth), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, bendLength + channelWidth], point: new paper.Point(startX + (2*(numBends - 1)+1)*(bendSpacing + channelWidth), startY - 0.5*bendLength), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [bendSpacing + channelWidth, channelWidth], point: new paper.Point(startX + (2*(numBends - 1)+1)*(bendSpacing + channelWidth) + channelWidth, startY + 0.5*bendLength), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, bendLength/2], point: new paper.Point(startX + (2*(numBends - 1)+2)*(bendSpacing + channelWidth), startY), fillColor: color })); } serpentine.fillColor = color; return serpentine; } var MixerTarget = function(params){ position = params["position"]; bendSpacing = params["bendSpacing"]; numBends = params["numberOfBends"]; channelWidth = params["channelWidth"]; bendLength = params["bendLength"]; orientation = params["orientation"]; let color = params["color"]; var serpentine = new paper.CompoundPath(); let startX, startY; if (orientation == "V"){ startX = position[0] + 0.5*(bendLength + channelWidth); startY = position[1] - 0.5 * channelWidth; serpentine.addChild(new paper.Path.Rectangle({ size: [0.5*bendLength + channelWidth, channelWidth], point: new paper.Point(startX - 0.5*bendLength - channelWidth, startY), fillColor: color })); //serpentine.add(new paper.Point(startX, startY)); for (i = 0; i < numBends - 1; i++) { serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, bendSpacing + channelWidth], point: new paper.Point(startX - 0.5*bendLength - channelWidth, startY + 2*i*(bendSpacing + channelWidth) + channelWidth), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [bendLength + channelWidth, channelWidth], point: new paper.Point(startX - 0.5*bendLength, startY + (2*i+1)*(bendSpacing + channelWidth)), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, bendSpacing + channelWidth], point: new paper.Point(startX + 0.5*bendLength, startY + (2*i+1)*(bendSpacing + channelWidth) + channelWidth), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [bendLength + channelWidth, channelWidth], point: new paper.Point(startX - 0.5*bendLength - channelWidth, startY + (2*i+2)*(bendSpacing + channelWidth)), fillColor: color })); } serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, bendSpacing + channelWidth], point: new paper.Point(startX - 0.5*bendLength - channelWidth, startY + 2*(numBends - 1)*(bendSpacing + channelWidth) + channelWidth), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [bendLength + channelWidth, channelWidth], point: new paper.Point(startX - 0.5*bendLength, startY + (2*(numBends - 1)+1)*(bendSpacing + channelWidth)), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, bendSpacing + channelWidth], point: new paper.Point(startX + 0.5*bendLength, startY + (2*(numBends - 1)+1)*(bendSpacing + channelWidth) + channelWidth), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [bendLength/2, channelWidth], point: new paper.Point(startX, startY + (2*(numBends - 1)+2)*(bendSpacing + channelWidth)), fillColor: color })); serpentine.scale(-1,1); } else { startX = position[0] - 0.5 * channelWidth; startY = position[1] + 0.5*(bendLength + channelWidth); //serpentine.add(new paper.Point(startX, startY)); serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, 0.5*bendLength + channelWidth], point: new paper.Point(startX, startY - 0.5*bendLength - channelWidth), fillColor: color })); for (i = 0; i < numBends - 1; i++) { serpentine.addChild(new paper.Path.Rectangle({ size: [bendSpacing + channelWidth, channelWidth], point: new paper.Point(startX + 2*i*(bendSpacing + channelWidth) + channelWidth, startY - 0.5*bendLength - channelWidth), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, bendLength + channelWidth], point: new paper.Point(startX + (2*i+1)*(bendSpacing + channelWidth), startY - 0.5*bendLength), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [bendSpacing + channelWidth, channelWidth], point: new paper.Point(startX + (2*i+1)*(bendSpacing + channelWidth) + channelWidth, startY + 0.5*bendLength), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, bendLength + channelWidth], point: new paper.Point(startX + (2*i+2)*(bendSpacing + channelWidth), startY - 0.5*bendLength - channelWidth), fillColor: color })); } serpentine.addChild(new paper.Path.Rectangle({ size: [bendSpacing + channelWidth, channelWidth], point: new paper.Point(startX + 2*(numBends - 1)*(bendSpacing + channelWidth) + channelWidth, startY - 0.5*bendLength - channelWidth), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, bendLength + channelWidth], point: new paper.Point(startX + (2*(numBends - 1)+1)*(bendSpacing + channelWidth), startY - 0.5*bendLength), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [bendSpacing + channelWidth, channelWidth], point: new paper.Point(startX + (2*(numBends - 1)+1)*(bendSpacing + channelWidth) + channelWidth, startY + 0.5*bendLength), fillColor: color })); serpentine.addChild(new paper.Path.Rectangle({ size: [channelWidth, bendLength/2], point: new paper.Point(startX + (2*(numBends - 1)+2)*(bendSpacing + channelWidth), startY), fillColor: color })); } serpentine.fillColor = color; serpentine.fillColor.alpha = 0.5; return serpentine; } var Tree = function(params) { position = params["position"]; cw = params["flowChannelWidth"]; orientation = params["orientation"]; spacing = params["spacing"]; leafs = params["leafs"]; color = params["color"]; width = params["width"]; startX = position[0]; startY = position[1]; var pathList = []; var inNodes = []; var currentPath = new paper.Path(); if (orientation == "V") { for (i = 0; i < leafs; i++) { inNodes.push(new paper.Point(startX, startY + i*(cw + spacing))); } while (inNodes.length > 1) { var outNodes = []; for (i = 0; i < inNodes.length; i += 2) { currentPath.add(inNodes[i]); currentPath.add(new paper.Point(inNodes[i].x + 3*cw, inNodes[i].y)); currentPath.add(new paper.Point(inNodes[i+1].x + 3*cw, inNodes[i+1].y)); currentPath.add(new paper.Point(inNodes[i+1])); outNodes.push(new paper.Point((inNodes[i].x + 3*cw, inNodes[i].y + inNodes[i+1].y)/2)); } pathList.push(currentPath); currentPath = new paper.Path(); inNodes = outNodes; } pathList.push(new paper.Point(width, pathList[pathList.length-1].y)); } else { for (i = 0; i < leafs; i++) { inNodes.push(new paper.Point(startX + i * (cw + spacing), startY)); } while (inNodes.length > 1) { var outNodes = []; for (i = 0; i < inNodes.length; i += 2) { currentPath.add(inNodes[i]); currentPath.add(new paper.Point(inNodes[i].x, inNodes[i].y + 3 * cw)); currentPath.add(new paper.Point(inNodes[i + 1].x, inNodes[i + 1].y + 3 * cw)); currentPath.add(new paper.Point(inNodes[i + 1])); outNodes.push(new paper.Point((inNodes[i].x + inNodes[i + 1].x) / 2, inNodes[i].y + 3 * cw)); } pathList.push(currentPath); currentPath = new paper.Path(); inNodes = outNodes; } } tree_path = new paper.CompoundPath(pathList); tree_path.strokeColor = color; tree_path.strokeWidth = cw; return tree_path; } var TreeTarget = function(params) { position = params["position"]; cw = params["flowChannelWidth"]; orientation = params["orientation"]; spacing = params["spacing"]; leafs = params["leafs"]; color = params["color"]; startX = position[0]; startY = position[1]; var pathList = []; var inNodes = []; var currentPath = new paper.Path(); if (orientation == "V") { for (i = 0; i < leafs; i++) { inNodes.push(new paper.Point(startX, startY + i*(cw + spacing))); } while (inNodes.length > 1) { var outNodes = []; for (i = 0; i < inNodes.length; i += 2) { currentPath.add(inNodes[i]); currentPath.add(new paper.Point(inNodes[i].x + 3*cw, inNodes[i].y)); currentPath.add(new paper.Point(inNodes[i+1].x + 3*cw, inNodes[i+1].y)); currentPath.add(new paper.Point(inNodes[i+1])); outNodes.push(new paper.Point((inNodes[i].x + 3*cw, inNodes[i].y + inNodes[i+1].y)/2)); } pathList.push(currentPath); currentPath = new paper.Path(); inNodes = outNodes; } } else { for (i = 0; i < leafs; i++) { inNodes.push(new paper.Point(startX + i * (cw + spacing), startY)); } while (inNodes.length > 1) { var outNodes = []; for (i = 0; i < inNodes.length; i += 2) { currentPath.add(inNodes[i]); currentPath.add(new paper.Point(inNodes[i].x, inNodes[i].y + 3 * cw)); currentPath.add(new paper.Point(inNodes[i + 1].x, inNodes[i + 1].y + 3 * cw)); currentPath.add(new paper.Point(inNodes[i + 1])); outNodes.push(new paper.Point((inNodes[i].x + inNodes[i + 1].x) / 2, inNodes[i].y + 3 * cw)); } pathList.push(currentPath); currentPath = new paper.Path(); inNodes = outNodes; } } tree_path = new paper.CompoundPath(pathList); tree_path.strokeColor = color; tree_path.strokeColor.alpha = 0.5; tree_path.strokeWidth = cw; return tree_path; }; var CellTrapL = function(params) { let orientation = (params["orientation"] == "V"); let position = params["position"]; let chamberLength = params["chamberLength"]; let numChambers = params["numChambers"]; let chamberWidth = params["chamberWidth"]; let feedingChannelWidth = params["feedingChannelWidth"]; let chamberSpacing = params["chamberSpacing"]; let color = params["color"]; let x = position[0]; let y = position[1]; let chamberList = []; var rec; var traps; var channels; if (orientation) { for (i = 0; i < numChambers/2; i++) { rec = paper.Path.Rectangle({ size: [2*chamberLength + feedingChannelWidth, chamberWidth], point: [x, y + i*(chamberWidth + chamberSpacing)], fillColor: color }); chamberList.push(rec); } channels = paper.Path.Rectangle({ point: [x + chamberLength, y], size: [feedingChannelWidth, numChambers/2*(chamberWidth + chamberSpacing)], fillColor: color }); chamberList.push(channels); } else { for (i = 0; i < numChambers/2; i++) { rec = paper.Path.Rectangle({ size: [chamberWidth, 2*chamberLength + feedingChannelWidth], point: [x + i*(chamberWidth + chamberSpacing), y], fillColor: color }); chamberList.push(rec); } channels = paper.Path.Rectangle({ point: [x, y + chamberLength], size: [numChambers/2*(chamberWidth + chamberSpacing), feedingChannelWidth], fillColor: color }); chamberList.push(channels); } traps = new paper.CompoundPath(chamberList); traps.fillColor = color; return traps; }; var CellTrapLTarget = function(params) { let orientation = (params["orientation"] == "V"); let position = params["position"]; let chamberLength = params["chamberLength"]; let numChambers = params["numChambers"]; let chamberWidth = params["chamberWidth"]; let feedingChannelWidth = params["feedingChannelWidth"]; let chamberSpacing = params["chamberSpacing"]; let color = params["color"]; let x = position[0]; let y = position[1]; let chamberList = []; var rec; var traps; var channels; if (orientation) { for (i = 0; i < numChambers/2; i++) { rec = paper.Path.Rectangle({ size: [2*chamberLength + feedingChannelWidth, chamberWidth], point: [x, y + i*(chamberWidth + chamberSpacing)], fillColor: color }); chamberList.push(rec); } channels = paper.Path.Rectangle({ point: [x + chamberLength, y], size: [feedingChannelWidth, numChambers/2*(chamberWidth + chamberSpacing)], fillColor: color }); chamberList.push(channels); } else { for (i = 0; i < numChambers/2; i++) { rec = paper.Path.Rectangle({ size: [chamberWidth, 2*chamberLength + feedingChannelWidth], point: [x + i*(chamberWidth + chamberSpacing), y], fillColor: color }); chamberList.push(rec); } channels = paper.Path.Rectangle({ point: [x, y + chamberLength], size: [numChambers/2*(chamberWidth + chamberSpacing), feedingChannelWidth], fillColor: color }); chamberList.push(channels); } traps = new paper.CompoundPath(chamberList); traps.fillColor = color; traps.fillColor.alpha = 0.5; return traps; }; var DropletGen = function(params) { let pos = params["position"]; let color = params["color"]; let A = params["orificeSize"]; let B = 4.8*A; let C = 6.71*A; let D = 2.09*A; let E = 4.85*A; //var vertices = []; let v1, v2, v3, v4, v5, v6, v7, v8, v9, v10; v1 = [pos[0] - D/2, pos[1] - A/2]; v2 = [pos[0] - A/2, pos[1] - E/2]; v3 = [pos[0] + A/2, pos[1] - E/2]; v4 = [pos[0] + D/2, pos[1] - A/2]; v5 = [pos[0] + D/2 + C, pos[1] - B/2]; v6 = [pos[0] + D/2 + C, pos[1] + B/2]; v7 = [pos[0] + D/2, pos[1] + A/2]; v8 = [pos[0] + A/2, pos[1] + E/2]; v9 = [pos[0] - A/2, pos[1] + E/2]; v10 = [pos[0] - D/2, pos[1] + A/2]; var decahedron = new paper.Path(); decahedron.add(new paper.Point(v1)); decahedron.add(new paper.Point(v2)); decahedron.add(new paper.Point(v3)); decahedron.add(new paper.Point(v4)); decahedron.add(new paper.Point(v5)); decahedron.add(new paper.Point(v6)); decahedron.add(new paper.Point(v7)); decahedron.add(new paper.Point(v8)); decahedron.add(new paper.Point(v9)); decahedron.add(new paper.Point(v10)); decahedron.closed = true; decahedron.fillColor = color; //decahedron.strokeColor = "#FFFFFF"; //decahedron.strokeWidth = 3 / paper.view.zoom; return decahedron; }; var DropletGenTarget = function(params) { let pos = params["position"]; let color = params["color"]; let A = params["orificeSize"]; let B = 4.8*A; let C = 6.71*A; let D = 2.09*A; let E = 4.85*A; //var vertices = []; let v1, v2, v3, v4, v5, v6, v7, v8, v9, v10; v1 = [pos[0] - D/2, pos[1] - A/2]; v2 = [pos[0] - A/2, pos[1] - E/2]; v3 = [pos[0] + A/2, pos[1] - E/2]; v4 = [pos[0] + D/2, pos[1] - A/2]; v5 = [pos[0] + D/2 + C, pos[1] - B/2]; v6 = [pos[0] + D/2 + C, pos[1] + B/2]; v7 = [pos[0] + D/2, pos[1] + A/2]; v8 = [pos[0] + A/2, pos[1] + E/2]; v9 = [pos[0] - A/2, pos[1] + E/2]; v10 = [pos[0] - D/2, pos[1] + A/2]; var decahedron = new paper.Path(); decahedron.add(new paper.Point(v1)); decahedron.add(new paper.Point(v2)); decahedron.add(new paper.Point(v3)); decahedron.add(new paper.Point(v4)); decahedron.add(new paper.Point(v5)); decahedron.add(new paper.Point(v6)); decahedron.add(new paper.Point(v7)); decahedron.add(new paper.Point(v8)); decahedron.add(new paper.Point(v9)); decahedron.add(new paper.Point(v10)); decahedron.closed = true; decahedron.fillColor = color; decahedron.fillColor.alpha = 0.5; //decahedron.strokeColor = "#FFFFFF"; //decahedron.strokeWidth = 3 / paper.view.zoom; return decahedron; } module.exports.RoundedRectLine = RoundedRectLine; module.exports.EdgedRectLine = EdgedRectLine; module.exports.GradientCircle = GradientCircle; module.exports.RoundedRect = RoundedRect; module.exports.EdgedRect = EdgedRect; module.exports.CircleTarget = CircleTarget; module.exports.GroverValve = GroverValve; module.exports.Diamond = Diamond; module.exports.DiamondTarget = DiamondTarget; module.exports.Mixer = Mixer; module.exports.MixerTarget = MixerTarget; module.exports.EdgedRect = EdgedRect; module.exports.Tree = Tree; module.exports.TreeTarget = TreeTarget; module.exports.CellTrapL = CellTrapL; module.exports.CellTrapLTarget = CellTrapLTarget; module.exports.DropletGen = DropletGen; module.exports.DropletGenTarget = DropletGenTarget;
Fix for diamond chamber checkbox
src/app/view/render2D/primitiveSets2D/basic2D.js
Fix for diamond chamber checkbox
<ide><path>rc/app/view/render2D/primitiveSets2D/basic2D.js <ide> let orientation = params["orientation"]; <ide> let color = params["color"]; <ide> let p0, p1, p2, p3, p4, p5; <del> if (orientation == "V"){ <add> if (orientation == "H"){ <add> p0 = [px - l/2, py - cw/2]; <add> p1 = [px - l/2, py + cw/2]; <add> p2 = [px, py + w + cw/2]; <add> p3 = [px + l/2, py + cw/2]; <add> p4 = [px + l/2, py - cw/2]; <add> p5 = [px, py - cw/2 - w]; <add> } <add> else{ <ide> p0 = [px - cw/2, py - l/2]; <ide> p1 = [px + cw/2, py - l/2]; <ide> p2 = [px + w + cw/2, py]; <ide> p3 = [px + cw/2, py + l/2]; <ide> p4 = [px - cw/2, py + l/2]; <ide> p5 = [px - cw/2 - w, py]; <del> } <del> else{ <del> p0 = [px - l/2, py - cw/2]; <del> p1 = [px - l/2, py + cw/2]; <del> p2 = [px, py + w + cw/2]; <del> p3 = [px + l/2, py + cw/2]; <del> p4 = [px + l/2, py - cw/2]; <del> p5 = [px, py - cw/2 - w]; <ide> } <ide> var hex = new paper.Path(); <ide> hex.add(new paper.Point(p0)); <ide> let orientation = params["orientation"]; <ide> let color = params["color"]; <ide> let p0, p1, p2, p3, p4, p5; <del> if (orientation == "V"){ <add> if (orientation == "H"){ <add> p0 = [px - l/2, py - cw/2]; <add> p1 = [px - l/2, py + cw/2]; <add> p2 = [px, py + w + cw/2]; <add> p3 = [px + l/2, py + cw/2]; <add> p4 = [px + l/2, py - cw/2]; <add> p5 = [px, py - cw/2 - w]; <add> } <add> else{ <ide> p0 = [px - cw/2, py - l/2]; <ide> p1 = [px + cw/2, py - l/2]; <ide> p2 = [px + w + cw/2, py]; <ide> p3 = [px + cw/2, py + l/2]; <ide> p4 = [px - cw/2, py + l/2]; <ide> p5 = [px - cw/2 - w, py]; <del> } <del> else{ <del> p0 = [px - l/2, py - cw/2]; <del> p1 = [px - l/2, py + cw/2]; <del> p2 = [px, py + w + cw/2]; <del> p3 = [px + l/2, py + cw/2]; <del> p4 = [px + l/2, py - cw/2]; <del> p5 = [px, py - cw/2 - w]; <ide> } <ide> var hex = new paper.Path(); <ide> hex.add(new paper.Point(p0));
JavaScript
mit
a57416c36b5604b84336ddbbaa78a2eff6c13bd7
0
mrbigmouth/acgn-stock,silentvow/acgn-stock,mrbigmouth/acgn-stock,silentvow/acgn-stock
import { _ } from 'meteor/underscore'; import { Meteor } from 'meteor/meteor'; import { resourceManager } from '/server/imports/threading/resourceManager'; import { dbFoundations } from '/db/dbFoundations'; import { dbLog } from '/db/dbLog'; import { dbCompanies } from '/db/dbCompanies'; import { dbCompanyArchive } from '/db/dbCompanyArchive'; import { dbDirectors } from '/db/dbDirectors'; import { dbPrice } from '/db/dbPrice'; import { debug } from '/server/imports/utils/debug'; const { foundExpireTime, foundationNeedUsers, minReleaseStock } = Meteor.settings.public; // 檢查所有已截止的新創公司 export function checkExpiredFoundations() { debug.log('checkExpiredFoundations'); const expiredFoundationCreatedAt = new Date(Date.now() - foundExpireTime); dbFoundations .find({ createdAt: { $lt: expiredFoundationCreatedAt } }, { fields: { _id: 1 }, disableOplog: true }) .forEach(({ _id: companyId }) => { //先鎖定資源,再重新讀取一次資料進行運算 resourceManager.request('checkExpiredFoundations', [`foundation${companyId}`], (release) => { const foundationData = dbFoundations.findOne(companyId); if (! foundationData) { release(); return; } if (foundationData.invest.length >= foundationNeedUsers) { doOnFoundationSuccess(foundationData); } else { doOnFoundationFailure(foundationData); } release(); }); }); } // 由投資狀況計算初始股價 function calculateInitialPrice(investors) { const totalFund = _.reduce(investors, (sum, investorData) => { return sum + investorData.amount; }, 0); if (totalFund === 0) { throw new Meteor.Error('something went wrong: totalFund === 0'); } let price = 1; while (Math.ceil(totalFund / price / 2) > minReleaseStock) { price *= 2; } return price; } // 以指定股價計算投資人的配股與退款 function calculateDirectors(investors, price) { return _.map(investors, ({userId, amount}) => { const stocks = Math.floor(amount / price); const refund = amount - (price * stocks); return { userId, stocks, refund }; }); } // 計算投資人的配股與退款、初始股價與初始釋股數 function processStockOffering(investors) { let price = calculateInitialPrice(investors); let directors; let totalRelease; do { if (price < 1) { throw new Meteor.Error('something went wrong: price < 1'); } directors = calculateDirectors(investors, price); totalRelease = _.reduce(directors, (sum, directorData) => { return sum + directorData.stocks; }, 0); // 確保股數在最小限制之上,否則股價折半重新計算 if (totalRelease < minReleaseStock) { price = Math.floor(price / 2); } } while (totalRelease < minReleaseStock); return { directors, price, totalRelease }; } // 新創公司成功之處理 export function doOnFoundationSuccess(foundationData) { const { _id: companyId, invest } = foundationData; const { directors, price, totalRelease } = processStockOffering(invest); const companiesBulk = dbCompanies.rawCollection().initializeUnorderedBulkOp(); const logBulk = dbLog.rawCollection().initializeUnorderedBulkOp(); const directorsBulk = dbDirectors.rawCollection().initializeUnorderedBulkOp(); const usersBulk = Meteor.users.rawCollection().initializeUnorderedBulkOp(); const basicCreatedAt = new Date(); logBulk.insert({ logType: '創立成功', userId: _.pluck(invest, 'userId'), companyId: companyId, data: { price }, createdAt: basicCreatedAt }); const candidateList = []; if (foundationData.manager !== '!none') { candidateList.push(foundationData.manager); } const voteList = candidateList.map(() => { return []; }); const companySchema = dbCompanies.simpleSchema(); const newCompanyData = companySchema.clean({ companyName: foundationData.companyName, manager: foundationData.manager, chairman: '!none', chairmanTitle: '董事長', tags: foundationData.tags, pictureSmall: foundationData.pictureSmall, pictureBig: foundationData.pictureBig, description: foundationData.description, illegalReason: foundationData.illegalReason, totalRelease: totalRelease, lastPrice: price, listPrice: price, totalValue: totalRelease * price, candidateList: candidateList, voteList: voteList, createdAt: basicCreatedAt }); companySchema.validate(newCompanyData); companiesBulk.insert({ _id: companyId, ...newCompanyData }); dbPrice.insert({ companyId: companyId, price: price, createdAt: basicCreatedAt }); let needExecuteDirectorsBulk = false; let needExecuteUserBulk = false; directors.forEach(({ userId, stocks, refund }, index) => { const createdAt = new Date(basicCreatedAt.getTime() + index + 1); if (stocks > 0) { logBulk.insert({ logType: '創立得股', userId: [userId], companyId: companyId, data: { fund: (price * stocks) + refund, stocks }, createdAt: createdAt }); needExecuteDirectorsBulk = true; directorsBulk.insert({ companyId, userId, stocks, createdAt }); } if (refund > 0) { logBulk.insert({ logType: '創立退款', userId: [userId], companyId: companyId, data: { companyName: foundationData.companyName, // TODO lagecy field refund: refund }, createdAt: createdAt }); needExecuteUserBulk = true; usersBulk .find({_id: userId}) .updateOne({ $inc: { 'profile.money': refund } }); } }); Meteor.wrapAsync(companiesBulk.execute).call(companiesBulk); Meteor.wrapAsync(logBulk.execute).call(logBulk); if (needExecuteDirectorsBulk) { Meteor.wrapAsync(directorsBulk.execute).call(directorsBulk); } if (needExecuteUserBulk) { Meteor.wrapAsync(usersBulk.execute).call(usersBulk); } dbFoundations.remove(companyId); dbCompanyArchive.update(companyId, { $set: { status: 'market' } }); } // 新創公司失敗之處理 export function doOnFoundationFailure(foundationData) { const { _id: companyId, invest, companyName, manager } = foundationData; const logBulk = dbLog.rawCollection().initializeUnorderedBulkOp(); const usersBulk = Meteor.users.rawCollection().initializeUnorderedBulkOp(); const createdAt = new Date(); logBulk.insert({ logType: '創立失敗', userId: _.union([manager], _.pluck(invest, 'userId')), data: { companyName }, createdAt: createdAt }); invest.forEach(({ userId, amount }, index) => { if (userId === foundationData.manager) { amount -= Meteor.settings.public.founderEarnestMoney; } logBulk.insert({ logType: '創立退款', userId: [userId], data: { companyName: foundationData.companyName, refund: amount }, createdAt: new Date(createdAt.getTime() + index + 1) }); usersBulk .find({_id: userId}) .updateOne({ $inc: { 'profile.money': amount } }); }); dbFoundations.remove(companyId); dbCompanyArchive.remove(companyId); logBulk .find({ companyId }) .update({ $unset: { companyId: 1 } }); Meteor.wrapAsync(logBulk.execute).call(logBulk); if (foundationData.invest.length > 0) { Meteor.wrapAsync(usersBulk.execute).call(usersBulk); } }
server/foundation.js
import { _ } from 'meteor/underscore'; import { Meteor } from 'meteor/meteor'; import { resourceManager } from '/server/imports/threading/resourceManager'; import { dbFoundations } from '/db/dbFoundations'; import { dbLog } from '/db/dbLog'; import { dbCompanies } from '/db/dbCompanies'; import { dbCompanyArchive } from '/db/dbCompanyArchive'; import { dbDirectors } from '/db/dbDirectors'; import { dbPrice } from '/db/dbPrice'; import { debug } from '/server/imports/utils/debug'; const { foundExpireTime, foundationNeedUsers, minReleaseStock } = Meteor.settings.public; // 檢查所有已截止的新創公司 export function checkExpiredFoundations() { debug.log('checkExpiredFoundations'); const expiredFoundationCreatedAt = new Date(Date.now() - foundExpireTime); dbFoundations .find({ createdAt: { $lt: expiredFoundationCreatedAt } }, { fields: { _id: 1 }, disableOplog: true }) .forEach(({ _id: companyId }) => { //先鎖定資源,再重新讀取一次資料進行運算 resourceManager.request('checkExpiredFoundations', [`foundation${companyId}`], (release) => { const foundationData = dbFoundations.findOne(companyId); if (! foundationData) { release(); return; } if (foundationData.invest.length >= foundationNeedUsers) { doOnFoundationSuccess(foundationData); } else { doOnFoundationFailure(foundationData); } release(); }); }); } // 由投資狀況計算初始股價 function calculateInitialPrice(investors) { const totalFund = _.reduce(investors, (sum, investorData) => { return sum + investorData.amount; }, 0); if (totalFund === 0) { throw new Meteor.Error('something went wrong: totalFund === 0'); } let price = 1; while (Math.ceil(totalFund / price / 2) > minReleaseStock) { price *= 2; } return price; } // 以指定股價計算投資人的配股與退款 function calculateDirectors(investors, price) { return _.map(investors, ({userId, amount}) => { const stocks = Math.floor(amount / price); const refund = amount - (price * stocks); return { userId, stocks, refund }; }); } // 計算投資人的配股與退款、初始股價與初始釋股數 function processStockOffering(investors) { let price = calculateInitialPrice(investors); let directors; let totalRelease; do { if (price < 1) { throw new Meteor.Error('something went wrong: price < 1'); } directors = calculateDirectors(investors, price); totalRelease = _.reduce(directors, (sum, directorData) => { return sum + directorData.stocks; }, 0); // 確保股數在最小限制之上,否則股價折半重新計算 if (totalRelease < minReleaseStock) { price = Math.floor(price / 2); } } while (totalRelease < minReleaseStock); return { directors, price, totalRelease }; } // 新創公司成功之處理 export function doOnFoundationSuccess(foundationData) { const { _id: companyId, invest } = foundationData; const { directors, price, totalRelease } = processStockOffering(invest); const companiesBulk = dbCompanies.rawCollection().initializeUnorderedBulkOp(); const logBulk = dbLog.rawCollection().initializeUnorderedBulkOp(); const directorsBulk = dbDirectors.rawCollection().initializeUnorderedBulkOp(); const usersBulk = Meteor.users.rawCollection().initializeUnorderedBulkOp(); const basicCreatedAt = new Date(); logBulk.insert({ logType: '創立成功', userId: _.pluck(invest, 'userId'), companyId: companyId, data: { price }, createdAt: basicCreatedAt }); const candidateList = []; if (foundationData.manager !== '!none') { candidateList.push(foundationData.manager); } companiesBulk.insert(dbCompanies.simpleSchema().clean({ _id: companyId, companyName: foundationData.companyName, manager: foundationData.manager, chairmanTitle: '董事長', tags: foundationData.tags, pictureSmall: foundationData.pictureSmall, pictureBig: foundationData.pictureBig, description: foundationData.description, illegalReason: foundationData.illegalReason, totalRelease: totalRelease, lastPrice: price, listPrice: price, totalValue: totalRelease * price, candidateList: candidateList, createdAt: basicCreatedAt }, { filter: false // 防止 _id 被 filter 掉 })); dbPrice.insert({ companyId: companyId, price: price, createdAt: basicCreatedAt }); let needExecuteDirectorsBulk = false; let needExecuteUserBulk = false; directors.forEach(({ userId, stocks, refund }, index) => { const createdAt = new Date(basicCreatedAt.getTime() + index + 1); if (stocks > 0) { logBulk.insert({ logType: '創立得股', userId: [userId], companyId: companyId, data: { fund: (price * stocks) + refund, stocks }, createdAt: createdAt }); needExecuteDirectorsBulk = true; directorsBulk.insert({ companyId, userId, stocks, createdAt }); } if (refund > 0) { logBulk.insert({ logType: '創立退款', userId: [userId], companyId: companyId, data: { companyName: foundationData.companyName, // TODO lagecy field refund: refund }, createdAt: createdAt }); needExecuteUserBulk = true; usersBulk .find({_id: userId}) .updateOne({ $inc: { 'profile.money': refund } }); } }); Meteor.wrapAsync(companiesBulk.execute).call(companiesBulk); Meteor.wrapAsync(logBulk.execute).call(logBulk); if (needExecuteDirectorsBulk) { Meteor.wrapAsync(directorsBulk.execute).call(directorsBulk); } if (needExecuteUserBulk) { Meteor.wrapAsync(usersBulk.execute).call(usersBulk); } dbFoundations.remove(companyId); dbCompanyArchive.update(companyId, { $set: { status: 'market' } }); } // 新創公司失敗之處理 export function doOnFoundationFailure(foundationData) { const { _id: companyId, invest, companyName, manager } = foundationData; const logBulk = dbLog.rawCollection().initializeUnorderedBulkOp(); const usersBulk = Meteor.users.rawCollection().initializeUnorderedBulkOp(); const createdAt = new Date(); logBulk.insert({ logType: '創立失敗', userId: _.union([manager], _.pluck(invest, 'userId')), data: { companyName }, createdAt: createdAt }); invest.forEach(({ userId, amount }, index) => { if (userId === foundationData.manager) { amount -= Meteor.settings.public.founderEarnestMoney; } logBulk.insert({ logType: '創立退款', userId: [userId], data: { companyName: foundationData.companyName, refund: amount }, createdAt: new Date(createdAt.getTime() + index + 1) }); usersBulk .find({_id: userId}) .updateOne({ $inc: { 'profile.money': amount } }); }); dbFoundations.remove(companyId); dbCompanyArchive.remove(companyId); logBulk .find({ companyId }) .update({ $unset: { companyId: 1 } }); Meteor.wrapAsync(logBulk.execute).call(logBulk); if (foundationData.invest.length > 0) { Meteor.wrapAsync(usersBulk.execute).call(usersBulk); } }
修正新創成功時新公司缺少資料的問題,並在插入前進行驗證
server/foundation.js
修正新創成功時新公司缺少資料的問題,並在插入前進行驗證
<ide><path>erver/foundation.js <ide> candidateList.push(foundationData.manager); <ide> } <ide> <del> companiesBulk.insert(dbCompanies.simpleSchema().clean({ <del> _id: companyId, <add> const voteList = candidateList.map(() => { <add> return []; <add> }); <add> <add> const companySchema = dbCompanies.simpleSchema(); <add> const newCompanyData = companySchema.clean({ <ide> companyName: foundationData.companyName, <ide> manager: foundationData.manager, <add> chairman: '!none', <ide> chairmanTitle: '董事長', <ide> tags: foundationData.tags, <ide> pictureSmall: foundationData.pictureSmall, <ide> listPrice: price, <ide> totalValue: totalRelease * price, <ide> candidateList: candidateList, <add> voteList: voteList, <ide> createdAt: basicCreatedAt <del> }, { <del> filter: false // 防止 _id 被 filter 掉 <del> })); <add> }); <add> companySchema.validate(newCompanyData); <add> <add> companiesBulk.insert({ <add> _id: companyId, <add> ...newCompanyData <add> }); <ide> <ide> dbPrice.insert({ <ide> companyId: companyId,
Java
apache-2.0
fc1c1a3ee2088f232fce16aeec6e6a88db684254
0
lovepoem/dubbo,bpzhang/dubbo,lovepoem/dubbo,wuwen5/dubbo,fengyie007/dubbo,bpzhang/dubbo,bpzhang/dubbo,fengyie007/dubbo,wuwen5/dubbo,wuwen5/dubbo,fengyie007/dubbo,lovepoem/dubbo
/* * 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.dubbo.common; import org.apache.dubbo.common.utils.CollectionUtils; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.io.File; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.function.Predicate; import static org.hamcrest.CoreMatchers.anyOf; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.fail; public class URLTest { @Test public void test_valueOf_noProtocolAndHost() throws Exception { URL url = URL.valueOf("/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url); assertNull(url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertNull(url.getHost()); assertNull(url.getAddress()); assertEquals(0, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getParameter("version")); assertEquals("morgan", url.getParameter("application")); url = URL.valueOf("context/path?version=1.0.0&application=morgan"); // ^^^^^^^ Caution , parse as host assertURLStrDecoder(url); assertNull(url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertEquals("context", url.getHost()); assertEquals(0, url.getPort()); assertEquals("path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getParameter("version")); assertEquals("morgan", url.getParameter("application")); } private void assertURLStrDecoder(URL url) { String fullURLStr = url.toFullString(); URL newUrl = URLStrParser.parseEncodedStr(URL.encode(fullURLStr)); assertEquals(URL.valueOf(fullURLStr), newUrl); URL newUrl2 = URLStrParser.parseDecodedStr(fullURLStr); assertEquals(URL.valueOf(fullURLStr), newUrl2); } @Test public void test_valueOf_noProtocol() throws Exception { URL url = URL.valueOf("10.20.130.230"); assertURLStrDecoder(url); assertNull(url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230", url.getAddress()); assertEquals(0, url.getPort()); assertNull(url.getPath()); assertEquals(0, url.getParameters().size()); url = URL.valueOf("10.20.130.230:20880"); assertURLStrDecoder(url); assertNull(url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertNull(url.getPath()); assertEquals(0, url.getParameters().size()); url = URL.valueOf("10.20.130.230/context/path"); assertURLStrDecoder(url); assertNull(url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230", url.getAddress()); assertEquals(0, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(0, url.getParameters().size()); url = URL.valueOf("10.20.130.230:20880/context/path"); assertURLStrDecoder(url); assertNull(url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(0, url.getParameters().size()); url = URL.valueOf("admin:[email protected]:20880/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url); assertNull(url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getParameter("version")); assertEquals("morgan", url.getParameter("application")); } @Test public void test_valueOf_noHost() throws Exception { URL url = URL.valueOf("file:///home/user1/router.js"); assertURLStrDecoder(url); assertEquals("file", url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertNull(url.getHost()); assertNull(url.getAddress()); assertEquals(0, url.getPort()); assertEquals("home/user1/router.js", url.getPath()); assertEquals(0, url.getParameters().size()); // Caution!! url = URL.valueOf("file://home/user1/router.js"); // ^^ only tow slash! assertURLStrDecoder(url); assertEquals("file", url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertEquals("home", url.getHost()); assertEquals(0, url.getPort()); assertEquals("user1/router.js", url.getPath()); assertEquals(0, url.getParameters().size()); url = URL.valueOf("file:/home/user1/router.js"); assertURLStrDecoder(url); assertEquals("file", url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertNull(url.getHost()); assertNull(url.getAddress()); assertEquals(0, url.getPort()); assertEquals("home/user1/router.js", url.getPath()); assertEquals(0, url.getParameters().size()); url = URL.valueOf("file:///d:/home/user1/router.js"); assertURLStrDecoder(url); assertEquals("file", url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertNull(url.getHost()); assertNull(url.getAddress()); assertEquals(0, url.getPort()); assertEquals("d:/home/user1/router.js", url.getPath()); assertEquals(0, url.getParameters().size()); url = URL.valueOf("file:///home/user1/router.js?p1=v1&p2=v2"); assertURLStrDecoder(url); assertEquals("file", url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertNull(url.getHost()); assertNull(url.getAddress()); assertEquals(0, url.getPort()); assertEquals("home/user1/router.js", url.getPath()); assertEquals(2, url.getParameters().size()); Map<String, String> params = new HashMap<String, String>(); params.put("p1", "v1"); params.put("p2", "v2"); assertEquals(params, url.getParameters()); url = URL.valueOf("file:/home/user1/router.js?p1=v1&p2=v2"); assertURLStrDecoder(url); assertEquals("file", url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertNull(url.getHost()); assertNull(url.getAddress()); assertEquals(0, url.getPort()); assertEquals("home/user1/router.js", url.getPath()); assertEquals(2, url.getParameters().size()); params = new HashMap<String, String>(); params.put("p1", "v1"); params.put("p2", "v2"); assertEquals(params, url.getParameters()); } @Test public void test_valueOf_WithProtocolHost() throws Exception { URL url = URL.valueOf("dubbo://10.20.130.230"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230", url.getAddress()); assertEquals(0, url.getPort()); assertNull(url.getPath()); assertEquals(0, url.getParameters().size()); url = URL.valueOf("dubbo://10.20.130.230:20880/context/path"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(0, url.getParameters().size()); url = URL.valueOf("dubbo://admin:[email protected]:20880"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertNull(url.getPath()); assertEquals(0, url.getParameters().size()); url = URL.valueOf("dubbo://admin:[email protected]:20880?version=1.0.0"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertNull(url.getPath()); assertEquals(1, url.getParameters().size()); assertEquals("1.0.0", url.getParameter("version")); url = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getParameter("version")); assertEquals("morgan", url.getParameter("application")); url = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?version=1.0.0&application=morgan&noValue"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(3, url.getParameters().size()); assertEquals("1.0.0", url.getParameter("version")); assertEquals("morgan", url.getParameter("application")); assertEquals("noValue", url.getParameter("noValue")); } // TODO Do not want to use spaces? See: DUBBO-502, URL class handles special conventions for special characters. @Test public void test_valueOf_spaceSafe() throws Exception { URL url = URL.valueOf("http://1.2.3.4:8080/path?key=value1 value2"); assertURLStrDecoder(url); assertEquals("http://1.2.3.4:8080/path?key=value1 value2", url.toString()); assertEquals("value1 value2", url.getParameter("key")); } @Test public void test_noValueKey() throws Exception { URL url = URL.valueOf("http://1.2.3.4:8080/path?k0&k1=v1"); assertURLStrDecoder(url); assertTrue(url.hasParameter("k0")); // If a Key has no corresponding Value, then the Key also used as the Value. assertEquals("k0", url.getParameter("k0")); } @Test public void test_valueOf_Exception_noProtocol() throws Exception { try { URL.valueOf("://1.2.3.4:8080/path"); fail(); } catch (IllegalStateException expected) { assertEquals("url missing protocol: \"://1.2.3.4:8080/path\"", expected.getMessage()); } try { String encodedURLStr = URL.encode("://1.2.3.4:8080/path"); URLStrParser.parseEncodedStr(encodedURLStr); fail(); } catch (IllegalStateException expected) { assertEquals("url missing protocol: \"://1.2.3.4:8080/path\"", URL.decode(expected.getMessage())); } try { URLStrParser.parseDecodedStr("://1.2.3.4:8080/path"); fail(); } catch (IllegalStateException expected) { assertEquals("url missing protocol: \"://1.2.3.4:8080/path\"", expected.getMessage()); } } @Test public void test_getAddress() throws Exception { URL url1 = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url1); assertEquals("10.20.130.230:20880", url1.getAddress()); } @Test public void test_getAbsolutePath() throws Exception { URL url = new URL("p1", "1.2.2.2", 33); assertURLStrDecoder(url); assertNull(url.getAbsolutePath()); url = new URL("file", null, 90, "/home/user1/route.js"); assertURLStrDecoder(url); assertEquals("/home/user1/route.js", url.getAbsolutePath()); } @Test public void test_equals() throws Exception { URL url1 = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url1); Map<String, String> params = new HashMap<String, String>(); params.put("version", "1.0.0"); params.put("application", "morgan"); URL url2 = new URL("dubbo", "admin", "hello1234", "10.20.130.230", 20880, "context/path", params); assertURLStrDecoder(url2); assertEquals(url1, url2); } @Test public void test_toString() throws Exception { URL url1 = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url1); assertThat(url1.toString(), anyOf( equalTo("dubbo://10.20.130.230:20880/context/path?version=1.0.0&application=morgan"), equalTo("dubbo://10.20.130.230:20880/context/path?application=morgan&version=1.0.0")) ); } @Test public void test_toFullString() throws Exception { URL url1 = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url1); assertThat(url1.toFullString(), anyOf( equalTo("dubbo://admin:[email protected]:20880/context/path?version=1.0.0&application=morgan"), equalTo("dubbo://admin:[email protected]:20880/context/path?application=morgan&version=1.0.0")) ); } @Test public void test_set_methods() throws Exception { URL url = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url); url = url.setHost("host"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("host", url.getHost()); assertEquals("host:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getParameter("version")); assertEquals("morgan", url.getParameter("application")); url = url.setPort(1); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("host", url.getHost()); assertEquals("host:1", url.getAddress()); assertEquals(1, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getParameter("version")); assertEquals("morgan", url.getParameter("application")); url = url.setPath("path"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("host", url.getHost()); assertEquals("host:1", url.getAddress()); assertEquals(1, url.getPort()); assertEquals("path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getParameter("version")); assertEquals("morgan", url.getParameter("application")); url = url.setProtocol("protocol"); assertURLStrDecoder(url); assertEquals("protocol", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("host", url.getHost()); assertEquals("host:1", url.getAddress()); assertEquals(1, url.getPort()); assertEquals("path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getParameter("version")); assertEquals("morgan", url.getParameter("application")); url = url.setUsername("username"); assertURLStrDecoder(url); assertEquals("protocol", url.getProtocol()); assertEquals("username", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("host", url.getHost()); assertEquals("host:1", url.getAddress()); assertEquals(1, url.getPort()); assertEquals("path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getParameter("version")); assertEquals("morgan", url.getParameter("application")); url = url.setPassword("password"); assertURLStrDecoder(url); assertEquals("protocol", url.getProtocol()); assertEquals("username", url.getUsername()); assertEquals("password", url.getPassword()); assertEquals("host", url.getHost()); assertEquals("host:1", url.getAddress()); assertEquals(1, url.getPort()); assertEquals("path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getParameter("version")); assertEquals("morgan", url.getParameter("application")); } @Test public void test_removeParameters() throws Exception { URL url = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?version=1.0.0&application=morgan&k1=v1&k2=v2"); assertURLStrDecoder(url); url = url.removeParameter("version"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(3, url.getParameters().size()); assertEquals("morgan", url.getParameter("application")); assertEquals("v1", url.getParameter("k1")); assertEquals("v2", url.getParameter("k2")); assertNull(url.getParameter("version")); url = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?version=1.0.0&application=morgan&k1=v1&k2=v2"); url = url.removeParameters("version", "application", "NotExistedKey"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("v1", url.getParameter("k1")); assertEquals("v2", url.getParameter("k2")); assertNull(url.getParameter("version")); assertNull(url.getParameter("application")); url = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?version=1.0.0&application=morgan&k1=v1&k2=v2"); url = url.removeParameters(Arrays.asList("version", "application")); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("v1", url.getParameter("k1")); assertEquals("v2", url.getParameter("k2")); assertNull(url.getParameter("version")); assertNull(url.getParameter("application")); } @Test public void test_addParameter() throws Exception { URL url = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?application=morgan"); url = url.addParameter("k1", "v1"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("morgan", url.getParameter("application")); assertEquals("v1", url.getParameter("k1")); } @Test public void test_addParameter_sameKv() throws Exception { URL url = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?application=morgan&k1=v1"); URL newUrl = url.addParameter("k1", "v1"); assertURLStrDecoder(url); assertSame(newUrl, url); } @Test public void test_addParameters() throws Exception { URL url = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?application=morgan"); url = url.addParameters(CollectionUtils.toStringMap("k1", "v1", "k2", "v2")); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(3, url.getParameters().size()); assertEquals("morgan", url.getParameter("application")); assertEquals("v1", url.getParameter("k1")); assertEquals("v2", url.getParameter("k2")); url = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?application=morgan"); url = url.addParameters("k1", "v1", "k2", "v2", "application", "xxx"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(3, url.getParameters().size()); assertEquals("xxx", url.getParameter("application")); assertEquals("v1", url.getParameter("k1")); assertEquals("v2", url.getParameter("k2")); url = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?application=morgan"); url = url.addParametersIfAbsent(CollectionUtils.toStringMap("k1", "v1", "k2", "v2", "application", "xxx")); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(3, url.getParameters().size()); assertEquals("morgan", url.getParameter("application")); assertEquals("v1", url.getParameter("k1")); assertEquals("v2", url.getParameter("k2")); url = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?application=morgan"); url = url.addParameter("k1", "v1"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("morgan", url.getParameter("application")); assertEquals("v1", url.getParameter("k1")); url = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?application=morgan"); url = url.addParameter("application", "xxx"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(1, url.getParameters().size()); assertEquals("xxx", url.getParameter("application")); } @Test public void test_addParameters_SameKv() throws Exception { { URL url = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?application=morgan&k1=v1"); URL newUrl = url.addParameters(CollectionUtils.toStringMap("k1", "v1")); assertURLStrDecoder(url); assertSame(url, newUrl); } { URL url = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?application=morgan&k1=v1&k2=v2"); URL newUrl = url.addParameters(CollectionUtils.toStringMap("k1", "v1", "k2", "v2")); assertURLStrDecoder(url); assertSame(newUrl, url); } } @Test public void test_addParameterIfAbsent() throws Exception { URL url = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?application=morgan"); url = url.addParameterIfAbsent("application", "xxx"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(1, url.getParameters().size()); assertEquals("morgan", url.getParameter("application")); } @Test public void test_windowAbsolutePathBeginWithSlashIsValid() throws Exception { final String osProperty = System.getProperties().getProperty("os.name"); if (!osProperty.toLowerCase().contains("windows")) { return; } System.out.println("Test Windows valid path string."); File f0 = new File("C:/Windows"); File f1 = new File("/C:/Windows"); File f2 = new File("C:\\Windows"); File f3 = new File("/C:\\Windows"); File f4 = new File("\\C:\\Windows"); assertEquals(f0, f1); assertEquals(f0, f2); assertEquals(f0, f3); assertEquals(f0, f4); } @Test public void test_javaNetUrl() throws Exception { java.net.URL url = new java.net.URL("http://admin:[email protected]:20880/context/path?version=1.0.0&application=morgan#anchor1"); assertEquals("http", url.getProtocol()); assertEquals("admin:hello1234", url.getUserInfo()); assertEquals("10.20.130.230", url.getHost()); assertEquals(20880, url.getPort()); assertEquals("/context/path", url.getPath()); assertEquals("version=1.0.0&application=morgan", url.getQuery()); assertEquals("anchor1", url.getRef()); assertEquals("admin:[email protected]:20880", url.getAuthority()); assertEquals("/context/path?version=1.0.0&application=morgan", url.getFile()); } @Test public void test_Anyhost() throws Exception { URL url = URL.valueOf("dubbo://0.0.0.0:20880"); assertURLStrDecoder(url); assertEquals("0.0.0.0", url.getHost()); assertTrue(url.isAnyHost()); } @Test public void test_Localhost() throws Exception { URL url = URL.valueOf("dubbo://127.0.0.1:20880"); assertURLStrDecoder(url); assertEquals("127.0.0.1", url.getHost()); assertEquals("127.0.0.1:20880", url.getAddress()); assertTrue(url.isLocalHost()); url = URL.valueOf("dubbo://127.0.1.1:20880"); assertURLStrDecoder(url); assertEquals("127.0.1.1", url.getHost()); assertEquals("127.0.1.1:20880", url.getAddress()); assertTrue(url.isLocalHost()); url = URL.valueOf("dubbo://localhost:20880"); assertURLStrDecoder(url); assertEquals("localhost", url.getHost()); assertEquals("localhost:20880", url.getAddress()); assertTrue(url.isLocalHost()); } @Test public void test_Path() throws Exception { URL url = new URL("dubbo", "localhost", 20880, "////path"); assertURLStrDecoder(url); assertEquals("path", url.getPath()); } @Test public void testAddParameters() throws Exception { URL url = URL.valueOf("dubbo://127.0.0.1:20880"); assertURLStrDecoder(url); Map<String, String> parameters = new HashMap<String, String>(); parameters.put("version", null); url.addParameters(parameters); assertURLStrDecoder(url); } @Test public void testUserNamePasswordContainsAt() { // Test username or password contains "@" URL url = URL.valueOf("ad@min:hello@[email protected]:20880/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url); assertNull(url.getProtocol()); assertEquals("ad@min", url.getUsername()); assertEquals("hello@1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getParameter("version")); assertEquals("morgan", url.getParameter("application")); } @Test public void testIpV6Address() { // Test username or password contains "@" URL url = URL.valueOf( "ad@min111:haha@1234@2001:0db8:85a3:08d3:1319:8a2e:0370:7344:20880/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url); assertNull(url.getProtocol()); assertEquals("ad@min111", url.getUsername()); assertEquals("haha@1234", url.getPassword()); assertEquals("2001:0db8:85a3:08d3:1319:8a2e:0370:7344", url.getHost()); assertEquals("2001:0db8:85a3:08d3:1319:8a2e:0370:7344:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getParameter("version")); assertEquals("morgan", url.getParameter("application")); } @Test public void testIpV6AddressWithScopeId() { URL url = URL.valueOf("2001:0db8:85a3:08d3:1319:8a2e:0370:7344%5/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url); assertNull(url.getProtocol()); assertEquals("2001:0db8:85a3:08d3:1319:8a2e:0370:7344%5", url.getHost()); assertEquals("2001:0db8:85a3:08d3:1319:8a2e:0370:7344%5", url.getAddress()); assertEquals(0, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getParameter("version")); assertEquals("morgan", url.getParameter("application")); } @Test public void testDefaultPort() { Assertions.assertEquals("10.20.153.10:2181", URL.appendDefaultPort("10.20.153.10:0", 2181)); Assertions.assertEquals("10.20.153.10:2181", URL.appendDefaultPort("10.20.153.10", 2181)); } @Test public void testGetServiceKey() { URL url1 = URL.valueOf("10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName"); assertURLStrDecoder(url1); Assertions.assertEquals("org.apache.dubbo.test.interfaceName", url1.getServiceKey()); URL url2 = URL.valueOf("10.20.130.230:20880/org.apache.dubbo.test.interfaceName?interface=org.apache.dubbo.test.interfaceName"); assertURLStrDecoder(url2); Assertions.assertEquals("org.apache.dubbo.test.interfaceName", url2.getServiceKey()); URL url3 = URL.valueOf( "10.20.130.230:20880/org.apache.dubbo.test.interfaceName?interface=org.apache.dubbo.test.interfaceName&group=group1&version=1.0.0"); assertURLStrDecoder(url3); Assertions.assertEquals("group1/org.apache.dubbo.test.interfaceName:1.0.0", url3.getServiceKey()); URL url4 = URL.valueOf("10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName"); assertURLStrDecoder(url4); Assertions.assertEquals("context/path", url4.getPathKey()); URL url5 = URL.valueOf("10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&group=group1&version=1.0.0"); assertURLStrDecoder(url5); Assertions.assertEquals("group1/context/path:1.0.0", url5.getPathKey()); } @Test public void testGetColonSeparatedKey() { URL url1 = URL.valueOf("10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&group=group&version=1.0.0"); assertURLStrDecoder(url1); Assertions.assertEquals("org.apache.dubbo.test.interfaceName:1.0.0:group", url1.getColonSeparatedKey()); URL url2 = URL.valueOf("10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&version=1.0.0"); assertURLStrDecoder(url2); Assertions.assertEquals("org.apache.dubbo.test.interfaceName:1.0.0:", url2.getColonSeparatedKey()); URL url3 = URL.valueOf("10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&group=group"); assertURLStrDecoder(url3); Assertions.assertEquals("org.apache.dubbo.test.interfaceName::group", url3.getColonSeparatedKey()); URL url4 = URL.valueOf("10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName"); assertURLStrDecoder(url4); Assertions.assertEquals("org.apache.dubbo.test.interfaceName::", url4.getColonSeparatedKey()); URL url5 = URL.valueOf("10.20.130.230:20880/org.apache.dubbo.test.interfaceName"); assertURLStrDecoder(url5); Assertions.assertEquals("org.apache.dubbo.test.interfaceName::", url5.getColonSeparatedKey()); URL url6 = URL.valueOf("10.20.130.230:20880/org.apache.dubbo.test.interfaceName?interface=org.apache.dubbo.test.interfaceName1"); assertURLStrDecoder(url6); Assertions.assertEquals("org.apache.dubbo.test.interfaceName1::", url6.getColonSeparatedKey()); } @Test public void testValueOf() { URL url = URL.valueOf("10.20.130.230"); assertURLStrDecoder(url); url = URL.valueOf("10.20.130.230:20880"); assertURLStrDecoder(url); url = URL.valueOf("dubbo://10.20.130.230:20880"); assertURLStrDecoder(url); url = URL.valueOf("dubbo://10.20.130.230:20880/path"); assertURLStrDecoder(url); } /** * Test {@link URL#getParameters(Predicate)} method * * @since 2.7.8 */ @Test public void testGetParameters() { URL url = URL.valueOf("10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&group=group&version=1.0.0"); Map<String, String> parameters = url.getParameters(i -> "version".equals(i)); String version = parameters.get("version"); assertEquals(1, parameters.size()); assertEquals("1.0.0", version); } @Test public void testGetParameter() { URL url = URL.valueOf("http://127.0.0.1:8080/path?i=1&b=false"); assertEquals(Integer.valueOf(1), url.getParameter("i", Integer.class)); assertEquals(Boolean.FALSE, url.getParameter("b", Boolean.class)); } @Test public void testEquals() { URL url1 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + "dubbo-demo-api-consumer&category=consumers&check=false&dubbo=2.0.2&generic=true&interface=" + "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false&timestamp=1599556506417"); URL url2 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + "dubbo-demo-api-consumer&category=consumers&check=false&dubbo=2.0.2&generic=true&interface=" + "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false&timestamp=2299556506417"); assertEquals(url1, url2); URL url3 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + "dubbo-demo-api-consumer&category=consumers&check=false&dubbo=2.0.2&interface=" + "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false&timestamp=2299556506417"); assertNotEquals(url2, url3); URL url4 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + "dubbo-demo-api-consumer&category=consumers&check=true&dubbo=2.0.2&interface=" + "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false&timestamp=2299556506417"); assertNotEquals(url3, url4); } @Test public void testHashcode() { URL url1 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + "dubbo-demo-api-consumer&category=consumers&check=false&dubbo=2.0.2&generic=true&interface=" + "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false&timestamp=1599556506417"); URL url2 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + "dubbo-demo-api-consumer&category=consumers&check=false&dubbo=2.0.2&generic=true&interface=" + "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false&timestamp=2299556506417"); assertEquals(url1.hashCode(), url2.hashCode()); URL url3 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + "dubbo-demo-api-consumer&category=consumers&check=false&dubbo=2.0.2&interface=" + "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false&timestamp=2299556506417"); assertNotEquals(url2.hashCode(), url3.hashCode()); URL url4 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + "dubbo-demo-api-consumer&category=consumers&check=true&dubbo=2.0.2&interface=" + "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false&timestamp=2299556506417"); assertNotEquals(url3.hashCode(), url4.hashCode()); } @Test public void testEqualsWithPassword() { URL url1 = URL.valueOf("ad@min:hello@[email protected]:20880/context/path?version=1.0.0&application=morgan"); URL url2 = URL.valueOf("ad@min:hello@[email protected]:20880/context/path?version=1.0.0&application=morgan"); URL url3 = URL.valueOf("ad@min:hello@[email protected]:20880/context/path?version=1.0.0&application=morgan"); boolean actual1 = url1.equals(url2); boolean actual2 = url1.equals(url3); assertFalse(actual1); assertTrue(actual2); } @Test public void testEqualsWithPath() { URL url1 = URL.valueOf("ad@min:hello@[email protected]:20880/context/path1?version=1.0.0&application=morgan"); URL url2 = URL.valueOf("ad@min:hello@[email protected]:20880/context/path2?version=1.0.0&application=morgan"); URL url3 = URL.valueOf("ad@min:hello@[email protected]:20880/context/path1?version=1.0.0&application=morgan"); boolean actual1 = url1.equals(url2); boolean actual2 = url1.equals(url3); assertFalse(actual1); assertTrue(actual2); } @Test public void testEqualsWithPort() { URL url1 = URL.valueOf("ad@min:hello@[email protected]:20880/context/path?version=1.0.0&application=morgan"); URL url2 = URL.valueOf("ad@min:hello@[email protected]:20881/context/path?version=1.0.0&application=morgan"); URL url3 = URL.valueOf("ad@min:hello@[email protected]:20880/context/path?version=1.0.0&application=morgan"); boolean actual1 = url1.equals(url2); boolean actual2 = url1.equals(url3); assertFalse(actual1); assertTrue(actual2); } @Test public void testEqualsWithProtocol() { URL url1 = URL.valueOf("dubbo://ad@min:hello@[email protected]:20880/context/path?version=1.0.0&application=morgan"); URL url2 = URL.valueOf("file://ad@min:hello@[email protected]:20880/context/path?version=1.0.0&application=morgan"); URL url3 = URL.valueOf("dubbo://ad@min:hello@[email protected]:20880/context/path?version=1.0.0&application=morgan"); boolean actual1 = url1.equals(url2); boolean actual2 = url1.equals(url3); assertFalse(actual1); assertTrue(actual2); } @Test public void testEqualsWithUser() { URL url1 = URL.valueOf("ad@min1:hello@[email protected]:20880/context/path?version=1.0.0&application=morgan"); URL url2 = URL.valueOf("ad@min2:hello@[email protected]:20880/context/path?version=1.0.0&application=morgan"); URL url3 = URL.valueOf("ad@min1:hello@[email protected]:20880/context/path?version=1.0.0&application=morgan"); boolean actual1 = url1.equals(url2); boolean actual2 = url1.equals(url3); assertFalse(actual1); assertTrue(actual2); } @Test public void testParameterContainPound() { URL url = URL.valueOf( "dubbo://ad@min:hello@[email protected]:20880/context/path?version=1.0.0&application=morgan&pound=abcd#efg&protocol=registry"); Assertions.assertEquals("abcd#efg", url.getParameter("pound")); Assertions.assertEquals("registry", url.getParameter("protocol")); } }
dubbo-common/src/test/java/org/apache/dubbo/common/URLTest.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.dubbo.common; import org.apache.dubbo.common.utils.CollectionUtils; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.io.File; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.function.Predicate; import static org.hamcrest.CoreMatchers.anyOf; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.fail; public class URLTest { @Test public void test_valueOf_noProtocolAndHost() throws Exception { URL url = URL.valueOf("/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url); assertNull(url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertNull(url.getHost()); assertNull(url.getAddress()); assertEquals(0, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getParameter("version")); assertEquals("morgan", url.getParameter("application")); url = URL.valueOf("context/path?version=1.0.0&application=morgan"); // ^^^^^^^ Caution , parse as host assertURLStrDecoder(url); assertNull(url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertEquals("context", url.getHost()); assertEquals(0, url.getPort()); assertEquals("path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getParameter("version")); assertEquals("morgan", url.getParameter("application")); } private void assertURLStrDecoder(URL url) { String fullURLStr = url.toFullString(); URL newUrl = URLStrParser.parseEncodedStr(URL.encode(fullURLStr)); assertEquals(URL.valueOf(fullURLStr), newUrl); URL newUrl2 = URLStrParser.parseDecodedStr(fullURLStr); assertEquals(URL.valueOf(fullURLStr), newUrl2); } @Test public void test_valueOf_noProtocol() throws Exception { URL url = URL.valueOf("10.20.130.230"); assertURLStrDecoder(url); assertNull(url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230", url.getAddress()); assertEquals(0, url.getPort()); assertNull(url.getPath()); assertEquals(0, url.getParameters().size()); url = URL.valueOf("10.20.130.230:20880"); assertURLStrDecoder(url); assertNull(url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertNull(url.getPath()); assertEquals(0, url.getParameters().size()); url = URL.valueOf("10.20.130.230/context/path"); assertURLStrDecoder(url); assertNull(url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230", url.getAddress()); assertEquals(0, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(0, url.getParameters().size()); url = URL.valueOf("10.20.130.230:20880/context/path"); assertURLStrDecoder(url); assertNull(url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(0, url.getParameters().size()); url = URL.valueOf("admin:[email protected]:20880/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url); assertNull(url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getParameter("version")); assertEquals("morgan", url.getParameter("application")); } @Test public void test_valueOf_noHost() throws Exception { URL url = URL.valueOf("file:///home/user1/router.js"); assertURLStrDecoder(url); assertEquals("file", url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertNull(url.getHost()); assertNull(url.getAddress()); assertEquals(0, url.getPort()); assertEquals("home/user1/router.js", url.getPath()); assertEquals(0, url.getParameters().size()); // Caution!! url = URL.valueOf("file://home/user1/router.js"); // ^^ only tow slash! assertURLStrDecoder(url); assertEquals("file", url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertEquals("home", url.getHost()); assertEquals(0, url.getPort()); assertEquals("user1/router.js", url.getPath()); assertEquals(0, url.getParameters().size()); url = URL.valueOf("file:/home/user1/router.js"); assertURLStrDecoder(url); assertEquals("file", url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertNull(url.getHost()); assertNull(url.getAddress()); assertEquals(0, url.getPort()); assertEquals("home/user1/router.js", url.getPath()); assertEquals(0, url.getParameters().size()); url = URL.valueOf("file:///d:/home/user1/router.js"); assertURLStrDecoder(url); assertEquals("file", url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertNull(url.getHost()); assertNull(url.getAddress()); assertEquals(0, url.getPort()); assertEquals("d:/home/user1/router.js", url.getPath()); assertEquals(0, url.getParameters().size()); url = URL.valueOf("file:///home/user1/router.js?p1=v1&p2=v2"); assertURLStrDecoder(url); assertEquals("file", url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertNull(url.getHost()); assertNull(url.getAddress()); assertEquals(0, url.getPort()); assertEquals("home/user1/router.js", url.getPath()); assertEquals(2, url.getParameters().size()); Map<String, String> params = new HashMap<String, String>(); params.put("p1", "v1"); params.put("p2", "v2"); assertEquals(params, url.getParameters()); url = URL.valueOf("file:/home/user1/router.js?p1=v1&p2=v2"); assertURLStrDecoder(url); assertEquals("file", url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertNull(url.getHost()); assertNull(url.getAddress()); assertEquals(0, url.getPort()); assertEquals("home/user1/router.js", url.getPath()); assertEquals(2, url.getParameters().size()); params = new HashMap<String, String>(); params.put("p1", "v1"); params.put("p2", "v2"); assertEquals(params, url.getParameters()); } @Test public void test_valueOf_WithProtocolHost() throws Exception { URL url = URL.valueOf("dubbo://10.20.130.230"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230", url.getAddress()); assertEquals(0, url.getPort()); assertNull(url.getPath()); assertEquals(0, url.getParameters().size()); url = URL.valueOf("dubbo://10.20.130.230:20880/context/path"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertNull(url.getUsername()); assertNull(url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(0, url.getParameters().size()); url = URL.valueOf("dubbo://admin:[email protected]:20880"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertNull(url.getPath()); assertEquals(0, url.getParameters().size()); url = URL.valueOf("dubbo://admin:[email protected]:20880?version=1.0.0"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertNull(url.getPath()); assertEquals(1, url.getParameters().size()); assertEquals("1.0.0", url.getParameter("version")); url = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getParameter("version")); assertEquals("morgan", url.getParameter("application")); url = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?version=1.0.0&application=morgan&noValue"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(3, url.getParameters().size()); assertEquals("1.0.0", url.getParameter("version")); assertEquals("morgan", url.getParameter("application")); assertEquals("noValue", url.getParameter("noValue")); } // TODO Do not want to use spaces? See: DUBBO-502, URL class handles special conventions for special characters. @Test public void test_valueOf_spaceSafe() throws Exception { URL url = URL.valueOf("http://1.2.3.4:8080/path?key=value1 value2"); assertURLStrDecoder(url); assertEquals("http://1.2.3.4:8080/path?key=value1 value2", url.toString()); assertEquals("value1 value2", url.getParameter("key")); } @Test public void test_noValueKey() throws Exception { URL url = URL.valueOf("http://1.2.3.4:8080/path?k0&k1=v1"); assertURLStrDecoder(url); assertTrue(url.hasParameter("k0")); // If a Key has no corresponding Value, then the Key also used as the Value. assertEquals("k0", url.getParameter("k0")); } @Test public void test_valueOf_Exception_noProtocol() throws Exception { try { URL.valueOf("://1.2.3.4:8080/path"); fail(); } catch (IllegalStateException expected) { assertEquals("url missing protocol: \"://1.2.3.4:8080/path\"", expected.getMessage()); } try { String encodedURLStr = URL.encode("://1.2.3.4:8080/path"); URLStrParser.parseEncodedStr(encodedURLStr); fail(); } catch (IllegalStateException expected) { assertEquals("url missing protocol: \"://1.2.3.4:8080/path\"", URL.decode(expected.getMessage())); } try { URLStrParser.parseDecodedStr("://1.2.3.4:8080/path"); fail(); } catch (IllegalStateException expected) { assertEquals("url missing protocol: \"://1.2.3.4:8080/path\"", expected.getMessage()); } } @Test public void test_getAddress() throws Exception { URL url1 = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url1); assertEquals("10.20.130.230:20880", url1.getAddress()); } @Test public void test_getAbsolutePath() throws Exception { URL url = new URL("p1", "1.2.2.2", 33); assertURLStrDecoder(url); assertNull(url.getAbsolutePath()); url = new URL("file", null, 90, "/home/user1/route.js"); assertURLStrDecoder(url); assertEquals("/home/user1/route.js", url.getAbsolutePath()); } @Test public void test_equals() throws Exception { URL url1 = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url1); Map<String, String> params = new HashMap<String, String>(); params.put("version", "1.0.0"); params.put("application", "morgan"); URL url2 = new URL("dubbo", "admin", "hello1234", "10.20.130.230", 20880, "context/path", params); assertURLStrDecoder(url2); assertEquals(url1, url2); } @Test public void test_toString() throws Exception { URL url1 = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url1); assertThat(url1.toString(), anyOf( equalTo("dubbo://10.20.130.230:20880/context/path?version=1.0.0&application=morgan"), equalTo("dubbo://10.20.130.230:20880/context/path?application=morgan&version=1.0.0")) ); } @Test public void test_toFullString() throws Exception { URL url1 = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url1); assertThat(url1.toFullString(), anyOf( equalTo("dubbo://admin:[email protected]:20880/context/path?version=1.0.0&application=morgan"), equalTo("dubbo://admin:[email protected]:20880/context/path?application=morgan&version=1.0.0")) ); } @Test public void test_set_methods() throws Exception { URL url = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url); url = url.setHost("host"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("host", url.getHost()); assertEquals("host:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getParameter("version")); assertEquals("morgan", url.getParameter("application")); url = url.setPort(1); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("host", url.getHost()); assertEquals("host:1", url.getAddress()); assertEquals(1, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getParameter("version")); assertEquals("morgan", url.getParameter("application")); url = url.setPath("path"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("host", url.getHost()); assertEquals("host:1", url.getAddress()); assertEquals(1, url.getPort()); assertEquals("path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getParameter("version")); assertEquals("morgan", url.getParameter("application")); url = url.setProtocol("protocol"); assertURLStrDecoder(url); assertEquals("protocol", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("host", url.getHost()); assertEquals("host:1", url.getAddress()); assertEquals(1, url.getPort()); assertEquals("path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getParameter("version")); assertEquals("morgan", url.getParameter("application")); url = url.setUsername("username"); assertURLStrDecoder(url); assertEquals("protocol", url.getProtocol()); assertEquals("username", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("host", url.getHost()); assertEquals("host:1", url.getAddress()); assertEquals(1, url.getPort()); assertEquals("path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getParameter("version")); assertEquals("morgan", url.getParameter("application")); url = url.setPassword("password"); assertURLStrDecoder(url); assertEquals("protocol", url.getProtocol()); assertEquals("username", url.getUsername()); assertEquals("password", url.getPassword()); assertEquals("host", url.getHost()); assertEquals("host:1", url.getAddress()); assertEquals(1, url.getPort()); assertEquals("path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getParameter("version")); assertEquals("morgan", url.getParameter("application")); } @Test public void test_removeParameters() throws Exception { URL url = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?version=1.0.0&application=morgan&k1=v1&k2=v2"); assertURLStrDecoder(url); url = url.removeParameter("version"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(3, url.getParameters().size()); assertEquals("morgan", url.getParameter("application")); assertEquals("v1", url.getParameter("k1")); assertEquals("v2", url.getParameter("k2")); assertNull(url.getParameter("version")); url = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?version=1.0.0&application=morgan&k1=v1&k2=v2"); url = url.removeParameters("version", "application", "NotExistedKey"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("v1", url.getParameter("k1")); assertEquals("v2", url.getParameter("k2")); assertNull(url.getParameter("version")); assertNull(url.getParameter("application")); url = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?version=1.0.0&application=morgan&k1=v1&k2=v2"); url = url.removeParameters(Arrays.asList("version", "application")); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("v1", url.getParameter("k1")); assertEquals("v2", url.getParameter("k2")); assertNull(url.getParameter("version")); assertNull(url.getParameter("application")); } @Test public void test_addParameter() throws Exception { URL url = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?application=morgan"); url = url.addParameter("k1", "v1"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("morgan", url.getParameter("application")); assertEquals("v1", url.getParameter("k1")); } @Test public void test_addParameter_sameKv() throws Exception { URL url = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?application=morgan&k1=v1"); URL newUrl = url.addParameter("k1", "v1"); assertURLStrDecoder(url); assertSame(newUrl, url); } @Test public void test_addParameters() throws Exception { URL url = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?application=morgan"); url = url.addParameters(CollectionUtils.toStringMap("k1", "v1", "k2", "v2")); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(3, url.getParameters().size()); assertEquals("morgan", url.getParameter("application")); assertEquals("v1", url.getParameter("k1")); assertEquals("v2", url.getParameter("k2")); url = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?application=morgan"); url = url.addParameters("k1", "v1", "k2", "v2", "application", "xxx"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(3, url.getParameters().size()); assertEquals("xxx", url.getParameter("application")); assertEquals("v1", url.getParameter("k1")); assertEquals("v2", url.getParameter("k2")); url = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?application=morgan"); url = url.addParametersIfAbsent(CollectionUtils.toStringMap("k1", "v1", "k2", "v2", "application", "xxx")); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(3, url.getParameters().size()); assertEquals("morgan", url.getParameter("application")); assertEquals("v1", url.getParameter("k1")); assertEquals("v2", url.getParameter("k2")); url = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?application=morgan"); url = url.addParameter("k1", "v1"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("morgan", url.getParameter("application")); assertEquals("v1", url.getParameter("k1")); url = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?application=morgan"); url = url.addParameter("application", "xxx"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(1, url.getParameters().size()); assertEquals("xxx", url.getParameter("application")); } @Test public void test_addParameters_SameKv() throws Exception { { URL url = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?application=morgan&k1=v1"); URL newUrl = url.addParameters(CollectionUtils.toStringMap("k1", "v1")); assertURLStrDecoder(url); assertSame(url, newUrl); } { URL url = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?application=morgan&k1=v1&k2=v2"); URL newUrl = url.addParameters(CollectionUtils.toStringMap("k1", "v1", "k2", "v2")); assertURLStrDecoder(url); assertSame(newUrl, url); } } @Test public void test_addParameterIfAbsent() throws Exception { URL url = URL.valueOf("dubbo://admin:[email protected]:20880/context/path?application=morgan"); url = url.addParameterIfAbsent("application", "xxx"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); assertEquals("hello1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(1, url.getParameters().size()); assertEquals("morgan", url.getParameter("application")); } @Test public void test_windowAbsolutePathBeginWithSlashIsValid() throws Exception { final String osProperty = System.getProperties().getProperty("os.name"); if (!osProperty.toLowerCase().contains("windows")) return; System.out.println("Test Windows valid path string."); File f0 = new File("C:/Windows"); File f1 = new File("/C:/Windows"); File f2 = new File("C:\\Windows"); File f3 = new File("/C:\\Windows"); File f4 = new File("\\C:\\Windows"); assertEquals(f0, f1); assertEquals(f0, f2); assertEquals(f0, f3); assertEquals(f0, f4); } @Test public void test_javaNetUrl() throws Exception { java.net.URL url = new java.net.URL("http://admin:[email protected]:20880/context/path?version=1.0.0&application=morgan#anchor1"); assertEquals("http", url.getProtocol()); assertEquals("admin:hello1234", url.getUserInfo()); assertEquals("10.20.130.230", url.getHost()); assertEquals(20880, url.getPort()); assertEquals("/context/path", url.getPath()); assertEquals("version=1.0.0&application=morgan", url.getQuery()); assertEquals("anchor1", url.getRef()); assertEquals("admin:[email protected]:20880", url.getAuthority()); assertEquals("/context/path?version=1.0.0&application=morgan", url.getFile()); } @Test public void test_Anyhost() throws Exception { URL url = URL.valueOf("dubbo://0.0.0.0:20880"); assertURLStrDecoder(url); assertEquals("0.0.0.0", url.getHost()); assertTrue(url.isAnyHost()); } @Test public void test_Localhost() throws Exception { URL url = URL.valueOf("dubbo://127.0.0.1:20880"); assertURLStrDecoder(url); assertEquals("127.0.0.1", url.getHost()); assertEquals("127.0.0.1:20880", url.getAddress()); assertTrue(url.isLocalHost()); url = URL.valueOf("dubbo://127.0.1.1:20880"); assertURLStrDecoder(url); assertEquals("127.0.1.1", url.getHost()); assertEquals("127.0.1.1:20880", url.getAddress()); assertTrue(url.isLocalHost()); url = URL.valueOf("dubbo://localhost:20880"); assertURLStrDecoder(url); assertEquals("localhost", url.getHost()); assertEquals("localhost:20880", url.getAddress()); assertTrue(url.isLocalHost()); } @Test public void test_Path() throws Exception { URL url = new URL("dubbo", "localhost", 20880, "////path"); assertURLStrDecoder(url); assertEquals("path", url.getPath()); } @Test public void testAddParameters() throws Exception { URL url = URL.valueOf("dubbo://127.0.0.1:20880"); assertURLStrDecoder(url); Map<String, String> parameters = new HashMap<String, String>(); parameters.put("version", null); url.addParameters(parameters); assertURLStrDecoder(url); } @Test public void testUserNamePasswordContainsAt() { // Test username or password contains "@" URL url = URL.valueOf("ad@min:hello@[email protected]:20880/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url); assertNull(url.getProtocol()); assertEquals("ad@min", url.getUsername()); assertEquals("hello@1234", url.getPassword()); assertEquals("10.20.130.230", url.getHost()); assertEquals("10.20.130.230:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getParameter("version")); assertEquals("morgan", url.getParameter("application")); } @Test public void testIpV6Address() { // Test username or password contains "@" URL url = URL.valueOf("ad@min111:haha@1234@2001:0db8:85a3:08d3:1319:8a2e:0370:7344:20880/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url); assertNull(url.getProtocol()); assertEquals("ad@min111", url.getUsername()); assertEquals("haha@1234", url.getPassword()); assertEquals("2001:0db8:85a3:08d3:1319:8a2e:0370:7344", url.getHost()); assertEquals("2001:0db8:85a3:08d3:1319:8a2e:0370:7344:20880", url.getAddress()); assertEquals(20880, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getParameter("version")); assertEquals("morgan", url.getParameter("application")); } @Test public void testIpV6AddressWithScopeId() { URL url = URL.valueOf("2001:0db8:85a3:08d3:1319:8a2e:0370:7344%5/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url); assertNull(url.getProtocol()); assertEquals("2001:0db8:85a3:08d3:1319:8a2e:0370:7344%5", url.getHost()); assertEquals("2001:0db8:85a3:08d3:1319:8a2e:0370:7344%5", url.getAddress()); assertEquals(0, url.getPort()); assertEquals("context/path", url.getPath()); assertEquals(2, url.getParameters().size()); assertEquals("1.0.0", url.getParameter("version")); assertEquals("morgan", url.getParameter("application")); } @Test public void testDefaultPort() { Assertions.assertEquals("10.20.153.10:2181", URL.appendDefaultPort("10.20.153.10:0", 2181)); Assertions.assertEquals("10.20.153.10:2181", URL.appendDefaultPort("10.20.153.10", 2181)); } @Test public void testGetServiceKey() { URL url1 = URL.valueOf("10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName"); assertURLStrDecoder(url1); Assertions.assertEquals("org.apache.dubbo.test.interfaceName", url1.getServiceKey()); URL url2 = URL.valueOf("10.20.130.230:20880/org.apache.dubbo.test.interfaceName?interface=org.apache.dubbo.test.interfaceName"); assertURLStrDecoder(url2); Assertions.assertEquals("org.apache.dubbo.test.interfaceName", url2.getServiceKey()); URL url3 = URL.valueOf("10.20.130.230:20880/org.apache.dubbo.test.interfaceName?interface=org.apache.dubbo.test.interfaceName&group=group1&version=1.0.0"); assertURLStrDecoder(url3); Assertions.assertEquals("group1/org.apache.dubbo.test.interfaceName:1.0.0", url3.getServiceKey()); URL url4 = URL.valueOf("10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName"); assertURLStrDecoder(url4); Assertions.assertEquals("context/path", url4.getPathKey()); URL url5 = URL.valueOf("10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&group=group1&version=1.0.0"); assertURLStrDecoder(url5); Assertions.assertEquals("group1/context/path:1.0.0", url5.getPathKey()); } @Test public void testGetColonSeparatedKey() { URL url1 = URL.valueOf("10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&group=group&version=1.0.0"); assertURLStrDecoder(url1); Assertions.assertEquals("org.apache.dubbo.test.interfaceName:1.0.0:group", url1.getColonSeparatedKey()); URL url2 = URL.valueOf("10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&version=1.0.0"); assertURLStrDecoder(url2); Assertions.assertEquals("org.apache.dubbo.test.interfaceName:1.0.0:", url2.getColonSeparatedKey()); URL url3 = URL.valueOf("10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&group=group"); assertURLStrDecoder(url3); Assertions.assertEquals("org.apache.dubbo.test.interfaceName::group", url3.getColonSeparatedKey()); URL url4 = URL.valueOf("10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName"); assertURLStrDecoder(url4); Assertions.assertEquals("org.apache.dubbo.test.interfaceName::", url4.getColonSeparatedKey()); URL url5 = URL.valueOf("10.20.130.230:20880/org.apache.dubbo.test.interfaceName"); assertURLStrDecoder(url5); Assertions.assertEquals("org.apache.dubbo.test.interfaceName::", url5.getColonSeparatedKey()); URL url6 = URL.valueOf("10.20.130.230:20880/org.apache.dubbo.test.interfaceName?interface=org.apache.dubbo.test.interfaceName1"); assertURLStrDecoder(url6); Assertions.assertEquals("org.apache.dubbo.test.interfaceName1::", url6.getColonSeparatedKey()); } @Test public void testValueOf() { URL url = URL.valueOf("10.20.130.230"); assertURLStrDecoder(url); url = URL.valueOf("10.20.130.230:20880"); assertURLStrDecoder(url); url = URL.valueOf("dubbo://10.20.130.230:20880"); assertURLStrDecoder(url); url = URL.valueOf("dubbo://10.20.130.230:20880/path"); assertURLStrDecoder(url); } /** * Test {@link URL#getParameters(Predicate)} method * * @since 2.7.8 */ @Test public void testGetParameters() { URL url = URL.valueOf("10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&group=group&version=1.0.0"); Map<String, String> parameters = url.getParameters(i -> "version".equals(i)); String version = parameters.get("version"); assertEquals(1, parameters.size()); assertEquals("1.0.0", version); } @Test public void testGetParameter() { URL url = URL.valueOf("http://127.0.0.1:8080/path?i=1&b=false"); assertEquals(Integer.valueOf(1), url.getParameter("i", Integer.class)); assertEquals(Boolean.FALSE, url.getParameter("b", Boolean.class)); } @Test public void testEquals() { URL url1 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + "dubbo-demo-api-consumer&category=consumers&check=false&dubbo=2.0.2&generic=true&interface=" + "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false&timestamp=1599556506417"); URL url2 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + "dubbo-demo-api-consumer&category=consumers&check=false&dubbo=2.0.2&generic=true&interface=" + "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false&timestamp=2299556506417"); assertEquals(url1, url2); URL url3 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + "dubbo-demo-api-consumer&category=consumers&check=false&dubbo=2.0.2&interface=" + "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false&timestamp=2299556506417"); assertNotEquals(url2, url3); URL url4 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + "dubbo-demo-api-consumer&category=consumers&check=true&dubbo=2.0.2&interface=" + "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false&timestamp=2299556506417"); assertNotEquals(url3, url4); } @Test public void testHashcode() { URL url1 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + "dubbo-demo-api-consumer&category=consumers&check=false&dubbo=2.0.2&generic=true&interface=" + "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false&timestamp=1599556506417"); URL url2 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + "dubbo-demo-api-consumer&category=consumers&check=false&dubbo=2.0.2&generic=true&interface=" + "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false&timestamp=2299556506417"); assertEquals(url1.hashCode(), url2.hashCode()); URL url3 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + "dubbo-demo-api-consumer&category=consumers&check=false&dubbo=2.0.2&interface=" + "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false&timestamp=2299556506417"); assertNotEquals(url2.hashCode(), url3.hashCode()); URL url4 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + "dubbo-demo-api-consumer&category=consumers&check=true&dubbo=2.0.2&interface=" + "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false&timestamp=2299556506417"); assertNotEquals(url3.hashCode(), url4.hashCode()); } @Test public void testEqualsWithPassword() { URL url1 = URL.valueOf("ad@min:hello@[email protected]:20880/context/path?version=1.0.0&application=morgan"); URL url2 = URL.valueOf("ad@min:hello@[email protected]:20880/context/path?version=1.0.0&application=morgan"); URL url3 = URL.valueOf("ad@min:hello@[email protected]:20880/context/path?version=1.0.0&application=morgan"); boolean actual1 = url1.equals(url2); boolean actual2 = url1.equals(url3); assertFalse(actual1); assertTrue(actual2); } @Test public void testEqualsWithPath() { URL url1 = URL.valueOf("ad@min:hello@[email protected]:20880/context/path1?version=1.0.0&application=morgan"); URL url2 = URL.valueOf("ad@min:hello@[email protected]:20880/context/path2?version=1.0.0&application=morgan"); URL url3 = URL.valueOf("ad@min:hello@[email protected]:20880/context/path1?version=1.0.0&application=morgan"); boolean actual1 = url1.equals(url2); boolean actual2 = url1.equals(url3); assertFalse(actual1); assertTrue(actual2); } @Test public void testEqualsWithPort() { URL url1 = URL.valueOf("ad@min:hello@[email protected]:20880/context/path?version=1.0.0&application=morgan"); URL url2 = URL.valueOf("ad@min:hello@[email protected]:20881/context/path?version=1.0.0&application=morgan"); URL url3 = URL.valueOf("ad@min:hello@[email protected]:20880/context/path?version=1.0.0&application=morgan"); boolean actual1 = url1.equals(url2); boolean actual2 = url1.equals(url3); assertFalse(actual1); assertTrue(actual2); } @Test public void testEqualsWithProtocol() { URL url1 = URL.valueOf("dubbo://ad@min:hello@[email protected]:20880/context/path?version=1.0.0&application=morgan"); URL url2 = URL.valueOf("file://ad@min:hello@[email protected]:20880/context/path?version=1.0.0&application=morgan"); URL url3 = URL.valueOf("dubbo://ad@min:hello@[email protected]:20880/context/path?version=1.0.0&application=morgan"); boolean actual1 = url1.equals(url2); boolean actual2 = url1.equals(url3); assertFalse(actual1); assertTrue(actual2); } @Test public void testEqualsWithUser() { URL url1 = URL.valueOf("ad@min1:hello@[email protected]:20880/context/path?version=1.0.0&application=morgan"); URL url2 = URL.valueOf("ad@min2:hello@[email protected]:20880/context/path?version=1.0.0&application=morgan"); URL url3 = URL.valueOf("ad@min1:hello@[email protected]:20880/context/path?version=1.0.0&application=morgan"); boolean actual1 = url1.equals(url2); boolean actual2 = url1.equals(url3); assertFalse(actual1); assertTrue(actual2); } }
Add test cases with # in the parameters for URLTest (#7767)
dubbo-common/src/test/java/org/apache/dubbo/common/URLTest.java
Add test cases with # in the parameters for URLTest (#7767)
<ide><path>ubbo-common/src/test/java/org/apache/dubbo/common/URLTest.java <ide> @Test <ide> public void test_windowAbsolutePathBeginWithSlashIsValid() throws Exception { <ide> final String osProperty = System.getProperties().getProperty("os.name"); <del> if (!osProperty.toLowerCase().contains("windows")) return; <add> if (!osProperty.toLowerCase().contains("windows")) { <add> return; <add> } <ide> <ide> System.out.println("Test Windows valid path string."); <ide> <ide> <ide> @Test <ide> public void test_javaNetUrl() throws Exception { <del> java.net.URL url = new java.net.URL("http://admin:[email protected]:20880/context/path?version=1.0.0&application=morgan#anchor1"); <add> java.net.URL url = <add> new java.net.URL("http://admin:[email protected]:20880/context/path?version=1.0.0&application=morgan#anchor1"); <ide> <ide> assertEquals("http", url.getProtocol()); <ide> assertEquals("admin:hello1234", url.getUserInfo()); <ide> @Test <ide> public void testIpV6Address() { <ide> // Test username or password contains "@" <del> URL url = URL.valueOf("ad@min111:haha@1234@2001:0db8:85a3:08d3:1319:8a2e:0370:7344:20880/context/path?version=1.0.0&application=morgan"); <add> URL url = URL.valueOf( <add> "ad@min111:haha@1234@2001:0db8:85a3:08d3:1319:8a2e:0370:7344:20880/context/path?version=1.0.0&application=morgan"); <ide> assertURLStrDecoder(url); <ide> assertNull(url.getProtocol()); <ide> assertEquals("ad@min111", url.getUsername()); <ide> assertURLStrDecoder(url2); <ide> Assertions.assertEquals("org.apache.dubbo.test.interfaceName", url2.getServiceKey()); <ide> <del> URL url3 = URL.valueOf("10.20.130.230:20880/org.apache.dubbo.test.interfaceName?interface=org.apache.dubbo.test.interfaceName&group=group1&version=1.0.0"); <add> URL url3 = URL.valueOf( <add> "10.20.130.230:20880/org.apache.dubbo.test.interfaceName?interface=org.apache.dubbo.test.interfaceName&group=group1&version=1.0.0"); <ide> assertURLStrDecoder(url3); <ide> Assertions.assertEquals("group1/org.apache.dubbo.test.interfaceName:1.0.0", url3.getServiceKey()); <ide> <ide> assertFalse(actual1); <ide> assertTrue(actual2); <ide> } <add> <add> @Test <add> public void testParameterContainPound() { <add> URL url = URL.valueOf( <add> "dubbo://ad@min:hello@[email protected]:20880/context/path?version=1.0.0&application=morgan&pound=abcd#efg&protocol=registry"); <add> Assertions.assertEquals("abcd#efg", url.getParameter("pound")); <add> Assertions.assertEquals("registry", url.getParameter("protocol")); <add> } <ide> }
Java
apache-2.0
3aed35ea9c77a7a627bab933d299e3f9d912f07d
0
apache/pdfbox,apache/pdfbox
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.pdfbox.text; import java.io.IOException; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Deque; import org.apache.pdfbox.cos.COSDictionary; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.pdmodel.documentinterchange.markedcontent.PDMarkedContent; import org.apache.pdfbox.pdmodel.graphics.PDXObject; import org.apache.pdfbox.contentstream.operator.markedcontent.BeginMarkedContentSequence; import org.apache.pdfbox.contentstream.operator.markedcontent.BeginMarkedContentSequenceWithProperties; import org.apache.pdfbox.contentstream.operator.markedcontent.DrawObject; import org.apache.pdfbox.contentstream.operator.markedcontent.EndMarkedContentSequence; /** * This is an stream engine to extract the marked content of a pdf. * * @author Johannes Koch */ public class PDFMarkedContentExtractor extends LegacyPDFStreamEngine { private boolean suppressDuplicateOverlappingText = true; private final List<PDMarkedContent> markedContents = new ArrayList<>(); private final Deque<PDMarkedContent> currentMarkedContents = new ArrayDeque<>(); private final Map<String, List<TextPosition>> characterListMapping = new HashMap<>(); /** * Instantiate a new PDFTextStripper object. */ public PDFMarkedContentExtractor() { this(null); } /** * Constructor. Will apply encoding-specific conversions to the output text. * * @param encoding The encoding that the output will be written in. */ public PDFMarkedContentExtractor(String encoding) { addOperator(new BeginMarkedContentSequenceWithProperties()); addOperator(new BeginMarkedContentSequence()); addOperator(new EndMarkedContentSequence()); addOperator(new DrawObject()); // todo: DP - Marked Content Point // todo: MP - Marked Content Point with Properties } /** * @return the suppressDuplicateOverlappingText setting. */ public boolean isSuppressDuplicateOverlappingText() { return suppressDuplicateOverlappingText; } /** * By default the class will attempt to remove text that overlaps each other. Word paints the * same character several times in order to make it look bold. By setting this to false all text * will be extracted, which means that certain sections will be duplicated, but better * performance will be noticed. * * @param suppressDuplicateOverlappingText The suppressDuplicateOverlappingText setting to set. */ public void setSuppressDuplicateOverlappingText(boolean suppressDuplicateOverlappingText) { this.suppressDuplicateOverlappingText = suppressDuplicateOverlappingText; } /** * This will determine of two floating point numbers are within a specified variance. * * @param first The first number to compare to. * @param second The second number to compare to. * @param variance The allowed variance. */ private boolean within( float first, float second, float variance ) { return second > first - variance && second < first + variance; } @Override public void beginMarkedContentSequence(COSName tag, COSDictionary properties) { PDMarkedContent markedContent = PDMarkedContent.create(tag, properties); if (this.currentMarkedContents.isEmpty()) { this.markedContents.add(markedContent); } else { PDMarkedContent currentMarkedContent = this.currentMarkedContents.peek(); if (currentMarkedContent != null) { currentMarkedContent.addMarkedContent(markedContent); } } this.currentMarkedContents.push(markedContent); } @Override public void endMarkedContentSequence() { if (!this.currentMarkedContents.isEmpty()) { this.currentMarkedContents.pop(); } } public void xobject(PDXObject xobject) { if (!this.currentMarkedContents.isEmpty()) { this.currentMarkedContents.peek().addXObject(xobject); } } /** * This will process a TextPosition object and add the * text to the list of characters on a page. It takes care of * overlapping text. * * @param text The text to process. */ @Override protected void processTextPosition( TextPosition text ) { boolean showCharacter = true; if( this.suppressDuplicateOverlappingText ) { showCharacter = false; String textCharacter = text.getUnicode(); float textX = text.getX(); float textY = text.getY(); List<TextPosition> sameTextCharacters = this.characterListMapping.computeIfAbsent(textCharacter, k -> new ArrayList<>()); // RDD - Here we compute the value that represents the end of the rendered // text. This value is used to determine whether subsequent text rendered // on the same line overwrites the current text. // // We subtract any positive padding to handle cases where extreme amounts // of padding are applied, then backed off (not sure why this is done, but there // are cases where the padding is on the order of 10x the character width, and // the TJ just backs up to compensate after each character). Also, we subtract // an amount to allow for kerning (a percentage of the width of the last // character). // boolean suppressCharacter = false; float tolerance = (text.getWidth()/textCharacter.length())/3.0f; for (TextPosition sameTextCharacter : sameTextCharacters) { String charCharacter = sameTextCharacter.getUnicode(); float charX = sameTextCharacter.getX(); float charY = sameTextCharacter.getY(); //only want to suppress if( charCharacter != null && //charCharacter.equals( textCharacter ) && within( charX, textX, tolerance ) && within( charY, textY, tolerance ) ) { suppressCharacter = true; break; } } if( !suppressCharacter ) { sameTextCharacters.add( text ); showCharacter = true; } } if( showCharacter ) { List<TextPosition> textList = new ArrayList<>(); /* In the wild, some PDF encoded documents put diacritics (accents on * top of characters) into a separate Tj element. When displaying them * graphically, the two chunks get overlaid. With text output though, * we need to do the overlay. This code recombines the diacritic with * its associated character if the two are consecutive. */ if(textList.isEmpty()) { textList.add(text); } else { /* test if we overlap the previous entry. * Note that we are making an assumption that we need to only look back * one TextPosition to find what we are overlapping. * This may not always be true. */ TextPosition previousTextPosition = textList.get(textList.size()-1); if(text.isDiacritic() && previousTextPosition.contains(text)) { previousTextPosition.mergeDiacritic(text); } /* If the previous TextPosition was the diacritic, merge it into this * one and remove it from the list. */ else if(previousTextPosition.isDiacritic() && text.contains(previousTextPosition)) { text.mergeDiacritic(previousTextPosition); textList.remove(textList.size()-1); textList.add(text); } else { textList.add(text); } } if (!this.currentMarkedContents.isEmpty()) { this.currentMarkedContents.peek().addText(text); } } } public List<PDMarkedContent> getMarkedContents() { return this.markedContents; } }
pdfbox/src/main/java/org/apache/pdfbox/text/PDFMarkedContentExtractor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.pdfbox.text; import java.io.IOException; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Deque; import org.apache.pdfbox.cos.COSDictionary; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.pdmodel.documentinterchange.markedcontent.PDMarkedContent; import org.apache.pdfbox.pdmodel.graphics.PDXObject; import org.apache.pdfbox.contentstream.operator.markedcontent.BeginMarkedContentSequence; import org.apache.pdfbox.contentstream.operator.markedcontent.BeginMarkedContentSequenceWithProperties; import org.apache.pdfbox.contentstream.operator.markedcontent.DrawObject; import org.apache.pdfbox.contentstream.operator.markedcontent.EndMarkedContentSequence; /** * This is an stream engine to extract the marked content of a pdf. * * @author Johannes Koch */ public class PDFMarkedContentExtractor extends LegacyPDFStreamEngine { private boolean suppressDuplicateOverlappingText = true; private final List<PDMarkedContent> markedContents = new ArrayList<>(); private final Deque<PDMarkedContent> currentMarkedContents = new ArrayDeque<>(); private final Map<String, List<TextPosition>> characterListMapping = new HashMap<>(); /** * Instantiate a new PDFTextStripper object. */ public PDFMarkedContentExtractor() throws IOException { this(null); } /** * Constructor. Will apply encoding-specific conversions to the output text. * * @param encoding The encoding that the output will be written in. */ public PDFMarkedContentExtractor(String encoding) { addOperator(new BeginMarkedContentSequenceWithProperties()); addOperator(new BeginMarkedContentSequence()); addOperator(new EndMarkedContentSequence()); addOperator(new DrawObject()); // todo: DP - Marked Content Point // todo: MP - Marked Content Point with Properties } /** * @return the suppressDuplicateOverlappingText setting. */ public boolean isSuppressDuplicateOverlappingText() { return suppressDuplicateOverlappingText; } /** * By default the class will attempt to remove text that overlaps each other. Word paints the * same character several times in order to make it look bold. By setting this to false all text * will be extracted, which means that certain sections will be duplicated, but better * performance will be noticed. * * @param suppressDuplicateOverlappingText The suppressDuplicateOverlappingText setting to set. */ public void setSuppressDuplicateOverlappingText(boolean suppressDuplicateOverlappingText) { this.suppressDuplicateOverlappingText = suppressDuplicateOverlappingText; } /** * This will determine of two floating point numbers are within a specified variance. * * @param first The first number to compare to. * @param second The second number to compare to. * @param variance The allowed variance. */ private boolean within( float first, float second, float variance ) { return second > first - variance && second < first + variance; } @Override public void beginMarkedContentSequence(COSName tag, COSDictionary properties) { PDMarkedContent markedContent = PDMarkedContent.create(tag, properties); if (this.currentMarkedContents.isEmpty()) { this.markedContents.add(markedContent); } else { PDMarkedContent currentMarkedContent = this.currentMarkedContents.peek(); if (currentMarkedContent != null) { currentMarkedContent.addMarkedContent(markedContent); } } this.currentMarkedContents.push(markedContent); } @Override public void endMarkedContentSequence() { if (!this.currentMarkedContents.isEmpty()) { this.currentMarkedContents.pop(); } } public void xobject(PDXObject xobject) { if (!this.currentMarkedContents.isEmpty()) { this.currentMarkedContents.peek().addXObject(xobject); } } /** * This will process a TextPosition object and add the * text to the list of characters on a page. It takes care of * overlapping text. * * @param text The text to process. */ @Override protected void processTextPosition( TextPosition text ) { boolean showCharacter = true; if( this.suppressDuplicateOverlappingText ) { showCharacter = false; String textCharacter = text.getUnicode(); float textX = text.getX(); float textY = text.getY(); List<TextPosition> sameTextCharacters = this.characterListMapping.computeIfAbsent(textCharacter, k -> new ArrayList<>()); // RDD - Here we compute the value that represents the end of the rendered // text. This value is used to determine whether subsequent text rendered // on the same line overwrites the current text. // // We subtract any positive padding to handle cases where extreme amounts // of padding are applied, then backed off (not sure why this is done, but there // are cases where the padding is on the order of 10x the character width, and // the TJ just backs up to compensate after each character). Also, we subtract // an amount to allow for kerning (a percentage of the width of the last // character). // boolean suppressCharacter = false; float tolerance = (text.getWidth()/textCharacter.length())/3.0f; for (TextPosition sameTextCharacter : sameTextCharacters) { String charCharacter = sameTextCharacter.getUnicode(); float charX = sameTextCharacter.getX(); float charY = sameTextCharacter.getY(); //only want to suppress if( charCharacter != null && //charCharacter.equals( textCharacter ) && within( charX, textX, tolerance ) && within( charY, textY, tolerance ) ) { suppressCharacter = true; break; } } if( !suppressCharacter ) { sameTextCharacters.add( text ); showCharacter = true; } } if( showCharacter ) { List<TextPosition> textList = new ArrayList<>(); /* In the wild, some PDF encoded documents put diacritics (accents on * top of characters) into a separate Tj element. When displaying them * graphically, the two chunks get overlaid. With text output though, * we need to do the overlay. This code recombines the diacritic with * its associated character if the two are consecutive. */ if(textList.isEmpty()) { textList.add(text); } else { /* test if we overlap the previous entry. * Note that we are making an assumption that we need to only look back * one TextPosition to find what we are overlapping. * This may not always be true. */ TextPosition previousTextPosition = textList.get(textList.size()-1); if(text.isDiacritic() && previousTextPosition.contains(text)) { previousTextPosition.mergeDiacritic(text); } /* If the previous TextPosition was the diacritic, merge it into this * one and remove it from the list. */ else if(previousTextPosition.isDiacritic() && text.contains(previousTextPosition)) { text.mergeDiacritic(previousTextPosition); textList.remove(textList.size()-1); textList.add(text); } else { textList.add(text); } } if (!this.currentMarkedContents.isEmpty()) { this.currentMarkedContents.peek().addText(text); } } } public List<PDMarkedContent> getMarkedContents() { return this.markedContents; } }
PDFBOX-4892: remove exception that isn't thrown git-svn-id: c3ad59981690829a43dc34c293c4e2cd04bcd994@1892785 13f79535-47bb-0310-9956-ffa450edef68
pdfbox/src/main/java/org/apache/pdfbox/text/PDFMarkedContentExtractor.java
PDFBOX-4892: remove exception that isn't thrown
<ide><path>dfbox/src/main/java/org/apache/pdfbox/text/PDFMarkedContentExtractor.java <ide> /** <ide> * Instantiate a new PDFTextStripper object. <ide> */ <del> public PDFMarkedContentExtractor() throws IOException <add> public PDFMarkedContentExtractor() <ide> { <ide> this(null); <ide> }
Java
bsd-3-clause
b338dfdf8981df9ba4ea2f1601bc40ed5cb63f68
0
inadco/protobuf-java-format
package com.googlecode.protobuf.format; /* Copyright (c) 2009, Orbitz World Wide All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Orbitz World Wide nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import java.io.IOException; import java.math.BigInteger; import java.nio.CharBuffer; import java.text.CharacterIterator; import java.text.StringCharacterIterator; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.protobuf.ByteString; import com.google.protobuf.ExtensionRegistry; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.Message; import com.google.protobuf.UnknownFieldSet; import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.EnumDescriptor; import com.google.protobuf.Descriptors.EnumValueDescriptor; import com.google.protobuf.Descriptors.FieldDescriptor; import com.googlecode.protobuf.format.util.IDUtil; import com.googlecode.protobuf.format.util.TextUtils; import static com.googlecode.protobuf.format.util.TextUtils.*; /** * Provide ascii text parsing and formatting support for proto2 instances. The implementation * largely follows google/protobuf/text_format.cc. * <p> * (c) 2009-10 Orbitz World Wide. All Rights Reserved. * * @author [email protected] Eliran Bivas * @author [email protected] Alex Antonov * <p/> * Based on the original code by: * @author [email protected] Wenbo Zhu * @author [email protected] Kenton Varda */ public class JsonFormat extends AbstractCharBasedFormatter { /** * Outputs a textual representation of the Protocol Message supplied into the parameter output. * (This representation is the new version of the classic "ProtocolPrinter" output from the * original Protocol Buffer system) */ public void print(final Message message, Appendable output) throws IOException { JsonGenerator generator = new JsonGenerator(output); generator.print("{"); print(message, generator); generator.print("}"); } /** * Outputs a textual representation of {@code fields} to {@code output}. */ public void print(final UnknownFieldSet fields, Appendable output) throws IOException { JsonGenerator generator = new JsonGenerator(output); generator.print("{"); printUnknownFields(fields, generator); generator.print("}"); } protected void print(Message message, JsonGenerator generator) throws IOException { for (Iterator<Map.Entry<FieldDescriptor, Object>> iter = message.getAllFields().entrySet().iterator(); iter.hasNext();) { Map.Entry<FieldDescriptor, Object> field = iter.next(); printField(field.getKey(), field.getValue(), generator); if (iter.hasNext()) { generator.print(","); } } if (message.getUnknownFields().asMap().size() > 0) generator.print(", "); printUnknownFields(message.getUnknownFields(), generator); } public void printField(FieldDescriptor field, Object value, JsonGenerator generator) throws IOException { printSingleField(field, value, generator); } private void printSingleField(FieldDescriptor field, Object value, JsonGenerator generator) throws IOException { if (field.isExtension()) { generator.print("\""); // We special-case MessageSet elements for compatibility with proto1. if (field.getContainingType().getOptions().getMessageSetWireFormat() && (field.getType() == FieldDescriptor.Type.MESSAGE) && (field.isOptional()) // object equality && (field.getExtensionScope() == field.getMessageType())) { generator.print(field.getMessageType().getFullName()); } else { generator.print(field.getFullName()); } generator.print("\""); } else { generator.print("\""); if (field.getType() == FieldDescriptor.Type.GROUP) { // Groups must be serialized with their original capitalization. generator.print(field.getMessageType().getName()); } else { generator.print(field.getName()); } generator.print("\""); } // Done with the name, on to the value if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { generator.print(": "); generator.indent(); } else { generator.print(": "); } if (field.isRepeated()) { // Repeated field. Print each element. generator.print("["); for (Iterator<?> iter = ((List<?>) value).iterator(); iter.hasNext();) { printFieldValue(field, iter.next(), generator); if (iter.hasNext()) { generator.print(","); } } generator.print("]"); } else { printFieldValue(field, value, generator); if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { generator.outdent(); } } } private void printFieldValue(FieldDescriptor field, Object value, JsonGenerator generator) throws IOException { switch (field.getType()) { case INT32: case INT64: case SINT32: case SINT64: case SFIXED32: case SFIXED64: case FLOAT: case DOUBLE: case BOOL: // Good old toString() does what we want for these types. generator.print(value.toString()); break; case UINT32: case FIXED32: generator.print(unsignedToString((Integer) value)); break; case UINT64: case FIXED64: generator.print(unsignedToString((Long) value)); break; case STRING: generator.print("\""); generator.print(escapeText((String) value)); generator.print("\""); break; case BYTES: { generator.print("\""); ByteString byteString = (ByteString) value; if(IDUtil.isValidID(byteString)){ generator.print(IDUtil.bytes2HexString(byteString.toByteArray())); }else{ generator.print(escapeBytes((ByteString) value)); } generator.print("\""); break; } case ENUM: { generator.print("\""); generator.print(((EnumValueDescriptor) value).getName()); generator.print("\""); break; } case MESSAGE: case GROUP: generator.print("{"); print((Message) value, generator); generator.print("}"); break; } } protected void printUnknownFields(UnknownFieldSet unknownFields, JsonGenerator generator) throws IOException { boolean firstField = true; for (Map.Entry<Integer, UnknownFieldSet.Field> entry : unknownFields.asMap().entrySet()) { UnknownFieldSet.Field field = entry.getValue(); if (firstField) {firstField = false;} else {generator.print(", ");} generator.print("\""); generator.print(entry.getKey().toString()); generator.print("\""); generator.print(": ["); boolean firstValue = true; for (long value : field.getVarintList()) { if (firstValue) {firstValue = false;} else {generator.print(", ");} generator.print(unsignedToString(value)); } for (int value : field.getFixed32List()) { if (firstValue) {firstValue = false;} else {generator.print(", ");} generator.print(String.format((Locale) null, "0x%08x", value)); } for (long value : field.getFixed64List()) { if (firstValue) {firstValue = false;} else {generator.print(", ");} generator.print(String.format((Locale) null, "0x%016x", value)); } for (ByteString value : field.getLengthDelimitedList()) { if (firstValue) {firstValue = false;} else {generator.print(", ");} generator.print("\""); generator.print(escapeBytes(value)); generator.print("\""); } for (UnknownFieldSet value : field.getGroupList()) { if (firstValue) {firstValue = false;} else {generator.print(", ");} generator.print("{"); printUnknownFields(value, generator); generator.print("}"); } generator.print("]"); } } /** * An inner class for writing text to the output stream. */ protected static class JsonGenerator { Appendable output; boolean atStartOfLine = true; StringBuilder indent = new StringBuilder(); public JsonGenerator(Appendable output) { this.output = output; } /** * Indent text by two spaces. After calling Indent(), two spaces will be inserted at the * beginning of each line of text. Indent() may be called multiple times to produce deeper * indents. */ public void indent() { indent.append(" "); } /** * Reduces the current indent level by two spaces, or crashes if the indent level is zero. */ public void outdent() { int length = indent.length(); if (length == 0) { throw new IllegalArgumentException(" Outdent() without matching Indent()."); } indent.delete(length - 2, length); } /** * Print text to the output stream. */ public void print(CharSequence text) throws IOException { int size = text.length(); int pos = 0; for (int i = 0; i < size; i++) { if (text.charAt(i) == '\n') { write(text.subSequence(pos, size), i - pos + 1); pos = i + 1; atStartOfLine = true; } } write(text.subSequence(pos, size), size - pos); } private void write(CharSequence data, int size) throws IOException { if (size == 0) { return; } if (atStartOfLine) { atStartOfLine = false; output.append(indent); } output.append(data); } } // ================================================================= // Parsing /** * Represents a stream of tokens parsed from a {@code String}. * <p/> * <p> * The Java standard library provides many classes that you might think would be useful for * implementing this, but aren't. For example: * <p/> * <ul> * <li>{@code java.io.StreamTokenizer}: This almost does what we want -- or, at least, something * that would get us close to what we want -- except for one fatal flaw: It automatically * un-escapes strings using Java escape sequences, which do not include all the escape sequences * we need to support (e.g. '\x'). * <li>{@code java.util.Scanner}: This seems like a great way at least to parse regular * expressions out of a stream (so we wouldn't have to load the entire input into a single * string before parsing). Sadly, {@code Scanner} requires that tokens be delimited with some * delimiter. Thus, although the text "foo:" should parse to two tokens ("foo" and ":"), {@code * Scanner} would recognize it only as a single token. Furthermore, {@code Scanner} provides no * way to inspect the contents of delimiters, making it impossible to keep track of line and * column numbers. * </ul> * <p/> * <p> * Luckily, Java's regular expression support does manage to be useful to us. (Barely: We need * {@code Matcher.usePattern()}, which is new in Java 1.5.) So, we can use that, at least. * Unfortunately, this implies that we need to have the entire input in one contiguous string. */ protected static class Tokenizer { private final CharSequence text; private final Matcher matcher; private String currentToken; // The character index within this.text at which the current token begins. private int pos = 0; // The line and column numbers of the current token. private int line = 0; private int column = 0; // The line and column numbers of the previous token (allows throwing // errors *after* consuming). private int previousLine = 0; private int previousColumn = 0; // We use possesive quantifiers (*+ and ++) because otherwise the Java // regex matcher has stack overflows on large inputs. private static final Pattern WHITESPACE = Pattern.compile("(\\s|(#.*$))++", Pattern.MULTILINE); private static final Pattern TOKEN = Pattern.compile( "[a-zA-Z_][0-9a-zA-Z_+-]*+|" + // an identifier "[.]?[0-9+-][0-9a-zA-Z_.+-]*+|" + // a number "\"([^\"\n\\\\]|\\\\.)*+(\"|\\\\?$)|" + // a double-quoted string "\'([^\'\n\\\\]|\\\\.)*+(\'|\\\\?$)", // a single-quoted string Pattern.MULTILINE); private static final Pattern DOUBLE_INFINITY = Pattern.compile( "-?inf(inity)?", Pattern.CASE_INSENSITIVE); private static final Pattern FLOAT_INFINITY = Pattern.compile( "-?inf(inity)?f?", Pattern.CASE_INSENSITIVE); private static final Pattern FLOAT_NAN = Pattern.compile( "nanf?", Pattern.CASE_INSENSITIVE); /** * Construct a tokenizer that parses tokens from the given text. */ public Tokenizer(CharSequence text) { this.text = text; matcher = WHITESPACE.matcher(text); skipWhitespace(); nextToken(); } /** * Are we at the end of the input? */ public boolean atEnd() { return currentToken.length() == 0; } /** * Advance to the next token. */ public void nextToken() { previousLine = line; previousColumn = column; // Advance the line counter to the current position. while (pos < matcher.regionStart()) { if (text.charAt(pos) == '\n') { ++line; column = 0; } else { ++column; } ++pos; } // Match the next token. if (matcher.regionStart() == matcher.regionEnd()) { // EOF currentToken = ""; } else { matcher.usePattern(TOKEN); if (matcher.lookingAt()) { currentToken = matcher.group(); matcher.region(matcher.end(), matcher.regionEnd()); } else { // Take one character. currentToken = String.valueOf(text.charAt(pos)); matcher.region(pos + 1, matcher.regionEnd()); } skipWhitespace(); } } /** * Skip over any whitespace so that the matcher region starts at the next token. */ private void skipWhitespace() { matcher.usePattern(WHITESPACE); if (matcher.lookingAt()) { matcher.region(matcher.end(), matcher.regionEnd()); } } /** * If the next token exactly matches {@code token}, consume it and return {@code true}. * Otherwise, return {@code false} without doing anything. */ public boolean tryConsume(String token) { if (currentToken.equals(token)) { nextToken(); return true; } else { return false; } } /** * If the next token exactly matches {@code token}, consume it. Otherwise, throw a * {@link ParseException}. */ public void consume(String token) throws ParseException { if (!tryConsume(token)) { throw parseException("Expected \"" + token + "\"."); } } /** * Returns {@code true} if the next token is an float, but does not consume it. */ public boolean lookingAtFloat() { return lookingAtInteger() && currentToken.contains("."); } /** * Returns {@code true} if the next token is an integer, but does not consume it. */ public boolean lookingAtInteger() { if (currentToken.length() == 0) { return false; } char c = currentToken.charAt(0); return (('0' <= c) && (c <= '9')) || (c == '-') || (c == '+'); } /** * Returns {@code true} if the next token is a boolean (true/false), but does not consume it. */ public boolean lookingAtBoolean() { if (currentToken.length() == 0) { return false; } return ("true".equals(currentToken) || "false".equals(currentToken)); } /** * @return currentToken to which the Tokenizer is pointing. */ public String currentToken() { return currentToken; } /** * If the next token is an identifier, consume it and return its value. Otherwise, throw a * {@link ParseException}. */ public String consumeIdentifier() throws ParseException { for (int i = 0; i < currentToken.length(); i++) { char c = currentToken.charAt(i); if ((('a' <= c) && (c <= 'z')) || (('A' <= c) && (c <= 'Z')) || (('0' <= c) && (c <= '9')) || (c == '_') || (c == '.') || (c == '"')) { // OK } else { throw parseException("Expected identifier. -" + c); } } String result = currentToken; // Need to clean-up result to remove quotes of any kind result = result.replaceAll("\"|'", ""); nextToken(); return result; } /** * If the next token is a 32-bit signed integer, consume it and return its value. Otherwise, * throw a {@link ParseException}. */ public int consumeInt32() throws ParseException { try { int result = parseInt32(currentToken); nextToken(); return result; } catch (NumberFormatException e) { throw integerParseException(e); } } /** * If the next token is a 32-bit unsigned integer, consume it and return its value. * Otherwise, throw a {@link ParseException}. */ public int consumeUInt32() throws ParseException { try { int result = parseUInt32(currentToken); nextToken(); return result; } catch (NumberFormatException e) { throw integerParseException(e); } } /** * If the next token is a 64-bit signed integer, consume it and return its value. Otherwise, * throw a {@link ParseException}. */ public long consumeInt64() throws ParseException { try { long result = parseInt64(currentToken); nextToken(); return result; } catch (NumberFormatException e) { throw integerParseException(e); } } /** * If the next token is a 64-bit unsigned integer, consume it and return its value. * Otherwise, throw a {@link ParseException}. */ public long consumeUInt64() throws ParseException { try { long result = parseUInt64(currentToken); nextToken(); return result; } catch (NumberFormatException e) { throw integerParseException(e); } } /** * If the next token is a double, consume it and return its value. Otherwise, throw a * {@link ParseException}. */ public double consumeDouble() throws ParseException { // We need to parse infinity and nan separately because // Double.parseDouble() does not accept "inf", "infinity", or "nan". if (DOUBLE_INFINITY.matcher(currentToken).matches()) { boolean negative = currentToken.startsWith("-"); nextToken(); return negative ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY; } if (currentToken.equalsIgnoreCase("nan")) { nextToken(); return Double.NaN; } try { double result = Double.parseDouble(prepareNumberFromString(currentToken)); nextToken(); return result; } catch (NumberFormatException e) { throw floatParseException(e); } } /** * If the next token is a float, consume it and return its value. Otherwise, throw a * {@link ParseException}. */ public float consumeFloat() throws ParseException { // We need to parse infinity and nan separately because // Float.parseFloat() does not accept "inf", "infinity", or "nan". if (FLOAT_INFINITY.matcher(currentToken).matches()) { boolean negative = currentToken.startsWith("-"); nextToken(); return negative ? Float.NEGATIVE_INFINITY : Float.POSITIVE_INFINITY; } if (FLOAT_NAN.matcher(currentToken).matches()) { nextToken(); return Float.NaN; } try { float result = Float.parseFloat(prepareNumberFromString(currentToken)); nextToken(); return result; } catch (NumberFormatException e) { throw floatParseException(e); } } /** * If the next token is a boolean, consume it and return its value. Otherwise, throw a * {@link ParseException}. */ public boolean consumeBoolean() throws ParseException { if (currentToken.equals("true")) { nextToken(); return true; } else if (currentToken.equals("false")) { nextToken(); return false; } else { throw parseException("Expected \"true\" or \"false\"."); } } /** * If the next token is a string, consume it and return its (unescaped) value. Otherwise, * throw a {@link ParseException}. */ public String consumeString() throws ParseException { char quote = currentToken.length() > 0 ? currentToken.charAt(0) : '\0'; if ((quote != '\"') && (quote != '\'')) { try { String result = currentToken.replace(',', '.'); Double.parseDouble(result); nextToken(); return result; } catch (NumberFormatException e) { throw parseException("Expected string."); } } if ((currentToken.length() < 2) || (currentToken.charAt(currentToken.length() - 1) != quote)) { throw parseException("String missing ending quote."); } try { String escaped = currentToken.substring(1, currentToken.length() - 1); String result = unescapeText(escaped); nextToken(); return result; } catch (InvalidEscapeSequence e) { throw parseException(e.getMessage()); } } /** * If the next token is a string, consume it, unescape it as a * {@link com.googlecode.protobuf.format.ByteString}, and return it. Otherwise, throw a * {@link ParseException}. */ public ByteString consumeByteString() throws ParseException { char quote = currentToken.length() > 0 ? currentToken.charAt(0) : '\0'; if ((quote != '\"') && (quote != '\'')) { throw parseException("Expected string."); } if ((currentToken.length() < 2) || (currentToken.charAt(currentToken.length() - 1) != quote)) { throw parseException("String missing ending quote."); } try { String escaped = currentToken.substring(1, currentToken.length() - 1); ByteString result = unescapeBytes(escaped); nextToken(); return result; } catch (InvalidEscapeSequence e) { throw parseException(e.getMessage()); } } /** * Returns a {@link ParseException} with the current line and column numbers in the * description, suitable for throwing. */ public ParseException parseException(String description) { // Note: People generally prefer one-based line and column numbers. return new ParseException((line + 1) + ":" + (column + 1) + ": " + description); } /** * Returns a {@link ParseException} with the line and column numbers of the previous token * in the description, suitable for throwing. */ public ParseException parseExceptionPreviousToken(String description) { // Note: People generally prefer one-based line and column numbers. return new ParseException((previousLine + 1) + ":" + (previousColumn + 1) + ": " + description); } /** * Constructs an appropriate {@link ParseException} for the given {@code * NumberFormatException} when trying to parse an integer. */ private ParseException integerParseException(NumberFormatException e) { return parseException("Couldn't parse integer: " + e.getMessage()); } /** * Constructs an appropriate {@link ParseException} for the given {@code * NumberFormatException} when trying to parse a float or double. */ private ParseException floatParseException(NumberFormatException e) { return parseException("Couldn't parse number: " + e.getMessage()); } } /** * Thrown when parsing an invalid text format message. */ public static class ParseException extends IOException { private static final long serialVersionUID = 1L; public ParseException(String message) { super(message); } } /** * Parse a text-format message from {@code input} and merge the contents into {@code builder}. * Extensions will be recognized if they are registered in {@code extensionRegistry}. */ public void merge(CharSequence input, ExtensionRegistry extensionRegistry, Message.Builder builder) throws ParseException { Tokenizer tokenizer = new Tokenizer(input); // Based on the state machine @ http://json.org/ tokenizer.consume("{"); // Needs to happen when the object starts. while (!tokenizer.tryConsume("}")) { // Continue till the object is done mergeField(tokenizer, extensionRegistry, builder); } // Test to make sure the tokenizer has reached the end of the stream. if (!tokenizer.atEnd()) { throw tokenizer.parseException("Expecting the end of the stream, but there seems to be more data! Check the input for a valid JSON format."); } } /** * Parse a single field from {@code tokenizer} and merge it into {@code builder}. If a ',' is * detected after the field ends, the next field will be parsed automatically */ protected void mergeField(Tokenizer tokenizer, ExtensionRegistry extensionRegistry, Message.Builder builder) throws ParseException { FieldDescriptor field; Descriptor type = builder.getDescriptorForType(); ExtensionRegistry.ExtensionInfo extension = null; boolean unknown = false; String name = tokenizer.consumeIdentifier(); field = type.findFieldByName(name); // Group names are expected to be capitalized as they appear in the // .proto file, which actually matches their type names, not their field // names. if (field == null) { // Explicitly specify US locale so that this code does not break when // executing in Turkey. String lowerName = name.toLowerCase(Locale.US); field = type.findFieldByName(lowerName); // If the case-insensitive match worked but the field is NOT a group, if ((field != null) && (field.getType() != FieldDescriptor.Type.GROUP)) { field = null; } } // Again, special-case group names as described above. if ((field != null) && (field.getType() == FieldDescriptor.Type.GROUP) && !field.getMessageType().getName().equals(name)) { field = null; } // Last try to lookup by field-index if 'name' is numeric, // which indicates a possible unknown field if (field == null && TextUtils.isDigits(name)) { field = type.findFieldByNumber(Integer.parseInt(name)); unknown = true; } // Finally, look for extensions extension = extensionRegistry.findExtensionByName(name); if (extension != null) { if (extension.descriptor.getContainingType() != type) { throw tokenizer.parseExceptionPreviousToken("Extension \"" + name + "\" does not extend message type \"" + type.getFullName() + "\"."); } field = extension.descriptor; } // Disabled throwing exception if field not found, since it could be a different version. if (field == null) { handleMissingField(tokenizer, extensionRegistry, builder); //throw tokenizer.parseExceptionPreviousToken("Message type \"" + type.getFullName() // + "\" has no field named \"" + name // + "\"."); } if (field != null) { tokenizer.consume(":"); boolean array = tokenizer.tryConsume("["); if (array) { while (!tokenizer.tryConsume("]")) { handleValue(tokenizer, extensionRegistry, builder, field, extension, unknown); tokenizer.tryConsume(","); } } else { handleValue(tokenizer, extensionRegistry, builder, field, extension, unknown); } } if (tokenizer.tryConsume(",")) { // Continue with the next field mergeField(tokenizer, extensionRegistry, builder); } } private void handleMissingField(Tokenizer tokenizer, ExtensionRegistry extensionRegistry, Message.Builder builder) throws ParseException { tokenizer.tryConsume(":"); if ("{".equals(tokenizer.currentToken())) { // Message structure tokenizer.consume("{"); do { tokenizer.consumeIdentifier(); handleMissingField(tokenizer, extensionRegistry, builder); } while (tokenizer.tryConsume(",")); tokenizer.consume("}"); } else if ("[".equals(tokenizer.currentToken())) { // Collection tokenizer.consume("["); do { handleMissingField(tokenizer, extensionRegistry, builder); } while (tokenizer.tryConsume(",")); tokenizer.consume("]"); } else { //if (!",".equals(tokenizer.currentToken)){ // Primitive value if ("null".equals(tokenizer.currentToken())) { tokenizer.consume("null"); } else if (tokenizer.lookingAtFloat()) { tokenizer.consumeFloat(); } else if (tokenizer.lookingAtInteger()) { tokenizer.consumeInt64(); } else if (tokenizer.lookingAtBoolean()) { tokenizer.consumeBoolean(); } else { tokenizer.consumeString(); } } } private void handleValue(Tokenizer tokenizer, ExtensionRegistry extensionRegistry, Message.Builder builder, FieldDescriptor field, ExtensionRegistry.ExtensionInfo extension, boolean unknown) throws ParseException { Object value = null; if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { value = handleObject(tokenizer, extensionRegistry, builder, field, extension, unknown); } else { value = handlePrimitive(tokenizer, field); } if (value != null) { if (field.isRepeated()) { builder.addRepeatedField(field, value); } else { builder.setField(field, value); } } } private Object handlePrimitive(Tokenizer tokenizer, FieldDescriptor field) throws ParseException { Object value = null; if ("null".equals(tokenizer.currentToken())) { tokenizer.consume("null"); return value; } switch (field.getType()) { case INT32: case SINT32: case SFIXED32: value = tokenizer.consumeInt32(); break; case INT64: case SINT64: case SFIXED64: value = tokenizer.consumeInt64(); break; case UINT32: case FIXED32: value = tokenizer.consumeUInt32(); break; case UINT64: case FIXED64: value = tokenizer.consumeUInt64(); break; case FLOAT: value = tokenizer.consumeFloat(); break; case DOUBLE: value = tokenizer.consumeDouble(); break; case BOOL: value = tokenizer.consumeBoolean(); break; case STRING: value = tokenizer.consumeString(); break; case BYTES: value = tokenizer.consumeByteString(); break; case ENUM: { EnumDescriptor enumType = field.getEnumType(); if (tokenizer.lookingAtInteger()) { int number = tokenizer.consumeInt32(); value = enumType.findValueByNumber(number); if (value == null) { throw tokenizer.parseExceptionPreviousToken("Enum type \"" + enumType.getFullName() + "\" has no value with number " + number + "."); } } else { String id = tokenizer.consumeIdentifier(); value = enumType.findValueByName(id); if (value == null) { throw tokenizer.parseExceptionPreviousToken("Enum type \"" + enumType.getFullName() + "\" has no value named \"" + id + "\"."); } } break; } case MESSAGE: case GROUP: throw new RuntimeException("Can't get here."); } return value; } private Object handleObject(Tokenizer tokenizer, ExtensionRegistry extensionRegistry, Message.Builder builder, FieldDescriptor field, ExtensionRegistry.ExtensionInfo extension, boolean unknown) throws ParseException { Message.Builder subBuilder; if (extension == null) { subBuilder = builder.newBuilderForField(field); } else { subBuilder = extension.defaultInstance.newBuilderForType(); } if (unknown) { ByteString data = tokenizer.consumeByteString(); try { subBuilder.mergeFrom(data); return subBuilder.build(); } catch (InvalidProtocolBufferException e) { throw tokenizer.parseException("Failed to build " + field.getFullName() + " from " + data); } } tokenizer.consume("{"); String endToken = "}"; while (!tokenizer.tryConsume(endToken)) { if (tokenizer.atEnd()) { throw tokenizer.parseException("Expected \"" + endToken + "\"."); } mergeField(tokenizer, extensionRegistry, subBuilder); if (tokenizer.tryConsume(",")) { // there are more fields in the object, so continue continue; } } return subBuilder.build(); } // ================================================================= // Utility functions // // Some of these methods are package-private because Descriptors.java uses // them. /** * Escapes bytes in the format used in protocol buffer text format, which is the same as the * format used for C string literals. All bytes that are not printable 7-bit ASCII characters * are escaped, as well as backslash, single-quote, and double-quote characters. Characters for * which no defined short-hand escape sequence is defined will be escaped using 3-digit octal * sequences. */ static String escapeBytes(ByteString input) { StringBuilder builder = new StringBuilder(input.size()); for (int i = 0; i < input.size(); i++) { byte b = input.byteAt(i); switch (b) { // Java does not recognize \a or \v, apparently. case 0x07: builder.append("\\a"); break; case '\b': builder.append("\\b"); break; case '\f': builder.append("\\f"); break; case '\n': builder.append("\\n"); break; case '\r': builder.append("\\r"); break; case '\t': builder.append("\\t"); break; case 0x0b: builder.append("\\v"); break; case '\\': builder.append("\\\\"); break; case '\'': builder.append("\\\'"); break; case '"': builder.append("\\\""); break; default: if (b >= 0x20) { builder.append((char) b); } else { final String unicodeString = unicodeEscaped((char) b); builder.append(unicodeString); } break; } } return builder.toString(); } static String bytesToHexString(ByteString input){ if(input == null){ return null; } return IDUtil.bytes2HexString(input.toByteArray()); } static String unicodeEscaped(char ch) { if (ch < 0x10) { return "\\u000" + Integer.toHexString(ch); } else if (ch < 0x100) { return "\\u00" + Integer.toHexString(ch); } else if (ch < 0x1000) { return "\\u0" + Integer.toHexString(ch); } return "\\u" + Integer.toHexString(ch); } /** * Un-escape a byte sequence as escaped using * {@link #escapeBytes(com.googlecode.protobuf.format.ByteString)}. Two-digit hex escapes (starting with * "\x") are also recognized. */ static ByteString unescapeBytes(CharSequence input) throws InvalidEscapeSequence { byte[] result = new byte[input.length()]; int pos = 0; for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); if (c == '\\') { if (i + 1 < input.length()) { ++i; c = input.charAt(i); if (isOctal(c)) { // Octal escape. int code = digitValue(c); if ((i + 1 < input.length()) && isOctal(input.charAt(i + 1))) { ++i; code = code * 8 + digitValue(input.charAt(i)); } if ((i + 1 < input.length()) && isOctal(input.charAt(i + 1))) { ++i; code = code * 8 + digitValue(input.charAt(i)); } result[pos++] = (byte) code; } else { switch (c) { case 'a': result[pos++] = 0x07; break; case 'b': result[pos++] = '\b'; break; case 'f': result[pos++] = '\f'; break; case 'n': result[pos++] = '\n'; break; case 'r': result[pos++] = '\r'; break; case 't': result[pos++] = '\t'; break; case 'v': result[pos++] = 0x0b; break; case '\\': result[pos++] = '\\'; break; case '\'': result[pos++] = '\''; break; case '"': result[pos++] = '\"'; break; case 'x': // hex escape int code = 0; if ((i + 1 < input.length()) && isHex(input.charAt(i + 1))) { ++i; code = digitValue(input.charAt(i)); } else { throw new InvalidEscapeSequence("Invalid escape sequence: '\\x' with no digits"); } if ((i + 1 < input.length()) && isHex(input.charAt(i + 1))) { ++i; code = code * 16 + digitValue(input.charAt(i)); } result[pos++] = (byte) code; break; case 'u': // UTF8 escape code = (16 * 3 * digitValue(input.charAt(i+1))) + (16 * 2 * digitValue(input.charAt(i+2))) + (16 * digitValue(input.charAt(i+3))) + digitValue(input.charAt(i+4)); i = i+4; result[pos++] = (byte) code; break; default: throw new InvalidEscapeSequence("Invalid escape sequence: '\\" + c + "'"); } } } else { throw new InvalidEscapeSequence("Invalid escape sequence: '\\' at end of string."); } } else { result[pos++] = (byte) c; } } return ByteString.copyFrom(result, 0, pos); } /** * Thrown by {@link JsonFormat#unescapeBytes} and {@link JsonFormat#unescapeText} when an * invalid escape sequence is seen. */ static class InvalidEscapeSequence extends IOException { private static final long serialVersionUID = 1L; public InvalidEscapeSequence(String description) { super(description); } } /** * Implements JSON string escaping as specified <a href="http://www.ietf.org/rfc/rfc4627.txt">here</a>. * <ul> * <li>The following characters are escaped by prefixing them with a '\' : \b,\f,\n,\r,\t,\,"</li> * <li>Other control characters in the range 0x0000-0x001F are escaped using the \\uXXXX notation</li> * <li>UTF-16 surrogate pairs are encoded using the \\uXXXX\\uXXXX notation</li> * <li>any other character is printed as-is</li> * </ul> */ static String escapeText(String input) { StringBuilder builder = new StringBuilder(input.length()); CharacterIterator iter = new StringCharacterIterator(input); for(char c = iter.first(); c != CharacterIterator.DONE; c = iter.next()) { switch(c) { case '\b': builder.append("\\b"); break; case '\f': builder.append("\\f"); break; case '\n': builder.append("\\n"); break; case '\r': builder.append("\\r"); break; case '\t': builder.append("\\t"); break; case '\\': builder.append("\\\\"); break; case '"': builder.append("\\\""); break; default: // Check for other control characters if(c >= 0x0000 && c <= 0x001F) { appendEscapedUnicode(builder, c); } else if(Character.isHighSurrogate(c)) { // Encode the surrogate pair using 2 six-character sequence (\\uXXXX\\uXXXX) appendEscapedUnicode(builder, c); c = iter.next(); if(c == CharacterIterator.DONE) throw new IllegalArgumentException("invalid unicode string: unexpected high surrogate pair value without corresponding low value."); appendEscapedUnicode(builder, c); } else { // Anything else can be printed as-is builder.append(c); } break; } } return builder.toString(); } static void appendEscapedUnicode(StringBuilder builder, char ch) { String prefix = "\\u"; if(ch < 0x10) { prefix = "\\u000"; } else if(ch < 0x100) { prefix = "\\u00"; } else if(ch < 0x1000) { prefix = "\\u0"; } builder.append(prefix).append(Integer.toHexString(ch)); } /** * Un-escape a text string as escaped using {@link #escapeText(String)}. */ static String unescapeText(String input) throws InvalidEscapeSequence { StringBuilder builder = new StringBuilder(); char[] array = input.toCharArray(); for(int i = 0; i < array.length; i++) { char c = array[i]; if(c == '\\') { if(i + 1 < array.length) { ++i; c = array[i]; switch(c) { case 'b': builder.append('\b'); break; case 'f': builder.append('\f'); break; case 'n': builder.append('\n'); break; case 'r': builder.append('\r'); break; case 't': builder.append('\t'); break; case '\\': builder.append('\\'); break; case '"': builder.append('\"'); break; case '\'': builder.append('\''); break; case 'u': // read the next 4 chars if(i + 4 < array.length) { ++i; int code = Integer.parseInt(new String(array, i, 4), 16); // this cast is safe because we know how many chars we read builder.append((char)code); i += 3; } else { throw new InvalidEscapeSequence("Invalid escape sequence: '\\u' at end of string."); } break; default: throw new InvalidEscapeSequence("Invalid escape sequence: '\\" + c + "'"); } } else { throw new InvalidEscapeSequence("Invalid escape sequence: '\\' at end of string."); } } else { builder.append(c); } } return builder.toString(); } /** * Parse a 32-bit signed integer from the text. Unlike the Java standard {@code * Integer.parseInt()}, this function recognizes the prefixes "0x" and "0" to signify * hexidecimal and octal numbers, respectively. */ static int parseInt32(String text) throws NumberFormatException { return (int) parseInteger(text, true, false); } /** * Parse a 32-bit unsigned integer from the text. Unlike the Java standard {@code * Integer.parseInt()}, this function recognizes the prefixes "0x" and "0" to signify * hexidecimal and octal numbers, respectively. The result is coerced to a (signed) {@code int} * when returned since Java has no unsigned integer type. */ static int parseUInt32(String text) throws NumberFormatException { return (int) parseInteger(text, false, false); } /** * Parse a 64-bit signed integer from the text. Unlike the Java standard {@code * Integer.parseInt()}, this function recognizes the prefixes "0x" and "0" to signify * hexidecimal and octal numbers, respectively. */ static long parseInt64(String text) throws NumberFormatException { return parseInteger(text, true, true); } /** * Parse a 64-bit unsigned integer from the text. Unlike the Java standard {@code * Integer.parseInt()}, this function recognizes the prefixes "0x" and "0" to signify * hexidecimal and octal numbers, respectively. The result is coerced to a (signed) {@code long} * when returned since Java has no unsigned long type. */ static long parseUInt64(String text) throws NumberFormatException { return parseInteger(text, false, true); } private static long parseInteger(String text, boolean isSigned, boolean isLong) throws NumberFormatException { int pos = 0; boolean negative = false; if (text.startsWith("-", pos)) { if (!isSigned) { throw new NumberFormatException("Number must be positive: " + text); } ++pos; negative = true; } int radix = 10; if (text.startsWith("0x", pos)) { pos += 2; radix = 16; } else if (text.startsWith("0", pos)) { radix = 8; } String numberText = prepareNumberFromString(text.substring(pos)); long result = 0; if (numberText.length() < 16) { // Can safely assume no overflow. result = Long.parseLong(numberText, radix); if (negative) { result = -result; } // Check bounds. // No need to check for 64-bit numbers since they'd have to be 16 chars // or longer to overflow. if (!isLong) { if (isSigned) { if ((result > Integer.MAX_VALUE) || (result < Integer.MIN_VALUE)) { throw new NumberFormatException("Number out of range for 32-bit signed integer: " + text); } } else { if ((result >= (1L << 32)) || (result < 0)) { throw new NumberFormatException("Number out of range for 32-bit unsigned integer: " + text); } } } } else { BigInteger bigValue = new BigInteger(numberText, radix); if (negative) { bigValue = bigValue.negate(); } // Check bounds. if (!isLong) { if (isSigned) { if (bigValue.bitLength() > 31) { throw new NumberFormatException("Number out of range for 32-bit signed integer: " + text); } } else { if (bigValue.bitLength() > 32) { throw new NumberFormatException("Number out of range for 32-bit unsigned integer: " + text); } } } else { if (isSigned) { if (bigValue.bitLength() > 63) { throw new NumberFormatException("Number out of range for 64-bit signed integer: " + text); } } else { if (bigValue.bitLength() > 64) { throw new NumberFormatException("Number out of range for 64-bit unsigned integer: " + text); } } } result = bigValue.longValue(); } return result; } /** * Accept "" empty string * and number in quote "6" as number */ private static String prepareNumberFromString(String numberText) { numberText = numberText.replaceAll("\"", ""); if (numberText.equals("")) { numberText = "0"; // default value } return numberText; } }
src/main/java/com/googlecode/protobuf/format/JsonFormat.java
package com.googlecode.protobuf.format; /* Copyright (c) 2009, Orbitz World Wide All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Orbitz World Wide nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import java.io.IOException; import java.math.BigInteger; import java.nio.CharBuffer; import java.text.CharacterIterator; import java.text.StringCharacterIterator; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.protobuf.ByteString; import com.google.protobuf.ExtensionRegistry; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.Message; import com.google.protobuf.UnknownFieldSet; import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.EnumDescriptor; import com.google.protobuf.Descriptors.EnumValueDescriptor; import com.google.protobuf.Descriptors.FieldDescriptor; import com.googlecode.protobuf.format.util.IDUtil; import com.googlecode.protobuf.format.util.TextUtils; import static com.googlecode.protobuf.format.util.TextUtils.*; /** * Provide ascii text parsing and formatting support for proto2 instances. The implementation * largely follows google/protobuf/text_format.cc. * <p> * (c) 2009-10 Orbitz World Wide. All Rights Reserved. * * @author [email protected] Eliran Bivas * @author [email protected] Alex Antonov * <p/> * Based on the original code by: * @author [email protected] Wenbo Zhu * @author [email protected] Kenton Varda */ public class JsonFormat extends AbstractCharBasedFormatter { /** * Outputs a textual representation of the Protocol Message supplied into the parameter output. * (This representation is the new version of the classic "ProtocolPrinter" output from the * original Protocol Buffer system) */ public void print(final Message message, Appendable output) throws IOException { JsonGenerator generator = new JsonGenerator(output); generator.print("{"); print(message, generator); generator.print("}"); } /** * Outputs a textual representation of {@code fields} to {@code output}. */ public void print(final UnknownFieldSet fields, Appendable output) throws IOException { JsonGenerator generator = new JsonGenerator(output); generator.print("{"); printUnknownFields(fields, generator); generator.print("}"); } protected void print(Message message, JsonGenerator generator) throws IOException { for (Iterator<Map.Entry<FieldDescriptor, Object>> iter = message.getAllFields().entrySet().iterator(); iter.hasNext();) { Map.Entry<FieldDescriptor, Object> field = iter.next(); printField(field.getKey(), field.getValue(), generator); if (iter.hasNext()) { generator.print(","); } } if (message.getUnknownFields().asMap().size() > 0) generator.print(", "); printUnknownFields(message.getUnknownFields(), generator); } public void printField(FieldDescriptor field, Object value, JsonGenerator generator) throws IOException { printSingleField(field, value, generator); } private void printSingleField(FieldDescriptor field, Object value, JsonGenerator generator) throws IOException { if (field.isExtension()) { generator.print("\""); // We special-case MessageSet elements for compatibility with proto1. if (field.getContainingType().getOptions().getMessageSetWireFormat() && (field.getType() == FieldDescriptor.Type.MESSAGE) && (field.isOptional()) // object equality && (field.getExtensionScope() == field.getMessageType())) { generator.print(field.getMessageType().getFullName()); } else { generator.print(field.getFullName()); } generator.print("\""); } else { generator.print("\""); if (field.getType() == FieldDescriptor.Type.GROUP) { // Groups must be serialized with their original capitalization. generator.print(field.getMessageType().getName()); } else { generator.print(field.getName()); } generator.print("\""); } // Done with the name, on to the value if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { generator.print(": "); generator.indent(); } else { generator.print(": "); } if (field.isRepeated()) { // Repeated field. Print each element. generator.print("["); for (Iterator<?> iter = ((List<?>) value).iterator(); iter.hasNext();) { printFieldValue(field, iter.next(), generator); if (iter.hasNext()) { generator.print(","); } } generator.print("]"); } else { printFieldValue(field, value, generator); if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { generator.outdent(); } } } private void printFieldValue(FieldDescriptor field, Object value, JsonGenerator generator) throws IOException { switch (field.getType()) { case INT32: case INT64: case SINT32: case SINT64: case SFIXED32: case SFIXED64: case FLOAT: case DOUBLE: case BOOL: // Good old toString() does what we want for these types. generator.print(value.toString()); break; case UINT32: case FIXED32: generator.print(unsignedToString((Integer) value)); break; case UINT64: case FIXED64: generator.print(unsignedToString((Long) value)); break; case STRING: generator.print("\""); generator.print(escapeText((String) value)); generator.print("\""); break; case BYTES: { generator.print("\""); ByteString byteString = (ByteString) value; if(IDUtil.isValidID(byteString)){ generator.print(IDUtil.bytes2HexString(byteString.toByteArray())); }else{ generator.print(bytesToHexString((ByteString) value)); } generator.print("\""); break; } case ENUM: { generator.print("\""); generator.print(((EnumValueDescriptor) value).getName()); generator.print("\""); break; } case MESSAGE: case GROUP: generator.print("{"); print((Message) value, generator); generator.print("}"); break; } } protected void printUnknownFields(UnknownFieldSet unknownFields, JsonGenerator generator) throws IOException { boolean firstField = true; for (Map.Entry<Integer, UnknownFieldSet.Field> entry : unknownFields.asMap().entrySet()) { UnknownFieldSet.Field field = entry.getValue(); if (firstField) {firstField = false;} else {generator.print(", ");} generator.print("\""); generator.print(entry.getKey().toString()); generator.print("\""); generator.print(": ["); boolean firstValue = true; for (long value : field.getVarintList()) { if (firstValue) {firstValue = false;} else {generator.print(", ");} generator.print(unsignedToString(value)); } for (int value : field.getFixed32List()) { if (firstValue) {firstValue = false;} else {generator.print(", ");} generator.print(String.format((Locale) null, "0x%08x", value)); } for (long value : field.getFixed64List()) { if (firstValue) {firstValue = false;} else {generator.print(", ");} generator.print(String.format((Locale) null, "0x%016x", value)); } for (ByteString value : field.getLengthDelimitedList()) { if (firstValue) {firstValue = false;} else {generator.print(", ");} generator.print("\""); generator.print(escapeBytes(value)); generator.print("\""); } for (UnknownFieldSet value : field.getGroupList()) { if (firstValue) {firstValue = false;} else {generator.print(", ");} generator.print("{"); printUnknownFields(value, generator); generator.print("}"); } generator.print("]"); } } /** * An inner class for writing text to the output stream. */ protected static class JsonGenerator { Appendable output; boolean atStartOfLine = true; StringBuilder indent = new StringBuilder(); public JsonGenerator(Appendable output) { this.output = output; } /** * Indent text by two spaces. After calling Indent(), two spaces will be inserted at the * beginning of each line of text. Indent() may be called multiple times to produce deeper * indents. */ public void indent() { indent.append(" "); } /** * Reduces the current indent level by two spaces, or crashes if the indent level is zero. */ public void outdent() { int length = indent.length(); if (length == 0) { throw new IllegalArgumentException(" Outdent() without matching Indent()."); } indent.delete(length - 2, length); } /** * Print text to the output stream. */ public void print(CharSequence text) throws IOException { int size = text.length(); int pos = 0; for (int i = 0; i < size; i++) { if (text.charAt(i) == '\n') { write(text.subSequence(pos, size), i - pos + 1); pos = i + 1; atStartOfLine = true; } } write(text.subSequence(pos, size), size - pos); } private void write(CharSequence data, int size) throws IOException { if (size == 0) { return; } if (atStartOfLine) { atStartOfLine = false; output.append(indent); } output.append(data); } } // ================================================================= // Parsing /** * Represents a stream of tokens parsed from a {@code String}. * <p/> * <p> * The Java standard library provides many classes that you might think would be useful for * implementing this, but aren't. For example: * <p/> * <ul> * <li>{@code java.io.StreamTokenizer}: This almost does what we want -- or, at least, something * that would get us close to what we want -- except for one fatal flaw: It automatically * un-escapes strings using Java escape sequences, which do not include all the escape sequences * we need to support (e.g. '\x'). * <li>{@code java.util.Scanner}: This seems like a great way at least to parse regular * expressions out of a stream (so we wouldn't have to load the entire input into a single * string before parsing). Sadly, {@code Scanner} requires that tokens be delimited with some * delimiter. Thus, although the text "foo:" should parse to two tokens ("foo" and ":"), {@code * Scanner} would recognize it only as a single token. Furthermore, {@code Scanner} provides no * way to inspect the contents of delimiters, making it impossible to keep track of line and * column numbers. * </ul> * <p/> * <p> * Luckily, Java's regular expression support does manage to be useful to us. (Barely: We need * {@code Matcher.usePattern()}, which is new in Java 1.5.) So, we can use that, at least. * Unfortunately, this implies that we need to have the entire input in one contiguous string. */ protected static class Tokenizer { private final CharSequence text; private final Matcher matcher; private String currentToken; // The character index within this.text at which the current token begins. private int pos = 0; // The line and column numbers of the current token. private int line = 0; private int column = 0; // The line and column numbers of the previous token (allows throwing // errors *after* consuming). private int previousLine = 0; private int previousColumn = 0; // We use possesive quantifiers (*+ and ++) because otherwise the Java // regex matcher has stack overflows on large inputs. private static final Pattern WHITESPACE = Pattern.compile("(\\s|(#.*$))++", Pattern.MULTILINE); private static final Pattern TOKEN = Pattern.compile( "[a-zA-Z_][0-9a-zA-Z_+-]*+|" + // an identifier "[.]?[0-9+-][0-9a-zA-Z_.+-]*+|" + // a number "\"([^\"\n\\\\]|\\\\.)*+(\"|\\\\?$)|" + // a double-quoted string "\'([^\'\n\\\\]|\\\\.)*+(\'|\\\\?$)", // a single-quoted string Pattern.MULTILINE); private static final Pattern DOUBLE_INFINITY = Pattern.compile( "-?inf(inity)?", Pattern.CASE_INSENSITIVE); private static final Pattern FLOAT_INFINITY = Pattern.compile( "-?inf(inity)?f?", Pattern.CASE_INSENSITIVE); private static final Pattern FLOAT_NAN = Pattern.compile( "nanf?", Pattern.CASE_INSENSITIVE); /** * Construct a tokenizer that parses tokens from the given text. */ public Tokenizer(CharSequence text) { this.text = text; matcher = WHITESPACE.matcher(text); skipWhitespace(); nextToken(); } /** * Are we at the end of the input? */ public boolean atEnd() { return currentToken.length() == 0; } /** * Advance to the next token. */ public void nextToken() { previousLine = line; previousColumn = column; // Advance the line counter to the current position. while (pos < matcher.regionStart()) { if (text.charAt(pos) == '\n') { ++line; column = 0; } else { ++column; } ++pos; } // Match the next token. if (matcher.regionStart() == matcher.regionEnd()) { // EOF currentToken = ""; } else { matcher.usePattern(TOKEN); if (matcher.lookingAt()) { currentToken = matcher.group(); matcher.region(matcher.end(), matcher.regionEnd()); } else { // Take one character. currentToken = String.valueOf(text.charAt(pos)); matcher.region(pos + 1, matcher.regionEnd()); } skipWhitespace(); } } /** * Skip over any whitespace so that the matcher region starts at the next token. */ private void skipWhitespace() { matcher.usePattern(WHITESPACE); if (matcher.lookingAt()) { matcher.region(matcher.end(), matcher.regionEnd()); } } /** * If the next token exactly matches {@code token}, consume it and return {@code true}. * Otherwise, return {@code false} without doing anything. */ public boolean tryConsume(String token) { if (currentToken.equals(token)) { nextToken(); return true; } else { return false; } } /** * If the next token exactly matches {@code token}, consume it. Otherwise, throw a * {@link ParseException}. */ public void consume(String token) throws ParseException { if (!tryConsume(token)) { throw parseException("Expected \"" + token + "\"."); } } /** * Returns {@code true} if the next token is an float, but does not consume it. */ public boolean lookingAtFloat() { return lookingAtInteger() && currentToken.contains("."); } /** * Returns {@code true} if the next token is an integer, but does not consume it. */ public boolean lookingAtInteger() { if (currentToken.length() == 0) { return false; } char c = currentToken.charAt(0); return (('0' <= c) && (c <= '9')) || (c == '-') || (c == '+'); } /** * Returns {@code true} if the next token is a boolean (true/false), but does not consume it. */ public boolean lookingAtBoolean() { if (currentToken.length() == 0) { return false; } return ("true".equals(currentToken) || "false".equals(currentToken)); } /** * @return currentToken to which the Tokenizer is pointing. */ public String currentToken() { return currentToken; } /** * If the next token is an identifier, consume it and return its value. Otherwise, throw a * {@link ParseException}. */ public String consumeIdentifier() throws ParseException { for (int i = 0; i < currentToken.length(); i++) { char c = currentToken.charAt(i); if ((('a' <= c) && (c <= 'z')) || (('A' <= c) && (c <= 'Z')) || (('0' <= c) && (c <= '9')) || (c == '_') || (c == '.') || (c == '"')) { // OK } else { throw parseException("Expected identifier. -" + c); } } String result = currentToken; // Need to clean-up result to remove quotes of any kind result = result.replaceAll("\"|'", ""); nextToken(); return result; } /** * If the next token is a 32-bit signed integer, consume it and return its value. Otherwise, * throw a {@link ParseException}. */ public int consumeInt32() throws ParseException { try { int result = parseInt32(currentToken); nextToken(); return result; } catch (NumberFormatException e) { throw integerParseException(e); } } /** * If the next token is a 32-bit unsigned integer, consume it and return its value. * Otherwise, throw a {@link ParseException}. */ public int consumeUInt32() throws ParseException { try { int result = parseUInt32(currentToken); nextToken(); return result; } catch (NumberFormatException e) { throw integerParseException(e); } } /** * If the next token is a 64-bit signed integer, consume it and return its value. Otherwise, * throw a {@link ParseException}. */ public long consumeInt64() throws ParseException { try { long result = parseInt64(currentToken); nextToken(); return result; } catch (NumberFormatException e) { throw integerParseException(e); } } /** * If the next token is a 64-bit unsigned integer, consume it and return its value. * Otherwise, throw a {@link ParseException}. */ public long consumeUInt64() throws ParseException { try { long result = parseUInt64(currentToken); nextToken(); return result; } catch (NumberFormatException e) { throw integerParseException(e); } } /** * If the next token is a double, consume it and return its value. Otherwise, throw a * {@link ParseException}. */ public double consumeDouble() throws ParseException { // We need to parse infinity and nan separately because // Double.parseDouble() does not accept "inf", "infinity", or "nan". if (DOUBLE_INFINITY.matcher(currentToken).matches()) { boolean negative = currentToken.startsWith("-"); nextToken(); return negative ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY; } if (currentToken.equalsIgnoreCase("nan")) { nextToken(); return Double.NaN; } try { double result = Double.parseDouble(prepareNumberFromString(currentToken)); nextToken(); return result; } catch (NumberFormatException e) { throw floatParseException(e); } } /** * If the next token is a float, consume it and return its value. Otherwise, throw a * {@link ParseException}. */ public float consumeFloat() throws ParseException { // We need to parse infinity and nan separately because // Float.parseFloat() does not accept "inf", "infinity", or "nan". if (FLOAT_INFINITY.matcher(currentToken).matches()) { boolean negative = currentToken.startsWith("-"); nextToken(); return negative ? Float.NEGATIVE_INFINITY : Float.POSITIVE_INFINITY; } if (FLOAT_NAN.matcher(currentToken).matches()) { nextToken(); return Float.NaN; } try { float result = Float.parseFloat(prepareNumberFromString(currentToken)); nextToken(); return result; } catch (NumberFormatException e) { throw floatParseException(e); } } /** * If the next token is a boolean, consume it and return its value. Otherwise, throw a * {@link ParseException}. */ public boolean consumeBoolean() throws ParseException { if (currentToken.equals("true")) { nextToken(); return true; } else if (currentToken.equals("false")) { nextToken(); return false; } else { throw parseException("Expected \"true\" or \"false\"."); } } /** * If the next token is a string, consume it and return its (unescaped) value. Otherwise, * throw a {@link ParseException}. */ public String consumeString() throws ParseException { char quote = currentToken.length() > 0 ? currentToken.charAt(0) : '\0'; if ((quote != '\"') && (quote != '\'')) { try { String result = currentToken.replace(',', '.'); Double.parseDouble(result); nextToken(); return result; } catch (NumberFormatException e) { throw parseException("Expected string."); } } if ((currentToken.length() < 2) || (currentToken.charAt(currentToken.length() - 1) != quote)) { throw parseException("String missing ending quote."); } try { String escaped = currentToken.substring(1, currentToken.length() - 1); String result = unescapeText(escaped); nextToken(); return result; } catch (InvalidEscapeSequence e) { throw parseException(e.getMessage()); } } /** * If the next token is a string, consume it, unescape it as a * {@link com.googlecode.protobuf.format.ByteString}, and return it. Otherwise, throw a * {@link ParseException}. */ public ByteString consumeByteString() throws ParseException { char quote = currentToken.length() > 0 ? currentToken.charAt(0) : '\0'; if ((quote != '\"') && (quote != '\'')) { throw parseException("Expected string."); } if ((currentToken.length() < 2) || (currentToken.charAt(currentToken.length() - 1) != quote)) { throw parseException("String missing ending quote."); } try { String escaped = currentToken.substring(1, currentToken.length() - 1); ByteString result = unescapeBytes(escaped); nextToken(); return result; } catch (InvalidEscapeSequence e) { throw parseException(e.getMessage()); } } /** * Returns a {@link ParseException} with the current line and column numbers in the * description, suitable for throwing. */ public ParseException parseException(String description) { // Note: People generally prefer one-based line and column numbers. return new ParseException((line + 1) + ":" + (column + 1) + ": " + description); } /** * Returns a {@link ParseException} with the line and column numbers of the previous token * in the description, suitable for throwing. */ public ParseException parseExceptionPreviousToken(String description) { // Note: People generally prefer one-based line and column numbers. return new ParseException((previousLine + 1) + ":" + (previousColumn + 1) + ": " + description); } /** * Constructs an appropriate {@link ParseException} for the given {@code * NumberFormatException} when trying to parse an integer. */ private ParseException integerParseException(NumberFormatException e) { return parseException("Couldn't parse integer: " + e.getMessage()); } /** * Constructs an appropriate {@link ParseException} for the given {@code * NumberFormatException} when trying to parse a float or double. */ private ParseException floatParseException(NumberFormatException e) { return parseException("Couldn't parse number: " + e.getMessage()); } } /** * Thrown when parsing an invalid text format message. */ public static class ParseException extends IOException { private static final long serialVersionUID = 1L; public ParseException(String message) { super(message); } } /** * Parse a text-format message from {@code input} and merge the contents into {@code builder}. * Extensions will be recognized if they are registered in {@code extensionRegistry}. */ public void merge(CharSequence input, ExtensionRegistry extensionRegistry, Message.Builder builder) throws ParseException { Tokenizer tokenizer = new Tokenizer(input); // Based on the state machine @ http://json.org/ tokenizer.consume("{"); // Needs to happen when the object starts. while (!tokenizer.tryConsume("}")) { // Continue till the object is done mergeField(tokenizer, extensionRegistry, builder); } // Test to make sure the tokenizer has reached the end of the stream. if (!tokenizer.atEnd()) { throw tokenizer.parseException("Expecting the end of the stream, but there seems to be more data! Check the input for a valid JSON format."); } } /** * Parse a single field from {@code tokenizer} and merge it into {@code builder}. If a ',' is * detected after the field ends, the next field will be parsed automatically */ protected void mergeField(Tokenizer tokenizer, ExtensionRegistry extensionRegistry, Message.Builder builder) throws ParseException { FieldDescriptor field; Descriptor type = builder.getDescriptorForType(); ExtensionRegistry.ExtensionInfo extension = null; boolean unknown = false; String name = tokenizer.consumeIdentifier(); field = type.findFieldByName(name); // Group names are expected to be capitalized as they appear in the // .proto file, which actually matches their type names, not their field // names. if (field == null) { // Explicitly specify US locale so that this code does not break when // executing in Turkey. String lowerName = name.toLowerCase(Locale.US); field = type.findFieldByName(lowerName); // If the case-insensitive match worked but the field is NOT a group, if ((field != null) && (field.getType() != FieldDescriptor.Type.GROUP)) { field = null; } } // Again, special-case group names as described above. if ((field != null) && (field.getType() == FieldDescriptor.Type.GROUP) && !field.getMessageType().getName().equals(name)) { field = null; } // Last try to lookup by field-index if 'name' is numeric, // which indicates a possible unknown field if (field == null && TextUtils.isDigits(name)) { field = type.findFieldByNumber(Integer.parseInt(name)); unknown = true; } // Finally, look for extensions extension = extensionRegistry.findExtensionByName(name); if (extension != null) { if (extension.descriptor.getContainingType() != type) { throw tokenizer.parseExceptionPreviousToken("Extension \"" + name + "\" does not extend message type \"" + type.getFullName() + "\"."); } field = extension.descriptor; } // Disabled throwing exception if field not found, since it could be a different version. if (field == null) { handleMissingField(tokenizer, extensionRegistry, builder); //throw tokenizer.parseExceptionPreviousToken("Message type \"" + type.getFullName() // + "\" has no field named \"" + name // + "\"."); } if (field != null) { tokenizer.consume(":"); boolean array = tokenizer.tryConsume("["); if (array) { while (!tokenizer.tryConsume("]")) { handleValue(tokenizer, extensionRegistry, builder, field, extension, unknown); tokenizer.tryConsume(","); } } else { handleValue(tokenizer, extensionRegistry, builder, field, extension, unknown); } } if (tokenizer.tryConsume(",")) { // Continue with the next field mergeField(tokenizer, extensionRegistry, builder); } } private void handleMissingField(Tokenizer tokenizer, ExtensionRegistry extensionRegistry, Message.Builder builder) throws ParseException { tokenizer.tryConsume(":"); if ("{".equals(tokenizer.currentToken())) { // Message structure tokenizer.consume("{"); do { tokenizer.consumeIdentifier(); handleMissingField(tokenizer, extensionRegistry, builder); } while (tokenizer.tryConsume(",")); tokenizer.consume("}"); } else if ("[".equals(tokenizer.currentToken())) { // Collection tokenizer.consume("["); do { handleMissingField(tokenizer, extensionRegistry, builder); } while (tokenizer.tryConsume(",")); tokenizer.consume("]"); } else { //if (!",".equals(tokenizer.currentToken)){ // Primitive value if ("null".equals(tokenizer.currentToken())) { tokenizer.consume("null"); } else if (tokenizer.lookingAtFloat()) { tokenizer.consumeFloat(); } else if (tokenizer.lookingAtInteger()) { tokenizer.consumeInt64(); } else if (tokenizer.lookingAtBoolean()) { tokenizer.consumeBoolean(); } else { tokenizer.consumeString(); } } } private void handleValue(Tokenizer tokenizer, ExtensionRegistry extensionRegistry, Message.Builder builder, FieldDescriptor field, ExtensionRegistry.ExtensionInfo extension, boolean unknown) throws ParseException { Object value = null; if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { value = handleObject(tokenizer, extensionRegistry, builder, field, extension, unknown); } else { value = handlePrimitive(tokenizer, field); } if (value != null) { if (field.isRepeated()) { builder.addRepeatedField(field, value); } else { builder.setField(field, value); } } } private Object handlePrimitive(Tokenizer tokenizer, FieldDescriptor field) throws ParseException { Object value = null; if ("null".equals(tokenizer.currentToken())) { tokenizer.consume("null"); return value; } switch (field.getType()) { case INT32: case SINT32: case SFIXED32: value = tokenizer.consumeInt32(); break; case INT64: case SINT64: case SFIXED64: value = tokenizer.consumeInt64(); break; case UINT32: case FIXED32: value = tokenizer.consumeUInt32(); break; case UINT64: case FIXED64: value = tokenizer.consumeUInt64(); break; case FLOAT: value = tokenizer.consumeFloat(); break; case DOUBLE: value = tokenizer.consumeDouble(); break; case BOOL: value = tokenizer.consumeBoolean(); break; case STRING: value = tokenizer.consumeString(); break; case BYTES: value = tokenizer.consumeByteString(); break; case ENUM: { EnumDescriptor enumType = field.getEnumType(); if (tokenizer.lookingAtInteger()) { int number = tokenizer.consumeInt32(); value = enumType.findValueByNumber(number); if (value == null) { throw tokenizer.parseExceptionPreviousToken("Enum type \"" + enumType.getFullName() + "\" has no value with number " + number + "."); } } else { String id = tokenizer.consumeIdentifier(); value = enumType.findValueByName(id); if (value == null) { throw tokenizer.parseExceptionPreviousToken("Enum type \"" + enumType.getFullName() + "\" has no value named \"" + id + "\"."); } } break; } case MESSAGE: case GROUP: throw new RuntimeException("Can't get here."); } return value; } private Object handleObject(Tokenizer tokenizer, ExtensionRegistry extensionRegistry, Message.Builder builder, FieldDescriptor field, ExtensionRegistry.ExtensionInfo extension, boolean unknown) throws ParseException { Message.Builder subBuilder; if (extension == null) { subBuilder = builder.newBuilderForField(field); } else { subBuilder = extension.defaultInstance.newBuilderForType(); } if (unknown) { ByteString data = tokenizer.consumeByteString(); try { subBuilder.mergeFrom(data); return subBuilder.build(); } catch (InvalidProtocolBufferException e) { throw tokenizer.parseException("Failed to build " + field.getFullName() + " from " + data); } } tokenizer.consume("{"); String endToken = "}"; while (!tokenizer.tryConsume(endToken)) { if (tokenizer.atEnd()) { throw tokenizer.parseException("Expected \"" + endToken + "\"."); } mergeField(tokenizer, extensionRegistry, subBuilder); if (tokenizer.tryConsume(",")) { // there are more fields in the object, so continue continue; } } return subBuilder.build(); } // ================================================================= // Utility functions // // Some of these methods are package-private because Descriptors.java uses // them. /** * Escapes bytes in the format used in protocol buffer text format, which is the same as the * format used for C string literals. All bytes that are not printable 7-bit ASCII characters * are escaped, as well as backslash, single-quote, and double-quote characters. Characters for * which no defined short-hand escape sequence is defined will be escaped using 3-digit octal * sequences. */ static String escapeBytes(ByteString input) { StringBuilder builder = new StringBuilder(input.size()); for (int i = 0; i < input.size(); i++) { byte b = input.byteAt(i); switch (b) { // Java does not recognize \a or \v, apparently. case 0x07: builder.append("\\a"); break; case '\b': builder.append("\\b"); break; case '\f': builder.append("\\f"); break; case '\n': builder.append("\\n"); break; case '\r': builder.append("\\r"); break; case '\t': builder.append("\\t"); break; case 0x0b: builder.append("\\v"); break; case '\\': builder.append("\\\\"); break; case '\'': builder.append("\\\'"); break; case '"': builder.append("\\\""); break; default: if (b >= 0x20) { builder.append((char) b); } else { final String unicodeString = unicodeEscaped((char) b); builder.append(unicodeString); } break; } } return builder.toString(); } static String bytesToHexString(ByteString input){ if(input == null){ return null; } return IDUtil.bytes2HexString(input.toByteArray()); } static String unicodeEscaped(char ch) { if (ch < 0x10) { return "\\u000" + Integer.toHexString(ch); } else if (ch < 0x100) { return "\\u00" + Integer.toHexString(ch); } else if (ch < 0x1000) { return "\\u0" + Integer.toHexString(ch); } return "\\u" + Integer.toHexString(ch); } /** * Un-escape a byte sequence as escaped using * {@link #escapeBytes(com.googlecode.protobuf.format.ByteString)}. Two-digit hex escapes (starting with * "\x") are also recognized. */ static ByteString unescapeBytes(CharSequence input) throws InvalidEscapeSequence { byte[] result = new byte[input.length()]; int pos = 0; for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); if (c == '\\') { if (i + 1 < input.length()) { ++i; c = input.charAt(i); if (isOctal(c)) { // Octal escape. int code = digitValue(c); if ((i + 1 < input.length()) && isOctal(input.charAt(i + 1))) { ++i; code = code * 8 + digitValue(input.charAt(i)); } if ((i + 1 < input.length()) && isOctal(input.charAt(i + 1))) { ++i; code = code * 8 + digitValue(input.charAt(i)); } result[pos++] = (byte) code; } else { switch (c) { case 'a': result[pos++] = 0x07; break; case 'b': result[pos++] = '\b'; break; case 'f': result[pos++] = '\f'; break; case 'n': result[pos++] = '\n'; break; case 'r': result[pos++] = '\r'; break; case 't': result[pos++] = '\t'; break; case 'v': result[pos++] = 0x0b; break; case '\\': result[pos++] = '\\'; break; case '\'': result[pos++] = '\''; break; case '"': result[pos++] = '\"'; break; case 'x': // hex escape int code = 0; if ((i + 1 < input.length()) && isHex(input.charAt(i + 1))) { ++i; code = digitValue(input.charAt(i)); } else { throw new InvalidEscapeSequence("Invalid escape sequence: '\\x' with no digits"); } if ((i + 1 < input.length()) && isHex(input.charAt(i + 1))) { ++i; code = code * 16 + digitValue(input.charAt(i)); } result[pos++] = (byte) code; break; case 'u': // UTF8 escape code = (16 * 3 * digitValue(input.charAt(i+1))) + (16 * 2 * digitValue(input.charAt(i+2))) + (16 * digitValue(input.charAt(i+3))) + digitValue(input.charAt(i+4)); i = i+4; result[pos++] = (byte) code; break; default: throw new InvalidEscapeSequence("Invalid escape sequence: '\\" + c + "'"); } } } else { throw new InvalidEscapeSequence("Invalid escape sequence: '\\' at end of string."); } } else { result[pos++] = (byte) c; } } return ByteString.copyFrom(result, 0, pos); } /** * Thrown by {@link JsonFormat#unescapeBytes} and {@link JsonFormat#unescapeText} when an * invalid escape sequence is seen. */ static class InvalidEscapeSequence extends IOException { private static final long serialVersionUID = 1L; public InvalidEscapeSequence(String description) { super(description); } } /** * Implements JSON string escaping as specified <a href="http://www.ietf.org/rfc/rfc4627.txt">here</a>. * <ul> * <li>The following characters are escaped by prefixing them with a '\' : \b,\f,\n,\r,\t,\,"</li> * <li>Other control characters in the range 0x0000-0x001F are escaped using the \\uXXXX notation</li> * <li>UTF-16 surrogate pairs are encoded using the \\uXXXX\\uXXXX notation</li> * <li>any other character is printed as-is</li> * </ul> */ static String escapeText(String input) { StringBuilder builder = new StringBuilder(input.length()); CharacterIterator iter = new StringCharacterIterator(input); for(char c = iter.first(); c != CharacterIterator.DONE; c = iter.next()) { switch(c) { case '\b': builder.append("\\b"); break; case '\f': builder.append("\\f"); break; case '\n': builder.append("\\n"); break; case '\r': builder.append("\\r"); break; case '\t': builder.append("\\t"); break; case '\\': builder.append("\\\\"); break; case '"': builder.append("\\\""); break; default: // Check for other control characters if(c >= 0x0000 && c <= 0x001F) { appendEscapedUnicode(builder, c); } else if(Character.isHighSurrogate(c)) { // Encode the surrogate pair using 2 six-character sequence (\\uXXXX\\uXXXX) appendEscapedUnicode(builder, c); c = iter.next(); if(c == CharacterIterator.DONE) throw new IllegalArgumentException("invalid unicode string: unexpected high surrogate pair value without corresponding low value."); appendEscapedUnicode(builder, c); } else { // Anything else can be printed as-is builder.append(c); } break; } } return builder.toString(); } static void appendEscapedUnicode(StringBuilder builder, char ch) { String prefix = "\\u"; if(ch < 0x10) { prefix = "\\u000"; } else if(ch < 0x100) { prefix = "\\u00"; } else if(ch < 0x1000) { prefix = "\\u0"; } builder.append(prefix).append(Integer.toHexString(ch)); } /** * Un-escape a text string as escaped using {@link #escapeText(String)}. */ static String unescapeText(String input) throws InvalidEscapeSequence { StringBuilder builder = new StringBuilder(); char[] array = input.toCharArray(); for(int i = 0; i < array.length; i++) { char c = array[i]; if(c == '\\') { if(i + 1 < array.length) { ++i; c = array[i]; switch(c) { case 'b': builder.append('\b'); break; case 'f': builder.append('\f'); break; case 'n': builder.append('\n'); break; case 'r': builder.append('\r'); break; case 't': builder.append('\t'); break; case '\\': builder.append('\\'); break; case '"': builder.append('\"'); break; case '\'': builder.append('\''); break; case 'u': // read the next 4 chars if(i + 4 < array.length) { ++i; int code = Integer.parseInt(new String(array, i, 4), 16); // this cast is safe because we know how many chars we read builder.append((char)code); i += 3; } else { throw new InvalidEscapeSequence("Invalid escape sequence: '\\u' at end of string."); } break; default: throw new InvalidEscapeSequence("Invalid escape sequence: '\\" + c + "'"); } } else { throw new InvalidEscapeSequence("Invalid escape sequence: '\\' at end of string."); } } else { builder.append(c); } } return builder.toString(); } /** * Parse a 32-bit signed integer from the text. Unlike the Java standard {@code * Integer.parseInt()}, this function recognizes the prefixes "0x" and "0" to signify * hexidecimal and octal numbers, respectively. */ static int parseInt32(String text) throws NumberFormatException { return (int) parseInteger(text, true, false); } /** * Parse a 32-bit unsigned integer from the text. Unlike the Java standard {@code * Integer.parseInt()}, this function recognizes the prefixes "0x" and "0" to signify * hexidecimal and octal numbers, respectively. The result is coerced to a (signed) {@code int} * when returned since Java has no unsigned integer type. */ static int parseUInt32(String text) throws NumberFormatException { return (int) parseInteger(text, false, false); } /** * Parse a 64-bit signed integer from the text. Unlike the Java standard {@code * Integer.parseInt()}, this function recognizes the prefixes "0x" and "0" to signify * hexidecimal and octal numbers, respectively. */ static long parseInt64(String text) throws NumberFormatException { return parseInteger(text, true, true); } /** * Parse a 64-bit unsigned integer from the text. Unlike the Java standard {@code * Integer.parseInt()}, this function recognizes the prefixes "0x" and "0" to signify * hexidecimal and octal numbers, respectively. The result is coerced to a (signed) {@code long} * when returned since Java has no unsigned long type. */ static long parseUInt64(String text) throws NumberFormatException { return parseInteger(text, false, true); } private static long parseInteger(String text, boolean isSigned, boolean isLong) throws NumberFormatException { int pos = 0; boolean negative = false; if (text.startsWith("-", pos)) { if (!isSigned) { throw new NumberFormatException("Number must be positive: " + text); } ++pos; negative = true; } int radix = 10; if (text.startsWith("0x", pos)) { pos += 2; radix = 16; } else if (text.startsWith("0", pos)) { radix = 8; } String numberText = prepareNumberFromString(text.substring(pos)); long result = 0; if (numberText.length() < 16) { // Can safely assume no overflow. result = Long.parseLong(numberText, radix); if (negative) { result = -result; } // Check bounds. // No need to check for 64-bit numbers since they'd have to be 16 chars // or longer to overflow. if (!isLong) { if (isSigned) { if ((result > Integer.MAX_VALUE) || (result < Integer.MIN_VALUE)) { throw new NumberFormatException("Number out of range for 32-bit signed integer: " + text); } } else { if ((result >= (1L << 32)) || (result < 0)) { throw new NumberFormatException("Number out of range for 32-bit unsigned integer: " + text); } } } } else { BigInteger bigValue = new BigInteger(numberText, radix); if (negative) { bigValue = bigValue.negate(); } // Check bounds. if (!isLong) { if (isSigned) { if (bigValue.bitLength() > 31) { throw new NumberFormatException("Number out of range for 32-bit signed integer: " + text); } } else { if (bigValue.bitLength() > 32) { throw new NumberFormatException("Number out of range for 32-bit unsigned integer: " + text); } } } else { if (isSigned) { if (bigValue.bitLength() > 63) { throw new NumberFormatException("Number out of range for 64-bit signed integer: " + text); } } else { if (bigValue.bitLength() > 64) { throw new NumberFormatException("Number out of range for 64-bit unsigned integer: " + text); } } } result = bigValue.longValue(); } return result; } /** * Accept "" empty string * and number in quote "6" as number */ private static String prepareNumberFromString(String numberText) { numberText = numberText.replaceAll("\"", ""); if (numberText.equals("")) { numberText = "0"; // default value } return numberText; } }
revert to use default bytestring conversion for non-id fields
src/main/java/com/googlecode/protobuf/format/JsonFormat.java
revert to use default bytestring conversion for non-id fields
<ide><path>rc/main/java/com/googlecode/protobuf/format/JsonFormat.java <ide> if(IDUtil.isValidID(byteString)){ <ide> generator.print(IDUtil.bytes2HexString(byteString.toByteArray())); <ide> }else{ <del> generator.print(bytesToHexString((ByteString) value)); <add> generator.print(escapeBytes((ByteString) value)); <ide> } <ide> generator.print("\""); <ide> break;
Java
apache-2.0
3bc47873f155b31a222cbe4cbf57ca478feb2c55
0
mashrin/processing.py,jdf/processing.py,mashrin/processing.py,jdf/processing.py,mashrin/processing.py,Luxapodular/processing.py,tildebyte/processing.py,tildebyte/processing.py,jdf/processing.py,tildebyte/processing.py,Luxapodular/processing.py,Luxapodular/processing.py
/* * Copyright 2010 Jonathan Feinberg * * 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 jycessing; import java.io.BufferedReader; import java.io.File; import java.io.FileFilter; import java.io.FileReader; import java.io.FilenameFilter; import java.io.IOException; import java.io.Reader; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import org.python.core.Py; import org.python.core.PyString; import org.python.util.InteractiveConsole; import processing.core.PApplet; public class Runner { static boolean VERBOSE = false; // Slurp the given Reader into a String. private static String read(final Reader r) throws IOException { final BufferedReader reader = new BufferedReader(r); final StringBuilder sb = new StringBuilder(1024); String line; try { while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } return sb.toString(); } finally { reader.close(); } } /** * Add a URL (referring to a jar file or class directory) to the current * classloader. Of course, this is a filthy hack, which depends on an * implementation detail (i.e., that the system classloader is a * URLClassLoader). But it certainly works with all known Sun JVMs of recent * vintage, and with OS X's JVMs. * * <p> * See <a href= * "http://robertmaldon.blogspot.com/2007/11/dynamically-add-to-eclipse-junit.html" * >this blog post</a>. * */ private static void addJar(final URL url) throws Exception { final URLClassLoader classLoader = (URLClassLoader) ClassLoader .getSystemClassLoader(); for (final URL u : classLoader.getURLs()) { if (u.equals(url)) { return; } } final Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); method.setAccessible(true); method.invoke(classLoader, new Object[] { url }); if (VERBOSE) { System.err.println("Added " + url + " to classpath."); } } /** * Add the given path to the list of paths searched for DLLs (as in those * loaded by loadLibrary). A hack, which depends on the presence of a * particular field in ClassLoader. Known to work on all recent Sun JVMs and * OS X. * * <p> * See <a href="http://forums.sun.com/thread.jspa?threadID=707176">this * thread</a>. */ private static void addLibraryPath(final String newPath) throws Exception { final Field field = ClassLoader.class.getDeclaredField("usr_paths"); field.setAccessible(true); final String[] paths = (String[]) field.get(null); for (final String path : paths) { if (newPath.equals(path)) { return; } } final String[] tmp = new String[paths.length + 1]; System.arraycopy(paths, 0, tmp, 0, paths.length); tmp[paths.length] = newPath; field.set(null, tmp); if (VERBOSE) { System.err.println("Added " + newPath + " to java.library.path."); } } /** * Recursively search the given directory for jar files and directories * containing dynamic libraries, adding them to the classpath and the * library path respectively. */ private static void searchForExtraStuff(final File dir) throws Exception { final File[] dlls = dir.listFiles(new FilenameFilter() { public boolean accept(final File dir, final String name) { return name.matches("^.+\\.(so|dll|jnilib)$"); } }); if (dlls != null && dlls.length > 0) { addLibraryPath(dir.getAbsolutePath()); } final File[] jars = dir.listFiles(new FilenameFilter() { public boolean accept(final File dir, final String name) { return name.matches("^.+\\.jar$"); } }); for (final File jar : jars) { addJar(jar.toURI().toURL()); } final File[] dirs = dir.listFiles(new FileFilter() { public boolean accept(final File f) { return f.isDirectory() && f.getName().charAt(0) != '.'; } }); for (final File d : dirs) { searchForExtraStuff(d); } } public static void main(final String[] args) throws Exception { if (args.length < 1) { System.err.println("I need the path of your Python script as an argument."); } // -Dverbose=true for some logging VERBOSE = Boolean.getBoolean("verbose"); // The last argument is the path to the Python sketch final String sketchPath = args[args.length - 1]; // This will throw an exception and die if the given file is not there // or not readable. final String sketchSource = read(new FileReader(sketchPath)); runSketch(args, sketchPath, sketchSource); } public static void runSketch(final String[] args, final String sketchPath, final String sketchSource) throws Exception { // Recursively search the "libraries" directory for jar files and // directories containing dynamic libraries, adding them to the // classpath and the library path respectively. searchForExtraStuff(new File("libraries")); Py.initPython(); final InteractiveConsole interp = new InteractiveConsole(); // This hack seems to be necessary in order to redirect stdout for unit // tests interp.setOut(System.out); // Where is the sketch located? final String sketchDir = new File(sketchPath).getCanonicalFile().getParent(); // Tell PApplet to make its home there, so that it can find the data // folder System.setProperty("user.dir", sketchDir); // Add it to the Python library path for auxilliary modules Py.getSystemState().path.insert(0, new PyString(sketchDir)); // For error messages interp.getLocals().__setitem__("__file__", new PyString(sketchPath)); // Bind the sketch to a PApplet final PAppletJythonDriver applet = new DriverImpl(interp, sketchPath, sketchSource); try { PApplet.runSketch(args, applet); } catch (Throwable t) { Py.printException(t); throw new RuntimeException(t); } finally { interp.cleanup(); } } }
src/jycessing/Runner.java
/* * Copyright 2010 Jonathan Feinberg * * 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 jycessing; import java.io.BufferedReader; import java.io.File; import java.io.FileFilter; import java.io.FileReader; import java.io.FilenameFilter; import java.io.IOException; import java.io.Reader; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import org.python.core.Py; import org.python.core.PyString; import org.python.util.InteractiveConsole; import processing.core.PApplet; public class Runner { static boolean VERBOSE = false; // Slurp the given Reader into a String. private static String read(final Reader r) throws IOException { final BufferedReader reader = new BufferedReader(r); final StringBuilder sb = new StringBuilder(1024); String line; try { while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } return sb.toString(); } finally { reader.close(); } } /** * Add a URL (referring to a jar file or class directory) to the current * classloader. Of course, this is a filthy hack, which depends on an * implementation detail (i.e., that the system classloader is a * URLClassLoader). But it certainly works with all known Sun JVMs of recent * vintage, and with OS X's JVMs. * * <p> * See <a href= * "http://robertmaldon.blogspot.com/2007/11/dynamically-add-to-eclipse-junit.html" * >this blog post</a>. * */ private static void addJar(final URL url) throws Exception { final URLClassLoader classLoader = (URLClassLoader) ClassLoader .getSystemClassLoader(); for (final URL u : classLoader.getURLs()) { if (u.equals(url)) { return; } } final Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); method.setAccessible(true); method.invoke(classLoader, new Object[] { url }); if (VERBOSE) { System.err.println("Added " + url + " to classpath."); } } /** * Add the given path to the list of paths searched for DLLs (as in those * loaded by loadLibrary). A hack, which depends on the presence of a * particular field in ClassLoader. Known to work on all recent Sun JVMs and * OS X. * * <p> * See <a href="http://forums.sun.com/thread.jspa?threadID=707176">this * thread</a>. */ private static void addLibraryPath(final String newPath) throws Exception { final Field field = ClassLoader.class.getDeclaredField("usr_paths"); field.setAccessible(true); final String[] paths = (String[]) field.get(null); for (final String path : paths) { if (newPath.equals(path)) { return; } } final String[] tmp = new String[paths.length + 1]; System.arraycopy(paths, 0, tmp, 0, paths.length); tmp[paths.length] = newPath; field.set(null, tmp); if (VERBOSE) { System.err.println("Added " + newPath + " to java.library.path."); } } /** * Recursively search the given directory for jar files and directories * containing dynamic libraries, adding them to the classpath and the * library path respectively. */ private static void searchForExtraStuff(final File dir) throws Exception { final File[] dlls = dir.listFiles(new FilenameFilter() { public boolean accept(final File dir, final String name) { return name.matches("^.+\\.(so|dll|jnilib)$"); } }); if (dlls != null && dlls.length > 0) { addLibraryPath(dir.getAbsolutePath()); } final File[] jars = dir.listFiles(new FilenameFilter() { public boolean accept(final File dir, final String name) { return name.matches("^.+\\.jar$"); } }); for (final File jar : jars) { addJar(jar.toURI().toURL()); } final File[] dirs = dir.listFiles(new FileFilter() { public boolean accept(final File f) { return f.isDirectory() && f.getName().charAt(0) != '.'; } }); for (final File d : dirs) { searchForExtraStuff(d); } } public static void main(final String[] args) throws Exception { if (args.length < 1) { System.err.println("I need the path of your Python script as an argument."); } // -Dverbose=true for some logging VERBOSE = Boolean.getBoolean("verbose"); // The last argument is the path to the Python sketch final String sketchPath = args[args.length - 1]; // This will throw an exception and die if the given file is not there // or not readable. final String sketchSource = read(new FileReader(sketchPath)); runSketch(args, sketchPath, sketchSource); } public static void runSketch(final String[] args, final String sketchPath, final String sketchSource) throws Exception { // Recursively search the "libraries" directory for jar files and // directories containing dynamic libraries, adding them to the // classpath and the library path respectively. searchForExtraStuff(new File("libraries")); Py.initPython(); final InteractiveConsole interp = new InteractiveConsole(); interp.setOut(System.out); // Where is the sketch located? final String sketchDir = new File(sketchPath).getCanonicalFile().getParent(); // Tell PApplet to make its home there, so that it can find the data // folder System.setProperty("user.dir", sketchDir); // Add it to the Python library path for auxilliary modules Py.getSystemState().path.insert(0, new PyString(sketchDir)); // For error messages interp.getLocals().__setitem__("__file__", new PyString(sketchPath)); // Bind the sketch to a PApplet final PAppletJythonDriver applet = new DriverImpl(interp, sketchPath, sketchSource); try { PApplet.runSketch(args, applet); } catch (Throwable t) { Py.printException(t); throw new RuntimeException(t); } finally { // interp.cleanup(); } } }
turn cleanup back on
src/jycessing/Runner.java
turn cleanup back on
<ide><path>rc/jycessing/Runner.java <ide> Py.initPython(); <ide> final InteractiveConsole interp = new InteractiveConsole(); <ide> <add> // This hack seems to be necessary in order to redirect stdout for unit <add> // tests <ide> interp.setOut(System.out); <ide> <ide> // Where is the sketch located? <ide> Py.printException(t); <ide> throw new RuntimeException(t); <ide> } finally { <del> // interp.cleanup(); <add> interp.cleanup(); <ide> } <ide> <ide> }
Java
mit
d0f46992616d91cb6ff3a7d30c79f7abc7cdeacd
0
msigwart/fakeload
package com.martensigwart.fakeload; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; final class MemorySimulator extends AbstractLoadSimulator { private static final Logger log = LoggerFactory.getLogger(MemorySimulator.class); private static final long KB = 1024; private static final long MB = KB*1024; private static final long GB = MB*1024; private long actualLoad; private final List<byte[]> allocatedMemory; MemorySimulator() { super(-1L); this.actualLoad = 0L; this.allocatedMemory = new ArrayList<>(); } @Override void simulateLoad() throws InterruptedException { allocatedMemory.clear(); long loadToAllocate = getLoad(); if (loadToAllocate < Integer.MAX_VALUE) { allocatedMemory.add(new byte[(int)loadToAllocate]); } else { int modulo = Math.toIntExact(loadToAllocate % Integer.MAX_VALUE); int times = Math.toIntExact((loadToAllocate - modulo) / Integer.MAX_VALUE); log.trace("modulo: {}, times: {}", modulo, times); for (int i = 0; i < times; i++) { log.trace("Round {} start", i); allocatedMemory.add(new byte[Integer.MAX_VALUE]); log.trace("Round {} end", i); } log.debug("now adding {} bytes", modulo); allocatedMemory.add(new byte[modulo]); } actualLoad = loadToAllocate; } @Override boolean waitConditionFulfilled() { return (getLoad() == actualLoad); } @Override String prettyFormat(long load) { return mb(load); } private String mb(long bytes) { return String.format("%d (%.2f MB)", bytes, (double)bytes / (MB)); } @Override String idString() { return "Memory Sim - "; } }
src/main/java/com/martensigwart/fakeload/MemorySimulator.java
package com.martensigwart.fakeload; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; public final class MemorySimulator extends AbstractLoadSimulator { private static final Logger log = LoggerFactory.getLogger(MemorySimulator.class); private static final long KB = 1024; private static final long MB = KB*1024; private static final long GB = MB*1024; private long actualLoad; private final List<byte[]> allocatedMemory; MemorySimulator() { super(-1L); this.actualLoad = 0L; this.allocatedMemory = new ArrayList<>(); } @Override void simulateLoad() throws InterruptedException { allocatedMemory.clear(); long loadToAllocate = getLoad(); if (loadToAllocate < Integer.MAX_VALUE) { allocatedMemory.add(new byte[(int)loadToAllocate]); } else { int modulo = Math.toIntExact(loadToAllocate % Integer.MAX_VALUE); int times = Math.toIntExact((loadToAllocate - modulo) / Integer.MAX_VALUE); log.trace("modulo: {}, times: {}", modulo, times); for (int i = 0; i < times; i++) { log.trace("Round {} start", i); allocatedMemory.add(new byte[Integer.MAX_VALUE]); log.trace("Round {} end", i); } log.debug("now adding {} bytes", modulo); allocatedMemory.add(new byte[modulo]); } actualLoad = loadToAllocate; } @Override boolean waitConditionFulfilled() { return (getLoad() == actualLoad); } @Override String prettyFormat(long load) { return mb(load); } private String mb(long bytes) { return String.format("%d (%.2f MB)", bytes, (double)bytes / (MB)); } @Override String idString() { return "Memory Sim - "; } }
added access modifier
src/main/java/com/martensigwart/fakeload/MemorySimulator.java
added access modifier
<ide><path>rc/main/java/com/martensigwart/fakeload/MemorySimulator.java <ide> import java.util.List; <ide> <ide> <del>public final class MemorySimulator extends AbstractLoadSimulator { <add>final class MemorySimulator extends AbstractLoadSimulator { <ide> <ide> private static final Logger log = LoggerFactory.getLogger(MemorySimulator.class); <ide>
Java
apache-2.0
8fb0abb0edf696a8c606f990c95fd6786893bbcb
0
PkayJava/fintech,PkayJava/fintech,PkayJava/fintech
package com.angkorteam.fintech.installation; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.List; import java.util.Map; import java.util.UUID; import org.apache.commons.lang3.StringUtils; import org.joda.time.DateTime; import org.junit.Before; import org.junit.Test; import com.angkorteam.fintech.Constants; import com.angkorteam.fintech.IMifos; import com.angkorteam.fintech.Session; import com.angkorteam.fintech.dto.Dropdown; import com.angkorteam.fintech.dto.constant.TellerStatus; import com.angkorteam.fintech.dto.request.AccountRuleBuilder; import com.angkorteam.fintech.dto.request.PaymentTypeBuilder; import com.angkorteam.fintech.dto.request.StaffBuilder; import com.angkorteam.fintech.dto.request.TellerBuilder; import com.angkorteam.fintech.helper.AccountingRuleHelper; import com.angkorteam.fintech.helper.LoginHelper; import com.angkorteam.fintech.helper.PaymentTypeHelper; import com.angkorteam.fintech.helper.StaffHelper; import com.angkorteam.fintech.helper.TellerHelper; import com.angkorteam.fintech.junit.JUnit; import com.angkorteam.fintech.junit.JUnitWicketTester; import com.angkorteam.fintech.pages.account.RuleBrowsePage; import com.angkorteam.framework.spring.JdbcTemplate; import com.angkorteam.framework.wicket.markup.html.form.select2.Option; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.exceptions.UnirestException; public class JUnitData implements IMifos { private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); private static final DateFormat DATE_FORMAT_1 = new SimpleDateFormat("dd MMM yyyy"); private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("dd MMM yyyy"); private String token; private JUnitWicketTester wicket; public static final String CURRENCY = "USD"; public static final String OFFICE = "JUNIT_OFFICE"; public static final String FUND = "JUNIT_FUND"; public static final String TELLER = "JUNIT_TELLER_300"; public static final String PAYMENT = "JUNIT_PAYMENT"; public static final String PAYMENT_CASH = "JUNIT_PAYMENT_CASH"; public static final String EMPLOYEE = "JUNIT_EMP"; private static final List<String> OFFICES = Lists.newArrayList(); private static final List<String> CURRENCIES = Lists.newArrayList(); private static final List<String> FUNDS = Lists.newArrayList(); private static final List<Map<String, Object>> HOLIDAYS = Lists.newArrayList(); private static final List<String> EMPLOYEES = Lists.newArrayList(); static { OFFICES.add(OFFICE); CURRENCIES.add("USD"); CURRENCIES.add("VND"); CURRENCIES.add("KHR"); CURRENCIES.add("MYR"); CURRENCIES.add("SGD"); CURRENCIES.add("THB"); FUNDS.add(FUND); { Map<String, Object> day = Maps.newHashMap(); day.put("name", "JUNIT_HOLIDAY_P_" + DateTime.now().getYear()); day.put("from", DateTime.now().minusMonths(5).toDate()); day.put("to", DateTime.now().minusMonths(5).plusDays(4).toDate()); day.put("rescheduled", DateTime.now().minusMonths(5).plusDays(5).toDate()); HOLIDAYS.add(day); } { Map<String, Object> day = Maps.newHashMap(); day.put("name", "JUNIT_HOLIDAY_F_" + DateTime.now().getYear()); day.put("from", DateTime.now().plusMonths(5).toDate()); day.put("to", DateTime.now().plusMonths(5).plusDays(4).toDate()); day.put("rescheduled", DateTime.now().plusMonths(5).plusDays(5).toDate()); HOLIDAYS.add(day); } EMPLOYEES.add(EMPLOYEE); } @Before public void before() throws UnirestException { this.wicket = JUnit.getWicket(); JsonNode tokenObject = LoginHelper.authenticate(Constants.AID, Constants.UID, Constants.PWD); this.token = tokenObject.getObject().getString("base64EncodedAuthenticationKey"); } @Test public void initJUnitData() throws ParseException, UnirestException { setupOffice(); Function.setupWorkingDay(this); setupCurrency(); setupFund(); setupTeller(this, this.wicket.getJdbcTemplate()); setupPaymentType(this, this.wicket.getJdbcTemplate()); Function.setupHoliday(this, this.wicket.getJdbcTemplate(), HOLIDAYS); setupEmployee(this, this.wicket.getJdbcTemplate()); setupDropdown(this, this.wicket.getJdbcTemplate()); } protected void setupAccountingRule() { // AccountRuleBuilder builder = new AccountRuleBuilder(); // builder.withName(this.ruleNameValue); // builder.withDescription(this.descriptionValue); // if (this.officeValue != null) { // builder.withOfficeId(this.officeValue.getId()); // } // if (this.debitAccountValue != null) { // builder.withAccountToDebit(this.debitAccountValue.getId()); // } // if (this.debitTagValue != null && !this.debitTagValue.isEmpty()) { // for (Option tag : this.debitTagValue) { // builder.withDebitTags(tag.getId()); // } // builder.withAllowMultipleDebitEntries(this.multipleDebitValue); // } // if (this.creditAccountValue != null) { // builder.withAccountToCredit(this.creditAccountValue.getId()); // } // if (this.creditTagValue != null && !this.creditTagValue.isEmpty()) { // for (Option tag : this.creditTagValue) { // builder.withCreditTags(tag.getId()); // } // builder.withAllowMultipleCreditEntries(this.multipleCreditValue); // } // // JsonNode node = null; // try { // node = AccountingRuleHelper.create((Session) getSession(), builder.build()); // } catch (UnirestException e) { // error(e.getMessage()); // return; // } // if (reportError(node)) { // return; // } // setResponsePage(RuleBrowsePage.class); } protected void setupDropdown(IMifos session, JdbcTemplate jdbcTemplate) throws UnirestException { Function.setupSystemParameter(session, jdbcTemplate, Dropdown.Customer_Identifier, "Mr.", "Mr."); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.Customer_Identifier, "Miss.", "Miss"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.Customer_Identifier, "Mrs.", "Mrs."); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.LoanCollateral, "LoanCollateral01", "LoanCollateral01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.LoanCollateral, "LoanCollateral02", "LoanCollateral02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.LoanPurpose, "LoanPurpose01", "LoanPurpose01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.LoanPurpose, "LoanPurpose02", "LoanPurpose02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.Gender, "M", "Male"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.Gender, "F", "Female"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.YesNo, "Y", "Yes"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.YesNo, "N", "No"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.GuarantorRelationship, "GuarantorRelationship01", "GuarantorRelationship01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.GuarantorRelationship, "GuarantorRelationship02", "GuarantorRelationship02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.AssetAccountTags, "AssetAccountTags01", "AssetAccountTags01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.AssetAccountTags, "AssetAccountTags02", "AssetAccountTags02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.LiabilityAccountTags, "LiabilityAccountTags01", "LiabilityAccountTags01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.LiabilityAccountTags, "LiabilityAccountTags02", "LiabilityAccountTags02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.EquityAccountTags, "EquityAccountTags01", "EquityAccountTags01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.EquityAccountTags, "EquityAccountTags02", "EquityAccountTags02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.IncomeAccountTags, "IncomeAccountTags01", "IncomeAccountTags01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.IncomeAccountTags, "IncomeAccountTags02", "IncomeAccountTags02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.ExpenseAccountTags, "ExpenseAccountTags01", "ExpenseAccountTags01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.ExpenseAccountTags, "ExpenseAccountTags02", "ExpenseAccountTags02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.GroupRole, "GroupRole01", "GroupRole01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.GroupRole, "GroupRole02", "GroupRole02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.ClientClosureReason, "ClientClosureReason01", "ClientClosureReason01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.ClientClosureReason, "ClientClosureReason02", "ClientClosureReason02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.GroupClosureReason, "GroupClosureReason01", "GroupClosureReason01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.GroupClosureReason, "GroupClosureReason02", "GroupClosureReason02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.ClientType, "ClientType01", "ClientType01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.ClientType, "ClientType02", "ClientType02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.ClientClassification, "ClientClassification01", "ClientClassification01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.ClientClassification, "ClientClassification02", "ClientClassification02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.ClientSubStatus, "ClientSubStatus01", "ClientSubStatus01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.ClientSubStatus, "ClientSubStatus02", "ClientSubStatus02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.ClientRejectReason, "ClientRejectReason01", "ClientRejectReason01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.ClientRejectReason, "ClientRejectReason02", "ClientRejectReason02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.ClientWithdrawReason, "ClientWithdrawReason01", "ClientWithdrawReason01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.ClientWithdrawReason, "ClientWithdrawReason02", "ClientWithdrawReason02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.EntityToEntityAccessTypes, "EntityToEntityAccessTypes01", "EntityToEntityAccessTypes01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.EntityToEntityAccessTypes, "EntityToEntityAccessTypes02", "EntityToEntityAccessTypes02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.CenterClosureReason, "CenterClosureReason01", "CenterClosureReason01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.CenterClosureReason, "CenterClosureReason02", "CenterClosureReason02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.LoanRescheduleReason, "LoanRescheduleReason01", "LoanRescheduleReason01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.LoanRescheduleReason, "LoanRescheduleReason02", "LoanRescheduleReason02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.Constitution, "Constitution01", "Constitution01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.Constitution, "Constitution02", "Constitution02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.MainBusinessLine, "MainBusinessLine01", "MainBusinessLine01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.MainBusinessLine, "MainBusinessLine02", "MainBusinessLine02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.WriteOffReasons, "WriteOffReasons01", "WriteOffReasons01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.WriteOffReasons, "WriteOffReasons02", "WriteOffReasons02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.State, "State01", "State01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.State, "State02", "State02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.Country, "Country01", "Country01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.Country, "Country02", "Country02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.AddressType, "AddressType01", "AddressType01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.AddressType, "AddressType02", "AddressType02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.MaritalStatus, "MaritalStatus01", "MaritalStatus01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.MaritalStatus, "MaritalStatus02", "MaritalStatus02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.Profession, "Profession01", "Profession01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.Profession, "Profession02", "Profession02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.Relationship, "Relationship01", "Relationship01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.Relationship, "Relationship02", "Relationship02"); } protected void setupEmployee(IMifos session, JdbcTemplate jdbcTemplate) throws ParseException, UnirestException { for (String employee : EMPLOYEES) { if (!jdbcTemplate.queryForObject("select count(*) from m_staff where firstname = ?", Boolean.class, employee)) { StaffBuilder builder = new StaffBuilder(); builder.withExternalId(StringUtils.upperCase(UUID.randomUUID().toString())); builder.withJoiningDate(DATE_FORMAT.parse("2017-01-01")); builder.withMobileNo(this.wicket.getNumberGenerator().generate(10)); builder.withLoanOfficer(true); builder.withFirstName(employee); builder.withLastName(employee); StaffHelper.create(session, builder.build()); } } } protected void setupPaymentType(IMifos session, JdbcTemplate jdbcTemplate) throws UnirestException { if (!jdbcTemplate.queryForObject("select count(*) from m_payment_type where value = ?", Boolean.class, PAYMENT)) { PaymentTypeBuilder builder = new PaymentTypeBuilder(); builder.withDescription(PAYMENT); builder.withName(PAYMENT); builder.withCashPayment(false); builder.withPosition(1); PaymentTypeHelper.create(session, builder.build()); } if (!jdbcTemplate.queryForObject("select count(*) from m_payment_type where value = ?", Boolean.class, PAYMENT_CASH)) { PaymentTypeBuilder builder = new PaymentTypeBuilder(); builder.withDescription(PAYMENT_CASH); builder.withName(PAYMENT_CASH); builder.withCashPayment(true); builder.withPosition(1); PaymentTypeHelper.create(session, builder.build()); } } protected void setupTeller(IMifos session, JdbcTemplate jdbcTemplate) throws UnirestException, ParseException { final String TELLER_INACTIVE = "JUNIT_TELLER_400"; final String TELLER_CLOSED = "JUNIT_TELLER_600"; String officeId = jdbcTemplate.queryForObject("select id from m_office where name = ?", String.class, OFFICE); Date startDate = DATE_FORMAT.parse("2017-01-01"); if (!jdbcTemplate.queryForObject("select count(*) from m_tellers where name = ?", Boolean.class, TELLER)) { TellerBuilder builder = new TellerBuilder(); builder.withDescription(TELLER); builder.withName(TELLER); builder.withStatus(TellerStatus.Active); builder.withOfficeId(officeId); builder.withStartDate(startDate); TellerHelper.create(session, builder.build()); } if (!jdbcTemplate.queryForObject("select count(*) from m_tellers where name = ?", Boolean.class, TELLER_INACTIVE)) { TellerBuilder builder = new TellerBuilder(); builder.withDescription(TELLER_INACTIVE); builder.withName(TELLER_INACTIVE); builder.withStatus(TellerStatus.Inactive); builder.withOfficeId(officeId); builder.withStartDate(startDate); TellerHelper.create(session, builder.build()); } if (!jdbcTemplate.queryForObject("select count(*) from m_tellers where name = ?", Boolean.class, TELLER_CLOSED)) { TellerBuilder builder = new TellerBuilder(); builder.withDescription(TELLER_CLOSED); builder.withName(TELLER_CLOSED); builder.withStatus(TellerStatus.Closed); builder.withOfficeId(officeId); builder.withStartDate(startDate); TellerHelper.create(session, builder.build()); } } protected void setupFund() throws UnirestException { Function.setupFund(this, this.wicket.getJdbcTemplate(), FUNDS); } protected void setupOffice() throws ParseException, UnirestException { Date openingDate = DATE_FORMAT.parse("2017-01-01"); Function.setupOffice(this, this.wicket.getJdbcTemplate(), openingDate, OFFICES); } protected void setupCurrency() throws UnirestException { Function.setupCurrency(this, this.wicket.getJdbcTemplate(), CURRENCIES); } @Override public String getIdentifier() { return Constants.AID; } @Override public String getToken() { return this.token; } }
src/test/java/com/angkorteam/fintech/installation/JUnitData.java
package com.angkorteam.fintech.installation; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.List; import java.util.Map; import java.util.UUID; import org.apache.commons.lang3.StringUtils; import org.joda.time.DateTime; import org.junit.Before; import org.junit.Test; import com.angkorteam.fintech.Constants; import com.angkorteam.fintech.IMifos; import com.angkorteam.fintech.dto.Dropdown; import com.angkorteam.fintech.dto.constant.TellerStatus; import com.angkorteam.fintech.dto.request.PaymentTypeBuilder; import com.angkorteam.fintech.dto.request.StaffBuilder; import com.angkorteam.fintech.dto.request.TellerBuilder; import com.angkorteam.fintech.helper.LoginHelper; import com.angkorteam.fintech.helper.PaymentTypeHelper; import com.angkorteam.fintech.helper.StaffHelper; import com.angkorteam.fintech.helper.TellerHelper; import com.angkorteam.fintech.junit.JUnit; import com.angkorteam.fintech.junit.JUnitWicketTester; import com.angkorteam.framework.spring.JdbcTemplate; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.exceptions.UnirestException; public class JUnitData implements IMifos { private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); private static final DateFormat DATE_FORMAT_1 = new SimpleDateFormat("dd MMM yyyy"); private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("dd MMM yyyy"); private String token; private JUnitWicketTester wicket; public static final String CURRENCY = "USD"; public static final String OFFICE = "JUNIT_OFFICE"; public static final String FUND = "JUNIT_FUND"; public static final String TELLER = "JUNIT_TELLER_300"; public static final String PAYMENT = "JUNIT_PAYMENT"; public static final String PAYMENT_CASH = "JUNIT_PAYMENT_CASH"; public static final String EMPLOYEE = "JUNIT_EMP"; private static final List<String> OFFICES = Lists.newArrayList(); private static final List<String> CURRENCIES = Lists.newArrayList(); private static final List<String> FUNDS = Lists.newArrayList(); private static final List<Map<String, Object>> HOLIDAYS = Lists.newArrayList(); private static final List<String> EMPLOYEES = Lists.newArrayList(); static { OFFICES.add(OFFICE); CURRENCIES.add("USD"); CURRENCIES.add("VND"); CURRENCIES.add("KHR"); CURRENCIES.add("MYR"); CURRENCIES.add("SGD"); CURRENCIES.add("THB"); FUNDS.add(FUND); { Map<String, Object> day = Maps.newHashMap(); day.put("name", "JUNIT_HOLIDAY_P_" + DateTime.now().getYear()); day.put("from", DateTime.now().minusMonths(5).toDate()); day.put("to", DateTime.now().minusMonths(5).plusDays(4).toDate()); day.put("rescheduled", DateTime.now().minusMonths(5).plusDays(5).toDate()); HOLIDAYS.add(day); } { Map<String, Object> day = Maps.newHashMap(); day.put("name", "JUNIT_HOLIDAY_F_" + DateTime.now().getYear()); day.put("from", DateTime.now().plusMonths(5).toDate()); day.put("to", DateTime.now().plusMonths(5).plusDays(4).toDate()); day.put("rescheduled", DateTime.now().plusMonths(5).plusDays(5).toDate()); HOLIDAYS.add(day); } EMPLOYEES.add(EMPLOYEE); } @Before public void before() throws UnirestException { this.wicket = JUnit.getWicket(); JsonNode tokenObject = LoginHelper.authenticate(Constants.AID, Constants.UID, Constants.PWD); this.token = tokenObject.getObject().getString("base64EncodedAuthenticationKey"); } @Test public void initJUnitData() throws ParseException, UnirestException { setupOffice(); Function.setupWorkingDay(this); setupCurrency(); setupFund(); setupTeller(this, this.wicket.getJdbcTemplate()); setupPaymentType(this, this.wicket.getJdbcTemplate()); Function.setupHoliday(this, this.wicket.getJdbcTemplate(), HOLIDAYS); setupEmployee(this, this.wicket.getJdbcTemplate()); setupDropdown(this, this.wicket.getJdbcTemplate()); } protected void setupDropdown(IMifos session, JdbcTemplate jdbcTemplate) throws UnirestException { Function.setupSystemParameter(session, jdbcTemplate, Dropdown.Customer_Identifier, "Mr.", "Mr."); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.Customer_Identifier, "Miss.", "Miss"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.Customer_Identifier, "Mrs.", "Mrs."); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.LoanCollateral, "LoanCollateral01", "LoanCollateral01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.LoanCollateral, "LoanCollateral02", "LoanCollateral02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.LoanPurpose, "LoanPurpose01", "LoanPurpose01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.LoanPurpose, "LoanPurpose02", "LoanPurpose02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.Gender, "M", "Male"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.Gender, "F", "Female"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.YesNo, "Y", "Yes"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.YesNo, "N", "No"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.GuarantorRelationship, "GuarantorRelationship01", "GuarantorRelationship01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.GuarantorRelationship, "GuarantorRelationship02", "GuarantorRelationship02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.AssetAccountTags, "AssetAccountTags01", "AssetAccountTags01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.AssetAccountTags, "AssetAccountTags02", "AssetAccountTags02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.LiabilityAccountTags, "LiabilityAccountTags01", "LiabilityAccountTags01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.LiabilityAccountTags, "LiabilityAccountTags02", "LiabilityAccountTags02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.EquityAccountTags, "EquityAccountTags01", "EquityAccountTags01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.EquityAccountTags, "EquityAccountTags02", "EquityAccountTags02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.IncomeAccountTags, "IncomeAccountTags01", "IncomeAccountTags01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.IncomeAccountTags, "IncomeAccountTags02", "IncomeAccountTags02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.ExpenseAccountTags, "ExpenseAccountTags01", "ExpenseAccountTags01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.ExpenseAccountTags, "ExpenseAccountTags02", "ExpenseAccountTags02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.GroupRole, "GroupRole01", "GroupRole01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.GroupRole, "GroupRole02", "GroupRole02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.ClientClosureReason, "ClientClosureReason01", "ClientClosureReason01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.ClientClosureReason, "ClientClosureReason02", "ClientClosureReason02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.GroupClosureReason, "GroupClosureReason01", "GroupClosureReason01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.GroupClosureReason, "GroupClosureReason02", "GroupClosureReason02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.ClientType, "ClientType01", "ClientType01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.ClientType, "ClientType02", "ClientType02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.ClientClassification, "ClientClassification01", "ClientClassification01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.ClientClassification, "ClientClassification02", "ClientClassification02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.ClientSubStatus, "ClientSubStatus01", "ClientSubStatus01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.ClientSubStatus, "ClientSubStatus02", "ClientSubStatus02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.ClientRejectReason, "ClientRejectReason01", "ClientRejectReason01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.ClientRejectReason, "ClientRejectReason02", "ClientRejectReason02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.ClientWithdrawReason, "ClientWithdrawReason01", "ClientWithdrawReason01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.ClientWithdrawReason, "ClientWithdrawReason02", "ClientWithdrawReason02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.EntityToEntityAccessTypes, "EntityToEntityAccessTypes01", "EntityToEntityAccessTypes01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.EntityToEntityAccessTypes, "EntityToEntityAccessTypes02", "EntityToEntityAccessTypes02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.CenterClosureReason, "CenterClosureReason01", "CenterClosureReason01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.CenterClosureReason, "CenterClosureReason02", "CenterClosureReason02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.LoanRescheduleReason, "LoanRescheduleReason01", "LoanRescheduleReason01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.LoanRescheduleReason, "LoanRescheduleReason02", "LoanRescheduleReason02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.Constitution, "Constitution01", "Constitution01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.Constitution, "Constitution02", "Constitution02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.MainBusinessLine, "MainBusinessLine01", "MainBusinessLine01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.MainBusinessLine, "MainBusinessLine02", "MainBusinessLine02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.WriteOffReasons, "WriteOffReasons01", "WriteOffReasons01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.WriteOffReasons, "WriteOffReasons02", "WriteOffReasons02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.State, "State01", "State01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.State, "State02", "State02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.Country, "Country01", "Country01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.Country, "Country02", "Country02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.AddressType, "AddressType01", "AddressType01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.AddressType, "AddressType02", "AddressType02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.MaritalStatus, "MaritalStatus01", "MaritalStatus01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.MaritalStatus, "MaritalStatus02", "MaritalStatus02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.Profession, "Profession01", "Profession01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.Profession, "Profession02", "Profession02"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.Relationship, "Relationship01", "Relationship01"); Function.setupSystemParameter(session, jdbcTemplate, Dropdown.Relationship, "Relationship02", "Relationship02"); } protected void setupEmployee(IMifos session, JdbcTemplate jdbcTemplate) throws ParseException, UnirestException { for (String employee : EMPLOYEES) { if (!jdbcTemplate.queryForObject("select count(*) from m_staff where firstname = ?", Boolean.class, employee)) { StaffBuilder builder = new StaffBuilder(); builder.withExternalId(StringUtils.upperCase(UUID.randomUUID().toString())); builder.withJoiningDate(DATE_FORMAT.parse("2017-01-01")); builder.withMobileNo(this.wicket.getNumberGenerator().generate(10)); builder.withLoanOfficer(true); builder.withFirstName(employee); builder.withLastName(employee); StaffHelper.create(session, builder.build()); } } } protected void setupPaymentType(IMifos session, JdbcTemplate jdbcTemplate) throws UnirestException { if (!jdbcTemplate.queryForObject("select count(*) from m_payment_type where value = ?", Boolean.class, PAYMENT)) { PaymentTypeBuilder builder = new PaymentTypeBuilder(); builder.withDescription(PAYMENT); builder.withName(PAYMENT); builder.withCashPayment(false); builder.withPosition(1); PaymentTypeHelper.create(session, builder.build()); } if (!jdbcTemplate.queryForObject("select count(*) from m_payment_type where value = ?", Boolean.class, PAYMENT_CASH)) { PaymentTypeBuilder builder = new PaymentTypeBuilder(); builder.withDescription(PAYMENT_CASH); builder.withName(PAYMENT_CASH); builder.withCashPayment(true); builder.withPosition(1); PaymentTypeHelper.create(session, builder.build()); } } protected void setupTeller(IMifos session, JdbcTemplate jdbcTemplate) throws UnirestException, ParseException { final String TELLER_INACTIVE = "JUNIT_TELLER_400"; final String TELLER_CLOSED = "JUNIT_TELLER_600"; String officeId = jdbcTemplate.queryForObject("select id from m_office where name = ?", String.class, OFFICE); Date startDate = DATE_FORMAT.parse("2017-01-01"); if (!jdbcTemplate.queryForObject("select count(*) from m_tellers where name = ?", Boolean.class, TELLER)) { TellerBuilder builder = new TellerBuilder(); builder.withDescription(TELLER); builder.withName(TELLER); builder.withStatus(TellerStatus.Active); builder.withOfficeId(officeId); builder.withStartDate(startDate); TellerHelper.create(session, builder.build()); } if (!jdbcTemplate.queryForObject("select count(*) from m_tellers where name = ?", Boolean.class, TELLER_INACTIVE)) { TellerBuilder builder = new TellerBuilder(); builder.withDescription(TELLER_INACTIVE); builder.withName(TELLER_INACTIVE); builder.withStatus(TellerStatus.Inactive); builder.withOfficeId(officeId); builder.withStartDate(startDate); TellerHelper.create(session, builder.build()); } if (!jdbcTemplate.queryForObject("select count(*) from m_tellers where name = ?", Boolean.class, TELLER_CLOSED)) { TellerBuilder builder = new TellerBuilder(); builder.withDescription(TELLER_CLOSED); builder.withName(TELLER_CLOSED); builder.withStatus(TellerStatus.Closed); builder.withOfficeId(officeId); builder.withStartDate(startDate); TellerHelper.create(session, builder.build()); } } protected void setupFund() throws UnirestException { Function.setupFund(this, this.wicket.getJdbcTemplate(), FUNDS); } protected void setupOffice() throws ParseException, UnirestException { Date openingDate = DATE_FORMAT.parse("2017-01-01"); Function.setupOffice(this, this.wicket.getJdbcTemplate(), openingDate, OFFICES); } protected void setupCurrency() throws UnirestException { Function.setupCurrency(this, this.wicket.getJdbcTemplate(), CURRENCIES); } @Override public String getIdentifier() { return Constants.AID; } @Override public String getToken() { return this.token; } }
setupAccountingRule
src/test/java/com/angkorteam/fintech/installation/JUnitData.java
setupAccountingRule
<ide><path>rc/test/java/com/angkorteam/fintech/installation/JUnitData.java <ide> <ide> import com.angkorteam.fintech.Constants; <ide> import com.angkorteam.fintech.IMifos; <add>import com.angkorteam.fintech.Session; <ide> import com.angkorteam.fintech.dto.Dropdown; <ide> import com.angkorteam.fintech.dto.constant.TellerStatus; <add>import com.angkorteam.fintech.dto.request.AccountRuleBuilder; <ide> import com.angkorteam.fintech.dto.request.PaymentTypeBuilder; <ide> import com.angkorteam.fintech.dto.request.StaffBuilder; <ide> import com.angkorteam.fintech.dto.request.TellerBuilder; <add>import com.angkorteam.fintech.helper.AccountingRuleHelper; <ide> import com.angkorteam.fintech.helper.LoginHelper; <ide> import com.angkorteam.fintech.helper.PaymentTypeHelper; <ide> import com.angkorteam.fintech.helper.StaffHelper; <ide> import com.angkorteam.fintech.helper.TellerHelper; <ide> import com.angkorteam.fintech.junit.JUnit; <ide> import com.angkorteam.fintech.junit.JUnitWicketTester; <add>import com.angkorteam.fintech.pages.account.RuleBrowsePage; <ide> import com.angkorteam.framework.spring.JdbcTemplate; <add>import com.angkorteam.framework.wicket.markup.html.form.select2.Option; <ide> import com.google.common.collect.Lists; <ide> import com.google.common.collect.Maps; <ide> import com.mashape.unirest.http.JsonNode; <ide> setupDropdown(this, this.wicket.getJdbcTemplate()); <ide> <ide> } <add> <add> protected void setupAccountingRule() { <add>// AccountRuleBuilder builder = new AccountRuleBuilder(); <add>// builder.withName(this.ruleNameValue); <add>// builder.withDescription(this.descriptionValue); <add>// if (this.officeValue != null) { <add>// builder.withOfficeId(this.officeValue.getId()); <add>// } <add>// if (this.debitAccountValue != null) { <add>// builder.withAccountToDebit(this.debitAccountValue.getId()); <add>// } <add>// if (this.debitTagValue != null && !this.debitTagValue.isEmpty()) { <add>// for (Option tag : this.debitTagValue) { <add>// builder.withDebitTags(tag.getId()); <add>// } <add>// builder.withAllowMultipleDebitEntries(this.multipleDebitValue); <add>// } <add>// if (this.creditAccountValue != null) { <add>// builder.withAccountToCredit(this.creditAccountValue.getId()); <add>// } <add>// if (this.creditTagValue != null && !this.creditTagValue.isEmpty()) { <add>// for (Option tag : this.creditTagValue) { <add>// builder.withCreditTags(tag.getId()); <add>// } <add>// builder.withAllowMultipleCreditEntries(this.multipleCreditValue); <add>// } <add>// <add>// JsonNode node = null; <add>// try { <add>// node = AccountingRuleHelper.create((Session) getSession(), builder.build()); <add>// } catch (UnirestException e) { <add>// error(e.getMessage()); <add>// return; <add>// } <add>// if (reportError(node)) { <add>// return; <add>// } <add>// setResponsePage(RuleBrowsePage.class); <add> } <ide> <ide> protected void setupDropdown(IMifos session, JdbcTemplate jdbcTemplate) throws UnirestException { <ide>
Java
apache-2.0
6a6bb48840aa0043200a5d9f6fffea47aea1a8db
0
mohanaraosv/commons-cli,apache/commons-cli,mohanaraosv/commons-cli,pplatek/commons-cli,pplatek/commons-cli,apache/commons-cli,pplatek/commons-cli,apache/commons-cli,apache/commons-cli,pplatek/commons-cli,mohanaraosv/commons-cli,mohanaraosv/commons-cli
/** * 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.commons.cli; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * <p> * This is a collection of tests that test real world * applications command lines. * </p> * * <p> * The following are the applications that are tested: * <ul> * <li>Ant</li> * </ul> * </p> * * @author John Keyes (john at integralsource.com) */ public class ApplicationTest extends TestCase { public static Test suite() { return new TestSuite(ApplicationTest.class); } public ApplicationTest(String name) { super(name); } /** * */ public void testLs() { // create the command line parser CommandLineParser parser = new PosixParser(); Options options = new Options(); options.addOption( "a", "all", false, "do not hide entries starting with ." ); options.addOption( "A", "almost-all", false, "do not list implied . and .." ); options.addOption( "b", "escape", false, "print octal escapes for nongraphic characters" ); options.addOption( OptionBuilder.withLongOpt( "block-size" ) .withDescription( "use SIZE-byte blocks" ) .withValueSeparator( '=' ) .hasArg() .create() ); options.addOption( "B", "ignore-backups", false, "do not list implied entried ending with ~"); options.addOption( "c", false, "with -lt: sort by, and show, ctime (time of last modification of file status information) with -l:show ctime and sort by name otherwise: sort by ctime" ); options.addOption( "C", false, "list entries by columns" ); String[] args = new String[]{ "--block-size=10" }; try { CommandLine line = parser.parse( options, args ); assertTrue( line.hasOption( "block-size" ) ); assertEquals( line.getOptionValue( "block-size" ), "10" ); } catch( ParseException exp ) { fail( "Unexpected exception:" + exp.getMessage() ); } } /** * Ant test */ public void testAnt() { // use the GNU parser CommandLineParser parser = new GnuParser( ); Options options = new Options(); options.addOption( "help", false, "print this message" ); options.addOption( "projecthelp", false, "print project help information" ); options.addOption( "version", false, "print the version information and exit" ); options.addOption( "quiet", false, "be extra quiet" ); options.addOption( "verbose", false, "be extra verbose" ); options.addOption( "debug", false, "print debug information" ); options.addOption( "logfile", true, "use given file for log" ); options.addOption( "logger", true, "the class which is to perform the logging" ); options.addOption( "listener", true, "add an instance of a class as a project listener" ); options.addOption( "buildfile", true, "use given buildfile" ); options.addOption( OptionBuilder.withDescription( "use value for given property" ) .hasArgs() .withValueSeparator() .create( 'D' ) ); //, null, true, , false, true ); options.addOption( "find", true, "search for buildfile towards the root of the filesystem and use it" ); String[] args = new String[]{ "-buildfile", "mybuild.xml", "-Dproperty=value", "-Dproperty1=value1", "-projecthelp" }; try { CommandLine line = parser.parse( options, args ); // check multiple values String[] opts = line.getOptionValues( "D" ); assertEquals( "property", opts[0] ); assertEquals( "value", opts[1] ); assertEquals( "property1", opts[2] ); assertEquals( "value1", opts[3] ); // check single value assertEquals( line.getOptionValue( "buildfile"), "mybuild.xml" ); // check option assertTrue( line.hasOption( "projecthelp") ); } catch( ParseException exp ) { fail( "Unexpected exception:" + exp.getMessage() ); } } }
src/test/org/apache/commons/cli/ApplicationTest.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.commons.cli; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * <p> * This is a collection of tests that test real world * applications command lines. * </p> * * <p> * The following are the applications that are tested: * <ul> * <li>Ant</li> * </ul> * </p> * * @author John Keyes (john at integralsource.com) */ public class ApplicationTest extends TestCase { public static Test suite() { return new TestSuite(ApplicationTest.class); } public ApplicationTest(String name) { super(name); } /** * */ public void testLs() { // create the command line parser CommandLineParser parser = new PosixParser(); Options options = new Options(); options.addOption( "a", "all", false, "do not hide entries starting with ." ); options.addOption( "A", "almost-all", false, "do not list implied . and .." ); options.addOption( "b", "escape", false, "print octal escapes for nongraphic characters" ); options.addOption( OptionBuilder.withLongOpt( "block-size" ) .withDescription( "use SIZE-byte blocks" ) .withValueSeparator( '=' ) .hasArg() .create() ); options.addOption( "B", "ignore-backups", false, "do not list implied entried ending with ~"); options.addOption( "c", false, "with -lt: sort by, and show, ctime (time of last modification of file status information) with -l:show ctime and sort by name otherwise: sort by ctime" ); options.addOption( "C", false, "list entries by columns" ); String[] args = new String[]{ "--block-size=10" }; try { CommandLine line = parser.parse( options, args ); assertTrue( line.hasOption( "block-size" ) ); assertEquals( line.getOptionValue( "block-size" ), "10" ); } catch( ParseException exp ) { fail( "Unexpected exception:" + exp.getMessage() ); } } /** * Ant test */ public void testAnt() { // use the GNU parser CommandLineParser parser = new GnuParser( ); Options options = new Options(); options.addOption( "help", false, "print this message" ); options.addOption( "projecthelp", false, "print project help information" ); options.addOption( "version", false, "print the version information and exit" ); options.addOption( "quiet", false, "be extra quiet" ); options.addOption( "verbose", false, "be extra verbose" ); options.addOption( "debug", false, "print debug information" ); options.addOption( "version", false, "produce logging information without adornments" ); options.addOption( "logfile", true, "use given file for log" ); options.addOption( "logger", true, "the class which is to perform the logging" ); options.addOption( "listener", true, "add an instance of a class as a project listener" ); options.addOption( "buildfile", true, "use given buildfile" ); options.addOption( OptionBuilder.withDescription( "use value for given property" ) .hasArgs() .withValueSeparator() .create( 'D' ) ); //, null, true, , false, true ); options.addOption( "find", true, "search for buildfile towards the root of the filesystem and use it" ); String[] args = new String[]{ "-buildfile", "mybuild.xml", "-Dproperty=value", "-Dproperty1=value1", "-projecthelp" }; try { CommandLine line = parser.parse( options, args ); // check multiple values String[] opts = line.getOptionValues( "D" ); assertEquals( "property", opts[0] ); assertEquals( "value", opts[1] ); assertEquals( "property1", opts[2] ); assertEquals( "value1", opts[3] ); // check single value assertEquals( line.getOptionValue( "buildfile"), "mybuild.xml" ); // check option assertTrue( line.hasOption( "projecthelp") ); } catch( ParseException exp ) { fail( "Unexpected exception:" + exp.getMessage() ); } } }
Removing the duplication 'version' option as pointed out by Andrew Kutz git-svn-id: c795571ee9b9ed630ea84edf5ecdcef3ba4f5328@651842 13f79535-47bb-0310-9956-ffa450edef68
src/test/org/apache/commons/cli/ApplicationTest.java
Removing the duplication 'version' option as pointed out by Andrew Kutz
<ide><path>rc/test/org/apache/commons/cli/ApplicationTest.java <ide> options.addOption( "quiet", false, "be extra quiet" ); <ide> options.addOption( "verbose", false, "be extra verbose" ); <ide> options.addOption( "debug", false, "print debug information" ); <del> options.addOption( "version", false, "produce logging information without adornments" ); <ide> options.addOption( "logfile", true, "use given file for log" ); <ide> options.addOption( "logger", true, "the class which is to perform the logging" ); <ide> options.addOption( "listener", true, "add an instance of a class as a project listener" );
Java
bsd-3-clause
887f36a798d8636d8b5b4f3482680d24cdd0f1cb
0
DataBiosphere/terra-common-lib,DataBiosphere/terra-common-lib,databiosphere/terra-common-lib
package bio.terra.common.tracing; import io.opencensus.contrib.http.servlet.OcHttpServletFilter; import io.opencensus.contrib.spring.aop.CensusSpringAspect; import io.opencensus.exporter.trace.stackdriver.StackdriverTraceConfiguration; import io.opencensus.exporter.trace.stackdriver.StackdriverTraceExporter; import io.opencensus.trace.AttributeValue; import io.opencensus.trace.Tracing; import io.opencensus.trace.config.TraceParams; import io.opencensus.trace.samplers.Samplers; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * Spring Configuration for Terra common tracing setup. * * <ul> * <li>{@link OcHttpServletFilter}, encloses HTTP requests to the server in a per-request * OpenCensus trace. * <li>{@link RequestAttributeInterceptor}, which adds additional per-request annotations for each * service request. * <li>{@link StackdriverTraceExporter} configuration, which causes traces sampled by the service * to be exported to Stackdriver aka Google Cloud Tracing. * <li>{@link CensusSpringAspect}, a Spring aspect to enable using the {@link * io.opencensus.contrib.spring.aop.Traced} annotation on Spring bean methods to add sub * spans. * </ul> * * <p>To enable, add this package to Spring's component scan, e.g. * {@code @ComponentScan(basePackages = "bio.terra.common.tracing")} */ @Configuration @EnableConfigurationProperties(value = TracingProperties.class) public class TracingConfig implements InitializingBean, WebMvcConfigurer { private static final Logger logger = LoggerFactory.getLogger(TracingConfig.class); private final ConfigurableEnvironment configurableEnvironment; private final TracingProperties tracingProperties; @Autowired public TracingConfig( ConfigurableEnvironment configurableEnvironment, TracingProperties tracingProperties) { this.configurableEnvironment = configurableEnvironment; this.tracingProperties = tracingProperties; } /** * A bean to register the {@link OcHttpServletFilter} to enclose server requests in OpenCensus * span scopes. */ @Bean public FilterRegistrationBean<OcHttpServletFilter> tracingServletFilter() { FilterRegistrationBean<OcHttpServletFilter> registration = new FilterRegistrationBean(new OcHttpServletFilter()); registration.setUrlPatterns(tracingProperties.getUrlPatterns()); return registration; } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new RequestAttributeInterceptor()); } /** Enable the @Traced annotation for use within the application. */ @Bean public CensusSpringAspect censusAspect() { return new CensusSpringAspect(Tracing.getTracer()); } @Override public void afterPropertiesSet() { setTraceSamplingProbability(); maybeExportToStackdriver(); } private void setTraceSamplingProbability() { TraceParams origParams = Tracing.getTraceConfig().getActiveTraceParams(); Tracing.getTraceConfig() .updateActiveTraceParams( origParams .toBuilder() .setSampler(Samplers.probabilitySampler(tracingProperties.getSamplingRate())) .build()); } private void maybeExportToStackdriver() { if (tracingProperties.getStackdriverExportEnabled()) { try { // Once properties are loaded, initialize the Stackdriver exporter. // Use Google's default environment inspection to set options. This will attempt to extract // the project ID and container environment from environment variables and/or application // default credentials. StackdriverTraceExporter.createAndRegister( StackdriverTraceConfiguration.builder() // Set attributes to appear on every trace exported for this service. .setFixedAttributes(createFixedAttributes()) .build()); logger.info("Registered StackdriverTraceExporter"); } catch (IOException e) { // We do not want to prevent servers from starting up if there is an error exporting traces. logger.error( "Unable to register StackdriverTraceExporter. Traces will not be exported.", e); } catch (IllegalStateException e) { // In testing, the exporter may have already been registered by a previous bean setup. // If the exporter is registered multiple times, an IllegalStateException is thrown. // This is expected in testing. logger.warn( "Unable to register StackdriverTraceExporter. In testing, this is expected " + "because the exporter may have already been registered. Otherwise, traces will " + "not be exported.", e); } } } private Map<String, AttributeValue> createFixedAttributes() { Map<String, AttributeValue> attributes = new HashMap<>(); String componentName = configurableEnvironment.getProperty("spring.application.name"); if (componentName != null) { attributes.put("/terra/component", AttributeValue.stringAttributeValue(componentName)); } String version = configurableEnvironment.getProperty("spring.application.version"); if (version != null) { attributes.put("/terra/version", AttributeValue.stringAttributeValue(version)); } return attributes; } }
src/main/java/bio/terra/common/tracing/TracingConfig.java
package bio.terra.common.tracing; import io.opencensus.contrib.http.servlet.OcHttpServletFilter; import io.opencensus.contrib.spring.aop.CensusSpringAspect; import io.opencensus.exporter.trace.stackdriver.StackdriverTraceConfiguration; import io.opencensus.exporter.trace.stackdriver.StackdriverTraceExporter; import io.opencensus.trace.AttributeValue; import io.opencensus.trace.Tracing; import io.opencensus.trace.config.TraceParams; import io.opencensus.trace.samplers.Samplers; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * Spring Configuration for Terra common tracing setup. * * <ul> * <li>{@link OcHttpServletFilter}, encloses HTTP requests to the server in a per-request * OpenCensus trace. * <li>{@link RequestAttributeInterceptor}, which adds additional per-request annotations for each * service request. * <li>{@link StackdriverTraceExporter} configuration, which causes traces sampled by the service * to be exported to Stackdriver aka Google Cloud Tracing. * <li>{@link CensusSpringAspect}, a Spring aspect to enable using the {@link * io.opencensus.contrib.spring.aop.Traced} annotation on Spring bean methods to add sub * spans. * </ul> * * <p>To enable, add this package to Spring's component scan, e.g. * {@code @ComponentScan(basePackages = "bio.terra.common.tracing")} */ @Configuration @EnableConfigurationProperties(value = TracingProperties.class) public class TracingConfig implements InitializingBean, WebMvcConfigurer { private static final Logger logger = LoggerFactory.getLogger(TracingConfig.class); private final ConfigurableEnvironment configurableEnvironment; private final TracingProperties tracingProperties; @Autowired public TracingConfig( ConfigurableEnvironment configurableEnvironment, TracingProperties tracingProperties) { this.configurableEnvironment = configurableEnvironment; this.tracingProperties = tracingProperties; } /** * A bean to register the {@link OcHttpServletFilter} to enclose server requests in OpenCensus * span scopes. */ @Bean public FilterRegistrationBean<OcHttpServletFilter> tracingServletFilter() { FilterRegistrationBean<OcHttpServletFilter> registration = new FilterRegistrationBean(new OcHttpServletFilter()); registration.setUrlPatterns(tracingProperties.getUrlPatterns()); return registration; } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new RequestAttributeInterceptor()); } /** Enable the @Traced annotation for use within the application. */ @Bean public CensusSpringAspect censusAspect() { return new CensusSpringAspect(Tracing.getTracer()); } @Override public void afterPropertiesSet() { setTraceSamplingProbability(); maybeExportToStackdriver(); } private void setTraceSamplingProbability() { TraceParams origParams = Tracing.getTraceConfig().getActiveTraceParams(); Tracing.getTraceConfig() .updateActiveTraceParams( origParams .toBuilder() .setSampler(Samplers.probabilitySampler(tracingProperties.getSamplingRate())) .build()); } private void maybeExportToStackdriver() { if (tracingProperties.getStackdriverExportEnabled()) { try { // Once properties are loaded, initialize the Stackdriver exporter. // Use Google's default environment inspection to set options. This will attempt to extract // the project ID and container environment from environment variables and/or application // default credentials. StackdriverTraceExporter.createAndRegister( StackdriverTraceConfiguration.builder() // Set attributes to appear on every trace exported for this service. .setFixedAttributes(createFixedAttributes()) .build()); logger.info("Registered StackdriverTraceExporter"); } catch (IOException e) { // We do not want to prevent servers from starting up if there is an error exporting traces. logger.error( "Unable to register StackdriverTraceExporter. Traces will not be exported.", e); } } } private Map<String, AttributeValue> createFixedAttributes() { Map<String, AttributeValue> attributes = new HashMap<>(); String componentName = configurableEnvironment.getProperty("spring.application.name"); if (componentName != null) { attributes.put("/terra/component", AttributeValue.stringAttributeValue(componentName)); } String version = configurableEnvironment.getProperty("spring.application.version"); if (version != null) { attributes.put("/terra/version", AttributeValue.stringAttributeValue(version)); } return attributes; } }
PF-279 Don't fail on re-registration of StackdriverTraceExporter. (#29) In client tests, the StackdriverTraceExporter can be registered multiple times by multiple instances TracingConfig bean. This is ok in testing. This is hard to reproduce in terra-common-lib because we don't yet have any google credentials to allow registration to succeed, so the StackdriverTraceExporter does not get registered successfully at all, much less multiple times. I don't think it's worth adding google credentials for testing for this use case, though we may eventually want them.
src/main/java/bio/terra/common/tracing/TracingConfig.java
PF-279 Don't fail on re-registration of StackdriverTraceExporter. (#29)
<ide><path>rc/main/java/bio/terra/common/tracing/TracingConfig.java <ide> // We do not want to prevent servers from starting up if there is an error exporting traces. <ide> logger.error( <ide> "Unable to register StackdriverTraceExporter. Traces will not be exported.", e); <add> } catch (IllegalStateException e) { <add> // In testing, the exporter may have already been registered by a previous bean setup. <add> // If the exporter is registered multiple times, an IllegalStateException is thrown. <add> // This is expected in testing. <add> logger.warn( <add> "Unable to register StackdriverTraceExporter. In testing, this is expected " <add> + "because the exporter may have already been registered. Otherwise, traces will " <add> + "not be exported.", <add> e); <ide> } <ide> } <ide> }
Java
mit
0e8af191af5bd827292c14ade40f65c5ead77d3d
0
MarkEWaite/git-plugin,martinda/git-plugin,MarkEWaite/git-plugin,martinda/git-plugin,MarkEWaite/git-plugin,jenkinsci/git-plugin,martinda/git-plugin,MarkEWaite/git-plugin,v1v/git-plugin,v1v/git-plugin,v1v/git-plugin,jenkinsci/git-plugin,jenkinsci/git-plugin,jenkinsci/git-plugin
package hudson.plugins.git; import com.cloudbees.plugins.credentials.Credentials; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.CredentialsScope; import com.cloudbees.plugins.credentials.CredentialsStore; import com.cloudbees.plugins.credentials.SystemCredentialsProvider; import com.cloudbees.plugins.credentials.common.StandardCredentials; import com.cloudbees.plugins.credentials.domains.Domain; import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl; import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.google.common.base.Function; import com.google.common.collect.Collections2; import com.google.common.collect.Lists; import hudson.EnvVars; import hudson.FilePath; import hudson.Launcher; import hudson.matrix.Axis; import hudson.matrix.AxisList; import hudson.matrix.MatrixBuild; import hudson.matrix.MatrixProject; import hudson.model.*; import hudson.plugins.git.GitSCM.BuildChooserContextImpl; import hudson.plugins.git.GitSCM.DescriptorImpl; import hudson.plugins.git.browser.GitRepositoryBrowser; import hudson.plugins.git.browser.GithubWeb; import hudson.plugins.git.extensions.GitSCMExtension; import hudson.plugins.git.extensions.impl.*; import hudson.plugins.git.util.BuildChooser; import hudson.plugins.git.util.BuildChooserContext; import hudson.plugins.git.util.BuildChooserContext.ContextCallable; import hudson.plugins.git.util.BuildData; import hudson.plugins.git.util.DefaultBuildChooser; import hudson.plugins.git.util.GitUtils; import hudson.plugins.parameterizedtrigger.BuildTrigger; import hudson.plugins.parameterizedtrigger.ResultCondition; import hudson.remoting.Channel; import hudson.remoting.VirtualChannel; import hudson.scm.ChangeLogSet; import hudson.scm.PollingResult; import hudson.scm.PollingResult.Change; import hudson.scm.SCMRevisionState; import hudson.slaves.DumbSlave; import hudson.slaves.EnvironmentVariablesNodeProperty.Entry; import hudson.tools.ToolProperty; import hudson.triggers.SCMTrigger; import hudson.util.StreamTaskListener; import jenkins.security.MasterToSlaveCallable; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import org.jenkinsci.plugins.gitclient.*; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.TestExtension; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.ObjectStreamException; import java.io.Serializable; import java.net.URL; import java.text.MessageFormat; import java.util.*; import org.eclipse.jgit.transport.RemoteConfig; import static org.hamcrest.Matchers.*; import static org.hamcrest.CoreMatchers.instanceOf; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import static org.junit.Assert.*; import org.junit.Before; import org.junit.BeforeClass; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import static org.mockito.Matchers.*; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import jenkins.model.Jenkins; import jenkins.plugins.git.CliGitCommand; import jenkins.plugins.git.GitSampleRepoRule; /** * Tests for {@link GitSCM}. * @author ishaaq */ public class GitSCMTest extends AbstractGitTestCase { @Rule public GitSampleRepoRule secondRepo = new GitSampleRepoRule(); private CredentialsStore store = null; @BeforeClass public static void setGitDefaults() throws Exception { CliGitCommand gitCmd = new CliGitCommand(null); gitCmd.setDefaults(); } @Before public void enableSystemCredentialsProvider() throws Exception { SystemCredentialsProvider.getInstance().setDomainCredentialsMap( Collections.singletonMap(Domain.global(), Collections.<Credentials>emptyList())); for (CredentialsStore s : CredentialsProvider.lookupStores(Jenkins.getInstance())) { if (s.getProvider() instanceof SystemCredentialsProvider.ProviderImpl) { store = s; break; } } assertThat("The system credentials provider is enabled", store, notNullValue()); } private StandardCredentials getInvalidCredential() { String username = "bad-user"; String password = "bad-password"; CredentialsScope scope = CredentialsScope.GLOBAL; String id = "username-" + username + "-password-" + password; return new UsernamePasswordCredentialsImpl(scope, id, "desc: " + id, username, password); } @Test public void trackCredentials() throws Exception { StandardCredentials credential = getInvalidCredential(); store.addCredentials(Domain.global(), credential); Fingerprint fingerprint = CredentialsProvider.getFingerprintOf(credential); assertThat("Fingerprint should not be set before job definition", fingerprint, nullValue()); JenkinsRule.WebClient wc = rule.createWebClient(); HtmlPage page = wc.goTo("credentials/store/system/domain/_/credentials/" + credential.getId()); assertThat("Have usage tracking reported", page.getElementById("usage"), notNullValue()); assertThat("No fingerprint created until first use", page.getElementById("usage-missing"), notNullValue()); assertThat("No fingerprint created until first use", page.getElementById("usage-present"), nullValue()); FreeStyleProject project = setupProject("master", credential); fingerprint = CredentialsProvider.getFingerprintOf(credential); assertThat("Fingerprint should not be set before first build", fingerprint, nullValue()); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); fingerprint = CredentialsProvider.getFingerprintOf(credential); assertThat("Fingerprint should be set after first build", fingerprint, notNullValue()); assertThat(fingerprint.getJobs(), hasItem(is(project.getFullName()))); Fingerprint.RangeSet rangeSet = fingerprint.getRangeSet(project); assertThat(rangeSet, notNullValue()); assertThat(rangeSet.includes(project.getLastBuild().getNumber()), is(true)); page = wc.goTo("credentials/store/system/domain/_/credentials/" + credential.getId()); assertThat(page.getElementById("usage-missing"), nullValue()); assertThat(page.getElementById("usage-present"), notNullValue()); assertThat(page.getAnchorByText(project.getFullDisplayName()), notNullValue()); } /** * Basic test - create a GitSCM based project, check it out and build for the first time. * Next test that polling works correctly, make another commit, check that polling finds it, * then build it and finally test the build culprits as well as the contents of the workspace. * @throws Exception if an exception gets thrown. */ @Test public void testBasic() throws Exception { FreeStyleProject project = setupSimpleProject("master"); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have only one culprit", 1, culprits.size()); assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName()); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testBasicRemotePoll() throws Exception { // FreeStyleProject project = setupProject("master", true, false); FreeStyleProject project = setupProject("master", false, null, null, null, true, null); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); // ... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have only one culprit", 1, culprits.size()); assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName()); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testBranchSpecWithRemotesMaster() throws Exception { FreeStyleProject projectMasterBranch = setupProject("remotes/origin/master", false, null, null, null, true, null); // create initial commit and build final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(projectMasterBranch, Result.SUCCESS, commitFile1); } /** * This test and testSpecificRefspecsWithoutCloneOption confirm behaviors of * refspecs on initial clone. Without the CloneOption to honor refspec, all * references are cloned, even if they will be later ignored due to the * refspec. With the CloneOption to ignore refspec, the initial clone also * honors the refspec and only retrieves references per the refspec. * @throws Exception on error */ @Test @Issue("JENKINS-31393") public void testSpecificRefspecs() throws Exception { List<UserRemoteConfig> repos = new ArrayList<>(); repos.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", "+refs/heads/foo:refs/remotes/foo", null)); /* Set CloneOption to honor refspec on initial clone */ FreeStyleProject projectWithMaster = setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null); CloneOption cloneOptionMaster = new CloneOption(false, null, null); cloneOptionMaster.setHonorRefspec(true); ((GitSCM)projectWithMaster.getScm()).getExtensions().add(cloneOptionMaster); /* Set CloneOption to honor refspec on initial clone */ FreeStyleProject projectWithFoo = setupProject(repos, Collections.singletonList(new BranchSpec("foo")), null, false, null); CloneOption cloneOptionFoo = new CloneOption(false, null, null); cloneOptionFoo.setHonorRefspec(true); ((GitSCM)projectWithMaster.getScm()).getExtensions().add(cloneOptionFoo); // create initial commit final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit in master"); // create branch and make initial commit git.branch("foo"); git.checkout().branch("foo"); commit(commitFile1, johnDoe, "Commit in foo"); build(projectWithMaster, Result.FAILURE); build(projectWithFoo, Result.SUCCESS, commitFile1); } /** * This test and testSpecificRefspecs confirm behaviors of * refspecs on initial clone. Without the CloneOption to honor refspec, all * references are cloned, even if they will be later ignored due to the * refspec. With the CloneOption to ignore refspec, the initial clone also * honors the refspec and only retrieves references per the refspec. * @throws Exception on error */ @Test @Issue("JENKINS-36507") public void testSpecificRefspecsWithoutCloneOption() throws Exception { List<UserRemoteConfig> repos = new ArrayList<>(); repos.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", "+refs/heads/foo:refs/remotes/foo", null)); FreeStyleProject projectWithMaster = setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null); FreeStyleProject projectWithFoo = setupProject(repos, Collections.singletonList(new BranchSpec("foo")), null, false, null); // create initial commit final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit in master"); // create branch and make initial commit git.branch("foo"); git.checkout().branch("foo"); commit(commitFile1, johnDoe, "Commit in foo"); build(projectWithMaster, Result.SUCCESS); /* If clone refspec had been honored, this would fail */ build(projectWithFoo, Result.SUCCESS, commitFile1); } @Test public void testBranchSpecWithRemotesHierarchical() throws Exception { FreeStyleProject projectMasterBranch = setupProject("master", false, null, null, null, true, null); FreeStyleProject projectHierarchicalBranch = setupProject("remotes/origin/rel-1/xy", false, null, null, null, true, null); // create initial commit final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); // create hierarchical branch, delete master branch, and build git.branch("rel-1/xy"); git.checkout("rel-1/xy"); git.deleteBranch("master"); build(projectMasterBranch, Result.FAILURE); build(projectHierarchicalBranch, Result.SUCCESS, commitFile1); } @Test public void testBranchSpecUsingTagWithSlash() throws Exception { FreeStyleProject projectMasterBranch = setupProject("path/tag", false, null, null, null, true, null); // create initial commit and build final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1 will be tagged with path/tag"); testRepo.git.tag("path/tag", "tag with a slash in the tag name"); build(projectMasterBranch, Result.SUCCESS, commitFile1); } @Test public void testBasicIncludedRegion() throws Exception { FreeStyleProject project = setupProject("master", false, null, null, null, ".*3"); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); assertFalse("scm polling detected commit2 change, which should not have been included", project.poll(listener).hasChanges()); final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); assertTrue("scm polling did not detect commit3 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2, commitFile3); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have two culprit", 2, culprits.size()); PersonIdent[] expected = {johnDoe, janeDoe}; assertCulprits("jane doe and john doe should be the culprits", culprits, expected); assertTrue(build2.getWorkspace().child(commitFile2).exists()); assertTrue(build2.getWorkspace().child(commitFile3).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testIncludedRegionWithDeeperCommits() throws Exception { FreeStyleProject project = setupProject("master", false, null, null, null, ".*3"); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); assertFalse("scm polling detected commit2 change, which should not have been included", project.poll(listener).hasChanges()); final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); final String commitFile4 = "commitFile4"; commit(commitFile4, janeDoe, "Commit number 4"); assertTrue("scm polling did not detect commit3 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2, commitFile3); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have two culprit", 2, culprits.size()); PersonIdent[] expected = {johnDoe, janeDoe}; assertCulprits("jane doe and john doe should be the culprits", culprits, expected); assertTrue(build2.getWorkspace().child(commitFile2).exists()); assertTrue(build2.getWorkspace().child(commitFile3).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testBasicExcludedRegion() throws Exception { FreeStyleProject project = setupProject("master", false, null, ".*2", null, null); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); assertFalse("scm polling detected commit2 change, which should have been excluded", project.poll(listener).hasChanges()); final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); assertTrue("scm polling did not detect commit3 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2, commitFile3); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have two culprit", 2, culprits.size()); PersonIdent[] expected = {johnDoe, janeDoe}; assertCulprits("jane doe and john doe should be the culprits", culprits, expected); assertTrue(build2.getWorkspace().child(commitFile2).exists()); assertTrue(build2.getWorkspace().child(commitFile3).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testCleanBeforeCheckout() throws Exception { FreeStyleProject p = setupProject("master", false, null, null, "Jane Doe", null); ((GitSCM)p.getScm()).getExtensions().add(new CleanBeforeCheckout()); final String commitFile1 = "commitFile1"; final String commitFile2 = "commitFile2"; commit(commitFile1, johnDoe, janeDoe, "Commit number 1"); commit(commitFile2, johnDoe, janeDoe, "Commit number 2"); final FreeStyleBuild firstBuild = build(p, Result.SUCCESS, commitFile1); final String branch1 = "Branch1"; final String branch2 = "Branch2"; List<BranchSpec> branches = new ArrayList<>(); branches.add(new BranchSpec("master")); branches.add(new BranchSpec(branch1)); branches.add(new BranchSpec(branch2)); git.branch(branch1); git.checkout(branch1); p.poll(listener).hasChanges(); assertTrue(firstBuild.getLog().contains("Cleaning")); assertTrue(firstBuild.getLog().indexOf("Cleaning") > firstBuild.getLog().indexOf("Cloning")); //clean should be after clone assertTrue(firstBuild.getLog().indexOf("Cleaning") < firstBuild.getLog().indexOf("Checking out")); //clean before checkout assertTrue(firstBuild.getWorkspace().child(commitFile1).exists()); git.checkout(branch1); final FreeStyleBuild secondBuild = build(p, Result.SUCCESS, commitFile2); p.poll(listener).hasChanges(); assertTrue(secondBuild.getLog().contains("Cleaning")); assertTrue(secondBuild.getLog().indexOf("Cleaning") < secondBuild.getLog().indexOf("Fetching upstream changes")); assertTrue(secondBuild.getWorkspace().child(commitFile2).exists()); } @Issue("JENKINS-8342") @Test public void testExcludedRegionMultiCommit() throws Exception { // Got 2 projects, each one should only build if changes in its own file FreeStyleProject clientProject = setupProject("master", false, null, ".*serverFile", null, null); FreeStyleProject serverProject = setupProject("master", false, null, ".*clientFile", null, null); String initialCommitFile = "initialFile"; commit(initialCommitFile, johnDoe, "initial commit"); build(clientProject, Result.SUCCESS, initialCommitFile); build(serverProject, Result.SUCCESS, initialCommitFile); assertFalse("scm polling should not detect any more changes after initial build", clientProject.poll(listener).hasChanges()); assertFalse("scm polling should not detect any more changes after initial build", serverProject.poll(listener).hasChanges()); // Got commits on serverFile, so only server project should build. commit("myserverFile", johnDoe, "commit first server file"); assertFalse("scm polling should not detect any changes in client project", clientProject.poll(listener).hasChanges()); assertTrue("scm polling did not detect changes in server project", serverProject.poll(listener).hasChanges()); // Got commits on both client and serverFile, so both projects should build. commit("myNewserverFile", johnDoe, "commit new server file"); commit("myclientFile", johnDoe, "commit first clientfile"); assertTrue("scm polling did not detect changes in client project", clientProject.poll(listener).hasChanges()); assertTrue("scm polling did not detect changes in server project", serverProject.poll(listener).hasChanges()); } /** * With multiple branches specified in the project and having commits from a user * excluded should not build the excluded revisions when another branch changes. */ /* @Issue("JENKINS-8342") @Test public void testMultipleBranchWithExcludedUser() throws Exception { final String branch1 = "Branch1"; final String branch2 = "Branch2"; List<BranchSpec> branches = new ArrayList<BranchSpec>(); branches.add(new BranchSpec("master")); branches.add(new BranchSpec(branch1)); branches.add(new BranchSpec(branch2)); final FreeStyleProject project = setupProject(branches, false, null, null, janeDoe.getName(), null, false, null); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); // create branches here so we can get back to them later... git.branch(branch1); git.branch(branch2); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); assertTrue("scm polling should detect changes in 'master' branch", project.poll(listener).hasChanges()); build(project, Result.SUCCESS, commitFile1, commitFile2); assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges()); // Add excluded commit final String commitFile4 = "commitFile4"; commit(commitFile4, janeDoe, "Commit number 4"); assertFalse("scm polling detected change in 'master', which should have been excluded", project.poll(listener).hasChanges()); // now jump back... git.checkout(branch1); final String branch1File1 = "branch1File1"; commit(branch1File1, janeDoe, "Branch1 commit number 1"); assertFalse("scm polling detected change in 'Branch1', which should have been excluded", project.poll(listener).hasChanges()); // and the other branch... git.checkout(branch2); final String branch2File1 = "branch2File1"; commit(branch2File1, janeDoe, "Branch2 commit number 1"); assertFalse("scm polling detected change in 'Branch2', which should have been excluded", project.poll(listener).hasChanges()); final String branch2File2 = "branch2File2"; commit(branch2File2, johnDoe, "Branch2 commit number 2"); assertTrue("scm polling should detect changes in 'Branch2' branch", project.poll(listener).hasChanges()); //... and build it... build(project, Result.SUCCESS, branch2File1, branch2File2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); // now jump back again... git.checkout(branch1); // Commit excluded after non-excluded commit, should trigger build. final String branch1File2 = "branch1File2"; commit(branch1File2, johnDoe, "Branch1 commit number 2"); final String branch1File3 = "branch1File3"; commit(branch1File3, janeDoe, "Branch1 commit number 3"); assertTrue("scm polling should detect changes in 'Branch1' branch", project.poll(listener).hasChanges()); build(project, Result.SUCCESS, branch1File1, branch1File2, branch1File3); } */ @Test public void testBasicExcludedUser() throws Exception { FreeStyleProject project = setupProject("master", false, null, null, "Jane Doe", null); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); assertFalse("scm polling detected commit2 change, which should have been excluded", project.poll(listener).hasChanges()); final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); assertTrue("scm polling did not detect commit3 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2, commitFile3); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have two culprit", 2, culprits.size()); PersonIdent[] expected = {johnDoe, janeDoe}; assertCulprits("jane doe and john doe should be the culprits", culprits, expected); assertTrue(build2.getWorkspace().child(commitFile2).exists()); assertTrue(build2.getWorkspace().child(commitFile3).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testBasicInSubdir() throws Exception { FreeStyleProject project = setupSimpleProject("master"); ((GitSCM)project.getScm()).getExtensions().add(new RelativeTargetDirectory("subdir")); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, "subdir", Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, "subdir", Result.SUCCESS, commitFile2); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have only one culprit", 1, culprits.size()); assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName()); assertEquals("The workspace should have a 'subdir' subdirectory, but does not.", true, build2.getWorkspace().child("subdir").exists()); assertEquals("The 'subdir' subdirectory should contain commitFile2, but does not.", true, build2.getWorkspace().child("subdir").child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testBasicWithSlave() throws Exception { FreeStyleProject project = setupSimpleProject("master"); project.setAssignedLabel(rule.createSlave().getSelfLabel()); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have only one culprit", 1, culprits.size()); assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName()); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Issue("HUDSON-7547") @Test public void testBasicWithSlaveNoExecutorsOnMaster() throws Exception { FreeStyleProject project = setupSimpleProject("master"); rule.jenkins.setNumExecutors(0); project.setAssignedLabel(rule.createSlave().getSelfLabel()); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have only one culprit", 1, culprits.size()); assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName()); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testAuthorOrCommitterFalse() throws Exception { // Test with authorOrCommitter set to false and make sure we get the committer. FreeStyleProject project = setupSimpleProject("master"); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, janeDoe, "Commit number 1"); final FreeStyleBuild firstBuild = build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, janeDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); final FreeStyleBuild secondBuild = build(project, Result.SUCCESS, commitFile2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final Set<User> secondCulprits = secondBuild.getCulprits(); assertEquals("The build should have only one culprit", 1, secondCulprits.size()); assertEquals("Did not get the committer as the change author with authorOrCommitter==false", janeDoe.getName(), secondCulprits.iterator().next().getFullName()); } @Test public void testAuthorOrCommitterTrue() throws Exception { // Next, test with authorOrCommitter set to true and make sure we get the author. FreeStyleProject project = setupSimpleProject("master"); ((GitSCM)project.getScm()).getExtensions().add(new AuthorInChangelog()); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, janeDoe, "Commit number 1"); final FreeStyleBuild firstBuild = build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, janeDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); final FreeStyleBuild secondBuild = build(project, Result.SUCCESS, commitFile2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final Set<User> secondCulprits = secondBuild.getCulprits(); assertEquals("The build should have only one culprit", 1, secondCulprits.size()); assertEquals("Did not get the author as the change author with authorOrCommitter==true", johnDoe.getName(), secondCulprits.iterator().next().getFullName()); } /** * Method name is self-explanatory. */ @Test public void testNewCommitToUntrackedBranchDoesNotTriggerBuild() throws Exception { FreeStyleProject project = setupSimpleProject("master"); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); //now create and checkout a new branch: git.checkout(Constants.HEAD, "untracked"); //.. and commit to it: final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); assertFalse("scm polling should not detect commit2 change because it is not in the branch we are tracking.", project.poll(listener).hasChanges()); } private String checkoutString(FreeStyleProject project, String envVar) { return "checkout -f " + getEnvVars(project).get(envVar); } @Test public void testEnvVarsAvailable() throws Exception { FreeStyleProject project = setupSimpleProject("master"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertEquals("origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH)); rule.assertLogContains(getEnvVars(project).get(GitSCM.GIT_BRANCH), build1); rule.assertLogContains(checkoutString(project, GitSCM.GIT_COMMIT), build1); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); rule.assertLogNotContains(checkoutString(project, GitSCM.GIT_PREVIOUS_COMMIT), build2); rule.assertLogContains(checkoutString(project, GitSCM.GIT_PREVIOUS_COMMIT), build1); rule.assertLogNotContains(checkoutString(project, GitSCM.GIT_PREVIOUS_SUCCESSFUL_COMMIT), build2); rule.assertLogContains(checkoutString(project, GitSCM.GIT_PREVIOUS_SUCCESSFUL_COMMIT), build1); } @Issue("HUDSON-7411") @Test public void testNodeEnvVarsAvailable() throws Exception { FreeStyleProject project = setupSimpleProject("master"); Node s = rule.createSlave(); setVariables(s, new Entry("TESTKEY", "slaveValue")); project.setAssignedLabel(s.getSelfLabel()); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertEquals("slaveValue", getEnvVars(project).get("TESTKEY")); } /** * A previous version of GitSCM would only build against branches, not tags. This test checks that that * regression has been fixed. */ @Test public void testGitSCMCanBuildAgainstTags() throws Exception { final String mytag = "mytag"; FreeStyleProject project = setupSimpleProject(mytag); build(project, Result.FAILURE); // fail, because there's nothing to be checked out here final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); // Try again. The first build will leave the repository in a bad state because we // cloned something without even a HEAD - which will mean it will want to re-clone once there is some // actual data. build(project, Result.FAILURE); // fail, because there's nothing to be checked out here //now create and checkout a new branch: final String tmpBranch = "tmp"; git.branch(tmpBranch); git.checkout(tmpBranch); // commit to it final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); assertFalse("scm polling should not detect any more changes since mytag is untouched right now", project.poll(listener).hasChanges()); build(project, Result.FAILURE); // fail, because there's nothing to be checked out here // tag it, then delete the tmp branch git.tag(mytag, "mytag initial"); git.checkout("master"); git.deleteBranch(tmpBranch); // at this point we're back on master, there are no other branches, tag "mytag" exists but is // not part of "master" assertTrue("scm polling should detect commit2 change in 'mytag'", project.poll(listener).hasChanges()); build(project, Result.SUCCESS, commitFile2); assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges()); // now, create tmp branch again against mytag: git.checkout(mytag); git.branch(tmpBranch); // another commit: final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); assertFalse("scm polling should not detect any more changes since mytag is untouched right now", project.poll(listener).hasChanges()); // now we're going to force mytag to point to the new commit, if everything goes well, gitSCM should pick the change up: git.tag(mytag, "mytag moved"); git.checkout("master"); git.deleteBranch(tmpBranch); if (sampleRepo.gitVersionAtLeast(2, 20, 0)) { /* Newer CLI git versions fail this test unless they have newer git client */ /* Don't want to force users onto a newer git client, so we skip the final build and assertions on git 2.20 and newer */ return; } // at this point we're back on master, there are no other branches, "mytag" has been updated to a new commit: assertTrue("scm polling should detect commit3 change in 'mytag'", project.poll(listener).hasChanges()); build(project, Result.SUCCESS, commitFile3); assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges()); } /** * Not specifying a branch string in the project implies that we should be polling for changes in * all branches. */ @Test public void testMultipleBranchBuild() throws Exception { // empty string will result in a project that tracks against changes in all branches: final FreeStyleProject project = setupSimpleProject(""); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); // create a branch here so we can get back to this point later... final String fork = "fork"; git.branch(fork); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); assertTrue("scm polling should detect changes in 'master' branch", project.poll(listener).hasChanges()); build(project, Result.SUCCESS, commitFile1, commitFile2); assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges()); // now jump back... git.checkout(fork); // add some commits to the fork branch... final String forkFile1 = "forkFile1"; commit(forkFile1, johnDoe, "Fork commit number 1"); final String forkFile2 = "forkFile2"; commit(forkFile2, johnDoe, "Fork commit number 2"); assertTrue("scm polling should detect changes in 'fork' branch", project.poll(listener).hasChanges()); build(project, Result.SUCCESS, forkFile1, forkFile2); assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges()); } @Test public void testMultipleBranchesWithTags() throws Exception { List<BranchSpec> branchSpecs = Arrays.asList( new BranchSpec("refs/tags/v*"), new BranchSpec("refs/remotes/origin/non-existent")); FreeStyleProject project = setupProject(branchSpecs, false, null, null, janeDoe.getName(), null, false, null); // create initial commit and then run the build against it: // Here the changelog is by default empty (because changelog for first commit is always empty commit("commitFileBase", johnDoe, "Initial Commit"); // there are no branches to be build FreeStyleBuild freeStyleBuild = build(project, Result.FAILURE); final String v1 = "v1"; git.tag(v1, "version 1"); assertTrue("v1 tag exists", git.tagExists(v1)); freeStyleBuild = build(project, Result.SUCCESS); assertTrue("change set is empty", freeStyleBuild.getChangeSet().isEmptySet()); commit("file1", johnDoe, "change to file1"); git.tag("none", "latest"); freeStyleBuild = build(project, Result.SUCCESS); ObjectId tag = git.revParse(Constants.R_TAGS + v1); GitSCM scm = (GitSCM)project.getScm(); BuildData buildData = scm.getBuildData(freeStyleBuild); assertEquals("last build matches the v1 tag revision", tag, buildData.lastBuild.getSHA1()); } @Issue("JENKINS-19037") @SuppressWarnings("ResultOfObjectAllocationIgnored") @Test public void testBlankRepositoryName() throws Exception { new GitSCM(null); } @Issue("JENKINS-10060") @Test public void testSubmoduleFixup() throws Exception { File repo = secondRepo.getRoot(); FilePath moduleWs = new FilePath(repo); org.jenkinsci.plugins.gitclient.GitClient moduleRepo = Git.with(listener, new EnvVars()).in(repo).getClient(); {// first we create a Git repository with submodule moduleRepo.init(); moduleWs.child("a").touch(0); moduleRepo.add("a"); moduleRepo.commit("creating a module"); git.addSubmodule(repo.getAbsolutePath(), "module1"); git.commit("creating a super project"); } // configure two uproject 'u' -> 'd' that's chained together. FreeStyleProject u = createFreeStyleProject(); FreeStyleProject d = createFreeStyleProject(); u.setScm(new GitSCM(workDir.getPath())); u.getPublishersList().add(new BuildTrigger(new hudson.plugins.parameterizedtrigger.BuildTriggerConfig(d.getName(), ResultCondition.SUCCESS, new GitRevisionBuildParameters()))); d.setScm(new GitSCM(workDir.getPath())); rule.jenkins.rebuildDependencyGraph(); FreeStyleBuild ub = rule.assertBuildStatusSuccess(u.scheduleBuild2(0)); System.out.println(ub.getLog()); for (int i=0; (d.getLastBuild()==null || d.getLastBuild().isBuilding()) && i<100; i++) // wait only up to 10 sec to avoid infinite loop Thread.sleep(100); FreeStyleBuild db = d.getLastBuild(); assertNotNull("downstream build didn't happen",db); rule.assertBuildStatusSuccess(db); } @Test public void testBuildChooserContext() throws Exception { final FreeStyleProject p = createFreeStyleProject(); final FreeStyleBuild b = rule.assertBuildStatusSuccess(p.scheduleBuild2(0)); BuildChooserContextImpl c = new BuildChooserContextImpl(p, b, null); c.actOnBuild(new ContextCallable<Run<?,?>, Object>() { public Object invoke(Run param, VirtualChannel channel) throws IOException, InterruptedException { assertSame(param,b); return null; } }); c.actOnProject(new ContextCallable<Job<?,?>, Object>() { public Object invoke(Job param, VirtualChannel channel) throws IOException, InterruptedException { assertSame(param,p); return null; } }); DumbSlave s = rule.createOnlineSlave(); assertEquals(p.toString(), s.getChannel().call(new BuildChooserContextTestCallable(c))); } private static class BuildChooserContextTestCallable extends MasterToSlaveCallable<String,IOException> { private final BuildChooserContext c; public BuildChooserContextTestCallable(BuildChooserContext c) { this.c = c; } public String call() throws IOException { try { return c.actOnProject(new ContextCallable<Job<?,?>, String>() { public String invoke(Job<?,?> param, VirtualChannel channel) throws IOException, InterruptedException { assertTrue(channel instanceof Channel); assertTrue(Hudson.getInstance()!=null); return param.toString(); } }); } catch (InterruptedException e) { throw new IOException(e); } } } // eg: "jane doe and john doe should be the culprits", culprits, [johnDoe, janeDoe]) static public void assertCulprits(String assertMsg, Set<User> actual, PersonIdent[] expected) { Collection<String> fullNames = Collections2.transform(actual, new Function<User,String>() { public String apply(User u) { return u.getFullName(); } }); for(PersonIdent p : expected) { assertTrue(assertMsg, fullNames.contains(p.getName())); } } @Test public void testEmailCommitter() throws Exception { FreeStyleProject project = setupSimpleProject("master"); // setup global config GitSCM scm = (GitSCM) project.getScm(); final DescriptorImpl descriptor = (DescriptorImpl) scm.getDescriptor(); assertFalse("Wrong initial value for create account based on e-mail", scm.isCreateAccountBasedOnEmail()); descriptor.setCreateAccountBasedOnEmail(true); assertTrue("Create account based on e-mail not set", scm.isCreateAccountBasedOnEmail()); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final FreeStyleBuild build = build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; final PersonIdent jeffDoe = new PersonIdent("Jeff Doe", "[email protected]"); commit(commitFile2, jeffDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have only one culprit", 1, culprits.size()); User culprit = culprits.iterator().next(); assertEquals("", jeffDoe.getEmailAddress(), culprit.getId()); assertEquals("", jeffDoe.getName(), culprit.getFullName()); rule.assertBuildStatusSuccess(build); } // Disabled - consistently fails, needs more analysis // @Test public void testFetchFromMultipleRepositories() throws Exception { FreeStyleProject project = setupSimpleProject("master"); TestGitRepo secondTestRepo = new TestGitRepo("second", secondRepo.getRoot(), listener); List<UserRemoteConfig> remotes = new ArrayList<>(); remotes.addAll(testRepo.remoteConfigs()); remotes.addAll(secondTestRepo.remoteConfigs()); project.setScm(new GitSCM( remotes, Collections.singletonList(new BranchSpec("master")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList())); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); /* Diagnostic help - for later use */ SCMRevisionState baseline = project.poll(listener).baseline; Change change = project.poll(listener).change; SCMRevisionState remote = project.poll(listener).remote; String assertionMessage = MessageFormat.format("polling incorrectly detected change after build. Baseline: {0}, Change: {1}, Remote: {2}", baseline, change, remote); assertFalse(assertionMessage, project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; secondTestRepo.commit(commitFile2, janeDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } private void branchSpecWithMultipleRepositories(String branchName) throws Exception { FreeStyleProject project = setupSimpleProject("master"); TestGitRepo secondTestRepo = new TestGitRepo("second", secondRepo.getRoot(), listener); List<UserRemoteConfig> remotes = new ArrayList<>(); remotes.addAll(testRepo.remoteConfigs()); remotes.addAll(secondTestRepo.remoteConfigs()); // create initial commit final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); project.setScm(new GitSCM( remotes, Collections.singletonList(new BranchSpec(branchName)), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList())); final FreeStyleBuild build = build(project, Result.SUCCESS, commitFile1); rule.assertBuildStatusSuccess(build); } @Issue("JENKINS-26268") public void testBranchSpecAsSHA1WithMultipleRepositories() throws Exception { branchSpecWithMultipleRepositories(testRepo.git.revParse("HEAD").getName()); } @Issue("JENKINS-26268") public void testBranchSpecAsRemotesOriginMasterWithMultipleRepositories() throws Exception { branchSpecWithMultipleRepositories("remotes/origin/master"); } @Issue("JENKINS-25639") @Test public void testCommitDetectedOnlyOnceInMultipleRepositories() throws Exception { FreeStyleProject project = setupSimpleProject("master"); TestGitRepo secondTestRepo = new TestGitRepo("secondRepo", secondRepo.getRoot(), listener); List<UserRemoteConfig> remotes = new ArrayList<>(); remotes.addAll(testRepo.remoteConfigs()); remotes.addAll(secondTestRepo.remoteConfigs()); GitSCM gitSCM = new GitSCM( remotes, Collections.singletonList(new BranchSpec("origin/master")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); project.setScm(gitSCM); commit("commitFile1", johnDoe, "Commit number 1"); FreeStyleBuild build = build(project, Result.SUCCESS, "commitFile1"); commit("commitFile2", johnDoe, "Commit number 2"); git = Git.with(listener, new EnvVars()).in(build.getWorkspace()).getClient(); for (RemoteConfig remoteConfig : gitSCM.getRepositories()) { git.fetch_().from(remoteConfig.getURIs().get(0), remoteConfig.getFetchRefSpecs()); } BuildChooser buildChooser = gitSCM.getBuildChooser(); Collection<Revision> candidateRevisions = buildChooser.getCandidateRevisions(false, "origin/master", git, listener, project.getLastBuild().getAction(BuildData.class), null); assertEquals(1, candidateRevisions.size()); gitSCM.setBuildChooser(buildChooser); // Should be a no-op Collection<Revision> candidateRevisions2 = buildChooser.getCandidateRevisions(false, "origin/master", git, listener, project.getLastBuild().getAction(BuildData.class), null); assertThat(candidateRevisions2, is(candidateRevisions)); } private final Random random = new Random(); private boolean useChangelogToBranch = random.nextBoolean(); private void addChangelogToBranchExtension(GitSCM scm) { if (useChangelogToBranch) { /* Changelog should be no different with this enabled or disabled */ ChangelogToBranchOptions changelogOptions = new ChangelogToBranchOptions("origin", "master"); scm.getExtensions().add(new ChangelogToBranch(changelogOptions)); } useChangelogToBranch = !useChangelogToBranch; } @Test public void testMerge() throws Exception { FreeStyleProject project = setupSimpleProject("master"); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("*")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", "default", MergeCommand.GitPluginFastForwardMode.FF))); addChangelogToBranchExtension(scm); project.setScm(scm); // create initial commit and then run the build against it: commit("commitFileBase", johnDoe, "Initial Commit"); testRepo.git.branch("integration"); build(project, Result.SUCCESS, "commitFileBase"); testRepo.git.checkout(null, "topic1"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertTrue(build1.getWorkspace().child(commitFile1).exists()); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); // do what the GitPublisher would do testRepo.git.deleteBranch("integration"); testRepo.git.checkout("topic1", "integration"); testRepo.git.checkout("master", "topic2"); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Issue("JENKINS-20392") @Test public void testMergeChangelog() throws Exception { FreeStyleProject project = setupSimpleProject("master"); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("*")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", "default", MergeCommand.GitPluginFastForwardMode.FF))); addChangelogToBranchExtension(scm); project.setScm(scm); // create initial commit and then run the build against it: // Here the changelog is by default empty (because changelog for first commit is always empty commit("commitFileBase", johnDoe, "Initial Commit"); testRepo.git.branch("integration"); build(project, Result.SUCCESS, "commitFileBase"); // Create second commit and run build // Here the changelog should contain exactly this one new commit testRepo.git.checkout("master", "topic2"); final String commitFile2 = "commitFile2"; String commitMessage = "Commit number 2"; commit(commitFile2, johnDoe, commitMessage); final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); ChangeLogSet<? extends ChangeLogSet.Entry> changeLog = build2.getChangeSet(); assertEquals("Changelog should contain one item", 1, changeLog.getItems().length); GitChangeSet singleChange = (GitChangeSet) changeLog.getItems()[0]; assertEquals("Changelog should contain commit number 2", commitMessage, singleChange.getComment().trim()); } @Test public void testMergeWithSlave() throws Exception { FreeStyleProject project = setupSimpleProject("master"); project.setAssignedLabel(rule.createSlave().getSelfLabel()); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("*")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", null, null))); addChangelogToBranchExtension(scm); project.setScm(scm); // create initial commit and then run the build against it: commit("commitFileBase", johnDoe, "Initial Commit"); testRepo.git.branch("integration"); build(project, Result.SUCCESS, "commitFileBase"); testRepo.git.checkout(null, "topic1"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertTrue(build1.getWorkspace().child(commitFile1).exists()); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); // do what the GitPublisher would do testRepo.git.deleteBranch("integration"); testRepo.git.checkout("topic1", "integration"); testRepo.git.checkout("master", "topic2"); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testMergeFailed() throws Exception { FreeStyleProject project = setupSimpleProject("master"); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("*")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); project.setScm(scm); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", "", MergeCommand.GitPluginFastForwardMode.FF))); addChangelogToBranchExtension(scm); // create initial commit and then run the build against it: commit("commitFileBase", johnDoe, "Initial Commit"); testRepo.git.branch("integration"); build(project, Result.SUCCESS, "commitFileBase"); testRepo.git.checkout(null, "topic1"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertTrue(build1.getWorkspace().child(commitFile1).exists()); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); // do what the GitPublisher would do testRepo.git.deleteBranch("integration"); testRepo.git.checkout("topic1", "integration"); testRepo.git.checkout("master", "topic2"); commit(commitFile1, "other content", johnDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); final FreeStyleBuild build2 = build(project, Result.FAILURE); rule.assertBuildStatus(Result.FAILURE, build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Issue("JENKINS-25191") @Test public void testMultipleMergeFailed() throws Exception { FreeStyleProject project = setupSimpleProject("master"); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("master")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); project.setScm(scm); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration1", "", MergeCommand.GitPluginFastForwardMode.FF))); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration2", "", MergeCommand.GitPluginFastForwardMode.FF))); addChangelogToBranchExtension(scm); commit("dummyFile", johnDoe, "Initial Commit"); testRepo.git.branch("integration1"); testRepo.git.branch("integration2"); build(project, Result.SUCCESS); final String commitFile = "commitFile"; testRepo.git.checkoutBranch("integration1","master"); commit(commitFile,"abc", johnDoe, "merge conflict with integration2"); testRepo.git.checkoutBranch("integration2","master"); commit(commitFile,"cde", johnDoe, "merge conflict with integration1"); final FreeStyleBuild build = build(project, Result.FAILURE); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testMergeFailedWithSlave() throws Exception { FreeStyleProject project = setupSimpleProject("master"); project.setAssignedLabel(rule.createSlave().getSelfLabel()); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("*")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", null, null))); addChangelogToBranchExtension(scm); project.setScm(scm); // create initial commit and then run the build against it: commit("commitFileBase", johnDoe, "Initial Commit"); testRepo.git.branch("integration"); build(project, Result.SUCCESS, "commitFileBase"); testRepo.git.checkout(null, "topic1"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertTrue(build1.getWorkspace().child(commitFile1).exists()); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); // do what the GitPublisher would do testRepo.git.deleteBranch("integration"); testRepo.git.checkout("topic1", "integration"); testRepo.git.checkout("master", "topic2"); commit(commitFile1, "other content", johnDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); final FreeStyleBuild build2 = build(project, Result.FAILURE); rule.assertBuildStatus(Result.FAILURE, build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testMergeWithMatrixBuild() throws Exception { //Create a matrix project and a couple of axes MatrixProject project = rule.jenkins.createProject(MatrixProject.class, "xyz"); project.setAxes(new AxisList(new Axis("VAR","a","b"))); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("*")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", null, null))); addChangelogToBranchExtension(scm); project.setScm(scm); // create initial commit and then run the build against it: commit("commitFileBase", johnDoe, "Initial Commit"); testRepo.git.branch("integration"); build(project, Result.SUCCESS, "commitFileBase"); testRepo.git.checkout(null, "topic1"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final MatrixBuild build1 = build(project, Result.SUCCESS, commitFile1); assertTrue(build1.getWorkspace().child(commitFile1).exists()); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); // do what the GitPublisher would do testRepo.git.deleteBranch("integration"); testRepo.git.checkout("topic1", "integration"); testRepo.git.checkout("master", "topic2"); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); final MatrixBuild build2 = build(project, Result.SUCCESS, commitFile2); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testEnvironmentVariableExpansion() throws Exception { FreeStyleProject project = createFreeStyleProject(); project.setScm(new GitSCM("${CAT}"+testRepo.gitDir.getPath())); // create initial commit and then run the build against it: commit("a.txt", johnDoe, "Initial Commit"); build(project, Result.SUCCESS, "a.txt"); PollingResult r = project.poll(StreamTaskListener.fromStdout()); assertFalse(r.hasChanges()); commit("b.txt", johnDoe, "Another commit"); r = project.poll(StreamTaskListener.fromStdout()); assertTrue(r.hasChanges()); build(project, Result.SUCCESS, "b.txt"); } @TestExtension("testEnvironmentVariableExpansion") public static class SupplySomeEnvVars extends EnvironmentContributor { @Override public void buildEnvironmentFor(Run r, EnvVars envs, TaskListener listener) throws IOException, InterruptedException { envs.put("CAT",""); } } private List<UserRemoteConfig> createRepoList(String url) { List<UserRemoteConfig> repoList = new ArrayList<>(); repoList.add(new UserRemoteConfig(url, null, null, null)); return repoList; } /** * Makes sure that git browser URL is preserved across config round trip. */ @Issue("JENKINS-22604") @Test public void testConfigRoundtripURLPreserved() throws Exception { FreeStyleProject p = createFreeStyleProject(); final String url = "https://github.com/jenkinsci/jenkins"; GitRepositoryBrowser browser = new GithubWeb(url); GitSCM scm = new GitSCM(createRepoList(url), Collections.singletonList(new BranchSpec("")), false, Collections.<SubmoduleConfig>emptyList(), browser, null, null); p.setScm(scm); rule.configRoundtrip(p); rule.assertEqualDataBoundBeans(scm,p.getScm()); assertEquals("Wrong key", "git " + url, scm.getKey()); } /** * Makes sure that git extensions are preserved across config round trip. */ @Issue("JENKINS-33695") @Test public void testConfigRoundtripExtensionsPreserved() throws Exception { FreeStyleProject p = createFreeStyleProject(); final String url = "git://github.com/jenkinsci/git-plugin.git"; GitRepositoryBrowser browser = new GithubWeb(url); GitSCM scm = new GitSCM(createRepoList(url), Collections.singletonList(new BranchSpec("*/master")), false, Collections.<SubmoduleConfig>emptyList(), browser, null, null); p.setScm(scm); /* Assert that no extensions are loaded initially */ assertEquals(Collections.emptyList(), scm.getExtensions().toList()); /* Add LocalBranch extension */ LocalBranch localBranchExtension = new LocalBranch("**"); scm.getExtensions().add(localBranchExtension); assertTrue(scm.getExtensions().toList().contains(localBranchExtension)); /* Save the configuration */ rule.configRoundtrip(p); List<GitSCMExtension> extensions = scm.getExtensions().toList();; assertTrue(extensions.contains(localBranchExtension)); assertEquals("Wrong extension count before reload", 1, extensions.size()); /* Reload configuration from disc */ p.doReload(); GitSCM reloadedGit = (GitSCM) p.getScm(); List<GitSCMExtension> reloadedExtensions = reloadedGit.getExtensions().toList(); assertEquals("Wrong extension count after reload", 1, reloadedExtensions.size()); LocalBranch reloadedLocalBranch = (LocalBranch) reloadedExtensions.get(0); assertEquals(localBranchExtension.getLocalBranch(), reloadedLocalBranch.getLocalBranch()); } /** * Makes sure that the configuration form works. */ @Test public void testConfigRoundtrip() throws Exception { FreeStyleProject p = createFreeStyleProject(); GitSCM scm = new GitSCM("https://github.com/jenkinsci/jenkins"); p.setScm(scm); rule.configRoundtrip(p); rule.assertEqualDataBoundBeans(scm,p.getScm()); } /** * Sample configuration that should result in no extensions at all */ @Test public void testDataCompatibility1() throws Exception { FreeStyleProject p = (FreeStyleProject) rule.jenkins.createProjectFromXML("foo", getClass().getResourceAsStream("GitSCMTest/old1.xml")); GitSCM oldGit = (GitSCM) p.getScm(); assertEquals(Collections.emptyList(), oldGit.getExtensions().toList()); assertEquals(0, oldGit.getSubmoduleCfg().size()); assertEquals("git git://github.com/jenkinsci/model-ant-project.git", oldGit.getKey()); assertThat(oldGit.getEffectiveBrowser(), instanceOf(GithubWeb.class)); GithubWeb browser = (GithubWeb) oldGit.getEffectiveBrowser(); assertEquals(browser.getRepoUrl(), "https://github.com/jenkinsci/model-ant-project.git/"); } @Test public void testPleaseDontContinueAnyway() throws Exception { // create an empty repository with some commits testRepo.commit("a","foo",johnDoe, "added"); FreeStyleProject p = createFreeStyleProject(); p.setScm(new GitSCM(testRepo.gitDir.getAbsolutePath())); rule.assertBuildStatusSuccess(p.scheduleBuild2(0)); // this should fail as it fails to fetch p.setScm(new GitSCM("http://localhost:4321/no/such/repository.git")); rule.assertBuildStatus(Result.FAILURE, p.scheduleBuild2(0).get()); } @Issue("JENKINS-19108") @Test public void testCheckoutToSpecificBranch() throws Exception { FreeStyleProject p = createFreeStyleProject(); GitSCM oldGit = new GitSCM("https://github.com/jenkinsci/model-ant-project.git/"); setupJGit(oldGit); oldGit.getExtensions().add(new LocalBranch("master")); p.setScm(oldGit); FreeStyleBuild b = rule.assertBuildStatusSuccess(p.scheduleBuild2(0)); GitClient gc = Git.with(StreamTaskListener.fromStdout(),null).in(b.getWorkspace()).getClient(); gc.withRepository(new RepositoryCallback<Void>() { public Void invoke(Repository repo, VirtualChannel channel) throws IOException, InterruptedException { Ref head = repo.getRef("HEAD"); assertTrue("Detached HEAD",head.isSymbolic()); Ref t = head.getTarget(); assertEquals(t.getName(),"refs/heads/master"); return null; } }); } /** * Verifies that if project specifies LocalBranch with value of "**" * that the checkout to a local branch using remote branch name sans 'origin'. * This feature is necessary to support Maven release builds that push updated * pom.xml to remote branch as * <br/> * <pre> * git push origin localbranch:localbranch * </pre> * @throws Exception */ @Test public void testCheckoutToDefaultLocalBranch_StarStar() throws Exception { FreeStyleProject project = setupSimpleProject("master"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); GitSCM git = (GitSCM)project.getScm(); git.getExtensions().add(new LocalBranch("**")); FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertEquals("GIT_BRANCH", "origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH)); assertEquals("GIT_LOCAL_BRANCH", "master", getEnvVars(project).get(GitSCM.GIT_LOCAL_BRANCH)); } /** * Verifies that if project specifies LocalBranch with null value (empty string) * that the checkout to a local branch using remote branch name sans 'origin'. * This feature is necessary to support Maven release builds that push updated * pom.xml to remote branch as * <br/> * <pre> * git push origin localbranch:localbranch * </pre> * @throws Exception */ @Test public void testCheckoutToDefaultLocalBranch_NULL() throws Exception { FreeStyleProject project = setupSimpleProject("master"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); GitSCM git = (GitSCM)project.getScm(); git.getExtensions().add(new LocalBranch("")); FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertEquals("GIT_BRANCH", "origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH)); assertEquals("GIT_LOCAL_BRANCH", "master", getEnvVars(project).get(GitSCM.GIT_LOCAL_BRANCH)); } /** * Verifies that GIT_LOCAL_BRANCH is not set if LocalBranch extension * is not configured. * @throws Exception */ @Test public void testCheckoutSansLocalBranchExtension() throws Exception { FreeStyleProject project = setupSimpleProject("master"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertEquals("GIT_BRANCH", "origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH)); assertEquals("GIT_LOCAL_BRANCH", null, getEnvVars(project).get(GitSCM.GIT_LOCAL_BRANCH)); } @Test public void testCheckoutFailureIsRetryable() throws Exception { FreeStyleProject project = setupSimpleProject("master"); // run build first to create workspace final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); // create lock file to simulate lock collision File lock = new File(build1.getWorkspace().toString(), ".git/index.lock"); try { FileUtils.touch(lock); final FreeStyleBuild build2 = build(project, Result.FAILURE); rule.assertLogContains("java.io.IOException: Could not checkout", build2); } finally { lock.delete(); } } @Test public void testInitSparseCheckout() throws Exception { if (!sampleRepo.gitVersionAtLeast(1, 7, 10)) { /* Older git versions have unexpected behaviors with sparse checkout */ return; } FreeStyleProject project = setupProject("master", Lists.newArrayList(new SparseCheckoutPath("toto"))); // run build first to create workspace final String commitFile1 = "toto/commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final String commitFile2 = "titi/commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); final FreeStyleBuild build1 = build(project, Result.SUCCESS); assertTrue(build1.getWorkspace().child("toto").exists()); assertTrue(build1.getWorkspace().child(commitFile1).exists()); assertFalse(build1.getWorkspace().child("titi").exists()); assertFalse(build1.getWorkspace().child(commitFile2).exists()); } @Test public void testInitSparseCheckoutBis() throws Exception { if (!sampleRepo.gitVersionAtLeast(1, 7, 10)) { /* Older git versions have unexpected behaviors with sparse checkout */ return; } FreeStyleProject project = setupProject("master", Lists.newArrayList(new SparseCheckoutPath("titi"))); // run build first to create workspace final String commitFile1 = "toto/commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final String commitFile2 = "titi/commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); final FreeStyleBuild build1 = build(project, Result.SUCCESS); assertTrue(build1.getWorkspace().child("titi").exists()); assertTrue(build1.getWorkspace().child(commitFile2).exists()); assertFalse(build1.getWorkspace().child("toto").exists()); assertFalse(build1.getWorkspace().child(commitFile1).exists()); } @Test public void testSparseCheckoutAfterNormalCheckout() throws Exception { if (!sampleRepo.gitVersionAtLeast(1, 7, 10)) { /* Older git versions have unexpected behaviors with sparse checkout */ return; } FreeStyleProject project = setupSimpleProject("master"); // run build first to create workspace final String commitFile1 = "toto/commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final String commitFile2 = "titi/commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); final FreeStyleBuild build1 = build(project, Result.SUCCESS); assertTrue(build1.getWorkspace().child("titi").exists()); assertTrue(build1.getWorkspace().child(commitFile2).exists()); assertTrue(build1.getWorkspace().child("toto").exists()); assertTrue(build1.getWorkspace().child(commitFile1).exists()); ((GitSCM) project.getScm()).getExtensions().add(new SparseCheckoutPaths(Lists.newArrayList(new SparseCheckoutPath("titi")))); final FreeStyleBuild build2 = build(project, Result.SUCCESS); assertTrue(build2.getWorkspace().child("titi").exists()); assertTrue(build2.getWorkspace().child(commitFile2).exists()); assertFalse(build2.getWorkspace().child("toto").exists()); assertFalse(build2.getWorkspace().child(commitFile1).exists()); } @Test public void testNormalCheckoutAfterSparseCheckout() throws Exception { if (!sampleRepo.gitVersionAtLeast(1, 7, 10)) { /* Older git versions have unexpected behaviors with sparse checkout */ return; } FreeStyleProject project = setupProject("master", Lists.newArrayList(new SparseCheckoutPath("titi"))); // run build first to create workspace final String commitFile1 = "toto/commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final String commitFile2 = "titi/commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); final FreeStyleBuild build2 = build(project, Result.SUCCESS); assertTrue(build2.getWorkspace().child("titi").exists()); assertTrue(build2.getWorkspace().child(commitFile2).exists()); assertFalse(build2.getWorkspace().child("toto").exists()); assertFalse(build2.getWorkspace().child(commitFile1).exists()); ((GitSCM) project.getScm()).getExtensions().remove(SparseCheckoutPaths.class); final FreeStyleBuild build1 = build(project, Result.SUCCESS); assertTrue(build1.getWorkspace().child("titi").exists()); assertTrue(build1.getWorkspace().child(commitFile2).exists()); assertTrue(build1.getWorkspace().child("toto").exists()); assertTrue(build1.getWorkspace().child(commitFile1).exists()); } @Test public void testInitSparseCheckoutOverSlave() throws Exception { if (!sampleRepo.gitVersionAtLeast(1, 7, 10)) { /* Older git versions have unexpected behaviors with sparse checkout */ return; } FreeStyleProject project = setupProject("master", Lists.newArrayList(new SparseCheckoutPath("titi"))); project.setAssignedLabel(rule.createSlave().getSelfLabel()); // run build first to create workspace final String commitFile1 = "toto/commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final String commitFile2 = "titi/commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); final FreeStyleBuild build1 = build(project, Result.SUCCESS); assertTrue(build1.getWorkspace().child("titi").exists()); assertTrue(build1.getWorkspace().child(commitFile2).exists()); assertFalse(build1.getWorkspace().child("toto").exists()); assertFalse(build1.getWorkspace().child(commitFile1).exists()); } /** * Test for JENKINS-22009. * * @throws Exception */ @Test @Issue("JENKINS-22009") public void testPolling_environmentValueInBranchSpec() throws Exception { // create parameterized project with environment value in branch specification FreeStyleProject project = createFreeStyleProject(); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("${MY_BRANCH}")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); project.setScm(scm); project.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("MY_BRANCH", "master"))); // commit something in order to create an initial base version in git commit("toto/commitFile1", johnDoe, "Commit number 1"); // build the project build(project, Result.SUCCESS); assertFalse("No changes to git since last build, thus no new build is expected", project.poll(listener).hasChanges()); } @Issue("JENKINS-29066") public void baseTestPolling_parentHead(List<GitSCMExtension> extensions) throws Exception { // create parameterized project with environment value in branch specification FreeStyleProject project = createFreeStyleProject(); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("**")), false, Collections.<SubmoduleConfig>emptyList(), null, null, extensions); project.setScm(scm); // commit something in order to create an initial base version in git commit("toto/commitFile1", johnDoe, "Commit number 1"); git.branch("someBranch"); commit("toto/commitFile2", johnDoe, "Commit number 2"); assertTrue("polling should detect changes",project.poll(listener).hasChanges()); // build the project build(project, Result.SUCCESS); /* Expects 1 build because the build of someBranch incorporates all * the changes from the master branch as well as the changes from someBranch. */ assertEquals("Wrong number of builds", 1, project.getBuilds().size()); assertFalse("polling should not detect changes",project.poll(listener).hasChanges()); } @Issue("JENKINS-29066") @Test public void testPolling_parentHead() throws Exception { baseTestPolling_parentHead(Collections.<GitSCMExtension>emptyList()); } @Issue("JENKINS-29066") @Test public void testPolling_parentHead_DisableRemotePoll() throws Exception { baseTestPolling_parentHead(Collections.<GitSCMExtension>singletonList(new DisableRemotePoll())); } @Test public void testPollingAfterManualBuildWithParametrizedBranchSpec() throws Exception { // create parameterized project with environment value in branch specification FreeStyleProject project = createFreeStyleProject(); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("${MY_BRANCH}")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); project.setScm(scm); project.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("MY_BRANCH", "trackedbranch"))); // Initial commit to master commit("file1", johnDoe, "Initial Commit"); // Create the branches git.branch("trackedbranch"); git.branch("manualbranch"); final StringParameterValue branchParam = new StringParameterValue("MY_BRANCH", "manualbranch"); final Action[] actions = {new ParametersAction(branchParam)}; FreeStyleBuild build = project.scheduleBuild2(0, new Cause.UserCause(), actions).get(); rule.assertBuildStatus(Result.SUCCESS, build); assertFalse("No changes to git since last build", project.poll(listener).hasChanges()); git.checkout("manualbranch"); commit("file2", johnDoe, "Commit to manually build branch"); assertFalse("No changes to tracked branch", project.poll(listener).hasChanges()); git.checkout("trackedbranch"); commit("file3", johnDoe, "Commit to tracked branch"); assertTrue("A change should be detected in tracked branch", project.poll(listener).hasChanges()); } private final class FakeParametersAction implements EnvironmentContributingAction, Serializable { // Test class for testPolling_environmentValueAsEnvironmentContributingAction test case final ParametersAction m_forwardingAction; public FakeParametersAction(StringParameterValue params) { this.m_forwardingAction = new ParametersAction(params); } public void buildEnvVars(AbstractBuild<?, ?> ab, EnvVars ev) { this.m_forwardingAction.buildEnvVars(ab, ev); } public String getIconFileName() { return this.m_forwardingAction.getIconFileName(); } public String getDisplayName() { return this.m_forwardingAction.getDisplayName(); } public String getUrlName() { return this.m_forwardingAction.getUrlName(); } public List<ParameterValue> getParameters() { return this.m_forwardingAction.getParameters(); } private void writeObject(java.io.ObjectOutputStream out) throws IOException { } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { } private void readObjectNoData() throws ObjectStreamException { } } @Test public void testPolling_CanDoRemotePollingIfOneBranchButMultipleRepositories() throws Exception { FreeStyleProject project = createFreeStyleProject(); List<UserRemoteConfig> remoteConfigs = new ArrayList<>(); remoteConfigs.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", "", null)); remoteConfigs.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "someOtherRepo", "", null)); GitSCM scm = new GitSCM(remoteConfigs, Collections.singletonList(new BranchSpec("origin/master")), false, Collections.<SubmoduleConfig> emptyList(), null, null, Collections.<GitSCMExtension> emptyList()); project.setScm(scm); commit("commitFile1", johnDoe, "Commit number 1"); FreeStyleBuild first_build = project.scheduleBuild2(0, new Cause.UserCause()).get(); rule.assertBuildStatus(Result.SUCCESS, first_build); first_build.getWorkspace().deleteContents(); PollingResult pollingResult = scm.poll(project, null, first_build.getWorkspace(), listener, null); assertFalse(pollingResult.hasChanges()); } /** * Test for JENKINS-24467. * * @throws Exception */ @Test public void testPolling_environmentValueAsEnvironmentContributingAction() throws Exception { // create parameterized project with environment value in branch specification FreeStyleProject project = createFreeStyleProject(); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("${MY_BRANCH}")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); project.setScm(scm); // Inital commit and build commit("toto/commitFile1", johnDoe, "Commit number 1"); String brokenPath = "\\broken/path\\of/doom"; if (!sampleRepo.gitVersionAtLeast(1, 8)) { /* Git 1.7.10.4 fails the first build unless the git-upload-pack * program is available in its PATH. * Later versions of git don't have that problem. */ final String systemPath = System.getenv("PATH"); brokenPath = systemPath + File.pathSeparator + brokenPath; } final StringParameterValue real_param = new StringParameterValue("MY_BRANCH", "master"); final StringParameterValue fake_param = new StringParameterValue("PATH", brokenPath); final Action[] actions = {new ParametersAction(real_param), new FakeParametersAction(fake_param)}; // SECURITY-170 - have to use ParametersDefinitionProperty project.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("MY_BRANCH", "master"))); FreeStyleBuild first_build = project.scheduleBuild2(0, new Cause.UserCause(), actions).get(); rule.assertBuildStatus(Result.SUCCESS, first_build); Launcher launcher = workspace.createLauncher(listener); final EnvVars environment = GitUtils.getPollEnvironment(project, workspace, launcher, listener); assertEquals(environment.get("MY_BRANCH"), "master"); assertNotSame("Enviroment path should not be broken path", environment.get("PATH"), brokenPath); } /** * Tests that builds have the correctly specified Custom SCM names, associated with * each build. * @throws Exception on various exceptions */ @Ignore("Intermittent failures on stable-3.10 branch, not on stable-3.9 or master") @Test public void testCustomSCMName() throws Exception { final String branchName = "master"; final FreeStyleProject project = setupProject(branchName, false); project.addTrigger(new SCMTrigger("")); GitSCM git = (GitSCM) project.getScm(); setupJGit(git); final String commitFile1 = "commitFile1"; final String scmNameString1 = ""; commit(commitFile1, johnDoe, "Commit number 1"); assertTrue("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); build(project, Result.SUCCESS, commitFile1); final ObjectId commit1 = testRepo.git.revListAll().get(0); // Check unset build SCM Name carries final int buildNumber1 = notifyAndCheckScmName( project, commit1, scmNameString1, 1, git); final String scmNameString2 = "ScmName2"; git.getExtensions().replace(new ScmName(scmNameString2)); commit("commitFile2", johnDoe, "Commit number 2"); assertTrue("scm polling should detect commit 2", project.poll(listener).hasChanges()); final ObjectId commit2 = testRepo.git.revListAll().get(0); // Check second set SCM Name final int buildNumber2 = notifyAndCheckScmName( project, commit2, scmNameString2, 2, git); checkNumberedBuildScmName(project, buildNumber1, scmNameString1, git); final String scmNameString3 = "ScmName3"; git.getExtensions().replace(new ScmName(scmNameString3)); commit("commitFile3", johnDoe, "Commit number 3"); assertTrue("scm polling should detect commit 3", project.poll(listener).hasChanges()); final ObjectId commit3 = testRepo.git.revListAll().get(0); // Check third set SCM Name final int buildNumber3 = notifyAndCheckScmName( project, commit3, scmNameString3, 3, git); checkNumberedBuildScmName(project, buildNumber1, scmNameString1, git); checkNumberedBuildScmName(project, buildNumber2, scmNameString2, git); commit("commitFile4", johnDoe, "Commit number 4"); assertTrue("scm polling should detect commit 4", project.poll(listener).hasChanges()); final ObjectId commit4 = testRepo.git.revListAll().get(0); // Check third set SCM Name still set final int buildNumber4 = notifyAndCheckScmName( project, commit4, scmNameString3, 4, git); checkNumberedBuildScmName(project, buildNumber1, scmNameString1, git); checkNumberedBuildScmName(project, buildNumber2, scmNameString2, git); checkNumberedBuildScmName(project, buildNumber3, scmNameString3, git); } /** * Method performs HTTP get on "notifyCommit" URL, passing it commit by SHA1 * and tests for custom SCM name build data consistency. * @param project project to build * @param commit commit to build * @param expectedScmName Expected SCM name for commit. * @param ordinal number of commit to log into errors, if any * @param git git SCM * @throws Exception on various exceptions occur */ private int notifyAndCheckScmName(FreeStyleProject project, ObjectId commit, String expectedScmName, int ordinal, GitSCM git) throws Exception { assertTrue("scm polling should detect commit " + ordinal, notifyCommit(project, commit)); final Build build = project.getLastBuild(); final BuildData buildData = git.getBuildData(build); assertEquals("Expected SHA1 != built SHA1 for commit " + ordinal, commit, buildData .getLastBuiltRevision().getSha1()); assertEquals("Expected SHA1 != retrieved SHA1 for commit " + ordinal, commit, buildData.getLastBuild(commit).getSHA1()); assertTrue("Commit " + ordinal + " not marked as built", buildData.hasBeenBuilt(commit)); assertEquals("Wrong SCM Name for commit " + ordinal, expectedScmName, buildData.getScmName()); return build.getNumber(); } private void checkNumberedBuildScmName(FreeStyleProject project, int buildNumber, String expectedScmName, GitSCM git) throws Exception { final BuildData buildData = git.getBuildData(project.getBuildByNumber(buildNumber)); assertEquals("Wrong SCM Name", expectedScmName, buildData.getScmName()); } /** * Tests that builds have the correctly specified branches, associated with * the commit id, passed with "notifyCommit" URL. * @throws Exception on various exceptions */ @Ignore("Intermittent failures on stable-3.10 branch, not on stable-3.9 or master") @Issue("JENKINS-24133") @Test public void testSha1NotificationBranches() throws Exception { final String branchName = "master"; final FreeStyleProject project = setupProject(branchName, false); project.addTrigger(new SCMTrigger("")); final GitSCM git = (GitSCM) project.getScm(); setupJGit(git); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); assertTrue("scm polling should detect commit 1", project.poll(listener).hasChanges()); build(project, Result.SUCCESS, commitFile1); final ObjectId commit1 = testRepo.git.revListAll().get(0); notifyAndCheckBranch(project, commit1, branchName, 1, git); commit("commitFile2", johnDoe, "Commit number 2"); assertTrue("scm polling should detect commit 2", project.poll(listener).hasChanges()); final ObjectId commit2 = testRepo.git.revListAll().get(0); notifyAndCheckBranch(project, commit2, branchName, 2, git); notifyAndCheckBranch(project, commit1, branchName, 1, git); } /* A null pointer exception was detected because the plugin failed to * write a branch name to the build data, so there was a SHA1 recorded * in the build data, but no branch name. */ @Test public void testNoNullPointerExceptionWithNullBranch() throws Exception { ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d"); /* This is the null that causes NPE */ Branch branch = new Branch(null, sha1); List<Branch> branchList = new ArrayList<>(); branchList.add(branch); Revision revision = new Revision(sha1, branchList); /* BuildData mock that will use the Revision with null branch name */ BuildData buildData = Mockito.mock(BuildData.class); Mockito.when(buildData.getLastBuiltRevision()).thenReturn(revision); Mockito.when(buildData.hasBeenReferenced(anyString())).thenReturn(true); /* List of build data that will be returned by the mocked BuildData */ List<BuildData> buildDataList = new ArrayList<>(); buildDataList.add(buildData); /* AbstractBuild mock which returns the buildDataList that contains a null branch name */ AbstractBuild build = Mockito.mock(AbstractBuild.class); Mockito.when(build.getActions(BuildData.class)).thenReturn(buildDataList); final FreeStyleProject project = setupProject("*/*", false); GitSCM scm = (GitSCM) project.getScm(); scm.buildEnvVars(build, new EnvVars()); // NPE here before fix applied /* Verify mocks were called as expected */ verify(buildData, times(1)).getLastBuiltRevision(); verify(buildData, times(1)).hasBeenReferenced(anyString()); verify(build, times(1)).getActions(BuildData.class); } @Test public void testBuildEnvVarsLocalBranchStarStar() throws Exception { ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d"); /* This is the null that causes NPE */ Branch branch = new Branch("origin/master", sha1); List<Branch> branchList = new ArrayList<>(); branchList.add(branch); Revision revision = new Revision(sha1, branchList); /* BuildData mock that will use the Revision with null branch name */ BuildData buildData = Mockito.mock(BuildData.class); Mockito.when(buildData.getLastBuiltRevision()).thenReturn(revision); Mockito.when(buildData.hasBeenReferenced(anyString())).thenReturn(true); /* List of build data that will be returned by the mocked BuildData */ List<BuildData> buildDataList = new ArrayList<>(); buildDataList.add(buildData); /* AbstractBuild mock which returns the buildDataList that contains a null branch name */ AbstractBuild build = Mockito.mock(AbstractBuild.class); Mockito.when(build.getActions(BuildData.class)).thenReturn(buildDataList); final FreeStyleProject project = setupProject("*/*", false); GitSCM scm = (GitSCM) project.getScm(); scm.getExtensions().add(new LocalBranch("**")); EnvVars env = new EnvVars(); scm.buildEnvVars(build, env); // NPE here before fix applied assertEquals("GIT_BRANCH", "origin/master", env.get("GIT_BRANCH")); assertEquals("GIT_LOCAL_BRANCH", "master", env.get("GIT_LOCAL_BRANCH")); /* Verify mocks were called as expected */ verify(buildData, times(1)).getLastBuiltRevision(); verify(buildData, times(1)).hasBeenReferenced(anyString()); verify(build, times(1)).getActions(BuildData.class); } @Test public void testBuildEnvVarsLocalBranchNull() throws Exception { ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d"); /* This is the null that causes NPE */ Branch branch = new Branch("origin/master", sha1); List<Branch> branchList = new ArrayList<>(); branchList.add(branch); Revision revision = new Revision(sha1, branchList); /* BuildData mock that will use the Revision with null branch name */ BuildData buildData = Mockito.mock(BuildData.class); Mockito.when(buildData.getLastBuiltRevision()).thenReturn(revision); Mockito.when(buildData.hasBeenReferenced(anyString())).thenReturn(true); /* List of build data that will be returned by the mocked BuildData */ List<BuildData> buildDataList = new ArrayList<>(); buildDataList.add(buildData); /* AbstractBuild mock which returns the buildDataList that contains a null branch name */ AbstractBuild build = Mockito.mock(AbstractBuild.class); Mockito.when(build.getActions(BuildData.class)).thenReturn(buildDataList); final FreeStyleProject project = setupProject("*/*", false); GitSCM scm = (GitSCM) project.getScm(); scm.getExtensions().add(new LocalBranch("")); EnvVars env = new EnvVars(); scm.buildEnvVars(build, env); // NPE here before fix applied assertEquals("GIT_BRANCH", "origin/master", env.get("GIT_BRANCH")); assertEquals("GIT_LOCAL_BRANCH", "master", env.get("GIT_LOCAL_BRANCH")); /* Verify mocks were called as expected */ verify(buildData, times(1)).getLastBuiltRevision(); verify(buildData, times(1)).hasBeenReferenced(anyString()); verify(build, times(1)).getActions(BuildData.class); } @Test public void testBuildEnvVarsLocalBranchNotSet() throws Exception { ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d"); /* This is the null that causes NPE */ Branch branch = new Branch("origin/master", sha1); List<Branch> branchList = new ArrayList<>(); branchList.add(branch); Revision revision = new Revision(sha1, branchList); /* BuildData mock that will use the Revision with null branch name */ BuildData buildData = Mockito.mock(BuildData.class); Mockito.when(buildData.getLastBuiltRevision()).thenReturn(revision); Mockito.when(buildData.hasBeenReferenced(anyString())).thenReturn(true); /* List of build data that will be returned by the mocked BuildData */ List<BuildData> buildDataList = new ArrayList<>(); buildDataList.add(buildData); /* AbstractBuild mock which returns the buildDataList that contains a null branch name */ AbstractBuild build = Mockito.mock(AbstractBuild.class); Mockito.when(build.getActions(BuildData.class)).thenReturn(buildDataList); final FreeStyleProject project = setupProject("*/*", false); GitSCM scm = (GitSCM) project.getScm(); EnvVars env = new EnvVars(); scm.buildEnvVars(build, env); // NPE here before fix applied assertEquals("GIT_BRANCH", "origin/master", env.get("GIT_BRANCH")); assertEquals("GIT_LOCAL_BRANCH", null, env.get("GIT_LOCAL_BRANCH")); /* Verify mocks were called as expected */ verify(buildData, times(1)).getLastBuiltRevision(); verify(buildData, times(1)).hasBeenReferenced(anyString()); verify(build, times(1)).getActions(BuildData.class); } @Issue("JENKINS-38241") @Test public void testCommitMessageIsPrintedToLogs() throws Exception { sampleRepo.init(); sampleRepo.write("file", "v1"); sampleRepo.git("commit", "--all", "--message=test commit"); FreeStyleProject p = setupSimpleProject("master"); Run<?,?> run = rule.buildAndAssertSuccess(p); TaskListener mockListener = Mockito.mock(TaskListener.class); Mockito.when(mockListener.getLogger()).thenReturn(Mockito.spy(StreamTaskListener.fromStdout().getLogger())); p.getScm().checkout(run, new Launcher.LocalLauncher(listener), new FilePath(run.getRootDir()).child("tmp-" + "master"), mockListener, null, SCMRevisionState.NONE); ArgumentCaptor<String> logCaptor = ArgumentCaptor.forClass(String.class); verify(mockListener.getLogger(), atLeastOnce()).println(logCaptor.capture()); List<String> values = logCaptor.getAllValues(); assertThat(values, hasItem("Commit message: \"test commit\"")); } /** * Method performs HTTP get on "notifyCommit" URL, passing it commit by SHA1 * and tests for build data consistency. * @param project project to build * @param commit commit to build * @param expectedBranch branch, that is expected to be built * @param ordinal number of commit to log into errors, if any * @param git git SCM * @throws Exception on various exceptions occur */ private void notifyAndCheckBranch(FreeStyleProject project, ObjectId commit, String expectedBranch, int ordinal, GitSCM git) throws Exception { assertTrue("scm polling should detect commit " + ordinal, notifyCommit(project, commit)); final BuildData buildData = git.getBuildData(project.getLastBuild()); final Collection<Branch> builtBranches = buildData.lastBuild.getRevision().getBranches(); assertEquals("Commit " + ordinal + " should be built", commit, buildData .getLastBuiltRevision().getSha1()); final String expectedBranchString = "origin/" + expectedBranch; assertFalse("Branches should be detected for the build", builtBranches.isEmpty()); assertEquals(expectedBranch + " branch should be detected", expectedBranchString, builtBranches.iterator().next().getName()); assertEquals(expectedBranchString, getEnvVars(project).get(GitSCM.GIT_BRANCH)); } /** * Method performs commit notification for the last committed SHA1 using * notifyCommit URL. * @param project project to trigger * @return whether the new build has been triggered (<code>true</code>) or * not (<code>false</code>). * @throws Exception on various exceptions */ private boolean notifyCommit(FreeStyleProject project, ObjectId commitId) throws Exception { final int initialBuildNumber = project.getLastBuild().getNumber(); final String commit1 = ObjectId.toString(commitId); final String notificationPath = rule.getURL().toExternalForm() + "git/notifyCommit?url=" + testRepo.gitDir.toString() + "&sha1=" + commit1; final URL notifyUrl = new URL(notificationPath); String notifyContent = null; try (final InputStream is = notifyUrl.openStream()) { notifyContent = IOUtils.toString(is); } assertThat(notifyContent, containsString("No Git consumers using SCM API plugin for: " + testRepo.gitDir.toString())); if ((project.getLastBuild().getNumber() == initialBuildNumber) && (rule.jenkins.getQueue().isEmpty())) { return false; } else { while (!rule.jenkins.getQueue().isEmpty()) { Thread.sleep(100); } final FreeStyleBuild build = project.getLastBuild(); while (build.isBuilding()) { Thread.sleep(100); } return true; } } private void setupJGit(GitSCM git) { git.gitTool="jgit"; rule.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(new JGitTool(Collections.<ToolProperty<?>>emptyList())); } /** We clean the environment, just in case the test is being run from a Jenkins job using this same plugin :). */ @TestExtension public static class CleanEnvironment extends EnvironmentContributor { @Override public void buildEnvironmentFor(Run run, EnvVars envs, TaskListener listener) { envs.remove(GitSCM.GIT_BRANCH); envs.remove(GitSCM.GIT_LOCAL_BRANCH); envs.remove(GitSCM.GIT_COMMIT); envs.remove(GitSCM.GIT_PREVIOUS_COMMIT); envs.remove(GitSCM.GIT_PREVIOUS_SUCCESSFUL_COMMIT); } } }
src/test/java/hudson/plugins/git/GitSCMTest.java
package hudson.plugins.git; import com.cloudbees.plugins.credentials.Credentials; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.CredentialsScope; import com.cloudbees.plugins.credentials.CredentialsStore; import com.cloudbees.plugins.credentials.SystemCredentialsProvider; import com.cloudbees.plugins.credentials.common.StandardCredentials; import com.cloudbees.plugins.credentials.domains.Domain; import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl; import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.google.common.base.Function; import com.google.common.collect.Collections2; import com.google.common.collect.Lists; import hudson.EnvVars; import hudson.FilePath; import hudson.Launcher; import hudson.matrix.Axis; import hudson.matrix.AxisList; import hudson.matrix.MatrixBuild; import hudson.matrix.MatrixProject; import hudson.model.*; import hudson.plugins.git.GitSCM.BuildChooserContextImpl; import hudson.plugins.git.GitSCM.DescriptorImpl; import hudson.plugins.git.browser.GitRepositoryBrowser; import hudson.plugins.git.browser.GithubWeb; import hudson.plugins.git.extensions.GitSCMExtension; import hudson.plugins.git.extensions.impl.*; import hudson.plugins.git.util.BuildChooser; import hudson.plugins.git.util.BuildChooserContext; import hudson.plugins.git.util.BuildChooserContext.ContextCallable; import hudson.plugins.git.util.BuildData; import hudson.plugins.git.util.DefaultBuildChooser; import hudson.plugins.git.util.GitUtils; import hudson.plugins.parameterizedtrigger.BuildTrigger; import hudson.plugins.parameterizedtrigger.ResultCondition; import hudson.remoting.Channel; import hudson.remoting.VirtualChannel; import hudson.scm.ChangeLogSet; import hudson.scm.PollingResult; import hudson.scm.PollingResult.Change; import hudson.scm.SCMRevisionState; import hudson.slaves.DumbSlave; import hudson.slaves.EnvironmentVariablesNodeProperty.Entry; import hudson.tools.ToolProperty; import hudson.triggers.SCMTrigger; import hudson.util.StreamTaskListener; import jenkins.security.MasterToSlaveCallable; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import org.jenkinsci.plugins.gitclient.*; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.TestExtension; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.ObjectStreamException; import java.io.Serializable; import java.net.URL; import java.text.MessageFormat; import java.util.*; import org.eclipse.jgit.transport.RemoteConfig; import static org.hamcrest.Matchers.*; import static org.hamcrest.CoreMatchers.instanceOf; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import static org.junit.Assert.*; import org.junit.Before; import org.junit.BeforeClass; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import static org.mockito.Matchers.*; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import jenkins.model.Jenkins; import jenkins.plugins.git.CliGitCommand; import jenkins.plugins.git.GitSampleRepoRule; /** * Tests for {@link GitSCM}. * @author ishaaq */ public class GitSCMTest extends AbstractGitTestCase { @Rule public GitSampleRepoRule secondRepo = new GitSampleRepoRule(); private CredentialsStore store = null; @BeforeClass public static void setGitDefaults() throws Exception { CliGitCommand gitCmd = new CliGitCommand(null); gitCmd.setDefaults(); } @Before public void enableSystemCredentialsProvider() throws Exception { SystemCredentialsProvider.getInstance().setDomainCredentialsMap( Collections.singletonMap(Domain.global(), Collections.<Credentials>emptyList())); for (CredentialsStore s : CredentialsProvider.lookupStores(Jenkins.getInstance())) { if (s.getProvider() instanceof SystemCredentialsProvider.ProviderImpl) { store = s; break; } } assertThat("The system credentials provider is enabled", store, notNullValue()); } private StandardCredentials getInvalidCredential() { String username = "bad-user"; String password = "bad-password"; CredentialsScope scope = CredentialsScope.GLOBAL; String id = "username-" + username + "-password-" + password; return new UsernamePasswordCredentialsImpl(scope, id, "desc: " + id, username, password); } @Test public void trackCredentials() throws Exception { StandardCredentials credential = getInvalidCredential(); store.addCredentials(Domain.global(), credential); Fingerprint fingerprint = CredentialsProvider.getFingerprintOf(credential); assertThat("Fingerprint should not be set before job definition", fingerprint, nullValue()); JenkinsRule.WebClient wc = rule.createWebClient(); HtmlPage page = wc.goTo("credentials/store/system/domain/_/credentials/" + credential.getId()); assertThat("Have usage tracking reported", page.getElementById("usage"), notNullValue()); assertThat("No fingerprint created until first use", page.getElementById("usage-missing"), notNullValue()); assertThat("No fingerprint created until first use", page.getElementById("usage-present"), nullValue()); FreeStyleProject project = setupProject("master", credential); fingerprint = CredentialsProvider.getFingerprintOf(credential); assertThat("Fingerprint should not be set before first build", fingerprint, nullValue()); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); fingerprint = CredentialsProvider.getFingerprintOf(credential); assertThat("Fingerprint should be set after first build", fingerprint, notNullValue()); assertThat(fingerprint.getJobs(), hasItem(is(project.getFullName()))); Fingerprint.RangeSet rangeSet = fingerprint.getRangeSet(project); assertThat(rangeSet, notNullValue()); assertThat(rangeSet.includes(project.getLastBuild().getNumber()), is(true)); page = wc.goTo("credentials/store/system/domain/_/credentials/" + credential.getId()); assertThat(page.getElementById("usage-missing"), nullValue()); assertThat(page.getElementById("usage-present"), notNullValue()); assertThat(page.getAnchorByText(project.getFullDisplayName()), notNullValue()); } /** * Basic test - create a GitSCM based project, check it out and build for the first time. * Next test that polling works correctly, make another commit, check that polling finds it, * then build it and finally test the build culprits as well as the contents of the workspace. * @throws Exception if an exception gets thrown. */ @Test public void testBasic() throws Exception { FreeStyleProject project = setupSimpleProject("master"); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have only one culprit", 1, culprits.size()); assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName()); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testBasicRemotePoll() throws Exception { // FreeStyleProject project = setupProject("master", true, false); FreeStyleProject project = setupProject("master", false, null, null, null, true, null); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); // ... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have only one culprit", 1, culprits.size()); assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName()); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testBranchSpecWithRemotesMaster() throws Exception { FreeStyleProject projectMasterBranch = setupProject("remotes/origin/master", false, null, null, null, true, null); // create initial commit and build final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(projectMasterBranch, Result.SUCCESS, commitFile1); } /** * This test and testSpecificRefspecsWithoutCloneOption confirm behaviors of * refspecs on initial clone. Without the CloneOption to honor refspec, all * references are cloned, even if they will be later ignored due to the * refspec. With the CloneOption to ignore refspec, the initial clone also * honors the refspec and only retrieves references per the refspec. * @throws Exception on error */ @Test @Issue("JENKINS-31393") public void testSpecificRefspecs() throws Exception { List<UserRemoteConfig> repos = new ArrayList<>(); repos.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", "+refs/heads/foo:refs/remotes/foo", null)); /* Set CloneOption to honor refspec on initial clone */ FreeStyleProject projectWithMaster = setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null); CloneOption cloneOptionMaster = new CloneOption(false, null, null); cloneOptionMaster.setHonorRefspec(true); ((GitSCM)projectWithMaster.getScm()).getExtensions().add(cloneOptionMaster); /* Set CloneOption to honor refspec on initial clone */ FreeStyleProject projectWithFoo = setupProject(repos, Collections.singletonList(new BranchSpec("foo")), null, false, null); CloneOption cloneOptionFoo = new CloneOption(false, null, null); cloneOptionFoo.setHonorRefspec(true); ((GitSCM)projectWithMaster.getScm()).getExtensions().add(cloneOptionFoo); // create initial commit final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit in master"); // create branch and make initial commit git.branch("foo"); git.checkout().branch("foo"); commit(commitFile1, johnDoe, "Commit in foo"); build(projectWithMaster, Result.FAILURE); build(projectWithFoo, Result.SUCCESS, commitFile1); } /** * This test and testSpecificRefspecs confirm behaviors of * refspecs on initial clone. Without the CloneOption to honor refspec, all * references are cloned, even if they will be later ignored due to the * refspec. With the CloneOption to ignore refspec, the initial clone also * honors the refspec and only retrieves references per the refspec. * @throws Exception on error */ @Test @Issue("JENKINS-36507") public void testSpecificRefspecsWithoutCloneOption() throws Exception { List<UserRemoteConfig> repos = new ArrayList<>(); repos.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", "+refs/heads/foo:refs/remotes/foo", null)); FreeStyleProject projectWithMaster = setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null); FreeStyleProject projectWithFoo = setupProject(repos, Collections.singletonList(new BranchSpec("foo")), null, false, null); // create initial commit final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit in master"); // create branch and make initial commit git.branch("foo"); git.checkout().branch("foo"); commit(commitFile1, johnDoe, "Commit in foo"); build(projectWithMaster, Result.SUCCESS); /* If clone refspec had been honored, this would fail */ build(projectWithFoo, Result.SUCCESS, commitFile1); } @Test public void testBranchSpecWithRemotesHierarchical() throws Exception { FreeStyleProject projectMasterBranch = setupProject("master", false, null, null, null, true, null); FreeStyleProject projectHierarchicalBranch = setupProject("remotes/origin/rel-1/xy", false, null, null, null, true, null); // create initial commit final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); // create hierarchical branch, delete master branch, and build git.branch("rel-1/xy"); git.checkout("rel-1/xy"); git.deleteBranch("master"); build(projectMasterBranch, Result.FAILURE); build(projectHierarchicalBranch, Result.SUCCESS, commitFile1); } @Test public void testBranchSpecUsingTagWithSlash() throws Exception { FreeStyleProject projectMasterBranch = setupProject("path/tag", false, null, null, null, true, null); // create initial commit and build final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1 will be tagged with path/tag"); testRepo.git.tag("path/tag", "tag with a slash in the tag name"); build(projectMasterBranch, Result.SUCCESS, commitFile1); } @Test public void testBasicIncludedRegion() throws Exception { FreeStyleProject project = setupProject("master", false, null, null, null, ".*3"); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); assertFalse("scm polling detected commit2 change, which should not have been included", project.poll(listener).hasChanges()); final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); assertTrue("scm polling did not detect commit3 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2, commitFile3); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have two culprit", 2, culprits.size()); PersonIdent[] expected = {johnDoe, janeDoe}; assertCulprits("jane doe and john doe should be the culprits", culprits, expected); assertTrue(build2.getWorkspace().child(commitFile2).exists()); assertTrue(build2.getWorkspace().child(commitFile3).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testIncludedRegionWithDeeperCommits() throws Exception { FreeStyleProject project = setupProject("master", false, null, null, null, ".*3"); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); assertFalse("scm polling detected commit2 change, which should not have been included", project.poll(listener).hasChanges()); final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); final String commitFile4 = "commitFile4"; commit(commitFile4, janeDoe, "Commit number 4"); assertTrue("scm polling did not detect commit3 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2, commitFile3); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have two culprit", 2, culprits.size()); PersonIdent[] expected = {johnDoe, janeDoe}; assertCulprits("jane doe and john doe should be the culprits", culprits, expected); assertTrue(build2.getWorkspace().child(commitFile2).exists()); assertTrue(build2.getWorkspace().child(commitFile3).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testBasicExcludedRegion() throws Exception { FreeStyleProject project = setupProject("master", false, null, ".*2", null, null); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); assertFalse("scm polling detected commit2 change, which should have been excluded", project.poll(listener).hasChanges()); final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); assertTrue("scm polling did not detect commit3 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2, commitFile3); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have two culprit", 2, culprits.size()); PersonIdent[] expected = {johnDoe, janeDoe}; assertCulprits("jane doe and john doe should be the culprits", culprits, expected); assertTrue(build2.getWorkspace().child(commitFile2).exists()); assertTrue(build2.getWorkspace().child(commitFile3).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testCleanBeforeCheckout() throws Exception { FreeStyleProject p = setupProject("master", false, null, null, "Jane Doe", null); ((GitSCM)p.getScm()).getExtensions().add(new CleanBeforeCheckout()); final String commitFile1 = "commitFile1"; final String commitFile2 = "commitFile2"; commit(commitFile1, johnDoe, janeDoe, "Commit number 1"); commit(commitFile2, johnDoe, janeDoe, "Commit number 2"); final FreeStyleBuild firstBuild = build(p, Result.SUCCESS, commitFile1); final String branch1 = "Branch1"; final String branch2 = "Branch2"; List<BranchSpec> branches = new ArrayList<>(); branches.add(new BranchSpec("master")); branches.add(new BranchSpec(branch1)); branches.add(new BranchSpec(branch2)); git.branch(branch1); git.checkout(branch1); p.poll(listener).hasChanges(); assertTrue(firstBuild.getLog().contains("Cleaning")); assertTrue(firstBuild.getLog().indexOf("Cleaning") > firstBuild.getLog().indexOf("Cloning")); //clean should be after clone assertTrue(firstBuild.getLog().indexOf("Cleaning") < firstBuild.getLog().indexOf("Checking out")); //clean before checkout assertTrue(firstBuild.getWorkspace().child(commitFile1).exists()); git.checkout(branch1); final FreeStyleBuild secondBuild = build(p, Result.SUCCESS, commitFile2); p.poll(listener).hasChanges(); assertTrue(secondBuild.getLog().contains("Cleaning")); assertTrue(secondBuild.getLog().indexOf("Cleaning") < secondBuild.getLog().indexOf("Fetching upstream changes")); assertTrue(secondBuild.getWorkspace().child(commitFile2).exists()); } @Issue("JENKINS-8342") @Test public void testExcludedRegionMultiCommit() throws Exception { // Got 2 projects, each one should only build if changes in its own file FreeStyleProject clientProject = setupProject("master", false, null, ".*serverFile", null, null); FreeStyleProject serverProject = setupProject("master", false, null, ".*clientFile", null, null); String initialCommitFile = "initialFile"; commit(initialCommitFile, johnDoe, "initial commit"); build(clientProject, Result.SUCCESS, initialCommitFile); build(serverProject, Result.SUCCESS, initialCommitFile); assertFalse("scm polling should not detect any more changes after initial build", clientProject.poll(listener).hasChanges()); assertFalse("scm polling should not detect any more changes after initial build", serverProject.poll(listener).hasChanges()); // Got commits on serverFile, so only server project should build. commit("myserverFile", johnDoe, "commit first server file"); assertFalse("scm polling should not detect any changes in client project", clientProject.poll(listener).hasChanges()); assertTrue("scm polling did not detect changes in server project", serverProject.poll(listener).hasChanges()); // Got commits on both client and serverFile, so both projects should build. commit("myNewserverFile", johnDoe, "commit new server file"); commit("myclientFile", johnDoe, "commit first clientfile"); assertTrue("scm polling did not detect changes in client project", clientProject.poll(listener).hasChanges()); assertTrue("scm polling did not detect changes in server project", serverProject.poll(listener).hasChanges()); } /** * With multiple branches specified in the project and having commits from a user * excluded should not build the excluded revisions when another branch changes. */ /* @Issue("JENKINS-8342") @Test public void testMultipleBranchWithExcludedUser() throws Exception { final String branch1 = "Branch1"; final String branch2 = "Branch2"; List<BranchSpec> branches = new ArrayList<BranchSpec>(); branches.add(new BranchSpec("master")); branches.add(new BranchSpec(branch1)); branches.add(new BranchSpec(branch2)); final FreeStyleProject project = setupProject(branches, false, null, null, janeDoe.getName(), null, false, null); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); // create branches here so we can get back to them later... git.branch(branch1); git.branch(branch2); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); assertTrue("scm polling should detect changes in 'master' branch", project.poll(listener).hasChanges()); build(project, Result.SUCCESS, commitFile1, commitFile2); assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges()); // Add excluded commit final String commitFile4 = "commitFile4"; commit(commitFile4, janeDoe, "Commit number 4"); assertFalse("scm polling detected change in 'master', which should have been excluded", project.poll(listener).hasChanges()); // now jump back... git.checkout(branch1); final String branch1File1 = "branch1File1"; commit(branch1File1, janeDoe, "Branch1 commit number 1"); assertFalse("scm polling detected change in 'Branch1', which should have been excluded", project.poll(listener).hasChanges()); // and the other branch... git.checkout(branch2); final String branch2File1 = "branch2File1"; commit(branch2File1, janeDoe, "Branch2 commit number 1"); assertFalse("scm polling detected change in 'Branch2', which should have been excluded", project.poll(listener).hasChanges()); final String branch2File2 = "branch2File2"; commit(branch2File2, johnDoe, "Branch2 commit number 2"); assertTrue("scm polling should detect changes in 'Branch2' branch", project.poll(listener).hasChanges()); //... and build it... build(project, Result.SUCCESS, branch2File1, branch2File2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); // now jump back again... git.checkout(branch1); // Commit excluded after non-excluded commit, should trigger build. final String branch1File2 = "branch1File2"; commit(branch1File2, johnDoe, "Branch1 commit number 2"); final String branch1File3 = "branch1File3"; commit(branch1File3, janeDoe, "Branch1 commit number 3"); assertTrue("scm polling should detect changes in 'Branch1' branch", project.poll(listener).hasChanges()); build(project, Result.SUCCESS, branch1File1, branch1File2, branch1File3); } */ @Test public void testBasicExcludedUser() throws Exception { FreeStyleProject project = setupProject("master", false, null, null, "Jane Doe", null); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); assertFalse("scm polling detected commit2 change, which should have been excluded", project.poll(listener).hasChanges()); final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); assertTrue("scm polling did not detect commit3 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2, commitFile3); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have two culprit", 2, culprits.size()); PersonIdent[] expected = {johnDoe, janeDoe}; assertCulprits("jane doe and john doe should be the culprits", culprits, expected); assertTrue(build2.getWorkspace().child(commitFile2).exists()); assertTrue(build2.getWorkspace().child(commitFile3).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testBasicInSubdir() throws Exception { FreeStyleProject project = setupSimpleProject("master"); ((GitSCM)project.getScm()).getExtensions().add(new RelativeTargetDirectory("subdir")); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, "subdir", Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, "subdir", Result.SUCCESS, commitFile2); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have only one culprit", 1, culprits.size()); assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName()); assertEquals("The workspace should have a 'subdir' subdirectory, but does not.", true, build2.getWorkspace().child("subdir").exists()); assertEquals("The 'subdir' subdirectory should contain commitFile2, but does not.", true, build2.getWorkspace().child("subdir").child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testBasicWithSlave() throws Exception { FreeStyleProject project = setupSimpleProject("master"); project.setAssignedLabel(rule.createSlave().getSelfLabel()); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have only one culprit", 1, culprits.size()); assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName()); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Issue("HUDSON-7547") @Test public void testBasicWithSlaveNoExecutorsOnMaster() throws Exception { FreeStyleProject project = setupSimpleProject("master"); rule.jenkins.setNumExecutors(0); project.setAssignedLabel(rule.createSlave().getSelfLabel()); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have only one culprit", 1, culprits.size()); assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName()); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testAuthorOrCommitterFalse() throws Exception { // Test with authorOrCommitter set to false and make sure we get the committer. FreeStyleProject project = setupSimpleProject("master"); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, janeDoe, "Commit number 1"); final FreeStyleBuild firstBuild = build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, janeDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); final FreeStyleBuild secondBuild = build(project, Result.SUCCESS, commitFile2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final Set<User> secondCulprits = secondBuild.getCulprits(); assertEquals("The build should have only one culprit", 1, secondCulprits.size()); assertEquals("Did not get the committer as the change author with authorOrCommitter==false", janeDoe.getName(), secondCulprits.iterator().next().getFullName()); } @Test public void testAuthorOrCommitterTrue() throws Exception { // Next, test with authorOrCommitter set to true and make sure we get the author. FreeStyleProject project = setupSimpleProject("master"); ((GitSCM)project.getScm()).getExtensions().add(new AuthorInChangelog()); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, janeDoe, "Commit number 1"); final FreeStyleBuild firstBuild = build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, janeDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); final FreeStyleBuild secondBuild = build(project, Result.SUCCESS, commitFile2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final Set<User> secondCulprits = secondBuild.getCulprits(); assertEquals("The build should have only one culprit", 1, secondCulprits.size()); assertEquals("Did not get the author as the change author with authorOrCommitter==true", johnDoe.getName(), secondCulprits.iterator().next().getFullName()); } /** * Method name is self-explanatory. */ @Test public void testNewCommitToUntrackedBranchDoesNotTriggerBuild() throws Exception { FreeStyleProject project = setupSimpleProject("master"); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); //now create and checkout a new branch: git.checkout(Constants.HEAD, "untracked"); //.. and commit to it: final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); assertFalse("scm polling should not detect commit2 change because it is not in the branch we are tracking.", project.poll(listener).hasChanges()); } private String checkoutString(FreeStyleProject project, String envVar) { return "checkout -f " + getEnvVars(project).get(envVar); } @Test public void testEnvVarsAvailable() throws Exception { FreeStyleProject project = setupSimpleProject("master"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertEquals("origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH)); rule.assertLogContains(getEnvVars(project).get(GitSCM.GIT_BRANCH), build1); rule.assertLogContains(checkoutString(project, GitSCM.GIT_COMMIT), build1); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); rule.assertLogNotContains(checkoutString(project, GitSCM.GIT_PREVIOUS_COMMIT), build2); rule.assertLogContains(checkoutString(project, GitSCM.GIT_PREVIOUS_COMMIT), build1); rule.assertLogNotContains(checkoutString(project, GitSCM.GIT_PREVIOUS_SUCCESSFUL_COMMIT), build2); rule.assertLogContains(checkoutString(project, GitSCM.GIT_PREVIOUS_SUCCESSFUL_COMMIT), build1); } @Issue("HUDSON-7411") @Test public void testNodeEnvVarsAvailable() throws Exception { FreeStyleProject project = setupSimpleProject("master"); Node s = rule.createSlave(); setVariables(s, new Entry("TESTKEY", "slaveValue")); project.setAssignedLabel(s.getSelfLabel()); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertEquals("slaveValue", getEnvVars(project).get("TESTKEY")); } /** * A previous version of GitSCM would only build against branches, not tags. This test checks that that * regression has been fixed. */ @Test public void testGitSCMCanBuildAgainstTags() throws Exception { final String mytag = "mytag"; FreeStyleProject project = setupSimpleProject(mytag); build(project, Result.FAILURE); // fail, because there's nothing to be checked out here final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); // Try again. The first build will leave the repository in a bad state because we // cloned something without even a HEAD - which will mean it will want to re-clone once there is some // actual data. build(project, Result.FAILURE); // fail, because there's nothing to be checked out here //now create and checkout a new branch: final String tmpBranch = "tmp"; git.branch(tmpBranch); git.checkout(tmpBranch); // commit to it final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); assertFalse("scm polling should not detect any more changes since mytag is untouched right now", project.poll(listener).hasChanges()); build(project, Result.FAILURE); // fail, because there's nothing to be checked out here // tag it, then delete the tmp branch git.tag(mytag, "mytag initial"); git.checkout("master"); git.deleteBranch(tmpBranch); // at this point we're back on master, there are no other branches, tag "mytag" exists but is // not part of "master" assertTrue("scm polling should detect commit2 change in 'mytag'", project.poll(listener).hasChanges()); build(project, Result.SUCCESS, commitFile2); assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges()); // now, create tmp branch again against mytag: git.checkout(mytag); git.branch(tmpBranch); // another commit: final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); assertFalse("scm polling should not detect any more changes since mytag is untouched right now", project.poll(listener).hasChanges()); // now we're going to force mytag to point to the new commit, if everything goes well, gitSCM should pick the change up: git.tag(mytag, "mytag moved"); git.checkout("master"); git.deleteBranch(tmpBranch); if (sampleRepo.gitVersionAtLeast(2, 20, 0)) { /* Newer CLI git versions fail this test unless they have newer git client */ /* Don't want to force users onto a newer git client, so we skip the final build and assertions on git 2.20 and newer */ return; } // at this point we're back on master, there are no other branches, "mytag" has been updated to a new commit: assertTrue("scm polling should detect commit3 change in 'mytag'", project.poll(listener).hasChanges()); build(project, Result.SUCCESS, commitFile3); assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges()); } /** * Not specifying a branch string in the project implies that we should be polling for changes in * all branches. */ @Test public void testMultipleBranchBuild() throws Exception { // empty string will result in a project that tracks against changes in all branches: final FreeStyleProject project = setupSimpleProject(""); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); // create a branch here so we can get back to this point later... final String fork = "fork"; git.branch(fork); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); assertTrue("scm polling should detect changes in 'master' branch", project.poll(listener).hasChanges()); build(project, Result.SUCCESS, commitFile1, commitFile2); assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges()); // now jump back... git.checkout(fork); // add some commits to the fork branch... final String forkFile1 = "forkFile1"; commit(forkFile1, johnDoe, "Fork commit number 1"); final String forkFile2 = "forkFile2"; commit(forkFile2, johnDoe, "Fork commit number 2"); assertTrue("scm polling should detect changes in 'fork' branch", project.poll(listener).hasChanges()); build(project, Result.SUCCESS, forkFile1, forkFile2); assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges()); } @Test public void testMultipleBranchesWithTags() throws Exception { List<BranchSpec> branchSpecs = Arrays.asList( new BranchSpec("refs/tags/v*"), new BranchSpec("refs/remotes/origin/non-existent")); FreeStyleProject project = setupProject(branchSpecs, false, null, null, janeDoe.getName(), null, false, null); // create initial commit and then run the build against it: // Here the changelog is by default empty (because changelog for first commit is always empty commit("commitFileBase", johnDoe, "Initial Commit"); // there are no branches to be build FreeStyleBuild freeStyleBuild = build(project, Result.FAILURE); final String v1 = "v1"; git.tag(v1, "version 1"); assertTrue("v1 tag exists", git.tagExists(v1)); freeStyleBuild = build(project, Result.SUCCESS); assertTrue("change set is empty", freeStyleBuild.getChangeSet().isEmptySet()); commit("file1", johnDoe, "change to file1"); git.tag("none", "latest"); freeStyleBuild = build(project, Result.SUCCESS); ObjectId tag = git.revParse(Constants.R_TAGS + v1); GitSCM scm = (GitSCM)project.getScm(); BuildData buildData = scm.getBuildData(freeStyleBuild); assertEquals("last build matches the v1 tag revision", tag, buildData.lastBuild.getSHA1()); } @Issue("JENKINS-19037") @SuppressWarnings("ResultOfObjectAllocationIgnored") @Test public void testBlankRepositoryName() throws Exception { new GitSCM(null); } @Issue("JENKINS-10060") @Test public void testSubmoduleFixup() throws Exception { File repo = secondRepo.getRoot(); FilePath moduleWs = new FilePath(repo); org.jenkinsci.plugins.gitclient.GitClient moduleRepo = Git.with(listener, new EnvVars()).in(repo).getClient(); {// first we create a Git repository with submodule moduleRepo.init(); moduleWs.child("a").touch(0); moduleRepo.add("a"); moduleRepo.commit("creating a module"); git.addSubmodule(repo.getAbsolutePath(), "module1"); git.commit("creating a super project"); } // configure two uproject 'u' -> 'd' that's chained together. FreeStyleProject u = createFreeStyleProject(); FreeStyleProject d = createFreeStyleProject(); u.setScm(new GitSCM(workDir.getPath())); u.getPublishersList().add(new BuildTrigger(new hudson.plugins.parameterizedtrigger.BuildTriggerConfig(d.getName(), ResultCondition.SUCCESS, new GitRevisionBuildParameters()))); d.setScm(new GitSCM(workDir.getPath())); rule.jenkins.rebuildDependencyGraph(); FreeStyleBuild ub = rule.assertBuildStatusSuccess(u.scheduleBuild2(0)); System.out.println(ub.getLog()); for (int i=0; (d.getLastBuild()==null || d.getLastBuild().isBuilding()) && i<100; i++) // wait only up to 10 sec to avoid infinite loop Thread.sleep(100); FreeStyleBuild db = d.getLastBuild(); assertNotNull("downstream build didn't happen",db); rule.assertBuildStatusSuccess(db); } @Test public void testBuildChooserContext() throws Exception { final FreeStyleProject p = createFreeStyleProject(); final FreeStyleBuild b = rule.assertBuildStatusSuccess(p.scheduleBuild2(0)); BuildChooserContextImpl c = new BuildChooserContextImpl(p, b, null); c.actOnBuild(new ContextCallable<Run<?,?>, Object>() { public Object invoke(Run param, VirtualChannel channel) throws IOException, InterruptedException { assertSame(param,b); return null; } }); c.actOnProject(new ContextCallable<Job<?,?>, Object>() { public Object invoke(Job param, VirtualChannel channel) throws IOException, InterruptedException { assertSame(param,p); return null; } }); DumbSlave s = rule.createOnlineSlave(); assertEquals(p.toString(), s.getChannel().call(new BuildChooserContextTestCallable(c))); } private static class BuildChooserContextTestCallable extends MasterToSlaveCallable<String,IOException> { private final BuildChooserContext c; public BuildChooserContextTestCallable(BuildChooserContext c) { this.c = c; } public String call() throws IOException { try { return c.actOnProject(new ContextCallable<Job<?,?>, String>() { public String invoke(Job<?,?> param, VirtualChannel channel) throws IOException, InterruptedException { assertTrue(channel instanceof Channel); assertTrue(Hudson.getInstance()!=null); return param.toString(); } }); } catch (InterruptedException e) { throw new IOException(e); } } } // eg: "jane doe and john doe should be the culprits", culprits, [johnDoe, janeDoe]) static public void assertCulprits(String assertMsg, Set<User> actual, PersonIdent[] expected) { Collection<String> fullNames = Collections2.transform(actual, new Function<User,String>() { public String apply(User u) { return u.getFullName(); } }); for(PersonIdent p : expected) { assertTrue(assertMsg, fullNames.contains(p.getName())); } } @Test public void testEmailCommitter() throws Exception { FreeStyleProject project = setupSimpleProject("master"); // setup global config GitSCM scm = (GitSCM) project.getScm(); final DescriptorImpl descriptor = (DescriptorImpl) scm.getDescriptor(); assertFalse("Wrong initial value for create account based on e-mail", scm.isCreateAccountBasedOnEmail()); descriptor.setCreateAccountBasedOnEmail(true); assertTrue("Create account based on e-mail not set", scm.isCreateAccountBasedOnEmail()); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final FreeStyleBuild build = build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; final PersonIdent jeffDoe = new PersonIdent("Jeff Doe", "[email protected]"); commit(commitFile2, jeffDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have only one culprit", 1, culprits.size()); User culprit = culprits.iterator().next(); assertEquals("", jeffDoe.getEmailAddress(), culprit.getId()); assertEquals("", jeffDoe.getName(), culprit.getFullName()); rule.assertBuildStatusSuccess(build); } // Disabled - consistently fails, needs more analysis // @Test public void testFetchFromMultipleRepositories() throws Exception { FreeStyleProject project = setupSimpleProject("master"); TestGitRepo secondTestRepo = new TestGitRepo("second", secondRepo.getRoot(), listener); List<UserRemoteConfig> remotes = new ArrayList<>(); remotes.addAll(testRepo.remoteConfigs()); remotes.addAll(secondTestRepo.remoteConfigs()); project.setScm(new GitSCM( remotes, Collections.singletonList(new BranchSpec("master")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList())); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); /* Diagnostic help - for later use */ SCMRevisionState baseline = project.poll(listener).baseline; Change change = project.poll(listener).change; SCMRevisionState remote = project.poll(listener).remote; String assertionMessage = MessageFormat.format("polling incorrectly detected change after build. Baseline: {0}, Change: {1}, Remote: {2}", baseline, change, remote); assertFalse(assertionMessage, project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; secondTestRepo.commit(commitFile2, janeDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } private void branchSpecWithMultipleRepositories(String branchName) throws Exception { FreeStyleProject project = setupSimpleProject("master"); TestGitRepo secondTestRepo = new TestGitRepo("second", secondRepo.getRoot(), listener); List<UserRemoteConfig> remotes = new ArrayList<>(); remotes.addAll(testRepo.remoteConfigs()); remotes.addAll(secondTestRepo.remoteConfigs()); // create initial commit final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); project.setScm(new GitSCM( remotes, Collections.singletonList(new BranchSpec(branchName)), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList())); final FreeStyleBuild build = build(project, Result.SUCCESS, commitFile1); rule.assertBuildStatusSuccess(build); } @Issue("JENKINS-26268") public void testBranchSpecAsSHA1WithMultipleRepositories() throws Exception { branchSpecWithMultipleRepositories(testRepo.git.revParse("HEAD").getName()); } @Issue("JENKINS-26268") public void testBranchSpecAsRemotesOriginMasterWithMultipleRepositories() throws Exception { branchSpecWithMultipleRepositories("remotes/origin/master"); } @Issue("JENKINS-25639") @Test public void testCommitDetectedOnlyOnceInMultipleRepositories() throws Exception { FreeStyleProject project = setupSimpleProject("master"); TestGitRepo secondTestRepo = new TestGitRepo("secondRepo", secondRepo.getRoot(), listener); List<UserRemoteConfig> remotes = new ArrayList<>(); remotes.addAll(testRepo.remoteConfigs()); remotes.addAll(secondTestRepo.remoteConfigs()); GitSCM gitSCM = new GitSCM( remotes, Collections.singletonList(new BranchSpec("origin/master")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); project.setScm(gitSCM); commit("commitFile1", johnDoe, "Commit number 1"); FreeStyleBuild build = build(project, Result.SUCCESS, "commitFile1"); commit("commitFile2", johnDoe, "Commit number 2"); git = Git.with(listener, new EnvVars()).in(build.getWorkspace()).getClient(); for (RemoteConfig remoteConfig : gitSCM.getRepositories()) { git.fetch_().from(remoteConfig.getURIs().get(0), remoteConfig.getFetchRefSpecs()); } BuildChooser buildChooser = gitSCM.getBuildChooser(); Collection<Revision> candidateRevisions = buildChooser.getCandidateRevisions(false, "origin/master", git, listener, project.getLastBuild().getAction(BuildData.class), null); assertEquals(1, candidateRevisions.size()); gitSCM.setBuildChooser(buildChooser); // Should be a no-op Collection<Revision> candidateRevisions2 = buildChooser.getCandidateRevisions(false, "origin/master", git, listener, project.getLastBuild().getAction(BuildData.class), null); assertThat(candidateRevisions2, is(candidateRevisions)); } private final Random random = new Random(); private boolean useChangelogToBranch = random.nextBoolean(); private void addChangelogToBranchExtension(GitSCM scm) { if (useChangelogToBranch) { /* Changelog should be no different with this enabled or disabled */ ChangelogToBranchOptions changelogOptions = new ChangelogToBranchOptions("origin", "master"); scm.getExtensions().add(new ChangelogToBranch(changelogOptions)); } useChangelogToBranch = !useChangelogToBranch; } @Test public void testMerge() throws Exception { FreeStyleProject project = setupSimpleProject("master"); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("*")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", "default", MergeCommand.GitPluginFastForwardMode.FF))); addChangelogToBranchExtension(scm); project.setScm(scm); // create initial commit and then run the build against it: commit("commitFileBase", johnDoe, "Initial Commit"); testRepo.git.branch("integration"); build(project, Result.SUCCESS, "commitFileBase"); testRepo.git.checkout(null, "topic1"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertTrue(build1.getWorkspace().child(commitFile1).exists()); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); // do what the GitPublisher would do testRepo.git.deleteBranch("integration"); testRepo.git.checkout("topic1", "integration"); testRepo.git.checkout("master", "topic2"); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Issue("JENKINS-20392") @Test public void testMergeChangelog() throws Exception { FreeStyleProject project = setupSimpleProject("master"); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("*")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", "default", MergeCommand.GitPluginFastForwardMode.FF))); addChangelogToBranchExtension(scm); project.setScm(scm); // create initial commit and then run the build against it: // Here the changelog is by default empty (because changelog for first commit is always empty commit("commitFileBase", johnDoe, "Initial Commit"); testRepo.git.branch("integration"); build(project, Result.SUCCESS, "commitFileBase"); // Create second commit and run build // Here the changelog should contain exactly this one new commit testRepo.git.checkout("master", "topic2"); final String commitFile2 = "commitFile2"; String commitMessage = "Commit number 2"; commit(commitFile2, johnDoe, commitMessage); final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); ChangeLogSet<? extends ChangeLogSet.Entry> changeLog = build2.getChangeSet(); assertEquals("Changelog should contain one item", 1, changeLog.getItems().length); GitChangeSet singleChange = (GitChangeSet) changeLog.getItems()[0]; assertEquals("Changelog should contain commit number 2", commitMessage, singleChange.getComment().trim()); } @Test public void testMergeWithSlave() throws Exception { FreeStyleProject project = setupSimpleProject("master"); project.setAssignedLabel(rule.createSlave().getSelfLabel()); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("*")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", null, null))); addChangelogToBranchExtension(scm); project.setScm(scm); // create initial commit and then run the build against it: commit("commitFileBase", johnDoe, "Initial Commit"); testRepo.git.branch("integration"); build(project, Result.SUCCESS, "commitFileBase"); testRepo.git.checkout(null, "topic1"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertTrue(build1.getWorkspace().child(commitFile1).exists()); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); // do what the GitPublisher would do testRepo.git.deleteBranch("integration"); testRepo.git.checkout("topic1", "integration"); testRepo.git.checkout("master", "topic2"); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testMergeFailed() throws Exception { FreeStyleProject project = setupSimpleProject("master"); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("*")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); project.setScm(scm); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", "", MergeCommand.GitPluginFastForwardMode.FF))); addChangelogToBranchExtension(scm); // create initial commit and then run the build against it: commit("commitFileBase", johnDoe, "Initial Commit"); testRepo.git.branch("integration"); build(project, Result.SUCCESS, "commitFileBase"); testRepo.git.checkout(null, "topic1"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertTrue(build1.getWorkspace().child(commitFile1).exists()); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); // do what the GitPublisher would do testRepo.git.deleteBranch("integration"); testRepo.git.checkout("topic1", "integration"); testRepo.git.checkout("master", "topic2"); commit(commitFile1, "other content", johnDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); final FreeStyleBuild build2 = build(project, Result.FAILURE); rule.assertBuildStatus(Result.FAILURE, build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Issue("JENKINS-25191") @Test public void testMultipleMergeFailed() throws Exception { FreeStyleProject project = setupSimpleProject("master"); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("master")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); project.setScm(scm); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration1", "", MergeCommand.GitPluginFastForwardMode.FF))); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration2", "", MergeCommand.GitPluginFastForwardMode.FF))); addChangelogToBranchExtension(scm); commit("dummyFile", johnDoe, "Initial Commit"); testRepo.git.branch("integration1"); testRepo.git.branch("integration2"); build(project, Result.SUCCESS); final String commitFile = "commitFile"; testRepo.git.checkoutBranch("integration1","master"); commit(commitFile,"abc", johnDoe, "merge conflict with integration2"); testRepo.git.checkoutBranch("integration2","master"); commit(commitFile,"cde", johnDoe, "merge conflict with integration1"); final FreeStyleBuild build = build(project, Result.FAILURE); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testMergeFailedWithSlave() throws Exception { FreeStyleProject project = setupSimpleProject("master"); project.setAssignedLabel(rule.createSlave().getSelfLabel()); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("*")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", null, null))); addChangelogToBranchExtension(scm); project.setScm(scm); // create initial commit and then run the build against it: commit("commitFileBase", johnDoe, "Initial Commit"); testRepo.git.branch("integration"); build(project, Result.SUCCESS, "commitFileBase"); testRepo.git.checkout(null, "topic1"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertTrue(build1.getWorkspace().child(commitFile1).exists()); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); // do what the GitPublisher would do testRepo.git.deleteBranch("integration"); testRepo.git.checkout("topic1", "integration"); testRepo.git.checkout("master", "topic2"); commit(commitFile1, "other content", johnDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); final FreeStyleBuild build2 = build(project, Result.FAILURE); rule.assertBuildStatus(Result.FAILURE, build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testMergeWithMatrixBuild() throws Exception { //Create a matrix project and a couple of axes MatrixProject project = rule.jenkins.createProject(MatrixProject.class, "xyz"); project.setAxes(new AxisList(new Axis("VAR","a","b"))); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("*")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", null, null))); addChangelogToBranchExtension(scm); project.setScm(scm); // create initial commit and then run the build against it: commit("commitFileBase", johnDoe, "Initial Commit"); testRepo.git.branch("integration"); build(project, Result.SUCCESS, "commitFileBase"); testRepo.git.checkout(null, "topic1"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final MatrixBuild build1 = build(project, Result.SUCCESS, commitFile1); assertTrue(build1.getWorkspace().child(commitFile1).exists()); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); // do what the GitPublisher would do testRepo.git.deleteBranch("integration"); testRepo.git.checkout("topic1", "integration"); testRepo.git.checkout("master", "topic2"); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); final MatrixBuild build2 = build(project, Result.SUCCESS, commitFile2); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testEnvironmentVariableExpansion() throws Exception { FreeStyleProject project = createFreeStyleProject(); project.setScm(new GitSCM("${CAT}"+testRepo.gitDir.getPath())); // create initial commit and then run the build against it: commit("a.txt", johnDoe, "Initial Commit"); build(project, Result.SUCCESS, "a.txt"); PollingResult r = project.poll(StreamTaskListener.fromStdout()); assertFalse(r.hasChanges()); commit("b.txt", johnDoe, "Another commit"); r = project.poll(StreamTaskListener.fromStdout()); assertTrue(r.hasChanges()); build(project, Result.SUCCESS, "b.txt"); } @TestExtension("testEnvironmentVariableExpansion") public static class SupplySomeEnvVars extends EnvironmentContributor { @Override public void buildEnvironmentFor(Run r, EnvVars envs, TaskListener listener) throws IOException, InterruptedException { envs.put("CAT",""); } } private List<UserRemoteConfig> createRepoList(String url) { List<UserRemoteConfig> repoList = new ArrayList<>(); repoList.add(new UserRemoteConfig(url, null, null, null)); return repoList; } /** * Makes sure that git browser URL is preserved across config round trip. */ @Issue("JENKINS-22604") @Test public void testConfigRoundtripURLPreserved() throws Exception { FreeStyleProject p = createFreeStyleProject(); final String url = "https://github.com/jenkinsci/jenkins"; GitRepositoryBrowser browser = new GithubWeb(url); GitSCM scm = new GitSCM(createRepoList(url), Collections.singletonList(new BranchSpec("")), false, Collections.<SubmoduleConfig>emptyList(), browser, null, null); p.setScm(scm); rule.configRoundtrip(p); rule.assertEqualDataBoundBeans(scm,p.getScm()); assertEquals("Wrong key", "git " + url, scm.getKey()); } /** * Makes sure that git extensions are preserved across config round trip. */ @Issue("JENKINS-33695") @Test public void testConfigRoundtripExtensionsPreserved() throws Exception { FreeStyleProject p = createFreeStyleProject(); final String url = "git://github.com/jenkinsci/git-plugin.git"; GitRepositoryBrowser browser = new GithubWeb(url); GitSCM scm = new GitSCM(createRepoList(url), Collections.singletonList(new BranchSpec("*/master")), false, Collections.<SubmoduleConfig>emptyList(), browser, null, null); p.setScm(scm); /* Assert that no extensions are loaded initially */ assertEquals(Collections.emptyList(), scm.getExtensions().toList()); /* Add LocalBranch extension */ LocalBranch localBranchExtension = new LocalBranch("**"); scm.getExtensions().add(localBranchExtension); assertTrue(scm.getExtensions().toList().contains(localBranchExtension)); /* Save the configuration */ rule.configRoundtrip(p); List<GitSCMExtension> extensions = scm.getExtensions().toList();; assertTrue(extensions.contains(localBranchExtension)); assertEquals("Wrong extension count before reload", 1, extensions.size()); /* Reload configuration from disc */ p.doReload(); GitSCM reloadedGit = (GitSCM) p.getScm(); List<GitSCMExtension> reloadedExtensions = reloadedGit.getExtensions().toList(); assertEquals("Wrong extension count after reload", 1, reloadedExtensions.size()); LocalBranch reloadedLocalBranch = (LocalBranch) reloadedExtensions.get(0); assertEquals(localBranchExtension.getLocalBranch(), reloadedLocalBranch.getLocalBranch()); } /** * Makes sure that the configuration form works. */ @Test public void testConfigRoundtrip() throws Exception { FreeStyleProject p = createFreeStyleProject(); GitSCM scm = new GitSCM("https://github.com/jenkinsci/jenkins"); p.setScm(scm); rule.configRoundtrip(p); rule.assertEqualDataBoundBeans(scm,p.getScm()); } /** * Sample configuration that should result in no extensions at all */ @Test public void testDataCompatibility1() throws Exception { FreeStyleProject p = (FreeStyleProject) rule.jenkins.createProjectFromXML("foo", getClass().getResourceAsStream("GitSCMTest/old1.xml")); GitSCM oldGit = (GitSCM) p.getScm(); assertEquals(Collections.emptyList(), oldGit.getExtensions().toList()); assertEquals(0, oldGit.getSubmoduleCfg().size()); assertEquals("git git://github.com/jenkinsci/model-ant-project.git", oldGit.getKey()); assertThat(oldGit.getEffectiveBrowser(), instanceOf(GithubWeb.class)); GithubWeb browser = (GithubWeb) oldGit.getEffectiveBrowser(); assertEquals(browser.getRepoUrl(), "https://github.com/jenkinsci/model-ant-project.git/"); } @Test public void testPleaseDontContinueAnyway() throws Exception { // create an empty repository with some commits testRepo.commit("a","foo",johnDoe, "added"); FreeStyleProject p = createFreeStyleProject(); p.setScm(new GitSCM(testRepo.gitDir.getAbsolutePath())); rule.assertBuildStatusSuccess(p.scheduleBuild2(0)); // this should fail as it fails to fetch p.setScm(new GitSCM("http://localhost:4321/no/such/repository.git")); rule.assertBuildStatus(Result.FAILURE, p.scheduleBuild2(0).get()); } @Issue("JENKINS-19108") @Test public void testCheckoutToSpecificBranch() throws Exception { FreeStyleProject p = createFreeStyleProject(); GitSCM oldGit = new GitSCM("https://github.com/jenkinsci/model-ant-project.git/"); setupJGit(oldGit); oldGit.getExtensions().add(new LocalBranch("master")); p.setScm(oldGit); FreeStyleBuild b = rule.assertBuildStatusSuccess(p.scheduleBuild2(0)); GitClient gc = Git.with(StreamTaskListener.fromStdout(),null).in(b.getWorkspace()).getClient(); gc.withRepository(new RepositoryCallback<Void>() { public Void invoke(Repository repo, VirtualChannel channel) throws IOException, InterruptedException { Ref head = repo.getRef("HEAD"); assertTrue("Detached HEAD",head.isSymbolic()); Ref t = head.getTarget(); assertEquals(t.getName(),"refs/heads/master"); return null; } }); } /** * Verifies that if project specifies LocalBranch with value of "**" * that the checkout to a local branch using remote branch name sans 'origin'. * This feature is necessary to support Maven release builds that push updated * pom.xml to remote branch as * <br/> * <pre> * git push origin localbranch:localbranch * </pre> * @throws Exception */ @Test public void testCheckoutToDefaultLocalBranch_StarStar() throws Exception { FreeStyleProject project = setupSimpleProject("master"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); GitSCM git = (GitSCM)project.getScm(); git.getExtensions().add(new LocalBranch("**")); FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertEquals("GIT_BRANCH", "origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH)); assertEquals("GIT_LOCAL_BRANCH", "master", getEnvVars(project).get(GitSCM.GIT_LOCAL_BRANCH)); } /** * Verifies that if project specifies LocalBranch with null value (empty string) * that the checkout to a local branch using remote branch name sans 'origin'. * This feature is necessary to support Maven release builds that push updated * pom.xml to remote branch as * <br/> * <pre> * git push origin localbranch:localbranch * </pre> * @throws Exception */ @Test public void testCheckoutToDefaultLocalBranch_NULL() throws Exception { FreeStyleProject project = setupSimpleProject("master"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); GitSCM git = (GitSCM)project.getScm(); git.getExtensions().add(new LocalBranch("")); FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertEquals("GIT_BRANCH", "origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH)); assertEquals("GIT_LOCAL_BRANCH", "master", getEnvVars(project).get(GitSCM.GIT_LOCAL_BRANCH)); } /** * Verifies that GIT_LOCAL_BRANCH is not set if LocalBranch extension * is not configured. * @throws Exception */ @Test public void testCheckoutSansLocalBranchExtension() throws Exception { FreeStyleProject project = setupSimpleProject("master"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertEquals("GIT_BRANCH", "origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH)); assertEquals("GIT_LOCAL_BRANCH", null, getEnvVars(project).get(GitSCM.GIT_LOCAL_BRANCH)); } @Test public void testCheckoutFailureIsRetryable() throws Exception { FreeStyleProject project = setupSimpleProject("master"); // run build first to create workspace final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); // create lock file to simulate lock collision File lock = new File(build1.getWorkspace().toString(), ".git/index.lock"); try { FileUtils.touch(lock); final FreeStyleBuild build2 = build(project, Result.FAILURE); rule.assertLogContains("java.io.IOException: Could not checkout", build2); } finally { lock.delete(); } } @Test public void testInitSparseCheckout() throws Exception { if (!sampleRepo.gitVersionAtLeast(1, 7, 10)) { /* Older git versions have unexpected behaviors with sparse checkout */ return; } FreeStyleProject project = setupProject("master", Lists.newArrayList(new SparseCheckoutPath("toto"))); // run build first to create workspace final String commitFile1 = "toto/commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final String commitFile2 = "titi/commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); final FreeStyleBuild build1 = build(project, Result.SUCCESS); assertTrue(build1.getWorkspace().child("toto").exists()); assertTrue(build1.getWorkspace().child(commitFile1).exists()); assertFalse(build1.getWorkspace().child("titi").exists()); assertFalse(build1.getWorkspace().child(commitFile2).exists()); } @Test public void testInitSparseCheckoutBis() throws Exception { if (!sampleRepo.gitVersionAtLeast(1, 7, 10)) { /* Older git versions have unexpected behaviors with sparse checkout */ return; } FreeStyleProject project = setupProject("master", Lists.newArrayList(new SparseCheckoutPath("titi"))); // run build first to create workspace final String commitFile1 = "toto/commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final String commitFile2 = "titi/commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); final FreeStyleBuild build1 = build(project, Result.SUCCESS); assertTrue(build1.getWorkspace().child("titi").exists()); assertTrue(build1.getWorkspace().child(commitFile2).exists()); assertFalse(build1.getWorkspace().child("toto").exists()); assertFalse(build1.getWorkspace().child(commitFile1).exists()); } @Test public void testSparseCheckoutAfterNormalCheckout() throws Exception { if (!sampleRepo.gitVersionAtLeast(1, 7, 10)) { /* Older git versions have unexpected behaviors with sparse checkout */ return; } FreeStyleProject project = setupSimpleProject("master"); // run build first to create workspace final String commitFile1 = "toto/commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final String commitFile2 = "titi/commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); final FreeStyleBuild build1 = build(project, Result.SUCCESS); assertTrue(build1.getWorkspace().child("titi").exists()); assertTrue(build1.getWorkspace().child(commitFile2).exists()); assertTrue(build1.getWorkspace().child("toto").exists()); assertTrue(build1.getWorkspace().child(commitFile1).exists()); ((GitSCM) project.getScm()).getExtensions().add(new SparseCheckoutPaths(Lists.newArrayList(new SparseCheckoutPath("titi")))); final FreeStyleBuild build2 = build(project, Result.SUCCESS); assertTrue(build2.getWorkspace().child("titi").exists()); assertTrue(build2.getWorkspace().child(commitFile2).exists()); assertFalse(build2.getWorkspace().child("toto").exists()); assertFalse(build2.getWorkspace().child(commitFile1).exists()); } @Test public void testNormalCheckoutAfterSparseCheckout() throws Exception { if (!sampleRepo.gitVersionAtLeast(1, 7, 10)) { /* Older git versions have unexpected behaviors with sparse checkout */ return; } FreeStyleProject project = setupProject("master", Lists.newArrayList(new SparseCheckoutPath("titi"))); // run build first to create workspace final String commitFile1 = "toto/commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final String commitFile2 = "titi/commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); final FreeStyleBuild build2 = build(project, Result.SUCCESS); assertTrue(build2.getWorkspace().child("titi").exists()); assertTrue(build2.getWorkspace().child(commitFile2).exists()); assertFalse(build2.getWorkspace().child("toto").exists()); assertFalse(build2.getWorkspace().child(commitFile1).exists()); ((GitSCM) project.getScm()).getExtensions().remove(SparseCheckoutPaths.class); final FreeStyleBuild build1 = build(project, Result.SUCCESS); assertTrue(build1.getWorkspace().child("titi").exists()); assertTrue(build1.getWorkspace().child(commitFile2).exists()); assertTrue(build1.getWorkspace().child("toto").exists()); assertTrue(build1.getWorkspace().child(commitFile1).exists()); } @Test public void testInitSparseCheckoutOverSlave() throws Exception { if (!sampleRepo.gitVersionAtLeast(1, 7, 10)) { /* Older git versions have unexpected behaviors with sparse checkout */ return; } FreeStyleProject project = setupProject("master", Lists.newArrayList(new SparseCheckoutPath("titi"))); project.setAssignedLabel(rule.createSlave().getSelfLabel()); // run build first to create workspace final String commitFile1 = "toto/commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final String commitFile2 = "titi/commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); final FreeStyleBuild build1 = build(project, Result.SUCCESS); assertTrue(build1.getWorkspace().child("titi").exists()); assertTrue(build1.getWorkspace().child(commitFile2).exists()); assertFalse(build1.getWorkspace().child("toto").exists()); assertFalse(build1.getWorkspace().child(commitFile1).exists()); } /** * Test for JENKINS-22009. * * @throws Exception */ @Test public void testPolling_environmentValueInBranchSpec() throws Exception { // create parameterized project with environment value in branch specification FreeStyleProject project = createFreeStyleProject(); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("${MY_BRANCH}")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); project.setScm(scm); project.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("MY_BRANCH", "master"))); // commit something in order to create an initial base version in git commit("toto/commitFile1", johnDoe, "Commit number 1"); // build the project build(project, Result.SUCCESS); assertFalse("No changes to git since last build, thus no new build is expected", project.poll(listener).hasChanges()); } @Issue("JENKINS-29066") public void baseTestPolling_parentHead(List<GitSCMExtension> extensions) throws Exception { // create parameterized project with environment value in branch specification FreeStyleProject project = createFreeStyleProject(); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("**")), false, Collections.<SubmoduleConfig>emptyList(), null, null, extensions); project.setScm(scm); // commit something in order to create an initial base version in git commit("toto/commitFile1", johnDoe, "Commit number 1"); git.branch("someBranch"); commit("toto/commitFile2", johnDoe, "Commit number 2"); assertTrue("polling should detect changes",project.poll(listener).hasChanges()); // build the project build(project, Result.SUCCESS); /* Expects 1 build because the build of someBranch incorporates all * the changes from the master branch as well as the changes from someBranch. */ assertEquals("Wrong number of builds", 1, project.getBuilds().size()); assertFalse("polling should not detect changes",project.poll(listener).hasChanges()); } @Issue("JENKINS-29066") @Test public void testPolling_parentHead() throws Exception { baseTestPolling_parentHead(Collections.<GitSCMExtension>emptyList()); } @Issue("JENKINS-29066") @Test public void testPolling_parentHead_DisableRemotePoll() throws Exception { baseTestPolling_parentHead(Collections.<GitSCMExtension>singletonList(new DisableRemotePoll())); } @Test public void testPollingAfterManualBuildWithParametrizedBranchSpec() throws Exception { // create parameterized project with environment value in branch specification FreeStyleProject project = createFreeStyleProject(); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("${MY_BRANCH}")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); project.setScm(scm); project.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("MY_BRANCH", "trackedbranch"))); // Initial commit to master commit("file1", johnDoe, "Initial Commit"); // Create the branches git.branch("trackedbranch"); git.branch("manualbranch"); final StringParameterValue branchParam = new StringParameterValue("MY_BRANCH", "manualbranch"); final Action[] actions = {new ParametersAction(branchParam)}; FreeStyleBuild build = project.scheduleBuild2(0, new Cause.UserCause(), actions).get(); rule.assertBuildStatus(Result.SUCCESS, build); assertFalse("No changes to git since last build", project.poll(listener).hasChanges()); git.checkout("manualbranch"); commit("file2", johnDoe, "Commit to manually build branch"); assertFalse("No changes to tracked branch", project.poll(listener).hasChanges()); git.checkout("trackedbranch"); commit("file3", johnDoe, "Commit to tracked branch"); assertTrue("A change should be detected in tracked branch", project.poll(listener).hasChanges()); } private final class FakeParametersAction implements EnvironmentContributingAction, Serializable { // Test class for testPolling_environmentValueAsEnvironmentContributingAction test case final ParametersAction m_forwardingAction; public FakeParametersAction(StringParameterValue params) { this.m_forwardingAction = new ParametersAction(params); } public void buildEnvVars(AbstractBuild<?, ?> ab, EnvVars ev) { this.m_forwardingAction.buildEnvVars(ab, ev); } public String getIconFileName() { return this.m_forwardingAction.getIconFileName(); } public String getDisplayName() { return this.m_forwardingAction.getDisplayName(); } public String getUrlName() { return this.m_forwardingAction.getUrlName(); } public List<ParameterValue> getParameters() { return this.m_forwardingAction.getParameters(); } private void writeObject(java.io.ObjectOutputStream out) throws IOException { } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { } private void readObjectNoData() throws ObjectStreamException { } } @Test public void testPolling_CanDoRemotePollingIfOneBranchButMultipleRepositories() throws Exception { FreeStyleProject project = createFreeStyleProject(); List<UserRemoteConfig> remoteConfigs = new ArrayList<>(); remoteConfigs.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", "", null)); remoteConfigs.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "someOtherRepo", "", null)); GitSCM scm = new GitSCM(remoteConfigs, Collections.singletonList(new BranchSpec("origin/master")), false, Collections.<SubmoduleConfig> emptyList(), null, null, Collections.<GitSCMExtension> emptyList()); project.setScm(scm); commit("commitFile1", johnDoe, "Commit number 1"); FreeStyleBuild first_build = project.scheduleBuild2(0, new Cause.UserCause()).get(); rule.assertBuildStatus(Result.SUCCESS, first_build); first_build.getWorkspace().deleteContents(); PollingResult pollingResult = scm.poll(project, null, first_build.getWorkspace(), listener, null); assertFalse(pollingResult.hasChanges()); } /** * Test for JENKINS-24467. * * @throws Exception */ @Test public void testPolling_environmentValueAsEnvironmentContributingAction() throws Exception { // create parameterized project with environment value in branch specification FreeStyleProject project = createFreeStyleProject(); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("${MY_BRANCH}")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); project.setScm(scm); // Inital commit and build commit("toto/commitFile1", johnDoe, "Commit number 1"); String brokenPath = "\\broken/path\\of/doom"; if (!sampleRepo.gitVersionAtLeast(1, 8)) { /* Git 1.7.10.4 fails the first build unless the git-upload-pack * program is available in its PATH. * Later versions of git don't have that problem. */ final String systemPath = System.getenv("PATH"); brokenPath = systemPath + File.pathSeparator + brokenPath; } final StringParameterValue real_param = new StringParameterValue("MY_BRANCH", "master"); final StringParameterValue fake_param = new StringParameterValue("PATH", brokenPath); final Action[] actions = {new ParametersAction(real_param), new FakeParametersAction(fake_param)}; // SECURITY-170 - have to use ParametersDefinitionProperty project.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("MY_BRANCH", "master"))); FreeStyleBuild first_build = project.scheduleBuild2(0, new Cause.UserCause(), actions).get(); rule.assertBuildStatus(Result.SUCCESS, first_build); Launcher launcher = workspace.createLauncher(listener); final EnvVars environment = GitUtils.getPollEnvironment(project, workspace, launcher, listener); assertEquals(environment.get("MY_BRANCH"), "master"); assertNotSame("Enviroment path should not be broken path", environment.get("PATH"), brokenPath); } /** * Tests that builds have the correctly specified Custom SCM names, associated with * each build. * @throws Exception on various exceptions */ @Ignore("Intermittent failures on stable-3.10 branch, not on stable-3.9 or master") @Test public void testCustomSCMName() throws Exception { final String branchName = "master"; final FreeStyleProject project = setupProject(branchName, false); project.addTrigger(new SCMTrigger("")); GitSCM git = (GitSCM) project.getScm(); setupJGit(git); final String commitFile1 = "commitFile1"; final String scmNameString1 = ""; commit(commitFile1, johnDoe, "Commit number 1"); assertTrue("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); build(project, Result.SUCCESS, commitFile1); final ObjectId commit1 = testRepo.git.revListAll().get(0); // Check unset build SCM Name carries final int buildNumber1 = notifyAndCheckScmName( project, commit1, scmNameString1, 1, git); final String scmNameString2 = "ScmName2"; git.getExtensions().replace(new ScmName(scmNameString2)); commit("commitFile2", johnDoe, "Commit number 2"); assertTrue("scm polling should detect commit 2", project.poll(listener).hasChanges()); final ObjectId commit2 = testRepo.git.revListAll().get(0); // Check second set SCM Name final int buildNumber2 = notifyAndCheckScmName( project, commit2, scmNameString2, 2, git); checkNumberedBuildScmName(project, buildNumber1, scmNameString1, git); final String scmNameString3 = "ScmName3"; git.getExtensions().replace(new ScmName(scmNameString3)); commit("commitFile3", johnDoe, "Commit number 3"); assertTrue("scm polling should detect commit 3", project.poll(listener).hasChanges()); final ObjectId commit3 = testRepo.git.revListAll().get(0); // Check third set SCM Name final int buildNumber3 = notifyAndCheckScmName( project, commit3, scmNameString3, 3, git); checkNumberedBuildScmName(project, buildNumber1, scmNameString1, git); checkNumberedBuildScmName(project, buildNumber2, scmNameString2, git); commit("commitFile4", johnDoe, "Commit number 4"); assertTrue("scm polling should detect commit 4", project.poll(listener).hasChanges()); final ObjectId commit4 = testRepo.git.revListAll().get(0); // Check third set SCM Name still set final int buildNumber4 = notifyAndCheckScmName( project, commit4, scmNameString3, 4, git); checkNumberedBuildScmName(project, buildNumber1, scmNameString1, git); checkNumberedBuildScmName(project, buildNumber2, scmNameString2, git); checkNumberedBuildScmName(project, buildNumber3, scmNameString3, git); } /** * Method performs HTTP get on "notifyCommit" URL, passing it commit by SHA1 * and tests for custom SCM name build data consistency. * @param project project to build * @param commit commit to build * @param expectedScmName Expected SCM name for commit. * @param ordinal number of commit to log into errors, if any * @param git git SCM * @throws Exception on various exceptions occur */ private int notifyAndCheckScmName(FreeStyleProject project, ObjectId commit, String expectedScmName, int ordinal, GitSCM git) throws Exception { assertTrue("scm polling should detect commit " + ordinal, notifyCommit(project, commit)); final Build build = project.getLastBuild(); final BuildData buildData = git.getBuildData(build); assertEquals("Expected SHA1 != built SHA1 for commit " + ordinal, commit, buildData .getLastBuiltRevision().getSha1()); assertEquals("Expected SHA1 != retrieved SHA1 for commit " + ordinal, commit, buildData.getLastBuild(commit).getSHA1()); assertTrue("Commit " + ordinal + " not marked as built", buildData.hasBeenBuilt(commit)); assertEquals("Wrong SCM Name for commit " + ordinal, expectedScmName, buildData.getScmName()); return build.getNumber(); } private void checkNumberedBuildScmName(FreeStyleProject project, int buildNumber, String expectedScmName, GitSCM git) throws Exception { final BuildData buildData = git.getBuildData(project.getBuildByNumber(buildNumber)); assertEquals("Wrong SCM Name", expectedScmName, buildData.getScmName()); } /** * Tests that builds have the correctly specified branches, associated with * the commit id, passed with "notifyCommit" URL. * @throws Exception on various exceptions */ @Ignore("Intermittent failures on stable-3.10 branch, not on stable-3.9 or master") @Issue("JENKINS-24133") @Test public void testSha1NotificationBranches() throws Exception { final String branchName = "master"; final FreeStyleProject project = setupProject(branchName, false); project.addTrigger(new SCMTrigger("")); final GitSCM git = (GitSCM) project.getScm(); setupJGit(git); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); assertTrue("scm polling should detect commit 1", project.poll(listener).hasChanges()); build(project, Result.SUCCESS, commitFile1); final ObjectId commit1 = testRepo.git.revListAll().get(0); notifyAndCheckBranch(project, commit1, branchName, 1, git); commit("commitFile2", johnDoe, "Commit number 2"); assertTrue("scm polling should detect commit 2", project.poll(listener).hasChanges()); final ObjectId commit2 = testRepo.git.revListAll().get(0); notifyAndCheckBranch(project, commit2, branchName, 2, git); notifyAndCheckBranch(project, commit1, branchName, 1, git); } /* A null pointer exception was detected because the plugin failed to * write a branch name to the build data, so there was a SHA1 recorded * in the build data, but no branch name. */ @Test public void testNoNullPointerExceptionWithNullBranch() throws Exception { ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d"); /* This is the null that causes NPE */ Branch branch = new Branch(null, sha1); List<Branch> branchList = new ArrayList<>(); branchList.add(branch); Revision revision = new Revision(sha1, branchList); /* BuildData mock that will use the Revision with null branch name */ BuildData buildData = Mockito.mock(BuildData.class); Mockito.when(buildData.getLastBuiltRevision()).thenReturn(revision); Mockito.when(buildData.hasBeenReferenced(anyString())).thenReturn(true); /* List of build data that will be returned by the mocked BuildData */ List<BuildData> buildDataList = new ArrayList<>(); buildDataList.add(buildData); /* AbstractBuild mock which returns the buildDataList that contains a null branch name */ AbstractBuild build = Mockito.mock(AbstractBuild.class); Mockito.when(build.getActions(BuildData.class)).thenReturn(buildDataList); final FreeStyleProject project = setupProject("*/*", false); GitSCM scm = (GitSCM) project.getScm(); scm.buildEnvVars(build, new EnvVars()); // NPE here before fix applied /* Verify mocks were called as expected */ verify(buildData, times(1)).getLastBuiltRevision(); verify(buildData, times(1)).hasBeenReferenced(anyString()); verify(build, times(1)).getActions(BuildData.class); } @Test public void testBuildEnvVarsLocalBranchStarStar() throws Exception { ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d"); /* This is the null that causes NPE */ Branch branch = new Branch("origin/master", sha1); List<Branch> branchList = new ArrayList<>(); branchList.add(branch); Revision revision = new Revision(sha1, branchList); /* BuildData mock that will use the Revision with null branch name */ BuildData buildData = Mockito.mock(BuildData.class); Mockito.when(buildData.getLastBuiltRevision()).thenReturn(revision); Mockito.when(buildData.hasBeenReferenced(anyString())).thenReturn(true); /* List of build data that will be returned by the mocked BuildData */ List<BuildData> buildDataList = new ArrayList<>(); buildDataList.add(buildData); /* AbstractBuild mock which returns the buildDataList that contains a null branch name */ AbstractBuild build = Mockito.mock(AbstractBuild.class); Mockito.when(build.getActions(BuildData.class)).thenReturn(buildDataList); final FreeStyleProject project = setupProject("*/*", false); GitSCM scm = (GitSCM) project.getScm(); scm.getExtensions().add(new LocalBranch("**")); EnvVars env = new EnvVars(); scm.buildEnvVars(build, env); // NPE here before fix applied assertEquals("GIT_BRANCH", "origin/master", env.get("GIT_BRANCH")); assertEquals("GIT_LOCAL_BRANCH", "master", env.get("GIT_LOCAL_BRANCH")); /* Verify mocks were called as expected */ verify(buildData, times(1)).getLastBuiltRevision(); verify(buildData, times(1)).hasBeenReferenced(anyString()); verify(build, times(1)).getActions(BuildData.class); } @Test public void testBuildEnvVarsLocalBranchNull() throws Exception { ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d"); /* This is the null that causes NPE */ Branch branch = new Branch("origin/master", sha1); List<Branch> branchList = new ArrayList<>(); branchList.add(branch); Revision revision = new Revision(sha1, branchList); /* BuildData mock that will use the Revision with null branch name */ BuildData buildData = Mockito.mock(BuildData.class); Mockito.when(buildData.getLastBuiltRevision()).thenReturn(revision); Mockito.when(buildData.hasBeenReferenced(anyString())).thenReturn(true); /* List of build data that will be returned by the mocked BuildData */ List<BuildData> buildDataList = new ArrayList<>(); buildDataList.add(buildData); /* AbstractBuild mock which returns the buildDataList that contains a null branch name */ AbstractBuild build = Mockito.mock(AbstractBuild.class); Mockito.when(build.getActions(BuildData.class)).thenReturn(buildDataList); final FreeStyleProject project = setupProject("*/*", false); GitSCM scm = (GitSCM) project.getScm(); scm.getExtensions().add(new LocalBranch("")); EnvVars env = new EnvVars(); scm.buildEnvVars(build, env); // NPE here before fix applied assertEquals("GIT_BRANCH", "origin/master", env.get("GIT_BRANCH")); assertEquals("GIT_LOCAL_BRANCH", "master", env.get("GIT_LOCAL_BRANCH")); /* Verify mocks were called as expected */ verify(buildData, times(1)).getLastBuiltRevision(); verify(buildData, times(1)).hasBeenReferenced(anyString()); verify(build, times(1)).getActions(BuildData.class); } @Test public void testBuildEnvVarsLocalBranchNotSet() throws Exception { ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d"); /* This is the null that causes NPE */ Branch branch = new Branch("origin/master", sha1); List<Branch> branchList = new ArrayList<>(); branchList.add(branch); Revision revision = new Revision(sha1, branchList); /* BuildData mock that will use the Revision with null branch name */ BuildData buildData = Mockito.mock(BuildData.class); Mockito.when(buildData.getLastBuiltRevision()).thenReturn(revision); Mockito.when(buildData.hasBeenReferenced(anyString())).thenReturn(true); /* List of build data that will be returned by the mocked BuildData */ List<BuildData> buildDataList = new ArrayList<>(); buildDataList.add(buildData); /* AbstractBuild mock which returns the buildDataList that contains a null branch name */ AbstractBuild build = Mockito.mock(AbstractBuild.class); Mockito.when(build.getActions(BuildData.class)).thenReturn(buildDataList); final FreeStyleProject project = setupProject("*/*", false); GitSCM scm = (GitSCM) project.getScm(); EnvVars env = new EnvVars(); scm.buildEnvVars(build, env); // NPE here before fix applied assertEquals("GIT_BRANCH", "origin/master", env.get("GIT_BRANCH")); assertEquals("GIT_LOCAL_BRANCH", null, env.get("GIT_LOCAL_BRANCH")); /* Verify mocks were called as expected */ verify(buildData, times(1)).getLastBuiltRevision(); verify(buildData, times(1)).hasBeenReferenced(anyString()); verify(build, times(1)).getActions(BuildData.class); } @Issue("JENKINS-38241") @Test public void testCommitMessageIsPrintedToLogs() throws Exception { sampleRepo.init(); sampleRepo.write("file", "v1"); sampleRepo.git("commit", "--all", "--message=test commit"); FreeStyleProject p = setupSimpleProject("master"); Run<?,?> run = rule.buildAndAssertSuccess(p); TaskListener mockListener = Mockito.mock(TaskListener.class); Mockito.when(mockListener.getLogger()).thenReturn(Mockito.spy(StreamTaskListener.fromStdout().getLogger())); p.getScm().checkout(run, new Launcher.LocalLauncher(listener), new FilePath(run.getRootDir()).child("tmp-" + "master"), mockListener, null, SCMRevisionState.NONE); ArgumentCaptor<String> logCaptor = ArgumentCaptor.forClass(String.class); verify(mockListener.getLogger(), atLeastOnce()).println(logCaptor.capture()); List<String> values = logCaptor.getAllValues(); assertThat(values, hasItem("Commit message: \"test commit\"")); } /** * Method performs HTTP get on "notifyCommit" URL, passing it commit by SHA1 * and tests for build data consistency. * @param project project to build * @param commit commit to build * @param expectedBranch branch, that is expected to be built * @param ordinal number of commit to log into errors, if any * @param git git SCM * @throws Exception on various exceptions occur */ private void notifyAndCheckBranch(FreeStyleProject project, ObjectId commit, String expectedBranch, int ordinal, GitSCM git) throws Exception { assertTrue("scm polling should detect commit " + ordinal, notifyCommit(project, commit)); final BuildData buildData = git.getBuildData(project.getLastBuild()); final Collection<Branch> builtBranches = buildData.lastBuild.getRevision().getBranches(); assertEquals("Commit " + ordinal + " should be built", commit, buildData .getLastBuiltRevision().getSha1()); final String expectedBranchString = "origin/" + expectedBranch; assertFalse("Branches should be detected for the build", builtBranches.isEmpty()); assertEquals(expectedBranch + " branch should be detected", expectedBranchString, builtBranches.iterator().next().getName()); assertEquals(expectedBranchString, getEnvVars(project).get(GitSCM.GIT_BRANCH)); } /** * Method performs commit notification for the last committed SHA1 using * notifyCommit URL. * @param project project to trigger * @return whether the new build has been triggered (<code>true</code>) or * not (<code>false</code>). * @throws Exception on various exceptions */ private boolean notifyCommit(FreeStyleProject project, ObjectId commitId) throws Exception { final int initialBuildNumber = project.getLastBuild().getNumber(); final String commit1 = ObjectId.toString(commitId); final String notificationPath = rule.getURL().toExternalForm() + "git/notifyCommit?url=" + testRepo.gitDir.toString() + "&sha1=" + commit1; final URL notifyUrl = new URL(notificationPath); String notifyContent = null; try (final InputStream is = notifyUrl.openStream()) { notifyContent = IOUtils.toString(is); } assertThat(notifyContent, containsString("No Git consumers using SCM API plugin for: " + testRepo.gitDir.toString())); if ((project.getLastBuild().getNumber() == initialBuildNumber) && (rule.jenkins.getQueue().isEmpty())) { return false; } else { while (!rule.jenkins.getQueue().isEmpty()) { Thread.sleep(100); } final FreeStyleBuild build = project.getLastBuild(); while (build.isBuilding()) { Thread.sleep(100); } return true; } } private void setupJGit(GitSCM git) { git.gitTool="jgit"; rule.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(new JGitTool(Collections.<ToolProperty<?>>emptyList())); } /** We clean the environment, just in case the test is being run from a Jenkins job using this same plugin :). */ @TestExtension public static class CleanEnvironment extends EnvironmentContributor { @Override public void buildEnvironmentFor(Run run, EnvVars envs, TaskListener listener) { envs.remove(GitSCM.GIT_BRANCH); envs.remove(GitSCM.GIT_LOCAL_BRANCH); envs.remove(GitSCM.GIT_COMMIT); envs.remove(GitSCM.GIT_PREVIOUS_COMMIT); envs.remove(GitSCM.GIT_PREVIOUS_SUCCESSFUL_COMMIT); } } }
Add issue annotation for JENKINS-22009
src/test/java/hudson/plugins/git/GitSCMTest.java
Add issue annotation for JENKINS-22009
<ide><path>rc/test/java/hudson/plugins/git/GitSCMTest.java <ide> * @throws Exception <ide> */ <ide> @Test <add> @Issue("JENKINS-22009") <ide> public void testPolling_environmentValueInBranchSpec() throws Exception { <ide> // create parameterized project with environment value in branch specification <ide> FreeStyleProject project = createFreeStyleProject();
Java
mit
b4039558b7143b076a072dc5b814a15591ec30d7
0
pebble-bike/PebbleBike-AndroidApp,pebble-bike/PebbleBike-AndroidApp,ventoo-bike/Ventoo-AndroidApp,jay3/Ventoo-AndroidApp,team-mount-ventoux/PebbleVentoo-AndroidApp,jay3/Ventoo-AndroidApp,team-mount-ventoux/PebbleVentoo-AndroidApp,ventoo-bike/Ventoo-AndroidApp
package com.njackson; import android.app.ActivityManager; import android.app.AlertDialog; import android.app.Dialog; import android.app.PendingIntent; import android.content.*; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.ViewGroup; import android.widget.Toast; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.SherlockFragment; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.getpebble.android.kit.PebbleKit; import com.getpebble.android.kit.util.PebbleDictionary; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesClient; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.location.ActivityRecognitionClient; import com.google.android.gms.location.DetectedActivity; import com.google.android.gms.maps.model.LatLng; import com.njackson.util.AltitudeGraphReduce; import de.cketti.library.changelog.ChangeLog; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.concurrent.TimeUnit; public class MainActivity extends SherlockFragmentActivity implements GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener, HomeActivity.OnButtonPressListener { private static final String TAG = "PB-MainActivity"; private ActivityRecognitionClient _mActivityRecognitionClient; private static boolean _activityRecognition = false; public static boolean _liveTracking = false; private PendingIntent _callbackIntent; private RequestType _requestType; private static int _units = Constants.IMPERIAL; private static float _speedConversion = 0.0f; private static float _distanceConversion = 0.0f; private static float _altitudeConversion = 0.0f; private Date _lastCycling; private ActivityRecognitionReceiver _activityRecognitionReceiver; private GPSServiceReceiver _gpsServiceReceiver; private boolean _googlePlayInstalled; private Fragment _mapFragment; enum RequestType { START, STOP } static MainActivity instance; public static MainActivity getInstance() { return instance; } public Boolean activityRecognitionEnabled() { return _activityRecognition; } // Listener for the fragment button press @Override public void onPressed(int sender, boolean value) { //To change body of implemented methods use File | Settings | File Templates. switch(sender) { case R.id.MAIN_START_BUTTON: startButtonClick(value); break; } } public void loadPreferences() { loadPreferences(PreferenceManager.getDefaultSharedPreferences(getApplicationContext())); } public void loadPreferences(SharedPreferences prefs) { //setup the defaults _activityRecognition = prefs.getBoolean("ACTIVITY_RECOGNITION",false); _liveTracking = prefs.getBoolean("LIVE_TRACKING",false); if(_activityRecognition) initActivityRecognitionClient(); else stopActivityRecogntionClient(); HomeActivity activity = getHomeScreen(); if(activity != null) activity.setStartButtonVisibility(!_activityRecognition); try { setConversionUnits(Integer.valueOf(prefs.getString("UNITS_OF_MEASURE", "0"))); } catch (Exception e) { Log.e(TAG, "Exception:" + e); } } private void startButtonClick(boolean value) { if(value) { startGPSService(); } else { stopGPSService(); } } public void setConversionUnits(int units) { _units = units; if(units == Constants.IMPERIAL) { _speedConversion = (float)Constants.MS_TO_MPH; _distanceConversion = (float)Constants.M_TO_MILES; _altitudeConversion = (float)Constants.M_TO_FEET; } else { _speedConversion = (float)Constants.MS_TO_KPH; _distanceConversion = (float)Constants.M_TO_KM; _altitudeConversion = (float)Constants.M_TO_M; } // set the screen units HomeActivity homeScreen = getHomeScreen(); if(homeScreen != null) homeScreen.setUnits(units); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); instance = this; setContentView(R.layout.main); final ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(false); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); actionBar.setDisplayHomeAsUpEnabled(false); ChangeLog cl = new ChangeLog(this); if (cl.isFirstRun()) { cl.getLogDialog().show(); } checkGooglePlayServices(); loadPreferences(); Bundle bundle = new Bundle(); bundle.putBoolean("ACTIVITY_RECOGNITION",_activityRecognition); bundle.putBoolean("LIVE_TRACKING",_liveTracking); bundle.putInt("UNITS_OF_MEASURE",_units); //instantiate the map fragment and store for future use //_mapFragment = Fragment.instantiate(this, "map", bundle); actionBar.addTab(actionBar.newTab().setText(R.string.TAB_TITLE_HOME).setTabListener(new TabListener<HomeActivity>(this, "home", HomeActivity.class, bundle))); //actionBar.addTab(actionBar.newTab().setText(R.string.TAB_TITLE_MAP).setTabListener(new TabListener<MapActivity>(this,"map",MapActivity.class,_mapFragment,null))); if (getIntent().getExtras() != null) { if (getIntent().getExtras().containsKey("button")) { Log.d(TAG, "onCreate() button:" + getIntent().getExtras().getInt("button")); changeState(getIntent().getExtras().getInt("button")); } if (getIntent().getExtras().containsKey("version")) { Log.d(TAG, "onCreate() version:" + getIntent().getExtras().getInt("version")); resendLastDataToPebble(); } /*if (getIntent().getExtras().containsKey("live_max_name")) { Log.d(TAG, "onNewIntent() live_max_name:" + getIntent().getExtras().getInt("live_max_name")); GPSService.liveSendNames(getIntent().getExtras().getInt("live_max_name")); }*/ } } @Override public void onResume() { super.onResume(); } public boolean onKeyUp(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_MENU) { // Physical Menu button startActivity(new Intent(getApplicationContext(), SettingsActivity.class)); } return super.onKeyUp(keyCode, event); } // This is called for activities that set launchMode to "singleTop" in their package, or if a client used the FLAG_ACTIVITY_SINGLE_TOP flag when calling startActivity(Intent). // In either case, when the activity is re-launched while at the top of the activity stack instead of a new instance of the activity being started, onNewIntent() will be called // on the existing instance with the Intent that was used to re-launch it. // An activity will always be paused before receiving a new intent, so you can count on onResume() being called after this method. protected void onNewIntent (Intent intent) { if (intent.getExtras() != null) { if (intent.getExtras().containsKey("button")) { Log.d(TAG, "onNewIntent() button:" + intent.getExtras().getInt("button")); changeState(intent.getExtras().getInt("button")); } if (intent.getExtras().containsKey("version")) { Log.d(TAG, "onNewIntent() version:" + intent.getExtras().getInt("version")); resendLastDataToPebble(); } /*if (intent.getExtras().containsKey("live_max_name")) { Log.d(TAG, "onNewIntent() live_max_name:" + intent.getExtras().getInt("live_max_name")); GPSService.liveSendNames(intent.getExtras().getInt("live_max_name")); }*/ } } private void changeState(int button) { Log.d(TAG, "changeState(button:" + button + ")"); switch (button) { case Constants.STOP_PRESS: stopGPSService(); setStartButtonText("Start"); break; case Constants.PLAY_PRESS: startGPSService(); setStartButtonText("Stop"); break; case Constants.REFRESH_PRESS: ResetSavedGPSStats(); break; } } private void sendWatchFaceToPebble(){ try { Uri uri = Uri.parse("http://labs.jayps.fr/pebblebike/pebblebike-1.2.0.pbw?and"); Intent startupIntent = new Intent(); startupIntent.setAction(Intent.ACTION_VIEW); startupIntent.setType("application/octet-stream"); startupIntent.setData(uri); ComponentName distantActivity = new ComponentName("com.getpebble.android", "com.getpebble.android.ui.UpdateActivity"); startupIntent.setComponent(distantActivity); startActivity(startupIntent); }catch (ActivityNotFoundException ae) { Toast.makeText(getApplicationContext(),"Unable to install watchface, do you have the latest pebble app installed?",Toast.LENGTH_LONG).show(); } } private void sendServiceState() { Log.d(TAG, "sendServiceState()"); PebbleDictionary dic = new PebbleDictionary(); if(checkServiceRunning()) { dic.addInt32(Constants.STATE_CHANGED,Constants.STATE_START); } else { dic.addInt32(Constants.STATE_CHANGED,Constants.STATE_STOP); } Log.d(TAG, " STATE_CHANGED: " + dic.getInteger(Constants.STATE_CHANGED)); PebbleKit.sendDataToPebble(getApplicationContext(), Constants.WATCH_UUID, dic); } private Intent _lastIntent = null; private void resendLastDataToPebble() { sendDataToPebble(_lastIntent); } public void sendDataToPebble(Intent intent) { //Log.d(TAG, "sendDataToPebble()"); PebbleDictionary dic = new PebbleDictionary(); String sending = "Sending "; if (intent == null) { Log.d(TAG, "sendDataToPebble(intent == null)"); intent = new Intent(); SharedPreferences settings = getSharedPreferences(Constants.PREFS_NAME,0); float distance = settings.getFloat("GPS_DISTANCE", 0.0f); intent.putExtra("DISTANCE", distance); dic.addInt32(Constants.MSG_VERSION_ANDROID, Constants.VERSION_ANDROID); sending += " MSG_VERSION_ANDROID: " + dic.getInteger(Constants.MSG_VERSION_ANDROID); } if (intent != null) { _lastIntent = intent; byte[] data = new byte[20]; int version = 0; data[0] = (byte) ((_units % 2) * 1); if (checkServiceRunning()) { data[0] += (byte) (1 * 2); } else { data[0] += (byte) (0 * 2); } // 2 unused bits data[0] += (byte) (0 * 4); data[0] += (byte) (0 * 8); data[0] += (byte) ((version % 4) * 16); data[1] = (byte) ((int) Math.ceil(intent.getFloatExtra("ACCURACY", 0.0f))); data[2] = (byte) (((int) (Math.floor(100 * intent.getFloatExtra("DISTANCE", 0.0f) * _distanceConversion) / 1)) % 256); data[3] = (byte) (((int) (Math.floor(100 * intent.getFloatExtra("DISTANCE", 0.0f) * _distanceConversion) / 1)) / 256); data[4] = (byte) (((int) intent.getLongExtra("TIME", 0) / 1000) % 256); data[5] = (byte) (((int) intent.getLongExtra("TIME", 0) / 1000) / 256); data[6] = (byte) (((int) (intent.getDoubleExtra("ALTITUDE", 0) * _altitudeConversion)) % 256); data[7] = (byte) (((int) (intent.getDoubleExtra("ALTITUDE", 0) * _altitudeConversion)) / 256); data[8] = (byte) (((int) Math.abs(intent.getDoubleExtra("ASCENT", 0) * _altitudeConversion)) % 256); data[9] = (byte) ((((int) Math.abs(intent.getDoubleExtra("ASCENT", 0) * _altitudeConversion)) / 256) % 128); if (intent.getDoubleExtra("ASCENT", 0.0f) < 0) { data[9] += 128; } data[10] = (byte) (((int) Math.abs(intent.getFloatExtra("ASCENTRATE", 0.0f) * _altitudeConversion)) % 256); data[11] = (byte) ((((int) Math.abs(intent.getFloatExtra("ASCENTRATE", 0.0f) * _altitudeConversion)) / 256) % 128); if (intent.getFloatExtra("ASCENTRATE", 0.0f) < 0) { data[11] += 128; } data[12] = (byte) (((int) Math.abs(intent.getFloatExtra("SLOPE", 0.0f))) % 128); if (intent.getFloatExtra("SLOPE", 0.0f) < 0) { data[12] += 128; } data[13] = (byte) (((int) Math.abs(intent.getDoubleExtra("XPOS", 0))) % 256); data[14] = (byte) ((((int) Math.abs(intent.getDoubleExtra("XPOS", 0))) / 256) % 128); if (intent.getDoubleExtra("XPOS", 0) < 0) { data[14] += 128; } data[15] = (byte) (((int) Math.abs(intent.getDoubleExtra("YPOS", 0))) % 256); data[16] = (byte) ((((int) Math.abs(intent.getDoubleExtra("YPOS", 0))) / 256) % 128); if (intent.getDoubleExtra("YPOS", 0) < 0) { data[16] += 128; } data[17] = (byte) (((int) (Math.floor(10 * intent.getFloatExtra("SPEED", 0.0f) * _speedConversion) / 1)) % 256); data[18] = (byte) (((int) (Math.floor(10 * intent.getFloatExtra("SPEED", 0.0f) * _speedConversion) / 1)) / 256); data[19] = (byte) (((int) (intent.getFloatExtra("BEARING", 0.0f) / 360 * 256)) % 256); dic.addBytes(Constants.ALTITUDE_DATA, data); for( int i = 0; i < data.length; i++ ) { sending += " data["+i+"]: " + ((256+data[i])%256); } } /*if (checkServiceRunning()) { dic.addInt32(Constants.STATE_CHANGED,Constants.STATE_START); } else { dic.addInt32(Constants.STATE_CHANGED,Constants.STATE_STOP); } sending += " STATE_CHANGED: " + dic.getInteger(Constants.STATE_CHANGED);*/ Log.d(TAG, sending); PebbleKit.sendDataToPebble(getApplicationContext(), Constants.WATCH_UUID, dic); } private void updateScreen(Intent intent) { HomeActivity homeScreen = getHomeScreen(); if (intent.hasExtra("SPEED")) { String speed = String.format(Locale.US, "%.1f", intent.getFloatExtra("SPEED", 99) * _speedConversion); homeScreen.setSpeed(speed); } if (intent.hasExtra("DISTANCE")) { String distance = String.format(Locale.US, "%.1f", Math.floor(10 * intent.getFloatExtra("DISTANCE", 99) * _distanceConversion) / 10); homeScreen.setDistance(distance); } if (intent.hasExtra("AVGSPEED")) { String avgSpeed = String.format(Locale.US, "%.1f", intent.getFloatExtra("AVGSPEED", 99) * _speedConversion); homeScreen.setAvgSpeed(avgSpeed); } if (intent.hasExtra("TIME")) { long time = intent.getLongExtra("TIME",0); //Log.d("PebbleBike",String.valueOf(TimeUnit.MILLISECONDS.toMinutes(time))); String dateFormatted = String.format("%d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(time), TimeUnit.MILLISECONDS.toMinutes(time) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(time)), TimeUnit.MILLISECONDS.toSeconds(time) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time))); homeScreen.setTime(dateFormatted); } if (intent.hasExtra("ALTITUDE")) { int altitude = (int)intent.getDoubleExtra("ALTITUDE", 0); AltitudeGraphReduce alt = AltitudeGraphReduce.getInstance(); alt.addAltitude(altitude); homeScreen.setAltitude( alt.getGraphData(), alt.getMax(), alt.getMin()); } } private void ResetSavedGPSStats() { GPSService.resetGPSStats(getSharedPreferences(Constants.PREFS_NAME, 0)); AltitudeGraphReduce.getInstance().restData(); // send the saved values directly to update pebble Intent intent = new Intent(); intent.putExtra("DISTANCE", 0); intent.putExtra("AVGSPEED", 0); intent.putExtra("ASCENT", 0); sendDataToPebble(intent); } private void setStartButtonText(String text) { HomeActivity activity = getHomeScreen(); if(activity != null) activity.setStartButtonText(text); } private HomeActivity getHomeScreen() { return (HomeActivity)(getSupportFragmentManager().findFragmentByTag("home")); } private void stopActivityRecogntionClient() { removeActivityRecognitionIntentReceiver(); if(_mActivityRecognitionClient == null) _mActivityRecognitionClient = new ActivityRecognitionClient(getApplicationContext(), this, this); _requestType = RequestType.STOP; _mActivityRecognitionClient.connect(); } private void initActivityRecognitionClient() { // Connect to the ActivityRecognitionService registerActivityRecognitionIntentReceiver(); _requestType = RequestType.START; _mActivityRecognitionClient = new ActivityRecognitionClient(getApplicationContext(), this, this); _mActivityRecognitionClient.connect(); } private void registerActivityRecognitionIntentReceiver() { IntentFilter filter = new IntentFilter(ActivityRecognitionReceiver.ACTION_RESP); filter.addCategory(Intent.CATEGORY_DEFAULT); _activityRecognitionReceiver = new ActivityRecognitionReceiver(); registerReceiver(_activityRecognitionReceiver, filter); } private void removeActivityRecognitionIntentReceiver() { if(_activityRecognitionReceiver != null) unregisterReceiver(_activityRecognitionReceiver); } private void startGPSService() { if (!checkServiceRunning()) { // only if GPS was not running on the phone Intent intent = new Intent(getApplicationContext(), GPSService.class); registerGPSServiceIntentReceiver(); startService(intent); PebbleKit.startAppOnPebble(getApplicationContext(), Constants.WATCH_UUID); } // in all cases resendLastDataToPebble(); } private void stopGPSService() { Log.d(TAG, "stopGPSService()"); if (checkServiceRunning()) { // only if GPS was running on the phone removeGPSServiceIntentReceiver(); stopService(new Intent(getApplicationContext(), GPSService.class)); } // in all cases sendServiceState(); } private void registerGPSServiceIntentReceiver() { IntentFilter filterResponse = new IntentFilter(GPSServiceReceiver.ACTION_RESP); filterResponse.addCategory(Intent.CATEGORY_DEFAULT); IntentFilter filterDisabled = new IntentFilter(GPSServiceReceiver.ACTION_GPS_DISABLED); filterDisabled.addCategory(Intent.CATEGORY_DEFAULT); _gpsServiceReceiver = new GPSServiceReceiver(); registerReceiver(_gpsServiceReceiver, filterResponse); registerReceiver(_gpsServiceReceiver, filterDisabled); } private void removeGPSServiceIntentReceiver() { if(_gpsServiceReceiver != null) unregisterReceiver(_gpsServiceReceiver); } private void checkGooglePlayServices() { // check to see that google play services are installed and up to date int googlePlayServicesAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); if(googlePlayServicesAvailable != ConnectionResult.SUCCESS) { // google play services need to be updated try { Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(googlePlayServicesAvailable, this, 123); if(errorDialog != null) errorDialog.show(); } catch (NoClassDefFoundError e) { Log.d(TAG, "NoClassDefFoundError " + e.getMessage()); Toast.makeText(this, "This device is not supported by Google Play Service.", Toast.LENGTH_LONG).show(); } catch (Exception e) { Log.e(TAG, "Exception " + e.getMessage()); } _googlePlayInstalled = false; } else { _googlePlayInstalled = true; } } public boolean checkServiceRunning() { ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (GPSService.class.getName().equals(service.service.getClassName())) { return true; } } return false; } private void showGPSDisabledAlertToUser(){ AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?") .setCancelable(false) .setPositiveButton("Goto Settings Page To Enable GPS", new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int id){ Intent callGPSSettingIntent = new Intent( android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(callGPSSettingIntent); } }); alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int id){ dialog.cancel(); } }); AlertDialog alert = alertDialogBuilder.create(); alert.show(); } private void updateActivityType(int type) { String activityType = ""; switch(type) { case DetectedActivity.ON_BICYCLE: activityType = "Bicycle"; break; case DetectedActivity.STILL: activityType = "Still"; break; case DetectedActivity.IN_VEHICLE: activityType = "In Vehicle"; break; case DetectedActivity.ON_FOOT: activityType = "On Foot"; break; } HomeActivity activity = getHomeScreen(); if(activity != null) activity.setActivityText(activityType); } @Override public void onConnected(Bundle connectionHint) { Log.d(TAG, "onConnected"); Intent intent = new Intent(getApplicationContext(), ActivityRecognitionIntentService.class); _callbackIntent = PendingIntent.getService(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); if(_requestType == RequestType.START) { Log.d(TAG, "Start Recognition"); _mActivityRecognitionClient.requestActivityUpdates(30000, _callbackIntent); } else if(_requestType == RequestType.STOP) { Log.d(TAG, "Stop Recognition"); _mActivityRecognitionClient.removeActivityUpdates(_callbackIntent); } else { Log.d(TAG, "other?"); } } @Override public void onDisconnected() { } @Override public void onConnectionFailed(ConnectionResult connectionResult) { //To change body of implemented methods use File | Settings | File Templates. } public class ActivityRecognitionReceiver extends BroadcastReceiver { public static final String ACTION_RESP = "com.njackson.intent.action.MESSAGE_PROCESSED"; @Override public void onReceive(Context context, Intent intent) { int activity = intent.getIntExtra("ACTIVITY_CHANGED", 0); updateActivityType(activity); if(activity == DetectedActivity.ON_BICYCLE) { Log.d(TAG, "AutoStart"); startGPSService(); _lastCycling = new Date(); } else { Log.d(TAG, "Waiting for stop"); // check to see if we have been inactive for 2 minutes Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cal.add(Calendar.MINUTE, -2); if(_lastCycling == null || _lastCycling.before(cal.getTime())) { Log.d(TAG, "AutoStop"); stopGPSService(); _lastCycling = null; } } } } public class GPSServiceReceiver extends BroadcastReceiver { public static final String ACTION_RESP = "com.njackson.intent.action.UPDATE_PEBBLE"; public static final String ACTION_GPS_DISABLED = "com.njackson.intent.action.GPS_DISABLED"; @Override public void onReceive(Context context, Intent intent) { if(intent.getAction().compareTo(ACTION_RESP) == 0) { sendDataToPebble(intent); updateScreen(intent); //updateMapLocation(intent); } else if(intent.getAction().compareTo(ACTION_GPS_DISABLED) == 0) { stopGPSService(); setStartButtonText("Start"); showGPSDisabledAlertToUser(); } } } private void updateMapLocation(Intent intent) { // do we need to update the map double lat = intent.getDoubleExtra("LAT",0); double lon = intent.getDoubleExtra("LON",0); MapActivity activity = (MapActivity)getSupportFragmentManager().findFragmentByTag("map"); if(activity != null) activity.setLocation(new LatLng(lat,lon)); } public static class TabListener<T extends SherlockFragment> implements ActionBar.TabListener { private final SherlockFragmentActivity mActivity; private final String mTag; private final Class<T> mClass; private final Bundle mArgs; private android.support.v4.app.Fragment mFragment; public TabListener(SherlockFragmentActivity activity, String tag, Class<T> clz) { this(activity, tag, clz, null); } public TabListener(SherlockFragmentActivity activity, String tag, Class<T> clz,android.support.v4.app.Fragment fragment, Bundle args) { this(activity, tag, clz, args); mFragment = fragment; } public TabListener(SherlockFragmentActivity activity, String tag, Class<T> clz, Bundle args) { mActivity = activity; mTag = tag; mClass = clz; mArgs = args; // Check to see if we already have a fragment for this tab, probably // from a previously saved state. If so, deactivate it, because our // initial state is that a tab isn't shown. mFragment = mActivity.getSupportFragmentManager().findFragmentByTag(mTag); if (mFragment != null && !mFragment.isDetached()) { FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction(); ft.detach(mFragment); ft.commit(); } } public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) { if (mFragment == null) { mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs); //mFragment.setArguments(mArgs); ft.add(android.R.id.content, mFragment, mTag); } else { ft.attach(mFragment); } } public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) { if (mFragment != null) { ft.detach(mFragment); } } public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) { //Do nothing } } }
src/com/njackson/MainActivity.java
package com.njackson; import android.app.ActivityManager; import android.app.AlertDialog; import android.app.Dialog; import android.app.PendingIntent; import android.content.*; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.ViewGroup; import android.widget.Toast; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.SherlockFragment; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.getpebble.android.kit.PebbleKit; import com.getpebble.android.kit.util.PebbleDictionary; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesClient; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.location.ActivityRecognitionClient; import com.google.android.gms.location.DetectedActivity; import com.google.android.gms.maps.model.LatLng; import com.njackson.util.AltitudeGraphReduce; import de.cketti.library.changelog.ChangeLog; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.concurrent.TimeUnit; public class MainActivity extends SherlockFragmentActivity implements GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener, HomeActivity.OnButtonPressListener { private static final String TAG = "PB-MainActivity"; private ActivityRecognitionClient _mActivityRecognitionClient; private static boolean _activityRecognition = false; public static boolean _liveTracking = false; private PendingIntent _callbackIntent; private RequestType _requestType; private static int _units = Constants.IMPERIAL; private static float _speedConversion = 0.0f; private static float _distanceConversion = 0.0f; private static float _altitudeConversion = 0.0f; private Date _lastCycling; private ActivityRecognitionReceiver _activityRecognitionReceiver; private GPSServiceReceiver _gpsServiceReceiver; private boolean _googlePlayInstalled; private Fragment _mapFragment; enum RequestType { START, STOP } static MainActivity instance; public static MainActivity getInstance() { return instance; } public Boolean activityRecognitionEnabled() { return _activityRecognition; } // Listener for the fragment button press @Override public void onPressed(int sender, boolean value) { //To change body of implemented methods use File | Settings | File Templates. switch(sender) { case R.id.MAIN_START_BUTTON: startButtonClick(value); break; } } public void loadPreferences() { loadPreferences(PreferenceManager.getDefaultSharedPreferences(getApplicationContext())); } public void loadPreferences(SharedPreferences prefs) { //setup the defaults _activityRecognition = prefs.getBoolean("ACTIVITY_RECOGNITION",false); _liveTracking = prefs.getBoolean("LIVE_TRACKING",false); if(_activityRecognition) initActivityRecognitionClient(); else stopActivityRecogntionClient(); HomeActivity activity = getHomeScreen(); if(activity != null) activity.setStartButtonVisibility(!_activityRecognition); try { setConversionUnits(Integer.valueOf(prefs.getString("UNITS_OF_MEASURE", "0"))); } catch (Exception e) { Log.e(TAG, "Exception:" + e); } } private void startButtonClick(boolean value) { if(value) { startGPSService(); } else { stopGPSService(); } } public void setConversionUnits(int units) { _units = units; if(units == Constants.IMPERIAL) { _speedConversion = (float)Constants.MS_TO_MPH; _distanceConversion = (float)Constants.M_TO_MILES; _altitudeConversion = (float)Constants.M_TO_FEET; } else { _speedConversion = (float)Constants.MS_TO_KPH; _distanceConversion = (float)Constants.M_TO_KM; _altitudeConversion = (float)Constants.M_TO_M; } // set the screen units HomeActivity homeScreen = getHomeScreen(); if(homeScreen != null) homeScreen.setUnits(units); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); instance = this; setContentView(R.layout.main); final ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(false); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); actionBar.setDisplayHomeAsUpEnabled(false); ChangeLog cl = new ChangeLog(this); if (cl.isFirstRun()) { cl.getLogDialog().show(); } checkGooglePlayServices(); loadPreferences(); Bundle bundle = new Bundle(); bundle.putBoolean("ACTIVITY_RECOGNITION",_activityRecognition); bundle.putBoolean("LIVE_TRACKING",_liveTracking); bundle.putInt("UNITS_OF_MEASURE",_units); //instantiate the map fragment and store for future use //_mapFragment = Fragment.instantiate(this, "map", bundle); actionBar.addTab(actionBar.newTab().setText(R.string.TAB_TITLE_HOME).setTabListener(new TabListener<HomeActivity>(this, "home", HomeActivity.class, bundle))); //actionBar.addTab(actionBar.newTab().setText(R.string.TAB_TITLE_MAP).setTabListener(new TabListener<MapActivity>(this,"map",MapActivity.class,_mapFragment,null))); if (getIntent().getExtras() != null) { if (getIntent().getExtras().containsKey("button")) { Log.d(TAG, "onCreate() button:" + getIntent().getExtras().getInt("button")); changeState(getIntent().getExtras().getInt("button")); } if (getIntent().getExtras().containsKey("version")) { Log.d(TAG, "onCreate() version:" + getIntent().getExtras().getInt("version")); resendLastDataToPebble(); } /*if (getIntent().getExtras().containsKey("live_max_name")) { Log.d(TAG, "onNewIntent() live_max_name:" + getIntent().getExtras().getInt("live_max_name")); GPSService.liveSendNames(getIntent().getExtras().getInt("live_max_name")); }*/ } } @Override public void onResume() { super.onResume(); } public boolean onKeyUp(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_MENU) { // Physical Menu button startActivity(new Intent(getApplicationContext(), SettingsActivity.class)); } return super.onKeyUp(keyCode, event); } // This is called for activities that set launchMode to "singleTop" in their package, or if a client used the FLAG_ACTIVITY_SINGLE_TOP flag when calling startActivity(Intent). // In either case, when the activity is re-launched while at the top of the activity stack instead of a new instance of the activity being started, onNewIntent() will be called // on the existing instance with the Intent that was used to re-launch it. // An activity will always be paused before receiving a new intent, so you can count on onResume() being called after this method. protected void onNewIntent (Intent intent) { if (intent.getExtras() != null) { if (intent.getExtras().containsKey("button")) { Log.d(TAG, "onNewIntent() button:" + intent.getExtras().getInt("button")); changeState(intent.getExtras().getInt("button")); } if (intent.getExtras().containsKey("version")) { Log.d(TAG, "onNewIntent() version:" + intent.getExtras().getInt("version")); resendLastDataToPebble(); } /*if (intent.getExtras().containsKey("live_max_name")) { Log.d(TAG, "onNewIntent() live_max_name:" + intent.getExtras().getInt("live_max_name")); GPSService.liveSendNames(intent.getExtras().getInt("live_max_name")); }*/ } } private void changeState(int button) { Log.d(TAG, "changeState(button:" + button + ")"); switch (button) { case Constants.STOP_PRESS: stopGPSService(); setStartButtonText("Start"); break; case Constants.PLAY_PRESS: startGPSService(); setStartButtonText("Stop"); break; case Constants.REFRESH_PRESS: ResetSavedGPSStats(); break; } } private void sendWatchFaceToPebble(){ try { Uri uri = Uri.parse("http://labs.jayps.fr/pebblebike/pebblebike-1.2.0.pbw?and"); Intent startupIntent = new Intent(); startupIntent.setAction(Intent.ACTION_VIEW); startupIntent.setType("application/octet-stream"); startupIntent.setData(uri); ComponentName distantActivity = new ComponentName("com.getpebble.android", "com.getpebble.android.ui.UpdateActivity"); startupIntent.setComponent(distantActivity); startActivity(startupIntent); }catch (ActivityNotFoundException ae) { Toast.makeText(getApplicationContext(),"Unable to install watchface, do you have the latest pebble app installed?",Toast.LENGTH_LONG).show(); } } private void sendServiceState() { Log.d(TAG, "sendServiceState()"); PebbleDictionary dic = new PebbleDictionary(); if(checkServiceRunning()) { dic.addInt32(Constants.STATE_CHANGED,Constants.STATE_START); } else { dic.addInt32(Constants.STATE_CHANGED,Constants.STATE_STOP); } Log.d(TAG, " STATE_CHANGED: " + dic.getInteger(Constants.STATE_CHANGED)); PebbleKit.sendDataToPebble(getApplicationContext(), Constants.WATCH_UUID, dic); } private Intent _lastIntent = null; private void resendLastDataToPebble() { sendDataToPebble(_lastIntent); } public void sendDataToPebble(Intent intent) { //Log.d(TAG, "sendDataToPebble()"); PebbleDictionary dic = new PebbleDictionary(); String sending = "Sending "; if (intent == null) { Log.d(TAG, "sendDataToPebble(intent == null)"); intent = new Intent(); SharedPreferences settings = getSharedPreferences(Constants.PREFS_NAME,0); float distance = settings.getFloat("GPS_DISTANCE", 0.0f); intent.putExtra("DISTANCE", distance); dic.addInt32(Constants.MSG_VERSION_ANDROID, Constants.VERSION_ANDROID); sending += " MSG_VERSION_ANDROID: " + dic.getInteger(Constants.MSG_VERSION_ANDROID); } if (intent != null) { _lastIntent = intent; byte[] data = new byte[20]; int version = 0; data[0] = (byte) ((_units % 2) * 1); if (checkServiceRunning()) { data[0] += (byte) (1 * 2); } else { data[0] += (byte) (0 * 2); } // 2 unused bits data[0] += (byte) (0 * 4); data[0] += (byte) (0 * 8); data[0] += (byte) ((version % 4) * 16); data[1] = (byte) ((int) Math.ceil(intent.getFloatExtra("ACCURACY", 0))); data[2] = (byte) (((int) (Math.floor(100 * intent.getFloatExtra("DISTANCE", 0) * _distanceConversion) / 1)) % 256); data[3] = (byte) (((int) (Math.floor(100 * intent.getFloatExtra("DISTANCE", 0) * _distanceConversion) / 1)) / 256); data[4] = (byte) (((int) intent.getLongExtra("TIME", 0) / 1000) % 256); data[5] = (byte) (((int) intent.getLongExtra("TIME", 0) / 1000) / 256); data[6] = (byte) (((int) (intent.getDoubleExtra("ALTITUDE", 0) * _altitudeConversion)) % 256); data[7] = (byte) (((int) (intent.getDoubleExtra("ALTITUDE", 0) * _altitudeConversion)) / 256); data[8] = (byte) (((int) Math.abs(intent.getDoubleExtra("ASCENT", 0) * _altitudeConversion)) % 256); data[9] = (byte) ((((int) Math.abs(intent.getDoubleExtra("ASCENT", 0) * _altitudeConversion)) / 256) % 128); if (intent.getDoubleExtra("ASCENT", 0) < 0) { data[9] += 128; } data[10] = (byte) (((int) Math.abs(intent.getFloatExtra("ASCENTRATE", 0) * _altitudeConversion)) % 256); data[11] = (byte) ((((int) Math.abs(intent.getFloatExtra("ASCENTRATE", 0) * _altitudeConversion)) / 256) % 128); if (intent.getFloatExtra("ASCENTRATE", 0) < 0) { data[11] += 128; } data[12] = (byte) (((int) Math.abs(intent.getFloatExtra("SLOPE", 0))) % 128); if (intent.getFloatExtra("SLOPE", 0) < 0) { data[12] += 128; } data[13] = (byte) (((int) Math.abs(intent.getDoubleExtra("XPOS", 0))) % 256); data[14] = (byte) ((((int) Math.abs(intent.getDoubleExtra("XPOS", 0))) / 256) % 128); if (intent.getDoubleExtra("XPOS", 0) < 0) { data[14] += 128; } data[15] = (byte) (((int) Math.abs(intent.getDoubleExtra("YPOS", 0))) % 256); data[16] = (byte) ((((int) Math.abs(intent.getDoubleExtra("YPOS", 0))) / 256) % 128); if (intent.getDoubleExtra("YPOS", 0) < 0) { data[16] += 128; } data[17] = (byte) (((int) (Math.floor(10 * intent.getFloatExtra("SPEED", 0) * _speedConversion) / 1)) % 256); data[18] = (byte) (((int) (Math.floor(10 * intent.getFloatExtra("SPEED", 0) * _speedConversion) / 1)) / 256); data[19] = (byte) (((int) (intent.getFloatExtra("BEARING", 0) / 360 * 256)) % 256); dic.addBytes(Constants.ALTITUDE_DATA, data); for( int i = 0; i < data.length; i++ ) { sending += " data["+i+"]: " + ((256+data[i])%256); } } /*if (checkServiceRunning()) { dic.addInt32(Constants.STATE_CHANGED,Constants.STATE_START); } else { dic.addInt32(Constants.STATE_CHANGED,Constants.STATE_STOP); } sending += " STATE_CHANGED: " + dic.getInteger(Constants.STATE_CHANGED);*/ Log.d(TAG, sending); PebbleKit.sendDataToPebble(getApplicationContext(), Constants.WATCH_UUID, dic); } private void updateScreen(Intent intent) { HomeActivity homeScreen = getHomeScreen(); if (intent.hasExtra("SPEED")) { String speed = String.format(Locale.US, "%.1f", intent.getFloatExtra("SPEED", 99) * _speedConversion); homeScreen.setSpeed(speed); } if (intent.hasExtra("DISTANCE")) { String distance = String.format(Locale.US, "%.1f", Math.floor(10 * intent.getFloatExtra("DISTANCE", 99) * _distanceConversion) / 10); homeScreen.setDistance(distance); } if (intent.hasExtra("AVGSPEED")) { String avgSpeed = String.format(Locale.US, "%.1f", intent.getFloatExtra("AVGSPEED", 99) * _speedConversion); homeScreen.setAvgSpeed(avgSpeed); } if (intent.hasExtra("TIME")) { long time = intent.getLongExtra("TIME",0); //Log.d("PebbleBike",String.valueOf(TimeUnit.MILLISECONDS.toMinutes(time))); String dateFormatted = String.format("%d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(time), TimeUnit.MILLISECONDS.toMinutes(time) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(time)), TimeUnit.MILLISECONDS.toSeconds(time) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time))); homeScreen.setTime(dateFormatted); } if (intent.hasExtra("ALTITUDE")) { int altitude = (int)intent.getDoubleExtra("ALTITUDE", 0); AltitudeGraphReduce alt = AltitudeGraphReduce.getInstance(); alt.addAltitude(altitude); homeScreen.setAltitude( alt.getGraphData(), alt.getMax(), alt.getMin()); } } private void ResetSavedGPSStats() { GPSService.resetGPSStats(getSharedPreferences(Constants.PREFS_NAME, 0)); AltitudeGraphReduce.getInstance().restData(); // send the saved values directly to update pebble Intent intent = new Intent(); intent.putExtra("DISTANCE", 0); intent.putExtra("AVGSPEED", 0); intent.putExtra("ASCENT", 0); sendDataToPebble(intent); } private void setStartButtonText(String text) { HomeActivity activity = getHomeScreen(); if(activity != null) activity.setStartButtonText(text); } private HomeActivity getHomeScreen() { return (HomeActivity)(getSupportFragmentManager().findFragmentByTag("home")); } private void stopActivityRecogntionClient() { removeActivityRecognitionIntentReceiver(); if(_mActivityRecognitionClient == null) _mActivityRecognitionClient = new ActivityRecognitionClient(getApplicationContext(), this, this); _requestType = RequestType.STOP; _mActivityRecognitionClient.connect(); } private void initActivityRecognitionClient() { // Connect to the ActivityRecognitionService registerActivityRecognitionIntentReceiver(); _requestType = RequestType.START; _mActivityRecognitionClient = new ActivityRecognitionClient(getApplicationContext(), this, this); _mActivityRecognitionClient.connect(); } private void registerActivityRecognitionIntentReceiver() { IntentFilter filter = new IntentFilter(ActivityRecognitionReceiver.ACTION_RESP); filter.addCategory(Intent.CATEGORY_DEFAULT); _activityRecognitionReceiver = new ActivityRecognitionReceiver(); registerReceiver(_activityRecognitionReceiver, filter); } private void removeActivityRecognitionIntentReceiver() { if(_activityRecognitionReceiver != null) unregisterReceiver(_activityRecognitionReceiver); } private void startGPSService() { if (!checkServiceRunning()) { // only if GPS was not running on the phone Intent intent = new Intent(getApplicationContext(), GPSService.class); registerGPSServiceIntentReceiver(); startService(intent); PebbleKit.startAppOnPebble(getApplicationContext(), Constants.WATCH_UUID); } // in all cases resendLastDataToPebble(); } private void stopGPSService() { Log.d(TAG, "stopGPSService()"); if (checkServiceRunning()) { // only if GPS was running on the phone removeGPSServiceIntentReceiver(); stopService(new Intent(getApplicationContext(), GPSService.class)); } // in all cases sendServiceState(); } private void registerGPSServiceIntentReceiver() { IntentFilter filterResponse = new IntentFilter(GPSServiceReceiver.ACTION_RESP); filterResponse.addCategory(Intent.CATEGORY_DEFAULT); IntentFilter filterDisabled = new IntentFilter(GPSServiceReceiver.ACTION_GPS_DISABLED); filterDisabled.addCategory(Intent.CATEGORY_DEFAULT); _gpsServiceReceiver = new GPSServiceReceiver(); registerReceiver(_gpsServiceReceiver, filterResponse); registerReceiver(_gpsServiceReceiver, filterDisabled); } private void removeGPSServiceIntentReceiver() { if(_gpsServiceReceiver != null) unregisterReceiver(_gpsServiceReceiver); } private void checkGooglePlayServices() { // check to see that google play services are installed and up to date int googlePlayServicesAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); if(googlePlayServicesAvailable != ConnectionResult.SUCCESS) { // google play services need to be updated try { Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(googlePlayServicesAvailable, this, 123); if(errorDialog != null) errorDialog.show(); } catch (NoClassDefFoundError e) { Log.d(TAG, "NoClassDefFoundError " + e.getMessage()); Toast.makeText(this, "This device is not supported by Google Play Service.", Toast.LENGTH_LONG).show(); } catch (Exception e) { Log.e(TAG, "Exception " + e.getMessage()); } _googlePlayInstalled = false; } else { _googlePlayInstalled = true; } } public boolean checkServiceRunning() { ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (GPSService.class.getName().equals(service.service.getClassName())) { return true; } } return false; } private void showGPSDisabledAlertToUser(){ AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?") .setCancelable(false) .setPositiveButton("Goto Settings Page To Enable GPS", new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int id){ Intent callGPSSettingIntent = new Intent( android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(callGPSSettingIntent); } }); alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int id){ dialog.cancel(); } }); AlertDialog alert = alertDialogBuilder.create(); alert.show(); } private void updateActivityType(int type) { String activityType = ""; switch(type) { case DetectedActivity.ON_BICYCLE: activityType = "Bicycle"; break; case DetectedActivity.STILL: activityType = "Still"; break; case DetectedActivity.IN_VEHICLE: activityType = "In Vehicle"; break; case DetectedActivity.ON_FOOT: activityType = "On Foot"; break; } HomeActivity activity = getHomeScreen(); if(activity != null) activity.setActivityText(activityType); } @Override public void onConnected(Bundle connectionHint) { Log.d(TAG, "onConnected"); Intent intent = new Intent(getApplicationContext(), ActivityRecognitionIntentService.class); _callbackIntent = PendingIntent.getService(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); if(_requestType == RequestType.START) { Log.d(TAG, "Start Recognition"); _mActivityRecognitionClient.requestActivityUpdates(30000, _callbackIntent); } else if(_requestType == RequestType.STOP) { Log.d(TAG, "Stop Recognition"); _mActivityRecognitionClient.removeActivityUpdates(_callbackIntent); } else { Log.d(TAG, "other?"); } } @Override public void onDisconnected() { } @Override public void onConnectionFailed(ConnectionResult connectionResult) { //To change body of implemented methods use File | Settings | File Templates. } public class ActivityRecognitionReceiver extends BroadcastReceiver { public static final String ACTION_RESP = "com.njackson.intent.action.MESSAGE_PROCESSED"; @Override public void onReceive(Context context, Intent intent) { int activity = intent.getIntExtra("ACTIVITY_CHANGED", 0); updateActivityType(activity); if(activity == DetectedActivity.ON_BICYCLE) { Log.d(TAG, "AutoStart"); startGPSService(); _lastCycling = new Date(); } else { Log.d(TAG, "Waiting for stop"); // check to see if we have been inactive for 2 minutes Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cal.add(Calendar.MINUTE, -2); if(_lastCycling == null || _lastCycling.before(cal.getTime())) { Log.d(TAG, "AutoStop"); stopGPSService(); _lastCycling = null; } } } } public class GPSServiceReceiver extends BroadcastReceiver { public static final String ACTION_RESP = "com.njackson.intent.action.UPDATE_PEBBLE"; public static final String ACTION_GPS_DISABLED = "com.njackson.intent.action.GPS_DISABLED"; @Override public void onReceive(Context context, Intent intent) { if(intent.getAction().compareTo(ACTION_RESP) == 0) { sendDataToPebble(intent); updateScreen(intent); //updateMapLocation(intent); } else if(intent.getAction().compareTo(ACTION_GPS_DISABLED) == 0) { stopGPSService(); setStartButtonText("Start"); showGPSDisabledAlertToUser(); } } } private void updateMapLocation(Intent intent) { // do we need to update the map double lat = intent.getDoubleExtra("LAT",0); double lon = intent.getDoubleExtra("LON",0); MapActivity activity = (MapActivity)getSupportFragmentManager().findFragmentByTag("map"); if(activity != null) activity.setLocation(new LatLng(lat,lon)); } public static class TabListener<T extends SherlockFragment> implements ActionBar.TabListener { private final SherlockFragmentActivity mActivity; private final String mTag; private final Class<T> mClass; private final Bundle mArgs; private android.support.v4.app.Fragment mFragment; public TabListener(SherlockFragmentActivity activity, String tag, Class<T> clz) { this(activity, tag, clz, null); } public TabListener(SherlockFragmentActivity activity, String tag, Class<T> clz,android.support.v4.app.Fragment fragment, Bundle args) { this(activity, tag, clz, args); mFragment = fragment; } public TabListener(SherlockFragmentActivity activity, String tag, Class<T> clz, Bundle args) { mActivity = activity; mTag = tag; mClass = clz; mArgs = args; // Check to see if we already have a fragment for this tab, probably // from a previously saved state. If so, deactivate it, because our // initial state is that a tab isn't shown. mFragment = mActivity.getSupportFragmentManager().findFragmentByTag(mTag); if (mFragment != null && !mFragment.isDetached()) { FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction(); ft.detach(mFragment); ft.commit(); } } public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) { if (mFragment == null) { mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs); //mFragment.setArguments(mArgs); ft.add(android.R.id.content, mFragment, mTag); } else { ft.attach(mFragment); } } public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) { if (mFragment != null) { ft.detach(mFragment); } } public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) { //Do nothing } } }
Correct types for initial values => avoid logs
src/com/njackson/MainActivity.java
Correct types for initial values
<ide><path>rc/com/njackson/MainActivity.java <ide> data[0] += (byte) (0 * 8); <ide> data[0] += (byte) ((version % 4) * 16); <ide> <del> data[1] = (byte) ((int) Math.ceil(intent.getFloatExtra("ACCURACY", 0))); <del> data[2] = (byte) (((int) (Math.floor(100 * intent.getFloatExtra("DISTANCE", 0) * _distanceConversion) / 1)) % 256); <del> data[3] = (byte) (((int) (Math.floor(100 * intent.getFloatExtra("DISTANCE", 0) * _distanceConversion) / 1)) / 256); <add> data[1] = (byte) ((int) Math.ceil(intent.getFloatExtra("ACCURACY", 0.0f))); <add> data[2] = (byte) (((int) (Math.floor(100 * intent.getFloatExtra("DISTANCE", 0.0f) * _distanceConversion) / 1)) % 256); <add> data[3] = (byte) (((int) (Math.floor(100 * intent.getFloatExtra("DISTANCE", 0.0f) * _distanceConversion) / 1)) / 256); <ide> data[4] = (byte) (((int) intent.getLongExtra("TIME", 0) / 1000) % 256); <ide> data[5] = (byte) (((int) intent.getLongExtra("TIME", 0) / 1000) / 256); <ide> <ide> <ide> data[8] = (byte) (((int) Math.abs(intent.getDoubleExtra("ASCENT", 0) * _altitudeConversion)) % 256); <ide> data[9] = (byte) ((((int) Math.abs(intent.getDoubleExtra("ASCENT", 0) * _altitudeConversion)) / 256) % 128); <del> if (intent.getDoubleExtra("ASCENT", 0) < 0) { <add> if (intent.getDoubleExtra("ASCENT", 0.0f) < 0) { <ide> data[9] += 128; <ide> } <del> data[10] = (byte) (((int) Math.abs(intent.getFloatExtra("ASCENTRATE", 0) * _altitudeConversion)) % 256); <del> data[11] = (byte) ((((int) Math.abs(intent.getFloatExtra("ASCENTRATE", 0) * _altitudeConversion)) / 256) % 128); <del> if (intent.getFloatExtra("ASCENTRATE", 0) < 0) { <add> data[10] = (byte) (((int) Math.abs(intent.getFloatExtra("ASCENTRATE", 0.0f) * _altitudeConversion)) % 256); <add> data[11] = (byte) ((((int) Math.abs(intent.getFloatExtra("ASCENTRATE", 0.0f) * _altitudeConversion)) / 256) % 128); <add> if (intent.getFloatExtra("ASCENTRATE", 0.0f) < 0) { <ide> data[11] += 128; <ide> } <del> data[12] = (byte) (((int) Math.abs(intent.getFloatExtra("SLOPE", 0))) % 128); <del> if (intent.getFloatExtra("SLOPE", 0) < 0) { <add> data[12] = (byte) (((int) Math.abs(intent.getFloatExtra("SLOPE", 0.0f))) % 128); <add> if (intent.getFloatExtra("SLOPE", 0.0f) < 0) { <ide> data[12] += 128; <ide> } <ide> <ide> data[16] += 128; <ide> } <ide> <del> data[17] = (byte) (((int) (Math.floor(10 * intent.getFloatExtra("SPEED", 0) * _speedConversion) / 1)) % 256); <del> data[18] = (byte) (((int) (Math.floor(10 * intent.getFloatExtra("SPEED", 0) * _speedConversion) / 1)) / 256); <del> data[19] = (byte) (((int) (intent.getFloatExtra("BEARING", 0) / 360 * 256)) % 256); <add> data[17] = (byte) (((int) (Math.floor(10 * intent.getFloatExtra("SPEED", 0.0f) * _speedConversion) / 1)) % 256); <add> data[18] = (byte) (((int) (Math.floor(10 * intent.getFloatExtra("SPEED", 0.0f) * _speedConversion) / 1)) / 256); <add> data[19] = (byte) (((int) (intent.getFloatExtra("BEARING", 0.0f) / 360 * 256)) % 256); <ide> <ide> dic.addBytes(Constants.ALTITUDE_DATA, data); <ide>
Java
apache-2.0
3443a0f844ed08fe0656de66375bd1f319ab181a
0
phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida
package ca.corefacility.bioinformatics.irida.web.controller; import ca.corefacility.bioinformatics.irida.exceptions.user.UserNotFoundException; import ca.corefacility.bioinformatics.irida.model.Project; import ca.corefacility.bioinformatics.irida.model.User; import ca.corefacility.bioinformatics.irida.model.enums.Order; import ca.corefacility.bioinformatics.irida.service.ProjectService; import ca.corefacility.bioinformatics.irida.service.UserService; import ca.corefacility.bioinformatics.irida.web.assembler.resource.project.ProjectCollectionResource; import ca.corefacility.bioinformatics.irida.web.assembler.resource.project.ProjectResource; import ca.corefacility.bioinformatics.irida.web.assembler.resource.user.UserResource; import ca.corefacility.bioinformatics.irida.web.assembler.resource.user.UserCollectionResource; import ca.corefacility.bioinformatics.irida.web.controller.links.PageableControllerLinkBuilder; import com.google.gson.Gson; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletResponse; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.hateoas.mvc.ControllerLinkBuilder; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static ca.corefacility.bioinformatics.irida.web.controller.links.PageableControllerLinkBuilder.pageLinksFor; import java.util.Collection; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; /** * Controller for managing users. * * @author Josh Adam <[email protected]> * @author Franklin Bristow <[email protected]> * @author Thomas Matthews <[email protected]> */ @Controller @RequestMapping(value = "/users") public class UsersController { private static final Logger logger = LoggerFactory.getLogger(UsersController.class); private final UserService userService; private final ProjectService projectService; private static final String USER_PROJECTS_REL = "user/projects"; @Autowired public UsersController(UserService userService, ProjectService projectService) { this.userService = userService; this.projectService = projectService; } @RequestMapping(method = RequestMethod.GET) public String showUsersPage(Model model, @RequestParam(value = PageableControllerLinkBuilder.REQUEST_PARAM_PAGE, defaultValue = "1") int page, @RequestParam(value = PageableControllerLinkBuilder.REQUEST_PARAM_SIZE, defaultValue = "20") int size, @RequestParam(value = PageableControllerLinkBuilder.REQUEST_PARAM_SORT_COLUMN, defaultValue = "username") String sortColumn, @RequestParam(value = PageableControllerLinkBuilder.REQUEST_PARAM_SORT_ORDER, defaultValue = "ASCENDING") Order sortOrder) { List<User> users = userService.list(page, size, sortColumn, sortOrder); ControllerLinkBuilder linkBuilder = linkTo(UsersController.class); int totalUsers = userService.count(); UserCollectionResource resources = new UserCollectionResource(); for (User u : users) { UserResource resource = new UserResource(u); resource.add(linkBuilder.slash(resource.getUsername()).withSelfRel()); resources.add(resource); } resources.add(pageLinksFor(UsersController.class, page, size, totalUsers, sortColumn, sortOrder)); resources.setTotalUsers(totalUsers); model.addAttribute("userResources", resources); model.addAttribute("users", true); model.addAttribute("pageTitle", "Users"); return "users/index"; } @RequestMapping(method = RequestMethod.POST) public @ResponseBody String create(HttpServletResponse response, @RequestParam(value = "username", required = false) String username, @RequestParam(value = "firstName", required = false) String firstName, @RequestParam(value = "lastName", required = false) String lastName, @RequestParam(value = "email", required = false) String email, @RequestParam(value = "phoneNumber", required = false) String phoneNumber, @RequestParam(value = "password", required = false) String password) { User user = new User(username, email, password, firstName, lastName, phoneNumber); try { userService.create(user); } catch (ConstraintViolationException e) { Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations(); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return validationMessages(constraintViolations); } response.setStatus(HttpServletResponse.SC_CREATED); return "success"; } @RequestMapping(value = "/{username}", method = RequestMethod.GET) public String getUser(HttpServletResponse response, @PathVariable String username, Model model) { try { UserResource u = new UserResource(userService.getUserByUsername(username)); u.add(linkTo(UsersController.class).slash(username).slash("projects").withRel(USER_PROJECTS_REL)); u.add(linkTo(UsersController.class).slash(username).withSelfRel()); model.addAttribute("user", u); } catch (UserNotFoundException e) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return "exceptions/404"; } return "users/user"; } @RequestMapping(value = "/{username}/projects", method = RequestMethod.GET) public String getUserProjects(HttpServletResponse response, @PathVariable String username, Model model) { try { User u = userService.getUserByUsername(username); ProjectCollectionResource resources = new ProjectCollectionResource(); Collection<Project> projects = projectService.getProjectsForUser(u); ControllerLinkBuilder linkBuilder = linkTo(ProjectsController.class); for (Project project : projects) { ProjectResource resource = new ProjectResource(project); resource.add(linkBuilder.slash(project.getIdentifier().getUUID()).withSelfRel()); resources.add(resource); } model.addAttribute("projectResources", resources); } catch (UserNotFoundException e) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return "exceptions/404"; } return "users/user"; } private String validationMessages(Set<ConstraintViolation<?>> failures) { Map<String, List<String>> mp = new HashMap(); for (ConstraintViolation<?> failure : failures) { logger.debug(failure.getPropertyPath().toString() + ": " + failure.getMessage()); String property = failure.getPropertyPath().toString(); if (mp.containsKey(property)) { mp.get(failure.getPropertyPath().toString()).add(failure.getMessage()); } else { List<String> list = new ArrayList<>(); list.add(failure.getMessage()); mp.put(property, list); } } Gson g = new Gson(); return g.toJson(mp); } }
src/main/java/ca/corefacility/bioinformatics/irida/web/controller/UsersController.java
package ca.corefacility.bioinformatics.irida.web.controller; import ca.corefacility.bioinformatics.irida.exceptions.user.UserNotFoundException; import ca.corefacility.bioinformatics.irida.model.Project; import ca.corefacility.bioinformatics.irida.model.User; import ca.corefacility.bioinformatics.irida.model.enums.Order; import ca.corefacility.bioinformatics.irida.service.ProjectService; import ca.corefacility.bioinformatics.irida.service.UserService; import ca.corefacility.bioinformatics.irida.web.assembler.resource.project.ProjectCollectionResource; import ca.corefacility.bioinformatics.irida.web.assembler.resource.project.ProjectResource; import ca.corefacility.bioinformatics.irida.web.assembler.resource.user.UserResource; import ca.corefacility.bioinformatics.irida.web.assembler.resource.user.UserCollectionResource; import ca.corefacility.bioinformatics.irida.web.controller.links.PageableControllerLinkBuilder; import com.google.gson.Gson; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletResponse; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.hateoas.mvc.ControllerLinkBuilder; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static ca.corefacility.bioinformatics.irida.web.controller.links.PageableControllerLinkBuilder.pageLinksFor; import java.util.Collection; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; /** * Controller for managing users. * * @author Josh Adam <[email protected]> * @author Franklin Bristow <[email protected]> * @author Thomas Matthews <[email protected]> */ @Controller @RequestMapping(value = "/users") public class UsersController { private static final Logger logger = LoggerFactory.getLogger(UsersController.class); private final UserService userService; private final ProjectService projectService; private static final String USER_PROJECTS_REL = "user/projects"; @Autowired public UsersController(UserService userService, ProjectService projectService) { this.userService = userService; this.projectService = projectService; } @RequestMapping(method = RequestMethod.GET) public String showUsersPage(Model model, @RequestParam(value = PageableControllerLinkBuilder.REQUEST_PARAM_PAGE, defaultValue = "1") int page, @RequestParam(value = PageableControllerLinkBuilder.REQUEST_PARAM_SIZE, defaultValue = "20") int size, @RequestParam(value = PageableControllerLinkBuilder.REQUEST_PARAM_SORT_COLUMN, defaultValue = "username") String sortColumn, @RequestParam(value = PageableControllerLinkBuilder.REQUEST_PARAM_SORT_ORDER, defaultValue = "ASCENDING") Order sortOrder) { List<User> users = userService.list(page, size, sortColumn, sortOrder); ControllerLinkBuilder linkBuilder = linkTo(UsersController.class); int totalUsers = userService.count(); UserCollectionResource resources = new UserCollectionResource(); for (User u : users) { UserResource resource = new UserResource(u); resource.add(linkBuilder.slash(resource.getUsername()).withSelfRel()); resources.add(resource); } resources.add(pageLinksFor(UsersController.class, page, size, totalUsers, sortColumn, sortOrder)); resources.setTotalUsers(totalUsers); model.addAttribute("userResources", resources); model.addAttribute("users", true); model.addAttribute("pageTitle", "Users"); return "users/index"; } @RequestMapping(method = RequestMethod.POST) public @ResponseBody String create(HttpServletResponse response, @RequestParam(value = "username", required = false) String username, @RequestParam(value = "firstName", required = false) String firstName, @RequestParam(value = "lastName", required = false) String lastName, @RequestParam(value = "email", required = false) String email, @RequestParam(value = "phoneNumber", required = false) String phoneNumber, @RequestParam(value = "password", required = false) String password) { User user = new User(username, email, password, firstName, lastName, phoneNumber); try { userService.create(user); } catch (ConstraintViolationException e) { Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations(); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return validationMessages(constraintViolations); } response.setStatus(HttpServletResponse.SC_CREATED); return "success"; } @RequestMapping(value = "/{username}", method = RequestMethod.GET) public String getUser(HttpServletResponse response, @PathVariable String username, Model model) { try { UserResource u = new UserResource(userService.getUserByUsername(username)); u.add(linkTo(UsersController.class).slash(username).slash("projects").withRel(USER_PROJECTS_REL)); u.add(linkTo(UsersController.class).slash(username).withSelfRel()); model.addAttribute("user", u); } catch (UserNotFoundException e) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return "exceptions/404"; } return "users/user"; } @RequestMapping(value = "/{username}/projects", method = RequestMethod.GET) public String getUserProjects(HttpServletResponse response, @PathVariable String username, Model model) { try { User u = userService.getUserByUsername(username); ProjectCollectionResource resources = new ProjectCollectionResource(); Collection<Project> projects = projectService.getProjectsForUser(u); ControllerLinkBuilder linkBuilder = linkTo(UsersController.class); for (Project project : projects) { ProjectResource resource = new ProjectResource(project); resource.add(linkBuilder.slash("project").slash(project.getIdentifier().getUUID()).withSelfRel()); resources.add(resource); } model.addAttribute("projectResources", resources); } catch (UserNotFoundException e) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return "exceptions/404"; } return "users/user"; } private String validationMessages(Set<ConstraintViolation<?>> failures) { Map<String, List<String>> mp = new HashMap(); for (ConstraintViolation<?> failure : failures) { logger.debug(failure.getPropertyPath().toString() + ": " + failure.getMessage()); String property = failure.getPropertyPath().toString(); if (mp.containsKey(property)) { mp.get(failure.getPropertyPath().toString()).add(failure.getMessage()); } else { List<String> list = new ArrayList<>(); list.add(failure.getMessage()); mp.put(property, list); } } Gson g = new Gson(); return g.toJson(mp); } }
Link to the project controller for project links instead of to the user controller.
src/main/java/ca/corefacility/bioinformatics/irida/web/controller/UsersController.java
Link to the project controller for project links instead of to the user controller.
<ide><path>rc/main/java/ca/corefacility/bioinformatics/irida/web/controller/UsersController.java <ide> User u = userService.getUserByUsername(username); <ide> ProjectCollectionResource resources = new ProjectCollectionResource(); <ide> Collection<Project> projects = projectService.getProjectsForUser(u); <del> ControllerLinkBuilder linkBuilder = linkTo(UsersController.class); <add> ControllerLinkBuilder linkBuilder = linkTo(ProjectsController.class); <ide> for (Project project : projects) { <ide> ProjectResource resource = new ProjectResource(project); <del> resource.add(linkBuilder.slash("project").slash(project.getIdentifier().getUUID()).withSelfRel()); <add> resource.add(linkBuilder.slash(project.getIdentifier().getUUID()).withSelfRel()); <ide> resources.add(resource); <ide> } <ide>
Java
lgpl-2.1
ee3a0d79b1618c1c5b9a7aef6e8ce621fc50e58d
0
skyvers/wildcat,skyvers/wildcat,skyvers/skyve,skyvers/skyve,skyvers/wildcat,skyvers/skyve,skyvers/skyve,skyvers/skyve,skyvers/skyve,skyvers/skyve,skyvers/wildcat,skyvers/wildcat
package org.skyve.impl.backup; import java.io.File; import java.io.FileReader; import java.math.BigDecimal; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.Time; import java.sql.Timestamp; import java.sql.Types; import java.util.Collection; import java.util.Map; import org.skyve.CORE; import org.skyve.EXT; import org.skyve.content.AttachmentContent; import org.skyve.content.ContentManager; import org.skyve.domain.Bean; import org.skyve.domain.messages.DomainException; import org.skyve.domain.messages.MessageSeverity; import org.skyve.impl.backup.RestoreOptions.ContentOption; import org.skyve.impl.backup.RestoreOptions.IndexingOption; import org.skyve.impl.backup.RestoreOptions.PreProcess; import org.skyve.impl.content.AbstractContentManager; import org.skyve.impl.content.elastic.ElasticContentManager; import org.skyve.impl.metadata.model.document.field.Field.IndexType; import org.skyve.impl.persistence.hibernate.AbstractHibernatePersistence; import org.skyve.impl.persistence.hibernate.dialect.SkyveDialect; import org.skyve.impl.util.UtilImpl; import org.skyve.job.CancellableJob; import org.skyve.metadata.model.Attribute.AttributeType; import org.skyve.util.FileUtil; import org.skyve.util.PushMessage; import org.skyve.util.Util; import org.supercsv.io.CsvMapReader; import org.supercsv.prefs.CsvPreference; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.io.WKTReader; public class RestoreJob extends CancellableJob { private static final long serialVersionUID = -4076693395300706664L; @Override public void execute() throws Exception { Bean bean = getBean(); if (! (bean instanceof RestoreOptions)) { getLog().add("Kick off the job with the appropriate options from the Data Maintenance page."); return; } restore((RestoreOptions) bean); } private void restore(RestoreOptions options) throws Exception { String customerName = CORE.getUser().getCustomerName(); Collection<String> log = getLog(); String trace; String selectedBackupName = options.getSelectedBackupName(); File backup = new File(String.format("%sbackup_%s%s%s", Util.getContentDirectory(), customerName, File.separator, selectedBackupName)); if (! backup.exists()) { trace = "Backup " + backup.getAbsolutePath() + " does not exist."; log.add(trace); Util.LOGGER.warning(trace); return; } EXT.push(new PushMessage().growl(MessageSeverity.info, "System Restore in progress - system unavailable until restore is complete.")); String extractDirName = selectedBackupName.substring(0, selectedBackupName.length() - 4); File extractDir = new File(backup.getParentFile(), extractDirName); trace = String.format("Extract %s to %s", backup.getAbsolutePath(), extractDir.getAbsolutePath()); log.add(trace); Util.LOGGER.info(trace); if (extractDir.exists()) { trace = String.format(" %s already exists - delete it.", extractDir.getAbsolutePath()); log.add(trace); Util.LOGGER.info(trace); FileUtil.delete(extractDir); trace = String.format(" %s deleted.", extractDir.getAbsolutePath()); log.add(trace); Util.LOGGER.info(trace); } FileUtil.extractZipArchive(backup, extractDir); trace = String.format("Extracted %s to %s", backup.getAbsolutePath(), extractDir.getAbsolutePath()); log.add(trace); Util.LOGGER.info(trace); setPercentComplete(50); PreProcess restorePreProcess = options.getPreProcess(); ContentOption contrentRestoreOption = options.getContentOption(); boolean truncateDatabase = PreProcess.deleteData.equals(restorePreProcess); if (truncateDatabase) { trace = "Truncate " + ((UtilImpl.SCHEMA == null) ? "default" : UtilImpl.SCHEMA) + " schema"; log.add(trace); Util.LOGGER.info(trace); } Truncate.truncate(UtilImpl.SCHEMA, truncateDatabase, true); boolean createUsingBackup = false; boolean ddlSync = false; if (PreProcess.createUsingBackup.equals(restorePreProcess)) { createUsingBackup = true; DDL.create(new File(extractDir, "create.sql"), true); ddlSync = true; } else if (PreProcess.createUsingMetadata.equals(restorePreProcess)) { DDL.create(null, true); ddlSync = true; } else if (PreProcess.dropUsingBackupAndCreateUsingBackup.equals(restorePreProcess)) { createUsingBackup = true; DDL.drop(new File(extractDir, "drop.sql"), true); DDL.create(new File(extractDir, "create.sql"), true); ddlSync = true; } else if (PreProcess.dropUsingBackupAndCreateUsingMetadata.equals(restorePreProcess)) { DDL.drop(new File(extractDir, "drop.sql"), true); DDL.create(null, true); ddlSync = true; } else if (PreProcess.dropUsingMetadataAndCreateUsingBackup.equals(restorePreProcess)) { createUsingBackup = true; DDL.drop(null, true); DDL.create(new File(extractDir, "create.sql"), true); ddlSync = true; } else if (PreProcess.dropUsingMetadataAndCreateUsingMetadata.equals(restorePreProcess)) { DDL.drop(null, true); DDL.create(null, true); ddlSync = true; } trace = "Restore " + extractDirName; log.add(trace); Util.LOGGER.info(trace); IndexingOption indexingOption = options.getIndexingOption(); restore(extractDirName, createUsingBackup, contrentRestoreOption, indexingOption); if (ddlSync) { trace = "DDL Sync"; log.add(trace); Util.LOGGER.info(trace); DDL.sync(true); } if (IndexingOption.both.equals(indexingOption) || IndexingOption.data.equals(indexingOption)) { trace = "Reindex textual indexes."; log.add(trace); Util.LOGGER.info(trace); execute(new ReindexBeansJob()); } trace = "Delete extracted folder " + extractDir.getAbsolutePath(); log.add(trace); Util.LOGGER.info(trace); FileUtil.delete(extractDir); trace = "DONE"; log.add(trace); Util.LOGGER.info(trace); setPercentComplete(100); EXT.push(new PushMessage().growl(MessageSeverity.info, "System Restore complete.")); } private void restore(String extractDirName, boolean createUsingBackup, ContentOption contentRestoreOption, IndexingOption indexingOption) throws Exception { String customerName = CORE.getUser().getCustomerName(); String backupDirectoryPath = UtilImpl.CONTENT_DIRECTORY + "backup_" + customerName + File.separator + extractDirName; File backupDirectory = new File(backupDirectoryPath); if ((! backupDirectory.exists()) || (! backupDirectory.isDirectory())) { throw new IllegalArgumentException(backupDirectoryPath + " is not a directory"); } Collection<Table> tables = createUsingBackup ? BackupUtil.readTables(new File(backupDirectory, "tables.txt")) : BackupUtil.getTables(); try (Connection connection = EXT.getDataStoreConnection()) { connection.setAutoCommit(false); // restore normal tables restoreData(backupDirectory, tables, connection, false, false, contentRestoreOption, indexingOption); setPercentComplete(25); // restore extension join tables restoreData(backupDirectory, tables, connection, false, true, contentRestoreOption, indexingOption); setPercentComplete(50); // link foreign keys restoreForeignKeys(backupDirectory, tables, connection); setPercentComplete(75); // restore collection join tables restoreData(backupDirectory, tables, connection, true, false, contentRestoreOption, indexingOption); setPercentComplete(100); } } // update bizKeys // check and remove content not present // validate by updating bizLock and rolling back // check commit points private void restoreData(File backupDirectory, Collection<Table> tables, Connection connection, boolean joinTables, boolean extensionTables, ContentOption contentRestoreOption, IndexingOption indexingOption) throws Exception { try (ContentManager cm = EXT.newContentManager()) { for (Table table : tables) { if (table instanceof JoinTable) { if (! joinTables) { continue; } } else { if (joinTables) { continue; } if (BackupUtil.hasBizCustomer(table)) { if (extensionTables) { continue; } } else { if (! extensionTables) { continue; } } } Collection<String> log = getLog(); String trace = " restore table " + table.name; log.add(trace); UtilImpl.LOGGER.info(trace); File backupFile = new File(backupDirectory.getAbsolutePath() + File.separator + table.name + ".csv"); if (! backupFile.exists()) { trace = " ***** File " + backupFile.getAbsolutePath() + File.separator + table.name + ".csv does not exist"; log.add(trace); System.err.println(trace); continue; } long rowCount = 0; try (FileReader fr = new FileReader(backupFile)) { try (CsvMapReader reader = new CsvMapReader(fr, CsvPreference.STANDARD_PREFERENCE)) { String[] headers = reader.getHeader(true); StringBuilder sql = new StringBuilder(128); sql.append("insert into ").append(table.name).append(" ("); for (String header : headers) { if (joinTables) { sql.append(header).append(','); } else { if (! header.endsWith("_id")) { sql.append(header).append(','); } } } sql.setLength(sql.length() - 1); // remove the last comma sql.append(") values ("); for (String header : headers) { if (joinTables) { sql.append("?,"); } else { if (! header.endsWith("_id")) { sql.append("?,"); } } } sql.setLength(sql.length() - 1); // remove the last comma sql.append(')'); Map<String, String> values = null; try (PreparedStatement statement = connection.prepareStatement(sql.toString())) { while ((values = reader.read(headers)) != null) { if (isCancelled()) { return; } statement.clearParameters(); int index = 1; for (String header : headers) { if ((! joinTables) && header.endsWith("_id")) { continue; } String stringValue = values.get(header); if ((stringValue == null) || (stringValue.length() == 0)) { statement.setObject(index++, null); continue; } AttributeType attributeType = table.fields.get(header); // replace any 2 CR or LF combinations in the string with 1 // Super CSV place 2 ox0A into the string when it comes across a '\n' // in a quoted string field value. stringValue = stringValue.replaceAll("[\\n\\r]{2}", "\n"); // foreign keys if (header.endsWith("_id")) { statement.setString(index++, stringValue); } else if (AttributeType.colour.equals(attributeType) || AttributeType.memo.equals(attributeType) || AttributeType.markup.equals(attributeType) || AttributeType.text.equals(attributeType) || AttributeType.enumeration.equals(attributeType) || AttributeType.id.equals(attributeType)) { statement.setString(index++, stringValue); } else if (AttributeType.geometry.equals(attributeType)) { Geometry geometry = new WKTReader().read(stringValue); SkyveDialect dialect = AbstractHibernatePersistence.getDialect(); int geometrySqlType = dialect.getGeometrySqlType(); if (geometrySqlType == Types.ARRAY) { statement.setBytes(index++, (byte[]) dialect.convertToPersistedValue(geometry)); } else { statement.setObject(index++, dialect.convertToPersistedValue(geometry), geometrySqlType); } } else if (AttributeType.bool.equals(attributeType)) { statement.setBoolean(index++, Boolean.parseBoolean(stringValue)); } else if (AttributeType.date.equals(attributeType)) { statement.setDate(index++, new Date(Long.parseLong(stringValue)), BackupUtil.GMT); } else if (AttributeType.time.equals(attributeType)) { statement.setTime(index++, new Time(Long.parseLong(stringValue)), BackupUtil.GMT); } else if (AttributeType.dateTime.equals(attributeType) || AttributeType.timestamp.equals(attributeType)) { statement.setTimestamp(index++, new Timestamp(Long.parseLong(stringValue)), BackupUtil.GMT); } else if (AttributeType.decimal2.equals(attributeType) || AttributeType.decimal5.equals(attributeType) || AttributeType.decimal10.equals(attributeType)) { statement.setBigDecimal(index++, new BigDecimal(stringValue)); } else if (AttributeType.integer.equals(attributeType)) { statement.setInt(index++, Integer.parseInt(stringValue)); } else if (AttributeType.longInteger.equals(attributeType)) { statement.setLong(index++, Long.parseLong(stringValue)); } else if (AttributeType.content.equals(attributeType)) { StringBuilder contentPath = new StringBuilder(128); contentPath.append(backupDirectory.getAbsolutePath()).append('/'); contentPath.append(AbstractContentManager.FILE_STORE_NAME).append('/'); AttachmentContent content = ElasticContentManager.getFromFileSystem(contentPath, stringValue); if (content == null) { trace = " Could not find file associated with " + stringValue; if (ContentOption.error.equals(contentRestoreOption)) { log.add(trace); Util.LOGGER.severe(trace); throw new DomainException(trace); } else if (ContentOption.clearOrphanedContentIds.equals(contentRestoreOption)) { trace += " : Setting content to null"; log.add(trace); Util.LOGGER.info(trace); statement.setString(index++, null); } else { trace += " : Setting content ID regardless"; log.add(trace); Util.LOGGER.info(trace); statement.setString(index++, stringValue); } } else { IndexType indexType = table.indexes.get(header); boolean textIndex = (indexType == null) || IndexType.textual.equals(indexType) || IndexType.both.equals(indexType); if (textIndex) { textIndex = IndexingOption.both.equals(indexingOption) || IndexingOption.content.equals(indexingOption); } cm.put(content, textIndex); statement.setString(index++, content.getContentId()); } } else { throw new IllegalStateException("No value set for " + header); } } // for (each header) statement.executeUpdate(); rowCount++; } // while (each CSV line) connection.commit(); } catch (Throwable t) { trace = t.getLocalizedMessage(); log.add(trace); Util.LOGGER.severe(trace); trace = "AT LINE " + rowCount + " OF " + backupFile.getAbsolutePath(); log.add(trace); Util.LOGGER.severe(trace); trace = "CAUSED BY:- " + sql.toString(); log.add(trace); Util.LOGGER.severe(trace); StringBuilder sb = new StringBuilder(512); sb.append("VALUES :- "); if (values == null) { sb.append("NONE"); } else { for (String header : values.keySet()) { sb.append(header).append('=').append(values.get(header)).append(','); } sb.setLength(sb.length() - 1); // remove last comma } trace = sb.toString(); log.add(trace); Util.LOGGER.severe(trace); throw t; } } } trace = " restored table " + table.name + " with " + rowCount + " rows."; log.add(trace); UtilImpl.LOGGER.info(trace); } // for (each table) } } private void restoreForeignKeys(File backupDirectory, Collection<Table> tables, Connection connection) throws Exception { Collection<String> log = getLog(); String trace; for (Table table : tables) { if (table instanceof JoinTable) { continue; } trace = " restore foreign keys for table " + table.name; log.add(trace); Util.LOGGER.info(trace); File backupFile = new File(backupDirectory.getAbsolutePath() + File.separator + table.name + ".csv"); if (! backupFile.exists()) { trace = " ***** File " + backupFile.getAbsolutePath() + File.separator + " does not exist"; log.add(trace); System.err.println(trace); continue; } long rowCount = 0; try (FileReader fr = new FileReader(backupFile)) { try (CsvMapReader reader = new CsvMapReader(fr, CsvPreference.STANDARD_PREFERENCE)) { String[] headers = reader.getHeader(true); StringBuilder sql = new StringBuilder(128); sql.append("update ").append(table.name); boolean foundAForeignKey = false; for (String header : headers) { if (header.endsWith("_id")) { if (! foundAForeignKey) { sql.append(" set "); } else { sql.append(", "); } sql.append(header).append(" = ?"); foundAForeignKey = true; } } if (foundAForeignKey) { sql.append(" where bizId = ?"); try (PreparedStatement statement = connection.prepareStatement(sql.toString())) { Map<String, String> values = null; while ((values = reader.read(headers)) != null) { if (isCancelled()) { return; } statement.clearParameters(); int i = 1; for (String header : headers) { if (header.endsWith("_id")) { final String stringValue = values.get(header); if ((stringValue == null) || (stringValue.length() == 0)) { statement.setObject(i, null); i++; } else { statement.setString(i, stringValue); i++; } } } // for (each header) // set the ID for the where clause statement.setString(i, values.get(Bean.DOCUMENT_ID)); statement.executeUpdate(); rowCount++; } // while (each CSV line) connection.commit(); } } } } trace = " restored foreign keys for table " + table.name + " with " + rowCount + " rows."; log.add(trace); UtilImpl.LOGGER.info(trace); } // for (each table) } }
skyve-ext/src/main/java/org/skyve/impl/backup/RestoreJob.java
package org.skyve.impl.backup; import java.io.File; import java.io.FileReader; import java.math.BigDecimal; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.Time; import java.sql.Timestamp; import java.sql.Types; import java.util.Collection; import java.util.Map; import org.skyve.CORE; import org.skyve.EXT; import org.skyve.content.AttachmentContent; import org.skyve.content.ContentManager; import org.skyve.domain.Bean; import org.skyve.domain.messages.DomainException; import org.skyve.domain.messages.MessageSeverity; import org.skyve.impl.backup.RestoreOptions.ContentOption; import org.skyve.impl.backup.RestoreOptions.IndexingOption; import org.skyve.impl.backup.RestoreOptions.PreProcess; import org.skyve.impl.content.AbstractContentManager; import org.skyve.impl.content.elastic.ElasticContentManager; import org.skyve.impl.metadata.model.document.field.Field.IndexType; import org.skyve.impl.persistence.hibernate.AbstractHibernatePersistence; import org.skyve.impl.persistence.hibernate.dialect.SkyveDialect; import org.skyve.impl.util.UtilImpl; import org.skyve.job.CancellableJob; import org.skyve.metadata.model.Attribute.AttributeType; import org.skyve.util.FileUtil; import org.skyve.util.PushMessage; import org.skyve.util.Util; import org.supercsv.io.CsvMapReader; import org.supercsv.prefs.CsvPreference; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.io.WKTReader; public class RestoreJob extends CancellableJob { private static final long serialVersionUID = -4076693395300706664L; @Override public void execute() throws Exception { Bean bean = getBean(); if (! (bean instanceof RestoreOptions)) { getLog().add("Kick off the job with the appropriate options from the Data Maintenance page."); return; } restore((RestoreOptions) bean); } private void restore(RestoreOptions options) throws Exception { String customerName = CORE.getUser().getCustomerName(); Collection<String> log = getLog(); String trace; String selectedBackupName = options.getSelectedBackupName(); File backup = new File(String.format("%sbackup_%s%s%s", Util.getContentDirectory(), customerName, File.separator, selectedBackupName)); if (! backup.exists()) { trace = "Backup " + backup.getAbsolutePath() + " does not exist."; log.add(trace); Util.LOGGER.warning(trace); return; } String extractDirName = selectedBackupName.substring(0, selectedBackupName.length() - 4); File extractDir = new File(backup.getParentFile(), extractDirName); trace = String.format("Extract %s to %s", backup.getAbsolutePath(), extractDir.getAbsolutePath()); log.add(trace); Util.LOGGER.info(trace); if (extractDir.exists()) { trace = String.format(" %s already exists - delete it.", extractDir.getAbsolutePath()); log.add(trace); Util.LOGGER.info(trace); FileUtil.delete(extractDir); trace = String.format(" %s deleted.", extractDir.getAbsolutePath()); log.add(trace); Util.LOGGER.info(trace); } FileUtil.extractZipArchive(backup, extractDir); trace = String.format("Extracted %s to %s", backup.getAbsolutePath(), extractDir.getAbsolutePath()); log.add(trace); Util.LOGGER.info(trace); setPercentComplete(50); PreProcess restorePreProcess = options.getPreProcess(); ContentOption contrentRestoreOption = options.getContentOption(); boolean truncateDatabase = PreProcess.deleteData.equals(restorePreProcess); if (truncateDatabase) { trace = "Truncate " + ((UtilImpl.SCHEMA == null) ? "default" : UtilImpl.SCHEMA) + " schema"; log.add(trace); Util.LOGGER.info(trace); } Truncate.truncate(UtilImpl.SCHEMA, truncateDatabase, true); boolean createUsingBackup = false; boolean ddlSync = false; if (PreProcess.createUsingBackup.equals(restorePreProcess)) { createUsingBackup = true; DDL.create(new File(extractDir, "create.sql"), true); ddlSync = true; } else if (PreProcess.createUsingMetadata.equals(restorePreProcess)) { DDL.create(null, true); ddlSync = true; } else if (PreProcess.dropUsingBackupAndCreateUsingBackup.equals(restorePreProcess)) { createUsingBackup = true; DDL.drop(new File(extractDir, "drop.sql"), true); DDL.create(new File(extractDir, "create.sql"), true); ddlSync = true; } else if (PreProcess.dropUsingBackupAndCreateUsingMetadata.equals(restorePreProcess)) { DDL.drop(new File(extractDir, "drop.sql"), true); DDL.create(null, true); ddlSync = true; } else if (PreProcess.dropUsingMetadataAndCreateUsingBackup.equals(restorePreProcess)) { createUsingBackup = true; DDL.drop(null, true); DDL.create(new File(extractDir, "create.sql"), true); ddlSync = true; } else if (PreProcess.dropUsingMetadataAndCreateUsingMetadata.equals(restorePreProcess)) { DDL.drop(null, true); DDL.create(null, true); ddlSync = true; } trace = "Restore " + extractDirName; log.add(trace); Util.LOGGER.info(trace); IndexingOption indexingOption = options.getIndexingOption(); restore(extractDirName, createUsingBackup, contrentRestoreOption, indexingOption); if (ddlSync) { trace = "DDL Sync"; log.add(trace); Util.LOGGER.info(trace); DDL.sync(true); } if (IndexingOption.both.equals(indexingOption) || IndexingOption.data.equals(indexingOption)) { trace = "Reindex textual indexes."; log.add(trace); Util.LOGGER.info(trace); execute(new ReindexBeansJob()); } trace = "Delete extracted folder " + extractDir.getAbsolutePath(); log.add(trace); Util.LOGGER.info(trace); FileUtil.delete(extractDir); trace = "DONE"; log.add(trace); Util.LOGGER.info(trace); setPercentComplete(100); EXT.push(new PushMessage().user().growl(MessageSeverity.info, "Restore Completed")); } private void restore(String extractDirName, boolean createUsingBackup, ContentOption contentRestoreOption, IndexingOption indexingOption) throws Exception { String customerName = CORE.getUser().getCustomerName(); String backupDirectoryPath = UtilImpl.CONTENT_DIRECTORY + "backup_" + customerName + File.separator + extractDirName; File backupDirectory = new File(backupDirectoryPath); if ((! backupDirectory.exists()) || (! backupDirectory.isDirectory())) { throw new IllegalArgumentException(backupDirectoryPath + " is not a directory"); } Collection<Table> tables = createUsingBackup ? BackupUtil.readTables(new File(backupDirectory, "tables.txt")) : BackupUtil.getTables(); try (Connection connection = EXT.getDataStoreConnection()) { connection.setAutoCommit(false); // restore normal tables restoreData(backupDirectory, tables, connection, false, false, contentRestoreOption, indexingOption); setPercentComplete(25); // restore extension join tables restoreData(backupDirectory, tables, connection, false, true, contentRestoreOption, indexingOption); setPercentComplete(50); // link foreign keys restoreForeignKeys(backupDirectory, tables, connection); setPercentComplete(75); // restore collection join tables restoreData(backupDirectory, tables, connection, true, false, contentRestoreOption, indexingOption); setPercentComplete(100); } } // update bizKeys // check and remove content not present // validate by updating bizLock and rolling back // check commit points private void restoreData(File backupDirectory, Collection<Table> tables, Connection connection, boolean joinTables, boolean extensionTables, ContentOption contentRestoreOption, IndexingOption indexingOption) throws Exception { try (ContentManager cm = EXT.newContentManager()) { for (Table table : tables) { if (table instanceof JoinTable) { if (! joinTables) { continue; } } else { if (joinTables) { continue; } if (BackupUtil.hasBizCustomer(table)) { if (extensionTables) { continue; } } else { if (! extensionTables) { continue; } } } Collection<String> log = getLog(); String trace = " restore table " + table.name; log.add(trace); UtilImpl.LOGGER.info(trace); File backupFile = new File(backupDirectory.getAbsolutePath() + File.separator + table.name + ".csv"); if (! backupFile.exists()) { trace = " ***** File " + backupFile.getAbsolutePath() + File.separator + table.name + ".csv does not exist"; log.add(trace); System.err.println(trace); continue; } long rowCount = 0; try (FileReader fr = new FileReader(backupFile)) { try (CsvMapReader reader = new CsvMapReader(fr, CsvPreference.STANDARD_PREFERENCE)) { String[] headers = reader.getHeader(true); StringBuilder sql = new StringBuilder(128); sql.append("insert into ").append(table.name).append(" ("); for (String header : headers) { if (joinTables) { sql.append(header).append(','); } else { if (! header.endsWith("_id")) { sql.append(header).append(','); } } } sql.setLength(sql.length() - 1); // remove the last comma sql.append(") values ("); for (String header : headers) { if (joinTables) { sql.append("?,"); } else { if (! header.endsWith("_id")) { sql.append("?,"); } } } sql.setLength(sql.length() - 1); // remove the last comma sql.append(')'); Map<String, String> values = null; try (PreparedStatement statement = connection.prepareStatement(sql.toString())) { while ((values = reader.read(headers)) != null) { if (isCancelled()) { return; } statement.clearParameters(); int index = 1; for (String header : headers) { if ((! joinTables) && header.endsWith("_id")) { continue; } String stringValue = values.get(header); if ((stringValue == null) || (stringValue.length() == 0)) { statement.setObject(index++, null); continue; } AttributeType attributeType = table.fields.get(header); // replace any 2 CR or LF combinations in the string with 1 // Super CSV place 2 ox0A into the string when it comes across a '\n' // in a quoted string field value. stringValue = stringValue.replaceAll("[\\n\\r]{2}", "\n"); // foreign keys if (header.endsWith("_id")) { statement.setString(index++, stringValue); } else if (AttributeType.colour.equals(attributeType) || AttributeType.memo.equals(attributeType) || AttributeType.markup.equals(attributeType) || AttributeType.text.equals(attributeType) || AttributeType.enumeration.equals(attributeType) || AttributeType.id.equals(attributeType)) { statement.setString(index++, stringValue); } else if (AttributeType.geometry.equals(attributeType)) { Geometry geometry = new WKTReader().read(stringValue); SkyveDialect dialect = AbstractHibernatePersistence.getDialect(); int geometrySqlType = dialect.getGeometrySqlType(); if (geometrySqlType == Types.ARRAY) { statement.setBytes(index++, (byte[]) dialect.convertToPersistedValue(geometry)); } else { statement.setObject(index++, dialect.convertToPersistedValue(geometry), geometrySqlType); } } else if (AttributeType.bool.equals(attributeType)) { statement.setBoolean(index++, Boolean.parseBoolean(stringValue)); } else if (AttributeType.date.equals(attributeType)) { statement.setDate(index++, new Date(Long.parseLong(stringValue)), BackupUtil.GMT); } else if (AttributeType.time.equals(attributeType)) { statement.setTime(index++, new Time(Long.parseLong(stringValue)), BackupUtil.GMT); } else if (AttributeType.dateTime.equals(attributeType) || AttributeType.timestamp.equals(attributeType)) { statement.setTimestamp(index++, new Timestamp(Long.parseLong(stringValue)), BackupUtil.GMT); } else if (AttributeType.decimal2.equals(attributeType) || AttributeType.decimal5.equals(attributeType) || AttributeType.decimal10.equals(attributeType)) { statement.setBigDecimal(index++, new BigDecimal(stringValue)); } else if (AttributeType.integer.equals(attributeType)) { statement.setInt(index++, Integer.parseInt(stringValue)); } else if (AttributeType.longInteger.equals(attributeType)) { statement.setLong(index++, Long.parseLong(stringValue)); } else if (AttributeType.content.equals(attributeType)) { StringBuilder contentPath = new StringBuilder(128); contentPath.append(backupDirectory.getAbsolutePath()).append('/'); contentPath.append(AbstractContentManager.FILE_STORE_NAME).append('/'); AttachmentContent content = ElasticContentManager.getFromFileSystem(contentPath, stringValue); if (content == null) { trace = " Could not find file associated with " + stringValue; if (ContentOption.error.equals(contentRestoreOption)) { log.add(trace); Util.LOGGER.severe(trace); throw new DomainException(trace); } else if (ContentOption.clearOrphanedContentIds.equals(contentRestoreOption)) { trace += " : Setting content to null"; log.add(trace); Util.LOGGER.info(trace); statement.setString(index++, null); } else { trace += " : Setting content ID regardless"; log.add(trace); Util.LOGGER.info(trace); statement.setString(index++, stringValue); } } else { IndexType indexType = table.indexes.get(header); boolean textIndex = (indexType == null) || IndexType.textual.equals(indexType) || IndexType.both.equals(indexType); if (textIndex) { textIndex = IndexingOption.both.equals(indexingOption) || IndexingOption.content.equals(indexingOption); } cm.put(content, textIndex); statement.setString(index++, content.getContentId()); } } else { throw new IllegalStateException("No value set for " + header); } } // for (each header) statement.executeUpdate(); rowCount++; } // while (each CSV line) connection.commit(); } catch (Throwable t) { trace = t.getLocalizedMessage(); log.add(trace); Util.LOGGER.severe(trace); trace = "AT LINE " + rowCount + " OF " + backupFile.getAbsolutePath(); log.add(trace); Util.LOGGER.severe(trace); trace = "CAUSED BY:- " + sql.toString(); log.add(trace); Util.LOGGER.severe(trace); StringBuilder sb = new StringBuilder(512); sb.append("VALUES :- "); if (values == null) { sb.append("NONE"); } else { for (String header : values.keySet()) { sb.append(header).append('=').append(values.get(header)).append(','); } sb.setLength(sb.length() - 1); // remove last comma } trace = sb.toString(); log.add(trace); Util.LOGGER.severe(trace); throw t; } } } trace = " restored table " + table.name + " with " + rowCount + " rows."; log.add(trace); UtilImpl.LOGGER.info(trace); } // for (each table) } } private void restoreForeignKeys(File backupDirectory, Collection<Table> tables, Connection connection) throws Exception { Collection<String> log = getLog(); String trace; for (Table table : tables) { if (table instanceof JoinTable) { continue; } trace = " restore foreign keys for table " + table.name; log.add(trace); Util.LOGGER.info(trace); File backupFile = new File(backupDirectory.getAbsolutePath() + File.separator + table.name + ".csv"); if (! backupFile.exists()) { trace = " ***** File " + backupFile.getAbsolutePath() + File.separator + " does not exist"; log.add(trace); System.err.println(trace); continue; } long rowCount = 0; try (FileReader fr = new FileReader(backupFile)) { try (CsvMapReader reader = new CsvMapReader(fr, CsvPreference.STANDARD_PREFERENCE)) { String[] headers = reader.getHeader(true); StringBuilder sql = new StringBuilder(128); sql.append("update ").append(table.name); boolean foundAForeignKey = false; for (String header : headers) { if (header.endsWith("_id")) { if (! foundAForeignKey) { sql.append(" set "); } else { sql.append(", "); } sql.append(header).append(" = ?"); foundAForeignKey = true; } } if (foundAForeignKey) { sql.append(" where bizId = ?"); try (PreparedStatement statement = connection.prepareStatement(sql.toString())) { Map<String, String> values = null; while ((values = reader.read(headers)) != null) { if (isCancelled()) { return; } statement.clearParameters(); int i = 1; for (String header : headers) { if (header.endsWith("_id")) { final String stringValue = values.get(header); if ((stringValue == null) || (stringValue.length() == 0)) { statement.setObject(i, null); i++; } else { statement.setString(i, stringValue); i++; } } } // for (each header) // set the ID for the where clause statement.setString(i, values.get(Bean.DOCUMENT_ID)); statement.executeUpdate(); rowCount++; } // while (each CSV line) connection.commit(); } } } } trace = " restored foreign keys for table " + table.name + " with " + rowCount + " rows."; log.add(trace); UtilImpl.LOGGER.info(trace); } // for (each table) } }
Change Restore notifications broadcast to all users.
skyve-ext/src/main/java/org/skyve/impl/backup/RestoreJob.java
Change Restore notifications broadcast to all users.
<ide><path>kyve-ext/src/main/java/org/skyve/impl/backup/RestoreJob.java <ide> return; <ide> } <ide> <add> EXT.push(new PushMessage().growl(MessageSeverity.info, "System Restore in progress - system unavailable until restore is complete.")); <add> <ide> String extractDirName = selectedBackupName.substring(0, selectedBackupName.length() - 4); <ide> File extractDir = new File(backup.getParentFile(), extractDirName); <ide> trace = String.format("Extract %s to %s", backup.getAbsolutePath(), extractDir.getAbsolutePath()); <ide> log.add(trace); <ide> Util.LOGGER.info(trace); <ide> setPercentComplete(100); <del> EXT.push(new PushMessage().user().growl(MessageSeverity.info, "Restore Completed")); <add> <add> EXT.push(new PushMessage().growl(MessageSeverity.info, "System Restore complete.")); <ide> } <ide> <ide> private void restore(String extractDirName,
Java
apache-2.0
1251b7ff1a25a3bb8a9d78adc3ea0289523df44d
0
nverwer/cocooncomponents,hhv/cocooncomponents
package org.apache.cocoon.components.cron; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.DomDriver; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.util.Arrays; import java.util.Comparator; import java.util.Date; import java.util.Enumeration; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; import org.apache.avalon.framework.CascadingRuntimeException; import org.apache.avalon.framework.configuration.Configurable; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.avalon.framework.parameters.Parameters; import org.apache.cocoon.components.cron.ConfigurableCronJob; import org.apache.cocoon.components.cron.ServiceableCronJob; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.io.filefilter.WildcardFileFilter; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.excalibur.source.Source; import org.apache.excalibur.source.SourceResolver; import org.joda.time.DateTime; /** * * @author <a href="mailto:[email protected]">Huib Verweij</a> * @author <a href="mailto:[email protected]">Maarten Kroon</a> * * Execute jobs that are submitted to a queue. * * A queue is a directory on disk that contains jobs-to-be-executed in * the "in" subdirectory. * * A job is a XML file containing meta-data describing the job and one * or more smaller tasks that are part of the job. A task contains a URL * that is 'resolved' when the task is executed. The output of the URL * ends up in a task-{id}.xml file. Note that tasks are executed * *** in random order ***. * * A queue has four directories: "in", "in-progress", "out" and "error". * 1 New jobs that are waiting to be processed are in "in". * 2 The one job that is being executed is in "in-progress". * 3 Finished jobs are zipped. Job-file and task-output files end up in "out". * 4 Jobs that could not be executed at all (or generated an error in * this class)end up in "error". * * Execute this object (a "Processor") every n (micro)seconds using a Cocoon * Quartz job and it will process one job in a queue. Processing a job means * moveing the job-*.xml file to "in-progress" and starting a separate thread * for each task in the job, then waiting till all tasks have finished. * * While executing, a Processor updates the file Queue/processor-status.xml * every 10 seconds or so with the following info: * &lt;processor id="thread-id" started="dateTime" tasks="nr of tasks" * tasks-completed="nr of completed tasks" /> * This file can be read in order to get an idea of the progress of the current * job. It also indicates whether the current job is being processed at all - if * the modified timestamp of the file is older than, say, a minute, it is * assumed the Processor/job has failed. * * When a Processor starts there are a few possible scenarios: * 1 another job is already being processed and that Processor is * still alive -> quit. * 2 there is no job to be processed -> quit. * 3 there is no other Processor running but there's a job already * being processed -> move job to "error"-directory, quit. * 4 there is a job to be processed and no Processor active -> * start processing a new job. * * To submit a job, place a XML file called "job-{id}.xml" in the "in"-directory, * containing the following structure: * &lt;job name="test-job" created="20140613T11:45:00" max-concurrent="3"> * &lt;tasks> * &lt;task id="task-1"> * &lt;uri>http://localhost:8888/koop/front/queue-test?id=1&lt;/uri> * &lt;/task> * ... * &lt;/tasks> * &lt;/job> * * At the moment, the max-concurrent attribute is ignored and the maximum * number of concurrent tasks is equal to the number of processors in the * server. * * To add this cronjob to Cocoon add a trigger to the Quartzcomponent * configuration and declare this component in the same sitemap. * &lt;component * class="org.apache.cocoon.components.cron.CocoonQuartzJobScheduler" * logger="cron" * role="org.apache.cocoon.components.cron.JobScheduler"> * ..... * &lt;trigger name="dequeue-job" * target="org.apache.cocoon.components.cron.CronJob/dequeue" * concurrent-runs="false"> * &lt;cron>0/10 * * * * ?&lt;/cron> * &lt;/trigger> * &lt;/component> * * and * * &lt;component class="org.apache.cocoon.components.cron.DequeueCronJob" * logger="cron.publish" * role="org.apache.cocoon.components.cron.CronJob/dequeue"> * &lt;queue-path>/tmp/LiDO-queue&lt;/queue-path> * &lt;/component> */ public class DequeueCronJob extends ServiceableCronJob implements Configurable, ConfigurableCronJob { private static final String PARAMETER_QUEUE_PATH = "queue-path"; private static final String PROCESSOR_STATUS_FILE = "processor-status.xml"; private static final long PROCESSOR_STATUS_FILE_STALE = 60000; private static final String inDirName = "in"; private static final String processingDirName = "in-progress"; private static final String outDirName = "out"; private static final String errorDirName = "error"; private File queuePath; private final long DONT_WAIT_TOO_LONG = 8000; /** * Zip contents of processingDir into "{currentJob-name}.zip" into outDir. * The zip contains a directory {currentJob-name}, all other files are in * that directory. * * @param processingDir * @param outDir * @param currentJob */ private void finishUpJob(File processingDir, File outDir, File currentJob) { final String basename = FilenameUtils.getBaseName(currentJob.getName()); final String zipFileName = String.format("%s.zip", basename); File zipFile = new File(outDir, zipFileName); final String zipFolder = basename + "/"; try { // create byte buffer byte[] buffer = new byte[1024]; FileOutputStream fos = new FileOutputStream(zipFile); ZipOutputStream zos = new ZipOutputStream(fos); // add a directory to the new ZIP first zos.putNextEntry(new ZipEntry(zipFolder)); File[] files = processingDir.listFiles(); for (File file : files) { System.out.println("Adding file: " + file.getName()); FileInputStream fis = new FileInputStream(file); // begin writing a new ZIP entry, positions the stream to the start of the entry data zos.putNextEntry(new ZipEntry(zipFolder + file.getName())); int length; while ((length = fis.read(buffer)) > 0) { zos.write(buffer, 0, length); } zos.closeEntry(); // close the InputStream fis.close(); } // close the ZipOutputStream zos.close(); } catch (IOException ioe) { System.out.println("Error creating zip file" + ioe); } } /** * The object that runs a task. */ private static class TaskRunner implements Callable { private final Task task; private final org.apache.avalon.framework.service.ServiceManager manager; private final org.apache.avalon.framework.logger.Logger logger; private final File outputFile; public TaskRunner(Task t, org.apache.avalon.framework.service.ServiceManager manager, org.apache.avalon.framework.logger.Logger logger, File outputFile) { this.task = t; this.manager = manager; this.logger = logger; this.outputFile = outputFile; } @Override public Object call() throws Exception { this.logger.info("Processing task " + task.id); Thread.sleep(4000); OutputStream os = new FileOutputStream(outputFile); processPipeline(task.uri, manager, logger, os); os.close(); return null; } } /** * An enum denoting the status of a Processor this class). */ public enum ProcessorStatus { ALIVE, DEAD, NONE } /** * Process a job: add all tasks to ExecutorService, invokeAll tasks * and wait until all tasks have finished. While waiting, update * processor-status.xml. * @param inDir Where all output files are stored. * @param currentJob The current job file. */ private void processCurrentJob(File inDir, File currentJob) { this.getLogger().info("Processing job " + currentJob.getAbsoluteFile()); JobConfig jobConfig = readJobConfig(currentJob); int totalTasks = jobConfig.tasks.length; int completedTasks = 0; DateTime jobStartedAt = new DateTime(); int processors = Runtime.getRuntime().availableProcessors(); ExecutorService jobExecutor = Executors.newFixedThreadPool(processors); this.getLogger().debug("Max concurrent jobs = " + processors); Set<Callable<TaskRunner>> callables = new HashSet<Callable<TaskRunner>>(); for (Task t : jobConfig.tasks) { File outputFile = new File(inDir, String.format("task-%s.output", t.id)); Callable taskRunner = new TaskRunner(t, this.manager, this.getLogger(), outputFile); callables.add(taskRunner); } try { List<Future<TaskRunner>> futures = jobExecutor.invokeAll(callables); for (Future<TaskRunner> future : futures) { try { future.get(500, TimeUnit.MILLISECONDS); completedTasks--; } catch (ExecutionException ex) { Logger.getLogger(DequeueCronJob.class.getName()).log(Level.SEVERE, null, ex); completedTasks--; } catch (TimeoutException ex) { Logger.getLogger(DequeueCronJob.class.getName()).log(Level.SEVERE, null, ex); } finally { writeProcessorStatus(jobConfig.name, jobStartedAt, totalTasks, completedTasks); } } jobExecutor.shutdown(); while (!jobExecutor.awaitTermination(DONT_WAIT_TOO_LONG, TimeUnit.MILLISECONDS)) { this.getLogger().info("Waiting for all tasks to finish "); } } catch (InterruptedException ex) { Logger.getLogger(DequeueCronJob.class.getName()).log(Level.SEVERE, null, ex); jobExecutor.shutdownNow(); } } /** * Read job description file into JobConfig object using XStream. * * @param currentJob * @return JobConfig */ private JobConfig readJobConfig(File currentJob) { // <job name="test-job" created="20140613T11:45:00" max-concurrent="3"> // <tasks> // <task id="task-1"> // <uri>http://localhost:8888/koop/front/queue-test?id=1</uri> // </task> // ... // </job> XStream xstream = new XStream(new DomDriver()); xstream.alias("job", JobConfig.class); xstream.useAttributeFor(JobConfig.class, "name"); xstream.useAttributeFor(JobConfig.class, "created"); xstream.useAttributeFor(JobConfig.class, "maxConcurrent"); xstream.aliasField("max-concurrent", JobConfig.class, "maxConcurrent"); xstream.alias("task", Task.class); xstream.useAttributeFor(Task.class, "id"); JobConfig jobConfig = (JobConfig) xstream.fromXML(currentJob); this.getLogger().info("jobConfig.name = " + jobConfig.name); this.getLogger().info("jobConfig.created = " + jobConfig.created); this.getLogger().info("jobConfig.maxConcurrent = " + jobConfig.maxConcurrent); this.getLogger().info("jobConfig.tasks = " + jobConfig.tasks); this.getLogger().info("jobConfig.tasks.length = " + jobConfig.tasks.length); return jobConfig; } @SuppressWarnings("rawtypes") @Override public void setup(Parameters params, Map objects) { return; } /** * We're done, delete status file. */ private synchronized void deleteProcessorStatus() { File pStatusFile = new File(this.queuePath, PROCESSOR_STATUS_FILE); pStatusFile.delete(); } /** * Update status file. * * @param jobName * @param started * @param totalTasks * @param completedTasks * @param currentTaskStartedAt */ private synchronized void writeProcessorStatus(String jobName, DateTime started, int totalTasks, int completedTasks) { File pStatusFile = new File(this.queuePath, PROCESSOR_STATUS_FILE); String status = String.format("<processor id=\"%s\" job-name=\"%s\" started=\"%s\" tasks=\"%d\" tasks-completed=\"%d\"/>", Thread.currentThread().getId(), jobName, started.toString(), totalTasks, completedTasks); try { FileUtils.writeStringToFile(pStatusFile, status, "UTF-8"); Logger.getLogger(DequeueCronJob.class.getName()).log(Level.INFO, status, status); } catch (IOException ex) { Logger.getLogger(DequeueCronJob.class.getName()).log(Level.SEVERE, null, ex); } } /** * Return File object for parent/path, creating it if necessary. * @param parent * @param path * @return Resulting File object. */ private File getOrCreateDirectory(File parent, String path) { File dir = new File(parent, path); if (!dir.exists()) { dir.mkdirs(); } return dir; } /** * Move file from one File object to another File object, deleting * an already existing file if necessary. * @param fromFile * @param toFile * @throws IOException */ private void moveFileTo(File fromFile, File toFile) throws IOException { if (toFile.isFile()) { FileUtils.forceDelete(toFile); } if (!fromFile.renameTo(toFile)) { if (this.getLogger().isErrorEnabled()) { this.getLogger().error(String.format("Could not move file \"%s\" to \"%s\"", fromFile.getAbsolutePath(), toFile.getAbsoluteFile())); } } } /** * Get oldest job (file named "job-*.xml") in dir, using * lastModified timestamp and picking first File if there is more * than one file with the same lastModified. * @param dir * @return */ protected File getOldestJobFile(File dir) { if (dir == null || !dir.isDirectory()) { return null; } File[] files = dir.listFiles((FileFilter) new WildcardFileFilter("job-*.xml")); if (files.length == 0) { return null; } Arrays.sort(files, new Comparator<File>() { public int compare(File file1, File file2) { return Long.valueOf(file1.lastModified()).compareTo(file2.lastModified()); } }); return files[0]; } /** * Get path to queue folder. * @param config * @throws ConfigurationException */ @Override public void configure(final Configuration config) throws ConfigurationException { String actualQueuesDirName = config.getChild(PARAMETER_QUEUE_PATH).getValue(); queuePath = new File(actualQueuesDirName); } /** * Process the URL in one Task. All errors are caught, if one task goes bad * continue processing the others. * @param url URL to fetch * @param manager Cocoon servicemanager (so cocoon: protocol is allowed.) * @param logger For logging stuff * @param os Where the output ends up. */ private static void processPipeline(String url, org.apache.avalon.framework.service.ServiceManager manager, org.apache.avalon.framework.logger.Logger logger, OutputStream os) { SourceResolver resolver = null; Source src = null; InputStream is = null; String cocoonPipeline = url; try { logger.info(String.format("Processing: %s", url)); resolver = (SourceResolver) manager.lookup(SourceResolver.ROLE); src = resolver.resolveURI(cocoonPipeline); is = src.getInputStream(); IOUtils.copy(is, os); } catch (Exception e) { try { os.write(e.getMessage().getBytes()); os.write("\n".getBytes()); e.printStackTrace(new PrintStream(os)); } catch (IOException ex) { Logger.getLogger(DequeueCronJob.class.getName()).log(Level.SEVERE, null, ex); } throw new CascadingRuntimeException(String.format("Error processing pipeline \"%s\"", cocoonPipeline), e); } finally { try { if (is != null) { is.close(); } } catch (IOException e) { throw new CascadingRuntimeException("DequeueCronJob raised an exception.", e); } if (resolver != null) { resolver.release(src); manager.release(resolver); resolver = null; src = null; } } } /** * Check if there's a job in the processingDir. * If yes then abstain if Processor = ALIVE, remove it otherwise. * If No then move oldest job to processingDir, process that job. */ private void processQueue() throws IOException { /* Create subdirs if necessary. */ File queueDir = this.queuePath; File inDir = getOrCreateDirectory(queueDir, inDirName); File processingDir = getOrCreateDirectory(queueDir, processingDirName); File outDir = getOrCreateDirectory(queueDir, outDirName); File errorDir = getOrCreateDirectory(queueDir, errorDirName); // Get status of Processor DequeueCronJob.ProcessorStatus pStatus = processorStatus(); File currentJobFile = getOldestJobFile(processingDir); this.getLogger().info(String.format("Processor: %s, current job: %s", pStatus, currentJobFile)); // A job is already being processed if (null != currentJobFile) { /* * A job is processed by a live Processor -> quit now. */ if (pStatus.equals(DequeueCronJob.ProcessorStatus.ALIVE)) { if (this.getLogger().isDebugEnabled()) { this.getLogger().debug(String.format("Active job \"%s\" in queue \"%s\", stopping", currentJobFile, queueDir)); } return; } else { /* * A job was processed, but the Processor is dead. * Move job tot error-folder. Clean processing folder. */ this.getLogger().warn(String.format("Stale job \"%s\" in queue \"%s\", cancelling job and stopping", currentJobFile, queueDir)); moveFileTo(currentJobFile, new File(errorDir, currentJobFile.getName())); FileUtils.cleanDirectory(processingDir); return; } } else { // No job being processed. File jobFile = getOldestJobFile(inDir); if (jobFile != null) { String jobFileName = jobFile.getName(); File currentJob = new File(processingDir, jobFileName); try { writeProcessorStatus(jobFileName, new DateTime(), 0, 0); if (this.getLogger().isDebugEnabled()) { this.getLogger().debug(String.format("Processing job \"%s\" in queue \"%s\"", jobFileName, queueDir)); } moveFileTo(jobFile, currentJob); this.getLogger().debug(String.format("Moved job \"%s\" to \"%s\"", jobFile, currentJob)); processCurrentJob(processingDir, currentJob); finishUpJob(processingDir, outDir, currentJob); } catch (IOException e) { if (this.getLogger().isErrorEnabled()) { this.getLogger().error("Error processing job \"" + jobFileName + "\"", e); } moveFileTo(currentJob, new File(errorDir, jobFileName)); String stackTrace = ExceptionUtils.getFullStackTrace(e); FileUtils.writeStringToFile(new File(errorDir, FilenameUtils.removeExtension(jobFileName) + ".txt"), stackTrace, "UTF-8"); } finally { FileUtils.cleanDirectory(processingDir); deleteProcessorStatus(); } } else { if (this.getLogger().isDebugEnabled()) { this.getLogger().debug("No job, stopping"); } } } } /** * Return NONE (No processor), ALIVE (Processor still active) or DEAD * (Processor hasn't updated status file for too long). * * @return ProcessorStatus: NONE, ALIVE or DEAD. */ private synchronized ProcessorStatus processorStatus() { File statusFile = new File(this.queuePath, PROCESSOR_STATUS_FILE); if (!statusFile.exists()) { return DequeueCronJob.ProcessorStatus.NONE; } else { long lastModified = statusFile.lastModified(); if (System.currentTimeMillis() - lastModified > PROCESSOR_STATUS_FILE_STALE) { return DequeueCronJob.ProcessorStatus.DEAD; } else { return DequeueCronJob.ProcessorStatus.ALIVE; } } } /** * Main entrypoint for CronJob. * @param name */ @Override public void execute(String name) { if (this.getLogger().isDebugEnabled()) { this.getLogger().debug("CronJob " + name + " launched at " + new Date()); } try { processQueue(); } catch (IOException e) { throw new CascadingRuntimeException("CronJob " + name + " raised an exception.", e); } } /** * Classes used by XStream for loading the job-*.xml config files into. */ private class Task { /* <task id="task-*"> <uri>URI of task to be executed, f.i. "cocoon://bron/svb/incremental" or "http://localhost:8888/import/bwbng"</uri> </task> */ private String id; private String uri; public Task() { } } private class JobConfig { // <job name="job-name" created="date" max-concurrent="n">tasks...</job> private String name; private DateTime created; private Integer maxConcurrent; private Task[] tasks; public JobConfig() { } } }
src/org/apache/cocoon/components/cron/DequeueCronJob.java
package org.apache.cocoon.components.cron; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.DomDriver; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.util.Arrays; import java.util.Comparator; import java.util.Date; import java.util.Enumeration; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; import org.apache.avalon.framework.CascadingRuntimeException; import org.apache.avalon.framework.configuration.Configurable; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.avalon.framework.parameters.Parameters; import org.apache.cocoon.components.cron.ConfigurableCronJob; import org.apache.cocoon.components.cron.ServiceableCronJob; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.io.filefilter.WildcardFileFilter; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.excalibur.source.Source; import org.apache.excalibur.source.SourceResolver; import org.joda.time.DateTime; /** * * * @author <a href="mailto:[email protected]">Maarten Kroon</a> * @author <a href="mailto:[email protected]">Huib Verweij</a> * * Execute jobs that are submitted to a queue. * * A queue is a directory on disk that contains jobs. * * A job is a zipped directory containing meta-data describing the job and one * or more smaller tasks that are part of the job. * * A queue has four directories, in, in-progress, out and error. 1 New jobs that * are waiting to be processed are in "in". 2 The one job that is being executed * is in "in-progress". 3 Finished jobs are moved to "out". 4 Jobs that could * not be executed at all end up in "error". * * Execute this object (a "Processor") every n (micro)seconds using a Cocoon * Quartz job and it will process one job in a queue. Processing a job means * unzipping the job.zip and starting a separate thread for each task in the * job. Every thread is 'join'ed so there are no runaway processes. * * While executing, a Processor updates the file processor-status.xml every 10 * seconds or so with the following info: * <processor id="(OS?) process-id" started="dateTime" tasks="nr of tasks" * tasks-completed="nr of completed tasks" task-started-at="time current task * was started"/> * This file can be read in order to get an idea of the progress of the current * job. It also indicates whether the current job is being processed at all - if * the modified timestamp of the file is older than, say, a minute, it is * assumed the Processor/job has failed. * * When a Processor starts there are a few possible scenarios: 1 another job is * already being processed and that Processor is still alive -> quit. 2 there is * no job to be processed -> quit. 3 there is no other Processor running but * there's a job already being processed -> move job to "error"-directory, quit. * 4 there is a job to be processed and no Processor active -> start processing * new job. * * To submit a job, upload a XML called "job-*.xml", containing the following * structure: * <job name="test-job" created="20140613T11:45:00" max-concurrent="3"> * <tasks> * <task id="task-1"> * <uri>http://localhost:8888/koop/front/queue-test?id=1</uri> * </task> * ... * </tasks> * </job> * */ public class DequeueCronJob extends ServiceableCronJob implements Configurable, ConfigurableCronJob { private static final String PARAMETER_QUEUE_PATH = "queue-path"; private static final String PROCESSOR_STATUS_FILE = "processor-status.xml"; private static final long PROCESSOR_STATUS_FILE_STALE = 60000; private final String inDirName = "in"; private final String processingDirName = "in-progress"; private final String outDirName = "out"; private final String errorDirName = "error"; private File queuePath; private final long DONT_WAIT_TOO_LONG = 8000; /** * Zip contents of processingDir into file, named after currentJob, * into outDir. * * @param processingDir * @param outDir * @param currentJob */ private void finishUpJob(File processingDir, File outDir, File currentJob) { final String basename = FilenameUtils.getBaseName(currentJob.getName()); final String zipFileName = String.format("%s.zip", basename); File zipFile = new File(outDir, zipFileName); final String zipFolder = basename + "/"; try { // create byte buffer byte[] buffer = new byte[1024]; FileOutputStream fos = new FileOutputStream(zipFile); ZipOutputStream zos = new ZipOutputStream(fos); // add a directory to the new ZIP first zos.putNextEntry(new ZipEntry(zipFolder)); File[] files = processingDir.listFiles(); for (File file : files) { System.out.println("Adding file: " + file.getName()); FileInputStream fis = new FileInputStream(file); // begin writing a new ZIP entry, positions the stream to the start of the entry data zos.putNextEntry(new ZipEntry(zipFolder + file.getName())); int length; while ((length = fis.read(buffer)) > 0) { zos.write(buffer, 0, length); } zos.closeEntry(); // close the InputStream fis.close(); } // close the ZipOutputStream zos.close(); } catch (IOException ioe) { System.out.println("Error creating zip file" + ioe); } } private static class TaskRunner implements Callable { private final Task task; private final org.apache.avalon.framework.service.ServiceManager manager; private final org.apache.avalon.framework.logger.Logger logger; private final File outputFile; public TaskRunner(Task t, org.apache.avalon.framework.service.ServiceManager manager, org.apache.avalon.framework.logger.Logger logger, File outputFile) { this.task = t; this.manager = manager; this.logger = logger; this.outputFile = outputFile; } @Override public Object call() throws Exception { this.logger.info("Processing task " + task.id); // Thread.sleep(4000); OutputStream os = new FileOutputStream(outputFile); processPipeline(task.uri, manager, logger, os); os.close(); return null; } } /** * An enum denoting the status of a Processor this class). */ public enum ProcessorStatus { ALIVE, DEAD, NONE } // private ExecutorService executor = Executors.newFixedThreadPool(1); private void processCurrentJob(File inDir, File currentJob) { this.getLogger().info("Processing job " + currentJob.getAbsoluteFile()); JobConfig jobConfig = readJobConfig(currentJob); int totalTasks = jobConfig.tasks.length; int completedTasks = 0; DateTime jobStartedAt = new DateTime(); int processors = Runtime.getRuntime().availableProcessors(); ExecutorService jobExecutor = Executors.newFixedThreadPool(processors); this.getLogger().info("Max concurrent jobs = " + processors); Set<Callable<TaskRunner>> callables = new HashSet<Callable<TaskRunner>>(); for (Task t : jobConfig.tasks) { File outputFile = new File(inDir, String.format("task-%s.output", t.id)); Callable taskRunner = new TaskRunner(t, this.manager, this.getLogger(), outputFile); callables.add(taskRunner); } try { List<Future<TaskRunner>> futures = jobExecutor.invokeAll(callables); for (Future<TaskRunner> future : futures) { try { this.getLogger().info("future.get = " + future.get()); completedTasks--; writeProcessorStatus(jobConfig.name, jobStartedAt, totalTasks, completedTasks); } catch (ExecutionException ex) { Logger.getLogger(DequeueCronJob.class.getName()).log(Level.SEVERE, null, ex); completedTasks--; } } jobExecutor.shutdown(); while (!jobExecutor.awaitTermination(DONT_WAIT_TOO_LONG, TimeUnit.MILLISECONDS)) { this.getLogger().info("Waiting for all tasks to finish "); } } catch (InterruptedException ex) { Logger.getLogger(DequeueCronJob.class.getName()).log(Level.SEVERE, null, ex); jobExecutor.shutdownNow(); } } /** * Read job description file into JobConfig object using XStream. * * @param currentJob * @return JobConfig */ private JobConfig readJobConfig(File currentJob) { // <job name="test-job" created="20140613T11:45:00" max-concurrent="3"> // <tasks> // <task id="task-1"> // <uri>http://localhost:8888/koop/front/queue-test?id=1</uri> // </task> // ... // </job> XStream xstream = new XStream(new DomDriver()); xstream.alias("job", JobConfig.class); xstream.useAttributeFor(JobConfig.class, "name"); xstream.useAttributeFor(JobConfig.class, "created"); xstream.useAttributeFor(JobConfig.class, "maxConcurrent"); xstream.aliasField("max-concurrent", JobConfig.class, "maxConcurrent"); xstream.alias("task", Task.class); xstream.useAttributeFor(Task.class, "id"); JobConfig jobConfig = (JobConfig) xstream.fromXML(currentJob); this.getLogger().info("jobConfig.name = " + jobConfig.name); this.getLogger().info("jobConfig.created = " + jobConfig.created); this.getLogger().info("jobConfig.maxConcurrent = " + jobConfig.maxConcurrent); this.getLogger().info("jobConfig.tasks = " + jobConfig.tasks); this.getLogger().info("jobConfig.tasks.length = " + jobConfig.tasks.length); return jobConfig; } @SuppressWarnings("rawtypes") @Override public void setup(Parameters params, Map objects) { return; } /** * We're done, delete status file. */ private synchronized void deleteProcessorStatus() { File pStatusFile = new File(this.queuePath, PROCESSOR_STATUS_FILE); pStatusFile.delete(); } /** * Update status file. * * @param jobName * @param started * @param totalTasks * @param completedTasks * @param currentTaskStartedAt */ private synchronized void writeProcessorStatus(String jobName, DateTime started, int totalTasks, int completedTasks) { File pStatusFile = new File(this.queuePath, PROCESSOR_STATUS_FILE); String status = String.format("<processor id=\"%s\" job-name=\"%s\" started=\"%s\" tasks=\"%d\" tasks-completed=\"%d\"/>", Thread.currentThread().getId(), jobName, started.toString(), totalTasks, completedTasks); try { FileUtils.writeStringToFile(pStatusFile, status, "UTF-8"); Logger.getLogger(DequeueCronJob.class.getName()).log(Level.INFO, status, status); } catch (IOException ex) { Logger.getLogger(DequeueCronJob.class.getName()).log(Level.SEVERE, null, ex); } } /** * Return File object for parent/path, creating it if necessary. * @param parent * @param path * @return Resulting File object. */ private File getOrCreateDirectory(File parent, String path) { File dir = new File(parent, path); if (!dir.exists()) { dir.mkdirs(); } return dir; } /** * Move file from one File object to another File object, deleting * an already existing file if necessary. * @param fromFile * @param toFile * @throws IOException */ private void moveFileTo(File fromFile, File toFile) throws IOException { if (toFile.isFile()) { FileUtils.forceDelete(toFile); } if (!fromFile.renameTo(toFile)) { if (this.getLogger().isErrorEnabled()) { this.getLogger().error(String.format("Could not move file \"%s\" to \"%s\"", fromFile.getAbsolutePath(), toFile.getAbsoluteFile())); } } } /** * Get oldest job (file named "job-*.xml") in dir, using * lastModified timestamp and picking first File if there is more * than one file with the same lastModified. * @param dir * @return */ protected File getOldestJobFile(File dir) { if (dir == null || !dir.isDirectory()) { return null; } File[] files = dir.listFiles((FileFilter) new WildcardFileFilter("job-*.xml")); if (files.length == 0) { return null; } Arrays.sort(files, new Comparator<File>() { public int compare(File file1, File file2) { return Long.valueOf(file1.lastModified()).compareTo(file2.lastModified()); } }); return files[0]; } /** * Get path to queue folder. * @param config * @throws ConfigurationException */ @Override public void configure(final Configuration config) throws ConfigurationException { String actualQueuesDirName = config.getChild(PARAMETER_QUEUE_PATH).getValue(); queuePath = new File(actualQueuesDirName); } /** * Process the URL in one Task. All errors are caught, if one task goes bad * continue processing the others. * @param url URL to fetch * @param manager Cocoon servicemanager (so cocoon: protocol is allowed.) * @param logger For logging stuff * @param os Where the output ends up. */ private static void processPipeline(String url, org.apache.avalon.framework.service.ServiceManager manager, org.apache.avalon.framework.logger.Logger logger, OutputStream os) { SourceResolver resolver = null; Source src = null; InputStream is = null; String cocoonPipeline = url; try { logger.info(String.format("Processing: %s", url)); resolver = (SourceResolver) manager.lookup(SourceResolver.ROLE); src = resolver.resolveURI(cocoonPipeline); is = src.getInputStream(); IOUtils.copy(is, os); } catch (Exception e) { try { os.write(e.getMessage().getBytes()); os.write("\n".getBytes()); e.printStackTrace(new PrintStream(os)); } catch (IOException ex) { Logger.getLogger(DequeueCronJob.class.getName()).log(Level.SEVERE, null, ex); } throw new CascadingRuntimeException(String.format("Error processing pipeline \"%s\"", cocoonPipeline), e); } finally { try { if (is != null) { is.close(); } } catch (IOException e) { throw new CascadingRuntimeException("DequeueCronJob raised an exception.", e); } if (resolver != null) { resolver.release(src); manager.release(resolver); resolver = null; src = null; } } } /** * Check if there's a job in the processingDir. * If yes then abstain if Processor = ALIVE, remove it otherwise. * If No then move oldest job to processingDir, process that job. */ private void processQueue() throws IOException { /* Create subdirs if necessary. */ File queueDir = this.queuePath; File inDir = getOrCreateDirectory(queueDir, inDirName); File processingDir = getOrCreateDirectory(queueDir, processingDirName); File outDir = getOrCreateDirectory(queueDir, outDirName); File errorDir = getOrCreateDirectory(queueDir, errorDirName); // Get status of Processor DequeueCronJob.ProcessorStatus pStatus = processorStatus(); File currentJobFile = getOldestJobFile(processingDir); this.getLogger().info(String.format("Processor: %s, current job: %s", pStatus, currentJobFile)); // A job is already being processed if (null != currentJobFile) { /* * A job is processed by a live Processor -> quit now. */ if (pStatus.equals(DequeueCronJob.ProcessorStatus.ALIVE)) { if (this.getLogger().isDebugEnabled()) { this.getLogger().debug(String.format("Active job \"%s\" in queue \"%s\", stopping", currentJobFile, queueDir)); } return; } else { /* * A job was processed, but the Processor is dead. * Move job tot error-folder. Clean processing folder. */ this.getLogger().warn(String.format("Stale job \"%s\" in queue \"%s\", cancelling job and stopping", currentJobFile, queueDir)); moveFileTo(currentJobFile, new File(errorDir, currentJobFile.getName())); FileUtils.cleanDirectory(processingDir); return; } } else { // No job being processed. File jobFile = getOldestJobFile(inDir); if (jobFile != null) { String jobFileName = jobFile.getName(); File currentJob = new File(processingDir, jobFileName); try { writeProcessorStatus(jobFileName, new DateTime(), 0, 0); if (this.getLogger().isDebugEnabled()) { this.getLogger().debug(String.format("Processing job \"%s\" in queue \"%s\"", jobFileName, queueDir)); } moveFileTo(jobFile, currentJob); this.getLogger().debug(String.format("Moved job \"%s\" to \"%s\"", jobFile, currentJob)); processCurrentJob(processingDir, currentJob); finishUpJob(processingDir, outDir, currentJob); } catch (IOException e) { if (this.getLogger().isErrorEnabled()) { this.getLogger().error("Error processing job \"" + jobFileName + "\"", e); } moveFileTo(currentJob, new File(errorDir, jobFileName)); String stackTrace = ExceptionUtils.getFullStackTrace(e); FileUtils.writeStringToFile(new File(errorDir, FilenameUtils.removeExtension(jobFileName) + ".txt"), stackTrace, "UTF-8"); } finally { FileUtils.cleanDirectory(processingDir); deleteProcessorStatus(); } } else { if (this.getLogger().isDebugEnabled()) { this.getLogger().debug("No job, stopping"); } } } } /** * Return NONE (No processor), ALIVE (Processor still active) or DEAD * (Processor hasn't updated status file for too long). * * @return ProcessorStatus: NONE, ALIVE or DEAD. */ private synchronized ProcessorStatus processorStatus() { File statusFile = new File(this.queuePath, PROCESSOR_STATUS_FILE); if (!statusFile.exists()) { return DequeueCronJob.ProcessorStatus.NONE; } else { long lastModified = statusFile.lastModified(); if (System.currentTimeMillis() - lastModified > PROCESSOR_STATUS_FILE_STALE) { return DequeueCronJob.ProcessorStatus.DEAD; } else { return DequeueCronJob.ProcessorStatus.ALIVE; } } } /** * Main entrypoint for CronJob. * @param name */ @Override public void execute(String name) { if (this.getLogger().isDebugEnabled()) { this.getLogger().debug("CronJob " + name + " launched at " + new Date()); } try { processQueue(); } catch (IOException e) { throw new CascadingRuntimeException("CronJob " + name + " raised an exception.", e); } } /** * Classes used by XStream for loading the job-*.xml config files into. */ private class Task { /* <task id="task-*"> <uri>URI of task to be executed, f.i. "cocoon://bron/svb/incremental" or "http://localhost:8888/import/bwbng"</uri> </task> */ private String id; private String uri; public Task() { } } private class JobConfig { // <job name="job-name" created="date" max-concurrent="n">tasks...</job> private String name; private DateTime created; private Integer maxConcurrent; private Task[] tasks; public JobConfig() { } } }
Improved docs and a little code.
src/org/apache/cocoon/components/cron/DequeueCronJob.java
Improved docs and a little code.
<ide><path>rc/org/apache/cocoon/components/cron/DequeueCronJob.java <ide> import java.util.concurrent.Executors; <ide> import java.util.concurrent.Future; <ide> import java.util.concurrent.TimeUnit; <add>import java.util.concurrent.TimeoutException; <ide> import java.util.logging.Level; <ide> import java.util.logging.Logger; <ide> import java.util.zip.ZipEntry; <ide> <ide> /** <ide> * <del> * <add> * @author <a href="mailto:[email protected]">Huib Verweij</a> <ide> * @author <a href="mailto:[email protected]">Maarten Kroon</a> <del> * @author <a href="mailto:[email protected]">Huib Verweij</a> <ide> * <ide> * Execute jobs that are submitted to a queue. <ide> * <del> * A queue is a directory on disk that contains jobs. <del> * <del> * A job is a zipped directory containing meta-data describing the job and one <del> * or more smaller tasks that are part of the job. <del> * <del> * A queue has four directories, in, in-progress, out and error. 1 New jobs that <del> * are waiting to be processed are in "in". 2 The one job that is being executed <del> * is in "in-progress". 3 Finished jobs are moved to "out". 4 Jobs that could <del> * not be executed at all end up in "error". <add> * A queue is a directory on disk that contains jobs-to-be-executed in <add> * the "in" subdirectory. <add> * <add> * A job is a XML file containing meta-data describing the job and one <add> * or more smaller tasks that are part of the job. A task contains a URL <add> * that is 'resolved' when the task is executed. The output of the URL <add> * ends up in a task-{id}.xml file. Note that tasks are executed <add> * *** in random order ***. <add> * <add> * A queue has four directories: "in", "in-progress", "out" and "error". <add> * 1 New jobs that are waiting to be processed are in "in". <add> * 2 The one job that is being executed is in "in-progress". <add> * 3 Finished jobs are zipped. Job-file and task-output files end up in "out". <add> * 4 Jobs that could not be executed at all (or generated an error in <add> * this class)end up in "error". <ide> * <ide> * Execute this object (a "Processor") every n (micro)seconds using a Cocoon <ide> * Quartz job and it will process one job in a queue. Processing a job means <del> * unzipping the job.zip and starting a separate thread for each task in the <del> * job. Every thread is 'join'ed so there are no runaway processes. <del> * <del> * While executing, a Processor updates the file processor-status.xml every 10 <del> * seconds or so with the following info: <del> * <processor id="(OS?) process-id" started="dateTime" tasks="nr of tasks" <del> * tasks-completed="nr of completed tasks" task-started-at="time current task <del> * was started"/> <add> * moveing the job-*.xml file to "in-progress" and starting a separate thread <add> * for each task in the job, then waiting till all tasks have finished. <add> * <add> * While executing, a Processor updates the file Queue/processor-status.xml <add> * every 10 seconds or so with the following info: <add> * &lt;processor id="thread-id" started="dateTime" tasks="nr of tasks" <add> * tasks-completed="nr of completed tasks" /> <ide> * This file can be read in order to get an idea of the progress of the current <ide> * job. It also indicates whether the current job is being processed at all - if <ide> * the modified timestamp of the file is older than, say, a minute, it is <ide> * assumed the Processor/job has failed. <ide> * <del> * When a Processor starts there are a few possible scenarios: 1 another job is <del> * already being processed and that Processor is still alive -> quit. 2 there is <del> * no job to be processed -> quit. 3 there is no other Processor running but <del> * there's a job already being processed -> move job to "error"-directory, quit. <del> * 4 there is a job to be processed and no Processor active -> start processing <del> * new job. <del> * <del> * To submit a job, upload a XML called "job-*.xml", containing the following <del> * structure: <del> * <job name="test-job" created="20140613T11:45:00" max-concurrent="3"> <del> * <tasks> <del> * <task id="task-1"> <del> * <uri>http://localhost:8888/koop/front/queue-test?id=1</uri> <del> * </task> <del> * ... <del> * </tasks> <del> * </job> <del> * <add> * When a Processor starts there are a few possible scenarios: <add> * 1 another job is already being processed and that Processor is <add> * still alive -> quit. <add> * 2 there is no job to be processed -> quit. <add> * 3 there is no other Processor running but there's a job already <add> * being processed -> move job to "error"-directory, quit. <add> * 4 there is a job to be processed and no Processor active -> <add> * start processing a new job. <add> * <add> * To submit a job, place a XML file called "job-{id}.xml" in the "in"-directory, <add> * containing the following structure: <add> * &lt;job name="test-job" created="20140613T11:45:00" max-concurrent="3"> <add> * &lt;tasks> <add> * &lt;task id="task-1"> <add> * &lt;uri>http://localhost:8888/koop/front/queue-test?id=1&lt;/uri> <add> * &lt;/task> <add> * ... <add> * &lt;/tasks> <add> * &lt;/job> <add> * <add> * At the moment, the max-concurrent attribute is ignored and the maximum <add> * number of concurrent tasks is equal to the number of processors in the <add> * server. <add> * <add> * To add this cronjob to Cocoon add a trigger to the Quartzcomponent <add> * configuration and declare this component in the same sitemap. <add> * &lt;component <add> * class="org.apache.cocoon.components.cron.CocoonQuartzJobScheduler" <add> * logger="cron" <add> * role="org.apache.cocoon.components.cron.JobScheduler"> <add> * ..... <add> * &lt;trigger name="dequeue-job" <add> * target="org.apache.cocoon.components.cron.CronJob/dequeue" <add> * concurrent-runs="false"> <add> * &lt;cron>0/10 * * * * ?&lt;/cron> <add> * &lt;/trigger> <add> * &lt;/component> <add> * <add> * and <add> * <add> * &lt;component class="org.apache.cocoon.components.cron.DequeueCronJob" <add> * logger="cron.publish" <add> * role="org.apache.cocoon.components.cron.CronJob/dequeue"> <add> * &lt;queue-path>/tmp/LiDO-queue&lt;/queue-path> <add> * &lt;/component> <ide> */ <ide> public class DequeueCronJob extends ServiceableCronJob implements Configurable, ConfigurableCronJob { <ide> <ide> private static final String PROCESSOR_STATUS_FILE = "processor-status.xml"; <ide> private static final long PROCESSOR_STATUS_FILE_STALE = 60000; <ide> <del> private final String inDirName = "in"; <del> private final String processingDirName = "in-progress"; <del> private final String outDirName = "out"; <del> private final String errorDirName = "error"; <add> private static final String inDirName = "in"; <add> private static final String processingDirName = "in-progress"; <add> private static final String outDirName = "out"; <add> private static final String errorDirName = "error"; <ide> <ide> private File queuePath; <ide> private final long DONT_WAIT_TOO_LONG = 8000; <ide> <del> /** <del> * Zip contents of processingDir into file, named after currentJob, <del> * into outDir. <add> <add> /** <add> * Zip contents of processingDir into "{currentJob-name}.zip" into outDir. <add> * The zip contains a directory {currentJob-name}, all other files are in <add> * that directory. <ide> * <ide> * @param processingDir <ide> * @param outDir <ide> } <ide> } <ide> <add> <add> /** <add> * The object that runs a task. <add> */ <ide> private static class TaskRunner implements Callable { <ide> <ide> private final Task task; <ide> @Override <ide> public Object call() throws Exception { <ide> this.logger.info("Processing task " + task.id); <del>// Thread.sleep(4000); <add> Thread.sleep(4000); <ide> OutputStream os = new FileOutputStream(outputFile); <ide> processPipeline(task.uri, manager, logger, os); <ide> os.close(); <ide> <ide> } <ide> <del>// private ExecutorService executor = Executors.newFixedThreadPool(1); <add> <add> /** <add> * Process a job: add all tasks to ExecutorService, invokeAll tasks <add> * and wait until all tasks have finished. While waiting, update <add> * processor-status.xml. <add> * @param inDir Where all output files are stored. <add> * @param currentJob The current job file. <add> */ <ide> private void processCurrentJob(File inDir, File currentJob) { <ide> this.getLogger().info("Processing job " + currentJob.getAbsoluteFile()); <ide> <ide> <ide> int processors = Runtime.getRuntime().availableProcessors(); <ide> ExecutorService jobExecutor = Executors.newFixedThreadPool(processors); <del> this.getLogger().info("Max concurrent jobs = " + processors); <add> this.getLogger().debug("Max concurrent jobs = " + processors); <ide> <ide> Set<Callable<TaskRunner>> callables = new HashSet<Callable<TaskRunner>>(); <ide> <ide> <ide> for (Future<TaskRunner> future : futures) { <ide> try { <del> this.getLogger().info("future.get = " + future.get()); <add> future.get(500, TimeUnit.MILLISECONDS); <ide> completedTasks--; <del> writeProcessorStatus(jobConfig.name, jobStartedAt, totalTasks, completedTasks); <ide> } catch (ExecutionException ex) { <ide> Logger.getLogger(DequeueCronJob.class.getName()).log(Level.SEVERE, null, ex); <ide> completedTasks--; <add> } catch (TimeoutException ex) { <add> Logger.getLogger(DequeueCronJob.class.getName()).log(Level.SEVERE, null, ex); <add> } finally { <add> writeProcessorStatus(jobConfig.name, jobStartedAt, totalTasks, completedTasks); <ide> } <ide> } <ide> jobExecutor.shutdown();
Java
apache-2.0
d3fefc9e1a0a69443fd8f79dcf84708a606ac16d
0
nicolargo/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,ibinti/intellij-community,ernestp/consulo,FHannes/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,amith01994/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,izonder/intellij-community,wreckJ/intellij-community,semonte/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,apixandru/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,FHannes/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,kool79/intellij-community,FHannes/intellij-community,jagguli/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,signed/intellij-community,fnouama/intellij-community,FHannes/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,caot/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,robovm/robovm-studio,izonder/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,robovm/robovm-studio,SerCeMan/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,dslomov/intellij-community,samthor/intellij-community,samthor/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,asedunov/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,clumsy/intellij-community,samthor/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,caot/intellij-community,fitermay/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,allotria/intellij-community,FHannes/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,signed/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,caot/intellij-community,retomerz/intellij-community,kool79/intellij-community,diorcety/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,kdwink/intellij-community,adedayo/intellij-community,holmes/intellij-community,diorcety/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,vladmm/intellij-community,samthor/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,ernestp/consulo,Lekanich/intellij-community,caot/intellij-community,clumsy/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,signed/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,signed/intellij-community,fnouama/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,caot/intellij-community,ahb0327/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,hurricup/intellij-community,amith01994/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,izonder/intellij-community,da1z/intellij-community,fitermay/intellij-community,petteyg/intellij-community,petteyg/intellij-community,robovm/robovm-studio,caot/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,apixandru/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,holmes/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,apixandru/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,xfournet/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,slisson/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,semonte/intellij-community,allotria/intellij-community,da1z/intellij-community,diorcety/intellij-community,amith01994/intellij-community,signed/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,petteyg/intellij-community,semonte/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,vladmm/intellij-community,slisson/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,izonder/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,holmes/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,asedunov/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,retomerz/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,retomerz/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,caot/intellij-community,blademainer/intellij-community,amith01994/intellij-community,samthor/intellij-community,amith01994/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,kool79/intellij-community,allotria/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,da1z/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,holmes/intellij-community,adedayo/intellij-community,fitermay/intellij-community,jagguli/intellij-community,samthor/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,ernestp/consulo,ryano144/intellij-community,semonte/intellij-community,samthor/intellij-community,samthor/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,signed/intellij-community,pwoodworth/intellij-community,consulo/consulo,caot/intellij-community,retomerz/intellij-community,fnouama/intellij-community,kdwink/intellij-community,fnouama/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,signed/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,vladmm/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,consulo/consulo,izonder/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,semonte/intellij-community,consulo/consulo,samthor/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,adedayo/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,hurricup/intellij-community,slisson/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,holmes/intellij-community,kool79/intellij-community,wreckJ/intellij-community,ernestp/consulo,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,FHannes/intellij-community,holmes/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,signed/intellij-community,diorcety/intellij-community,kdwink/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,supersven/intellij-community,blademainer/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,fnouama/intellij-community,ernestp/consulo,alphafoobar/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,da1z/intellij-community,kool79/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,consulo/consulo,vladmm/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,kool79/intellij-community,kool79/intellij-community,hurricup/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,semonte/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,allotria/intellij-community,supersven/intellij-community,caot/intellij-community,mglukhikh/intellij-community,consulo/consulo,fitermay/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,asedunov/intellij-community,jagguli/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,allotria/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,signed/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,supersven/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,consulo/consulo,Lekanich/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,slisson/intellij-community,kool79/intellij-community,clumsy/intellij-community,diorcety/intellij-community,kool79/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,semonte/intellij-community,Distrotech/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,diorcety/intellij-community,tmpgit/intellij-community,holmes/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,slisson/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,caot/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,blademainer/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,slisson/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,fitermay/intellij-community,ryano144/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,diorcety/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,retomerz/intellij-community,apixandru/intellij-community,retomerz/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,ibinti/intellij-community,clumsy/intellij-community,FHannes/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,ibinti/intellij-community,signed/intellij-community,ibinti/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,ryano144/intellij-community,blademainer/intellij-community,dslomov/intellij-community,vladmm/intellij-community,clumsy/intellij-community,allotria/intellij-community,petteyg/intellij-community,kool79/intellij-community,samthor/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,retomerz/intellij-community,izonder/intellij-community,slisson/intellij-community,ernestp/consulo,petteyg/intellij-community,alphafoobar/intellij-community,signed/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,izonder/intellij-community,supersven/intellij-community,allotria/intellij-community,gnuhub/intellij-community,semonte/intellij-community,da1z/intellij-community,supersven/intellij-community,holmes/intellij-community,adedayo/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,asedunov/intellij-community,xfournet/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,allotria/intellij-community,akosyakov/intellij-community,semonte/intellij-community,izonder/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community
/* * Copyright 2000-2011 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.testFramework; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.impl.ProjectImpl; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.UserDataHolder; import com.intellij.psi.PsiElement; //import com.intellij.psi.impl.DocumentCommitThread; import com.intellij.psi.impl.source.tree.TreeElement; import com.intellij.util.Processor; import com.intellij.util.containers.Stack; import com.intellij.util.io.PersistentEnumerator; import com.intellij.util.ui.UIUtil; import gnu.trove.THashMap; import gnu.trove.THashSet; import gnu.trove.TObjectHashingStrategy; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.TestOnly; import javax.swing.*; import java.lang.ref.Reference; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; /** * User: cdr */ public class LeakHunter { private static final Map<Class, List<Field>> allFields = new THashMap<Class, List<Field>>(); private static List<Field> getAllFields(Class aClass) { List<Field> cached = allFields.get(aClass); if (cached == null) { Field[] declaredFields = aClass.getDeclaredFields(); cached =new ArrayList<Field>(declaredFields.length + 5); for (Field declaredField : declaredFields) { declaredField.setAccessible(true); cached.add(declaredField); } Class superclass = aClass.getSuperclass(); if (superclass != null) { for (Field sup : getAllFields(superclass)) { if (!cached.contains(sup)) { cached.add(sup); } } } allFields.put(aClass, cached); } return cached; } private static final Set<Object> visited = new THashSet<Object>(TObjectHashingStrategy.IDENTITY); private static class BackLink { private final Class aClass; private final Object value; private final Field field; private final BackLink backLink; private BackLink(Class aClass, Object value, Field field, BackLink backLink) { this.aClass = aClass; this.value = value; this.field = field; this.backLink = backLink; } } private static final Stack<BackLink> toVisit = new Stack<BackLink>(); private static void walkObjects(Processor<BackLink> leakProcessor, Class lookFor) { while (true) { if (toVisit.isEmpty()) return; BackLink backLink = toVisit.pop(); Object root = backLink.value; if (!visited.add(root)) continue; Class rootClass = backLink.aClass; List<Field> fields = getAllFields(rootClass); for (Field field : fields) { String fieldName = field.getName(); if (root instanceof Reference && "referent".equals(fieldName)) continue; // do not follow weak/soft refs Object value; try { value = field.get(root); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } if (value == null) continue; if (value instanceof PsiElement || value instanceof TreeElement) { int i = 0; } Class valueClass = value.getClass(); if (lookFor.isAssignableFrom(valueClass) && isReallyLeak(field, fieldName, value, valueClass)) { BackLink newBackLink = new BackLink(valueClass, value, field, backLink); leakProcessor.process(newBackLink); } else { BackLink newBackLink = new BackLink(valueClass, value, field, backLink); if (toFollow(valueClass)) { toVisit.push(newBackLink); } } } if (rootClass.isArray()) { if (toFollow(rootClass.getComponentType())) { try { for (Object o : (Object[])root) { if (o == null) continue; Class oClass = o.getClass(); toVisit.push(new BackLink(oClass, o, null, backLink)); } } catch (ClassCastException ignored) { } } } } } private static final Key<Boolean> IS_NOT_A_LEAK = Key.create("IS_NOT_A_LEAK"); public static void markAsNotALeak(UserDataHolder object) { object.putUserData(IS_NOT_A_LEAK, Boolean.TRUE); } //static { // markAsNotALeak(DocumentCommitThread.THE_POISON_PILL); //} private static boolean isReallyLeak(Field field, String fieldName, Object value, Class valueClass) { if (value instanceof UserDataHolder && ((UserDataHolder)value).getUserData(IS_NOT_A_LEAK) != null) return false; return true; } private static final Set<String> noFollowClasses = new THashSet<String>(); static { noFollowClasses.add("java.lang.Boolean"); noFollowClasses.add("java.lang.Byte"); noFollowClasses.add("java.lang.Class"); noFollowClasses.add("java.lang.Character"); noFollowClasses.add("java.lang.Double"); noFollowClasses.add("java.lang.Float"); noFollowClasses.add("java.lang.Integer"); noFollowClasses.add("java.lang.Long"); noFollowClasses.add("java.lang.Object"); noFollowClasses.add("java.lang.Short"); noFollowClasses.add("java.lang.String"); } private static boolean toFollow(Class oClass) { String name = oClass.getName(); return !noFollowClasses.contains(name); } private static final Key<Boolean> REPORTED_LEAKED = Key.create("REPORTED_LEAKED"); @TestOnly public static void checkProjectLeak(Object root) throws Exception { checkLeak(root, ProjectImpl.class); } @TestOnly public static void checkLeak(@NotNull Object root, @NotNull Class suspectClass) { if (SwingUtilities.isEventDispatchThread()) { UIUtil.dispatchAllInvocationEvents(); } else { UIUtil.pump(); } PersistentEnumerator.clearCacheForTests(); toVisit.clear(); visited.clear(); toVisit.push(new BackLink(root.getClass(), root, null,null)); try { walkObjects(new Processor<BackLink>() { @Override public boolean process(BackLink backLink) { UserDataHolder leaked = (UserDataHolder)backLink.value; if (leaked.getUserData(REPORTED_LEAKED) == null) { String place = leaked instanceof Project ? PlatformTestCase.getCreationPlace((Project)leaked) : ""; System.out.println("LEAK: hash: "+System.identityHashCode(leaked) + "; place: "+ place); while (backLink != null) { String valueStr; try { valueStr = String.valueOf(leaked); } catch (Exception e) { valueStr = "("+e.getMessage()+" while computing .toString())"; } System.out.println("-->"+backLink.field+"; Value: "+ valueStr +"; "+backLink.aClass); backLink = backLink.backLink; } System.out.println(";-----"); leaked.putUserData(REPORTED_LEAKED, Boolean.TRUE); throw new RuntimeException(); } return true; } }, suspectClass); } finally { visited.clear(); toVisit.clear(); } } }
platform/testFramework/src/com/intellij/testFramework/LeakHunter.java
/* * Copyright 2000-2011 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.testFramework; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.impl.ProjectImpl; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.UserDataHolder; import com.intellij.psi.PsiElement; //import com.intellij.psi.impl.DocumentCommitThread; import com.intellij.psi.impl.source.tree.TreeElement; import com.intellij.util.Processor; import com.intellij.util.containers.Stack; import com.intellij.util.io.PersistentEnumerator; import com.intellij.util.ui.UIUtil; import gnu.trove.THashMap; import gnu.trove.THashSet; import gnu.trove.TObjectHashingStrategy; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.TestOnly; import javax.swing.*; import java.lang.ref.Reference; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; /** * User: cdr */ public class LeakHunter { private static final Map<Class, List<Field>> allFields = new THashMap<Class, List<Field>>(); private static List<Field> getAllFields(Class aClass) { List<Field> cached = allFields.get(aClass); if (cached == null) { Field[] declaredFields = aClass.getDeclaredFields(); cached =new ArrayList<Field>(declaredFields.length + 5); for (Field declaredField : declaredFields) { declaredField.setAccessible(true); cached.add(declaredField); } Class superclass = aClass.getSuperclass(); if (superclass != null) { for (Field sup : getAllFields(superclass)) { if (!cached.contains(sup)) { cached.add(sup); } } } allFields.put(aClass, cached); } return cached; } private static final Set<Object> visited = new THashSet<Object>(TObjectHashingStrategy.IDENTITY); private static class BackLink { private final Class aClass; private final Object value; private final Field field; private final BackLink backLink; private BackLink(Class aClass, Object value, Field field, BackLink backLink) { this.aClass = aClass; this.value = value; this.field = field; this.backLink = backLink; } } private static final Stack<BackLink> toVisit = new Stack<BackLink>(); private static void walkObjects(Processor<BackLink> leakProcessor, Class lookFor) { while (true) { if (toVisit.isEmpty()) return; BackLink backLink = toVisit.pop(); Object root = backLink.value; if (!visited.add(root)) continue; Class rootClass = backLink.aClass; List<Field> fields = getAllFields(rootClass); for (Field field : fields) { String fieldName = field.getName(); if (root instanceof Reference && "referent".equals(fieldName)) continue; // do not follow weak/soft refs Object value; try { value = field.get(root); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } if (value == null) continue; if (value instanceof PsiElement || value instanceof TreeElement) { int i = 0; } Class valueClass = value.getClass(); if (lookFor.isAssignableFrom(valueClass) && isReallyLeak(field, fieldName, value, valueClass)) { BackLink newBackLink = new BackLink(valueClass, value, field, backLink); leakProcessor.process(newBackLink); } else { BackLink newBackLink = new BackLink(valueClass, value, field, backLink); if (toFollow(valueClass)) { toVisit.push(newBackLink); } } } if (rootClass.isArray()) { if (toFollow(rootClass.getComponentType())) { try { for (Object o : (Object[])root) { if (o == null) continue; Class oClass = o.getClass(); toVisit.push(new BackLink(oClass, o, null, backLink)); } } catch (ClassCastException ignored) { } } } } } private static final Key<Boolean> IS_NOT_A_LEAK = Key.create("IS_NOT_A_LEAK"); public static void markAsNotALeak(UserDataHolder object) { object.putUserData(IS_NOT_A_LEAK, Boolean.TRUE); } //static { // markAsNotALeak(DocumentCommitThread.THE_POISON_PILL); //} private static boolean isReallyLeak(Field field, String fieldName, Object value, Class valueClass) { if (value instanceof UserDataHolder && ((UserDataHolder)value).getUserData(IS_NOT_A_LEAK) != null) return false; return true; } private static final Set<String> noFollowClasses = new THashSet<String>(); static { noFollowClasses.add("java.lang.Boolean"); noFollowClasses.add("java.lang.Byte"); noFollowClasses.add("java.lang.Class"); noFollowClasses.add("java.lang.Character"); noFollowClasses.add("java.lang.Double"); noFollowClasses.add("java.lang.Float"); noFollowClasses.add("java.lang.Integer"); noFollowClasses.add("java.lang.Long"); noFollowClasses.add("java.lang.Object"); noFollowClasses.add("java.lang.Short"); noFollowClasses.add("java.lang.String"); } private static boolean toFollow(Class oClass) { String name = oClass.getName(); return !noFollowClasses.contains(name); } private static final Key<Boolean> REPORTED_LEAKED = Key.create("REPORTED_LEAKED"); @TestOnly public static void checkProjectLeak(Object root) throws Exception { checkLeak(root, ProjectImpl.class); } @TestOnly public static void checkLeak(@NotNull Object root, @NotNull Class suspectClass) { if (SwingUtilities.isEventDispatchThread()) { UIUtil.dispatchAllInvocationEvents(); } else { UIUtil.pump(); } PersistentEnumerator.clearCacheForTests(); toVisit.clear(); visited.clear(); toVisit.push(new BackLink(root.getClass(), root, null,null)); try { walkObjects(new Processor<BackLink>() { @Override public boolean process(BackLink backLink) { UserDataHolder leaked = (UserDataHolder)backLink.value; if (leaked.getUserData(REPORTED_LEAKED) == null) { String place = leaked instanceof Project ? PlatformTestCase.getCreationPlace((Project)leaked) : ""; System.out.println("LEAK: hash: "+System.identityHashCode(leaked) + "; place: "+ place); while (backLink != null) { System.out.println("-->"+backLink.field+"; Value: "+backLink.value+"; "+backLink.aClass); backLink = backLink.backLink; } System.out.println(";-----"); leaked.putUserData(REPORTED_LEAKED, Boolean.TRUE); throw new RuntimeException(); } return true; } }, suspectClass); } finally { visited.clear(); toVisit.clear(); } } }
ignore exceptions while print diag
platform/testFramework/src/com/intellij/testFramework/LeakHunter.java
ignore exceptions while print diag
<ide><path>latform/testFramework/src/com/intellij/testFramework/LeakHunter.java <ide> String place = leaked instanceof Project ? PlatformTestCase.getCreationPlace((Project)leaked) : ""; <ide> System.out.println("LEAK: hash: "+System.identityHashCode(leaked) + "; place: "+ place); <ide> while (backLink != null) { <del> System.out.println("-->"+backLink.field+"; Value: "+backLink.value+"; "+backLink.aClass); <add> String valueStr; <add> try { <add> valueStr = String.valueOf(leaked); <add> } <add> catch (Exception e) { <add> valueStr = "("+e.getMessage()+" while computing .toString())"; <add> } <add> System.out.println("-->"+backLink.field+"; Value: "+ valueStr +"; "+backLink.aClass); <ide> backLink = backLink.backLink; <ide> } <ide> System.out.println(";-----");
Java
apache-2.0
8145cdc615c79e4d44a7143030297ce7c493179d
0
willkara/sakai,joserabal/sakai,frasese/sakai,joserabal/sakai,rodriguezdevera/sakai,ouit0408/sakai,willkara/sakai,OpenCollabZA/sakai,zqian/sakai,rodriguezdevera/sakai,frasese/sakai,OpenCollabZA/sakai,joserabal/sakai,zqian/sakai,willkara/sakai,Fudan-University/sakai,zqian/sakai,rodriguezdevera/sakai,rodriguezdevera/sakai,OpenCollabZA/sakai,OpenCollabZA/sakai,willkara/sakai,ouit0408/sakai,Fudan-University/sakai,Fudan-University/sakai,zqian/sakai,rodriguezdevera/sakai,ouit0408/sakai,Fudan-University/sakai,Fudan-University/sakai,willkara/sakai,OpenCollabZA/sakai,joserabal/sakai,OpenCollabZA/sakai,frasese/sakai,ouit0408/sakai,willkara/sakai,frasese/sakai,frasese/sakai,ouit0408/sakai,OpenCollabZA/sakai,joserabal/sakai,ouit0408/sakai,joserabal/sakai,zqian/sakai,willkara/sakai,OpenCollabZA/sakai,Fudan-University/sakai,frasese/sakai,zqian/sakai,Fudan-University/sakai,zqian/sakai,ouit0408/sakai,Fudan-University/sakai,willkara/sakai,ouit0408/sakai,frasese/sakai,joserabal/sakai,rodriguezdevera/sakai,joserabal/sakai,frasese/sakai,rodriguezdevera/sakai,zqian/sakai,rodriguezdevera/sakai
/********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2007, 2008 The Sakai Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.calendar.impl.readers; import java.io.InputStream; import java.text.DateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import net.fortuna.ical4j.data.CalendarBuilder; import net.fortuna.ical4j.model.Component; import net.fortuna.ical4j.model.component.VEvent; import net.fortuna.ical4j.model.property.DateProperty; import net.fortuna.ical4j.util.CompatibilityHints; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sakaiproject.calendar.impl.GenericCalendarImporter; import org.sakaiproject.exception.ImportException; import org.sakaiproject.time.api.TimeBreakdown; import org.sakaiproject.util.ResourceLoader; /** * This class parses an import file from iCalendar. */ public class IcalendarReader extends Reader { private ResourceLoader rb = new ResourceLoader("calendar"); private static Logger M_log = LoggerFactory.getLogger(IcalendarReader.class); private Map<String, String> defaultHeaderMap = getDefaultColumnMap(); private static final String TITLE_PROPERTY_NAME = "Summary"; private static final String CONTACT_SECTION_HEADER = "Contacts"; private static final String TODO_SECTION_HEADER = "Todos"; private static final String EVENT_SECTION_HEADER = "Events"; /** * Default constructor */ public IcalendarReader() { super(); } /* (non-Javadoc) * @see org.sakaiproject.tool.calendar.ImportReader#importStreamFromDelimitedFile(java.io.InputStream, org.sakaiproject.tool.calendar.ImportReader.ReaderImportRowHandler) */ public void importStreamFromDelimitedFile( InputStream stream, ReaderImportRowHandler handler) throws ImportException//, IOException, ParserException { try { ColumnHeader columnDescriptionArray[] = null; String descriptionColumns[] = {"Summary","Description","Start Date","Start Time","Duration","Location"}; int lineNumber = 1; String durationformat =""; String requireValues = ""; // column map stuff trimLeadingTrailingQuotes(descriptionColumns); columnDescriptionArray = buildColumnDescriptionArray(descriptionColumns); // enable "relaxed parsing"; read file using LF instead of CRLF CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_UNFOLDING, true); CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING, true); CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_OUTLOOK_COMPATIBILITY, true); CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_VALIDATION, true); CalendarBuilder builder = new CalendarBuilder(); net.fortuna.ical4j.model.Calendar calendar = builder.build(stream); for (Iterator i = calendar.getComponents("VEVENT").iterator(); i.hasNext();) { Component component = (Component) i.next(); // Find event duration DateProperty dtstartdate; DateProperty dtenddate; if(component instanceof VEvent){ VEvent vEvent = (VEvent) component; dtstartdate = vEvent.getStartDate(); dtenddate = vEvent.getEndDate(true); }else{ dtstartdate = (DateProperty) component.getProperty("DTSTART"); dtenddate = (DateProperty) component.getProperty("DTEND"); } if ( component.getProperty("SUMMARY") == null ) { M_log.warn("IcalendarReader: SUMMARY is required; event not imported"); continue; } String summary = component.getProperty("SUMMARY").getValue(); if ( component.getProperty("RRULE") != null ) { M_log.warn("IcalendarReader: Re-occurring events not supported: " + summary ); continue; } else if (dtstartdate == null || dtenddate == null ) { M_log.warn("IcalendarReader: DTSTART/DTEND required: " + summary ); continue; } int durationsecs = (int) ((dtenddate.getDate().getTime() - dtstartdate.getDate().getTime()) / 1000); int durationminutes = (durationsecs/60) % 60; int durationhours = (durationsecs/(60*60)) % 24; // Put duration in proper format (hh:mm or mm) if less than 1 hour if (durationminutes < 10) { durationformat = "0"+durationminutes; } else { durationformat = ""+durationminutes; } if (durationhours != 0) { durationformat = durationhours+":"+durationformat; } String description = ""; if ( component.getProperty("DESCRIPTION") != null ) description = component.getProperty("DESCRIPTION").getValue(); String location = ""; if (component.getProperty("LOCATION") != null) location = component.getProperty("LOCATION").getValue(); String columns[] = {component.getProperty("SUMMARY").getValue(), description, DateFormat.getDateInstance(DateFormat.SHORT, rb.getLocale()).format(dtstartdate.getDate()), DateFormat.getTimeInstance(DateFormat.SHORT, rb.getLocale()).format(dtstartdate.getDate()), durationformat, location}; // Remove trailing/leading quotes from all columns. //trimLeadingTrailingQuotes(columns); handler.handleRow( processLine( columnDescriptionArray, lineNumber, columns)); lineNumber++; } // end for } catch (Exception e) { M_log.warn(".importSteamFromDelimitedFile(): ", e); } } // end importStreamFromDelimitedFile /* (non-Javadoc) * @see org.sakaiproject.tool.calendar.schedimportreaders.Reader#filterEvents(java.util.List, java.lang.String[]) */ public List filterEvents(List events, String[] customFieldNames) throws ImportException { Iterator it = events.iterator(); int lineNumber = 1; // // Convert the date/time fields as they appear in the Outlook import to // be a synthesized start/end timerange. // while ( it.hasNext() ) { Map eventProperties = (Map)it.next(); Date startTime = (Date) eventProperties.get(defaultHeaderMap.get(GenericCalendarImporter.START_TIME_DEFAULT_COLUMN_HEADER)); TimeBreakdown startTimeBreakdown = null; if ( startTime != null ) { // if the source time zone were known, this would be // a good place to set it: startCal.setTimeZone() GregorianCalendar startCal = new GregorianCalendar(); startCal.setTimeInMillis( startTime.getTime() ); startTimeBreakdown = getTimeService().newTimeBreakdown( 0, 0, 0, startCal.get(Calendar.HOUR_OF_DAY), startCal.get(Calendar.MINUTE), startCal.get(Calendar.SECOND), 0 ); } else { Integer line = Integer.valueOf(lineNumber); String msg = (String)rb.getFormattedMessage("err_no_stime_on", new Object[]{line}); throw new ImportException( msg ); } Integer durationInMinutes = (Integer)eventProperties.get(defaultHeaderMap.get(GenericCalendarImporter.DURATION_DEFAULT_COLUMN_HEADER)); if ( durationInMinutes == null ) { Integer line = Integer.valueOf(lineNumber); String msg = (String)rb.getFormattedMessage("err_no_dtime_on", new Object[]{line}); throw new ImportException( msg ); } Date endTime = new Date( startTime.getTime() + (durationInMinutes.longValue() * 60 * 1000) ); TimeBreakdown endTimeBreakdown = null; if ( endTime != null ) { // if the source time zone were known, this would be // a good place to set it: endCal.setTimeZone() GregorianCalendar endCal = new GregorianCalendar(); endCal.setTimeInMillis( endTime.getTime() ); endTimeBreakdown = getTimeService().newTimeBreakdown( 0, 0, 0, endCal.get(Calendar.HOUR_OF_DAY), endCal.get(Calendar.MINUTE), endCal.get(Calendar.SECOND), 0 ); } Date startDate = (Date) eventProperties.get(defaultHeaderMap.get(GenericCalendarImporter.DATE_DEFAULT_COLUMN_HEADER)); // if the source time zone were known, this would be // a good place to set it: startCal.setTimeZone() GregorianCalendar startCal = new GregorianCalendar(); if ( startDate != null ) startCal.setTimeInMillis( startDate.getTime() ); startTimeBreakdown.setYear( startCal.get(Calendar.YEAR) ); startTimeBreakdown.setMonth( startCal.get(Calendar.MONTH)+1 ); startTimeBreakdown.setDay( startCal.get(Calendar.DAY_OF_MONTH) ); endTimeBreakdown.setYear( startCal.get(Calendar.YEAR) ); endTimeBreakdown.setMonth( startCal.get(Calendar.MONTH)+1 ); endTimeBreakdown.setDay( startCal.get(Calendar.DAY_OF_MONTH) ); eventProperties.put( GenericCalendarImporter.ACTUAL_TIMERANGE, getTimeService().newTimeRange( getTimeService().newTimeLocal(startTimeBreakdown), getTimeService().newTimeLocal(endTimeBreakdown), true, false)); lineNumber++; } return events; } /* (non-Javadoc) * @see org.sakaiproject.tool.calendar.schedimportreaders.Reader#getDefaultColumnMap() */ public Map<String, String> getDefaultColumnMap() { Map<String, String> columnHeaderMap = new HashMap<String, String>(); columnHeaderMap.put(GenericCalendarImporter.TITLE_DEFAULT_COLUMN_HEADER, TITLE_PROPERTY_NAME); columnHeaderMap.put(GenericCalendarImporter.DESCRIPTION_DEFAULT_COLUMN_HEADER, GenericCalendarImporter.DESCRIPTION_PROPERTY_NAME); columnHeaderMap.put(GenericCalendarImporter.DATE_DEFAULT_COLUMN_HEADER, GenericCalendarImporter.DATE_PROPERTY_NAME); columnHeaderMap.put(GenericCalendarImporter.START_TIME_DEFAULT_COLUMN_HEADER, GenericCalendarImporter.START_TIME_PROPERTY_NAME); columnHeaderMap.put(GenericCalendarImporter.DURATION_DEFAULT_COLUMN_HEADER, GenericCalendarImporter.DURATION_PROPERTY_NAME); //columnHeaderMap.put(ITEM_HEADER, GenericCalendarImporter.ITEM_TYPE_PROPERTY_NAME); columnHeaderMap.put(GenericCalendarImporter.LOCATION_DEFAULT_COLUMN_HEADER, GenericCalendarImporter.LOCATION_PROPERTY_NAME); return columnHeaderMap; } }
calendar/calendar-impl/impl/src/java/org/sakaiproject/calendar/impl/readers/IcalendarReader.java
/********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2007, 2008 The Sakai Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.calendar.impl.readers; import java.io.InputStream; import java.text.DateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import net.fortuna.ical4j.data.CalendarBuilder; import net.fortuna.ical4j.model.Component; import net.fortuna.ical4j.model.component.VEvent; import net.fortuna.ical4j.model.property.DateProperty; import net.fortuna.ical4j.util.CompatibilityHints; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sakaiproject.calendar.impl.GenericCalendarImporter; import org.sakaiproject.exception.ImportException; import org.sakaiproject.time.api.TimeBreakdown; import org.sakaiproject.util.ResourceLoader; /** * This class parses an import file from iCalendar. */ public class IcalendarReader extends Reader { private ResourceLoader rb = new ResourceLoader("calendar"); private static Logger M_log = LoggerFactory.getLogger(IcalendarReader.class); private Map<String, String> defaultHeaderMap = getDefaultColumnMap(); private static final String CONTACT_SECTION_HEADER = "Contacts"; private static final String TODO_SECTION_HEADER = "Todos"; private static final String EVENT_SECTION_HEADER = "Events"; /** * Default constructor */ public IcalendarReader() { super(); } /* (non-Javadoc) * @see org.sakaiproject.tool.calendar.ImportReader#importStreamFromDelimitedFile(java.io.InputStream, org.sakaiproject.tool.calendar.ImportReader.ReaderImportRowHandler) */ public void importStreamFromDelimitedFile( InputStream stream, ReaderImportRowHandler handler) throws ImportException//, IOException, ParserException { try { ColumnHeader columnDescriptionArray[] = null; String descriptionColumns[] = {"Summary","Description","Start Date","Start Time","Duration","Location"}; int lineNumber = 1; String durationformat =""; String requireValues = ""; // column map stuff trimLeadingTrailingQuotes(descriptionColumns); columnDescriptionArray = buildColumnDescriptionArray(descriptionColumns); // enable "relaxed parsing"; read file using LF instead of CRLF CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_UNFOLDING, true); CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING, true); CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_OUTLOOK_COMPATIBILITY, true); CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_VALIDATION, true); CalendarBuilder builder = new CalendarBuilder(); net.fortuna.ical4j.model.Calendar calendar = builder.build(stream); for (Iterator i = calendar.getComponents("VEVENT").iterator(); i.hasNext();) { Component component = (Component) i.next(); // Find event duration DateProperty dtstartdate; DateProperty dtenddate; if(component instanceof VEvent){ VEvent vEvent = (VEvent) component; dtstartdate = vEvent.getStartDate(); dtenddate = vEvent.getEndDate(true); }else{ dtstartdate = (DateProperty) component.getProperty("DTSTART"); dtenddate = (DateProperty) component.getProperty("DTEND"); } if ( component.getProperty("SUMMARY") == null ) { M_log.warn("IcalendarReader: SUMMARY is required; event not imported"); continue; } String summary = component.getProperty("SUMMARY").getValue(); if ( component.getProperty("RRULE") != null ) { M_log.warn("IcalendarReader: Re-occuring events not supported: " + summary ); continue; } else if (dtstartdate == null || dtenddate == null ) { M_log.warn("IcalendarReader: DTSTART/DTEND required: " + summary ); continue; } int durationsecs = (int) ((dtenddate.getDate().getTime() - dtstartdate.getDate().getTime()) / 1000); int durationminutes = (durationsecs/60) % 60; int durationhours = (durationsecs/(60*60)) % 24; // Put duration in proper format (hh:mm or mm) if less than 1 hour if (durationminutes < 10) { durationformat = "0"+durationminutes; } else { durationformat = ""+durationminutes; } if (durationhours != 0) { durationformat = durationhours+":"+durationformat; } String description = ""; if ( component.getProperty("DESCRIPTION") != null ) description = component.getProperty("DESCRIPTION").getValue(); String location = ""; if (component.getProperty("LOCATION") != null) location = component.getProperty("LOCATION").getValue(); String columns[] = {component.getProperty("SUMMARY").getValue(), description, DateFormat.getDateInstance(DateFormat.SHORT, rb.getLocale()).format(dtstartdate.getDate()), DateFormat.getTimeInstance(DateFormat.SHORT, rb.getLocale()).format(dtstartdate.getDate()), durationformat, location}; // Remove trailing/leading quotes from all columns. //trimLeadingTrailingQuotes(columns); handler.handleRow( processLine( columnDescriptionArray, lineNumber, columns)); lineNumber++; } // end for } catch (Exception e) { M_log.warn(".importSteamFromDelimitedFile(): ", e); } } // end importStreamFromDelimitedFile /* (non-Javadoc) * @see org.sakaiproject.tool.calendar.schedimportreaders.Reader#filterEvents(java.util.List, java.lang.String[]) */ public List filterEvents(List events, String[] customFieldNames) throws ImportException { Iterator it = events.iterator(); int lineNumber = 1; // // Convert the date/time fields as they appear in the Outlook import to // be a synthesized start/end timerange. // while ( it.hasNext() ) { Map eventProperties = (Map)it.next(); Date startTime = (Date) eventProperties.get(defaultHeaderMap.get(GenericCalendarImporter.START_TIME_DEFAULT_COLUMN_HEADER)); TimeBreakdown startTimeBreakdown = null; if ( startTime != null ) { // if the source time zone were known, this would be // a good place to set it: startCal.setTimeZone() GregorianCalendar startCal = new GregorianCalendar(); startCal.setTimeInMillis( startTime.getTime() ); startTimeBreakdown = getTimeService().newTimeBreakdown( 0, 0, 0, startCal.get(Calendar.HOUR_OF_DAY), startCal.get(Calendar.MINUTE), startCal.get(Calendar.SECOND), 0 ); } else { Integer line = Integer.valueOf(lineNumber); String msg = (String)rb.getFormattedMessage("err_no_stime_on", new Object[]{line}); throw new ImportException( msg ); } Integer durationInMinutes = (Integer)eventProperties.get(defaultHeaderMap.get(GenericCalendarImporter.DURATION_DEFAULT_COLUMN_HEADER)); if ( durationInMinutes == null ) { Integer line = Integer.valueOf(lineNumber); String msg = (String)rb.getFormattedMessage("err_no_dtime_on", new Object[]{line}); throw new ImportException( msg ); } Date endTime = new Date( startTime.getTime() + (durationInMinutes.longValue() * 60 * 1000) ); TimeBreakdown endTimeBreakdown = null; if ( endTime != null ) { // if the source time zone were known, this would be // a good place to set it: endCal.setTimeZone() GregorianCalendar endCal = new GregorianCalendar(); endCal.setTimeInMillis( endTime.getTime() ); endTimeBreakdown = getTimeService().newTimeBreakdown( 0, 0, 0, endCal.get(Calendar.HOUR_OF_DAY), endCal.get(Calendar.MINUTE), endCal.get(Calendar.SECOND), 0 ); } Date startDate = (Date) eventProperties.get(defaultHeaderMap.get(GenericCalendarImporter.DATE_DEFAULT_COLUMN_HEADER)); // if the source time zone were known, this would be // a good place to set it: startCal.setTimeZone() GregorianCalendar startCal = new GregorianCalendar(); if ( startDate != null ) startCal.setTimeInMillis( startDate.getTime() ); startTimeBreakdown.setYear( startCal.get(Calendar.YEAR) ); startTimeBreakdown.setMonth( startCal.get(Calendar.MONTH)+1 ); startTimeBreakdown.setDay( startCal.get(Calendar.DAY_OF_MONTH) ); endTimeBreakdown.setYear( startCal.get(Calendar.YEAR) ); endTimeBreakdown.setMonth( startCal.get(Calendar.MONTH)+1 ); endTimeBreakdown.setDay( startCal.get(Calendar.DAY_OF_MONTH) ); eventProperties.put( GenericCalendarImporter.ACTUAL_TIMERANGE, getTimeService().newTimeRange( getTimeService().newTimeLocal(startTimeBreakdown), getTimeService().newTimeLocal(endTimeBreakdown), true, false)); lineNumber++; } return events; } /* (non-Javadoc) * @see org.sakaiproject.tool.calendar.schedimportreaders.Reader#getDefaultColumnMap() */ public Map<String, String> getDefaultColumnMap() { Map<String, String> columnHeaderMap = new HashMap<String, String>(); columnHeaderMap.put(GenericCalendarImporter.TITLE_DEFAULT_COLUMN_HEADER, GenericCalendarImporter.TITLE_PROPERTY_NAME); columnHeaderMap.put(GenericCalendarImporter.DESCRIPTION_DEFAULT_COLUMN_HEADER, GenericCalendarImporter.DESCRIPTION_PROPERTY_NAME); columnHeaderMap.put(GenericCalendarImporter.DATE_DEFAULT_COLUMN_HEADER, GenericCalendarImporter.DATE_PROPERTY_NAME); columnHeaderMap.put(GenericCalendarImporter.START_TIME_DEFAULT_COLUMN_HEADER, GenericCalendarImporter.START_TIME_PROPERTY_NAME); columnHeaderMap.put(GenericCalendarImporter.DURATION_DEFAULT_COLUMN_HEADER, GenericCalendarImporter.DURATION_PROPERTY_NAME); //columnHeaderMap.put(ITEM_HEADER, GenericCalendarImporter.ITEM_TYPE_PROPERTY_NAME); columnHeaderMap.put(GenericCalendarImporter.LOCATION_DEFAULT_COLUMN_HEADER, GenericCalendarImporter.LOCATION_PROPERTY_NAME); return columnHeaderMap; } }
SAK-30877 Get activity title from external calendars (#2463)
calendar/calendar-impl/impl/src/java/org/sakaiproject/calendar/impl/readers/IcalendarReader.java
SAK-30877 Get activity title from external calendars (#2463)
<ide><path>alendar/calendar-impl/impl/src/java/org/sakaiproject/calendar/impl/readers/IcalendarReader.java <ide> private static Logger M_log = LoggerFactory.getLogger(IcalendarReader.class); <ide> private Map<String, String> defaultHeaderMap = getDefaultColumnMap(); <ide> <add> private static final String TITLE_PROPERTY_NAME = "Summary"; <ide> private static final String CONTACT_SECTION_HEADER = "Contacts"; <ide> private static final String TODO_SECTION_HEADER = "Todos"; <ide> private static final String EVENT_SECTION_HEADER = "Events"; <ide> <ide> if ( component.getProperty("RRULE") != null ) <ide> { <del> M_log.warn("IcalendarReader: Re-occuring events not supported: " + summary ); <add> M_log.warn("IcalendarReader: Re-occurring events not supported: " + summary ); <ide> continue; <ide> } <ide> else if (dtstartdate == null || dtenddate == null ) <ide> { <ide> Map<String, String> columnHeaderMap = new HashMap<String, String>(); <ide> <del> columnHeaderMap.put(GenericCalendarImporter.TITLE_DEFAULT_COLUMN_HEADER, GenericCalendarImporter.TITLE_PROPERTY_NAME); <add> columnHeaderMap.put(GenericCalendarImporter.TITLE_DEFAULT_COLUMN_HEADER, TITLE_PROPERTY_NAME); <ide> columnHeaderMap.put(GenericCalendarImporter.DESCRIPTION_DEFAULT_COLUMN_HEADER, GenericCalendarImporter.DESCRIPTION_PROPERTY_NAME); <ide> columnHeaderMap.put(GenericCalendarImporter.DATE_DEFAULT_COLUMN_HEADER, GenericCalendarImporter.DATE_PROPERTY_NAME); <ide> columnHeaderMap.put(GenericCalendarImporter.START_TIME_DEFAULT_COLUMN_HEADER, GenericCalendarImporter.START_TIME_PROPERTY_NAME);
Java
mpl-2.0
35593a9b49c6be3d0c8ae3d5f8bf8f52e1d294a8
0
choreos/choreos_middleware,choreos/enactment_engine,choreos/enactment_engine,choreos/choreos_middleware,choreos/enactment_engine,choreos/enactment_engine,choreos/choreos_middleware
package eu.choreos.monitoring.platform.daemon; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.*; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import com.sun.org.apache.bcel.internal.generic.NEW; import eu.choreos.platform.utils.CommandRuntimeException; import eu.choreos.platform.utils.ShellHandler; public class ThresholdTest { Threshold threshold; @Before public void setUp() throws CommandRuntimeException { threshold = new Threshold("Test", Threshold.MAX, 3); } @Test public void upperBoundarySurpassed() { assertTrue(threshold.wasSurpassed(4.0)); } @Test public void upperBoundaryNotSurpassed() { assertFalse(threshold.wasSurpassed(2.0)); } @Test public void lowerBoundarySurpassed() { threshold = new Threshold("Test", Threshold.MIN, 3); assertTrue(threshold.wasSurpassed(2.0)); } @Test public void lowerBoundaryNotSurpassed() { threshold = new Threshold("Test", Threshold.MIN, 3); assertFalse(threshold.wasSurpassed(4.0)); } @Test public void testToString() { threshold.wasSurpassed(4.0); assertEquals("Triggered: Test <= 3.0. Measured: 4.0", threshold.toString()); } }
ThresholdEvaluationDaemon/src/test/java/eu/choreos/monitoring/platform/daemon/ThresholdTest.java
package eu.choreos.monitoring.platform.daemon; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.*; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import com.sun.org.apache.bcel.internal.generic.NEW; import eu.choreos.platform.utils.CommandRuntimeException; import eu.choreos.platform.utils.ShellHandler; public class ThresholdTest { Threshold threshold; String pwd; String hostname; private ShellHandler shellHandler = new ShellHandler(); @Before public void setUp() throws CommandRuntimeException { hostname = shellHandler.runLocalCommand("/bin/bash /tmp/hostname.sh") .replace("\n", ""); pwd = shellHandler.runLocalCommand("pwd").replace("\n", ""); threshold = new Threshold("Test", Threshold.MAX, 3); } @Test public void upperBoundarySurpassed() { assertTrue(threshold.wasSurpassed(4.0)); } @Test public void upperBoundaryNotSurpassed() { assertFalse(threshold.wasSurpassed(2.0)); } @Test public void lowerBoundarySurpassed() { threshold = new Threshold("Test", Threshold.MIN, 3); assertTrue(threshold.wasSurpassed(2.0)); } @Test public void lowerBoundaryNotSurpassed() { threshold = new Threshold("Test", Threshold.MIN, 3); assertFalse(threshold.wasSurpassed(4.0)); } @Test public void testToString() { threshold.wasSurpassed(4.0); assertEquals("Triggered: Test <= 3.0. Measured: 4.0", threshold.toString()); } }
Removed unnecessary invocation of shell scripts in test class
ThresholdEvaluationDaemon/src/test/java/eu/choreos/monitoring/platform/daemon/ThresholdTest.java
Removed unnecessary invocation of shell scripts in test class
<ide><path>hresholdEvaluationDaemon/src/test/java/eu/choreos/monitoring/platform/daemon/ThresholdTest.java <ide> <ide> Threshold threshold; <ide> <del> String pwd; <del> <del> String hostname; <del> <del> private ShellHandler shellHandler = new ShellHandler(); <del> <ide> @Before <ide> public void setUp() throws CommandRuntimeException { <del> hostname = shellHandler.runLocalCommand("/bin/bash /tmp/hostname.sh") <del> .replace("\n", ""); <del> pwd = shellHandler.runLocalCommand("pwd").replace("\n", ""); <ide> threshold = new Threshold("Test", Threshold.MAX, 3); <ide> } <ide>
Java
apache-2.0
44c133b69fc17c74fefe2a7edd7bb251119e24d9
0
AechPro/Machine-Learning,AechPro/Machine-Learning
NEAT/NEAT/Population/Phenotype.java
package NEAT.Population; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.util.ArrayList; import javax.imageio.ImageIO; import NEAT.Display.DisplayObject; import NEAT.Genes.*; import NEAT.util.SortingUnit; import NEAT.util.XORTester; public class Phenotype extends DisplayObject { private ArrayList<Node> inputNodes; private ArrayList<Node> outputNodes; private ArrayList<Node> biasNodes; private ArrayList<Node> nodes; private SortingUnit sorter; private int depth; private int x,y; public Phenotype(ArrayList<Node> ns, int _x, int _y) { super(); x = _x; y = _y; nodes = ns; depth = calculateDepth(); init(); } public Phenotype(ArrayList<Node> ns, int _x, int _y, int _renderPriority, int _updatePriority) { super(_renderPriority, _updatePriority); x = _x; y = _y; nodes = ns; depth = calculateDepth(); init(); } public void init() { sorter = new SortingUnit(); separateNodes(); sorter.sortNodes(nodes, 0, nodes.size()-1); sorter.sortNodes(inputNodes, 0, inputNodes.size()-1); sorter.sortNodes(outputNodes, 0, outputNodes.size()-1); sorter.sortNodes(biasNodes, 0, biasNodes.size()-1); //System.out.println("PHENOTYPE CREATED WITH\n"+nodes.size()+" TOTAL NODES\n"+inputNodes.size()+" INPUT NODES\n" // + biasNodes.size()+" BIAS NODES\n"+outputNodes.size()+" OUTPUT NODES"); } public boolean activate(double[] input) { boolean activatedOnce = false; double sum = 0; int attempts = 0; boolean debugging = false; loadInputs(input); if(debugging) {System.out.println("Beginning activation on input "+input[0]+" | "+input[1]);} while(inactiveOutputs() || !activatedOnce) { if(attempts++>20) {if(debugging) {System.out.println("Returning false");} return false;} for(Node n : nodes) { if(n.getType() == Node.INPUT_NODE || n.getType() == Node.BIAS_NODE){continue;} sum = 0; n.setInactiveOutput(0d); n.setActive(false); if(debugging) {System.out.println("Operating on node "+n);} for(Connection c : n.getInputs()) { if(debugging) {System.out.println("Propagating connection "+c);} if(c.getInput().isActive() || c.getInput().getType() == Node.INPUT_NODE || c.getInput().getType() == Node.BIAS_NODE) { n.setActive(true); } //System.out.println("CONNECTION INPUT: "+c.getInput()); // System.out.println("NODES CHECK: "+nodes.get(nodes.indexOf(c.getInput()))); sum+=c.getWeight()*c.getInput().getActiveOutput(); if(debugging) {System.out.println("SUM SO FAR: "+sum);} } n.setInactiveOutput(sum); if(debugging) {System.out.println("Fully propagated node "+n);} } if(debugging) {System.out.println("Activating propagated nodes");} for(Node n : nodes) { if(n.getType() != Node.INPUT_NODE && n.getType() != Node.BIAS_NODE && n.isActive()) { n.setActiveOutput(sigmoid(n.getInactiveOutput(),n.getActivationResponse())); n.setActivationCount(n.getActivationCount()+1); if(debugging) {System.out.println("Activated node "+n);} } } if(debugging) {System.out.println("Loop end");} activatedOnce = true; } if(debugging) {System.out.println("Returning true");} return true; } public double[] readOutputVector() { double[] outputVector = new double[outputNodes.size()]; for(int i=0,stop=outputNodes.size();i<stop;i++) { outputVector[i] = outputNodes.get(i).getActiveOutput(); } return outputVector; } public void loadInputs(double[] inps) { //System.out.println("LOADING TO "+inputNodes.size()+" INPUT NODES"); for(int i=0;i<inputNodes.size();i++) { inputNodes.get(i).setActiveOutput(inps[i]); inputNodes.get(i).setActive(true); inputNodes.get(i).setActivationCount(1); //System.out.println("LOADED NODE "+inputNodes.get(i)); } for(int i=0;i<biasNodes.size();i++) { biasNodes.get(i).setActiveOutput(1.0); biasNodes.get(i).setActive(true); biasNodes.get(i).setActivationCount(1); } } public boolean inactiveOutputs() { for(int i=0,stop=outputNodes.size();i<stop;i++) { if(outputNodes.get(i).getActivationCount() == 0) {return true;} } return false; } public void separateNodes() { inputNodes = new ArrayList<Node>(); outputNodes = new ArrayList<Node>(); biasNodes = new ArrayList<Node>(); for(int i=0,stop=nodes.size();i<stop;i++) { if(nodes.get(i).getType() == Node.INPUT_NODE) {inputNodes.add(nodes.get(i));} if(nodes.get(i).getType() == Node.BIAS_NODE) {biasNodes.add(nodes.get(i));} if(nodes.get(i).getType() == Node.OUTPUT_NODE) {outputNodes.add(nodes.get(i));} } } public int calculateDepth() { ArrayList<Double> uniqueYVals = new ArrayList<Double>(); for(Node n : nodes) { boolean contained = false; for(int i=0;i<uniqueYVals.size();i++) { if(uniqueYVals.get(i).doubleValue() == n.getSplitY()){contained = true;} } if(!contained) { uniqueYVals.add(n.getSplitY()); } } return uniqueYVals.size()-1; } public void reset() { for(Node n : nodes) { n.setInactiveOutput(0d); n.setActivationCount(0); n.setActiveOutput(0d); n.setActive(false); } } public int getDepth() {return depth;} public ArrayList<Node> getNodes(){return nodes;} public ArrayList<Node> getInputNodes(){return inputNodes;} public ArrayList<Node> getOutputNodes(){return outputNodes;} public ArrayList<Node> getBiasNodes(){return biasNodes;} @Override public void update(double delta) { } @Override public void render(Graphics2D g) { int r = 15; g.setColor(Color.WHITE); for(Node n : nodes) { for(Connection c : n.getOutputs()) { int x1 = x + n.getX() + r/2; int y1 = y + n.getY() + r/2; int x2 = x + c.getOutput().getX()+r/2; int y2 = y + c.getOutput().getY()+r/2; g.drawLine(x1, y1, x2, y2); } } for(Node n : nodes) { switch(n.getType()) { case(Node.INPUT_NODE): g.setColor(Color.GREEN); break; case(Node.OUTPUT_NODE): g.setColor(Color.RED); break; case(Node.BIAS_NODE): g.setColor(Color.WHITE); break; default: g.setColor(Color.YELLOW); break; } g.fillOval(x+n.getX(),y+n.getY(),r,r); } } public void renderDebug(Graphics2D g) { int r = 15; for(int i=0;i<XORTester.inputs.length;i++) { loadInputs(XORTester.inputs[i]); g.setColor(Color.WHITE); r+=15; for(Node n : inputNodes) { g.drawString(""+n.getActiveOutput(),x+n.getX(),y+n.getY()+r); } for(Node n : biasNodes) { g.drawString(""+n.getActiveOutput(),x+n.getX(),y+n.getY()+r); } for(int count = 0;count<depth+1;count++) { activate(XORTester.inputs[i]); } for(Node n : nodes) { if(n.getType() == Node.HIDDEN_NODE) { g.drawString(""+Math.round(n.getActiveOutput()*100.0)/100.0,x+n.getX()+30,y+n.getY()+r-15); } } for(Node n : outputNodes) { g.drawString(""+Math.round(n.getActiveOutput()*100.0)/100.0,x+n.getX()+30,y+n.getY()+r-15); } } } public void saveAsImage(String dir, int w, int h) { BufferedImage im = new BufferedImage(w,h,BufferedImage.TYPE_INT_ARGB); Graphics2D graphics = (Graphics2D) im.getGraphics(); graphics.setColor(Color.BLACK); graphics.fillRect(0,0,w,h); int oldX = x; int oldY = y; x = 100; y = 100+h/2; render(graphics); renderDebug(graphics); graphics.dispose(); try{ImageIO.write(im, "png", new File(dir));} catch(Exception e){e.printStackTrace();} x = oldX; y = oldY; } public double sigmoid(double x, double response) { //System.out.println("CALCULATING SIGMOID OF "+x+" OUTPUT = "+1.0d/(1.0d+(double)(Math.exp(-x/response)))); return 1.0d/(1.0d+(double)(Math.exp(-x/response))); } }
Delete Phenotype.java
NEAT/NEAT/Population/Phenotype.java
Delete Phenotype.java
<ide><path>EAT/NEAT/Population/Phenotype.java <del>package NEAT.Population; <del> <del>import java.awt.Color; <del>import java.awt.Graphics2D; <del>import java.awt.image.BufferedImage; <del>import java.io.File; <del>import java.util.ArrayList; <del> <del>import javax.imageio.ImageIO; <del> <del>import NEAT.Display.DisplayObject; <del>import NEAT.Genes.*; <del>import NEAT.util.SortingUnit; <del>import NEAT.util.XORTester; <del> <del>public class Phenotype extends DisplayObject <del>{ <del> private ArrayList<Node> inputNodes; <del> private ArrayList<Node> outputNodes; <del> private ArrayList<Node> biasNodes; <del> private ArrayList<Node> nodes; <del> private SortingUnit sorter; <del> private int depth; <del> private int x,y; <del> public Phenotype(ArrayList<Node> ns, int _x, int _y) <del> { <del> super(); <del> x = _x; <del> y = _y; <del> nodes = ns; <del> depth = calculateDepth(); <del> init(); <del> } <del> public Phenotype(ArrayList<Node> ns, int _x, int _y, int _renderPriority, int _updatePriority) <del> { <del> super(_renderPriority, _updatePriority); <del> x = _x; <del> y = _y; <del> nodes = ns; <del> depth = calculateDepth(); <del> init(); <del> } <del> public void init() <del> { <del> sorter = new SortingUnit(); <del> separateNodes(); <del> sorter.sortNodes(nodes, 0, nodes.size()-1); <del> sorter.sortNodes(inputNodes, 0, inputNodes.size()-1); <del> sorter.sortNodes(outputNodes, 0, outputNodes.size()-1); <del> sorter.sortNodes(biasNodes, 0, biasNodes.size()-1); <del> //System.out.println("PHENOTYPE CREATED WITH\n"+nodes.size()+" TOTAL NODES\n"+inputNodes.size()+" INPUT NODES\n" <del> // + biasNodes.size()+" BIAS NODES\n"+outputNodes.size()+" OUTPUT NODES"); <del> } <del> public boolean activate(double[] input) <del> { <del> boolean activatedOnce = false; <del> double sum = 0; <del> int attempts = 0; <del> boolean debugging = false; <del> loadInputs(input); <del> if(debugging) {System.out.println("Beginning activation on input "+input[0]+" | "+input[1]);} <del> while(inactiveOutputs() || !activatedOnce) <del> { <del> if(attempts++>20) {if(debugging) {System.out.println("Returning false");} return false;} <del> for(Node n : nodes) <del> { <del> if(n.getType() == Node.INPUT_NODE || n.getType() == Node.BIAS_NODE){continue;} <del> sum = 0; <del> n.setInactiveOutput(0d); <del> n.setActive(false); <del> if(debugging) {System.out.println("Operating on node "+n);} <del> for(Connection c : n.getInputs()) <del> { <del> if(debugging) {System.out.println("Propagating connection "+c);} <del> if(c.getInput().isActive() || c.getInput().getType() == Node.INPUT_NODE || c.getInput().getType() == Node.BIAS_NODE) <del> { <del> n.setActive(true); <del> } <del> //System.out.println("CONNECTION INPUT: "+c.getInput()); <del> // System.out.println("NODES CHECK: "+nodes.get(nodes.indexOf(c.getInput()))); <del> sum+=c.getWeight()*c.getInput().getActiveOutput(); <del> if(debugging) {System.out.println("SUM SO FAR: "+sum);} <del> } <del> n.setInactiveOutput(sum); <del> if(debugging) {System.out.println("Fully propagated node "+n);} <del> <del> } <del> if(debugging) {System.out.println("Activating propagated nodes");} <del> for(Node n : nodes) <del> { <del> if(n.getType() != Node.INPUT_NODE && n.getType() != Node.BIAS_NODE && n.isActive()) <del> { <del> n.setActiveOutput(sigmoid(n.getInactiveOutput(),n.getActivationResponse())); <del> n.setActivationCount(n.getActivationCount()+1); <del> if(debugging) {System.out.println("Activated node "+n);} <del> } <del> <del> } <del> if(debugging) {System.out.println("Loop end");} <del> activatedOnce = true; <del> } <del> if(debugging) {System.out.println("Returning true");} <del> return true; <del> } <del> public double[] readOutputVector() <del> { <del> double[] outputVector = new double[outputNodes.size()]; <del> for(int i=0,stop=outputNodes.size();i<stop;i++) <del> { <del> outputVector[i] = outputNodes.get(i).getActiveOutput(); <del> } <del> return outputVector; <del> } <del> public void loadInputs(double[] inps) <del> { <del> //System.out.println("LOADING TO "+inputNodes.size()+" INPUT NODES"); <del> for(int i=0;i<inputNodes.size();i++) <del> { <del> inputNodes.get(i).setActiveOutput(inps[i]); <del> inputNodes.get(i).setActive(true); <del> inputNodes.get(i).setActivationCount(1); <del> //System.out.println("LOADED NODE "+inputNodes.get(i)); <del> } <del> for(int i=0;i<biasNodes.size();i++) <del> { <del> biasNodes.get(i).setActiveOutput(1.0); <del> biasNodes.get(i).setActive(true); <del> biasNodes.get(i).setActivationCount(1); <del> } <del> } <del> public boolean inactiveOutputs() <del> { <del> for(int i=0,stop=outputNodes.size();i<stop;i++) <del> { <del> if(outputNodes.get(i).getActivationCount() == 0) {return true;} <del> } <del> return false; <del> } <del> public void separateNodes() <del> { <del> inputNodes = new ArrayList<Node>(); <del> outputNodes = new ArrayList<Node>(); <del> biasNodes = new ArrayList<Node>(); <del> for(int i=0,stop=nodes.size();i<stop;i++) <del> { <del> if(nodes.get(i).getType() == Node.INPUT_NODE) {inputNodes.add(nodes.get(i));} <del> if(nodes.get(i).getType() == Node.BIAS_NODE) {biasNodes.add(nodes.get(i));} <del> if(nodes.get(i).getType() == Node.OUTPUT_NODE) {outputNodes.add(nodes.get(i));} <del> } <del> } <del> public int calculateDepth() <del> { <del> ArrayList<Double> uniqueYVals = new ArrayList<Double>(); <del> for(Node n : nodes) <del> { <del> boolean contained = false; <del> for(int i=0;i<uniqueYVals.size();i++) <del> { <del> if(uniqueYVals.get(i).doubleValue() == n.getSplitY()){contained = true;} <del> } <del> if(!contained) <del> { <del> uniqueYVals.add(n.getSplitY()); <del> } <del> } <del> return uniqueYVals.size()-1; <del> } <del> public void reset() <del> { <del> for(Node n : nodes) <del> { <del> n.setInactiveOutput(0d); <del> n.setActivationCount(0); <del> n.setActiveOutput(0d); <del> n.setActive(false); <del> } <del> } <del> public int getDepth() {return depth;} <del> public ArrayList<Node> getNodes(){return nodes;} <del> public ArrayList<Node> getInputNodes(){return inputNodes;} <del> public ArrayList<Node> getOutputNodes(){return outputNodes;} <del> public ArrayList<Node> getBiasNodes(){return biasNodes;} <del> @Override <del> public void update(double delta) <del> { <del> } <del> @Override <del> public void render(Graphics2D g) <del> { <del> int r = 15; <del> g.setColor(Color.WHITE); <del> for(Node n : nodes) <del> { <del> for(Connection c : n.getOutputs()) <del> { <del> int x1 = x + n.getX() + r/2; <del> int y1 = y + n.getY() + r/2; <del> int x2 = x + c.getOutput().getX()+r/2; <del> int y2 = y + c.getOutput().getY()+r/2; <del> g.drawLine(x1, y1, x2, y2); <del> } <del> } <del> for(Node n : nodes) <del> { <del> switch(n.getType()) <del> { <del> case(Node.INPUT_NODE): <del> g.setColor(Color.GREEN); <del> break; <del> case(Node.OUTPUT_NODE): <del> g.setColor(Color.RED); <del> break; <del> case(Node.BIAS_NODE): <del> g.setColor(Color.WHITE); <del> break; <del> default: <del> g.setColor(Color.YELLOW); <del> break; <del> } <del> g.fillOval(x+n.getX(),y+n.getY(),r,r); <del> } <del> } <del> public void renderDebug(Graphics2D g) <del> { <del> int r = 15; <del> for(int i=0;i<XORTester.inputs.length;i++) <del> { <del> loadInputs(XORTester.inputs[i]); <del> g.setColor(Color.WHITE); <del> r+=15; <del> for(Node n : inputNodes) <del> { <del> g.drawString(""+n.getActiveOutput(),x+n.getX(),y+n.getY()+r); <del> <del> } <del> for(Node n : biasNodes) <del> { <del> g.drawString(""+n.getActiveOutput(),x+n.getX(),y+n.getY()+r); <del> } <del> for(int count = 0;count<depth+1;count++) <del> { <del> activate(XORTester.inputs[i]); <del> } <del> for(Node n : nodes) <del> { <del> if(n.getType() == Node.HIDDEN_NODE) <del> { <del> g.drawString(""+Math.round(n.getActiveOutput()*100.0)/100.0,x+n.getX()+30,y+n.getY()+r-15); <del> } <del> } <del> for(Node n : outputNodes) <del> { <del> g.drawString(""+Math.round(n.getActiveOutput()*100.0)/100.0,x+n.getX()+30,y+n.getY()+r-15); <del> } <del> } <del> } <del> public void saveAsImage(String dir, int w, int h) <del> { <del> BufferedImage im = new BufferedImage(w,h,BufferedImage.TYPE_INT_ARGB); <del> Graphics2D graphics = (Graphics2D) im.getGraphics(); <del> graphics.setColor(Color.BLACK); <del> graphics.fillRect(0,0,w,h); <del> int oldX = x; <del> int oldY = y; <del> x = 100; <del> y = 100+h/2; <del> render(graphics); <del> renderDebug(graphics); <del> graphics.dispose(); <del> try{ImageIO.write(im, "png", new File(dir));} <del> catch(Exception e){e.printStackTrace();} <del> x = oldX; <del> y = oldY; <del> } <del> public double sigmoid(double x, double response) <del> { <del> //System.out.println("CALCULATING SIGMOID OF "+x+" OUTPUT = "+1.0d/(1.0d+(double)(Math.exp(-x/response)))); <del> return 1.0d/(1.0d+(double)(Math.exp(-x/response))); <del> } <del>}
Java
apache-2.0
d9bae1d54415b80baed608d68df833fbc38f83f5
0
inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service
package org.slc.sli.modeling.xmi.reader; import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.slc.sli.modeling.uml.Occurs; import org.slc.sli.modeling.xmi.XmiAttributeName; import org.slc.sli.modeling.xmi.XmiElementName; import static org.junit.Assert.*; import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; /** * Tests the XMI reading utility. * * @author kmyers */ public class XmiReaderTest { private XMLStreamReader mockReader = mock(XMLStreamReader.class); private XmiAttributeName sampleAttribute = XmiAttributeName.ID; @Test public void testAssertNotNullHappyPath() { Object o = new Object(); assertTrue(XmiReader.assertNotNull(o) == o); } @Test(expected = AssertionError.class) public void testAssertNotNullSadPath() { XmiReader.assertNotNull(null); } @Test public void testMatches() { XmiElementName xmiElementName = XmiElementName.ASSOCIATION; XmiElementName nonMatchingXmiElementName = XmiElementName.ASSOCIATION_END; String elementName = xmiElementName.getLocalName(); QName matchingQName = new QName(elementName); QName nonMatchingQName = new QName(""); when(mockReader.getName()).thenReturn(matchingQName); when(mockReader.getLocalName()).thenReturn(elementName); assertTrue(XmiReader.match(xmiElementName, matchingQName)); assertFalse(XmiReader.match(xmiElementName, nonMatchingQName)); assertTrue(XmiReader.match(xmiElementName, mockReader)); assertFalse(XmiReader.match(nonMatchingXmiElementName, mockReader)); assertTrue(XmiReader.match(matchingQName, mockReader)); assertFalse(XmiReader.match(nonMatchingQName, mockReader)); } @Test public void testGetOccursHappyPath() { when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn("1"); assertTrue(XmiReader.getOccurs(mockReader, sampleAttribute) == Occurs.ONE); when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn("0"); assertTrue(XmiReader.getOccurs(mockReader, sampleAttribute) == Occurs.ZERO); when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn("-1"); assertTrue(XmiReader.getOccurs(mockReader, sampleAttribute) == Occurs.UNBOUNDED); } @Test(expected = AssertionError.class) public void testGetOccursSadPath() { when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn("123"); XmiReader.getOccurs(mockReader, sampleAttribute); } @Test public void testGetIdRefHappyPath() { String id = "ID1234567890"; when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn(id); assertTrue(XmiReader.getIdRef(mockReader).toString().equals(id)); } @Test(expected = XmiMissingAttributeException.class) public void testGetIdRefSadPath() { when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn(null); XmiReader.getIdRef(mockReader); } @Test public void testGetIdHappyPath() { String id = "ID1234567890"; when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn(id); assertTrue(XmiReader.getId(mockReader).toString().equals(id)); } @Test public void testGetBoolean() { boolean defaultBoolean; defaultBoolean = false; when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn("true"); assertTrue(XmiReader.getBoolean(sampleAttribute, defaultBoolean, mockReader)); defaultBoolean = true; when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn("false"); assertFalse(XmiReader.getBoolean(sampleAttribute, defaultBoolean, mockReader)); defaultBoolean = false; when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn(null); assertFalse(XmiReader.getBoolean(sampleAttribute, defaultBoolean, mockReader)); defaultBoolean = true; when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn(null); assertTrue(XmiReader.getBoolean(sampleAttribute, defaultBoolean, mockReader)); } @Test public void testCloseQuiet() throws IOException { Closeable mockCloseable = mock(Closeable.class); XmiReader.closeQuiet(mockCloseable); doThrow(new IOException()).when(mockCloseable).close(); XmiReader.closeQuiet(mockCloseable); } @Test public void testAssertElementNameEqualsStreamReadNameHappyPath() { XmiElementName xmiElementName = XmiElementName.ASSOCIATION; String elementName = xmiElementName.getLocalName(); when(mockReader.getLocalName()).thenReturn(elementName); XmiReader.assertName(xmiElementName, mockReader); } @Test(expected = AssertionError.class) public void testAssertElementNameEqualsStreamReadNameSadPath() { XmiElementName xmiElementName = XmiElementName.ASSOCIATION; String elementName = XmiElementName.ASSOCIATION_END.getLocalName(); when(mockReader.getLocalName()).thenReturn(elementName); XmiReader.assertName(xmiElementName, mockReader); } @Test public void testAssertQNameEqualsStreamReadNameHappyPath() { XmiElementName xmiElementName = XmiElementName.ASSOCIATION; String elementName = xmiElementName.getLocalName(); QName matchingQName = new QName(elementName); when(mockReader.getName()).thenReturn(matchingQName); when(mockReader.getLocalName()).thenReturn(elementName); XmiReader.assertName(matchingQName, mockReader); } @Test(expected = AssertionError.class) public void testAssertQNameEqualsStreamReadNameSadPath() { XmiElementName xmiElementName = XmiElementName.ASSOCIATION; String elementName = xmiElementName.getLocalName(); QName matchingQName = new QName(elementName); QName nonMatchingQName = new QName(""); when(mockReader.getName()).thenReturn(matchingQName); when(mockReader.getLocalName()).thenReturn(elementName); XmiReader.assertName(nonMatchingQName, mockReader); } @Test public void testConstructor() { new XmiReader(); } @Test public void testSkipElement() throws XMLStreamException { final List<String> localNames = new ArrayList<String>(); localNames.add("myLocalName1"); localNames.add("myLocalName2"); localNames.add("myLocalName2"); localNames.add("myLocalName1"); final List<Integer> eventTypes = new ArrayList<Integer>(); eventTypes.add(XMLStreamConstants.START_ELEMENT); eventTypes.add(XMLStreamConstants.CHARACTERS); eventTypes.add(XMLStreamConstants.END_ELEMENT); eventTypes.add(XMLStreamConstants.END_ELEMENT); when(mockReader.hasNext()).thenReturn(true); when(mockReader.getEventType()).thenAnswer(new Answer<Integer>() { @Override public Integer answer(InvocationOnMock invocation) throws Throwable { return eventTypes.remove(0); } }); when(mockReader.getLocalName()).thenAnswer(new Answer<String>() { @Override public String answer(InvocationOnMock invocation) throws Throwable { return localNames.remove(0); } }); XmiReader.skipElement(mockReader, false); } @Test(expected = AssertionError.class) public void testSkipElementSadPath1TrueCheck() throws XMLStreamException { XmiElementName xmiElementName = XmiElementName.ASSOCIATION; String elementName = xmiElementName.getLocalName(); QName matchingQName = new QName(elementName); when(mockReader.getName()).thenReturn(matchingQName); XmiReader.skipElement(mockReader, true); } @Test(expected = AssertionError.class) public void testSkipElementSadPath2NoNext() throws XMLStreamException { when(mockReader.hasNext()).thenReturn(false); XmiReader.skipElement(mockReader, false); } @Test(expected = AssertionError.class) public void testSkipElementSadPath3UnknownEventType() throws XMLStreamException { when(mockReader.hasNext()).thenReturn(true); when(mockReader.getEventType()).thenReturn(123456789); XmiReader.skipElement(mockReader, false); } @Test(expected = AssertionError.class) public void testSkipElementSadPath4LocalNamesDoNotMatch() throws XMLStreamException { final List<String> localNames = new ArrayList<String>(); localNames.add("myLocalName1"); localNames.add("myLocalName2"); localNames.add("myLocalName2"); when(mockReader.hasNext()).thenReturn(true); when(mockReader.getEventType()).thenReturn(XMLStreamConstants.END_ELEMENT); when(mockReader.getLocalName()).thenAnswer(new Answer<String>() { @Override public String answer(InvocationOnMock invocation) throws Throwable { return localNames.remove(0); } }); XmiReader.skipElement(mockReader, false); } @Test public void testGetName() { String defaultString; defaultString = "defString"; when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn("specifiedString"); assertEquals("specifiedString", XmiReader.getName(mockReader, defaultString, sampleAttribute)); when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn(null); assertEquals(defaultString, XmiReader.getName(mockReader, defaultString, sampleAttribute)); } }
sli/modeling/xmi/src/test/java/org/slc/sli/modeling/xmi/reader/XmiReaderTest.java
package org.slc.sli.modeling.xmi.reader; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.slc.sli.modeling.uml.Occurs; import org.slc.sli.modeling.xmi.XmiAttributeName; import org.slc.sli.modeling.xmi.XmiElementName; /** * Tests the XMI reading utility. * * @author kmyers * */ public class XmiReaderTest { private XMLStreamReader mockReader = mock(XMLStreamReader.class); private XmiAttributeName sampleAttribute = XmiAttributeName.ID; @Test public void testAssertNotNullHappyPath() { Object o = new Object(); assertTrue(XmiReader.assertNotNull(o) == o); } @Test(expected = AssertionError.class) public void testAssertNotNullSadPath() { XmiReader.assertNotNull(null); } @Test public void testMatches() { XmiElementName xmiElementName = XmiElementName.ASSOCIATION; XmiElementName nonMatchingXmiElementName = XmiElementName.ASSOCIATION_END; String elementName = xmiElementName.getLocalName(); QName matchingQName = new QName(elementName); QName nonMatchingQName = new QName(""); when(mockReader.getName()).thenReturn(matchingQName); when(mockReader.getLocalName()).thenReturn(elementName); assertTrue(XmiReader.match(xmiElementName, matchingQName)); assertFalse(XmiReader.match(xmiElementName, nonMatchingQName)); assertTrue(XmiReader.match(xmiElementName, mockReader)); assertFalse(XmiReader.match(nonMatchingXmiElementName, mockReader)); assertTrue(XmiReader.match(matchingQName, mockReader)); assertFalse(XmiReader.match(nonMatchingQName, mockReader)); } @Test public void testGetOccursHappyPath() { when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn("1"); assertTrue(XmiReader.getOccurs(mockReader, sampleAttribute) == Occurs.ONE); when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn("0"); assertTrue(XmiReader.getOccurs(mockReader, sampleAttribute) == Occurs.ZERO); when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn("-1"); assertTrue(XmiReader.getOccurs(mockReader, sampleAttribute) == Occurs.UNBOUNDED); } @Test (expected = AssertionError.class) public void testGetOccursSadPath() { when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn("123"); XmiReader.getOccurs(mockReader, sampleAttribute); } @Test public void testGetIdRefHappyPath() { String id = "ID1234567890"; when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn(id); assertTrue(XmiReader.getIdRef(mockReader).toString().equals(id)); } @Test (expected = XmiMissingAttributeException.class) public void testGetIdRefSadPath() { when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn(null); XmiReader.getIdRef(mockReader); } @Test public void testGetIdHappyPath() { String id = "ID1234567890"; when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn(id); assertTrue(XmiReader.getId(mockReader).toString().equals(id)); } @Test public void testGetBoolean() { boolean defaultBoolean; defaultBoolean = false; when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn("true"); assertTrue(XmiReader.getBoolean(sampleAttribute, defaultBoolean, mockReader)); defaultBoolean = true; when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn("false"); assertFalse(XmiReader.getBoolean(sampleAttribute, defaultBoolean, mockReader)); defaultBoolean = false; when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn(null); assertFalse(XmiReader.getBoolean(sampleAttribute, defaultBoolean, mockReader)); defaultBoolean = true; when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn(null); assertTrue(XmiReader.getBoolean(sampleAttribute, defaultBoolean, mockReader)); } @Test public void testCloseQuiet() throws IOException { Closeable mockCloseable = mock(Closeable.class); XmiReader.closeQuiet(mockCloseable); doThrow(new IOException()).when(mockCloseable).close(); XmiReader.closeQuiet(mockCloseable); } @Test public void testAssertElementNameEqualsStreamReadNameHappyPath() { XmiElementName xmiElementName = XmiElementName.ASSOCIATION; String elementName = xmiElementName.getLocalName(); when(mockReader.getLocalName()).thenReturn(elementName); XmiReader.assertName(xmiElementName, mockReader); } @Test (expected = AssertionError.class) public void testAssertElementNameEqualsStreamReadNameSadPath() { XmiElementName xmiElementName = XmiElementName.ASSOCIATION; String elementName = XmiElementName.ASSOCIATION_END.getLocalName(); when(mockReader.getLocalName()).thenReturn(elementName); XmiReader.assertName(xmiElementName, mockReader); } @Test public void testAssertQNameEqualsStreamReadNameHappyPath() { XmiElementName xmiElementName = XmiElementName.ASSOCIATION; String elementName = xmiElementName.getLocalName(); QName matchingQName = new QName(elementName); when(mockReader.getName()).thenReturn(matchingQName); when(mockReader.getLocalName()).thenReturn(elementName); XmiReader.assertName(matchingQName, mockReader); } @Test (expected = AssertionError.class) public void testAssertQNameEqualsStreamReadNameSadPath() { XmiElementName xmiElementName = XmiElementName.ASSOCIATION; String elementName = xmiElementName.getLocalName(); QName matchingQName = new QName(elementName); QName nonMatchingQName = new QName(""); when(mockReader.getName()).thenReturn(matchingQName); when(mockReader.getLocalName()).thenReturn(elementName); XmiReader.assertName(nonMatchingQName, mockReader); } @Test public void testConstructor() { new XmiReader(); } @Test public void testSkipElement() throws XMLStreamException { final List<String> localNames = new ArrayList<String>(); localNames.add("myLocalName1"); localNames.add("myLocalName2"); localNames.add("myLocalName2"); localNames.add("myLocalName1"); final List<Integer> eventTypes = new ArrayList<Integer>(); eventTypes.add(XMLStreamConstants.START_ELEMENT); eventTypes.add(XMLStreamConstants.CHARACTERS); eventTypes.add(XMLStreamConstants.END_ELEMENT); eventTypes.add(XMLStreamConstants.END_ELEMENT); when(mockReader.hasNext()).thenReturn(true); when(mockReader.getEventType()).thenAnswer(new Answer<Integer>() { @Override public Integer answer(InvocationOnMock invocation) throws Throwable { return eventTypes.remove(0); } }); when(mockReader.getLocalName()).thenAnswer(new Answer<String>() { @Override public String answer(InvocationOnMock invocation) throws Throwable { return localNames.remove(0); } }); XmiReader.skipElement(mockReader, false); } @Test (expected = AssertionError.class) public void testSkipElementSadPath1TrueCheck() throws XMLStreamException { XmiElementName xmiElementName = XmiElementName.ASSOCIATION; String elementName = xmiElementName.getLocalName(); QName matchingQName = new QName(elementName); when(mockReader.getName()).thenReturn(matchingQName); XmiReader.skipElement(mockReader, true); } @Test (expected = AssertionError.class) public void testSkipElementSadPath2NoNext() throws XMLStreamException { when(mockReader.hasNext()).thenReturn(false); XmiReader.skipElement(mockReader, false); } @Test (expected = AssertionError.class) public void testSkipElementSadPath3UnknownEventType() throws XMLStreamException { when(mockReader.hasNext()).thenReturn(true); when(mockReader.getEventType()).thenReturn(123456789); XmiReader.skipElement(mockReader, false); } @Test (expected = AssertionError.class) public void testSkipElementSadPath4LocalNamesDoNotMatch() throws XMLStreamException { final List<String> localNames = new ArrayList<String>(); localNames.add("myLocalName1"); localNames.add("myLocalName2"); localNames.add("myLocalName2"); when(mockReader.hasNext()).thenReturn(true); when(mockReader.getEventType()).thenReturn(XMLStreamConstants.END_ELEMENT); when(mockReader.getLocalName()).thenAnswer(new Answer<String>() { @Override public String answer(InvocationOnMock invocation) throws Throwable { return localNames.remove(0); } }); XmiReader.skipElement(mockReader, false); } @Test public void testGetName() { String defaultString; defaultString = "defString"; when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn("specifiedString"); assertEquals("specifiedString", XmiReader.getName(mockReader, defaultString, sampleAttribute)); when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn(null); assertEquals(defaultString, XmiReader.getName(mockReader, defaultString, sampleAttribute)); } }
Formatting.
sli/modeling/xmi/src/test/java/org/slc/sli/modeling/xmi/reader/XmiReaderTest.java
Formatting.
<ide><path>li/modeling/xmi/src/test/java/org/slc/sli/modeling/xmi/reader/XmiReaderTest.java <ide> package org.slc.sli.modeling.xmi.reader; <del> <del>import static org.junit.Assert.assertEquals; <del>import static org.junit.Assert.assertFalse; <del>import static org.junit.Assert.assertTrue; <del>import static org.mockito.Matchers.any; <del>import static org.mockito.Mockito.doThrow; <del>import static org.mockito.Mockito.mock; <del>import static org.mockito.Mockito.when; <ide> <ide> import java.io.Closeable; <ide> import java.io.IOException; <ide> import org.slc.sli.modeling.xmi.XmiAttributeName; <ide> import org.slc.sli.modeling.xmi.XmiElementName; <ide> <add>import static org.junit.Assert.*; <add>import static org.mockito.Matchers.any; <add>import static org.mockito.Mockito.*; <add> <ide> /** <ide> * Tests the XMI reading utility. <ide> * <ide> * @author kmyers <del> * <ide> */ <ide> public class XmiReaderTest { <ide> <ide> assertTrue(XmiReader.getOccurs(mockReader, sampleAttribute) == Occurs.UNBOUNDED); <ide> } <ide> <del> @Test (expected = AssertionError.class) <add> @Test(expected = AssertionError.class) <ide> public void testGetOccursSadPath() { <ide> <ide> when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn("123"); <ide> assertTrue(XmiReader.getIdRef(mockReader).toString().equals(id)); <ide> } <ide> <del> @Test (expected = XmiMissingAttributeException.class) <add> @Test(expected = XmiMissingAttributeException.class) <ide> public void testGetIdRefSadPath() { <ide> when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn(null); <ide> XmiReader.getIdRef(mockReader); <ide> <ide> } <ide> <del> @Test (expected = AssertionError.class) <add> @Test(expected = AssertionError.class) <ide> public void testAssertElementNameEqualsStreamReadNameSadPath() { <ide> XmiElementName xmiElementName = XmiElementName.ASSOCIATION; <ide> String elementName = XmiElementName.ASSOCIATION_END.getLocalName(); <ide> <ide> } <ide> <del> @Test (expected = AssertionError.class) <add> @Test(expected = AssertionError.class) <ide> public void testAssertQNameEqualsStreamReadNameSadPath() { <ide> XmiElementName xmiElementName = XmiElementName.ASSOCIATION; <ide> String elementName = xmiElementName.getLocalName(); <ide> XmiReader.skipElement(mockReader, false); <ide> } <ide> <del> @Test (expected = AssertionError.class) <add> @Test(expected = AssertionError.class) <ide> public void testSkipElementSadPath1TrueCheck() throws XMLStreamException { <ide> <ide> XmiElementName xmiElementName = XmiElementName.ASSOCIATION; <ide> XmiReader.skipElement(mockReader, true); <ide> } <ide> <del> @Test (expected = AssertionError.class) <add> @Test(expected = AssertionError.class) <ide> public void testSkipElementSadPath2NoNext() throws XMLStreamException { <ide> <ide> when(mockReader.hasNext()).thenReturn(false); <ide> XmiReader.skipElement(mockReader, false); <ide> } <ide> <del> @Test (expected = AssertionError.class) <add> @Test(expected = AssertionError.class) <ide> public void testSkipElementSadPath3UnknownEventType() throws XMLStreamException { <ide> <ide> when(mockReader.hasNext()).thenReturn(true); <ide> XmiReader.skipElement(mockReader, false); <ide> } <ide> <del> @Test (expected = AssertionError.class) <add> @Test(expected = AssertionError.class) <ide> public void testSkipElementSadPath4LocalNamesDoNotMatch() throws XMLStreamException { <ide> <ide> final List<String> localNames = new ArrayList<String>();
Java
epl-1.0
30b26a37e6093db0563327c47e4826c59e6fb36b
0
cdealti/kura,markoer/kura,ctron/kura,ctron/kura,markcullen/kura_Windows,nicolatimeus/kura,ymai/kura,amitjoy/kura,MMaiero/kura,markcullen/kura_Windows,darionct/kura,gavinying/kura,amitjoy/kura,unverbraucht/kura,amitjoy/kura,rohitdubey12/kura,cdealti/kura,cdealti/kura,rohitdubey12/kura,markoer/kura,ctron/kura,ymai/kura,markoer/kura,cdealti/kura,nicolatimeus/kura,amitjoy/kura,darionct/kura,cdealti/kura,ctron/kura,markoer/kura,ymai/kura,gavinying/kura,ymai/kura,markcullen/kura_Windows,MMaiero/kura,unverbraucht/kura,MMaiero/kura,gavinying/kura,darionct/kura,nicolatimeus/kura,rohitdubey12/kura,gavinying/kura,markoer/kura,markcullen/kura_Windows,MMaiero/kura,MMaiero/kura,markoer/kura,darionct/kura,gavinying/kura,unverbraucht/kura,nicolatimeus/kura,amitjoy/kura,unverbraucht/kura,nicolatimeus/kura,rohitdubey12/kura,ctron/kura,markcullen/kura_Windows,ymai/kura,cdealti/kura,unverbraucht/kura,MMaiero/kura,rohitdubey12/kura,nicolatimeus/kura,darionct/kura,gavinying/kura,darionct/kura,ctron/kura,ymai/kura,amitjoy/kura
/** * Copyright (c) 2011, 2015 Eurotech and/or its affiliates * * 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: * Eurotech */ package org.eclipse.kura.core.deployment; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.util.Date; import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.eclipse.kura.KuraErrorCode; import org.eclipse.kura.KuraException; import org.eclipse.kura.cloud.Cloudlet; import org.eclipse.kura.cloud.CloudletTopic; import org.eclipse.kura.core.deployment.download.DeploymentPackageDownloadOptions; import org.eclipse.kura.core.deployment.download.DownloadCountingOutputStream; import org.eclipse.kura.core.deployment.download.DownloadFileUtilities; import org.eclipse.kura.core.deployment.download.DownloadImpl; import org.eclipse.kura.core.deployment.install.DeploymentPackageInstallOptions; import org.eclipse.kura.core.deployment.install.InstallImpl; import org.eclipse.kura.core.deployment.uninstall.DeploymentPackageUninstallOptions; import org.eclipse.kura.core.deployment.uninstall.UninstallImpl; import org.eclipse.kura.core.deployment.xml.XmlBundle; import org.eclipse.kura.core.deployment.xml.XmlBundleInfo; import org.eclipse.kura.core.deployment.xml.XmlBundles; import org.eclipse.kura.core.deployment.xml.XmlDeploymentPackage; import org.eclipse.kura.core.deployment.xml.XmlDeploymentPackages; import org.eclipse.kura.core.deployment.xml.XmlUtil; import org.eclipse.kura.core.util.ThrowableUtil; import org.eclipse.kura.data.DataTransportService; import org.eclipse.kura.message.KuraPayload; import org.eclipse.kura.message.KuraRequestPayload; import org.eclipse.kura.message.KuraResponsePayload; import org.eclipse.kura.ssl.SslManagerService; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; import org.osgi.service.component.ComponentContext; import org.osgi.service.component.ComponentException; import org.osgi.service.deploymentadmin.BundleInfo; import org.osgi.service.deploymentadmin.DeploymentAdmin; import org.osgi.service.deploymentadmin.DeploymentPackage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CloudDeploymentHandlerV2 extends Cloudlet { private static final Logger s_logger = LoggerFactory.getLogger(CloudDeploymentHandlerV2.class); public static final String APP_ID = "DEPLOY-V2"; private static final String DPA_CONF_PATH_PROPNAME = "dpa.configuration"; private static final String KURA_CONF_URL_PROPNAME = "kura.configuration"; private static final String PACKAGES_PATH_PROPNAME = "kura.packages"; private static final String KURA_DATA_DIR = "kura.data"; public static final String RESOURCE_PACKAGES = "packages"; public static final String RESOURCE_BUNDLES = "bundles"; /* EXEC */ public static final String RESOURCE_DOWNLOAD = "download"; public static final String RESOURCE_INSTALL = "install"; public static final String RESOURCE_UNINSTALL = "uninstall"; public static final String RESOURCE_CANCEL = "cancel"; public static final String RESOURCE_START = "start"; public static final String RESOURCE_STOP = "stop"; /* Metrics in the REPLY to RESOURCE_DOWNLOAD */ public static final String METRIC_DOWNLOAD_STATUS = "download.status"; public static final String METRIC_REQUESTER_CLIENT_ID = "requester.client.id"; /** * Enum representing the different status of the download process * * {@link DeploymentAgentService.DOWNLOAD_STATUS.PROGRESS} Download in * progress {@link DeploymentAgentService.DOWNLOAD_STATUS.COMPLETE} Download * completed {@link DeploymentAgentService.DOWNLOAD_STATUS.FAILED} Download * failed */ public static enum DOWNLOAD_STATUS { IN_PROGRESS("IN_PROGRESS"), COMPLETED("COMPLETED"), FAILED("FAILED"), ALREADY_DONE("ALREADY DONE"); private final String status; DOWNLOAD_STATUS(String status) { this.status = status; } public String getStatusString() { return status; } } public static enum INSTALL_STATUS { IDLE("IDLE"), IN_PROGRESS("IN_PROGRESS"), COMPLETED("COMPLETED"), FAILED("FAILED"), ALREADY_DONE("ALREADY DONE"); private final String status; INSTALL_STATUS(String status) { this.status = status; } public String getStatusString() { return status; } } public static enum UNINSTALL_STATUS { IDLE("IDLE"), IN_PROGRESS("IN_PROGRESS"), COMPLETED("COMPLETED"), FAILED("FAILED"), ALREADY_DONE("ALREADY DONE"); private final String status; UNINSTALL_STATUS(String status) { this.status = status; } public String getStatusString() { return status; } } private static String s_pendingPackageUrl = null; private static DownloadImpl m_downloadImplementation; private static UninstallImpl m_uninstallImplementation; public static InstallImpl m_installImplementation; private SslManagerService m_sslManagerService; private DeploymentAdmin m_deploymentAdmin; private static ExecutorService executor = Executors.newSingleThreadExecutor(); private Future<?> downloaderFuture; private Future<?> installerFuture; private BundleContext m_bundleContext; private DataTransportService m_dataTransportService; private String m_dpaConfPath; private String m_packagesPath; private DeploymentPackageDownloadOptions m_downloadOptions; private boolean m_isInstalling = false; private DeploymentPackageInstallOptions m_installOptions; private String m_pendingUninstPackageName; private String m_installVerificationDir; private String m_clientId; // ---------------------------------------------------------------- // // Dependencies // // ---------------------------------------------------------------- public void setSslManagerService(SslManagerService sslManagerService) { this.m_sslManagerService = sslManagerService; } public void unsetSslManagerService(SslManagerService sslManagerService) { this.m_sslManagerService = null; } protected void setDeploymentAdmin(DeploymentAdmin deploymentAdmin) { m_deploymentAdmin = deploymentAdmin; } protected void unsetDeploymentAdmin(DeploymentAdmin deploymentAdmin) { m_deploymentAdmin = null; } public void setDataTransportService(DataTransportService dataTransportService) { m_dataTransportService = dataTransportService; } public void unsetDataTransportService(DataTransportService dataTransportService) { m_dataTransportService = null; } public CloudDeploymentHandlerV2() { super(APP_ID); } // ---------------------------------------------------------------- // // Activation APIs // // ---------------------------------------------------------------- @Override protected void activate(ComponentContext componentContext) { s_logger.info("Cloud Deployment v2 is starting"); super.activate(componentContext); m_bundleContext = componentContext.getBundleContext(); m_clientId= m_dataTransportService.getClientId(); m_dpaConfPath = System.getProperty(DPA_CONF_PATH_PROPNAME); if (m_dpaConfPath == null || m_dpaConfPath.isEmpty()) { throw new ComponentException("The value of '" + DPA_CONF_PATH_PROPNAME + "' is not defined"); } String sKuraConfUrl = System.getProperty(KURA_CONF_URL_PROPNAME); if (sKuraConfUrl == null || sKuraConfUrl.isEmpty()) { throw new ComponentException("The value of '" + KURA_CONF_URL_PROPNAME + "' is not defined"); } URL kuraUrl = null; try { kuraUrl = new URL(sKuraConfUrl); } catch (MalformedURLException e) { throw new ComponentException("Invalid Kura configuration URL"); } Properties kuraProperties = new Properties(); try { kuraProperties.load(kuraUrl.openStream()); } catch (FileNotFoundException e) { throw new ComponentException("Kura configuration file not found", e); } catch (IOException e) { throw new ComponentException("Exception loading Kura configuration file", e); } m_packagesPath = kuraProperties.getProperty(PACKAGES_PATH_PROPNAME); if (m_packagesPath == null || m_packagesPath.isEmpty()) { throw new ComponentException("The value of '" + PACKAGES_PATH_PROPNAME + "' is not defined"); } if (kuraProperties.getProperty(PACKAGES_PATH_PROPNAME) != null && kuraProperties.getProperty(PACKAGES_PATH_PROPNAME).trim().equals("kura/packages")) { kuraProperties.setProperty(PACKAGES_PATH_PROPNAME, "/opt/eclipse/kura/kura/packages"); m_packagesPath = kuraProperties.getProperty(PACKAGES_PATH_PROPNAME); s_logger.warn("Overridding invalid kura.packages location"); } String kuraDataDir= kuraProperties.getProperty(KURA_DATA_DIR); m_installImplementation = new InstallImpl(this, kuraDataDir); m_installImplementation.setPackagesPath(m_packagesPath); m_installImplementation.setDpaConfPath(m_dpaConfPath); m_installImplementation.setDeploymentAdmin(m_deploymentAdmin); m_installImplementation.sendInstallConfirmations(); } @Override protected void deactivate(ComponentContext componentContext) { s_logger.info("Bundle " + APP_ID + " is deactivating!"); if(downloaderFuture != null){ downloaderFuture.cancel(true); } if(installerFuture != null){ installerFuture.cancel(true); } m_bundleContext = null; } // ---------------------------------------------------------------- // // Public methods // // ---------------------------------------------------------------- public void publishMessage(DeploymentPackageOptions options, KuraPayload messagePayload, String messageType){ try { String messageTopic = new StringBuilder("NOTIFY/").append(options.getClientId()) .append("/") .append(messageType) .toString(); getCloudApplicationClient().controlPublish(options.getRequestClientId(), messageTopic, messagePayload, 2, DFLT_RETAIN, DFLT_PRIORITY); } catch (KuraException e) { s_logger.error("Error publishing response for command {} {}", messageType, e); } } // ---------------------------------------------------------------- // // Protected methods // // ---------------------------------------------------------------- @Override protected void doGet(CloudletTopic reqTopic, KuraRequestPayload reqPayload, KuraResponsePayload respPayload) throws KuraException { //doGetResource(reqTopic, reqPayload); String[] resources = reqTopic.getResources(); if (resources == null || resources.length == 0) { s_logger.error("Bad request topic: {}", reqTopic.toString()); s_logger.error("Expected one resource but found {}", resources != null ? resources.length : "none"); respPayload.setResponseCode(KuraResponsePayload.RESPONSE_CODE_BAD_REQUEST); return; } if (resources[0].equals(RESOURCE_DOWNLOAD)) { doGetDownload(reqPayload, respPayload); } else if (resources[0].equals(RESOURCE_INSTALL)) { doGetInstall(reqPayload, respPayload); } else if (resources[0].equals(RESOURCE_PACKAGES)) { doGetPackages(reqPayload, respPayload); } else if (resources[0].equals(RESOURCE_BUNDLES)) { doGetBundles(reqPayload, respPayload); } else { s_logger.error("Bad request topic: {}", reqTopic.toString()); s_logger.error("Cannot find resource with name: {}", resources[0]); respPayload.setResponseCode(KuraResponsePayload.RESPONSE_CODE_NOTFOUND); return; } } @Override protected void doExec(CloudletTopic reqTopic, KuraRequestPayload reqPayload, KuraResponsePayload respPayload) throws KuraException { String[] resources = reqTopic.getResources(); if (resources == null || resources.length == 0) { s_logger.error("Bad request topic: {}", reqTopic.toString()); s_logger.error("Expected one resource but found {}", resources != null ? resources.length : "none"); respPayload.setResponseCode(KuraResponsePayload.RESPONSE_CODE_BAD_REQUEST); return; } if (resources[0].equals(RESOURCE_DOWNLOAD)) { doExecDownload(reqPayload, respPayload); } else if (resources[0].equals(RESOURCE_INSTALL)) { doExecInstall(reqPayload, respPayload); } else if (resources[0].equals(RESOURCE_UNINSTALL)) { doExecUninstall(reqPayload, respPayload); } else if (resources[0].equals(RESOURCE_START)) { String bundleId = resources[1]; doExecStartStopBundle(reqPayload, respPayload, true, bundleId); } else if (resources[0].equals(RESOURCE_STOP)) { String bundleId = resources[1]; doExecStartStopBundle(reqPayload, respPayload, false, bundleId); }else { s_logger.error("Bad request topic: {}", reqTopic.toString()); s_logger.error("Cannot find resource with name: {}", resources[0]); respPayload.setResponseCode(KuraResponsePayload.RESPONSE_CODE_NOTFOUND); return; } } @Override protected void doDel(CloudletTopic reqTopic, KuraRequestPayload reqPayload, KuraResponsePayload respPayload) throws KuraException { String[] resources = reqTopic.getResources(); if (resources == null || resources.length == 0) { s_logger.error("Bad request topic: {}", reqTopic.toString()); s_logger.error("Expected one resource but found {}", resources != null ? resources.length : "none"); respPayload.setResponseCode(KuraResponsePayload.RESPONSE_CODE_BAD_REQUEST); return; } if (resources[0].equals(RESOURCE_DOWNLOAD)) { doDelDownload(reqPayload, respPayload); } else { s_logger.error("Bad request topic: {}", reqTopic.toString()); s_logger.error("Cannot find resource with name: {}", resources[0]); respPayload.setResponseCode(KuraResponsePayload.RESPONSE_CODE_NOTFOUND); return; } } // ---------------------------------------------------------------- // // Private methods // // ---------------------------------------------------------------- private void doDelDownload(KuraRequestPayload request, KuraResponsePayload response) { try{ m_downloadImplementation.getDownloadHelper().cancelDownload(); m_downloadImplementation.deleteDownloadedFile(); }catch(Exception ex){ s_logger.info("Error cancelling download!", ex); } } private void doExecDownload(KuraRequestPayload request, KuraResponsePayload response) { final DeploymentPackageDownloadOptions options; try { options = new DeploymentPackageDownloadOptions(request); options.setClientId(m_clientId); m_downloadImplementation= new DownloadImpl(options, this); } catch (Exception ex) { s_logger.info("Malformed download request!"); response.setResponseCode(KuraResponsePayload.RESPONSE_CODE_ERROR); response.setTimestamp(new Date()); try { response.setBody("Malformed donwload request".getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { // Ignore } response.setException(ex); return; } m_downloadOptions = options; if (s_pendingPackageUrl != null && s_pendingPackageUrl.equals(options.getDeployUrl())) { s_logger.info("Another request seems for the same URL is pending: {}.", s_pendingPackageUrl); response.setResponseCode(KuraResponsePayload.RESPONSE_CODE_OK); response.setTimestamp(new Date()); response.addMetric(METRIC_DOWNLOAD_STATUS, DOWNLOAD_STATUS.IN_PROGRESS); try { response.setBody("The requested resource is already in download".getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { } return; } else if (s_pendingPackageUrl != null && !s_pendingPackageUrl.equals(options.getDeployUrl())) { s_logger.info("Another request is pending for a different URL: {}.", s_pendingPackageUrl); response.setResponseCode(KuraResponsePayload.RESPONSE_CODE_ERROR); response.setTimestamp(new Date()); response.addMetric(METRIC_DOWNLOAD_STATUS, DOWNLOAD_STATUS.IN_PROGRESS); try { response.setBody("Only one request at a time is allowed".getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { } return; } boolean alreadyDownloaded = false; try { alreadyDownloaded = m_downloadImplementation.isAlreadyDownloaded(); } catch (KuraException ex) { response.setResponseCode(KuraResponsePayload.RESPONSE_CODE_ERROR); response.setException(ex); response.setTimestamp(new Date()); try { response.setBody("Error checking download status".getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { } return; } s_logger.info("About to download and install package at URL {}", options.getDeployUrl()); try { s_pendingPackageUrl = options.getDeployUrl(); m_downloadImplementation.setSslManager(m_sslManagerService); m_downloadImplementation.setAlreadyDownloadedFlag(alreadyDownloaded); m_downloadImplementation.setVerificationDirectory(m_installVerificationDir); s_logger.info("Downloading package from URL: " + options.getDeployUrl()); downloaderFuture = executor.submit(new Runnable(){ @Override public void run() { try { m_downloadImplementation.downloadDeploymentPackageInternal(); } catch (KuraException e) { } finally{ s_pendingPackageUrl = null; } } }); } catch (Exception e) { s_logger.error("Failed to download and install package at URL {}: {}", options.getDeployUrl(), e); s_pendingPackageUrl = null; response.setResponseCode(KuraResponsePayload.RESPONSE_CODE_ERROR); response.setTimestamp(new Date()); try { response.setBody(e.getMessage().getBytes("UTF-8")); } catch (UnsupportedEncodingException uee) { } } return; } private void doExecInstall(KuraRequestPayload request, KuraResponsePayload response){ final DeploymentPackageInstallOptions options; try { options = new DeploymentPackageInstallOptions(request); options.setClientId(m_clientId); } catch (Exception ex) { s_logger.info("Malformed install request!"); response.setResponseCode(KuraResponsePayload.RESPONSE_CODE_ERROR); response.setTimestamp(new Date()); try { response.setBody("Malformed install request".getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { // Ignore } response.setException(ex); return; } m_installOptions = options; boolean alreadyDownloaded = false; try { alreadyDownloaded = m_downloadImplementation.isAlreadyDownloaded(); } catch (KuraException ex) { response.setResponseCode(KuraResponsePayload.RESPONSE_CODE_ERROR); response.setException(ex); response.setTimestamp(new Date()); try { response.setBody("Error checking download status".getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { } return; } if(alreadyDownloaded && !m_isInstalling){ //Check if file exists try { m_isInstalling = true; final File dpFile = DownloadFileUtilities.getDpDownloadFile(options); m_installImplementation.setOptions(options); //if yes, install installerFuture = executor.submit(new Runnable(){ @Override public void run() { try { installDownloadedFile(dpFile, m_installOptions); } catch (KuraException e) { s_logger.error("Impossible to send an exception message to the cloud platform"); } finally { m_installOptions = null; m_isInstalling = false; } } }); } catch (IOException e) { response.setResponseCode(KuraResponsePayload.RESPONSE_CODE_ERROR); response.setException(e); response.setTimestamp(new Date()); try { response.setBody("Exception during install".getBytes("UTF-8")); } catch (UnsupportedEncodingException e1) { } } } else { response.setResponseCode(KuraResponsePayload.RESPONSE_CODE_ERROR); response.setException(new KuraException(KuraErrorCode.INTERNAL_ERROR)); response.setTimestamp(new Date()); try { response.setBody("Already installing/uninstalling".getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { } return; } } private void doExecUninstall(KuraRequestPayload request, KuraResponsePayload response) { final DeploymentPackageUninstallOptions options; try { options = new DeploymentPackageUninstallOptions(request); options.setClientId(m_clientId); } catch (Exception ex) { s_logger.info("Malformed uninstall request!"); response.setResponseCode(KuraResponsePayload.RESPONSE_CODE_ERROR); response.setTimestamp(new Date()); try { response.setBody("Malformed uninstall request".getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { // Ignore } response.setException(ex); return; } final String packageName = options.getDpName(); // // We only allow one request at a time if (!m_isInstalling && m_pendingUninstPackageName != null) { s_logger.info("Antother request seems still pending: {}. Checking if stale...", m_pendingUninstPackageName); response = new KuraResponsePayload(KuraResponsePayload.RESPONSE_CODE_ERROR); response.setTimestamp(new Date()); try { response.setBody("Only one request at a time is allowed".getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { // Ignore } } else { s_logger.info("About to uninstall package {}", packageName); try { m_isInstalling = true; m_pendingUninstPackageName = packageName; m_uninstallImplementation= new UninstallImpl(this, m_deploymentAdmin); s_logger.info("Uninstalling package..."); installerFuture = executor.submit(new Runnable(){ @Override public void run() { try { m_uninstallImplementation.uninstaller(options, packageName); } catch (Exception e) { try { m_uninstallImplementation.uninstallFailedAsync(options, packageName, e); } catch (KuraException e1) { } } finally { m_installOptions = null; m_isInstalling = false; } } }); } catch (Exception e) { s_logger.error("Failed to uninstall package {}: {}", packageName, e); response = new KuraResponsePayload(KuraResponsePayload.RESPONSE_CODE_ERROR); response.setTimestamp(new Date()); try { response.setBody(e.getMessage().getBytes("UTF-8")); } catch (UnsupportedEncodingException uee) { // Ignore } } finally { m_isInstalling = false; m_pendingUninstPackageName = null; } } } private void doExecStartStopBundle(KuraRequestPayload request, KuraResponsePayload response, boolean start, String bundleId) { if (bundleId == null) { s_logger.info("EXEC start/stop bundle: null bundle ID"); response.setResponseCode(KuraResponsePayload.RESPONSE_CODE_BAD_REQUEST); response.setTimestamp(new Date()); } else { Long id = null; try { id = Long.valueOf(bundleId); } catch (NumberFormatException e){ s_logger.error("EXEC start/stop bundle: bad bundle ID format: {}", e); response.setResponseCode(KuraResponsePayload.RESPONSE_CODE_BAD_REQUEST); response.setTimestamp(new Date()); response.setExceptionMessage(e.getMessage()); response.setExceptionStack(ThrowableUtil.stackTraceAsString(e)); } if (id != null) { s_logger.info("Executing command {}", start ? RESOURCE_START : RESOURCE_STOP); Bundle bundle = m_bundleContext.getBundle(id); if (bundle == null) { s_logger.error("Bundle ID {} not found", id); response.setResponseCode(KuraResponsePayload.RESPONSE_CODE_NOTFOUND); response.setTimestamp(new Date()); } else { try { if (start) { bundle.start(); } else { bundle.stop(); } s_logger.info("{} bundle ID {} ({})", new Object[] {start ? "Started" : "Stopped", id, bundle.getSymbolicName()}); response.setResponseCode(KuraResponsePayload.RESPONSE_CODE_OK); response.setTimestamp(new Date()); } catch (BundleException e) { s_logger.error("Failed to {} bundle {}: {}", new Object[] {start ? "start" : "stop", id, e}); response.setResponseCode(KuraResponsePayload.RESPONSE_CODE_ERROR); response.setTimestamp(new Date()); } } } } } private void doGetInstall(KuraRequestPayload reqPayload, KuraResponsePayload respPayload) { if(m_isInstalling){ m_installImplementation.installInProgressSyncMessage(respPayload); } else { m_installImplementation.installIdleSyncMessage(respPayload); } } private void doGetDownload(KuraRequestPayload reqPayload, KuraResponsePayload respPayload) { if (s_pendingPackageUrl != null){ //A download is pending DownloadCountingOutputStream downloadHelper= m_downloadImplementation.getDownloadHelper(); DownloadImpl.downloadInProgressSyncMessage(respPayload, downloadHelper, m_downloadOptions); } else { //No pending downloads DownloadImpl.downloadAlreadyDoneSyncMessage(respPayload); //is it right? Do we remove the last object } } private void doGetPackages(KuraRequestPayload request, KuraResponsePayload response) { DeploymentPackage[] dps = m_deploymentAdmin.listDeploymentPackages(); XmlDeploymentPackages xdps = new XmlDeploymentPackages(); XmlDeploymentPackage[] axdp = new XmlDeploymentPackage[dps.length]; for (int i = 0; i < dps.length; i++) { DeploymentPackage dp = dps[i]; XmlDeploymentPackage xdp = new XmlDeploymentPackage(); xdp.setName(dp.getName()); xdp.setVersion(dp.getVersion().toString()); BundleInfo[] bis = dp.getBundleInfos(); XmlBundleInfo[] axbi = new XmlBundleInfo[bis.length]; for (int j = 0; j < bis.length; j++) { BundleInfo bi = bis[j]; XmlBundleInfo xbi = new XmlBundleInfo(); xbi.setName(bi.getSymbolicName()); xbi.setVersion(bi.getVersion().toString()); axbi[j] = xbi; } xdp.setBundleInfos(axbi); axdp[i] = xdp; } xdps.setDeploymentPackages(axdp); try { String s = XmlUtil.marshal(xdps); //s_logger.info("Getting resource {}: {}", RESOURCE_PACKAGES, s); response.setTimestamp(new Date()); try { response.setBody(s.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { // Ignore } } catch (Exception e) { s_logger.error("Error getting resource {}: {}", RESOURCE_PACKAGES, e); } } private void doGetBundles(KuraRequestPayload request, KuraResponsePayload response) { Bundle[] bundles = m_bundleContext.getBundles(); XmlBundles xmlBundles = new XmlBundles(); XmlBundle[] axb = new XmlBundle[bundles.length]; for (int i = 0; i < bundles.length; i++) { Bundle bundle = bundles[i]; XmlBundle xmlBundle = new XmlBundle(); xmlBundle.setName(bundle.getSymbolicName()); xmlBundle.setVersion(bundle.getVersion().toString()); xmlBundle.setId(bundle.getBundleId()); int state = bundle.getState(); switch(state) { case Bundle.UNINSTALLED: xmlBundle.setState("UNINSTALLED"); break; case Bundle.INSTALLED: xmlBundle.setState("INSTALLED"); break; case Bundle.RESOLVED: xmlBundle.setState("RESOLVED"); break; case Bundle.STARTING: xmlBundle.setState("STARTING"); break; case Bundle.STOPPING: xmlBundle.setState("STOPPING"); break; case Bundle.ACTIVE: xmlBundle.setState("ACTIVE"); break; default: xmlBundle.setState(String.valueOf(state)); } axb[i] = xmlBundle; } xmlBundles.setBundles(axb); try { String s = XmlUtil.marshal(xmlBundles); //s_logger.info("Getting resource {}: {}", RESOURCE_BUNDLES, s); response.setTimestamp(new Date()); try { response.setBody(s.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { // Ignore } } catch (Exception e) { s_logger.error("Error getting resource {}: {}", RESOURCE_BUNDLES, e); } } public void installDownloadedFile(File dpFile, DeploymentPackageInstallOptions options) throws KuraException { try{ if(options.getSystemUpdate()){ m_installImplementation.installSh(options, dpFile); } else { m_installImplementation.installDp(options, dpFile); } } catch (Exception e) { s_logger.info("Install exception"); m_installImplementation.installFailedAsync(options, dpFile.getName(), e); } } }
kura/org.eclipse.kura.core.deployment/src/main/java/org/eclipse/kura/core/deployment/CloudDeploymentHandlerV2.java
/** * Copyright (c) 2011, 2015 Eurotech and/or its affiliates * * 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: * Eurotech */ package org.eclipse.kura.core.deployment; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.util.Date; import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.eclipse.kura.KuraErrorCode; import org.eclipse.kura.KuraException; import org.eclipse.kura.cloud.Cloudlet; import org.eclipse.kura.cloud.CloudletTopic; import org.eclipse.kura.core.deployment.download.DeploymentPackageDownloadOptions; import org.eclipse.kura.core.deployment.download.DownloadCountingOutputStream; import org.eclipse.kura.core.deployment.download.DownloadFileUtilities; import org.eclipse.kura.core.deployment.download.DownloadImpl; import org.eclipse.kura.core.deployment.install.DeploymentPackageInstallOptions; import org.eclipse.kura.core.deployment.install.InstallImpl; import org.eclipse.kura.core.deployment.uninstall.DeploymentPackageUninstallOptions; import org.eclipse.kura.core.deployment.uninstall.UninstallImpl; import org.eclipse.kura.core.deployment.xml.XmlBundle; import org.eclipse.kura.core.deployment.xml.XmlBundleInfo; import org.eclipse.kura.core.deployment.xml.XmlBundles; import org.eclipse.kura.core.deployment.xml.XmlDeploymentPackage; import org.eclipse.kura.core.deployment.xml.XmlDeploymentPackages; import org.eclipse.kura.core.deployment.xml.XmlUtil; import org.eclipse.kura.core.util.ThrowableUtil; import org.eclipse.kura.data.DataTransportService; import org.eclipse.kura.message.KuraPayload; import org.eclipse.kura.message.KuraRequestPayload; import org.eclipse.kura.message.KuraResponsePayload; import org.eclipse.kura.ssl.SslManagerService; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; import org.osgi.service.component.ComponentContext; import org.osgi.service.component.ComponentException; import org.osgi.service.deploymentadmin.BundleInfo; import org.osgi.service.deploymentadmin.DeploymentAdmin; import org.osgi.service.deploymentadmin.DeploymentPackage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CloudDeploymentHandlerV2 extends Cloudlet { private static final Logger s_logger = LoggerFactory.getLogger(CloudDeploymentHandlerV2.class); public static final String APP_ID = "DEPLOY-V2"; private static final String DPA_CONF_PATH_PROPNAME = "dpa.configuration"; private static final String KURA_CONF_URL_PROPNAME = "kura.configuration"; private static final String PACKAGES_PATH_PROPNAME = "kura.packages"; private static final String KURA_DATA_DIR = "kura.data"; public static final String RESOURCE_PACKAGES = "packages"; public static final String RESOURCE_BUNDLES = "bundles"; /* EXEC */ public static final String RESOURCE_DOWNLOAD = "download"; public static final String RESOURCE_INSTALL = "install"; public static final String RESOURCE_UNINSTALL = "uninstall"; public static final String RESOURCE_CANCEL = "cancel"; public static final String RESOURCE_START = "start"; public static final String RESOURCE_STOP = "stop"; /* Metrics in the REPLY to RESOURCE_DOWNLOAD */ public static final String METRIC_DOWNLOAD_STATUS = "download.status"; public static final String METRIC_REQUESTER_CLIENT_ID = "requester.client.id"; /** * Enum representing the different status of the download process * * {@link DeploymentAgentService.DOWNLOAD_STATUS.PROGRESS} Download in * progress {@link DeploymentAgentService.DOWNLOAD_STATUS.COMPLETE} Download * completed {@link DeploymentAgentService.DOWNLOAD_STATUS.FAILED} Download * failed */ public static enum DOWNLOAD_STATUS { IN_PROGRESS("IN_PROGRESS"), COMPLETED("COMPLETED"), FAILED("FAILED"), ALREADY_DONE("ALREADY DONE"); private final String status; DOWNLOAD_STATUS(String status) { this.status = status; } public String getStatusString() { return status; } } public static enum INSTALL_STATUS { IDLE("IDLE"), IN_PROGRESS("IN_PROGRESS"), COMPLETED("COMPLETED"), FAILED("FAILED"), ALREADY_DONE("ALREADY DONE"); private final String status; INSTALL_STATUS(String status) { this.status = status; } public String getStatusString() { return status; } } public static enum UNINSTALL_STATUS { IDLE("IDLE"), IN_PROGRESS("IN_PROGRESS"), COMPLETED("COMPLETED"), FAILED("FAILED"), ALREADY_DONE("ALREADY DONE"); private final String status; UNINSTALL_STATUS(String status) { this.status = status; } public String getStatusString() { return status; } } private static String s_pendingPackageUrl = null; private static DownloadImpl m_downloadImplementation; private static UninstallImpl m_uninstallImplementation; public static InstallImpl m_installImplementation; private SslManagerService m_sslManagerService; private DeploymentAdmin m_deploymentAdmin; private static ExecutorService executor = Executors.newSingleThreadExecutor(); private Future<?> downloaderFuture; private Future<?> installerFuture; private BundleContext m_bundleContext; private DataTransportService m_dataTransportService; private String m_dpaConfPath; private String m_packagesPath; private DeploymentPackageDownloadOptions m_downloadOptions; private boolean m_isInstalling = false; private DeploymentPackageInstallOptions m_installOptions; private String m_pendingUninstPackageName; private String m_installVerificationDir; private String m_clientId; // ---------------------------------------------------------------- // // Dependencies // // ---------------------------------------------------------------- public void setSslManagerService(SslManagerService sslManagerService) { this.m_sslManagerService = sslManagerService; } public void unsetSslManagerService(SslManagerService sslManagerService) { this.m_sslManagerService = null; } protected void setDeploymentAdmin(DeploymentAdmin deploymentAdmin) { m_deploymentAdmin = deploymentAdmin; } protected void unsetDeploymentAdmin(DeploymentAdmin deploymentAdmin) { m_deploymentAdmin = null; } public void setDataTransportService(DataTransportService dataTransportService) { m_dataTransportService = dataTransportService; } public void unsetDataTransportService(DataTransportService dataTransportService) { m_dataTransportService = null; } public CloudDeploymentHandlerV2() { super(APP_ID); } // ---------------------------------------------------------------- // // Activation APIs // // ---------------------------------------------------------------- @Override protected void activate(ComponentContext componentContext) { s_logger.info("Cloud Deployment v2 is starting"); super.activate(componentContext); m_bundleContext = componentContext.getBundleContext(); m_clientId= m_dataTransportService.getClientId(); m_dpaConfPath = System.getProperty(DPA_CONF_PATH_PROPNAME); if (m_dpaConfPath == null || m_dpaConfPath.isEmpty()) { throw new ComponentException("The value of '" + DPA_CONF_PATH_PROPNAME + "' is not defined"); } String sKuraConfUrl = System.getProperty(KURA_CONF_URL_PROPNAME); if (sKuraConfUrl == null || sKuraConfUrl.isEmpty()) { throw new ComponentException("The value of '" + KURA_CONF_URL_PROPNAME + "' is not defined"); } URL kuraUrl = null; try { kuraUrl = new URL(sKuraConfUrl); } catch (MalformedURLException e) { throw new ComponentException("Invalid Kura configuration URL"); } Properties kuraProperties = new Properties(); try { kuraProperties.load(kuraUrl.openStream()); } catch (FileNotFoundException e) { throw new ComponentException("Kura configuration file not found", e); } catch (IOException e) { throw new ComponentException("Exception loading Kura configuration file", e); } m_packagesPath = kuraProperties.getProperty(PACKAGES_PATH_PROPNAME); if (m_packagesPath == null || m_packagesPath.isEmpty()) { throw new ComponentException("The value of '" + PACKAGES_PATH_PROPNAME + "' is not defined"); } if (kuraProperties.getProperty(PACKAGES_PATH_PROPNAME) != null && kuraProperties.getProperty(PACKAGES_PATH_PROPNAME).trim().equals("kura/packages")) { kuraProperties.setProperty(PACKAGES_PATH_PROPNAME, "/opt/eclipse/kura/kura/packages"); m_packagesPath = kuraProperties.getProperty(PACKAGES_PATH_PROPNAME); s_logger.warn("Overridding invalid kura.packages location"); } String kuraDataDir= kuraProperties.getProperty(KURA_DATA_DIR); m_installImplementation = new InstallImpl(this, kuraDataDir); m_installImplementation.setPackagesPath(m_packagesPath); m_installImplementation.setDpaConfPath(m_dpaConfPath); m_installImplementation.setDeploymentAdmin(m_deploymentAdmin); m_installImplementation.sendInstallConfirmations(); Thread t = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(5000); s_logger.info("STARTING DOWNLOAD..."); CloudletTopic ct = CloudletTopic.parseAppTopic("EXEC/download"); KuraRequestPayload request = new KuraRequestPayload(); request.setRequestId("RequestID"); request.setRequesterClientId("RequesterClientId"); String url = "https://s3.amazonaws.com/kura-resources/dps/heater.dp";//"http://esfdownload.eurotech-inc.com/update_site/esf3/3.0.2/user_workspace_archive_3.0.2.zip"; DeploymentPackageDownloadOptions options = new DeploymentPackageDownloadOptions(url, "dpName", "dpVersion"); options.setUsername("[email protected]"); options.setPassword("lc2251981"); // options.setPassword("errata"); request.addMetric(DeploymentPackageDownloadOptions.METRIC_DP_DOWNLOAD_URI, options.getDeployUrl()); request.addMetric(DeploymentPackageDownloadOptions.METRIC_DP_NAME, options.getDpName()); request.addMetric(DeploymentPackageDownloadOptions.METRIC_DP_VERSION, options.getDpVersion()); //request.addMetric(DeploymentPackageDownloadOptions.METRIC_HTTP_USER, options.getUsername()); //request.addMetric(DeploymentPackageDownloadOptions.METRIC_HTTP_PASSWORD, options.getPassword()); //request.addMetric(DeploymentPackageDownloadOptions.METRIC_BLOCK_SIZE, 1024 * 8); //request.addMetric(DeploymentPackageDownloadOptions.METRIC_DP_NOTIFY_BLOCK_SIZE, 1024 * 1024); request.addMetric(DeploymentPackageDownloadOptions.METRIC_JOB_ID, Long.parseLong("1111")); request.addMetric(DeploymentPackageDownloadOptions.METRIC_DP_INSTALL_SYSTEM_UPDATE, false); request.addMetric(DeploymentPackageDownloadOptions.METRIC_DP_REBOOT, true); KuraResponsePayload response = new KuraResponsePayload(KuraResponsePayload.RESPONSE_CODE_OK); doExec(ct, request, response); s_logger.info("*******************************************"); s_logger.info(response.getMetric(KuraResponsePayload.METRIC_RESPONSE_CODE).toString()); if(response.getBody() != null){ s_logger.info(new String(response.getBody())); } if(response.getMetric(METRIC_DOWNLOAD_STATUS) != null){ s_logger.info(response.getMetric(METRIC_DOWNLOAD_STATUS).toString()); } s_logger.info("*******************************************"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KuraException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); t.start(); } @Override protected void deactivate(ComponentContext componentContext) { s_logger.info("Bundle " + APP_ID + " is deactivating!"); if(downloaderFuture != null){ downloaderFuture.cancel(true); } if(installerFuture != null){ installerFuture.cancel(true); } m_bundleContext = null; } // ---------------------------------------------------------------- // // Public methods // // ---------------------------------------------------------------- public void publishMessage(DeploymentPackageOptions options, KuraPayload messagePayload, String messageType){ try { String messageTopic = new StringBuilder("NOTIFY/").append(options.getClientId()) .append("/") .append(messageType) .toString(); getCloudApplicationClient().controlPublish(options.getRequestClientId(), messageTopic, messagePayload, 2, DFLT_RETAIN, DFLT_PRIORITY); } catch (KuraException e) { s_logger.error("Error publishing response for command {} {}", messageType, e); } } // ---------------------------------------------------------------- // // Protected methods // // ---------------------------------------------------------------- @Override protected void doGet(CloudletTopic reqTopic, KuraRequestPayload reqPayload, KuraResponsePayload respPayload) throws KuraException { //doGetResource(reqTopic, reqPayload); String[] resources = reqTopic.getResources(); if (resources == null || resources.length == 0) { s_logger.error("Bad request topic: {}", reqTopic.toString()); s_logger.error("Expected one resource but found {}", resources != null ? resources.length : "none"); respPayload.setResponseCode(KuraResponsePayload.RESPONSE_CODE_BAD_REQUEST); return; } if (resources[0].equals(RESOURCE_DOWNLOAD)) { doGetDownload(reqPayload, respPayload); } else if (resources[0].equals(RESOURCE_INSTALL)) { doGetInstall(reqPayload, respPayload); } else if (resources[0].equals(RESOURCE_PACKAGES)) { doGetPackages(reqPayload, respPayload); } else if (resources[0].equals(RESOURCE_BUNDLES)) { doGetBundles(reqPayload, respPayload); } else { s_logger.error("Bad request topic: {}", reqTopic.toString()); s_logger.error("Cannot find resource with name: {}", resources[0]); respPayload.setResponseCode(KuraResponsePayload.RESPONSE_CODE_NOTFOUND); return; } } @Override protected void doExec(CloudletTopic reqTopic, KuraRequestPayload reqPayload, KuraResponsePayload respPayload) throws KuraException { String[] resources = reqTopic.getResources(); if (resources == null || resources.length == 0) { s_logger.error("Bad request topic: {}", reqTopic.toString()); s_logger.error("Expected one resource but found {}", resources != null ? resources.length : "none"); respPayload.setResponseCode(KuraResponsePayload.RESPONSE_CODE_BAD_REQUEST); return; } if (resources[0].equals(RESOURCE_DOWNLOAD)) { doExecDownload(reqPayload, respPayload); } else if (resources[0].equals(RESOURCE_INSTALL)) { doExecInstall(reqPayload, respPayload); } else if (resources[0].equals(RESOURCE_UNINSTALL)) { doExecUninstall(reqPayload, respPayload); } else if (resources[0].equals(RESOURCE_START)) { String bundleId = resources[1]; doExecStartStopBundle(reqPayload, respPayload, true, bundleId); } else if (resources[0].equals(RESOURCE_STOP)) { String bundleId = resources[1]; doExecStartStopBundle(reqPayload, respPayload, false, bundleId); }else { s_logger.error("Bad request topic: {}", reqTopic.toString()); s_logger.error("Cannot find resource with name: {}", resources[0]); respPayload.setResponseCode(KuraResponsePayload.RESPONSE_CODE_NOTFOUND); return; } } @Override protected void doDel(CloudletTopic reqTopic, KuraRequestPayload reqPayload, KuraResponsePayload respPayload) throws KuraException { String[] resources = reqTopic.getResources(); if (resources == null || resources.length == 0) { s_logger.error("Bad request topic: {}", reqTopic.toString()); s_logger.error("Expected one resource but found {}", resources != null ? resources.length : "none"); respPayload.setResponseCode(KuraResponsePayload.RESPONSE_CODE_BAD_REQUEST); return; } if (resources[0].equals(RESOURCE_DOWNLOAD)) { doDelDownload(reqPayload, respPayload); } else { s_logger.error("Bad request topic: {}", reqTopic.toString()); s_logger.error("Cannot find resource with name: {}", resources[0]); respPayload.setResponseCode(KuraResponsePayload.RESPONSE_CODE_NOTFOUND); return; } } // ---------------------------------------------------------------- // // Private methods // // ---------------------------------------------------------------- private void doDelDownload(KuraRequestPayload request, KuraResponsePayload response) { try{ m_downloadImplementation.getDownloadHelper().cancelDownload(); m_downloadImplementation.deleteDownloadedFile(); }catch(Exception ex){ s_logger.info("Error cancelling download!", ex); } } private void doExecDownload(KuraRequestPayload request, KuraResponsePayload response) { final DeploymentPackageDownloadOptions options; try { options = new DeploymentPackageDownloadOptions(request); options.setClientId(m_clientId); m_downloadImplementation= new DownloadImpl(options, this); } catch (Exception ex) { s_logger.info("Malformed download request!"); response.setResponseCode(KuraResponsePayload.RESPONSE_CODE_ERROR); response.setTimestamp(new Date()); try { response.setBody("Malformed donwload request".getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { // Ignore } response.setException(ex); return; } m_downloadOptions = options; if (s_pendingPackageUrl != null && s_pendingPackageUrl.equals(options.getDeployUrl())) { s_logger.info("Another request seems for the same URL is pending: {}.", s_pendingPackageUrl); response.setResponseCode(KuraResponsePayload.RESPONSE_CODE_OK); response.setTimestamp(new Date()); response.addMetric(METRIC_DOWNLOAD_STATUS, DOWNLOAD_STATUS.IN_PROGRESS); try { response.setBody("The requested resource is already in download".getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { } return; } else if (s_pendingPackageUrl != null && !s_pendingPackageUrl.equals(options.getDeployUrl())) { s_logger.info("Another request is pending for a different URL: {}.", s_pendingPackageUrl); response.setResponseCode(KuraResponsePayload.RESPONSE_CODE_ERROR); response.setTimestamp(new Date()); response.addMetric(METRIC_DOWNLOAD_STATUS, DOWNLOAD_STATUS.IN_PROGRESS); try { response.setBody("Only one request at a time is allowed".getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { } return; } boolean alreadyDownloaded = false; try { alreadyDownloaded = m_downloadImplementation.isAlreadyDownloaded(); } catch (KuraException ex) { response.setResponseCode(KuraResponsePayload.RESPONSE_CODE_ERROR); response.setException(ex); response.setTimestamp(new Date()); try { response.setBody("Error checking download status".getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { } return; } s_logger.info("About to download and install package at URL {}", options.getDeployUrl()); try { s_pendingPackageUrl = options.getDeployUrl(); m_downloadImplementation.setSslManager(m_sslManagerService); m_downloadImplementation.setAlreadyDownloadedFlag(alreadyDownloaded); m_downloadImplementation.setVerificationDirectory(m_installVerificationDir); s_logger.info("Downloading package from URL: " + options.getDeployUrl()); downloaderFuture = executor.submit(new Runnable(){ @Override public void run() { try { m_downloadImplementation.downloadDeploymentPackageInternal(); } catch (KuraException e) { } finally{ s_pendingPackageUrl = null; } } }); } catch (Exception e) { s_logger.error("Failed to download and install package at URL {}: {}", options.getDeployUrl(), e); s_pendingPackageUrl = null; response.setResponseCode(KuraResponsePayload.RESPONSE_CODE_ERROR); response.setTimestamp(new Date()); try { response.setBody(e.getMessage().getBytes("UTF-8")); } catch (UnsupportedEncodingException uee) { } } return; } private void doExecInstall(KuraRequestPayload request, KuraResponsePayload response){ final DeploymentPackageInstallOptions options; try { options = new DeploymentPackageInstallOptions(request); options.setClientId(m_clientId); } catch (Exception ex) { s_logger.info("Malformed install request!"); response.setResponseCode(KuraResponsePayload.RESPONSE_CODE_ERROR); response.setTimestamp(new Date()); try { response.setBody("Malformed install request".getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { // Ignore } response.setException(ex); return; } m_installOptions = options; boolean alreadyDownloaded = false; try { alreadyDownloaded = m_downloadImplementation.isAlreadyDownloaded(); } catch (KuraException ex) { response.setResponseCode(KuraResponsePayload.RESPONSE_CODE_ERROR); response.setException(ex); response.setTimestamp(new Date()); try { response.setBody("Error checking download status".getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { } return; } if(alreadyDownloaded && !m_isInstalling){ //Check if file exists try { m_isInstalling = true; final File dpFile = DownloadFileUtilities.getDpDownloadFile(options); m_installImplementation.setOptions(options); //if yes, install installerFuture = executor.submit(new Runnable(){ @Override public void run() { try { installDownloadedFile(dpFile, m_installOptions); } catch (KuraException e) { s_logger.error("Impossible to send an exception message to the cloud platform"); } finally { m_installOptions = null; m_isInstalling = false; } } }); } catch (IOException e) { response.setResponseCode(KuraResponsePayload.RESPONSE_CODE_ERROR); response.setException(e); response.setTimestamp(new Date()); try { response.setBody("Exception during install".getBytes("UTF-8")); } catch (UnsupportedEncodingException e1) { } } } else { response.setResponseCode(KuraResponsePayload.RESPONSE_CODE_ERROR); response.setException(new KuraException(KuraErrorCode.INTERNAL_ERROR)); response.setTimestamp(new Date()); try { response.setBody("Already installing/uninstalling".getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { } return; } } private void doExecUninstall(KuraRequestPayload request, KuraResponsePayload response) { final DeploymentPackageUninstallOptions options; try { options = new DeploymentPackageUninstallOptions(request); options.setClientId(m_clientId); } catch (Exception ex) { s_logger.info("Malformed uninstall request!"); response.setResponseCode(KuraResponsePayload.RESPONSE_CODE_ERROR); response.setTimestamp(new Date()); try { response.setBody("Malformed uninstall request".getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { // Ignore } response.setException(ex); return; } final String packageName = options.getDpName(); // // We only allow one request at a time if (!m_isInstalling && m_pendingUninstPackageName != null) { s_logger.info("Antother request seems still pending: {}. Checking if stale...", m_pendingUninstPackageName); response = new KuraResponsePayload(KuraResponsePayload.RESPONSE_CODE_ERROR); response.setTimestamp(new Date()); try { response.setBody("Only one request at a time is allowed".getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { // Ignore } } else { s_logger.info("About to uninstall package {}", packageName); try { m_isInstalling = true; m_pendingUninstPackageName = packageName; m_uninstallImplementation= new UninstallImpl(this, m_deploymentAdmin); s_logger.info("Uninstalling package..."); installerFuture = executor.submit(new Runnable(){ @Override public void run() { try { m_uninstallImplementation.uninstaller(options, packageName); } catch (Exception e) { try { m_uninstallImplementation.uninstallFailedAsync(options, packageName, e); } catch (KuraException e1) { } } finally { m_installOptions = null; m_isInstalling = false; } } }); } catch (Exception e) { s_logger.error("Failed to uninstall package {}: {}", packageName, e); response = new KuraResponsePayload(KuraResponsePayload.RESPONSE_CODE_ERROR); response.setTimestamp(new Date()); try { response.setBody(e.getMessage().getBytes("UTF-8")); } catch (UnsupportedEncodingException uee) { // Ignore } } finally { m_isInstalling = false; m_pendingUninstPackageName = null; } } } private void doExecStartStopBundle(KuraRequestPayload request, KuraResponsePayload response, boolean start, String bundleId) { if (bundleId == null) { s_logger.info("EXEC start/stop bundle: null bundle ID"); response.setResponseCode(KuraResponsePayload.RESPONSE_CODE_BAD_REQUEST); response.setTimestamp(new Date()); } else { Long id = null; try { id = Long.valueOf(bundleId); } catch (NumberFormatException e){ s_logger.error("EXEC start/stop bundle: bad bundle ID format: {}", e); response.setResponseCode(KuraResponsePayload.RESPONSE_CODE_BAD_REQUEST); response.setTimestamp(new Date()); response.setExceptionMessage(e.getMessage()); response.setExceptionStack(ThrowableUtil.stackTraceAsString(e)); } if (id != null) { s_logger.info("Executing command {}", start ? RESOURCE_START : RESOURCE_STOP); Bundle bundle = m_bundleContext.getBundle(id); if (bundle == null) { s_logger.error("Bundle ID {} not found", id); response.setResponseCode(KuraResponsePayload.RESPONSE_CODE_NOTFOUND); response.setTimestamp(new Date()); } else { try { if (start) { bundle.start(); } else { bundle.stop(); } s_logger.info("{} bundle ID {} ({})", new Object[] {start ? "Started" : "Stopped", id, bundle.getSymbolicName()}); response.setResponseCode(KuraResponsePayload.RESPONSE_CODE_OK); response.setTimestamp(new Date()); } catch (BundleException e) { s_logger.error("Failed to {} bundle {}: {}", new Object[] {start ? "start" : "stop", id, e}); response.setResponseCode(KuraResponsePayload.RESPONSE_CODE_ERROR); response.setTimestamp(new Date()); } } } } } private void doGetInstall(KuraRequestPayload reqPayload, KuraResponsePayload respPayload) { if(m_isInstalling){ m_installImplementation.installInProgressSyncMessage(respPayload); } else { m_installImplementation.installIdleSyncMessage(respPayload); } } private void doGetDownload(KuraRequestPayload reqPayload, KuraResponsePayload respPayload) { if (s_pendingPackageUrl != null){ //A download is pending DownloadCountingOutputStream downloadHelper= m_downloadImplementation.getDownloadHelper(); DownloadImpl.downloadInProgressSyncMessage(respPayload, downloadHelper, m_downloadOptions); } else { //No pending downloads DownloadImpl.downloadAlreadyDoneSyncMessage(respPayload); //is it right? Do we remove the last object } } private void doGetPackages(KuraRequestPayload request, KuraResponsePayload response) { DeploymentPackage[] dps = m_deploymentAdmin.listDeploymentPackages(); XmlDeploymentPackages xdps = new XmlDeploymentPackages(); XmlDeploymentPackage[] axdp = new XmlDeploymentPackage[dps.length]; for (int i = 0; i < dps.length; i++) { DeploymentPackage dp = dps[i]; XmlDeploymentPackage xdp = new XmlDeploymentPackage(); xdp.setName(dp.getName()); xdp.setVersion(dp.getVersion().toString()); BundleInfo[] bis = dp.getBundleInfos(); XmlBundleInfo[] axbi = new XmlBundleInfo[bis.length]; for (int j = 0; j < bis.length; j++) { BundleInfo bi = bis[j]; XmlBundleInfo xbi = new XmlBundleInfo(); xbi.setName(bi.getSymbolicName()); xbi.setVersion(bi.getVersion().toString()); axbi[j] = xbi; } xdp.setBundleInfos(axbi); axdp[i] = xdp; } xdps.setDeploymentPackages(axdp); try { String s = XmlUtil.marshal(xdps); //s_logger.info("Getting resource {}: {}", RESOURCE_PACKAGES, s); response.setTimestamp(new Date()); try { response.setBody(s.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { // Ignore } } catch (Exception e) { s_logger.error("Error getting resource {}: {}", RESOURCE_PACKAGES, e); } } private void doGetBundles(KuraRequestPayload request, KuraResponsePayload response) { Bundle[] bundles = m_bundleContext.getBundles(); XmlBundles xmlBundles = new XmlBundles(); XmlBundle[] axb = new XmlBundle[bundles.length]; for (int i = 0; i < bundles.length; i++) { Bundle bundle = bundles[i]; XmlBundle xmlBundle = new XmlBundle(); xmlBundle.setName(bundle.getSymbolicName()); xmlBundle.setVersion(bundle.getVersion().toString()); xmlBundle.setId(bundle.getBundleId()); int state = bundle.getState(); switch(state) { case Bundle.UNINSTALLED: xmlBundle.setState("UNINSTALLED"); break; case Bundle.INSTALLED: xmlBundle.setState("INSTALLED"); break; case Bundle.RESOLVED: xmlBundle.setState("RESOLVED"); break; case Bundle.STARTING: xmlBundle.setState("STARTING"); break; case Bundle.STOPPING: xmlBundle.setState("STOPPING"); break; case Bundle.ACTIVE: xmlBundle.setState("ACTIVE"); break; default: xmlBundle.setState(String.valueOf(state)); } axb[i] = xmlBundle; } xmlBundles.setBundles(axb); try { String s = XmlUtil.marshal(xmlBundles); //s_logger.info("Getting resource {}: {}", RESOURCE_BUNDLES, s); response.setTimestamp(new Date()); try { response.setBody(s.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { // Ignore } } catch (Exception e) { s_logger.error("Error getting resource {}: {}", RESOURCE_BUNDLES, e); } } public void installDownloadedFile(File dpFile, DeploymentPackageInstallOptions options) throws KuraException { try{ if(options.getSystemUpdate()){ m_installImplementation.installSh(options, dpFile); } else { m_installImplementation.installDp(options, dpFile); } } catch (Exception e) { s_logger.info("Install exception"); m_installImplementation.installFailedAsync(options, dpFile.getName(), e); } } }
Removed unwanted debug code. Signed-off-by: MMaiero <[email protected]>
kura/org.eclipse.kura.core.deployment/src/main/java/org/eclipse/kura/core/deployment/CloudDeploymentHandlerV2.java
Removed unwanted debug code.
<ide><path>ura/org.eclipse.kura.core.deployment/src/main/java/org/eclipse/kura/core/deployment/CloudDeploymentHandlerV2.java <ide> m_installImplementation.setDpaConfPath(m_dpaConfPath); <ide> m_installImplementation.setDeploymentAdmin(m_deploymentAdmin); <ide> m_installImplementation.sendInstallConfirmations(); <del> <del> <del> <del> Thread t = new Thread(new Runnable() { <del> <del> @Override <del> public void run() { <del> try { <del> Thread.sleep(5000); <del> s_logger.info("STARTING DOWNLOAD..."); <del> CloudletTopic ct = CloudletTopic.parseAppTopic("EXEC/download"); <del> KuraRequestPayload request = new KuraRequestPayload(); <del> request.setRequestId("RequestID"); <del> request.setRequesterClientId("RequesterClientId"); <del> String url = "https://s3.amazonaws.com/kura-resources/dps/heater.dp";//"http://esfdownload.eurotech-inc.com/update_site/esf3/3.0.2/user_workspace_archive_3.0.2.zip"; <del> DeploymentPackageDownloadOptions options = new DeploymentPackageDownloadOptions(url, "dpName", "dpVersion"); <del> options.setUsername("[email protected]"); <del> options.setPassword("lc2251981"); <del> // options.setPassword("errata"); <del> request.addMetric(DeploymentPackageDownloadOptions.METRIC_DP_DOWNLOAD_URI, options.getDeployUrl()); <del> request.addMetric(DeploymentPackageDownloadOptions.METRIC_DP_NAME, options.getDpName()); <del> request.addMetric(DeploymentPackageDownloadOptions.METRIC_DP_VERSION, options.getDpVersion()); <del> //request.addMetric(DeploymentPackageDownloadOptions.METRIC_HTTP_USER, options.getUsername()); <del> //request.addMetric(DeploymentPackageDownloadOptions.METRIC_HTTP_PASSWORD, options.getPassword()); <del> //request.addMetric(DeploymentPackageDownloadOptions.METRIC_BLOCK_SIZE, 1024 * 8); <del> //request.addMetric(DeploymentPackageDownloadOptions.METRIC_DP_NOTIFY_BLOCK_SIZE, 1024 * 1024); <del> request.addMetric(DeploymentPackageDownloadOptions.METRIC_JOB_ID, Long.parseLong("1111")); <del> request.addMetric(DeploymentPackageDownloadOptions.METRIC_DP_INSTALL_SYSTEM_UPDATE, false); <del> request.addMetric(DeploymentPackageDownloadOptions.METRIC_DP_REBOOT, true); <del> <del> KuraResponsePayload response = new KuraResponsePayload(KuraResponsePayload.RESPONSE_CODE_OK); <del> <del> doExec(ct, request, response); <del> <del> s_logger.info("*******************************************"); <del> s_logger.info(response.getMetric(KuraResponsePayload.METRIC_RESPONSE_CODE).toString()); <del> if(response.getBody() != null){ <del> s_logger.info(new String(response.getBody())); <del> } <del> if(response.getMetric(METRIC_DOWNLOAD_STATUS) != null){ <del> s_logger.info(response.getMetric(METRIC_DOWNLOAD_STATUS).toString()); <del> } <del> s_logger.info("*******************************************"); <del> <del> } catch (InterruptedException e) { <del> // TODO Auto-generated catch block <del> e.printStackTrace(); <del> } catch (KuraException e) { <del> // TODO Auto-generated catch block <del> e.printStackTrace(); <del> } <del> } <del> <del> }); <del> t.start(); <ide> } <ide> <ide> @Override
JavaScript
mit
43b08df3b318c66c370317d7524314489c85153a
0
jmptrader/formula.js,darioajr/formula.js,zp-j/formula.js,GerHobbelt/formula.js,fashionsun/formula.js
// Copyright (c) 2012 Sutoiku, Inc. // 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. // Some algorithms have been ported from Apache OpenOffice: /************************************************************** * * 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. * *************************************************************/ /*jslint evil: true*/ /*jshint -W079 */ /*global define */ (function () { if (typeof exports !== "undefined") { module.exports = exportModule( require('numeric'), require('numeral'), require('jStat'), require('moment'), require('lodash'), require('underscore.string'), require('blueimp-md5') ); } else if (typeof define === "function" && define.amd) { define( 'formula', ['numeric', 'numeral', 'jStat', 'moment', 'lodash', 'underscore.string', 'md5'], exportModule ); } function exportModule(numeric, numeral, jStatLib, moment, _, _s, md5Lib) { var Formula = {}, jStat = jStatLib.jStat, md5 = md5Lib.md5; var MEMOIZED_FACT = []; var SQRT2PI = 2.5066282746310002; var WEEK_STARTS = [ undefined, 0, 1, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, 1, 2, 3, 4, 5, 6, 0 ]; var WEEK_TYPES = [ [], [1, 2, 3, 4, 5, 6, 7], [7, 1, 2, 3, 4, 5, 6], [6, 0, 1, 2, 3, 4, 5], [], [], [], [], [], [], [], [7, 1, 2, 3, 4, 5, 6], [6, 7, 1, 2, 3, 4, 5], [5, 6, 7, 1, 2, 3, 4], [4, 5, 6, 7, 1, 2, 3], [3, 4, 5, 6, 7, 1, 2], [2, 3, 4, 5, 6, 7, 1], [1, 2, 3, 4, 5, 6, 7] ]; var WEEKEND_TYPES = [ [], [6, 0], [0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], undefined, undefined, undefined, [0], [1], [2], [3], [4], [5], [6] ]; // Override some functions Formula.UNIQUE = function () { return _.unique(arguments); }; Formula.FLATTEN = function () { return _.flatten(arguments); }; // Generate a callback function Formula.FUNCTION = function () { var args = Array.prototype.slice.call(arguments); var expression = args[args.length - 1]; var regexp = /(\w+)\(/g; var newExpression = expression.replace(regexp, function () { return "Formulae." + arguments[0]; }); args[args.length - 1] = "return " + newExpression + ";"; if (newExpression !== expression) { args.unshift('Formulae'); } return Function.apply(null, args); }; // Moment functions Formula.MOMENT = function (timestamp, format) { return moment(timestamp).format(format); }; Formula.MOMENTADD = function (start_date, period, number) { return moment(start_date).add(period, number); }; Formula.MOMENTDIFF = function (start_date, end_date, period) { return moment(end_date).diff(moment.utc(start_date), period); }; Formula.MOMENTSUB = function (start_date, period, number) { return moment(start_date).subtract(period, number); }; Formula.MOMENTUTC = function (timestamp, format) { return moment.utc(timestamp).format(format); }; Formula.MOMENTUTCADD = function (start_date, period, number) { return moment.utc(start_date).add(period, number); }; Formula.MOMENTUTCDIFF = function (start_date, end_date, period) { return moment.utc(end_date).diff(moment.utc(start_date), period); }; Formula.MOMENTUTCSUB = function (start_date, period, number) { return moment.utc(start_date).subtract(period, number); }; Formula.MOMENTUNIX = function (unixTime) { return moment.unix(unixTime).toDate(); }; Formula.MOMENTFORMAT = function (date, format) { return moment(date).format(format); }; Formula.MOMENTISLEAPYEAR = function (date, format) { return moment(date, format).isLeapYear(); }; Formula.MOMENTISDST = function (date, format) { return moment(date, format).isDST(); }; Formula.MOMENTSTARTOF = function (date, units, format) { return moment(date, format).startOf(units).toDate(); }; Formula.MOMENTENDOF = function (date, units, format) { return moment(date, format).endOf(units).toDate(); }; Formula.MOMENTISAFTER = function (date1, date2, format) { return moment(date1, format).isAfter(moment(date2, format)); }; Formula.MOMENTISBEFORE = function (date1, date2, format) { return moment(date1, format).isBefore(moment(date2, format)); }; Formula.INTERVAL = function (second) { var year = Math.floor(second/946080000); second = second%946080000; var month = Math.floor(second/2592000); second = second%2592000; var day = Math.floor(second/86400); second = second%86400; var hour = Math.floor(second/3600); second = second%3600; var min = Math.floor(second/60); second = second%60; var sec = second; year = (year > 0) ? year + 'Y' : ''; month = (month > 0) ? month + 'M' : ''; day = (day > 0) ? day + 'D' : ''; hour = (hour > 0) ? hour + 'H' : ''; min = (min > 0) ? min + 'M' : ''; sec = (sec > 0) ? sec + 'S' : ''; return 'P' + year + month + day + 'T' + hour + min + sec; }; // Custom Functions Formula.ARGSCONCAT = function (args) { var result = []; for (var i = 0; i < args.length; i++) { result = result.concat(args[i]); } return result; }; Formula.ARGSTOARRAY = function (args) { return Array.prototype.slice.call(args, 0); }; Formula.CLEANFLOAT = function (number) { var power = Math.pow(10, 14); return Math.round(number * power) / power; }; Formula.COUNTIN = function (range, value) { var result = 0; for (var i = 0; i < range.length; i++) { if (range[i] === value) { result++; } } return result; }; Formula.FINDFIELD = function(database, title) { var index = null; for (var i = 0; i < database.length; i++) { if (database[i][0] === title) { index = i; break; } } // Return error if the input field title is incorrect if (index == null) { return '#VALUE!'; } return index; }; Formula.FINDRESULTINDEX = function(database, criteria) { var maxCriteriaLength = criteria[0].length; for (var i = 1; i < criteria.length; i++) { if (criteria[i].length > maxCriteriaLength) { maxCriteriaLength = criteria[i].length; } } var columnResultIndexes = []; for (i = 1; i < maxCriteriaLength; i++) { var rowResultIndexes = []; for (var j = 0; j < criteria.length; j++) { if (criteria[j].length < maxCriteriaLength) { continue; } var criteriaTitle = criteria[j][0]; var criteriaIndex = Formula.FINDFIELD(database, criteriaTitle); var criteriaValues = _.rest(database[criteriaIndex]); var count = 0; var singleResultIndexes = []; for (var k = 0; k < criteriaValues.length; k++) { if (eval(criteriaValues[k] + criteria[j][i])) { singleResultIndexes[count++] = k; } } rowResultIndexes[j] = singleResultIndexes; } columnResultIndexes[i - 1] = _.intersection.apply(_, rowResultIndexes); } var resultIndexes = _.union.apply(_, columnResultIndexes); return resultIndexes; }; // Database functions Formula.DAVERAGE = function(database, field, criteria) { // Return error if field is not a number and not a string if (isNaN(field) && (typeof field !== "string")) { return '#VALUE!'; } var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); var targetFields = []; if (typeof field === "string") { var index = Formula.FINDFIELD(database, field); targetFields = _.rest(database[index]); } else { targetFields = _.rest(database[field]); } var sum = 0; for (var i = 0; i < resultIndexes.length; i++) { sum += targetFields[resultIndexes[i]]; } var average = Formula.IF(resultIndexes.length === 0, "#DIV/0!", sum / resultIndexes.length); return average; }; Formula.DCOUNT = function(database, field, criteria) { // Return error if field is not a number and not a string if (isNaN(field) && (typeof field !== "string")) { return '#VALUE!'; } var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); var targetFields = []; if (typeof field === "string") { var index = Formula.FINDFIELD(database, field); targetFields = _.rest(database[index]); } else { targetFields = _.rest(database[field]); } var targetValues = []; for (var i = 0; i < resultIndexes.length; i++) { targetValues[i] = targetFields[resultIndexes[i]]; } return Formula.COUNT(targetValues); }; Formula.DCOUNTA = function(database, field, criteria) { // Return error if field is not a number and not a string if (isNaN(field) && (typeof field !== "string")) { return '#VALUE!'; } var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); var targetFields = []; if (typeof field === "string") { var index = Formula.FINDFIELD(database, field); targetFields = _.rest(database[index]); } else { targetFields = _.rest(database[field]); } var targetValues = []; for (var i = 0; i < resultIndexes.length; i++) { targetValues[i] = targetFields[resultIndexes[i]]; } return Formula.COUNTA(targetValues); }; Formula.DGET = function(database, field, criteria) { // Return error if field is not a number and not a string if (isNaN(field) && (typeof field !== "string")) { return '#VALUE!'; } var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); var targetFields = []; if (typeof field === "string") { var index = Formula.FINDFIELD(database, field); targetFields = _.rest(database[index]); } else { targetFields = _.rest(database[field]); } var targetValues = 0; // Return error if no record meets the criteria if (resultIndexes.length === 0) { return '#VALUE!'; } // Returns the #NUM! error value because more than one record meets the // criteria if (resultIndexes.length > 1) { return '#NUM!'; } return targetFields[resultIndexes[0]]; }; Formula.DMAX = function(database, field, criteria) { // Return error if field is not a number and not a string if (isNaN(field) && (typeof field !== "string")) { return '#VALUE!'; } var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); var targetFields = []; if (typeof field === "string") { var index = Formula.FINDFIELD(database, field); targetFields = _.rest(database[index]); } else { targetFields = _.rest(database[field]); } var maxValue = targetFields[resultIndexes[0]]; for (var i = 1; i < resultIndexes.length; i++) { if (maxValue < targetFields[resultIndexes[i]]) { maxValue = targetFields[resultIndexes[i]]; } } return maxValue; }; Formula.DMIN = function(database, field, criteria) { // Return error if field is not a number and not a string if (isNaN(field) && (typeof field !== "string")) { return '#VALUE!'; } var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); var targetFields = []; if (typeof field === "string") { var index = Formula.FINDFIELD(database, field); targetFields = _.rest(database[index]); } else { targetFields = _.rest(database[field]); } var minValue = targetFields[resultIndexes[0]]; for (var i = 1; i < resultIndexes.length; i++) { if (minValue > targetFields[resultIndexes[i]]) { minValue = targetFields[resultIndexes[i]]; } } return minValue; }; Formula.DPRODUCT = function(database, field, criteria) { // Return error if field is not a number and not a string if (isNaN(field) && (typeof field !== "string")) { return '#VALUE!'; } var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); var targetFields = []; if (typeof field === "string") { var index = Formula.FINDFIELD(database, field); targetFields = _.rest(database[index]); } else { targetFields = _.rest(database[field]); } var targetValues = []; for (var i = 0; i < resultIndexes.length; i++) { targetValues[i] = targetFields[resultIndexes[i]]; } targetValues = _.compact(targetValues); var result = 1; for (i = 0; i < targetValues.length; i++) { result *= targetValues[i]; } return result; }; Formula.DSTDEV = function(database, field, criteria) { // Return error if field is not a number and not a string if (isNaN(field) && (typeof field !== "string")) { return '#VALUE!'; } var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); var targetFields = []; if (typeof field === "string") { var index = Formula.FINDFIELD(database, field); targetFields = _.rest(database[index]); } else { targetFields = _.rest(database[field]); } var targetValues = []; for (var i = 0; i < resultIndexes.length; i++) { targetValues[i] = targetFields[resultIndexes[i]]; } targetValues = _.compact(targetValues); return Formula.STDEVS(targetValues); }; Formula.DSTDEVP = function(database, field, criteria) { // Return error if field is not a number and not a string if (isNaN(field) && (typeof field !== "string")) { return '#VALUE!'; } var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); var targetFields = []; if (typeof field === "string") { var index = Formula.FINDFIELD(database, field); targetFields = _.rest(database[index]); } else { targetFields = _.rest(database[field]); } var targetValues = []; for (var i = 0; i < resultIndexes.length; i++) { targetValues[i] = targetFields[resultIndexes[i]]; } targetValues = _.compact(targetValues); return Formula.STDEVP(targetValues); }; Formula.DSUM = function(database, field, criteria) { // Return error if field is not a number and not a string if (isNaN(field) && (typeof field !== "string")) { return '#VALUE!'; } var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); var targetFields = []; if (typeof field === "string") { var index = Formula.FINDFIELD(database, field); targetFields = _.rest(database[index]); } else { targetFields = _.rest(database[field]); } var targetValues = []; for (var i = 0; i < resultIndexes.length; i++) { targetValues[i] = targetFields[resultIndexes[i]]; } return Formula.SUM(targetValues); }; Formula.DVAR = function(database, field, criteria) { // Return error if field is not a number and not a string if (isNaN(field) && (typeof field !== "string")) { return '#VALUE!'; } var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); var targetFields = []; if (typeof field === "string") { var index = Formula.FINDFIELD(database, field); targetFields = _.rest(database[index]); } else { targetFields = _.rest(database[field]); } var targetValues = []; for (var i = 0; i < resultIndexes.length; i++) { targetValues[i] = targetFields[resultIndexes[i]]; } return Formula.VARS(targetValues); }; Formula.DVARP = function(database, field, criteria) { // Return error if field is not a number and not a string if (isNaN(field) && (typeof field !== "string")) { return '#VALUE!'; } var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); var targetFields = []; if (typeof field === "string") { var index = Formula.FINDFIELD(database, field); targetFields = _.rest(database[index]); } else { targetFields = _.rest(database[field]); } var targetValues = []; for (var i = 0; i < resultIndexes.length; i++) { targetValues[i] = targetFields[resultIndexes[i]]; } return Formula.VARP(targetValues); }; Formula.GETJSON = function (file) { var request = new XMLHttpRequest(); request.open('GET', file, false); request.send(null); if (request.status === 200) { return JSON.parse(request.responseText); } }; // Date functions Formula.DATE = function (year, month, day) { return new Date(year, month - 1, day); }; Formula.DATEVALUE = function (date_text) { return Math.ceil((moment(date_text) - moment('1900-1-1')) / 86400000) + 2; }; Formula.DAY = function (date) { return moment(new Date(date)).date(); }; Formula.DAYS = function (end_date, start_date) { return moment(new Date(end_date)).diff(moment(new Date(start_date)), 'days'); }; Formula.DAYS360 = function (start_date, end_date, method) { var start = moment(new Date(start_date)); var end = moment(new Date(end_date)); var smd = 31; var emd = 31; var sd = start.date(); var ed = end.date(); if (method) { sd = (sd === 31) ? 30 : sd; ed = (ed === 31) ? 30 : ed; } else { if (start.month() === 1) { smd = start.daysInMonth(); } if (end.month() === 1) { emd = end.daysInMonth(); } sd = (sd === smd) ? 30 : sd; if (sd === 30 || sd === smd) { ed = (ed === emd) ? 30 : ed; } } return 360 * (end.year() - start.year()) + 30 * (end.month() - start.month()) + (ed - sd); }; Formula.EDATE = function (start_date, months) { return moment(new Date(start_date)).add('months', months).toDate(); }; Formula.EOMONTH = function (start_date, months) { var edate = moment(new Date(start_date)).add('months', months); return new Date(edate.year(), edate.month(), edate.daysInMonth()); }; Formula.FROMNOW = function (timestamp, nosuffix) { return moment(new Date(timestamp)).fromNow(nosuffix); }; Formula.HOUR = function (timestamp) { return (timestamp <= 1) ? Math.floor(24 * timestamp) : moment(new Date(timestamp)).hours(); }; Formula.MINUTE = function (timestamp) { return (timestamp <= 1) ? Math.floor(24 * 60 * timestamp) - 60 * Math.floor(24 * timestamp) : moment(new Date(timestamp)).minutes(); }; Formula.ISOWEEKNUM = function (date) { return moment(new Date(date)).format('w'); }; Formula.MONTH = function (timestamp) { return moment(new Date(timestamp)).month() + 1; }; Formula.NETWORKDAYS = function (start_date, end_date, holidays) { return Formula.NETWORKDAYSINTL(start_date, end_date, 1, holidays); }; Formula.NETWORKDAYSINTL = function (start_date, end_date, weekend, holidays) { var weekend_type = (typeof weekend === 'undefined') ? 1 : weekend; var weekend_days = WEEKEND_TYPES[weekend_type]; var sd = moment(start_date); var ed = moment(end_date); var net_days = ed.diff(sd, 'days') + 1; var net_work_days = net_days; var cd = sd; var holiday_dates = []; if (typeof holidays !== 'undefined') { for (var i = 0; i < holidays.length; i++) { holiday_dates[i] = moment(new Date(holidays[i])).format('MM-DD-YYYY'); } } if (!weekend_days.length && !holiday_dates.length) { // No need to loop here. return net_work_days; } var j = 0; while (j < net_days) { if (weekend_days.indexOf(parseInt(cd.format('d'), 10)) >= 0) { net_work_days--; } else if (holiday_dates.indexOf(cd.format('MM-DD-YYYY')) >= 0) { net_work_days--; } cd = cd.add('days', 1); j++; } return net_work_days; }; Formula.NOW = function () { return new Date(); }; Formula.SECOND = function (timestamp) { return moment(new Date(timestamp)).seconds(); }; Formula.TIME = function (hour, minute, second) { return (3600 * hour + 60 * minute + second) / 86400; }; Formula.TIMEVALUE = function (time_text) { var timestamp = moment(new Date(time_text)); return (3600 * timestamp.hours() + 60 * timestamp.minutes() + timestamp.seconds()) / 86400; }; Formula.TODAY = function () { return new Date(); }; Formula.WEEKDAY = function (date, type) { var week_day = moment(new Date(date)).format('d'); var week_type = (typeof type === 'undefined') ? 1 : type; return WEEK_TYPES[week_type][week_day]; }; Formula.WEEKNUM = function (date, type) { var current_date = moment(new Date(date)); var january_first = moment(new Date(current_date.year(), 0, 1)); var week_type = (typeof type === 'undefined') ? 1 : type; var week_start = WEEK_STARTS[week_type]; var first_day = january_first.format('d'); var offset = (first_day < week_start) ? week_start - first_day + 1 : first_day - week_start; if (week_type === 21) { return Formula.ISOWEEKNUM(date); } else { return Math.floor(current_date.diff(january_first.subtract('days', offset), 'days') / 7) + 1; } }; Formula.WORKDAY = function (start_date, days, holidays) { return Formula.WORKDAYINTL(start_date, days, 1, holidays); }; Formula.WORKDAYINTL = function (start_date, days, weekend, holidays) { var weekend_type = (typeof weekend === 'undefined') ? 1 : weekend; var weekend_days = WEEKEND_TYPES[weekend_type]; var sd = moment(new Date(start_date)); var cd = sd; var day_of_week = ''; var holiday_dates = []; if (typeof holidays !== 'undefined') { for (var i = 0; i < holidays.length; i++) { holiday_dates[i] = moment(new Date(holidays[i])).format('MM-DD-YYYY'); } } var j = 0; while (j < days) { cd = cd.add('days', 1); day_of_week = cd.format('d'); if (weekend_days.indexOf(parseInt(day_of_week, 10)) < 0 && holiday_dates.indexOf(cd.format('MM-DD-YYYY')) < 0) { j++; } } return cd.toDate(); }; Formula.YEAR = function (date) { return moment(new Date(date)).year(); }; Formula.YEARFRAC = function (start_date, end_date, basis) { // Credits: David A. Wheeler [http://www.dwheeler.com/] // Initialize parameters basis = (typeof basis === 'undefined') ? 0 : basis; var sdate = moment(new Date(start_date)); var edate = moment(new Date(end_date)); // Return error if either date is invalid if (!sdate.isValid() || !edate.isValid()) { return '#VALUE!'; } // Return error if basis is neither 0, 1, 2, 3, or 4 if ([0, 1, 2, 3, 4].indexOf(basis) === -1) { return '#NUM!'; } // Return zero if start_date and end_date are the same if (sdate === edate) { return 0; } // Swap dates if start_date is later than end_date if (sdate.diff(edate) > 0) { edate = moment(new Date(start_date)); sdate = moment(new Date(end_date)); } // Lookup years, months, and days var syear = sdate.year(); var smonth = sdate.month(); var sday = sdate.date(); var eyear = edate.year(); var emonth = edate.month(); var eday = edate.date(); switch (basis) { case 0: // US (NASD) 30/360 // Note: if eday == 31, it stays 31 if sday < 30 if (sday === 31 && eday === 31) { sday = 30; eday = 30; } else if (sday === 31) { sday = 30; } else if (sday === 30 && eday === 31) { eday = 30; } else if (smonth === 1 && emonth === 1 && sdate.daysInMonth() === sday && edate.daysInMonth() === eday) { sday = 30; eday = 30; } else if (smonth === 1 && sdate.daysInMonth() === sday) { sday = 30; } return ((eday + emonth * 30 + eyear * 360) - (sday + smonth * 30 + syear * 360)) / 360; case 1: // Actual/actual var feb29Between = function (date1, date2) { // Requires year2 == (year1 + 1) or year2 == year1 // Returns TRUE if February 29 is between the two dates (date1 may be February 29), with two possibilities: // year1 is a leap year and date1 <= Februay 29 of year1 // year2 is a leap year and date2 > Februay 29 of year2 var mar1year1 = moment(new Date(date1.year(), 2, 1)); if (moment([date1.year()]).isLeapYear() && date1.diff(mar1year1) < 0 && date2.diff(mar1year1) >= 0) { return true; } var mar1year2 = moment(new Date(date2.year(), 2, 1)); if (moment([date2.year()]).isLeapYear() && date2.diff(mar1year2) >= 0 && date1.diff(mar1year2) < 0) { return true; } return false; }; var ylength = 365; if (syear === eyear || ((syear + 1) === eyear) && ((smonth > emonth) || ((smonth === emonth) && (sday >= eday)))) { if (syear === eyear && moment([syear]).isLeapYear()) { ylength = 366; } else if (feb29Between(sdate, edate) || (emonth === 1 && eday === 29)) { ylength = 366; } return edate.diff(sdate, 'days') / ylength; } else { var years = (eyear - syear) + 1; var days = moment(new Date(eyear + 1, 0, 1)).diff(moment(new Date(syear, 0, 1)), 'days'); var average = days / years; return edate.diff(sdate, 'days') / average; } break; case 2: // Actual/360 return edate.diff(sdate, 'days') / 360; case 3: // Actual/365 return edate.diff(sdate, 'days') / 365; case 4: // European 30/360 if (sday === 31) { sday = 30; } if (eday === 31) { eday = 30; } // Remarkably, do NOT change February 28 or February 29 at ALL return ((eday + emonth * 30 + eyear * 360) - (sday + smonth * 30 + syear * 360)) / 360; } }; // Engineering functions Formula.BESSELI = function () { return; }; Formula.BESSELJ = function () { return; }; Formula.BESSELK = function () { return; }; Formula.BESSELY = function () { return; }; Formula.VALIDBIN = function (number) { return (/^[01]{1,10}$/).test(number); }; Formula.BIN2DEC = function (number) { // Return error if number is not binary or contains more than 10 characters (10 digits) if (!Formula.VALIDBIN(number)) { return '#NUM!'; } // Convert binary number to decimal var result = parseInt(number, 2); // Handle negative numbers var stringified = number.toString(); if (stringified.length === 10 && stringified.substring(0, 1) === '1') { return parseInt(stringified.substring(1), 2) - 512; } else { return result; } }; Formula.BIN2HEX = function (number, places) { // Return error if number is not binary or contains more than 10 characters (10 digits) if (!Formula.VALIDBIN(number)) { return '#NUM!'; } // Ignore places and return a 10-character hexadecimal number if number is negative var stringified = number.toString(); if (stringified.length === 10 && stringified.substring(0, 1) === '1') { return (1099511627264 + parseInt(stringified.substring(1), 2)).toString(16); } // Convert binary number to hexadecimal var result = parseInt(number, 2).toString(16); // Return hexadecimal number using the minimum number of characters necessary if places is undefined if (typeof places === 'undefined') { return result; } else { // Return error if places is nonnumeric if (isNaN(places)) { return '#VALUE!'; } // Return error if places is negative if (places < 0) { return '#NUM!'; } // Truncate places in case it is not an integer places = Math.floor(places); // Pad return value with leading 0s (zeros) if necessary (using Underscore.string) return (places >= result.length) ? _s.repeat('0', places - result.length) + result : '#NUM!'; } }; Formula.BIN2OCT = function (number, places) { // Return error if number is not binary or contains more than 10 characters (10 digits) if (!Formula.VALIDBIN(number)) { return '#NUM!'; } // Ignore places and return a 10-character octal number if number is negative var stringified = number.toString(); if (stringified.length === 10 && stringified.substring(0, 1) === '1') { return (1073741312 + parseInt(stringified.substring(1), 2)).toString(8); } // Convert binary number to octal var result = parseInt(number, 2).toString(8); // Return octal number using the minimum number of characters necessary if places is undefined if (typeof places === 'undefined') { return result; } else { // Return error if places is nonnumeric if (isNaN(places)) { return '#VALUE!'; } // Return error if places is negative if (places < 0) { return '#NUM!'; } // Truncate places in case it is not an integer places = Math.floor(places); // Pad return value with leading 0s (zeros) if necessary (using Underscore.string) return (places >= result.length) ? _s.repeat('0', places - result.length) + result : '#NUM!'; } }; Formula.BITAND = function (number1, number2) { // Return error if either number is a non-numeric value if (isNaN(number1) || isNaN(number2)) { return '#VALUE!'; } // Return error if either number is less than 0 if (number1 < 0 || number2 < 0) { return '#NUM!'; } // Return error if either number is a non-integer if (Math.floor(number1) !== number1 || Math.floor(number2) !== number2) { return '#NUM!'; } // Return error if either number is greater than (2^48)-1 if (number1 > 281474976710655 || number2 > 281474976710655) { return '#NUM!'; } // Return bitwise AND of two numbers return number1 & number2; }; Formula.BITLSHIFT = function (number, shift) { // Return error if either number is a non-numeric value if (isNaN(number) || isNaN(shift)) { return '#VALUE!'; } // Return error if number is less than 0 if (number < 0) { return '#NUM!'; } // Return error if number is a non-integer if (Math.floor(number) !== number) { return '#NUM!'; } // Return error if number is greater than (2^48)-1 if (number > 281474976710655) { return '#NUM!'; } // Return error if the absolute value of shift is greater than 53 if (Math.abs(shift) > 53) { return '#NUM!'; } // Return number shifted by shift bits to the left or to the right if shift is negative return (shift >= 0 ) ? number << shift : number >> -shift; }; Formula.BITOR = function (number1, number2) { // Return error if either number is a non-numeric value if (isNaN(number1) || isNaN(number2)) { return '#VALUE!'; } // Return error if either number is less than 0 if (number1 < 0 || number2 < 0) { return '#NUM!'; } // Return error if either number is a non-integer if (Math.floor(number1) !== number1 || Math.floor(number2) !== number2) { return '#NUM!'; } // Return error if either number is greater than (2^48)-1 if (number1 > 281474976710655 || number2 > 281474976710655) { return '#NUM!'; } // Return bitwise OR of two numbers return number1 | number2; }; Formula.BITRSHIFT = function (number, shift) { // Return error if either number is a non-numeric value if (isNaN(number) || isNaN(shift)) { return '#VALUE!'; } // Return error if number is less than 0 if (number < 0) { return '#NUM!'; } // Return error if number is a non-integer if (Math.floor(number) !== number) { return '#NUM!'; } // Return error if number is greater than (2^48)-1 if (number > 281474976710655) { return '#NUM!'; } // Return error if the absolute value of shift is greater than 53 if (Math.abs(shift) > 53) { return '#NUM!'; } // Return number shifted by shift bits to the right or to the left if shift is negative return (shift >= 0 ) ? number >> shift : number << -shift; }; Formula.BITXOR = function (number1, number2) { // Return error if either number is a non-numeric value if (isNaN(number1) || isNaN(number2)) { return '#VALUE!'; } // Return error if either number is less than 0 if (number1 < 0 || number2 < 0) { return '#NUM!'; } // Return error if either number is a non-integer if (Math.floor(number1) !== number1 || Math.floor(number2) !== number2) { return '#NUM!'; } // Return error if either number is greater than (2^48)-1 if (number1 > 281474976710655 || number2 > 281474976710655) { return '#NUM!'; } // Return bitwise XOR of two numbers return number1 ^ number2; }; Formula.COMPLEX = function (real, imaginary, suffix) { // Return error if either number is a non-numeric value if (isNaN(real) || isNaN(imaginary)) { return '#VALUE!'; } // Set suffix suffix = (typeof suffix === 'undefined') ? 'i' : suffix; // Return error if suffix is neither "i" nor "j" if (suffix !== 'i' && suffix !== 'j') { return '#VALUE!'; } // Return complex number if (real === 0 && imaginary === 0) { return 0; } else if (real === 0) { return (imaginary === 1) ? suffix : imaginary.toString() + suffix; } else if (imaginary === 0) { return real.toString(); } else { var sign = (imaginary > 0) ? '+' : ''; return real.toString() + sign + ((imaginary === 1) ? suffix : imaginary.toString() + suffix); } }; Formula.CONVERT = function (number, from_unit, to_unit) { // Return error if number is a non-numeric value if (isNaN(number)) { return '#VALUE!'; } // List of units supported by CONVERT and units defined by the International System of Units // [Name, Symbol, Alternate symbols, Quantity, ISU, CONVERT, Conversion ratio] var units = [ ["a.u. of action", "?", null, "action", false, false, 1.05457168181818e-34], ["a.u. of charge", "e", null, "electric_charge", false, false, 1.60217653141414e-19], ["a.u. of energy", "Eh", null, "energy", false, false, 4.35974417757576e-18], ["a.u. of length", "a?", null, "length", false, false, 5.29177210818182e-11], ["a.u. of mass", "m?", null, "mass", false, false, 9.10938261616162e-31], ["a.u. of time", "?/Eh", null, "time", false, false, 2.41888432650516e-17], ["admiralty knot", "admkn", null, "speed", false, true, 0.514773333], ["ampere", "A", null, "electric_current", true, false, 1], ["ampere per meter", "A/m", null, "magnetic_field_intensity", true, false, 1], ["ångström", "Å", ["ang"], "length", false, true, 1e-10], ["are", "ar", null, "area", false, true, 100], ["astronomical unit", "ua", null, "length", false, false, 1.49597870691667e-11], ["bar", "bar", null, "pressure", false, false, 100000], ["barn", "b", null, "area", false, false, 1e-28], ["becquerel", "Bq", null, "radioactivity", true, false, 1], ["bit", "bit", ["b"], "information", false, true, 1], ["btu", "BTU", ["btu"], "energy", false, true, 1055.05585262], ["byte", "byte", null, "information", false, true, 8], ["candela", "cd", null, "luminous_intensity", true, false, 1], ["candela per square metre", "cd/m?", null, "luminance", true, false, 1], ["coulomb", "C", null, "electric_charge", true, false, 1], ["cubic ångström", "ang3", ["ang^3"], "volume", false, true, 1e-30], ["cubic foot", "ft3", ["ft^3"], "volume", false, true, 0.028316846592], ["cubic inch", "in3", ["in^3"], "volume", false, true, 0.000016387064], ["cubic light-year", "ly3", ["ly^3"], "volume", false, true, 8.46786664623715e-47], ["cubic metre", "m?", null, "volume", true, true, 1], ["cubic mile", "mi3", ["mi^3"], "volume", false, true, 4168181825.44058], ["cubic nautical mile", "Nmi3", ["Nmi^3"], "volume", false, true, 6352182208], ["cubic Pica", "Pica3", ["Picapt3", "Pica^3", "Picapt^3"], "volume", false, true, 7.58660370370369e-8], ["cubic yard", "yd3", ["yd^3"], "volume", false, true, 0.764554857984], ["cup", "cup", null, "volume", false, true, 0.0002365882365], ["dalton", "Da", ["u"], "mass", false, false, 1.66053886282828e-27], ["day", "d", ["day"], "time", false, true, 86400], ["degree", "°", null, "angle", false, false, 0.0174532925199433], ["degrees Rankine", "Rank", null, "temperature", false, true, 0.555555555555556], ["dyne", "dyn", ["dy"], "force", false, true, 0.00001], ["electronvolt", "eV", ["ev"], "energy", false, true, 1.60217656514141], ["ell", "ell", null, "length", false, true, 1.143], ["erg", "erg", ["e"], "energy", false, true, 1e-7], ["farad", "F", null, "electric_capacitance", true, false, 1], ["fluid ounce", "oz", null, "volume", false, true, 0.0000295735295625], ["foot", "ft", null, "length", false, true, 0.3048], ["foot-pound", "flb", null, "energy", false, true, 1.3558179483314], ["gal", "Gal", null, "acceleration", false, false, 0.01], ["gallon", "gal", null, "volume", false, true, 0.003785411784], ["gauss", "G", ["ga"], "magnetic_flux_density", false, true, 1], ["grain", "grain", null, "mass", false, true, 0.0000647989], ["gram", "g", null, "mass", false, true, 0.001], ["gray", "Gy", null, "absorbed_dose", true, false, 1], ["gross registered ton", "GRT", ["regton"], "volume", false, true, 2.8316846592], ["hectare", "ha", null, "area", false, true, 10000], ["henry", "H", null, "inductance", true, false, 1], ["hertz", "Hz", null, "frequency", true, false, 1], ["horsepower", "HP", ["h"], "power", false, true, 745.69987158227], ["horsepower-hour", "HPh", ["hh", "hph"], "energy", false, true, 2684519.538], ["hour", "h", ["hr"], "time", false, true, 3600], ["imperial gallon (U.K.)", "uk_gal", null, "volume", false, true, 0.00454609], ["imperial hundredweight", "lcwt", ["uk_cwt", "hweight"], "mass", false, true, 50.802345], ["imperial quart (U.K)", "uk_qt", null, "volume", false, true, 0.0011365225], ["imperial ton", "brton", ["uk_ton", "LTON"], "mass", false, true, 1016.046909], ["inch", "in", null, "length", false, true, 0.0254], ["international acre", "uk_acre", null, "area", false, true, 4046.8564224], ["IT calorie", "cal", null, "energy", false, true, 4.1868], ["joule", "J", null, "energy", true, true, 1], ["katal", "kat", null, "catalytic_activity", true, false, 1], ["kelvin", "K", ["kel"], "temperature", true, true, 1], ["kilogram", "kg", null, "mass", true, true, 1], ["knot", "kn", null, "speed", false, true, 0.514444444444444], ["light-year", "ly", null, "length", false, true, 9460730472580800], ["litre", "L", ["l", "lt"], "volume", false, true, 0.001], ["lumen", "lm", null, "luminous_flux", true, false, 1], ["lux", "lx", null, "illuminance", true, false, 1], ["maxwell", "Mx", null, "magnetic_flux", false, false, 1e-18], ["measurement ton", "MTON", null, "volume", false, true, 1.13267386368], ["meter per hour", "m/h", ["m/hr"], "speed", false, true, 0.00027777777777778], ["meter per second", "m/s", ["m/sec"], "speed", true, true, 1], ["meter per second squared", "m?s??", null, "acceleration", true, false, 1], ["parsec", "pc", ["parsec"], "length", false, true, 30856775814671900], ["meter squared per second", "m?/s", null, "kinematic_viscosity", true, false, 1], ["metre", "m", null, "length", true, true, 1], ["miles per hour", "mph", null, "speed", false, true, 0.44704], ["millimetre of mercury", "mmHg", null, "pressure", false, false, 133.322], ["minute", "?", null, "angle", false, false, 0.000290888208665722], ["minute", "min", ["mn"], "time", false, true, 60], ["modern teaspoon", "tspm", null, "volume", false, true, 0.000005], ["mole", "mol", null, "amount_of_substance", true, false, 1], ["morgen", "Morgen", null, "area", false, true, 2500], ["n.u. of action", "?", null, "action", false, false, 1.05457168181818e-34], ["n.u. of mass", "m?", null, "mass", false, false, 9.10938261616162e-31], ["n.u. of speed", "c?", null, "speed", false, false, 299792458], ["n.u. of time", "?/(me?c??)", null, "time", false, false, 1.28808866778687e-21], ["nautical mile", "M", ["Nmi"], "length", false, true, 1852], ["newton", "N", null, "force", true, true, 1], ["œrsted", "Oe ", null, "magnetic_field_intensity", false, false, 79.5774715459477], ["ohm", "Ω", null, "electric_resistance", true, false, 1], ["ounce mass", "ozm", null, "mass", false, true, 0.028349523125], ["pascal", "Pa", null, "pressure", true, false, 1], ["pascal second", "Pa?s", null, "dynamic_viscosity", true, false, 1], ["pferdestärke", "PS", null, "power", false, true, 735.49875], ["phot", "ph", null, "illuminance", false, false, 0.0001], ["pica (1/6 inch)", "pica", null, "length", false, true, 0.00035277777777778], ["pica (1/72 inch)", "Pica", ["Picapt"], "length", false, true, 0.00423333333333333], ["poise", "P", null, "dynamic_viscosity", false, false, 0.1], ["pond", "pond", null, "force", false, true, 0.00980665], ["pound force", "lbf", null, "force", false, true, 4.4482216152605], ["pound mass", "lbm", null, "mass", false, true, 0.45359237], ["quart", "qt", null, "volume", false, true, 0.000946352946], ["radian", "rad", null, "angle", true, false, 1], ["second", "?", null, "angle", false, false, 0.00000484813681109536], ["second", "s", ["sec"], "time", true, true, 1], ["short hundredweight", "cwt", ["shweight"], "mass", false, true, 45.359237], ["siemens", "S", null, "electrical_conductance", true, false, 1], ["sievert", "Sv", null, "equivalent_dose", true, false, 1], ["slug", "sg", null, "mass", false, true, 14.59390294], ["square ångström", "ang2", ["ang^2"], "area", false, true, 1e-20], ["square foot", "ft2", ["ft^2"], "area", false, true, 0.09290304], ["square inch", "in2", ["in^2"], "area", false, true, 0.00064516], ["square light-year", "ly2", ["ly^2"], "area", false, true, 8.95054210748189e+31], ["square meter", "m?", null, "area", true, true, 1], ["square mile", "mi2", ["mi^2"], "area", false, true, 2589988.110336], ["square nautical mile", "Nmi2", ["Nmi^2"], "area", false, true, 3429904], ["square Pica", "Pica2", ["Picapt2", "Pica^2", "Picapt^2"], "area", false, true, 0.00001792111111111], ["square yard", "yd2", ["yd^2"], "area", false, true, 0.83612736], ["statute mile", "mi", null, "length", false, true, 1609.344], ["steradian", "sr", null, "solid_angle", true, false, 1], ["stilb", "sb", null, "luminance", false, false, 0.0001], ["stokes", "St", null, "kinematic_viscosity", false, false, 0.0001], ["stone", "stone", null, "mass", false, true, 6.35029318], ["tablespoon", "tbs", null, "volume", false, true, 0.0000147868], ["teaspoon", "tsp", null, "volume", false, true, 0.00000492892], ["tesla", "T", null, "magnetic_flux_density", true, true, 1], ["thermodynamic calorie", "c", null, "energy", false, true, 4.184], ["ton", "ton", null, "mass", false, true, 907.18474], ["tonne", "t", null, "mass", false, false, 1000], ["U.K. pint", "uk_pt", null, "volume", false, true, 0.00056826125], ["U.S. bushel", "bushel", null, "volume", false, true, 0.03523907], ["U.S. oil barrel", "barrel", null, "volume", false, true, 0.158987295], ["U.S. pint", "pt", ["us_pt"], "volume", false, true, 0.000473176473], ["U.S. survey mile", "survey_mi", null, "length", false, true, 1609.347219], ["U.S. survey/statute acre", "us_acre", null, "area", false, true, 4046.87261], ["volt", "V", null, "voltage", true, false, 1], ["watt", "W", null, "power", true, true, 1], ["watt-hour", "Wh", ["wh"], "energy", false, true, 3600], ["weber", "Wb", null, "magnetic_flux", true, false, 1], ["yard", "yd", null, "length", false, true, 0.9144], ["year", "yr", null, "time", false, true, 31557600] ]; // Binary prefixes // [Name, Prefix power of 2 value, Previx value, Abbreviation, Derived from] var binary_prefixes = { Yi: ["yobi", 80, 1208925819614629174706176, "Yi", "yotta"], Zi: ["zebi", 70, 1180591620717411303424, "Zi", "zetta"], Ei: ["exbi", 60, 1152921504606846976, "Ei", "exa"], Pi: ["pebi", 50, 1125899906842624, "Pi", "peta"], Ti: ["tebi", 40, 1099511627776, "Ti", "tera"], Gi: ["gibi", 30, 1073741824, "Gi", "giga"], Mi: ["mebi", 20, 1048576, "Mi", "mega"], ki: ["kibi", 10, 1024, "ki", "kilo"] }; // Unit prefixes // [Name, Multiplier, Abbreviation] var unit_prefixes = { Y: ["yotta", 1e+24, "Y"], Z: ["zetta", 1e+21, "Z"], E: ["exa", 1e+18, "E"], P: ["peta", 1e+15, "P"], T: ["tera", 1e+12, "T"], G: ["giga", 1e+09, "G"], M: ["mega", 1e+06, "M"], k: ["kilo", 1e+03, "k"], h: ["hecto", 1e+02, "h"], e: ["dekao", 1e+01, "e"], d: ["deci", 1e-01, "d"], c: ["centi", 1e-02, "c"], m: ["milli", 1e-03, "m"], u: ["micro", 1e-06, "u"], n: ["nano", 1e-09, "n"], p: ["pico", 1e-12, "p"], f: ["femto", 1e-15, "f"], a: ["atto", 1e-18, "a"], z: ["zepto", 1e-21, "z"], y: ["yocto", 1e-24, "y"] }; // Initialize units and multipliers var from = null; var to = null; var base_from_unit = from_unit; var base_to_unit = to_unit; var from_multiplier = 1; var to_multiplier = 1; var alt; // Lookup from and to units for (var i = 0; i < units.length; i++) { alt = (units[i][2] === null) ? [] : units[i][2]; if (units[i][1] === base_from_unit || alt.indexOf(base_from_unit) >= 0) { from = units[i]; } if (units[i][1] === base_to_unit || alt.indexOf(base_to_unit) >= 0) { to = units[i]; } } // Lookup from prefix if (from === null) { var from_binary_prefix = binary_prefixes[from_unit.substring(0, 2)]; var from_unit_prefix = unit_prefixes[from_unit.substring(0, 1)]; // Handle dekao unit prefix (only unit prefix with two characters) if (from_unit.substring(0, 2) === 'da') { from_unit_prefix = ["dekao", 1e+01, "da"]; } // Handle binary prefixes first (so that 'Yi' is processed before 'Y') if (from_binary_prefix) { from_multiplier = from_binary_prefix[2]; base_from_unit = from_unit.substring(2); } else if (from_unit_prefix) { from_multiplier = from_unit_prefix[1]; base_from_unit = from_unit.substring(from_unit_prefix[2].length); } // Lookup from unit for (var j = 0; j < units.length; j++) { alt = (units[j][2] === null) ? [] : units[j][2]; if (units[j][1] === base_from_unit || alt.indexOf(base_from_unit) >= 0) { from = units[j]; } } } // Lookup to prefix if (to === null) { var to_binary_prefix = binary_prefixes[to_unit.substring(0, 2)]; var to_unit_prefix = unit_prefixes[to_unit.substring(0, 1)]; // Handle dekao unit prefix (only unit prefix with two characters) if (to_unit.substring(0, 2) === 'da') { to_unit_prefix = ["dekao", 1e+01, "da"]; } // Handle binary prefixes first (so that 'Yi' is processed before 'Y') if (to_binary_prefix) { to_multiplier = to_binary_prefix[2]; base_to_unit = to_unit.substring(2); } else if (to_unit_prefix) { to_multiplier = to_unit_prefix[1]; base_to_unit = to_unit.substring(to_unit_prefix[2].length); } // Lookup to unit for (var k = 0; k < units.length; k++) { alt = (units[k][2] === null) ? [] : units[k][2]; if (units[k][1] === base_to_unit || alt.indexOf(base_to_unit) >= 0) { to = units[k]; } } } // Return error if a unit does not exist if (from === null || to === null) { return '#N/A'; } // Return error if units represent different quantities if (from[3] !== to[3]) { return '#N/A'; } // Return converted number return number * from[6] * from_multiplier / (to[6] * to_multiplier); }; Formula.DEC2BIN = function (number, places) { // Return error if number is not a number if (isNaN(number)) { return '#VALUE!'; } // Return error if number is not decimal, is lower than -512, or is greater than 511 if (!/^-?[0-9]{1,3}$/.test(number) || number < -512 || number > 511) { return '#NUM!'; } // Ignore places and return a 10-character binary number if number is negative if (number < 0) { return '1' + _s.repeat('0', 9 - (512 + number).toString(2).length) + (512 + number).toString(2); } // Convert decimal number to binary var result = parseInt(number, 10).toString(2); // Return binary number using the minimum number of characters necessary if places is undefined if (typeof places === 'undefined') { return result; } else { // Return error if places is nonnumeric if (isNaN(places)) { return '#VALUE!'; } // Return error if places is negative if (places < 0) { return '#NUM!'; } // Truncate places in case it is not an integer places = Math.floor(places); // Pad return value with leading 0s (zeros) if necessary (using Underscore.string) return (places >= result.length) ? _s.repeat('0', places - result.length) + result : '#NUM!'; } }; Formula.DEC2HEX = function (number, places) { // Return error if number is not a number if (isNaN(number)) { return '#VALUE!'; } // Return error if number is not decimal, is lower than -549755813888, or is greater than 549755813887 if (!/^-?[0-9]{1,12}$/.test(number) || number < -549755813888 || number > 549755813887) { return '#NUM!'; } // Ignore places and return a 10-character hexadecimal number if number is negative if (number < 0) { return (1099511627776 + number).toString(16); } // Convert decimal number to hexadecimal var result = parseInt(number, 10).toString(16); // Return hexadecimal number using the minimum number of characters necessary if places is undefined if (typeof places === 'undefined') { return result; } else { // Return error if places is nonnumeric if (isNaN(places)) { return '#VALUE!'; } // Return error if places is negative if (places < 0) { return '#NUM!'; } // Truncate places in case it is not an integer places = Math.floor(places); // Pad return value with leading 0s (zeros) if necessary (using Underscore.string) return (places >= result.length) ? _s.repeat('0', places - result.length) + result : '#NUM!'; } }; Formula.DEC2OCT = function (number, places) { // Return error if number is not a number if (isNaN(number)) { return '#VALUE!'; } // Return error if number is not decimal, is lower than -549755813888, or is greater than 549755813887 if (!/^-?[0-9]{1,9}$/.test(number) || number < -536870912 || number > 536870911) { return '#NUM!'; } // Ignore places and return a 10-character octal number if number is negative if (number < 0) { return (1073741824 + number).toString(8); } // Convert decimal number to octal var result = parseInt(number, 10).toString(8); // Return octal number using the minimum number of characters necessary if places is undefined if (typeof places === 'undefined') { return result; } else { // Return error if places is nonnumeric if (isNaN(places)) { return '#VALUE!'; } // Return error if places is negative if (places < 0) { return '#NUM!'; } // Truncate places in case it is not an integer places = Math.floor(places); // Pad return value with leading 0s (zeros) if necessary (using Underscore.string) return (places >= result.length) ? _s.repeat('0', places - result.length) + result : '#NUM!'; } }; Formula.DELTA = function (number1, number2) { // Set number2 to zero if undefined number2 = (typeof number2 === 'undefined') ? 0 : number2; // Return error if either number is not a number if (isNaN(number1) || isNaN(number2)) { return '#VALUE!'; } // Return delta return (number1 === number2) ? 1 : 0; }; Formula.ERF = function (lower_bound, upper_bound) { // Set number2 to zero if undefined upper_bound = (typeof upper_bound === 'undefined') ? 0 : upper_bound; // Return error if either number is not a number if (isNaN(lower_bound) || isNaN(upper_bound)) { return '#VALUE!'; } // Return ERFC using jStat [http://www.jstat.org/] return jStat.erf(lower_bound); }; Formula.ERFC = function (x) { // Return error if x is not a number if (isNaN(x)) { return '#VALUE!'; } // Return ERFC using jStat [http://www.jstat.org/] return jStat.erfc(x); }; Formula.ERFCPRECISE = function () { return; }; Formula.ERFPRECISE = function () { return; }; Formula.GESTEP = function (number, step) { // Set step to zero if undefined step = (typeof step === 'undefined') ? 0 : step; // Return error if either number is not a number if (isNaN(number) || isNaN(step)) { return '#VALUE!'; } // Return delta return (number >= step) ? 1 : 0; }; Formula.HEX2BIN = function (number, places) { // Return error if number is not hexadecimal or contains more than ten characters (10 digits) if (!/^[0-9A-Fa-f]{1,10}$/.test(number)) { return '#NUM!'; } // Check if number is negative var negative = (number.length === 10 && number.substring(0, 1).toLowerCase() === 'f') ? true : false; // Convert hexadecimal number to decimal var decimal = (negative) ? parseInt(number, 16) - 1099511627776 : parseInt(number, 16); // Return error if number is lower than -512 or greater than 511 if (decimal < -512 || decimal > 511) { return '#NUM!'; } // Ignore places and return a 10-character binary number if number is negative if (negative) { return '1' + _s.repeat('0', 9 - (512 + decimal).toString(2).length) + (512 + decimal).toString(2); } // Convert decimal number to binary var result = decimal.toString(2); // Return binary number using the minimum number of characters necessary if places is undefined if (typeof places === 'undefined') { return result; } else { // Return error if places is nonnumeric if (isNaN(places)) { return '#VALUE!'; } // Return error if places is negative if (places < 0) { return '#NUM!'; } // Truncate places in case it is not an integer places = Math.floor(places); // Pad return value with leading 0s (zeros) if necessary (using Underscore.string) return (places >= result.length) ? _s.repeat('0', places - result.length) + result : '#NUM!'; } }; Formula.HEX2DEC = function (number) { // Return error if number is not hexadecimal or contains more than ten characters (10 digits) if (!/^[0-9A-Fa-f]{1,10}$/.test(number)) { return '#NUM!'; } // Convert hexadecimal number to decimal var decimal = parseInt(number, 16); // Return decimal number return (decimal >= 549755813888) ? decimal - 1099511627776 : decimal; }; Formula.HEX2OCT = function (number, places) { // Return error if number is not hexadecimal or contains more than ten characters (10 digits) if (!/^[0-9A-Fa-f]{1,10}$/.test(number)) { return '#NUM!'; } // Convert hexadecimal number to decimal var decimal = parseInt(number, 16); // Return error if number is positive and greater than 0x1fffffff (536870911) if (decimal > 536870911 && decimal < 1098974756864) { return '#NUM!'; } // Ignore places and return a 10-character octal number if number is negative if (decimal >= 1098974756864) { return (decimal - 1098437885952).toString(8); } // Convert decimal number to octal var result = decimal.toString(8); // Return octal number using the minimum number of characters necessary if places is undefined if (typeof places === 'undefined') { return result; } else { // Return error if places is nonnumeric if (isNaN(places)) { return '#VALUE!'; } // Return error if places is negative if (places < 0) { return '#NUM!'; } // Truncate places in case it is not an integer places = Math.floor(places); // Pad return value with leading 0s (zeros) if necessary (using Underscore.string) return (places >= result.length) ? _s.repeat('0', places - result.length) + result : '#NUM!'; } }; Formula.IMABS = function (inumber) { // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Return absolute value of complex number return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)); }; Formula.IMAGINARY = function (inumber) { // Return 0 if inumber is equal to 0 if (inumber === 0 || inumber === '0') { return 0; } // Handle special cases if (['i', 'j'].indexOf(inumber) >= 0) { return 1; } // Normalize imaginary coefficient inumber = inumber.replace('+i', '+1i').replace('-i', '-1i').replace('+j', '+1j').replace('-j', '-1j'); // Lookup sign var plus = inumber.indexOf('+'); var minus = inumber.indexOf('-'); if (plus === 0) { plus = inumber.indexOf('+', 1); } if (minus === 0) { minus = inumber.indexOf('-', 1); } // Lookup imaginary unit var last = inumber.substring(inumber.length - 1, inumber.length); var unit = (last === 'i' || last === 'j'); if (plus >= 0 || minus >= 0) { // Return error if imaginary unit is neither i nor j if (!unit) { return '#NUM!'; } // Return imaginary coefficient of complex number if (plus >= 0) { return (isNaN(inumber.substring(0, plus)) || isNaN(inumber.substring(plus + 1, inumber.length - 1))) ? '#NUM!' : Number(inumber.substring(plus + 1, inumber.length - 1)); } else { return (isNaN(inumber.substring(0, minus)) || isNaN(inumber.substring(minus + 1, inumber.length - 1))) ? '#NUM!' : -Number(inumber.substring(minus + 1, inumber.length - 1)); } } else { if (unit) { return (isNaN(inumber.substring(0, inumber.length - 1))) ? '#NUM!' : inumber.substring(0, inumber.length - 1); } else { return (isNaN(inumber)) ? '#NUM!' : 0; } } }; Formula.IMARGUMENT = function (inumber) { // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Return error if inumber is equal to zero if (x === 0 && y === 0) { return '#DIV/0!'; } // Return PI/2 if x is equal to zero and y is positive if (x === 0 && y > 0) { return Math.PI / 2; } // Return -PI/2 if x is equal to zero and y is negative if (x === 0 && y < 0) { return -Math.PI / 2; } // Return zero if x is negative and y is equal to zero if (y === 0 && x > 0) { return 0; } // Return zero if x is negative and y is equal to zero if (y === 0 && x < 0) { return -Math.PI; } // Return argument of complex number if (x > 0) { return Math.atan(y / x); } else if (x < 0 && y >= 0) { return Math.atan(y / x) + Math.PI; } else { return Math.atan(y / x) - Math.PI; } }; Formula.IMCONJUGATE = function (inumber) { // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Lookup imaginary unit var unit = inumber.substring(inumber.length - 1); unit = (unit === 'i' || unit === 'j') ? unit : 'i'; // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Return conjugate of complex number return (y !== 0) ? Formula.COMPLEX(x, -y, unit) : inumber; }; Formula.IMCOS = function (inumber) { // Return error if inumber is a logical value if (inumber === true || inumber === false) { return '#VALUE!'; } // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Lookup imaginary unit var unit = inumber.substring(inumber.length - 1); unit = (unit === 'i' || unit === 'j') ? unit : 'i'; // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Return cosine of complex number return Formula.COMPLEX(Math.cos(x) * (Math.exp(y) + Math.exp(-y)) / 2, -Math.sin(x) * (Math.exp(y) - Math.exp(-y)) / 2, unit); }; Formula.IMCOSH = function (inumber) { // Return error if inumber is a logical value if (inumber === true || inumber === false) { return '#VALUE!'; } // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Lookup imaginary unit var unit = inumber.substring(inumber.length - 1); unit = (unit === 'i' || unit === 'j') ? unit : 'i'; // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Return hyperbolic cosine of complex number return Formula.COMPLEX(Math.cos(y) * (Math.exp(x) + Math.exp(-x)) / 2, Math.sin(y) * (Math.exp(x) - Math.exp(-x)) / 2, unit); }; Formula.IMCOT = function (inumber) { // Return error if inumber is a logical value if (inumber === true || inumber === false) { return '#VALUE!'; } // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Return cotangent of complex number return Formula.IMDIV(Formula.IMCOS(inumber), Formula.IMSIN(inumber)); }; Formula.IMCSC = function (inumber) { // Return error if inumber is a logical value if (inumber === true || inumber === false) { return '#VALUE!'; } // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Return cosecant of complex number return Formula.IMDIV('1', Formula.IMSIN(inumber)); }; Formula.IMCSCH = function (inumber) { // Return error if inumber is a logical value if (inumber === true || inumber === false) { return '#VALUE!'; } // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Return hyperbolic cosecant of complex number return Formula.IMDIV('1', Formula.IMSINH(inumber)); }; Formula.IMDIV = function (inumber1, inumber2) { // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var a = Formula.IMREAL(inumber1); var b = Formula.IMAGINARY(inumber1); var c = Formula.IMREAL(inumber2); var d = Formula.IMAGINARY(inumber2); // Lookup imaginary unit var unit1 = inumber1.substring(inumber1.length - 1); var unit2 = inumber1.substring(inumber1.length - 1); var unit = 'i'; if (unit1 === 'j') { unit = 'j'; } else if (unit2 === 'j') { unit = 'j'; } // Return error if either coefficient is not a number if (a === '#NUM!' || b === '#NUM!' || c === '#NUM!' || d === '#NUM!') { return '#NUM!'; } // Return error if inumber2 is null if (c === 0 && d === 0) { return '#NUM!'; } // Return exponential of complex number var den = c * c + d * d; return Formula.COMPLEX((a * c + b * d) / den, (b * c - a * d) / den, unit); }; Formula.IMEXP = function (inumber) { // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Lookup imaginary unit var unit = inumber.substring(inumber.length - 1); unit = (unit === 'i' || unit === 'j') ? unit : 'i'; // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Return exponential of complex number var e = Math.exp(x); return Formula.COMPLEX(e * Math.cos(y), e * Math.sin(y), unit); }; Formula.IMLN = function (inumber) { // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Lookup imaginary unit var unit = inumber.substring(inumber.length - 1); unit = (unit === 'i' || unit === 'j') ? unit : 'i'; // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Return exponential of complex number return Formula.COMPLEX(Math.log(Math.sqrt(x * x + y * y)), Math.atan(y / x), unit); }; Formula.IMLOG10 = function (inumber) { // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Lookup imaginary unit var unit = inumber.substring(inumber.length - 1); unit = (unit === 'i' || unit === 'j') ? unit : 'i'; // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Return exponential of complex number return Formula.COMPLEX(Math.log(Math.sqrt(x * x + y * y)) / Math.log(10), Math.atan(y / x) / Math.log(10), unit); }; Formula.IMLOG2 = function (inumber) { // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Lookup imaginary unit var unit = inumber.substring(inumber.length - 1); unit = (unit === 'i' || unit === 'j') ? unit : 'i'; // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Return exponential of complex number return Formula.COMPLEX(Math.log(Math.sqrt(x * x + y * y)) / Math.log(2), Math.atan(y / x) / Math.log(2), unit); }; Formula.IMPOWER = function (inumber, number) { // Return error if number is nonnumeric if (isNaN(number)) { return '#VALUE!'; } // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Lookup imaginary unit var unit = inumber.substring(inumber.length - 1); unit = (unit === 'i' || unit === 'j') ? unit : 'i'; // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Calculate power of modulus var p = Math.pow(Formula.IMABS(inumber), number); // Calculate argument var t = Formula.IMARGUMENT(inumber); // Return exponential of complex number return Formula.COMPLEX(p * Math.cos(number * t), p * Math.sin(number * t), unit); }; Formula.IMPRODUCT = function () { // Initialize result var result = arguments[0]; // Loop on all numbers for (var i = 1; i < arguments.length; i++) { // Lookup coefficients of two complex numbers var a = Formula.IMREAL(result); var b = Formula.IMAGINARY(result); var c = Formula.IMREAL(arguments[i]); var d = Formula.IMAGINARY(arguments[i]); // Return error if either coefficient is not a number if (a === '#NUM!' || b === '#NUM!' || c === '#NUM!' || d === '#NUM!') { return '#NUM!'; } // Complute product of two complex numbers result = Formula.COMPLEX(a * c - b * d, a * d + b * c); } // Return product of complex numbers return result; }; Formula.IMREAL = function (inumber) { // Return 0 if inumber is equal to 0 if (inumber === 0 || inumber === '0') { return 0; } // Handle special cases if (['i', '+i', '1i', '+1i', '-i', '-1i', 'j', '+j', '1j', '+1j', '-j', '-1j'].indexOf(inumber) >= 0) { return 0; } // Lookup sign var plus = inumber.indexOf('+'); var minus = inumber.indexOf('-'); if (plus === 0) { plus = inumber.indexOf('+', 1); } if (minus === 0) { minus = inumber.indexOf('-', 1); } // Lookup imaginary unit var last = inumber.substring(inumber.length - 1, inumber.length); var unit = (last === 'i' || last === 'j'); if (plus >= 0 || minus >= 0) { // Return error if imaginary unit is neither i nor j if (!unit) { return '#NUM!'; } // Return real coefficient of complex number if (plus >= 0) { return (isNaN(inumber.substring(0, plus)) || isNaN(inumber.substring(plus + 1, inumber.length - 1))) ? '#NUM!' : Number(inumber.substring(0, plus)); } else { return (isNaN(inumber.substring(0, minus)) || isNaN(inumber.substring(minus + 1, inumber.length - 1))) ? '#NUM!' : Number(inumber.substring(0, minus)); } } else { if (unit) { return (isNaN(inumber.substring(0, inumber.length - 1))) ? '#NUM!' : 0; } else { return (isNaN(inumber)) ? '#NUM!' : inumber; } } }; Formula.IMSEC = function (inumber) { // Return error if inumber is a logical value if (inumber === true || inumber === false) { return '#VALUE!'; } // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Return secant of complex number return Formula.IMDIV('1', Formula.IMCOS(inumber)); }; Formula.IMSECH = function (inumber) { // Return error if inumber is a logical value if (inumber === true || inumber === false) { return '#VALUE!'; } // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Return hyperbolic secant of complex number return Formula.IMDIV('1', Formula.IMCOSH(inumber)); }; Formula.IMSIN = function (inumber) { // Return error if inumber is a logical value if (inumber === true || inumber === false) { return '#VALUE!'; } // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Lookup imaginary unit var unit = inumber.substring(inumber.length - 1); unit = (unit === 'i' || unit === 'j') ? unit : 'i'; // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Return sine of complex number return Formula.COMPLEX(Math.sin(x) * (Math.exp(y) + Math.exp(-y)) / 2, Math.cos(x) * (Math.exp(y) - Math.exp(-y)) / 2, unit); }; Formula.IMSINH = function (inumber) { // Return error if inumber is a logical value if (inumber === true || inumber === false) { return '#VALUE!'; } // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Lookup imaginary unit var unit = inumber.substring(inumber.length - 1); unit = (unit === 'i' || unit === 'j') ? unit : 'i'; // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Return hyperbolic sine of complex number return Formula.COMPLEX(Math.cos(y) * (Math.exp(x) - Math.exp(-x)) / 2, Math.sin(y) * (Math.exp(x) + Math.exp(-x)) / 2, unit); }; Formula.IMSQRT = function (inumber) { // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Lookup imaginary unit var unit = inumber.substring(inumber.length - 1); unit = (unit === 'i' || unit === 'j') ? unit : 'i'; // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Calculate power of modulus var s = Math.sqrt(Formula.IMABS(inumber)); // Calculate argument var t = Formula.IMARGUMENT(inumber); // Return exponential of complex number return Formula.COMPLEX(s * Math.cos(t / 2), s * Math.sin(t / 2), unit); }; Formula.IMSUB = function (inumber1, inumber2) { // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var a = Formula.IMREAL(inumber1); var b = Formula.IMAGINARY(inumber1); var c = Formula.IMREAL(inumber2); var d = Formula.IMAGINARY(inumber2); // Lookup imaginary unit var unit1 = inumber1.substring(inumber1.length - 1); var unit2 = inumber1.substring(inumber1.length - 1); var unit = 'i'; if (unit1 === 'j') { unit = 'j'; } else if (unit2 === 'j') { unit = 'j'; } // Return error if either coefficient is not a number if (a === '#NUM!' || b === '#NUM!' || c === '#NUM!' || d === '#NUM!') { return '#NUM!'; } // Return _ of two complex numbers return Formula.COMPLEX(a - c, b - d, unit); }; Formula.IMSUM = function () { // Initialize result var result = arguments[0]; // Loop on all numbers for (var i = 1; i < arguments.length; i++) { // Lookup coefficients of two complex numbers var a = Formula.IMREAL(result); var b = Formula.IMAGINARY(result); var c = Formula.IMREAL(arguments[i]); var d = Formula.IMAGINARY(arguments[i]); // Return error if either coefficient is not a number if (a === '#NUM!' || b === '#NUM!' || c === '#NUM!' || d === '#NUM!') { return '#NUM!'; } // Complute product of two complex numbers result = Formula.COMPLEX(a + c, b + d); } // Return sum of complex numbers return result; }; Formula.IMTAN = function (inumber) { // Return error if inumber is a logical value if (inumber === true || inumber === false) { return '#VALUE!'; } // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Return tangent of complex number return Formula.IMDIV(Formula.IMSIN(inumber), Formula.IMCOS(inumber)); }; Formula.OCT2BIN = function (number, places) { // Return error if number is not hexadecimal or contains more than ten characters (10 digits) if (!/^[0-7]{1,10}$/.test(number)) { return '#NUM!'; } // Check if number is negative var negative = (number.length === 10 && number.substring(0, 1) === '7') ? true : false; // Convert octal number to decimal var decimal = (negative) ? parseInt(number, 8) - 1073741824 : parseInt(number, 8); // Return error if number is lower than -512 or greater than 511 if (decimal < -512 || decimal > 511) { return '#NUM!'; } // Ignore places and return a 10-character binary number if number is negative if (negative) { return '1' + _s.repeat('0', 9 - (512 + decimal).toString(2).length) + (512 + decimal).toString(2); } // Convert decimal number to binary var result = decimal.toString(2); // Return binary number using the minimum number of characters necessary if places is undefined if (typeof places === 'undefined') { return result; } else { // Return error if places is nonnumeric if (isNaN(places)) { return '#VALUE!'; } // Return error if places is negative if (places < 0) { return '#NUM!'; } // Truncate places in case it is not an integer places = Math.floor(places); // Pad return value with leading 0s (zeros) if necessary (using Underscore.string) return (places >= result.length) ? _s.repeat('0', places - result.length) + result : '#NUM!'; } }; Formula.OCT2DEC = function (number) { // Return error if number is not octal or contains more than ten characters (10 digits) if (!/^[0-7]{1,10}$/.test(number)) { return '#NUM!'; } // Convert octal number to decimal var decimal = parseInt(number, 8); // Return decimal number return (decimal >= 536870912) ? decimal - 1073741824 : decimal; }; Formula.OCT2HEX = function (number, places) { // Return error if number is not octal or contains more than ten characters (10 digits) if (!/^[0-7]{1,10}$/.test(number)) { return '#NUM!'; } // Convert octal number to decimal var decimal = parseInt(number, 8); // Ignore places and return a 10-character octal number if number is negative if (decimal >= 536870912) { return 'ff' + (decimal + 3221225472).toString(16); } // Convert decimal number to hexadecimal var result = decimal.toString(16); // Return hexadecimal number using the minimum number of characters necessary if places is undefined if (typeof places === 'undefined') { return result; } else { // Return error if places is nonnumeric if (isNaN(places)) { return '#VALUE!'; } // Return error if places is negative if (places < 0) { return '#NUM!'; } // Truncate places in case it is not an integer places = Math.floor(places); // Pad return value with leading 0s (zeros) if necessary (using Underscore.string) return (places >= result.length) ? _s.repeat('0', places - result.length) + result : '#NUM!'; } }; // Financial functions Formula.ACCRINT = function (issue, first, settlement, rate, par, frequency, basis, method) { // Return error if either date is invalid if (!moment(issue).isValid() || !moment(first).isValid() || !moment(settlement).isValid()) { return '#VALUE!'; } // Return error if either rate or par are lower than or equal to zero if (rate <= 0 || par <= 0) { return '#NUM!'; } // Return error if frequency is neither 1, 2, or 4 if ([1, 2, 4].indexOf(frequency) === -1) { return '#NUM!'; } // Return error if basis is neither 0, 1, 2, 3, or 4 if ([0, 1, 2, 3, 4].indexOf(basis) === -1) { return '#NUM!'; } // Return error if issue greater than or equal to settlement if (moment(issue).diff(moment(settlement)) >= 0) { return '#NUM!'; } // Set default values par = (typeof par === 'undefined') ? 0 : par; basis = (typeof basis === 'undefined') ? 0 : basis; method = (typeof method === 'undefined') ? true : method; // Compute accrued interest var factor = 0; var id = moment(new Date(issue)); var fd = moment(new Date(first)); var sd = moment(new Date(settlement)); var days = (moment([id.year()]).isLeapYear()) ? 366 : 365; switch (basis) { case 0: // US (NASD) 30/360 factor = Formula.YEARFRAC(issue, settlement, basis); break; case 1: // Actual/actual factor = Formula.YEARFRAC(issue, settlement, basis); break; case 2: // Actual/360 factor = Formula.YEARFRAC(issue, settlement, basis); break; case 3: // Actual/365 factor = Formula.YEARFRAC(issue, settlement, basis); break; case 4: // European 30/360 factor = Formula.YEARFRAC(issue, settlement, basis); break; } return par * rate * factor; }; Formula.ACCRINTM = function () { return; }; Formula.AMORDEGRC = function () { return; }; Formula.AMORLINC = function () { return; }; Formula.COUPDAYBS = function () { return; }; Formula.COUPDAYS = function () { return; }; Formula.COUPDAYSNC = function () { return; }; Formula.COUPNCD = function () { return; }; Formula.COUPNUM = function () { return; }; Formula.COUPPCD = function () { return; }; Formula.CUMIPMT = function (rate, periods, value, start, end, type) { // Credits: algorithm inspired by Apache OpenOffice // Credits: Hannes Stiebitzhofer for the translations of function and variable names // Requires Formula.FV() and Formula.PMT() from Formula.js [http://stoic.com/formula/] // Evaluate rate and periods (TODO: replace with secure expression evaluator) rate = eval(rate); periods = eval(periods); // Return error if either rate, periods, or value are lower than or equal to zero if (rate <= 0 || periods <= 0 || value <= 0) { return '#NUM!'; } // Return error if start < 1, end < 1, or start > end if (start < 1 || end < 1 || start > end) { return '#NUM!'; } // Return error if type is neither 0 nor 1 if (type !== 0 && type !== 1) { return '#NUM!'; } // Compute cumulative interest var payment = Formula.PMT(rate, periods, value, 0, type); var interest = 0; if (start === 1) { if (type === 0) { interest = -value; start++; } } for (var i = start; i <= end; i++) { if (type === 1) { interest += Formula.FV(rate, i - 2, payment, value, 1) - payment; } else { interest += Formula.FV(rate, i - 1, payment, value, 0); } } interest *= rate; // Return cumulative interest return interest; }; Formula.CUMPRINC = function (rate, periods, value, start, end, type) { // Credits: algorithm inspired by Apache OpenOffice // Credits: Hannes Stiebitzhofer for the translations of function and variable names // Requires Formula.FV() and Formula.PMT() from Formula.js [http://stoic.com/formula/] // Evaluate rate and periods (TODO: replace with secure expression evaluator) rate = eval(rate); periods = eval(periods); // Return error if either rate, periods, or value are lower than or equal to zero if (rate <= 0 || periods <= 0 || value <= 0) { return '#NUM!'; } // Return error if start < 1, end < 1, or start > end if (start < 1 || end < 1 || start > end) { return '#NUM!'; } // Return error if type is neither 0 nor 1 if (type !== 0 && type !== 1) { return '#NUM!'; } // Compute cumulative principal var payment = Formula.PMT(rate, periods, value, 0, type); var principal = 0; if (start === 1) { if (type === 0) { principal = payment + value * rate; } else { principal = payment; } start++; } for (var i = start; i <= end; i++) { if (type > 0) { principal += payment - (Formula.FV(rate, i - 2, payment, value, 1) - payment) * rate; } else { principal += payment - Formula.FV(rate, i - 1, payment, value, 0) * rate; } } // Return cumulative principal return principal; }; Formula.DB = function (cost, salvage, life, period, month) { // Initialize month month = (typeof month === 'undefined') ? 12 : month; // Return error if any of the parameters is not a number if (isNaN(cost) || isNaN(salvage) || isNaN(life) || isNaN(period) || isNaN(month)) { return '#VALUE!'; } // Return error if any of the parameters is negative [ if (cost < 0 || salvage < 0 || life < 0 || period < 0) { return '#NUM!'; } // Return error if month is not an integer between 1 and 12 if ([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].indexOf(month) === -1) { return '#NUM!'; } // Return error if period is greater than life if (period > life) { return '#NUM!'; } // Return 0 (zero) if salvage is greater than or equal to cost if (salvage >= cost) { return 0; } // Rate is rounded to three decimals places var rate = (1 - Math.pow(salvage / cost, 1 / life)).toFixed(3); // Compute initial depreciation var initial = cost * rate * month / 12; // Compute total depreciation var total = initial; var current = 0; var ceiling = (period === life) ? life - 1 : period; for (var i = 2; i <= ceiling; i++) { current = (cost - total) * rate; total += current; } // Depreciation for the first and last periods are special cases if (period === 1) { // First period return initial; } else if (period === life) { // Last period return (cost - total) * rate; } else { return current; } }; Formula.DDB = function (cost, salvage, life, period, factor) { // Initialize factor factor = (typeof factor === 'undefined') ? 2 : factor; // Return error if any of the parameters is not a number if (isNaN(cost) || isNaN(salvage) || isNaN(life) || isNaN(period) || isNaN(factor)) { return '#VALUE!'; } // Return error if any of the parameters is negative or if factor is null if (cost < 0 || salvage < 0 || life < 0 || period < 0 || factor <= 0) { return '#NUM!'; } // Return error if period is greater than life if (period > life) { return '#NUM!'; } // Return 0 (zero) if salvage is greater than or equal to cost if (salvage >= cost) { return 0; } // Compute depreciation var total = 0; var current = 0; for (var i = 1; i <= period; i++) { current = Math.min((cost - total) * (factor / life), (cost - salvage - total)); total += current; } // Return depreciation return current; }; Formula.DISC = function () { return; }; Formula.DOLLARDE = function (dollar, fraction) { // Credits: algorithm inspired by Apache OpenOffice // Return error if any of the parameters is not a number if (isNaN(dollar) || isNaN(fraction)) { return '#VALUE!'; } // Return error if fraction is negative if (fraction < 0) { return '#NUM!'; } // Return error if fraction is greater than or equal to 0 and less than 1 if (fraction >= 0 && fraction < 1) { return '#DIV/0!'; } // Truncate fraction if it is not an integer fraction = parseInt(fraction, 10); // Compute integer part var result = parseInt(dollar, 10); // Add decimal part result += (dollar % 1) * Math.pow(10, Math.ceil(Math.log(fraction) / Math.LN10)) / fraction; // Round result var power = Math.pow(10, Math.ceil(Math.log(fraction) / Math.LN2) + 1); result = Math.round(result * power) / power; // Return converted dollar price return result; }; Formula.DOLLARFR = function (dollar, fraction) { // Credits: algorithm inspired by Apache OpenOffice // Return error if any of the parameters is not a number if (isNaN(dollar) || isNaN(fraction)) { return '#VALUE!'; } // Return error if fraction is negative if (fraction < 0) { return '#NUM!'; } // Return error if fraction is greater than or equal to 0 and less than 1 if (fraction >= 0 && fraction < 1) { return '#DIV/0!'; } // Truncate fraction if it is not an integer fraction = parseInt(fraction, 10); // Compute integer part var result = parseInt(dollar, 10); // Add decimal part result += (dollar % 1) * Math.pow(10, -Math.ceil(Math.log(fraction) / Math.LN10)) * fraction; // Return converted dollar price return result; }; Formula.DURATION = function () { return; }; Formula.EFFECT = function (rate, periods) { // Return error if any of the parameters is not a number if (isNaN(rate) || isNaN(periods)) { return '#VALUE!'; } // Return error if rate <=0 or periods < 1 if (rate <= 0 || periods < 1) { return '#NUM!'; } // Truncate periods if it is not an integer periods = parseInt(periods, 10); // Return effective annual interest rate return Math.pow(1 + rate / periods, periods) - 1; }; Formula.FV = function (rate, periods, payment, value, type) { // Credits: algorithm inspired by Apache OpenOffice // Initialize type type = (typeof type === 'undefined') ? 0 : type; // Evaluate rate (TODO: replace with secure expression evaluator) rate = eval(rate); // Return future value var result; if (rate === 0) { result = value + payment * periods; } else { var term = Math.pow(1 + rate, periods); if (type === 1) { result = value * term + payment * (1 + rate) * (term - 1.0) / rate; } else { result = value * term + payment * (term - 1) / rate; } } return -result; }; Formula.FVSCHEDULE = function (principal, schedule) { // Initialize future value var future = principal; // Apply all interests in schedule for (var i = 0; i < schedule.length; i++) { // Return error if schedule value is not a number if (isNaN(schedule[i])) { return '#VALUE!'; } // Apply scheduled interest future *= 1 + schedule[i]; } // Return future value return future; }; Formula.INTRATE = function () { return; }; Formula.IPMT = function (rate, period, periods, present, future, type) { // Credits: algorithm inspired by Apache OpenOffice // Initialize type type = (typeof type === 'undefined') ? 0 : type; // Evaluate rate and periods (TODO: replace with secure expression evaluator) rate = eval(rate); periods = eval(periods); // Compute payment var payment = Formula.PMT(rate, periods, present, future, type); // Compute interest var interest; if (period === 1) { if (type === 1) { interest = 0; } else { interest = -present; } } else { if (type === 1) { interest = Formula.FV(rate, period - 2, payment, present, 1) - payment; } else { interest = Formula.FV(rate, period - 1, payment, present, 0); } } // Return interest return interest * rate; }; Formula.IRR = function (values, guess) { // Credits: algorithm inspired by Apache OpenOffice // Calculates the resulting amount var irrResult = function (values, dates, rate) { var r = rate + 1; var result = values[0]; for (var i = 1; i < values.length; i++) { result += values[i] / Math.pow(r, (dates[i] - dates[0]) / 365); } return result; }; // Calculates the first derivation var irrResultDeriv = function (values, dates, rate) { var r = rate + 1; var result = 0; for (var i = 1; i < values.length; i++) { var frac = (dates[i] - dates[0]) / 365; result -= frac * values[i] / Math.pow(r, frac + 1); } return result; }; // Initialize dates and check that values contains at least one positive value and one negative value var dates = []; var positive = false; var negative = false; for (var i = 0; i < values.length; i++) { dates[i] = (i === 0) ? 0 : dates[i - 1] + 365; if (values[i] > 0) { positive = true; } if (values[i] < 0) { negative = true; } } // Return error if values does not contain at least one positive value and one negative value if (!positive || !negative) { return '#NUM!'; } // Initialize guess and resultRate guess = (typeof guess === 'undefined') ? 0.1 : guess; var resultRate = guess; // Set maximum epsilon for end of iteration var epsMax = 1e-10; // Set maximum number of iterations var iterMax = 50; // Implement Newton's method var newRate, epsRate, resultValue; var iteration = 0; var contLoop = true; do { resultValue = irrResult(values, dates, resultRate); newRate = resultRate - resultValue / irrResultDeriv(values, dates, resultRate); epsRate = Math.abs(newRate - resultRate); resultRate = newRate; contLoop = (epsRate > epsMax) && (Math.abs(resultValue) > epsMax); } while (contLoop && (++iteration < iterMax)); if (contLoop) { return '#NUM!'; } // Return internal rate of return return resultRate; }; Formula.ISPMT = function (rate, period, periods, value) { // Evaluate rate and periods (TODO: replace with secure expression evaluator) rate = eval(rate); periods = eval(periods); // Return interest return value * rate * (period / periods - 1); }; Formula.MDURATION = function () { return; }; Formula.MIRR = function (values, finance_rate, reinvest_rate) { // Initialize number of values var n = values.length; // Lookup payments (negative values) and incomes (positive values) var payments = []; var incomes = []; for (var i = 0; i < n; i++) { if (values[i] < 0) { payments.push(values[i]); } else { incomes.push(values[i]); } } // Return modified internal rate of return var num = -Formula.NPV(reinvest_rate, incomes) * Math.pow(1 + reinvest_rate, n - 1); var den = Formula.NPV(finance_rate, payments) * (1 + finance_rate); return Math.pow(num / den, 1 / (n - 1)) - 1; }; Formula.NOMINAL = function (rate, periods) { // Return error if any of the parameters is not a number if (isNaN(rate) || isNaN(periods)) { return '#VALUE!'; } // Return error if rate <=0 or periods < 1 if (rate <= 0 || periods < 1) { return '#NUM!'; } // Truncate periods if it is not an integer periods = parseInt(periods, 10); // Return nominal annual interest rate return (Math.pow(rate + 1, 1 / periods) - 1) * periods; }; Formula.NPER = function (rate, payment, present, future, type) { // Initialize type type = (typeof type === 'undefined') ? 0 : type; // Initialize future value future = (typeof future === 'undefined') ? 0 : future; // Evaluate rate and periods (TODO: replace with secure expression evaluator) rate = eval(rate); // Return number of periods var num = payment * (1 + rate * type) - future * rate; var den = (present * rate + payment * (1 + rate * type)); return Math.log(num / den) / Math.log(1 + rate); }; Formula.NPV = function () { // Cast arguments to array var args = []; for (var i = 0; i < arguments.length; i++) { args = args.concat(arguments[i]); } // Lookup rate var rate = args[0]; // Initialize net present value var value = 0; // Loop on all values for (var j = 1; j < args.length; j++) { value += args[j] / Math.pow(1 + rate, j); } // Return net present value return value; }; Formula.ODDFPRICE = function () { return; }; Formula.ODDFYIELD = function () { return; }; Formula.ODDLPRICE = function () { return; }; Formula.ODDLYIELD = function () { return; }; Formula.PDURATION = function (rate, present, future) { // Return error if any of the parameters is not a number if (isNaN(rate) || isNaN(present) || isNaN(future)) { return '#VALUE!'; } // Return error if rate <=0 if (rate <= 0) { return '#NUM!'; } // Return number of periods return (Math.log(future) - Math.log(present)) / Math.log(1 + rate); }; Formula.PMT = function (rate, periods, present, future, type) { // Credits: algorithm inspired by Apache OpenOffice // Initialize type type = (typeof type === 'undefined') ? 0 : type; // Evaluate rate and periods (TODO: replace with secure expression evaluator) rate = eval(rate); periods = eval(periods); // Return payment var result; if (rate === 0) { result = (present + future) / periods; } else { var term = Math.pow(1 + rate, periods); if (type === 1) { result = (future * rate / (term - 1) + present * rate / (1 - 1 / term)) / (1 + rate); } else { result = future * rate / (term - 1) + present * rate / (1 - 1 / term); } } return -result; }; Formula.PPMT = function (rate, period, periods, present, future, type) { return Formula.PMT(rate, periods, present, future, type) - Formula.IPMT(rate, period, periods, present, future, type); }; Formula.PRICE = function () { return; }; Formula.PRICEDISC = function () { return; }; Formula.PRICEMAT = function () { return; }; Formula.PV = function (rate, periods, payment, future, type) { // Initialize type type = (typeof type === 'undefined') ? 0 : type; // Evaluate rate and periods (TODO: replace with secure expression evaluator) rate = eval(rate); periods = eval(periods); // Return present value if (rate === 0) { return -payment * periods - future; } else { return (((1 - Math.pow(1 + rate, periods)) / rate) * payment * (1 + rate * type) - future) / Math.pow(1 + rate, periods); } }; Formula.RATE = function (periods, payment, present, future, type, guess) { // Credits: rabugento // Initialize guess guess = (typeof guess === 'undefined') ? 0.01 : guess; // Initialize future future = (typeof future === 'undefined') ? 0 : future; // Initialize type type = (typeof type === 'undefined') ? 0 : type; // Evaluate periods (TODO: replace with secure expression evaluator) periods = eval(periods); // Set maximum epsilon for end of iteration var epsMax = 1e-10; // Set maximum number of iterations var iterMax = 50; // Implement Newton's method var y, y0, y1, x0, x1 = 0, f = 0, i = 0; var rate = guess; if (Math.abs(rate) < epsMax) { y = present * (1 + periods * rate) + payment * (1 + rate * type) * periods + future; } else { f = Math.exp(periods * Math.log(1 + rate)); y = present * f + payment * (1 / rate + type) * (f - 1) + future; } y0 = present + payment * periods + future; y1 = present * f + payment * (1 / rate + type) * (f - 1) + future; i = x0 = 0; x1 = rate; while ((Math.abs(y0 - y1) > epsMax) && (i < iterMax)) { rate = (y1 * x0 - y0 * x1) / (y1 - y0); x0 = x1; x1 = rate; if (Math.abs(rate) < epsMax) { y = present * (1 + periods * rate) + payment * (1 + rate * type) * periods + future; } else { f = Math.exp(periods * Math.log(1 + rate)); y = present * f + payment * (1 / rate + type) * (f - 1) + future; } y0 = y1; y1 = y; ++i; } return rate; }; Formula.RECEIVED = function () { return; }; Formula.RRI = function (periods, present, future) { // Return error if any of the parameters is not a number if (isNaN(periods) || isNaN(present) || isNaN(future)) { return '#VALUE!'; } // Return error if periods or present is equal to 0 (zero) if (periods === 0 || present === 0) { return '#NUM!'; } // Return equivalent interest rate return Math.pow(future / present, 1 / periods) - 1; }; Formula.SLN = function (cost, salvage, life) { // Return error if any of the parameters is not a number if (isNaN(cost) || isNaN(salvage) || isNaN(life)) { return '#VALUE!'; } // Return error if life equal to 0 (zero) if (life === 0) { return '#NUM!'; } // Return straight-line depreciation return (cost - salvage) / life; }; Formula.SYD = function (cost, salvage, life, period) { // Return error if any of the parameters is not a number if (isNaN(cost) || isNaN(salvage) || isNaN(life) || isNaN(period)) { return '#VALUE!'; } // Return error if life equal to 0 (zero) if (life === 0) { return '#NUM!'; } // Return error if period is lower than 1 or greater than life if (period < 1 || period > life) { return '#NUM!'; } // Truncate period if it is not an integer period = parseInt(period, 10); // Return straight-line depreciation return (cost - salvage) * (life - period + 1) * 2 / (life * (life + 1)); }; Formula.TBILLEQ = function (settlement, maturity, discount) { // Return error if either date is invalid if (!moment(settlement).isValid() || !moment(maturity).isValid()) { return '#VALUE!'; } // Return error if discount is lower than or equal to zero if (discount <= 0) { return '#NUM!'; } // Return error if settlement is greater than maturity if (moment(settlement).diff(moment(maturity)) > 0) { return '#NUM!'; } // Return error if maturity is more than one year after settlement if (moment(maturity).diff(moment(settlement), 'years') > 1) { return '#NUM!'; } // Return bond-equivalent yield return (365 * discount) / (360 - discount * Formula.DAYS360(settlement, maturity)); }; Formula.TBILLPRICE = function (settlement, maturity, discount) { // Return error if either date is invalid if (!moment(settlement).isValid() || !moment(maturity).isValid()) { return '#VALUE!'; } // Return error if discount is lower than or equal to zero if (discount <= 0) { return '#NUM!'; } // Return error if settlement is greater than maturity if (moment(settlement).diff(moment(maturity)) > 0) { return '#NUM!'; } // Return error if maturity is more than one year after settlement if (moment(maturity).diff(moment(settlement), 'years') > 1) { return '#NUM!'; } // Return bond-equivalent yield return 100 * (1 - discount * Formula.DAYS360(settlement, maturity) / 360); }; Formula.TBILLYIELD = function (settlement, maturity, price) { // Return error if either date is invalid if (!moment(settlement).isValid() || !moment(maturity).isValid()) { return '#VALUE!'; } // Return error if price is lower than or equal to zero if (price <= 0) { return '#NUM!'; } // Return error if settlement is greater than maturity if (moment(settlement).diff(moment(maturity)) > 0) { return '#NUM!'; } // Return error if maturity is more than one year after settlement if (moment(maturity).diff(moment(settlement), 'years') > 1) { return '#NUM!'; } // Return bond-equivalent yield return (100 - price) * 360 / (price * Formula.DAYS360(settlement, maturity)); }; Formula.VDB = function () { return; }; Formula.XIRR = function (values, dates, guess) { // Credits: algorithm inspired by Apache OpenOffice // Calculates the resulting amount var irrResult = function (values, dates, rate) { var r = rate + 1; var result = values[0]; for (var i = 1; i < values.length; i++) { result += values[i] / Math.pow(r, moment(dates[i]).diff(moment(dates[0]), 'days') / 365); } return result; }; // Calculates the first derivation var irrResultDeriv = function (values, dates, rate) { var r = rate + 1; var result = 0; for (var i = 1; i < values.length; i++) { var frac = moment(dates[i]).diff(moment(dates[0]), 'days') / 365; result -= frac * values[i] / Math.pow(r, frac + 1); } return result; }; // Check that values contains at least one positive value and one negative value var positive = false; var negative = false; for (var i = 0; i < values.length; i++) { if (values[i] > 0) { positive = true; } if (values[i] < 0) { negative = true; } } // Return error if values does not contain at least one positive value and one negative value if (!positive || !negative) { return '#NUM!'; } // Initialize guess and resultRate guess = guess || 0.1; var resultRate = guess; // Set maximum epsilon for end of iteration var epsMax = 1e-10; // Set maximum number of iterations var iterMax = 50; // Implement Newton's method var newRate, epsRate, resultValue; var iteration = 0; var contLoop = true; do { resultValue = irrResult(values, dates, resultRate); newRate = resultRate - resultValue / irrResultDeriv(values, dates, resultRate); epsRate = Math.abs(newRate - resultRate); resultRate = newRate; contLoop = (epsRate > epsMax) && (Math.abs(resultValue) > epsMax); } while (contLoop && (++iteration < iterMax)); if (contLoop) { return '#NUM!'; } // Return internal rate of return return resultRate; }; Formula.XNPV = function (rate, values, dates) { var result = 0; for (var i = 0; i < values.length; i++) { result += values[i] / Math.pow(1 + rate, moment(dates[i]).diff(moment(dates[0]), 'days') / 365); } return result; }; Formula.YIELD = function () { return; }; Formula.YIELDDISC = function () { return; }; Formula.YIELDMAT = function () { }; // Information functions Formula.ISNUMBER = function (number) { return (!isNaN(parseFloat(number)) && isFinite(number)) ? true : false; }; // Logical functions Formula.AND = function () { var result = true; for (var i = 0; i < arguments.length; i++) { if (!arguments[i]) { result = false; } } return result; }; Formula.FALSE = function () { return false; }; Formula.SWITCH = function () { var result; if (arguments.length > 0) { var targetValue = arguments[0]; var argc = arguments.length - 1; var switchCount = Math.floor(argc / 2); var switchSatisfied = false; var defaultClause = argc % 2 === 0 ? null : arguments[arguments.length - 1]; if (switchCount) { for (var index = 0; index < switchCount; index++) { if (targetValue === arguments[index * 2 + 1]) { result = arguments[index * 2 + 2]; switchSatisfied = true; break; } } } if (!switchSatisfied && defaultClause) { result = defaultClause; } } return result; }; Formula.IF = function (test, then_value, otherwise_value) { if (test) { return (typeof then_value === 'undefined') ? true : then_value; } else { return (typeof otherwise_value === 'undefined') ? true : otherwise_value; } }; Formula.IFERROR = function (value, value_if_error) { return (['#DIV/0!', '#N/A', '#NAME?', '#NUM!', '#NULL!', '#REF!', '#VALUE!'].indexOf(value) >= 0 ) ? value_if_error : value; }; Formula.IFNA = function (value, value_if_na) { return (value === '#N/A') ? value_if_na : value; }; Formula.NOT = function (logical) { return !logical; }; Formula.OR = function () { var result = false; for (var i = 0; i < arguments.length; i++) { if (arguments[i]) { result = true; } } return result; }; Formula.TRUE = function () { return true; }; Formula.XOR = function () { var result = 0; for (var i = 0; i < arguments.length; i++) { if (arguments[i]) { result++; } } return (Math.floor(Math.abs(result)) & 1) ? true : false; }; // Lookup and reference functions Formula.REFERENCE = function (context, reference) { try { var path = reference.split('.'), result = context; _(path).forEach(function (step) { if (step[step.length - 1] === ']') { var opening = step.indexOf('['); var index = step.substring(opening + 1, step.length - 1); result = result[step.substring(0, opening)][index]; } else { result = result[step]; } }); return result; } catch (error) { return; } }; // Math functions Formula.ABS = function (number) { return Math.abs(number); }; Formula.ACOS = function (number) { return Math.acos(number); }; Formula.ACOSH = function (number) { return Math.log(number + Math.sqrt(number * number - 1)); }; Formula.ACOT = function (number) { return Math.atan(1 / number); }; Formula.ACOTH = function (number) { return 0.5 * Math.log((number + 1) / (number - 1)); }; Formula.AGGREGATE = function (function_code, options) { var result = []; for (var i = 2; i < arguments.length; i++) { switch (function_code) { case 1: result[i - 2] = Formula.AVERAGE(arguments[i]); break; case 2: result[i - 2] = Formula.COUNT(arguments[i]); break; case 3: result[i - 2] = Formula.COUNTA(arguments[i]); break; case 4: result[i - 2] = Formula.MAX(arguments[i]); break; case 5: result[i - 2] = Formula.MIN(arguments[i]); break; case 6: result[i - 2] = Formula.PRODUCT(arguments[i]); break; case 7: result[i - 2] = Formula.STDEVS(arguments[i]); break; case 8: result[i - 2] = Formula.STDEVP(arguments[i]); break; case 9: result[i - 2] = Formula.SUM(arguments[i]); break; case 10: result[i - 2] = Formula.VARS(arguments[i]); break; case 11: result[i - 2] = Formula.VARP(arguments[i]); break; case 12: result[i - 2] = Formula.MEDIAN(arguments[i]); break; case 13: result[i - 2] = Formula.MODESNGL(arguments[i]); break; case 14: result[i - 2] = Formula.LARGE(arguments[i]); break; case 15: result[i - 2] = Formula.SMALL(arguments[i]); break; case 16: result[i - 2] = Formula.PERCENTILEINC(arguments[i]); break; case 17: result[i - 2] = Formula.QUARTILEINC(arguments[i]); break; case 18: result[i - 2] = Formula.PERCENTILEEXC(arguments[i]); break; case 19: result[i - 2] = Formula.QUARTILEEXC(arguments[i]); break; } } return result; }; Formula.ARABIC = function (text) { // Credits: Rafa? Kukawski if (!/^M*(?:D?C{0,3}|C[MD])(?:L?X{0,3}|X[CL])(?:V?I{0,3}|I[XV])$/.test(text)) { throw new Error('Incorrect roman number'); } var r = 0; text.replace(/[MDLV]|C[MD]?|X[CL]?|I[XV]?/g, function (i) { r += {M: 1000, CM: 900, D: 500, CD: 400, C: 100, XC: 90, L: 50, XL: 40, X: 10, IX: 9, V: 5, IV: 4, I: 1}[i]; }); return r; }; Formula.ASIN = function (number) { return Math.asin(number); }; Formula.ASINH = function (number) { return Math.log(number + Math.sqrt(number * number + 1)); }; Formula.ATAN = function (number) { return Math.atan(number); }; Formula.ATAN2 = function (number_x, number_y) { return Math.atan2(number_x, number_y); }; Formula.ATANH = function (number) { return Math.log((1 + number) / (1 - number)) / 2; }; Formula.BASE = function (number, radix, min_length) { min_length = (typeof min_length === 'undefined') ? 0 : min_length; var result = number.toString(radix); return new Array(Math.max(min_length + 1 - result.length, 0)).join('0') + result; }; Formula.CEILING = function (number, significance, mode) { if (significance === 0) { return 0; } significance = (typeof significance === 'undefined') ? 1 : Math.abs(significance); mode = (typeof mode === 'undefined') ? 0 : mode; var precision = -Math.floor(Math.log(significance) / Math.log(10)); if (number >= 0) { return Formula.ROUND(Math.ceil(number / significance) * significance, precision); } else { if (mode === 0) { return -Formula.ROUND(Math.floor(Math.abs(number) / significance) * significance, precision); } else { return -Formula.ROUND(Math.ceil(Math.abs(number) / significance) * significance, precision); } } }; Formula.CEILINGMATH = Formula.CEILING; Formula.CEILINGPRECISE = Formula.CEILING; Formula.COMBIN = function (number, number_chosen) { return Formula.FACT(number) / (Formula.FACT(number_chosen) * Formula.FACT(number - number_chosen)); }; Formula.COMBINA = function (number, number_chosen) { return (number === 0 && number_chosen === 0) ? 1 : Formula.COMBIN(number + number_chosen - 1, number - 1); }; Formula.COS = function (number) { return Math.cos(number); }; Formula.COSH = function (number) { return (Math.exp(number) + Math.exp(-number)) / 2; }; Formula.COT = function (number) { return 1 / Math.tan(number); }; Formula.COTH = function (number) { var e2 = Math.exp(2 * number); return (e2 + 1) / (e2 - 1); }; Formula.CSC = function (number) { return 1 / Math.sin(number); }; Formula.CSCH = function (number) { return 2 / (Math.exp(number) - Math.exp(-number)); }; Formula.DECIMAL = function (number, radix) { return parseInt(number, radix); }; Formula.DEGREES = function (number) { return number * 180 / Math.PI; }; Formula.EVEN = function (number) { return Formula.CEILING(number, -2, -1); }; Formula.EXP = function (number) { return Math.exp(number); }; Formula.FACT = function (number) { var n = Math.floor(number); if (n === 0 || n === 1) { return 1; } else if (MEMOIZED_FACT[n] > 0) { return MEMOIZED_FACT[n]; } else { MEMOIZED_FACT[n] = Formula.FACT(n - 1) * n; return MEMOIZED_FACT[n]; } }; Formula.FACTDOUBLE = function (number) { var n = Math.floor(number); if (n <= 0) { return 1; } else { return n * Formula.FACTDOUBLE(n - 2); } }; Formula.FLOOR = function (number, significance, mode) { if (significance === 0) { return 0; } significance = (typeof significance === 'undefined') ? 1 : Math.abs(significance); mode = (typeof mode === 'undefined') ? 0 : mode; var precision = -Math.floor(Math.log(significance) / Math.log(10)); if (number >= 0) { return Formula.ROUND(Math.floor(number / significance) * significance, precision); } else { if (mode === 0) { return -Formula.ROUND(Math.ceil(Math.abs(number) / significance) * significance, precision); } else { return -Formula.ROUND(Math.floor(Math.abs(number) / significance) * significance, precision); } } }; Formula.FLOORMATH = Formula.FLOOR; Formula.FLOORPRECISE = Formula.FLOOR; Formula.GCD = function () { // Credits: Andrew Pociu for (var r, a, i = arguments.length - 1, result = arguments[i]; i;) { for (a = arguments[--i]; (r = a % result); a = result, result = r) { //empty } } return result; }; Formula.INT = function (number) { return Math.floor(number); }; Formula.ISEVEN = function (number) { return (Math.floor(Math.abs(number)) & 1) ? false : true; }; Formula.ISOCEILING = Formula.CEILING; Formula.ISODD = function (number) { return (Math.floor(Math.abs(number)) & 1) ? true : false; }; Formula.LCM = function () { // Credits: Jonas Raoni Soares Silva var o = Formula.ARGSTOARRAY(arguments); for (var i, j, n, d, r = 1; (n = o.pop()) !== undefined;) { while (n > 1) { if (n % 2) { for (i = 3, j = Math.floor(Math.sqrt(n)); i <= j && n % i; i += 2) { //empty } d = (i <= j) ? i : n; } else { d = 2; } for (n /= d, r *= d, i = o.length; i; (o[--i] % d) === 0 && (o[i] /= d) === 1 && o.splice(i, 1)) { //empty } } } return r; }; Formula.LN = function (number) { return Math.log(number); }; Formula.LOG = function (number, base) { base = (typeof base === 'undefined') ? 10 : base; return Math.log(number) / Math.log(base); }; Formula.LOG10 = function (number) { return Math.log(number) / Math.log(10); }; Formula.MDETERM = numeric.det; Formula.MINVERSE = numeric.inv; Formula.MMULT = numeric.dot; Formula.MOD = function (dividend, divisor) { var modulus = Math.abs(dividend % divisor); return (divisor > 0) ? modulus : -modulus; }; Formula.MROUND = function (number, multiple) { if (number * multiple < 0) { throw new Error('Number and multiple must have the same sign.'); } return Math.round(number / multiple) * multiple; }; Formula.MULTINOMIAL = function () { var sum = 0; var divisor = 1; for (var i = 0; i < arguments.length; i++) { sum += arguments[i]; divisor *= Formula.FACT(arguments[i]); } return Formula.FACT(sum) / divisor; }; Formula.MUNIT = numeric.identity; Formula.ODD = function (number) { var temp = Math.ceil(Math.abs(number)); temp = (temp & 1) ? temp : temp + 1; return (number > 0) ? temp : -temp; }; Formula.PI = function () { return Math.PI; }; Formula.POWER = function (number, power) { var result = Math.pow(number, power); if (isNaN(result)) { return '#NUM!'; } return result; }; Formula.PRODUCT = function () { var result = 1; for (var i = 0; i < arguments.length; i++) { result *= arguments[i]; } return result; }; Formula.QUOTIENT = function (numerator, denominator) { return (numerator / denominator).toFixed(0); }; Formula.RADIANS = function (number) { return number * Math.PI / 180; }; Formula.RAND = function () { return Math.random(); }; Formula.RANDBETWEEN = function (bottom, top) { // Creative Commons Attribution 3.0 License // Copyright (c) 2012 eqcode return bottom + Math.ceil((top - bottom + 1) * Math.random()) - 1; }; Formula.ROUND = function (number, digits) { return Math.round(number * Math.pow(10, digits)) / Math.pow(10, digits); }; Formula.ROUNDDOWN = function (number, digits) { var sign = (number > 0) ? 1 : -1; return sign * (Math.floor(Math.abs(number) * Math.pow(10, digits))) / Math.pow(10, digits); }; Formula.ROUNDUP = function (number, digits) { var sign = (number > 0) ? 1 : -1; return sign * (Math.ceil(Math.abs(number) * Math.pow(10, digits))) / Math.pow(10, digits); }; Formula.SERIESSUM = function (x, n, m, coefficients) { var result = coefficients[0] * Math.pow(x, n); for (var i = 1; i < coefficients.length; i++) { result += coefficients[i] * Math.pow(x, n + i * m); } return result; }; Formula.SEC = function (number) { return 1 / Math.cos(number); }; Formula.SECH = function (number) { return 2 / (Math.exp(number) + Math.exp(-number)); }; Formula.SIGN = function (number) { if (number < 0) { return -1; } else if (number === 0) { return 0; } else { return 1; } }; Formula.SIN = function (number) { return Math.sin(number); }; Formula.SINH = function (number) { return (Math.exp(number) - Math.exp(-number)) / 2; }; Formula.SQRT = function (number) { return Math.sqrt(number); }; Formula.SQRTPI = function (number) { return Math.sqrt(number * Math.PI); }; Formula.SUBTOTAL = function (function_code) { var result = []; for (var i = 1; i < arguments.length; i++) { switch (function_code) { case 1: result[i - 1] = Formula.AVERAGE(arguments[i]); break; case 2: result[i - 1] = Formula.COUNT(arguments[i]); break; case 3: result[i - 1] = Formula.COUNTA(arguments[i]); break; case 4: result[i - 1] = Formula.MAX(arguments[i]); break; case 5: result[i - 1] = Formula.MIN(arguments[i]); break; case 6: result[i - 1] = Formula.PRODUCT(arguments[i]); break; case 7: result[i - 1] = Formula.STDEV(arguments[i]); break; case 8: result[i - 1] = Formula.STDEVP(arguments[i]); break; case 9: result[i - 1] = Formula.SUM(arguments[i]); break; case 10: result[i - 1] = Formula.VAR(arguments[i]); break; case 11: result[i - 1] = Formula.VARP(arguments[i]); break; } } return result; }; Formula.SUM = function () { var numbers = Formula.ARGSTOARRAY(arguments); var result = 0; for (var i = 0; i < numbers.length; i++) { if (numbers[i] instanceof Array) { for (var j = 0; j < numbers[i].length; j++) { if (numbers[i][j] instanceof Array) { for (var k = 0; k < numbers[i][j].length; k++) { result += (Formula.ISNUMBER(numbers[i][j][k])) ? numbers[i][j][k] : 0; } } else { result += (Formula.ISNUMBER(numbers[i][j])) ? numbers[i][j] : 0; } } } else { result += (Formula.ISNUMBER(numbers[i])) ? numbers[i] : 0; } } return result; }; Formula.SUMIF = function (range, criteria) { var result = 0; for (var i = 0; i < range.length; i++) { result += (eval(range[i] + criteria)) ? range[i] : 0; } return result; }; Formula.SUMIFS = function () { var criteria = (arguments.length - 1) / 2; var range = arguments[0]; var result = 0; for (var i = 0; i < range.length; i++) { var fit = true; for (var j = 0; j < criteria; j++) { if (!eval(arguments[2 * j + 1][i] + arguments[2 * j + 2])) { fit = false; } } result += (fit) ? range[i] : 0; } return result; }; Formula.SUMPRODUCT = function () { var arrays = arguments.length + 1; var result = 0; for (var i = 0; i < arguments[0].length; i++) { for (var j = 0; j < arguments[0][i].length; j++) { var product = 1; for (var k = 1; k < arrays; k++) { product *= arguments[k - 1][i][j]; } result += product; } } return result; }; Formula.SUMSQ = function () { var numbers = Formula.ARGSTOARRAY(arguments); var result = 0; for (var i = 0; i < numbers.length; i++) { result += (Formula.ISNUMBER(numbers[i])) ? numbers[i] * numbers[i] : 0; } return result; }; Formula.SUMX2MY2 = function (array_x, array_y) { var result = 0; for (var i = 0; i < array_x.length; i++) { result += array_x[i] * array_x[i] - array_y[i] * array_y[i]; } return result; }; Formula.SUMX2PY2 = function (array_x, array_y) { var result = 0; for (var i = 0; i < array_x.length; i++) { result += array_x[i] * array_x[i] + array_y[i] * array_y[i]; } return result; }; Formula.SUMXMY2 = function (array_x, array_y) { var result = 0; for (var i = 0; i < array_x.length; i++) { result += Math.pow(array_x[i] - array_y[i], 2); } return result; }; Formula.TAN = function (number) { return Math.tan(number); }; Formula.TANH = function (number) { var e2 = Math.exp(2 * number); return (e2 - 1) / (e2 + 1); }; Formula.TRUNC = function (number, digits) { digits = (typeof digits === 'undefined') ? 0 : digits; var sign = (number > 0) ? 1 : -1; return sign * (Math.floor(Math.abs(number) * Math.pow(10, digits))) / Math.pow(10, digits); }; // Statistical functions Formula.AVEDEV = function () { var range = Formula.ARGSCONCAT(arguments); return jStat.sum(jStat(range).subtract(jStat.mean(range)).abs()[0]) / range.length; }; Formula.AVERAGE = function () { var range = Formula.ARGSCONCAT(arguments); var n = range.length; var count = 0; var sigma = 0; for (var i = 0; i < n; i++) { if (range[i] !== true && range[i] !== false) { sigma += range[i]; count++; } } return sigma / count; }; Formula.AVERAGEA = function () { return jStat.mean(Formula.ARGSCONCAT(arguments)); }; Formula.AVERAGEIF = function (range, criteria, average_range) { average_range = (typeof average_range === 'undefined') ? range : average_range; var average_count = 0; var result = 0; for (var i = 0; i < range.length; i++) { if (eval(range[i] + criteria)) { result += average_range[i]; average_count++; } } return result / average_count; }; Formula.AVERAGEIFS = function () { var criteria = (arguments.length - 1) / 2; var range = arguments[0]; var count = 0; var result = 0; for (var i = 0; i < range.length; i++) { var fit = true; for (var j = 0; j < criteria; j++) { if (!eval(arguments[2 * j + 1][i] + arguments[2 * j + 2])) { fit = false; } } if (fit) { result += range[i]; count++; } } return result / count; }; Formula.BETADIST = function (x, alpha, beta, cumulative, A, B) { A = (typeof A === 'undefined') ? 0 : A; B = (typeof B === 'undefined') ? 1 : B; x = (x - A) / (B - A); return (cumulative) ? jStat.beta.cdf(x, alpha, beta) : jStat.beta.pdf(x, alpha, beta); }; Formula.BETAINV = function (probability, alpha, beta, A, B) { A = (typeof A === 'undefined') ? 0 : A; B = (typeof B === 'undefined') ? 1 : B; return jStat.beta.inv(probability, alpha, beta) * (B - A) + A; }; Formula.BINOMDIST = function (successes, trials, probability, cumulative) { return (cumulative) ? jStat.binomial.cdf(successes, trials, probability) : jStat.binomial.pdf(successes, trials, probability); }; Formula.BINOMDISTRANGE = function (trials, probability, successes, successes2) { successes2 = (typeof successes2 === 'undefined') ? successes : successes2; var result = 0; for (var i = successes; i <= successes2; i++) { result += Formula.COMBIN(trials, i) * Math.pow(probability, i) * Math.pow(1 - probability, trials - i); } return result; }; Formula.BINOMINV = function (trials, probability, alpha) { var x = 0; while (x <= trials) { if (jStat.binomial.cdf(x, trials, probability) >= alpha) { return x; } x++; } }; Formula.CHISQDIST = function (x, k, cumulative) { return (cumulative) ? jStat.chisquare.cdf(x, k) : jStat.chisquare.pdf(x, k); }; Formula.CHISQDISTRT = function (x, k) { return; }; Formula.CHISQINV = function (probability, k) { return jStat.chisquare.inv(probability, k); }; Formula.CHISQINVRT = function () { return; }; Formula.CHISQTEST = function () { return; }; Formula.CONFIDENCENORM = function (alpha, sd, n) { return jStat.normalci(1, alpha, sd, n)[1] - 1; }; Formula.CONFIDENCET = function (alpha, sd, n) { return jStat.tci(1, alpha, sd, n)[1] - 1; }; Formula.CORREL = function () { return jStat.corrcoeff.apply(this, arguments); }; Formula.COUNT = function () { return Formula.ARGSCONCAT(arguments).length; }; Formula.COUNTA = function () { var range = Formula.ARGSCONCAT(arguments); return range.length - Formula.COUNTBLANK(range); }; Formula.COUNTBLANK = function () { var range = Formula.ARGSCONCAT(arguments); var blanks = 0; for (var i = 0; i < range.length; i++) { if (range[i] === null || range[i] === '') { blanks++; } } return blanks; }; Formula.COUNTIF = function (range, criteria) { var matches = 0; for (var i = 0; i < range.length; i++) { if (range[i].match(new RegExp(criteria))) { matches++; } } return matches; }; Formula.COUNTIFS = function () { var criteria = (arguments.length - 1) / 2; var range = arguments[0]; var result = 0; for (var i = 0; i < range.length; i++) { var fit = true; for (var j = 0; j < criteria; j++) { if (!eval(arguments[2 * j + 1][i] + arguments[2 * j + 2])) { fit = false; } } result += (fit) ? 1 : 0; } return result; }; Formula.COUNTUNIQUE = function () { return _.uniq(Formula.ARGSCONCAT(arguments)).length; }; Formula.COVARIANCEP = function (array1, array2) { var mean1 = jStat.mean(array1); var mean2 = jStat.mean(array2); var result = 0; var n = array1.length; for (var i = 0; i < n; i++) { result += (array1[i] - mean1) * (array2[i] - mean2); } return result / n; }; Formula.COVARIANCES = function () { return jStat.covariance.apply(this, arguments); }; Formula.DEVSQ = function () { var range = Formula.ARGSCONCAT(arguments); var mean = jStat.mean(range); var result = 0; for (var i = 0; i < range.length; i++) { result += Math.pow((range[i] - mean), 2); } return result; }; Formula.EXPONDIST = function (x, lambda, cumulative) { return (cumulative) ? jStat.exponential.cdf(x, lambda) : jStat.exponential.pdf(x, lambda); }; Formula.FDIST = function (x, d1, d2, cumulative) { return (cumulative) ? jStat.centralF.cdf(x, d1, d2) : jStat.centralF.pdf(x, d1, d2); }; Formula.FDISTRT = function () { return; }; Formula.FINV = function (probability, d1, d2) { if (probability <= 0.0 || probability > 1.0) { return '#NUM!'; } return jStat.centralF.inv(1.0 - probability, d1, d2); }; Formula.FINVRT = function () { return; }; Formula.FTEST = function () { return; }; Formula.FISHER = function (x) { return Math.log((1 + x) / (1 - x)) / 2; }; Formula.FISHERINV = function (y) { var e2y = Math.exp(2 * y); return (e2y - 1) / (e2y + 1); }; Formula.FORECAST = function (x, data_y, data_x) { var xmean = jStat.mean(data_x); var ymean = jStat.mean(data_y); var n = data_x.length; var num = 0; var den = 0; for (var i = 0; i < n; i++) { num += (data_x[i] - xmean) * (data_y[i] - ymean); den += Math.pow(data_x[i] - xmean, 2); } var b = num / den; var a = ymean - b * xmean; return a + b * x; }; Formula.FREQUENCY = function (data, bins) { var n = data.length; var b = bins.length; var r = []; for (var i = 0; i <= b; i++) { r[i] = 0; for (var j = 0; j < n; j++) { if (i === 0) { if (data[j] <= bins[0]) { r[0] += 1; } } else if (i < b) { if (data[j] > bins[i - 1] && data[j] <= bins[i]) { r[i] += 1; } } else if (i === b) { if (data[j] > bins[b - 1]) { r[b] += 1; } } } } return r; }; Formula.GAMMA = function () { return jStat.gammafn.apply(this, arguments); }; Formula.GAMMADIST = function (x, alpha, beta, cumulative) { /* var shape = alpha; var scale = 1 / beta; return (cumulative) ? jStat.gamma.cdf(x, shape, scale) : jStat.gamma.pdf(x, shape, scale); */ return; }; Formula.GAMMAINV = function (probability, alpha, beta) { /* var shape = alpha; var scale = 1 / beta; return jStat.gamma.inv(probability, shape, scale); */ return; }; Formula.GAMMALN = function () { return jStat.gammaln.apply(this, arguments); }; Formula.GAMMALNPRECISE = function () { return; }; Formula.GAUSS = function (z) { return jStat.normal.cdf(z, 0, 1) - 0.5; }; Formula.GEOMEAN = function () { return jStat.geomean(Formula.ARGSCONCAT(arguments)); }; Formula.GROWTH = function (known_y, known_x, new_x, use_const) { // Credits: Ilmari Karonen // Default values for optional parameters: var i; if (typeof(known_x) === 'undefined') { known_x = []; for (i = 1; i <= known_y.length; i++) { known_x.push(i); } } if (typeof(new_x) === 'undefined') { new_x = []; for (i = 1; i <= known_y.length; i++) { new_x.push(i); } } if (typeof(use_const) === 'undefined') { use_const = true; } // Calculate sums over the data: var n = known_y.length; var avg_x = 0; var avg_y = 0; var avg_xy = 0; var avg_xx = 0; for (i = 0; i < n; i++) { var x = known_x[i]; var y = Math.log(known_y[i]); avg_x += x; avg_y += y; avg_xy += x * y; avg_xx += x * x; } avg_x /= n; avg_y /= n; avg_xy /= n; avg_xx /= n; // Compute linear regression coefficients: var beta; var alpha; if (use_const) { beta = (avg_xy - avg_x * avg_y) / (avg_xx - avg_x * avg_x); alpha = avg_y - beta * avg_x; } else { beta = avg_xy / avg_xx; alpha = 0; } // Compute and return result array: var new_y = []; for (i = 0; i < new_x.length; i++) { new_y.push(Math.exp(alpha + beta * new_x[i])); } return new_y; }; Formula.HARMEAN = function () { var range = Formula.ARGSCONCAT(arguments); var n = range.length; var den = 0; for (var i = 0; i < n; i++) { den += 1 / range[i]; } return n / den; }; Formula.HYPGEOMDIST = function (x, n, M, N, cumulative) { function pdf(x, n, M, N) { return Formula.COMBIN(M, x) * Formula.COMBIN(N - M, n - x) / Formula.COMBIN(N, n); } function cdf(x, n, M, N) { var result = 0; for (var i = 0; i <= x; i++) { result += pdf(i, n, M, N); } return result; } return (cumulative) ? cdf(x, n, M, N) : pdf(x, n, M, N); }; Formula.INTERCEPT = function (data_y, data_x) { return Formula.FORECAST(0, data_y, data_x); }; Formula.KURT = function () { var range = Formula.ARGSCONCAT(arguments); var mean = jStat.mean(range); var n = range.length; var sigma = 0; for (var i = 0; i < n; i++) { sigma += Math.pow(range[i] - mean, 4); } sigma = sigma / Math.pow(jStat.stdev(range, true), 4); return ((n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3))) * sigma - 3 * (n - 1) * (n - 1) / ((n - 2) * (n - 3)); }; Formula.LARGE = function (array, k) { return array.sort(function (a, b) { return b - a; })[k - 1]; }; Formula.LINEST = function (data_y, data_x) { var xmean = jStat.mean(data_x); var ymean = jStat.mean(data_y); var n = data_x.length; var num = 0; var den = 0; for (var i = 0; i < n; i++) { num += (data_x[i] - xmean) * (data_y[i] - ymean); den += Math.pow(data_x[i] - xmean, 2); } var m = num / den; var b = ymean - m * xmean; return [m, b]; }; Formula.LOGEST = function () { return; }; Formula.LOGNORMDIST = function (x, mean, sd, cumulative) { return (cumulative) ? jStat.lognormal.cdf(x, mean, sd) : jStat.lognormal.pdf(x, mean, sd); }; Formula.LOGNORMINV = function (probability, mean, sd) { return jStat.lognormal.inv(probability, mean, sd); }; Formula.MAX = function () { var range = Formula.ARGSCONCAT(arguments); var n = range.length; var max = (n > 0) ? range[0] : 0; for (var i = 0; i < n; i++) { max = (range[i] > max && (range[i] !== true) && (range[i] !== false)) ? range[i] : max; } return max; }; Formula.MAXA = function () { var range = Formula.ARGSCONCAT(arguments); return (range.length > 0) ? Math.max.apply(Math, range) : 0; }; Formula.MEDIAN = function () { return jStat.median(Formula.ARGSCONCAT(arguments)); }; Formula.MIN = function () { var range = Formula.ARGSCONCAT(arguments); var n = range.length; var min = (n > 0) ? range[0] : 0; for (var i = 0; i < n; i++) { min = (range[i] < min && (range[i] !== true) && (range[i] !== false)) ? range[i] : min; } return min; }; Formula.MINA = function () { var range = Formula.ARGSCONCAT(arguments); return (range.length > 0) ? Math.min.apply(Math, range) : 0; }; Formula.MODEMULT = function () { // Credits: Roönaän var range = Formula.ARGSCONCAT(arguments), n = range.length, count = {}, maxItems = [], max = 0, currentItem; for (var i = 0; i < n; i++) { currentItem = range[i]; count[currentItem] = count[currentItem] ? count[currentItem] + 1 : 1; if (count[currentItem] > max) { max = count[currentItem]; maxItems = []; } if (count[currentItem] === max) { maxItems[maxItems.length] = currentItem; } } return maxItems; }; Formula.MODESNGL = function () { return Formula.MODEMULT(Formula.ARGSCONCAT(arguments)).sort(function (a, b) { return a - b; })[0]; }; Formula.NEGBINOMDIST = function (k, r, p, cumulative) { return (cumulative) ? jStat.negbin.cdf(k, r, p) : jStat.negbin.pdf(k, r, p); }; Formula.NORMDIST = function (x, mean, sd, cumulative) { // Check parameters if (isNaN(x) || isNaN(mean) || isNaN(sd)) { return '#VALUE!'; } if (sd <= 0) { return '#NUM!'; } // Return normal distribution computed by jStat [http://jstat.org] return (cumulative) ? jStat.normal.cdf(x, mean, sd) : jStat.normal.pdf(x, mean, sd); }; Formula.NORMINV = function (probability, mean, sd) { return jStat.normal.inv(probability, mean, sd); }; Formula.NORMSDIST = function (z, cumulative) { return (cumulative) ? jStat.normal.cdf(z, 0, 1) : jStat.normal.pdf(z, 0, 1); }; Formula.NORMSINV = function (probability) { return jStat.normal.inv(probability, 0, 1); }; Formula.PEARSON = function (data_x, data_y) { var xmean = jStat.mean(data_x); var ymean = jStat.mean(data_y); var n = data_x.length; var num = 0; var den1 = 0; var den2 = 0; for (var i = 0; i < n; i++) { num += (data_x[i] - xmean) * (data_y[i] - ymean); den1 += Math.pow(data_x[i] - xmean, 2); den2 += Math.pow(data_y[i] - ymean, 2); } return num / Math.sqrt(den1 * den2); }; Formula.PERCENTILEEXC = function (array, k) { array = array.sort(function (a, b) { { return a - b; } }); var n = array.length; if (k < 1 / (n + 1) || k > 1 - 1 / (n + 1)) { return '#NUM!'; } var l = k * (n + 1) - 1; var fl = Math.floor(l); return Formula.CLEANFLOAT((l === fl) ? array[l] : array[fl] + (l - fl) * (array[fl + 1] - array[fl])); }; Formula.PERCENTILEINC = function (array, k) { array = array.sort(function (a, b) { return a - b; }); var n = array.length; var l = k * (n - 1); var fl = Math.floor(l); return Formula.CLEANFLOAT((l === fl) ? array[l] : array[fl] + (l - fl) * (array[fl + 1] - array[fl])); }; Formula.PERCENTRANKEXC = function (array, x, significance) { array = array.sort(function (a, b) { return a - b; }); var uniques = _.uniq(array); var n = array.length; var m = uniques.length; significance = (typeof significance === 'undefined') ? 3 : significance; var power = Math.pow(10, significance); var result = 0; var match = false; var i = 0; while (!match && i < m) { if (x === uniques[i]) { result = (array.indexOf(uniques[i]) + 1) / (n + 1); match = true; } else if (x >= uniques[i] && (x < uniques[i + 1] || i === m - 1)) { result = (array.indexOf(uniques[i]) + 1 + (x - uniques[i]) / (uniques[i + 1] - uniques[i])) / (n + 1); match = true; } i++; } return Math.floor(result * power) / power; }; Formula.PERCENTRANKINC = function (array, x, significance) { array = array.sort(function (a, b) { return a - b; }); var uniques = _.uniq(array); var n = array.length; var m = uniques.length; significance = (typeof significance === 'undefined') ? 3 : significance; var power = Math.pow(10, significance); var result = 0; var match = false; var i = 0; while (!match && i < m) { if (x === uniques[i]) { result = array.indexOf(uniques[i]) / (n - 1); match = true; } else if (x >= uniques[i] && (x < uniques[i + 1] || i === m - 1)) { result = (array.indexOf(uniques[i]) + (x - uniques[i]) / (uniques[i + 1] - uniques[i])) / (n - 1); match = true; } i++; } return Math.floor(result * power) / power; }; Formula.PERMUT = function (number, number_chosen) { return Formula.FACT(number) / Formula.FACT(number - number_chosen); }; Formula.PERMUTATIONA = function (number, number_chosen) { return Math.pow(number, number_chosen); }; Formula.PHI = function (x) { return Math.exp(-0.5 * x * x) / SQRT2PI; }; Formula.POISSONDIST = function (x, mean, cumulative) { return (cumulative) ? jStat.poisson.cdf(x, mean) : jStat.poisson.pdf(x, mean); }; Formula.PROB = function (range, probability, lower, upper) { if (typeof lower === 'undefined') { return 0; } upper = (typeof upper === 'undefined') ? lower : upper; if (lower === upper) { return (range.indexOf(lower) >= 0) ? probability[range.indexOf(lower)] : 0; } var sorted = range.sort(function (a, b) { return a - b; }); var n = sorted.length; var result = 0; for (var i = 0; i < n; i++) { if (sorted[i] >= lower && sorted[i] <= upper) { result += probability[range.indexOf(sorted[i])]; } } return result; }; Formula.QUARTILEEXC = function (range, quart) { switch (quart) { case 1: return Formula.PERCENTILEEXC(range, 0.25); case 2: return Formula.PERCENTILEEXC(range, 0.5); case 3: return Formula.PERCENTILEEXC(range, 0.75); default: return '#NUM!'; } }; Formula.QUARTILEINC = function (range, quart) { switch (quart) { case 1: return Formula.PERCENTILEINC(range, 0.25); case 2: return Formula.PERCENTILEINC(range, 0.5); case 3: return Formula.PERCENTILEINC(range, 0.75); default: return '#NUM!'; } }; Formula.RANKAVG = function (number, range, order) { order = (typeof order === 'undefined') ? false : order; var sort = (order) ? function (a, b) { return a - b; } : function (a, b) { return b - a; }; range = range.sort(sort); var count = Formula.COUNTIN(range, number); return (count > 1) ? (2 * range.indexOf(number) + count + 1) / 2 : range.indexOf(number) + 1; }; Formula.RANKEQ = function (number, range, order) { order = (typeof order === 'undefined') ? false : order; var sort = (order) ? function (a, b) { return a - b; } : function (a, b) { return b - a; }; range = range.sort(sort); return range.indexOf(number) + 1; }; Formula.RSQ = function (data_x, data_y) { return Math.pow(Formula.PEARSON(data_x, data_y), 2); }; Formula.SKEW = function () { var range = Formula.ARGSCONCAT(arguments); var mean = jStat.mean(range); var n = range.length; var sigma = 0; for (var i = 0; i < n; i++) { sigma += Math.pow(range[i] - mean, 3); } return n * sigma / ((n - 1) * (n - 2) * Math.pow(jStat.stdev(range, true), 3)); }; Formula.SKEWP = function () { var range = Formula.ARGSCONCAT(arguments); var mean = jStat.mean(range); var n = range.length; var m2 = 0; var m3 = 0; for (var i = 0; i < n; i++) { m3 += Math.pow(range[i] - mean, 3); m2 += Math.pow(range[i] - mean, 2); } m3 = m3 / n; m2 = m2 / n; return m3 / Math.pow(m2, 3 / 2); }; Formula.SLOPE = function (data_y, data_x) { var xmean = jStat.mean(data_x); var ymean = jStat.mean(data_y); var n = data_x.length; var num = 0; var den = 0; for (var i = 0; i < n; i++) { num += (data_x[i] - xmean) * (data_y[i] - ymean); den += Math.pow(data_x[i] - xmean, 2); } return num / den; }; Formula.SMALL = function (array, k) { return array.sort(function (a, b) { return a - b; })[k - 1]; }; Formula.STANDARDIZE = function (x, mean, sd) { return (x - mean) / sd; }; Formula.STDEVA = function () { var range = Formula.ARGSCONCAT(arguments); var n = range.length; var sigma = 0; var mean = jStat.mean(range); for (var i = 0; i < n; i++) { sigma += Math.pow(range[i] - mean, 2); } return Math.sqrt(sigma / (n - 1)); }; Formula.STDEVP = function () { var range = Formula.ARGSCONCAT(arguments); var n = range.length; var sigma = 0; var count = 0; var mean = Formula.AVERAGE(range); for (var i = 0; i < n; i++) { if (range[i] !== true && range[i] !== false) { sigma += Math.pow(range[i] - mean, 2); count++; } } return Math.sqrt(sigma / count); }; Formula.STDEVPA = function () { var range = Formula.ARGSCONCAT(arguments); var n = range.length; var sigma = 0; var mean = jStat.mean(range); for (var i = 0; i < n; i++) { sigma += Math.pow(range[i] - mean, 2); } return Math.sqrt(sigma / n); }; Formula.STDEVS = function () { var range = Formula.ARGSCONCAT(arguments); var n = range.length; var sigma = 0; var count = 0; var mean = Formula.AVERAGE(range); for (var i = 0; i < n; i++) { if (range[i] !== true && range[i] !== false) { sigma += Math.pow(range[i] - mean, 2); count++; } } return Math.sqrt(sigma / (count - 1)); }; Formula.STEYX = function (data_y, data_x) { var xmean = jStat.mean(data_x); var ymean = jStat.mean(data_y); var n = data_x.length; var lft = 0; var num = 0; var den = 0; for (var i = 0; i < n; i++) { lft += Math.pow(data_y[i] - ymean, 2); num += (data_x[i] - xmean) * (data_y[i] - ymean); den += Math.pow(data_x[i] - xmean, 2); } return Math.sqrt((lft - num * num / den) / (n - 2)); }; Formula.TDIST = function (x, df, cumulative) { return (cumulative) ? jStat.studentt.cdf(x, df) : jStat.studentt.pdf(x, df); }; Formula.TDIST2T = function () { return; }; Formula.TDISTRT = function () { return; }; Formula.TINV = function (probability, df) { return jStat.studentt.inv(probability, df); }; Formula.TINV2T = function () { return; }; Formula.TTEST = function () { return; }; Formula.TREND = function () { return; }; Formula.TRIMMEAN = function (range, percent) { var n = range.length; var trim = Formula.FLOOR(range.length * percent, 2) / 2; return jStat.mean(_.initial(_.rest(range.sort(function (a, b) { return a - b; }), trim), trim)); }; Formula.VARA = function () { var range = Formula.ARGSCONCAT(arguments); var n = range.length; var sigma = 0; var mean = jStat.mean(range); for (var i = 0; i < n; i++) { sigma += Math.pow(range[i] - mean, 2); } return sigma / (n - 1); }; Formula.VARP = function () { var range = Formula.ARGSCONCAT(arguments); var n = range.length; var sigma = 0; var count = 0; var mean = Formula.AVERAGE(range); for (var i = 0; i < n; i++) { if (range[i] !== true && range[i] !== false) { sigma += Math.pow(range[i] - mean, 2); count++; } } return sigma / count; }; Formula.VARPA = function () { var range = Formula.ARGSCONCAT(arguments); var n = range.length; var sigma = 0; var mean = jStat.mean(range); for (var i = 0; i < n; i++) { sigma += Math.pow(range[i] - mean, 2); } return sigma / n; }; Formula.VARS = function () { var range = Formula.ARGSCONCAT(arguments); var n = range.length; var sigma = 0; var count = 0; var mean = Formula.AVERAGE(range); for (var i = 0; i < n; i++) { if (range[i] !== true && range[i] !== false) { sigma += Math.pow(range[i] - mean, 2); count++; } } return sigma / (count - 1); }; Formula.WEIBULLDIST = function (x, alpha, beta, cumulative) { return (cumulative) ? 1 - Math.exp(-Math.pow(x / beta, alpha)) : Math.pow(x, alpha - 1) * Math.exp(-Math.pow(x / beta, alpha)) * alpha / Math.pow(beta, alpha); }; Formula.ZTEST = function (range, x, sigma) { var n = range.length; var sd = (typeof sigma === 'undefined') ? Formula.STDEVS(range) : sigma; return 1 - Formula.NORMSDIST((Formula.AVERAGE(range) - x) / (sd / Math.sqrt(n)), Formula.TRUE); }; // Text functions Formula.CHAR = function (number) { return String.fromCharCode(number); }; Formula.CLEAN = function (text) { var re = /[\0-\x1F]/g; return text.replace(re, ""); }; Formula.CODE = function (text) { return text.charCodeAt(0); }; Formula.CONCATENATE = function () { var string = ''; for (var i = 0; i < arguments.length; i++) { if (arguments[i] !== null && arguments[i] !== undefined) { string += arguments[i]; } } return string; }; Formula.DOLLAR = function (number, decimals) { decimals = (typeof decimals === 'undefined') ? 2 : decimals; var format = ''; if (decimals <= 0) { number = Math.round(number * Math.pow(10, decimals)) / Math.pow(10, decimals); format = '($0,0)'; } else if (decimals > 0) { format = '($0,0.' + new Array(decimals + 1).join('0') + ')'; } return numeral(number).format(format); }; Formula.EXACT = function (text1, text2) { return text1 === text2; }; Formula.FIND = function (find_text, within_text, position) { position = (typeof position === 'undefined') ? 0 : position; return within_text ? within_text.indexOf(find_text, position - 1) + 1 : null; }; Formula.FIXED = function (number, decimals, no_commas) { decimals = (typeof decimals === 'undefined') ? 2 : decimals; no_commas = (typeof no_commas === 'undefined') ? false : no_commas; var format = no_commas ? '0' : '0,0'; if (decimals <= 0) { number = Math.round(number * Math.pow(10, decimals)) / Math.pow(10, decimals); } else if (decimals > 0) { format += '.' + new Array(decimals + 1).join('0'); } return numeral(number).format(format); }; Formula.HTML2TEXT = function (value) { var result = ''; if (value) { if (value instanceof Array) { value.forEach(function (line) { if (result !== '') { result += '\n'; } result += (line.replace(/<(?:.|\n)*?>/gm, '')); }); } else { result = value.replace(/<(?:.|\n)*?>/gm, ''); } } return result; }; Formula.HUMANIZE = function (value) { if (value instanceof Date) { var dvalue = moment(value); if (dvalue.hours() || dvalue.minutes() || dvalue.seconds()) { return dvalue.format("dddd, MMMM Do YYYY, h:mm:ss"); } else { return dvalue.format("dddd, MMMM Do YYYY"); } } return value; }; Formula.JOIN = function (array, separator) { return array.join(separator); }; Formula.LEFT = function (text, number) { number = (typeof number === 'undefined') ? 1 : number; return text ? text.substring(0, number) : null; }; Formula.LEN = function (text) { return text ? text.length : 0; }; Formula.LOWER = function (text) { return text ? text.toLowerCase() : text; }; Formula.MID = function (text, start, number) { return text.substring(start - 1, number); }; Formula.NUMBERVALUE = function (text, decimal_separator, group_separator) { decimal_separator = (typeof decimal_separator === 'undefined') ? '.' : decimal_separator; group_separator = (typeof group_separator === 'undefined') ? ',' : group_separator; return Number(text.replace(decimal_separator, '.').replace(group_separator, '')); }; Formula.PROPER = function (text) { return text.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); }); }; Formula.REGEXEXTRACT = function (text, regular_expression) { var match = text.match(new RegExp(regular_expression)); console.log(match); return match ? (match[match.length > 1 ? match.length - 1 : 0]) : null; }; Formula.REGEXMATCH = function (text, regular_expression, full) { var match = text.match(new RegExp(regular_expression)); return full ? match : !!match; }; Formula.REGEXREPLACE = function (text, regular_expression, replacement) { return text.replace(new RegExp(regular_expression), replacement); }; Formula.REPLACE = function (text, position, length, new_text) { return text.substr(0, position - 1) + new_text + text.substr(position - 1 + length); }; Formula.REPT = function (text, number) { return new Array(number + 1).join(text); }; Formula.RIGHT = function (text, number) { number = (typeof number === 'undefined') ? 1 : number; return text ? text.substring(text.length - number) : null; }; Formula.ROMAN = function (number) { // The MIT License // Copyright (c) 2008 Steven Levithan var digits = String(number).split(''); var key = ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX']; var roman = ''; var i = 3; while (i--) { roman = (key[+digits.pop() + (i * 10)] || '') + roman; } return new Array(+digits.join('') + 1).join('M') + roman; }; Formula.SEARCH = function (find_text, within_text, position) { position = (typeof position === 'undefined') ? 0 : position; return within_text.toLowerCase().indexOf(find_text.toLowerCase(), position - 1) + 1; }; Formula.SPLIT = function (text, separator) { return _s.words(text, separator); }; Formula.SUBSTITUTE = function (text, old_text, new_text, occurrence) { if (!text || !old_text || !new_text) { return text; } else if (typeof occurrence === 'undefined') { return text.replace(new RegExp(old_text, 'g'), new_text); } else { var index = 0; var i = 0; while (text.indexOf(old_text, index) > 0) { index = text.indexOf(old_text, index + 1); i++; if (i === occurrence) { return text.substring(0, index) + new_text + text.substring(index + old_text.length); } } } }; Formula.T = function (value) { return (typeof value === "string") ? value : null; }; Formula.TEXT = function (value, format) { var text = ''; if (value) { if (value instanceof Object) { try { text = JSON.stringify(value); } catch (err) { // ignore } } else if (typeof value === 'string') { if (format) { text = (format.indexOf('0') >= 0) ? numeral(value).format(format) : moment(new Date(value)).format(format); } else { text = value; } } else if (value.toString && typeof value.toString === 'function') { text = value.toString(); } } return text; }; Formula.TRIM = function (text) { return _s.clean(text); }; Formula.UNICHAR = Formula.CHAR; Formula.UNICODE = Formula.CODE; Formula.UPPER = function (text) { return text.toUpperCase(); }; Formula.VALUE = function (text) { return numeral().unformat(text); }; // Hashing function Formula.MD5 = function (data, key, raw) { return md5(data, key, raw); }; Formula.NUMERAL = function (number, format) { return numeral(number).format(format); }; // Excel Error Handling Formula.ISERR = function (value) { return value === '#VALUE!' || value === '#REF!' || value === '#DIV/0!' || value === '#NUM!' || value === '#NAME?' || value === '#NULL!' || isNaN(value); }; Formula.ISERROR = function (value) { return Formula.ISERR(value) || value === '#N/A'; }; Formula.IFERROR = function (value, valueIfError) { if (Formula.ISERROR(value)) { return valueIfError; } return value; }; return Formula; } }).call(this);
lib/formula.js
// Copyright (c) 2012 Sutoiku, Inc. // 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. // Some algorithms have been ported from Apache OpenOffice: /************************************************************** * * 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. * *************************************************************/ /*jslint evil: true*/ /*jshint -W079 */ /*global define */ (function () { if (typeof exports !== "undefined") { module.exports = exportModule( require('numeric'), require('numeral'), require('jStat'), require('moment'), require('lodash'), require('underscore.string'), require('blueimp-md5') ); } else if (typeof define === "function" && define.amd) { define( 'formula', ['numeric', 'numeral', 'jStat', 'moment', 'lodash', 'underscore.string', 'md5'], exportModule ); } function exportModule(numeric, numeral, jStatLib, moment, _, _s, md5Lib) { var Formula = {}, jStat = jStatLib.jStat, md5 = md5Lib.md5; var MEMOIZED_FACT = []; var SQRT2PI = 2.5066282746310002; var WEEK_STARTS = [ undefined, 0, 1, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, 1, 2, 3, 4, 5, 6, 0 ]; var WEEK_TYPES = [ [], [1, 2, 3, 4, 5, 6, 7], [7, 1, 2, 3, 4, 5, 6], [6, 0, 1, 2, 3, 4, 5], [], [], [], [], [], [], [], [7, 1, 2, 3, 4, 5, 6], [6, 7, 1, 2, 3, 4, 5], [5, 6, 7, 1, 2, 3, 4], [4, 5, 6, 7, 1, 2, 3], [3, 4, 5, 6, 7, 1, 2], [2, 3, 4, 5, 6, 7, 1], [1, 2, 3, 4, 5, 6, 7] ]; var WEEKEND_TYPES = [ [], [6, 0], [0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], undefined, undefined, undefined, [0], [1], [2], [3], [4], [5], [6] ]; // Override some functions Formula.UNIQUE = function () { return _.unique(arguments); }; Formula.FLATTEN = function () { return _.flatten(arguments); }; // Generate a callback function Formula.FUNCTION = function () { var args = Array.prototype.slice.call(arguments); var expression = args[args.length - 1]; var regexp = /(\w+)\(/g; var newExpression = expression.replace(regexp, function () { return "Formulae." + arguments[0]; }); args[args.length - 1] = "return " + newExpression + ";"; if (newExpression !== expression) { args.unshift('Formulae'); } return Function.apply(null, args); }; // Moment functions Formula.MOMENT = function (timestamp, format) { return moment(timestamp).format(format); }; Formula.MOMENTADD = function (start_date, period, number) { return moment(start_date).add(period, number); }; Formula.MOMENTDIFF = function (start_date, end_date, period) { return moment(end_date).diff(moment.utc(start_date), period); }; Formula.MOMENTSUB = function (start_date, period, number) { return moment(start_date).subtract(period, number); }; Formula.MOMENTUTC = function (timestamp, format) { return moment.utc(timestamp).format(format); }; Formula.MOMENTUTCADD = function (start_date, period, number) { return moment.utc(start_date).add(period, number); }; Formula.MOMENTUTCDIFF = function (start_date, end_date, period) { return moment.utc(end_date).diff(moment.utc(start_date), period); }; Formula.MOMENTUTCSUB = function (start_date, period, number) { return moment.utc(start_date).subtract(period, number); }; Formula.MOMENTUNIX = function (unixTime) { return moment.unix(unixTime).toDate(); }; Formula.MOMENTFORMAT = function (date, format) { return moment(date).format(format); }; Formula.MOMENTISLEAPYEAR = function (date, format) { return moment(date, format).isLeapYear(); }; Formula.MOMENTISDST = function (date, format) { return moment(date, format).isDST(); }; Formula.MOMENTSTARTOF = function (date, units, format) { return moment(date, format).startOf(units).toDate(); }; Formula.MOMENTENDOF = function (date, units, format) { return moment(date, format).endOf(units).toDate(); }; Formula.MOMENTISAFTER = function (date1, date2, format) { return moment(date1, format).isAfter(moment(date2, format)); }; Formula.MOMENTISBEFORE = function (date1, date2, format) { return moment(date1, format).isBefore(moment(date2, format)); }; Formula.INTERVAL = function (second) { var year = Math.floor(second/946080000); second = second%946080000; var month = Math.floor(second/2592000); second = second%2592000; var day = Math.floor(second/86400); second = second%86400; var hour = Math.floor(second/3600); second = second%3600; var min = Math.floor(second/60); second = second%60; var sec = second; year = (year > 0) ? year + 'Y' : ''; month = (month > 0) ? month + 'M' : ''; day = (day > 0) ? day + 'D' : ''; hour = (hour > 0) ? hour + 'H' : ''; min = (min > 0) ? min + 'M' : ''; sec = (sec > 0) ? sec + 'S' : ''; return 'P' + year + month + day + 'T' + hour + min + sec; }; // Custom Functions Formula.ARGSCONCAT = function (args) { var result = []; for (var i = 0; i < args.length; i++) { result = result.concat(args[i]); } return result; }; Formula.ARGSTOARRAY = function (args) { return Array.prototype.slice.call(args, 0); }; Formula.CLEANFLOAT = function (number) { var power = Math.pow(10, 14); return Math.round(number * power) / power; }; Formula.COUNTIN = function (range, value) { var result = 0; for (var i = 0; i < range.length; i++) { if (range[i] === value) { result++; } } return result; }; Formula.FINDFIELD = function(database, title) { var index = null; for (var i = 0; i < database.length; i++) { if (database[i][0] === title) { index = i; break; } } // Return error if the input field title is incorrect if (index == null) { return '#VALUE!'; } return index; }; Formula.FINDRESULTINDEX = function(database, criteria) { var maxCriteriaLength = criteria[0].length; for (var i = 1; i < criteria.length; i++) { if (criteria[i].length > maxCriteriaLength) { maxCriteriaLength = criteria[i].length; } } var columnResultIndexes = []; for (i = 1; i < maxCriteriaLength; i++) { var rowResultIndexes = []; for (var j = 0; j < criteria.length; j++) { if (criteria[j].length < maxCriteriaLength) { continue; } var criteriaTitle = criteria[j][0]; var criteriaIndex = Formula.FINDFIELD(database, criteriaTitle); var criteriaValues = _.rest(database[criteriaIndex]); var count = 0; var singleResultIndexes = []; for (var k = 0; k < criteriaValues.length; k++) { if (eval(criteriaValues[k] + criteria[j][i])) { singleResultIndexes[count++] = k; } } rowResultIndexes[j] = singleResultIndexes; } columnResultIndexes[i - 1] = _.intersection.apply(_, rowResultIndexes); } var resultIndexes = _.union.apply(_, columnResultIndexes); return resultIndexes; }; // Database functions Formula.DAVERAGE = function(database, field, criteria) { // Return error if field is not a number and not a string if (isNaN(field) && (typeof field !== "string")) { return '#VALUE!'; } var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); var targetFields = []; if (typeof field === "string") { var index = Formula.FINDFIELD(database, field); targetFields = _.rest(database[index]); } else { targetFields = _.rest(database[field]); } var sum = 0; for (var i = 0; i < resultIndexes.length; i++) { sum += targetFields[resultIndexes[i]]; } var average = Formula.IF(resultIndexes.length === 0, "#DIV/0!", sum / resultIndexes.length); return average; }; Formula.DCOUNT = function(database, field, criteria) { // Return error if field is not a number and not a string if (isNaN(field) && (typeof field !== "string")) { return '#VALUE!'; } var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); var targetFields = []; if (typeof field === "string") { var index = Formula.FINDFIELD(database, field); targetFields = _.rest(database[index]); } else { targetFields = _.rest(database[field]); } var targetValues = []; for (var i = 0; i < resultIndexes.length; i++) { targetValues[i] = targetFields[resultIndexes[i]]; } return Formula.COUNT(targetValues); }; Formula.DCOUNTA = function(database, field, criteria) { // Return error if field is not a number and not a string if (isNaN(field) && (typeof field !== "string")) { return '#VALUE!'; } var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); var targetFields = []; if (typeof field === "string") { var index = Formula.FINDFIELD(database, field); targetFields = _.rest(database[index]); } else { targetFields = _.rest(database[field]); } var targetValues = []; for (var i = 0; i < resultIndexes.length; i++) { targetValues[i] = targetFields[resultIndexes[i]]; } return Formula.COUNTA(targetValues); }; Formula.DGET = function(database, field, criteria) { // Return error if field is not a number and not a string if (isNaN(field) && (typeof field !== "string")) { return '#VALUE!'; } var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); var targetFields = []; if (typeof field === "string") { var index = Formula.FINDFIELD(database, field); targetFields = _.rest(database[index]); } else { targetFields = _.rest(database[field]); } var targetValues = 0; // Return error if no record meets the criteria if (resultIndexes.length === 0) { return '#VALUE!'; } // Returns the #NUM! error value because more than one record meets the // criteria if (resultIndexes.length > 1) { return '#NUM!'; } return targetFields[resultIndexes[0]]; }; Formula.DMAX = function(database, field, criteria) { // Return error if field is not a number and not a string if (isNaN(field) && (typeof field !== "string")) { return '#VALUE!'; } var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); var targetFields = []; if (typeof field === "string") { var index = Formula.FINDFIELD(database, field); targetFields = _.rest(database[index]); } else { targetFields = _.rest(database[field]); } var maxValue = targetFields[resultIndexes[0]]; for (var i = 1; i < resultIndexes.length; i++) { if (maxValue < targetFields[resultIndexes[i]]) { maxValue = targetFields[resultIndexes[i]]; } } return maxValue; }; Formula.DMIN = function(database, field, criteria) { // Return error if field is not a number and not a string if (isNaN(field) && (typeof field !== "string")) { return '#VALUE!'; } var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); var targetFields = []; if (typeof field === "string") { var index = Formula.FINDFIELD(database, field); targetFields = _.rest(database[index]); } else { targetFields = _.rest(database[field]); } var minValue = targetFields[resultIndexes[0]]; for (var i = 1; i < resultIndexes.length; i++) { if (minValue > targetFields[resultIndexes[i]]) { minValue = targetFields[resultIndexes[i]]; } } return minValue; }; Formula.DPRODUCT = function(database, field, criteria) { // Return error if field is not a number and not a string if (isNaN(field) && (typeof field !== "string")) { return '#VALUE!'; } var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); var targetFields = []; if (typeof field === "string") { var index = Formula.FINDFIELD(database, field); targetFields = _.rest(database[index]); } else { targetFields = _.rest(database[field]); } var targetValues = []; for (var i = 0; i < resultIndexes.length; i++) { targetValues[i] = targetFields[resultIndexes[i]]; } targetValues = _.compact(targetValues); var result = 1; for (i = 0; i < targetValues.length; i++) { result *= targetValues[i]; } return result; }; Formula.DSTDEV = function(database, field, criteria) { // Return error if field is not a number and not a string if (isNaN(field) && (typeof field !== "string")) { return '#VALUE!'; } var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); var targetFields = []; if (typeof field === "string") { var index = Formula.FINDFIELD(database, field); targetFields = _.rest(database[index]); } else { targetFields = _.rest(database[field]); } var targetValues = []; for (var i = 0; i < resultIndexes.length; i++) { targetValues[i] = targetFields[resultIndexes[i]]; } targetValues = _.compact(targetValues); return Formula.STDEVS(targetValues); }; Formula.DSTDEVP = function(database, field, criteria) { // Return error if field is not a number and not a string if (isNaN(field) && (typeof field !== "string")) { return '#VALUE!'; } var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); var targetFields = []; if (typeof field === "string") { var index = Formula.FINDFIELD(database, field); targetFields = _.rest(database[index]); } else { targetFields = _.rest(database[field]); } var targetValues = []; for (var i = 0; i < resultIndexes.length; i++) { targetValues[i] = targetFields[resultIndexes[i]]; } targetValues = _.compact(targetValues); return Formula.STDEVP(targetValues); }; Formula.DSUM = function(database, field, criteria) { // Return error if field is not a number and not a string if (isNaN(field) && (typeof field !== "string")) { return '#VALUE!'; } var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); var targetFields = []; if (typeof field === "string") { var index = Formula.FINDFIELD(database, field); targetFields = _.rest(database[index]); } else { targetFields = _.rest(database[field]); } var targetValues = []; for (var i = 0; i < resultIndexes.length; i++) { targetValues[i] = targetFields[resultIndexes[i]]; } return Formula.SUM(targetValues); }; Formula.DVAR = function(database, field, criteria) { // Return error if field is not a number and not a string if (isNaN(field) && (typeof field !== "string")) { return '#VALUE!'; } var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); var targetFields = []; if (typeof field === "string") { var index = Formula.FINDFIELD(database, field); targetFields = _.rest(database[index]); } else { targetFields = _.rest(database[field]); } var targetValues = []; for (var i = 0; i < resultIndexes.length; i++) { targetValues[i] = targetFields[resultIndexes[i]]; } return Formula.VARS(targetValues); }; Formula.DVARP = function(database, field, criteria) { // Return error if field is not a number and not a string if (isNaN(field) && (typeof field !== "string")) { return '#VALUE!'; } var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); var targetFields = []; if (typeof field === "string") { var index = Formula.FINDFIELD(database, field); targetFields = _.rest(database[index]); } else { targetFields = _.rest(database[field]); } var targetValues = []; for (var i = 0; i < resultIndexes.length; i++) { targetValues[i] = targetFields[resultIndexes[i]]; } return Formula.VARP(targetValues); }; Formula.GETJSON = function (file) { var request = new XMLHttpRequest(); request.open('GET', file, false); request.send(null); if (request.status === 200) { return JSON.parse(request.responseText); } }; // Date functions Formula.DATE = function (year, month, day) { return new Date(year, month - 1, day); }; Formula.DATEVALUE = function (date_text) { return Math.ceil((moment(date_text) - moment('1900-1-1')) / 86400000) + 2; }; Formula.DAY = function (date) { return moment(new Date(date)).date(); }; Formula.DAYS = function (end_date, start_date) { return moment(new Date(end_date)).diff(moment(new Date(start_date)), 'days'); }; Formula.DAYS360 = function (start_date, end_date, method) { var start = moment(new Date(start_date)); var end = moment(new Date(end_date)); var smd = 31; var emd = 31; var sd = start.date(); var ed = end.date(); if (method) { sd = (sd === 31) ? 30 : sd; ed = (ed === 31) ? 30 : ed; } else { if (start.month() === 1) { smd = start.daysInMonth(); } if (end.month() === 1) { emd = end.daysInMonth(); } sd = (sd === smd) ? 30 : sd; if (sd === 30 || sd === smd) { ed = (ed === emd) ? 30 : ed; } } return 360 * (end.year() - start.year()) + 30 * (end.month() - start.month()) + (ed - sd); }; Formula.EDATE = function (start_date, months) { return moment(new Date(start_date)).add('months', months).toDate(); }; Formula.EOMONTH = function (start_date, months) { var edate = moment(new Date(start_date)).add('months', months); return new Date(edate.year(), edate.month(), edate.daysInMonth()); }; Formula.FROMNOW = function (timestamp, nosuffix) { return moment(new Date(timestamp)).fromNow(nosuffix); }; Formula.HOUR = function (timestamp) { return (timestamp <= 1) ? Math.floor(24 * timestamp) : moment(new Date(timestamp)).hours(); }; Formula.MINUTE = function (timestamp) { return (timestamp <= 1) ? Math.floor(24 * 60 * timestamp) - 60 * Math.floor(24 * timestamp) : moment(new Date(timestamp)).minutes(); }; Formula.ISOWEEKNUM = function (date) { return moment(new Date(date)).format('w'); }; Formula.MONTH = function (timestamp) { return moment(new Date(timestamp)).month() + 1; }; Formula.NETWORKDAYS = function (start_date, end_date, holidays) { return Formula.NETWORKDAYSINTL(start_date, end_date, 1, holidays); }; Formula.NETWORKDAYSINTL = function (start_date, end_date, weekend, holidays) { var weekend_type = (typeof weekend === 'undefined') ? 1 : weekend; var weekend_days = WEEKEND_TYPES[weekend_type]; var sd = moment(start_date); var ed = moment(end_date); var net_days = ed.diff(sd, 'days') + 1; var net_work_days = net_days; var cd = sd; var holiday_dates = []; if (typeof holidays !== 'undefined') { for (var i = 0; i < holidays.length; i++) { holiday_dates[i] = moment(new Date(holidays[i])).format('MM-DD-YYYY'); } } if (!weekend_days.length && !holiday_dates.length) { // No need to loop here. return net_work_days; } var j = 0; while (j < net_days) { if (weekend_days.indexOf(parseInt(cd.format('d'), 10)) >= 0) { net_work_days--; } else if (holiday_dates.indexOf(cd.format('MM-DD-YYYY')) >= 0) { net_work_days--; } cd = cd.add('days', 1); j++; } return net_work_days; }; Formula.NOW = function () { return new Date(); }; Formula.SECOND = function (timestamp) { return moment(new Date(timestamp)).seconds(); }; Formula.TIME = function (hour, minute, second) { return (3600 * hour + 60 * minute + second) / 86400; }; Formula.TIMEVALUE = function (time_text) { var timestamp = moment(new Date(time_text)); return (3600 * timestamp.hours() + 60 * timestamp.minutes() + timestamp.seconds()) / 86400; }; Formula.TODAY = function () { return new Date(); }; Formula.WEEKDAY = function (date, type) { var week_day = moment(new Date(date)).format('d'); var week_type = (typeof type === 'undefined') ? 1 : type; return WEEK_TYPES[week_type][week_day]; }; Formula.WEEKNUM = function (date, type) { var current_date = moment(new Date(date)); var january_first = moment(new Date(current_date.year(), 0, 1)); var week_type = (typeof type === 'undefined') ? 1 : type; var week_start = WEEK_STARTS[week_type]; var first_day = january_first.format('d'); var offset = (first_day < week_start) ? week_start - first_day + 1 : first_day - week_start; if (week_type === 21) { return Formula.ISOWEEKNUM(date); } else { return Math.floor(current_date.diff(january_first.subtract('days', offset), 'days') / 7) + 1; } }; Formula.WORKDAY = function (start_date, days, holidays) { return Formula.WORKDAYINTL(start_date, days, 1, holidays); }; Formula.WORKDAYINTL = function (start_date, days, weekend, holidays) { var weekend_type = (typeof weekend === 'undefined') ? 1 : weekend; var weekend_days = WEEKEND_TYPES[weekend_type]; var sd = moment(new Date(start_date)); var cd = sd; var day_of_week = ''; var holiday_dates = []; if (typeof holidays !== 'undefined') { for (var i = 0; i < holidays.length; i++) { holiday_dates[i] = moment(new Date(holidays[i])).format('MM-DD-YYYY'); } } var j = 0; while (j < days) { cd = cd.add('days', 1); day_of_week = cd.format('d'); if (weekend_days.indexOf(parseInt(day_of_week, 10)) < 0 && holiday_dates.indexOf(cd.format('MM-DD-YYYY')) < 0) { j++; } } return cd.toDate(); }; Formula.YEAR = function (date) { return moment(new Date(date)).year(); }; Formula.YEARFRAC = function (start_date, end_date, basis) { // Credits: David A. Wheeler [http://www.dwheeler.com/] // Initialize parameters basis = (typeof basis === 'undefined') ? 0 : basis; var sdate = moment(new Date(start_date)); var edate = moment(new Date(end_date)); // Return error if either date is invalid if (!sdate.isValid() || !edate.isValid()) { return '#VALUE!'; } // Return error if basis is neither 0, 1, 2, 3, or 4 if ([0, 1, 2, 3, 4].indexOf(basis) === -1) { return '#NUM!'; } // Return zero if start_date and end_date are the same if (sdate === edate) { return 0; } // Swap dates if start_date is later than end_date if (sdate.diff(edate) > 0) { edate = moment(new Date(start_date)); sdate = moment(new Date(end_date)); } // Lookup years, months, and days var syear = sdate.year(); var smonth = sdate.month(); var sday = sdate.date(); var eyear = edate.year(); var emonth = edate.month(); var eday = edate.date(); switch (basis) { case 0: // US (NASD) 30/360 // Note: if eday == 31, it stays 31 if sday < 30 if (sday === 31 && eday === 31) { sday = 30; eday = 30; } else if (sday === 31) { sday = 30; } else if (sday === 30 && eday === 31) { eday = 30; } else if (smonth === 1 && emonth === 1 && sdate.daysInMonth() === sday && edate.daysInMonth() === eday) { sday = 30; eday = 30; } else if (smonth === 1 && sdate.daysInMonth() === sday) { sday = 30; } return ((eday + emonth * 30 + eyear * 360) - (sday + smonth * 30 + syear * 360)) / 360; case 1: // Actual/actual var feb29Between = function (date1, date2) { // Requires year2 == (year1 + 1) or year2 == year1 // Returns TRUE if February 29 is between the two dates (date1 may be February 29), with two possibilities: // year1 is a leap year and date1 <= Februay 29 of year1 // year2 is a leap year and date2 > Februay 29 of year2 var mar1year1 = moment(new Date(date1.year(), 2, 1)); if (moment([date1.year()]).isLeapYear() && date1.diff(mar1year1) < 0 && date2.diff(mar1year1) >= 0) { return true; } var mar1year2 = moment(new Date(date2.year(), 2, 1)); if (moment([date2.year()]).isLeapYear() && date2.diff(mar1year2) >= 0 && date1.diff(mar1year2) < 0) { return true; } return false; }; var ylength = 365; if (syear === eyear || ((syear + 1) === eyear) && ((smonth > emonth) || ((smonth === emonth) && (sday >= eday)))) { if (syear === eyear && moment([syear]).isLeapYear()) { ylength = 366; } else if (feb29Between(sdate, edate) || (emonth === 1 && eday === 29)) { ylength = 366; } return edate.diff(sdate, 'days') / ylength; } else { var years = (eyear - syear) + 1; var days = moment(new Date(eyear + 1, 0, 1)).diff(moment(new Date(syear, 0, 1)), 'days'); var average = days / years; return edate.diff(sdate, 'days') / average; } break; case 2: // Actual/360 return edate.diff(sdate, 'days') / 360; case 3: // Actual/365 return edate.diff(sdate, 'days') / 365; case 4: // European 30/360 if (sday === 31) { sday = 30; } if (eday === 31) { eday = 30; } // Remarkably, do NOT change February 28 or February 29 at ALL return ((eday + emonth * 30 + eyear * 360) - (sday + smonth * 30 + syear * 360)) / 360; } }; // Engineering functions Formula.BESSELI = function () { return; }; Formula.BESSELJ = function () { return; }; Formula.BESSELK = function () { return; }; Formula.BESSELY = function () { return; }; Formula.VALIDBIN = function (number) { return (/^[01]{1,10}$/).test(number); }; Formula.BIN2DEC = function (number) { // Return error if number is not binary or contains more than 10 characters (10 digits) if (!Formula.VALIDBIN(number)) { return '#NUM!'; } // Convert binary number to decimal var result = parseInt(number, 2); // Handle negative numbers var stringified = number.toString(); if (stringified.length === 10 && stringified.substring(0, 1) === '1') { return parseInt(stringified.substring(1), 2) - 512; } else { return result; } }; Formula.BIN2HEX = function (number, places) { // Return error if number is not binary or contains more than 10 characters (10 digits) if (!Formula.VALIDBIN(number)) { return '#NUM!'; } // Ignore places and return a 10-character hexadecimal number if number is negative var stringified = number.toString(); if (stringified.length === 10 && stringified.substring(0, 1) === '1') { return (1099511627264 + parseInt(stringified.substring(1), 2)).toString(16); } // Convert binary number to hexadecimal var result = parseInt(number, 2).toString(16); // Return hexadecimal number using the minimum number of characters necessary if places is undefined if (typeof places === 'undefined') { return result; } else { // Return error if places is nonnumeric if (isNaN(places)) { return '#VALUE!'; } // Return error if places is negative if (places < 0) { return '#NUM!'; } // Truncate places in case it is not an integer places = Math.floor(places); // Pad return value with leading 0s (zeros) if necessary (using Underscore.string) return (places >= result.length) ? _s.repeat('0', places - result.length) + result : '#NUM!'; } }; Formula.BIN2OCT = function (number, places) { // Return error if number is not binary or contains more than 10 characters (10 digits) if (!Formula.VALIDBIN(number)) { return '#NUM!'; } // Ignore places and return a 10-character octal number if number is negative var stringified = number.toString(); if (stringified.length === 10 && stringified.substring(0, 1) === '1') { return (1073741312 + parseInt(stringified.substring(1), 2)).toString(8); } // Convert binary number to octal var result = parseInt(number, 2).toString(8); // Return octal number using the minimum number of characters necessary if places is undefined if (typeof places === 'undefined') { return result; } else { // Return error if places is nonnumeric if (isNaN(places)) { return '#VALUE!'; } // Return error if places is negative if (places < 0) { return '#NUM!'; } // Truncate places in case it is not an integer places = Math.floor(places); // Pad return value with leading 0s (zeros) if necessary (using Underscore.string) return (places >= result.length) ? _s.repeat('0', places - result.length) + result : '#NUM!'; } }; Formula.BITAND = function (number1, number2) { // Return error if either number is a non-numeric value if (isNaN(number1) || isNaN(number2)) { return '#VALUE!'; } // Return error if either number is less than 0 if (number1 < 0 || number2 < 0) { return '#NUM!'; } // Return error if either number is a non-integer if (Math.floor(number1) !== number1 || Math.floor(number2) !== number2) { return '#NUM!'; } // Return error if either number is greater than (2^48)-1 if (number1 > 281474976710655 || number2 > 281474976710655) { return '#NUM!'; } // Return bitwise AND of two numbers return number1 & number2; }; Formula.BITLSHIFT = function (number, shift) { // Return error if either number is a non-numeric value if (isNaN(number) || isNaN(shift)) { return '#VALUE!'; } // Return error if number is less than 0 if (number < 0) { return '#NUM!'; } // Return error if number is a non-integer if (Math.floor(number) !== number) { return '#NUM!'; } // Return error if number is greater than (2^48)-1 if (number > 281474976710655) { return '#NUM!'; } // Return error if the absolute value of shift is greater than 53 if (Math.abs(shift) > 53) { return '#NUM!'; } // Return number shifted by shift bits to the left or to the right if shift is negative return (shift >= 0 ) ? number << shift : number >> -shift; }; Formula.BITOR = function (number1, number2) { // Return error if either number is a non-numeric value if (isNaN(number1) || isNaN(number2)) { return '#VALUE!'; } // Return error if either number is less than 0 if (number1 < 0 || number2 < 0) { return '#NUM!'; } // Return error if either number is a non-integer if (Math.floor(number1) !== number1 || Math.floor(number2) !== number2) { return '#NUM!'; } // Return error if either number is greater than (2^48)-1 if (number1 > 281474976710655 || number2 > 281474976710655) { return '#NUM!'; } // Return bitwise OR of two numbers return number1 | number2; }; Formula.BITRSHIFT = function (number, shift) { // Return error if either number is a non-numeric value if (isNaN(number) || isNaN(shift)) { return '#VALUE!'; } // Return error if number is less than 0 if (number < 0) { return '#NUM!'; } // Return error if number is a non-integer if (Math.floor(number) !== number) { return '#NUM!'; } // Return error if number is greater than (2^48)-1 if (number > 281474976710655) { return '#NUM!'; } // Return error if the absolute value of shift is greater than 53 if (Math.abs(shift) > 53) { return '#NUM!'; } // Return number shifted by shift bits to the right or to the left if shift is negative return (shift >= 0 ) ? number >> shift : number << -shift; }; Formula.BITXOR = function (number1, number2) { // Return error if either number is a non-numeric value if (isNaN(number1) || isNaN(number2)) { return '#VALUE!'; } // Return error if either number is less than 0 if (number1 < 0 || number2 < 0) { return '#NUM!'; } // Return error if either number is a non-integer if (Math.floor(number1) !== number1 || Math.floor(number2) !== number2) { return '#NUM!'; } // Return error if either number is greater than (2^48)-1 if (number1 > 281474976710655 || number2 > 281474976710655) { return '#NUM!'; } // Return bitwise XOR of two numbers return number1 ^ number2; }; Formula.COMPLEX = function (real, imaginary, suffix) { // Return error if either number is a non-numeric value if (isNaN(real) || isNaN(imaginary)) { return '#VALUE!'; } // Set suffix suffix = (typeof suffix === 'undefined') ? 'i' : suffix; // Return error if suffix is neither "i" nor "j" if (suffix !== 'i' && suffix !== 'j') { return '#VALUE!'; } // Return complex number if (real === 0 && imaginary === 0) { return 0; } else if (real === 0) { return (imaginary === 1) ? suffix : imaginary.toString() + suffix; } else if (imaginary === 0) { return real.toString(); } else { var sign = (imaginary > 0) ? '+' : ''; return real.toString() + sign + ((imaginary === 1) ? suffix : imaginary.toString() + suffix); } }; Formula.CONVERT = function (number, from_unit, to_unit) { // Return error if number is a non-numeric value if (isNaN(number)) { return '#VALUE!'; } // List of units supported by CONVERT and units defined by the International System of Units // [Name, Symbol, Alternate symbols, Quantity, ISU, CONVERT, Conversion ratio] var units = [ ["a.u. of action", "?", null, "action", false, false, 1.05457168181818e-34], ["a.u. of charge", "e", null, "electric_charge", false, false, 1.60217653141414e-19], ["a.u. of energy", "Eh", null, "energy", false, false, 4.35974417757576e-18], ["a.u. of length", "a?", null, "length", false, false, 5.29177210818182e-11], ["a.u. of mass", "m?", null, "mass", false, false, 9.10938261616162e-31], ["a.u. of time", "?/Eh", null, "time", false, false, 2.41888432650516e-17], ["admiralty knot", "admkn", null, "speed", false, true, 0.514773333], ["ampere", "A", null, "electric_current", true, false, 1], ["ampere per meter", "A/m", null, "magnetic_field_intensity", true, false, 1], ["ångström", "Å", ["ang"], "length", false, true, 1e-10], ["are", "ar", null, "area", false, true, 100], ["astronomical unit", "ua", null, "length", false, false, 1.49597870691667e-11], ["bar", "bar", null, "pressure", false, false, 100000], ["barn", "b", null, "area", false, false, 1e-28], ["becquerel", "Bq", null, "radioactivity", true, false, 1], ["bit", "bit", ["b"], "information", false, true, 1], ["btu", "BTU", ["btu"], "energy", false, true, 1055.05585262], ["byte", "byte", null, "information", false, true, 8], ["candela", "cd", null, "luminous_intensity", true, false, 1], ["candela per square metre", "cd/m?", null, "luminance", true, false, 1], ["coulomb", "C", null, "electric_charge", true, false, 1], ["cubic ångström", "ang3", ["ang^3"], "volume", false, true, 1e-30], ["cubic foot", "ft3", ["ft^3"], "volume", false, true, 0.028316846592], ["cubic inch", "in3", ["in^3"], "volume", false, true, 0.000016387064], ["cubic light-year", "ly3", ["ly^3"], "volume", false, true, 8.46786664623715e-47], ["cubic metre", "m?", null, "volume", true, true, 1], ["cubic mile", "mi3", ["mi^3"], "volume", false, true, 4168181825.44058], ["cubic nautical mile", "Nmi3", ["Nmi^3"], "volume", false, true, 6352182208], ["cubic Pica", "Pica3", ["Picapt3", "Pica^3", "Picapt^3"], "volume", false, true, 7.58660370370369e-8], ["cubic yard", "yd3", ["yd^3"], "volume", false, true, 0.764554857984], ["cup", "cup", null, "volume", false, true, 0.0002365882365], ["dalton", "Da", ["u"], "mass", false, false, 1.66053886282828e-27], ["day", "d", ["day"], "time", false, true, 86400], ["degree", "°", null, "angle", false, false, 0.0174532925199433], ["degrees Rankine", "Rank", null, "temperature", false, true, 0.555555555555556], ["dyne", "dyn", ["dy"], "force", false, true, 0.00001], ["electronvolt", "eV", ["ev"], "energy", false, true, 1.60217656514141], ["ell", "ell", null, "length", false, true, 1.143], ["erg", "erg", ["e"], "energy", false, true, 1e-7], ["farad", "F", null, "electric_capacitance", true, false, 1], ["fluid ounce", "oz", null, "volume", false, true, 0.0000295735295625], ["foot", "ft", null, "length", false, true, 0.3048], ["foot-pound", "flb", null, "energy", false, true, 1.3558179483314], ["gal", "Gal", null, "acceleration", false, false, 0.01], ["gallon", "gal", null, "volume", false, true, 0.003785411784], ["gauss", "G", ["ga"], "magnetic_flux_density", false, true, 1], ["grain", "grain", null, "mass", false, true, 0.0000647989], ["gram", "g", null, "mass", false, true, 0.001], ["gray", "Gy", null, "absorbed_dose", true, false, 1], ["gross registered ton", "GRT", ["regton"], "volume", false, true, 2.8316846592], ["hectare", "ha", null, "area", false, true, 10000], ["henry", "H", null, "inductance", true, false, 1], ["hertz", "Hz", null, "frequency", true, false, 1], ["horsepower", "HP", ["h"], "power", false, true, 745.69987158227], ["horsepower-hour", "HPh", ["hh", "hph"], "energy", false, true, 2684519.538], ["hour", "h", ["hr"], "time", false, true, 3600], ["imperial gallon (U.K.)", "uk_gal", null, "volume", false, true, 0.00454609], ["imperial hundredweight", "lcwt", ["uk_cwt", "hweight"], "mass", false, true, 50.802345], ["imperial quart (U.K)", "uk_qt", null, "volume", false, true, 0.0011365225], ["imperial ton", "brton", ["uk_ton", "LTON"], "mass", false, true, 1016.046909], ["inch", "in", null, "length", false, true, 0.0254], ["international acre", "uk_acre", null, "area", false, true, 4046.8564224], ["IT calorie", "cal", null, "energy", false, true, 4.1868], ["joule", "J", null, "energy", true, true, 1], ["katal", "kat", null, "catalytic_activity", true, false, 1], ["kelvin", "K", ["kel"], "temperature", true, true, 1], ["kilogram", "kg", null, "mass", true, true, 1], ["knot", "kn", null, "speed", false, true, 0.514444444444444], ["light-year", "ly", null, "length", false, true, 9460730472580800], ["litre", "L", ["l", "lt"], "volume", false, true, 0.001], ["lumen", "lm", null, "luminous_flux", true, false, 1], ["lux", "lx", null, "illuminance", true, false, 1], ["maxwell", "Mx", null, "magnetic_flux", false, false, 1e-18], ["measurement ton", "MTON", null, "volume", false, true, 1.13267386368], ["meter per hour", "m/h", ["m/hr"], "speed", false, true, 0.00027777777777778], ["meter per second", "m/s", ["m/sec"], "speed", true, true, 1], ["meter per second squared", "m?s??", null, "acceleration", true, false, 1], ["parsec", "pc", ["parsec"], "length", false, true, 30856775814671900], ["meter squared per second", "m?/s", null, "kinematic_viscosity", true, false, 1], ["metre", "m", null, "length", true, true, 1], ["miles per hour", "mph", null, "speed", false, true, 0.44704], ["millimetre of mercury", "mmHg", null, "pressure", false, false, 133.322], ["minute", "?", null, "angle", false, false, 0.000290888208665722], ["minute", "min", ["mn"], "time", false, true, 60], ["modern teaspoon", "tspm", null, "volume", false, true, 0.000005], ["mole", "mol", null, "amount_of_substance", true, false, 1], ["morgen", "Morgen", null, "area", false, true, 2500], ["n.u. of action", "?", null, "action", false, false, 1.05457168181818e-34], ["n.u. of mass", "m?", null, "mass", false, false, 9.10938261616162e-31], ["n.u. of speed", "c?", null, "speed", false, false, 299792458], ["n.u. of time", "?/(me?c??)", null, "time", false, false, 1.28808866778687e-21], ["nautical mile", "M", ["Nmi"], "length", false, true, 1852], ["newton", "N", null, "force", true, true, 1], ["œrsted", "Oe ", null, "magnetic_field_intensity", false, false, 79.5774715459477], ["ohm", "Ω", null, "electric_resistance", true, false, 1], ["ounce mass", "ozm", null, "mass", false, true, 0.028349523125], ["pascal", "Pa", null, "pressure", true, false, 1], ["pascal second", "Pa?s", null, "dynamic_viscosity", true, false, 1], ["pferdestärke", "PS", null, "power", false, true, 735.49875], ["phot", "ph", null, "illuminance", false, false, 0.0001], ["pica (1/6 inch)", "pica", null, "length", false, true, 0.00035277777777778], ["pica (1/72 inch)", "Pica", ["Picapt"], "length", false, true, 0.00423333333333333], ["poise", "P", null, "dynamic_viscosity", false, false, 0.1], ["pond", "pond", null, "force", false, true, 0.00980665], ["pound force", "lbf", null, "force", false, true, 4.4482216152605], ["pound mass", "lbm", null, "mass", false, true, 0.45359237], ["quart", "qt", null, "volume", false, true, 0.000946352946], ["radian", "rad", null, "angle", true, false, 1], ["second", "?", null, "angle", false, false, 0.00000484813681109536], ["second", "s", ["sec"], "time", true, true, 1], ["short hundredweight", "cwt", ["shweight"], "mass", false, true, 45.359237], ["siemens", "S", null, "electrical_conductance", true, false, 1], ["sievert", "Sv", null, "equivalent_dose", true, false, 1], ["slug", "sg", null, "mass", false, true, 14.59390294], ["square ångström", "ang2", ["ang^2"], "area", false, true, 1e-20], ["square foot", "ft2", ["ft^2"], "area", false, true, 0.09290304], ["square inch", "in2", ["in^2"], "area", false, true, 0.00064516], ["square light-year", "ly2", ["ly^2"], "area", false, true, 8.95054210748189e+31], ["square meter", "m?", null, "area", true, true, 1], ["square mile", "mi2", ["mi^2"], "area", false, true, 2589988.110336], ["square nautical mile", "Nmi2", ["Nmi^2"], "area", false, true, 3429904], ["square Pica", "Pica2", ["Picapt2", "Pica^2", "Picapt^2"], "area", false, true, 0.00001792111111111], ["square yard", "yd2", ["yd^2"], "area", false, true, 0.83612736], ["statute mile", "mi", null, "length", false, true, 1609.344], ["steradian", "sr", null, "solid_angle", true, false, 1], ["stilb", "sb", null, "luminance", false, false, 0.0001], ["stokes", "St", null, "kinematic_viscosity", false, false, 0.0001], ["stone", "stone", null, "mass", false, true, 6.35029318], ["tablespoon", "tbs", null, "volume", false, true, 0.0000147868], ["teaspoon", "tsp", null, "volume", false, true, 0.00000492892], ["tesla", "T", null, "magnetic_flux_density", true, true, 1], ["thermodynamic calorie", "c", null, "energy", false, true, 4.184], ["ton", "ton", null, "mass", false, true, 907.18474], ["tonne", "t", null, "mass", false, false, 1000], ["U.K. pint", "uk_pt", null, "volume", false, true, 0.00056826125], ["U.S. bushel", "bushel", null, "volume", false, true, 0.03523907], ["U.S. oil barrel", "barrel", null, "volume", false, true, 0.158987295], ["U.S. pint", "pt", ["us_pt"], "volume", false, true, 0.000473176473], ["U.S. survey mile", "survey_mi", null, "length", false, true, 1609.347219], ["U.S. survey/statute acre", "us_acre", null, "area", false, true, 4046.87261], ["volt", "V", null, "voltage", true, false, 1], ["watt", "W", null, "power", true, true, 1], ["watt-hour", "Wh", ["wh"], "energy", false, true, 3600], ["weber", "Wb", null, "magnetic_flux", true, false, 1], ["yard", "yd", null, "length", false, true, 0.9144], ["year", "yr", null, "time", false, true, 31557600] ]; // Binary prefixes // [Name, Prefix power of 2 value, Previx value, Abbreviation, Derived from] var binary_prefixes = { Yi: ["yobi", 80, 1208925819614629174706176, "Yi", "yotta"], Zi: ["zebi", 70, 1180591620717411303424, "Zi", "zetta"], Ei: ["exbi", 60, 1152921504606846976, "Ei", "exa"], Pi: ["pebi", 50, 1125899906842624, "Pi", "peta"], Ti: ["tebi", 40, 1099511627776, "Ti", "tera"], Gi: ["gibi", 30, 1073741824, "Gi", "giga"], Mi: ["mebi", 20, 1048576, "Mi", "mega"], ki: ["kibi", 10, 1024, "ki", "kilo"] }; // Unit prefixes // [Name, Multiplier, Abbreviation] var unit_prefixes = { Y: ["yotta", 1e+24, "Y"], Z: ["zetta", 1e+21, "Z"], E: ["exa", 1e+18, "E"], P: ["peta", 1e+15, "P"], T: ["tera", 1e+12, "T"], G: ["giga", 1e+09, "G"], M: ["mega", 1e+06, "M"], k: ["kilo", 1e+03, "k"], h: ["hecto", 1e+02, "h"], e: ["dekao", 1e+01, "e"], d: ["deci", 1e-01, "d"], c: ["centi", 1e-02, "c"], m: ["milli", 1e-03, "m"], u: ["micro", 1e-06, "u"], n: ["nano", 1e-09, "n"], p: ["pico", 1e-12, "p"], f: ["femto", 1e-15, "f"], a: ["atto", 1e-18, "a"], z: ["zepto", 1e-21, "z"], y: ["yocto", 1e-24, "y"] }; // Initialize units and multipliers var from = null; var to = null; var base_from_unit = from_unit; var base_to_unit = to_unit; var from_multiplier = 1; var to_multiplier = 1; var alt; // Lookup from and to units for (var i = 0; i < units.length; i++) { alt = (units[i][2] === null) ? [] : units[i][2]; if (units[i][1] === base_from_unit || alt.indexOf(base_from_unit) >= 0) { from = units[i]; } if (units[i][1] === base_to_unit || alt.indexOf(base_to_unit) >= 0) { to = units[i]; } } // Lookup from prefix if (from === null) { var from_binary_prefix = binary_prefixes[from_unit.substring(0, 2)]; var from_unit_prefix = unit_prefixes[from_unit.substring(0, 1)]; // Handle dekao unit prefix (only unit prefix with two characters) if (from_unit.substring(0, 2) === 'da') { from_unit_prefix = ["dekao", 1e+01, "da"]; } // Handle binary prefixes first (so that 'Yi' is processed before 'Y') if (from_binary_prefix) { from_multiplier = from_binary_prefix[2]; base_from_unit = from_unit.substring(2); } else if (from_unit_prefix) { from_multiplier = from_unit_prefix[1]; base_from_unit = from_unit.substring(from_unit_prefix[2].length); } // Lookup from unit for (var j = 0; j < units.length; j++) { alt = (units[j][2] === null) ? [] : units[j][2]; if (units[j][1] === base_from_unit || alt.indexOf(base_from_unit) >= 0) { from = units[j]; } } } // Lookup to prefix if (to === null) { var to_binary_prefix = binary_prefixes[to_unit.substring(0, 2)]; var to_unit_prefix = unit_prefixes[to_unit.substring(0, 1)]; // Handle dekao unit prefix (only unit prefix with two characters) if (to_unit.substring(0, 2) === 'da') { to_unit_prefix = ["dekao", 1e+01, "da"]; } // Handle binary prefixes first (so that 'Yi' is processed before 'Y') if (to_binary_prefix) { to_multiplier = to_binary_prefix[2]; base_to_unit = to_unit.substring(2); } else if (to_unit_prefix) { to_multiplier = to_unit_prefix[1]; base_to_unit = to_unit.substring(to_unit_prefix[2].length); } // Lookup to unit for (var k = 0; k < units.length; k++) { alt = (units[k][2] === null) ? [] : units[k][2]; if (units[k][1] === base_to_unit || alt.indexOf(base_to_unit) >= 0) { to = units[k]; } } } // Return error if a unit does not exist if (from === null || to === null) { return '#N/A'; } // Return error if units represent different quantities if (from[3] !== to[3]) { return '#N/A'; } // Return converted number return number * from[6] * from_multiplier / (to[6] * to_multiplier); }; Formula.DEC2BIN = function (number, places) { // Return error if number is not a number if (isNaN(number)) { return '#VALUE!'; } // Return error if number is not decimal, is lower than -512, or is greater than 511 if (!/^-?[0-9]{1,3}$/.test(number) || number < -512 || number > 511) { return '#NUM!'; } // Ignore places and return a 10-character binary number if number is negative if (number < 0) { return '1' + _s.repeat('0', 9 - (512 + number).toString(2).length) + (512 + number).toString(2); } // Convert decimal number to binary var result = parseInt(number, 10).toString(2); // Return binary number using the minimum number of characters necessary if places is undefined if (typeof places === 'undefined') { return result; } else { // Return error if places is nonnumeric if (isNaN(places)) { return '#VALUE!'; } // Return error if places is negative if (places < 0) { return '#NUM!'; } // Truncate places in case it is not an integer places = Math.floor(places); // Pad return value with leading 0s (zeros) if necessary (using Underscore.string) return (places >= result.length) ? _s.repeat('0', places - result.length) + result : '#NUM!'; } }; Formula.DEC2HEX = function (number, places) { // Return error if number is not a number if (isNaN(number)) { return '#VALUE!'; } // Return error if number is not decimal, is lower than -549755813888, or is greater than 549755813887 if (!/^-?[0-9]{1,12}$/.test(number) || number < -549755813888 || number > 549755813887) { return '#NUM!'; } // Ignore places and return a 10-character hexadecimal number if number is negative if (number < 0) { return (1099511627776 + number).toString(16); } // Convert decimal number to hexadecimal var result = parseInt(number, 10).toString(16); // Return hexadecimal number using the minimum number of characters necessary if places is undefined if (typeof places === 'undefined') { return result; } else { // Return error if places is nonnumeric if (isNaN(places)) { return '#VALUE!'; } // Return error if places is negative if (places < 0) { return '#NUM!'; } // Truncate places in case it is not an integer places = Math.floor(places); // Pad return value with leading 0s (zeros) if necessary (using Underscore.string) return (places >= result.length) ? _s.repeat('0', places - result.length) + result : '#NUM!'; } }; Formula.DEC2OCT = function (number, places) { // Return error if number is not a number if (isNaN(number)) { return '#VALUE!'; } // Return error if number is not decimal, is lower than -549755813888, or is greater than 549755813887 if (!/^-?[0-9]{1,9}$/.test(number) || number < -536870912 || number > 536870911) { return '#NUM!'; } // Ignore places and return a 10-character octal number if number is negative if (number < 0) { return (1073741824 + number).toString(8); } // Convert decimal number to octal var result = parseInt(number, 10).toString(8); // Return octal number using the minimum number of characters necessary if places is undefined if (typeof places === 'undefined') { return result; } else { // Return error if places is nonnumeric if (isNaN(places)) { return '#VALUE!'; } // Return error if places is negative if (places < 0) { return '#NUM!'; } // Truncate places in case it is not an integer places = Math.floor(places); // Pad return value with leading 0s (zeros) if necessary (using Underscore.string) return (places >= result.length) ? _s.repeat('0', places - result.length) + result : '#NUM!'; } }; Formula.DELTA = function (number1, number2) { // Set number2 to zero if undefined number2 = (typeof number2 === 'undefined') ? 0 : number2; // Return error if either number is not a number if (isNaN(number1) || isNaN(number2)) { return '#VALUE!'; } // Return delta return (number1 === number2) ? 1 : 0; }; Formula.ERF = function (lower_bound, upper_bound) { // Set number2 to zero if undefined upper_bound = (typeof upper_bound === 'undefined') ? 0 : upper_bound; // Return error if either number is not a number if (isNaN(lower_bound) || isNaN(upper_bound)) { return '#VALUE!'; } // Return ERFC using jStat [http://www.jstat.org/] return jStat.erf(lower_bound); }; Formula.ERFC = function (x) { // Return error if x is not a number if (isNaN(x)) { return '#VALUE!'; } // Return ERFC using jStat [http://www.jstat.org/] return jStat.erfc(x); }; Formula.ERFCPRECISE = function () { return; }; Formula.ERFPRECISE = function () { return; }; Formula.GESTEP = function (number, step) { // Set step to zero if undefined step = (typeof step === 'undefined') ? 0 : step; // Return error if either number is not a number if (isNaN(number) || isNaN(step)) { return '#VALUE!'; } // Return delta return (number >= step) ? 1 : 0; }; Formula.HEX2BIN = function (number, places) { // Return error if number is not hexadecimal or contains more than ten characters (10 digits) if (!/^[0-9A-Fa-f]{1,10}$/.test(number)) { return '#NUM!'; } // Check if number is negative var negative = (number.length === 10 && number.substring(0, 1).toLowerCase() === 'f') ? true : false; // Convert hexadecimal number to decimal var decimal = (negative) ? parseInt(number, 16) - 1099511627776 : parseInt(number, 16); // Return error if number is lower than -512 or greater than 511 if (decimal < -512 || decimal > 511) { return '#NUM!'; } // Ignore places and return a 10-character binary number if number is negative if (negative) { return '1' + _s.repeat('0', 9 - (512 + decimal).toString(2).length) + (512 + decimal).toString(2); } // Convert decimal number to binary var result = decimal.toString(2); // Return binary number using the minimum number of characters necessary if places is undefined if (typeof places === 'undefined') { return result; } else { // Return error if places is nonnumeric if (isNaN(places)) { return '#VALUE!'; } // Return error if places is negative if (places < 0) { return '#NUM!'; } // Truncate places in case it is not an integer places = Math.floor(places); // Pad return value with leading 0s (zeros) if necessary (using Underscore.string) return (places >= result.length) ? _s.repeat('0', places - result.length) + result : '#NUM!'; } }; Formula.HEX2DEC = function (number) { // Return error if number is not hexadecimal or contains more than ten characters (10 digits) if (!/^[0-9A-Fa-f]{1,10}$/.test(number)) { return '#NUM!'; } // Convert hexadecimal number to decimal var decimal = parseInt(number, 16); // Return decimal number return (decimal >= 549755813888) ? decimal - 1099511627776 : decimal; }; Formula.HEX2OCT = function (number, places) { // Return error if number is not hexadecimal or contains more than ten characters (10 digits) if (!/^[0-9A-Fa-f]{1,10}$/.test(number)) { return '#NUM!'; } // Convert hexadecimal number to decimal var decimal = parseInt(number, 16); // Return error if number is positive and greater than 0x1fffffff (536870911) if (decimal > 536870911 && decimal < 1098974756864) { return '#NUM!'; } // Ignore places and return a 10-character octal number if number is negative if (decimal >= 1098974756864) { return (decimal - 1098437885952).toString(8); } // Convert decimal number to octal var result = decimal.toString(8); // Return octal number using the minimum number of characters necessary if places is undefined if (typeof places === 'undefined') { return result; } else { // Return error if places is nonnumeric if (isNaN(places)) { return '#VALUE!'; } // Return error if places is negative if (places < 0) { return '#NUM!'; } // Truncate places in case it is not an integer places = Math.floor(places); // Pad return value with leading 0s (zeros) if necessary (using Underscore.string) return (places >= result.length) ? _s.repeat('0', places - result.length) + result : '#NUM!'; } }; Formula.IMABS = function (inumber) { // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Return absolute value of complex number return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)); }; Formula.IMAGINARY = function (inumber) { // Return 0 if inumber is equal to 0 if (inumber === 0 || inumber === '0') { return 0; } // Handle special cases if (['i', 'j'].indexOf(inumber) >= 0) { return 1; } // Normalize imaginary coefficient inumber = inumber.replace('+i', '+1i').replace('-i', '-1i').replace('+j', '+1j').replace('-j', '-1j'); // Lookup sign var plus = inumber.indexOf('+'); var minus = inumber.indexOf('-'); if (plus === 0) { plus = inumber.indexOf('+', 1); } if (minus === 0) { minus = inumber.indexOf('-', 1); } // Lookup imaginary unit var last = inumber.substring(inumber.length - 1, inumber.length); var unit = (last === 'i' || last === 'j'); if (plus >= 0 || minus >= 0) { // Return error if imaginary unit is neither i nor j if (!unit) { return '#NUM!'; } // Return imaginary coefficient of complex number if (plus >= 0) { return (isNaN(inumber.substring(0, plus)) || isNaN(inumber.substring(plus + 1, inumber.length - 1))) ? '#NUM!' : Number(inumber.substring(plus + 1, inumber.length - 1)); } else { return (isNaN(inumber.substring(0, minus)) || isNaN(inumber.substring(minus + 1, inumber.length - 1))) ? '#NUM!' : -Number(inumber.substring(minus + 1, inumber.length - 1)); } } else { if (unit) { return (isNaN(inumber.substring(0, inumber.length - 1))) ? '#NUM!' : inumber.substring(0, inumber.length - 1); } else { return (isNaN(inumber)) ? '#NUM!' : 0; } } }; Formula.IMARGUMENT = function (inumber) { // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Return error if inumber is equal to zero if (x === 0 && y === 0) { return '#DIV/0!'; } // Return PI/2 if x is equal to zero and y is positive if (x === 0 && y > 0) { return Math.PI / 2; } // Return -PI/2 if x is equal to zero and y is negative if (x === 0 && y < 0) { return -Math.PI / 2; } // Return zero if x is negative and y is equal to zero if (y === 0 && x > 0) { return 0; } // Return zero if x is negative and y is equal to zero if (y === 0 && x < 0) { return -Math.PI; } // Return argument of complex number if (x > 0) { return Math.atan(y / x); } else if (x < 0 && y >= 0) { return Math.atan(y / x) + Math.PI; } else { return Math.atan(y / x) - Math.PI; } }; Formula.IMCONJUGATE = function (inumber) { // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Lookup imaginary unit var unit = inumber.substring(inumber.length - 1); unit = (unit === 'i' || unit === 'j') ? unit : 'i'; // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Return conjugate of complex number return (y !== 0) ? Formula.COMPLEX(x, -y, unit) : inumber; }; Formula.IMCOS = function (inumber) { // Return error if inumber is a logical value if (inumber === true || inumber === false) { return '#VALUE!'; } // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Lookup imaginary unit var unit = inumber.substring(inumber.length - 1); unit = (unit === 'i' || unit === 'j') ? unit : 'i'; // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Return cosine of complex number return Formula.COMPLEX(Math.cos(x) * (Math.exp(y) + Math.exp(-y)) / 2, -Math.sin(x) * (Math.exp(y) - Math.exp(-y)) / 2, unit); }; Formula.IMCOSH = function (inumber) { // Return error if inumber is a logical value if (inumber === true || inumber === false) { return '#VALUE!'; } // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Lookup imaginary unit var unit = inumber.substring(inumber.length - 1); unit = (unit === 'i' || unit === 'j') ? unit : 'i'; // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Return hyperbolic cosine of complex number return Formula.COMPLEX(Math.cos(y) * (Math.exp(x) + Math.exp(-x)) / 2, Math.sin(y) * (Math.exp(x) - Math.exp(-x)) / 2, unit); }; Formula.IMCOT = function (inumber) { // Return error if inumber is a logical value if (inumber === true || inumber === false) { return '#VALUE!'; } // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Return cotangent of complex number return Formula.IMDIV(Formula.IMCOS(inumber), Formula.IMSIN(inumber)); }; Formula.IMCSC = function (inumber) { // Return error if inumber is a logical value if (inumber === true || inumber === false) { return '#VALUE!'; } // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Return cosecant of complex number return Formula.IMDIV('1', Formula.IMSIN(inumber)); }; Formula.IMCSCH = function (inumber) { // Return error if inumber is a logical value if (inumber === true || inumber === false) { return '#VALUE!'; } // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Return hyperbolic cosecant of complex number return Formula.IMDIV('1', Formula.IMSINH(inumber)); }; Formula.IMDIV = function (inumber1, inumber2) { // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var a = Formula.IMREAL(inumber1); var b = Formula.IMAGINARY(inumber1); var c = Formula.IMREAL(inumber2); var d = Formula.IMAGINARY(inumber2); // Lookup imaginary unit var unit1 = inumber1.substring(inumber1.length - 1); var unit2 = inumber1.substring(inumber1.length - 1); var unit = 'i'; if (unit1 === 'j') { unit = 'j'; } else if (unit2 === 'j') { unit = 'j'; } // Return error if either coefficient is not a number if (a === '#NUM!' || b === '#NUM!' || c === '#NUM!' || d === '#NUM!') { return '#NUM!'; } // Return error if inumber2 is null if (c === 0 && d === 0) { return '#NUM!'; } // Return exponential of complex number var den = c * c + d * d; return Formula.COMPLEX((a * c + b * d) / den, (b * c - a * d) / den, unit); }; Formula.IMEXP = function (inumber) { // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Lookup imaginary unit var unit = inumber.substring(inumber.length - 1); unit = (unit === 'i' || unit === 'j') ? unit : 'i'; // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Return exponential of complex number var e = Math.exp(x); return Formula.COMPLEX(e * Math.cos(y), e * Math.sin(y), unit); }; Formula.IMLN = function (inumber) { // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Lookup imaginary unit var unit = inumber.substring(inumber.length - 1); unit = (unit === 'i' || unit === 'j') ? unit : 'i'; // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Return exponential of complex number return Formula.COMPLEX(Math.log(Math.sqrt(x * x + y * y)), Math.atan(y / x), unit); }; Formula.IMLOG10 = function (inumber) { // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Lookup imaginary unit var unit = inumber.substring(inumber.length - 1); unit = (unit === 'i' || unit === 'j') ? unit : 'i'; // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Return exponential of complex number return Formula.COMPLEX(Math.log(Math.sqrt(x * x + y * y)) / Math.log(10), Math.atan(y / x) / Math.log(10), unit); }; Formula.IMLOG2 = function (inumber) { // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Lookup imaginary unit var unit = inumber.substring(inumber.length - 1); unit = (unit === 'i' || unit === 'j') ? unit : 'i'; // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Return exponential of complex number return Formula.COMPLEX(Math.log(Math.sqrt(x * x + y * y)) / Math.log(2), Math.atan(y / x) / Math.log(2), unit); }; Formula.IMPOWER = function (inumber, number) { // Return error if number is nonnumeric if (isNaN(number)) { return '#VALUE!'; } // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Lookup imaginary unit var unit = inumber.substring(inumber.length - 1); unit = (unit === 'i' || unit === 'j') ? unit : 'i'; // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Calculate power of modulus var p = Math.pow(Formula.IMABS(inumber), number); // Calculate argument var t = Formula.IMARGUMENT(inumber); // Return exponential of complex number return Formula.COMPLEX(p * Math.cos(number * t), p * Math.sin(number * t), unit); }; Formula.IMPRODUCT = function () { // Initialize result var result = arguments[0]; // Loop on all numbers for (var i = 1; i < arguments.length; i++) { // Lookup coefficients of two complex numbers var a = Formula.IMREAL(result); var b = Formula.IMAGINARY(result); var c = Formula.IMREAL(arguments[i]); var d = Formula.IMAGINARY(arguments[i]); // Return error if either coefficient is not a number if (a === '#NUM!' || b === '#NUM!' || c === '#NUM!' || d === '#NUM!') { return '#NUM!'; } // Complute product of two complex numbers result = Formula.COMPLEX(a * c - b * d, a * d + b * c); } // Return product of complex numbers return result; }; Formula.IMREAL = function (inumber) { // Return 0 if inumber is equal to 0 if (inumber === 0 || inumber === '0') { return 0; } // Handle special cases if (['i', '+i', '1i', '+1i', '-i', '-1i', 'j', '+j', '1j', '+1j', '-j', '-1j'].indexOf(inumber) >= 0) { return 0; } // Lookup sign var plus = inumber.indexOf('+'); var minus = inumber.indexOf('-'); if (plus === 0) { plus = inumber.indexOf('+', 1); } if (minus === 0) { minus = inumber.indexOf('-', 1); } // Lookup imaginary unit var last = inumber.substring(inumber.length - 1, inumber.length); var unit = (last === 'i' || last === 'j'); if (plus >= 0 || minus >= 0) { // Return error if imaginary unit is neither i nor j if (!unit) { return '#NUM!'; } // Return real coefficient of complex number if (plus >= 0) { return (isNaN(inumber.substring(0, plus)) || isNaN(inumber.substring(plus + 1, inumber.length - 1))) ? '#NUM!' : Number(inumber.substring(0, plus)); } else { return (isNaN(inumber.substring(0, minus)) || isNaN(inumber.substring(minus + 1, inumber.length - 1))) ? '#NUM!' : Number(inumber.substring(0, minus)); } } else { if (unit) { return (isNaN(inumber.substring(0, inumber.length - 1))) ? '#NUM!' : 0; } else { return (isNaN(inumber)) ? '#NUM!' : inumber; } } }; Formula.IMSEC = function (inumber) { // Return error if inumber is a logical value if (inumber === true || inumber === false) { return '#VALUE!'; } // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Return secant of complex number return Formula.IMDIV('1', Formula.IMCOS(inumber)); }; Formula.IMSECH = function (inumber) { // Return error if inumber is a logical value if (inumber === true || inumber === false) { return '#VALUE!'; } // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Return hyperbolic secant of complex number return Formula.IMDIV('1', Formula.IMCOSH(inumber)); }; Formula.IMSIN = function (inumber) { // Return error if inumber is a logical value if (inumber === true || inumber === false) { return '#VALUE!'; } // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Lookup imaginary unit var unit = inumber.substring(inumber.length - 1); unit = (unit === 'i' || unit === 'j') ? unit : 'i'; // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Return sine of complex number return Formula.COMPLEX(Math.sin(x) * (Math.exp(y) + Math.exp(-y)) / 2, Math.cos(x) * (Math.exp(y) - Math.exp(-y)) / 2, unit); }; Formula.IMSINH = function (inumber) { // Return error if inumber is a logical value if (inumber === true || inumber === false) { return '#VALUE!'; } // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Lookup imaginary unit var unit = inumber.substring(inumber.length - 1); unit = (unit === 'i' || unit === 'j') ? unit : 'i'; // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Return hyperbolic sine of complex number return Formula.COMPLEX(Math.cos(y) * (Math.exp(x) - Math.exp(-x)) / 2, Math.sin(y) * (Math.exp(x) + Math.exp(-x)) / 2, unit); }; Formula.IMSQRT = function (inumber) { // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Lookup imaginary unit var unit = inumber.substring(inumber.length - 1); unit = (unit === 'i' || unit === 'j') ? unit : 'i'; // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Calculate power of modulus var s = Math.sqrt(Formula.IMABS(inumber)); // Calculate argument var t = Formula.IMARGUMENT(inumber); // Return exponential of complex number return Formula.COMPLEX(s * Math.cos(t / 2), s * Math.sin(t / 2), unit); }; Formula.IMSUB = function (inumber1, inumber2) { // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var a = Formula.IMREAL(inumber1); var b = Formula.IMAGINARY(inumber1); var c = Formula.IMREAL(inumber2); var d = Formula.IMAGINARY(inumber2); // Lookup imaginary unit var unit1 = inumber1.substring(inumber1.length - 1); var unit2 = inumber1.substring(inumber1.length - 1); var unit = 'i'; if (unit1 === 'j') { unit = 'j'; } else if (unit2 === 'j') { unit = 'j'; } // Return error if either coefficient is not a number if (a === '#NUM!' || b === '#NUM!' || c === '#NUM!' || d === '#NUM!') { return '#NUM!'; } // Return _ of two complex numbers return Formula.COMPLEX(a - c, b - d, unit); }; Formula.IMSUM = function () { // Initialize result var result = arguments[0]; // Loop on all numbers for (var i = 1; i < arguments.length; i++) { // Lookup coefficients of two complex numbers var a = Formula.IMREAL(result); var b = Formula.IMAGINARY(result); var c = Formula.IMREAL(arguments[i]); var d = Formula.IMAGINARY(arguments[i]); // Return error if either coefficient is not a number if (a === '#NUM!' || b === '#NUM!' || c === '#NUM!' || d === '#NUM!') { return '#NUM!'; } // Complute product of two complex numbers result = Formula.COMPLEX(a + c, b + d); } // Return sum of complex numbers return result; }; Formula.IMTAN = function (inumber) { // Return error if inumber is a logical value if (inumber === true || inumber === false) { return '#VALUE!'; } // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] var x = Formula.IMREAL(inumber); var y = Formula.IMAGINARY(inumber); // Return error if either coefficient is not a number if (x === '#NUM!' || y === '#NUM!') { return '#NUM!'; } // Return tangent of complex number return Formula.IMDIV(Formula.IMSIN(inumber), Formula.IMCOS(inumber)); }; Formula.OCT2BIN = function (number, places) { // Return error if number is not hexadecimal or contains more than ten characters (10 digits) if (!/^[0-7]{1,10}$/.test(number)) { return '#NUM!'; } // Check if number is negative var negative = (number.length === 10 && number.substring(0, 1) === '7') ? true : false; // Convert octal number to decimal var decimal = (negative) ? parseInt(number, 8) - 1073741824 : parseInt(number, 8); // Return error if number is lower than -512 or greater than 511 if (decimal < -512 || decimal > 511) { return '#NUM!'; } // Ignore places and return a 10-character binary number if number is negative if (negative) { return '1' + _s.repeat('0', 9 - (512 + decimal).toString(2).length) + (512 + decimal).toString(2); } // Convert decimal number to binary var result = decimal.toString(2); // Return binary number using the minimum number of characters necessary if places is undefined if (typeof places === 'undefined') { return result; } else { // Return error if places is nonnumeric if (isNaN(places)) { return '#VALUE!'; } // Return error if places is negative if (places < 0) { return '#NUM!'; } // Truncate places in case it is not an integer places = Math.floor(places); // Pad return value with leading 0s (zeros) if necessary (using Underscore.string) return (places >= result.length) ? _s.repeat('0', places - result.length) + result : '#NUM!'; } }; Formula.OCT2DEC = function (number) { // Return error if number is not octal or contains more than ten characters (10 digits) if (!/^[0-7]{1,10}$/.test(number)) { return '#NUM!'; } // Convert octal number to decimal var decimal = parseInt(number, 8); // Return decimal number return (decimal >= 536870912) ? decimal - 1073741824 : decimal; }; Formula.OCT2HEX = function (number, places) { // Return error if number is not octal or contains more than ten characters (10 digits) if (!/^[0-7]{1,10}$/.test(number)) { return '#NUM!'; } // Convert octal number to decimal var decimal = parseInt(number, 8); // Ignore places and return a 10-character octal number if number is negative if (decimal >= 536870912) { return 'ff' + (decimal + 3221225472).toString(16); } // Convert decimal number to hexadecimal var result = decimal.toString(16); // Return hexadecimal number using the minimum number of characters necessary if places is undefined if (typeof places === 'undefined') { return result; } else { // Return error if places is nonnumeric if (isNaN(places)) { return '#VALUE!'; } // Return error if places is negative if (places < 0) { return '#NUM!'; } // Truncate places in case it is not an integer places = Math.floor(places); // Pad return value with leading 0s (zeros) if necessary (using Underscore.string) return (places >= result.length) ? _s.repeat('0', places - result.length) + result : '#NUM!'; } }; // Financial functions Formula.ACCRINT = function (issue, first, settlement, rate, par, frequency, basis, method) { // Return error if either date is invalid if (!moment(issue).isValid() || !moment(first).isValid() || !moment(settlement).isValid()) { return '#VALUE!'; } // Return error if either rate or par are lower than or equal to zero if (rate <= 0 || par <= 0) { return '#NUM!'; } // Return error if frequency is neither 1, 2, or 4 if ([1, 2, 4].indexOf(frequency) === -1) { return '#NUM!'; } // Return error if basis is neither 0, 1, 2, 3, or 4 if ([0, 1, 2, 3, 4].indexOf(basis) === -1) { return '#NUM!'; } // Return error if issue greater than or equal to settlement if (moment(issue).diff(moment(settlement)) >= 0) { return '#NUM!'; } // Set default values par = (typeof par === 'undefined') ? 0 : par; basis = (typeof basis === 'undefined') ? 0 : basis; method = (typeof method === 'undefined') ? true : method; // Compute accrued interest var factor = 0; var id = moment(new Date(issue)); var fd = moment(new Date(first)); var sd = moment(new Date(settlement)); var days = (moment([id.year()]).isLeapYear()) ? 366 : 365; switch (basis) { case 0: // US (NASD) 30/360 factor = Formula.YEARFRAC(issue, settlement, basis); break; case 1: // Actual/actual factor = Formula.YEARFRAC(issue, settlement, basis); break; case 2: // Actual/360 factor = Formula.YEARFRAC(issue, settlement, basis); break; case 3: // Actual/365 factor = Formula.YEARFRAC(issue, settlement, basis); break; case 4: // European 30/360 factor = Formula.YEARFRAC(issue, settlement, basis); break; } return par * rate * factor; }; Formula.ACCRINTM = function () { return; }; Formula.AMORDEGRC = function () { return; }; Formula.AMORLINC = function () { return; }; Formula.COUPDAYBS = function () { return; }; Formula.COUPDAYS = function () { return; }; Formula.COUPDAYSNC = function () { return; }; Formula.COUPNCD = function () { return; }; Formula.COUPNUM = function () { return; }; Formula.COUPPCD = function () { return; }; Formula.CUMIPMT = function (rate, periods, value, start, end, type) { // Credits: algorithm inspired by Apache OpenOffice // Credits: Hannes Stiebitzhofer for the translations of function and variable names // Requires Formula.FV() and Formula.PMT() from Formula.js [http://stoic.com/formula/] // Evaluate rate and periods (TODO: replace with secure expression evaluator) rate = eval(rate); periods = eval(periods); // Return error if either rate, periods, or value are lower than or equal to zero if (rate <= 0 || periods <= 0 || value <= 0) { return '#NUM!'; } // Return error if start < 1, end < 1, or start > end if (start < 1 || end < 1 || start > end) { return '#NUM!'; } // Return error if type is neither 0 nor 1 if (type !== 0 && type !== 1) { return '#NUM!'; } // Compute cumulative interest var payment = Formula.PMT(rate, periods, value, 0, type); var interest = 0; if (start === 1) { if (type === 0) { interest = -value; start++; } } for (var i = start; i <= end; i++) { if (type === 1) { interest += Formula.FV(rate, i - 2, payment, value, 1) - payment; } else { interest += Formula.FV(rate, i - 1, payment, value, 0); } } interest *= rate; // Return cumulative interest return interest; }; Formula.CUMPRINC = function (rate, periods, value, start, end, type) { // Credits: algorithm inspired by Apache OpenOffice // Credits: Hannes Stiebitzhofer for the translations of function and variable names // Requires Formula.FV() and Formula.PMT() from Formula.js [http://stoic.com/formula/] // Evaluate rate and periods (TODO: replace with secure expression evaluator) rate = eval(rate); periods = eval(periods); // Return error if either rate, periods, or value are lower than or equal to zero if (rate <= 0 || periods <= 0 || value <= 0) { return '#NUM!'; } // Return error if start < 1, end < 1, or start > end if (start < 1 || end < 1 || start > end) { return '#NUM!'; } // Return error if type is neither 0 nor 1 if (type !== 0 && type !== 1) { return '#NUM!'; } // Compute cumulative principal var payment = Formula.PMT(rate, periods, value, 0, type); var principal = 0; if (start === 1) { if (type === 0) { principal = payment + value * rate; } else { principal = payment; } start++; } for (var i = start; i <= end; i++) { if (type > 0) { principal += payment - (Formula.FV(rate, i - 2, payment, value, 1) - payment) * rate; } else { principal += payment - Formula.FV(rate, i - 1, payment, value, 0) * rate; } } // Return cumulative principal return principal; }; Formula.DB = function (cost, salvage, life, period, month) { // Initialize month month = (typeof month === 'undefined') ? 12 : month; // Return error if any of the parameters is not a number if (isNaN(cost) || isNaN(salvage) || isNaN(life) || isNaN(period) || isNaN(month)) { return '#VALUE!'; } // Return error if any of the parameters is negative [ if (cost < 0 || salvage < 0 || life < 0 || period < 0) { return '#NUM!'; } // Return error if month is not an integer between 1 and 12 if ([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].indexOf(month) === -1) { return '#NUM!'; } // Return error if period is greater than life if (period > life) { return '#NUM!'; } // Return 0 (zero) if salvage is greater than or equal to cost if (salvage >= cost) { return 0; } // Rate is rounded to three decimals places var rate = (1 - Math.pow(salvage / cost, 1 / life)).toFixed(3); // Compute initial depreciation var initial = cost * rate * month / 12; // Compute total depreciation var total = initial; var current = 0; var ceiling = (period === life) ? life - 1 : period; for (var i = 2; i <= ceiling; i++) { current = (cost - total) * rate; total += current; } // Depreciation for the first and last periods are special cases if (period === 1) { // First period return initial; } else if (period === life) { // Last period return (cost - total) * rate; } else { return current; } }; Formula.DDB = function (cost, salvage, life, period, factor) { // Initialize factor factor = (typeof factor === 'undefined') ? 2 : factor; // Return error if any of the parameters is not a number if (isNaN(cost) || isNaN(salvage) || isNaN(life) || isNaN(period) || isNaN(factor)) { return '#VALUE!'; } // Return error if any of the parameters is negative or if factor is null if (cost < 0 || salvage < 0 || life < 0 || period < 0 || factor <= 0) { return '#NUM!'; } // Return error if period is greater than life if (period > life) { return '#NUM!'; } // Return 0 (zero) if salvage is greater than or equal to cost if (salvage >= cost) { return 0; } // Compute depreciation var total = 0; var current = 0; for (var i = 1; i <= period; i++) { current = Math.min((cost - total) * (factor / life), (cost - salvage - total)); total += current; } // Return depreciation return current; }; Formula.DISC = function () { return; }; Formula.DOLLARDE = function (dollar, fraction) { // Credits: algorithm inspired by Apache OpenOffice // Return error if any of the parameters is not a number if (isNaN(dollar) || isNaN(fraction)) { return '#VALUE!'; } // Return error if fraction is negative if (fraction < 0) { return '#NUM!'; } // Return error if fraction is greater than or equal to 0 and less than 1 if (fraction >= 0 && fraction < 1) { return '#DIV/0!'; } // Truncate fraction if it is not an integer fraction = parseInt(fraction, 10); // Compute integer part var result = parseInt(dollar, 10); // Add decimal part result += (dollar % 1) * Math.pow(10, Math.ceil(Math.log(fraction) / Math.LN10)) / fraction; // Round result var power = Math.pow(10, Math.ceil(Math.log(fraction) / Math.LN2) + 1); result = Math.round(result * power) / power; // Return converted dollar price return result; }; Formula.DOLLARFR = function (dollar, fraction) { // Credits: algorithm inspired by Apache OpenOffice // Return error if any of the parameters is not a number if (isNaN(dollar) || isNaN(fraction)) { return '#VALUE!'; } // Return error if fraction is negative if (fraction < 0) { return '#NUM!'; } // Return error if fraction is greater than or equal to 0 and less than 1 if (fraction >= 0 && fraction < 1) { return '#DIV/0!'; } // Truncate fraction if it is not an integer fraction = parseInt(fraction, 10); // Compute integer part var result = parseInt(dollar, 10); // Add decimal part result += (dollar % 1) * Math.pow(10, -Math.ceil(Math.log(fraction) / Math.LN10)) * fraction; // Return converted dollar price return result; }; Formula.DURATION = function () { return; }; Formula.EFFECT = function (rate, periods) { // Return error if any of the parameters is not a number if (isNaN(rate) || isNaN(periods)) { return '#VALUE!'; } // Return error if rate <=0 or periods < 1 if (rate <= 0 || periods < 1) { return '#NUM!'; } // Truncate periods if it is not an integer periods = parseInt(periods, 10); // Return effective annual interest rate return Math.pow(1 + rate / periods, periods) - 1; }; Formula.FV = function (rate, periods, payment, value, type) { // Credits: algorithm inspired by Apache OpenOffice // Initialize type type = (typeof type === 'undefined') ? 0 : type; // Evaluate rate (TODO: replace with secure expression evaluator) rate = eval(rate); // Return future value var result; if (rate === 0) { result = value + payment * periods; } else { var term = Math.pow(1 + rate, periods); if (type === 1) { result = value * term + payment * (1 + rate) * (term - 1.0) / rate; } else { result = value * term + payment * (term - 1) / rate; } } return -result; }; Formula.FVSCHEDULE = function (principal, schedule) { // Initialize future value var future = principal; // Apply all interests in schedule for (var i = 0; i < schedule.length; i++) { // Return error if schedule value is not a number if (isNaN(schedule[i])) { return '#VALUE!'; } // Apply scheduled interest future *= 1 + schedule[i]; } // Return future value return future; }; Formula.INTRATE = function () { return; }; Formula.IPMT = function (rate, period, periods, present, future, type) { // Credits: algorithm inspired by Apache OpenOffice // Initialize type type = (typeof type === 'undefined') ? 0 : type; // Evaluate rate and periods (TODO: replace with secure expression evaluator) rate = eval(rate); periods = eval(periods); // Compute payment var payment = Formula.PMT(rate, periods, present, future, type); // Compute interest var interest; if (period === 1) { if (type === 1) { interest = 0; } else { interest = -present; } } else { if (type === 1) { interest = Formula.FV(rate, period - 2, payment, present, 1) - payment; } else { interest = Formula.FV(rate, period - 1, payment, present, 0); } } // Return interest return interest * rate; }; Formula.IRR = function (values, guess) { // Credits: algorithm inspired by Apache OpenOffice // Calculates the resulting amount var irrResult = function (values, dates, rate) { var r = rate + 1; var result = values[0]; for (var i = 1; i < values.length; i++) { result += values[i] / Math.pow(r, (dates[i] - dates[0]) / 365); } return result; }; // Calculates the first derivation var irrResultDeriv = function (values, dates, rate) { var r = rate + 1; var result = 0; for (var i = 1; i < values.length; i++) { var frac = (dates[i] - dates[0]) / 365; result -= frac * values[i] / Math.pow(r, frac + 1); } return result; }; // Initialize dates and check that values contains at least one positive value and one negative value var dates = []; var positive = false; var negative = false; for (var i = 0; i < values.length; i++) { dates[i] = (i === 0) ? 0 : dates[i - 1] + 365; if (values[i] > 0) { positive = true; } if (values[i] < 0) { negative = true; } } // Return error if values does not contain at least one positive value and one negative value if (!positive || !negative) { return '#NUM!'; } // Initialize guess and resultRate guess = (typeof guess === 'undefined') ? 0.1 : guess; var resultRate = guess; // Set maximum epsilon for end of iteration var epsMax = 1e-10; // Set maximum number of iterations var iterMax = 50; // Implement Newton's method var newRate, epsRate, resultValue; var iteration = 0; var contLoop = true; do { resultValue = irrResult(values, dates, resultRate); newRate = resultRate - resultValue / irrResultDeriv(values, dates, resultRate); epsRate = Math.abs(newRate - resultRate); resultRate = newRate; contLoop = (epsRate > epsMax) && (Math.abs(resultValue) > epsMax); } while (contLoop && (++iteration < iterMax)); if (contLoop) { return '#NUM!'; } // Return internal rate of return return resultRate; }; Formula.ISPMT = function (rate, period, periods, value) { // Evaluate rate and periods (TODO: replace with secure expression evaluator) rate = eval(rate); periods = eval(periods); // Return interest return value * rate * (period / periods - 1); }; Formula.MDURATION = function () { return; }; Formula.MIRR = function (values, finance_rate, reinvest_rate) { // Initialize number of values var n = values.length; // Lookup payments (negative values) and incomes (positive values) var payments = []; var incomes = []; for (var i = 0; i < n; i++) { if (values[i] < 0) { payments.push(values[i]); } else { incomes.push(values[i]); } } // Return modified internal rate of return var num = -Formula.NPV(reinvest_rate, incomes) * Math.pow(1 + reinvest_rate, n - 1); var den = Formula.NPV(finance_rate, payments) * (1 + finance_rate); return Math.pow(num / den, 1 / (n - 1)) - 1; }; Formula.NOMINAL = function (rate, periods) { // Return error if any of the parameters is not a number if (isNaN(rate) || isNaN(periods)) { return '#VALUE!'; } // Return error if rate <=0 or periods < 1 if (rate <= 0 || periods < 1) { return '#NUM!'; } // Truncate periods if it is not an integer periods = parseInt(periods, 10); // Return nominal annual interest rate return (Math.pow(rate + 1, 1 / periods) - 1) * periods; }; Formula.NPER = function (rate, payment, present, future, type) { // Initialize type type = (typeof type === 'undefined') ? 0 : type; // Initialize future value future = (typeof future === 'undefined') ? 0 : future; // Evaluate rate and periods (TODO: replace with secure expression evaluator) rate = eval(rate); // Return number of periods var num = payment * (1 + rate * type) - future * rate; var den = (present * rate + payment * (1 + rate * type)); return Math.log(num / den) / Math.log(1 + rate); }; Formula.NPV = function () { // Cast arguments to array var args = []; for (var i = 0; i < arguments.length; i++) { args = args.concat(arguments[i]); } // Lookup rate var rate = args[0]; // Initialize net present value var value = 0; // Loop on all values for (var j = 1; j < args.length; j++) { value += args[j] / Math.pow(1 + rate, j); } // Return net present value return value; }; Formula.ODDFPRICE = function () { return; }; Formula.ODDFYIELD = function () { return; }; Formula.ODDLPRICE = function () { return; }; Formula.ODDLYIELD = function () { return; }; Formula.PDURATION = function (rate, present, future) { // Return error if any of the parameters is not a number if (isNaN(rate) || isNaN(present) || isNaN(future)) { return '#VALUE!'; } // Return error if rate <=0 if (rate <= 0) { return '#NUM!'; } // Return number of periods return (Math.log(future) - Math.log(present)) / Math.log(1 + rate); }; Formula.PMT = function (rate, periods, present, future, type) { // Credits: algorithm inspired by Apache OpenOffice // Initialize type type = (typeof type === 'undefined') ? 0 : type; // Evaluate rate and periods (TODO: replace with secure expression evaluator) rate = eval(rate); periods = eval(periods); // Return payment var result; if (rate === 0) { result = (present + future) / periods; } else { var term = Math.pow(1 + rate, periods); if (type === 1) { result = (future * rate / (term - 1) + present * rate / (1 - 1 / term)) / (1 + rate); } else { result = future * rate / (term - 1) + present * rate / (1 - 1 / term); } } return -result; }; Formula.PPMT = function (rate, period, periods, present, future, type) { return Formula.PMT(rate, periods, present, future, type) - Formula.IPMT(rate, period, periods, present, future, type); }; Formula.PRICE = function () { return; }; Formula.PRICEDISC = function () { return; }; Formula.PRICEMAT = function () { return; }; Formula.PV = function (rate, periods, payment, future, type) { // Initialize type type = (typeof type === 'undefined') ? 0 : type; // Evaluate rate and periods (TODO: replace with secure expression evaluator) rate = eval(rate); periods = eval(periods); // Return present value if (rate === 0) { return -payment * periods - future; } else { return (((1 - Math.pow(1 + rate, periods)) / rate) * payment * (1 + rate * type) - future) / Math.pow(1 + rate, periods); } }; Formula.RATE = function (periods, payment, present, future, type, guess) { // Credits: rabugento // Initialize guess guess = (typeof guess === 'undefined') ? 0.01 : guess; // Initialize future future = (typeof future === 'undefined') ? 0 : future; // Initialize type type = (typeof type === 'undefined') ? 0 : type; // Evaluate periods (TODO: replace with secure expression evaluator) periods = eval(periods); // Set maximum epsilon for end of iteration var epsMax = 1e-10; // Set maximum number of iterations var iterMax = 50; // Implement Newton's method var y, y0, y1, x0, x1 = 0, f = 0, i = 0; var rate = guess; if (Math.abs(rate) < epsMax) { y = present * (1 + periods * rate) + payment * (1 + rate * type) * periods + future; } else { f = Math.exp(periods * Math.log(1 + rate)); y = present * f + payment * (1 / rate + type) * (f - 1) + future; } y0 = present + payment * periods + future; y1 = present * f + payment * (1 / rate + type) * (f - 1) + future; i = x0 = 0; x1 = rate; while ((Math.abs(y0 - y1) > epsMax) && (i < iterMax)) { rate = (y1 * x0 - y0 * x1) / (y1 - y0); x0 = x1; x1 = rate; if (Math.abs(rate) < epsMax) { y = present * (1 + periods * rate) + payment * (1 + rate * type) * periods + future; } else { f = Math.exp(periods * Math.log(1 + rate)); y = present * f + payment * (1 / rate + type) * (f - 1) + future; } y0 = y1; y1 = y; ++i; } return rate; }; Formula.RECEIVED = function () { return; }; Formula.RRI = function (periods, present, future) { // Return error if any of the parameters is not a number if (isNaN(periods) || isNaN(present) || isNaN(future)) { return '#VALUE!'; } // Return error if periods or present is equal to 0 (zero) if (periods === 0 || present === 0) { return '#NUM!'; } // Return equivalent interest rate return Math.pow(future / present, 1 / periods) - 1; }; Formula.SLN = function (cost, salvage, life) { // Return error if any of the parameters is not a number if (isNaN(cost) || isNaN(salvage) || isNaN(life)) { return '#VALUE!'; } // Return error if life equal to 0 (zero) if (life === 0) { return '#NUM!'; } // Return straight-line depreciation return (cost - salvage) / life; }; Formula.SYD = function (cost, salvage, life, period) { // Return error if any of the parameters is not a number if (isNaN(cost) || isNaN(salvage) || isNaN(life) || isNaN(period)) { return '#VALUE!'; } // Return error if life equal to 0 (zero) if (life === 0) { return '#NUM!'; } // Return error if period is lower than 1 or greater than life if (period < 1 || period > life) { return '#NUM!'; } // Truncate period if it is not an integer period = parseInt(period, 10); // Return straight-line depreciation return (cost - salvage) * (life - period + 1) * 2 / (life * (life + 1)); }; Formula.TBILLEQ = function (settlement, maturity, discount) { // Return error if either date is invalid if (!moment(settlement).isValid() || !moment(maturity).isValid()) { return '#VALUE!'; } // Return error if discount is lower than or equal to zero if (discount <= 0) { return '#NUM!'; } // Return error if settlement is greater than maturity if (moment(settlement).diff(moment(maturity)) > 0) { return '#NUM!'; } // Return error if maturity is more than one year after settlement if (moment(maturity).diff(moment(settlement), 'years') > 1) { return '#NUM!'; } // Return bond-equivalent yield return (365 * discount) / (360 - discount * Formula.DAYS360(settlement, maturity)); }; Formula.TBILLPRICE = function (settlement, maturity, discount) { // Return error if either date is invalid if (!moment(settlement).isValid() || !moment(maturity).isValid()) { return '#VALUE!'; } // Return error if discount is lower than or equal to zero if (discount <= 0) { return '#NUM!'; } // Return error if settlement is greater than maturity if (moment(settlement).diff(moment(maturity)) > 0) { return '#NUM!'; } // Return error if maturity is more than one year after settlement if (moment(maturity).diff(moment(settlement), 'years') > 1) { return '#NUM!'; } // Return bond-equivalent yield return 100 * (1 - discount * Formula.DAYS360(settlement, maturity) / 360); }; Formula.TBILLYIELD = function (settlement, maturity, price) { // Return error if either date is invalid if (!moment(settlement).isValid() || !moment(maturity).isValid()) { return '#VALUE!'; } // Return error if price is lower than or equal to zero if (price <= 0) { return '#NUM!'; } // Return error if settlement is greater than maturity if (moment(settlement).diff(moment(maturity)) > 0) { return '#NUM!'; } // Return error if maturity is more than one year after settlement if (moment(maturity).diff(moment(settlement), 'years') > 1) { return '#NUM!'; } // Return bond-equivalent yield return (100 - price) * 360 / (price * Formula.DAYS360(settlement, maturity)); }; Formula.VDB = function () { return; }; Formula.XIRR = function (values, dates, guess) { // Credits: algorithm inspired by Apache OpenOffice // Calculates the resulting amount var irrResult = function (values, dates, rate) { var r = rate + 1; var result = values[0]; for (var i = 1; i < values.length; i++) { result += values[i] / Math.pow(r, moment(dates[i]).diff(moment(dates[0]), 'days') / 365); } return result; }; // Calculates the first derivation var irrResultDeriv = function (values, dates, rate) { var r = rate + 1; var result = 0; for (var i = 1; i < values.length; i++) { var frac = moment(dates[i]).diff(moment(dates[0]), 'days') / 365; result -= frac * values[i] / Math.pow(r, frac + 1); } return result; }; // Check that values contains at least one positive value and one negative value var positive = false; var negative = false; for (var i = 0; i < values.length; i++) { if (values[i] > 0) { positive = true; } if (values[i] < 0) { negative = true; } } // Return error if values does not contain at least one positive value and one negative value if (!positive || !negative) { return '#NUM!'; } // Initialize guess and resultRate guess = guess || 0.1; var resultRate = guess; // Set maximum epsilon for end of iteration var epsMax = 1e-10; // Set maximum number of iterations var iterMax = 50; // Implement Newton's method var newRate, epsRate, resultValue; var iteration = 0; var contLoop = true; do { resultValue = irrResult(values, dates, resultRate); newRate = resultRate - resultValue / irrResultDeriv(values, dates, resultRate); epsRate = Math.abs(newRate - resultRate); resultRate = newRate; contLoop = (epsRate > epsMax) && (Math.abs(resultValue) > epsMax); } while (contLoop && (++iteration < iterMax)); if (contLoop) { return '#NUM!'; } // Return internal rate of return return resultRate; }; Formula.XNPV = function (rate, values, dates) { var result = 0; for (var i = 0; i < values.length; i++) { result += values[i] / Math.pow(1 + rate, moment(dates[i]).diff(moment(dates[0]), 'days') / 365); } return result; }; Formula.YIELD = function () { return; }; Formula.YIELDDISC = function () { return; }; Formula.YIELDMAT = function () { }; // Information functions Formula.ISNUMBER = function (number) { return (!isNaN(parseFloat(number)) && isFinite(number)) ? true : false; }; // Logical functions Formula.AND = function () { var result = true; for (var i = 0; i < arguments.length; i++) { if (!arguments[i]) { result = false; } } return result; }; Formula.FALSE = function () { return false; }; Formula.SWITCH = function () { var result; if (arguments.length > 0) { var targetValue = arguments[0]; var argc = arguments.length - 1; var switchCount = Math.floor(argc / 2); var switchSatisfied = false; var defaultClause = argc % 2 === 0 ? null : arguments[arguments.length - 1]; if (switchCount) { for (var index = 0; index < switchCount; index++) { if (targetValue === arguments[index * 2 + 1]) { result = arguments[index * 2 + 2]; switchSatisfied = true; break; } } } if (!switchSatisfied && defaultClause) { result = defaultClause; } } return result; }; Formula.IF = function (test, then_value, otherwise_value) { if (test) { return (typeof then_value === 'undefined') ? true : then_value; } else { return (typeof otherwise_value === 'undefined') ? true : otherwise_value; } }; Formula.IFERROR = function (value, value_if_error) { return (['#DIV/0!', '#N/A', '#NAME?', '#NUM!', '#NULL!', '#REF!', '#VALUE!'].indexOf(value) >= 0 ) ? value_if_error : value; }; Formula.IFNA = function (value, value_if_na) { return (value === '#N/A') ? value_if_na : value; }; Formula.NOT = function (logical) { return !logical; }; Formula.OR = function () { var result = false; for (var i = 0; i < arguments.length; i++) { if (arguments[i]) { result = true; } } return result; }; Formula.TRUE = function () { return true; }; Formula.XOR = function () { var result = 0; for (var i = 0; i < arguments.length; i++) { if (arguments[i]) { result++; } } return (Math.floor(Math.abs(result)) & 1) ? true : false; }; // Lookup and reference functions Formula.REFERENCE = function (context, reference) { try { var path = reference.split('.'), result = context; _(path).forEach(function (step) { if (step[step.length - 1] === ']') { var opening = step.indexOf('['); var index = step.substring(opening + 1, step.length - 1); result = result[step.substring(0, opening)][index]; } else { result = result[step]; } }); return result; } catch (error) { return; } }; // Math functions Formula.ABS = function (number) { return Math.abs(number); }; Formula.ACOS = function (number) { return Math.acos(number); }; Formula.ACOSH = function (number) { return Math.log(number + Math.sqrt(number * number - 1)); }; Formula.ACOT = function (number) { return Math.atan(1 / number); }; Formula.ACOTH = function (number) { return 0.5 * Math.log((number + 1) / (number - 1)); }; Formula.AGGREGATE = function (function_code, options) { var result = []; for (var i = 2; i < arguments.length; i++) { switch (function_code) { case 1: result[i - 2] = Formula.AVERAGE(arguments[i]); break; case 2: result[i - 2] = Formula.COUNT(arguments[i]); break; case 3: result[i - 2] = Formula.COUNTA(arguments[i]); break; case 4: result[i - 2] = Formula.MAX(arguments[i]); break; case 5: result[i - 2] = Formula.MIN(arguments[i]); break; case 6: result[i - 2] = Formula.PRODUCT(arguments[i]); break; case 7: result[i - 2] = Formula.STDEVS(arguments[i]); break; case 8: result[i - 2] = Formula.STDEVP(arguments[i]); break; case 9: result[i - 2] = Formula.SUM(arguments[i]); break; case 10: result[i - 2] = Formula.VARS(arguments[i]); break; case 11: result[i - 2] = Formula.VARP(arguments[i]); break; case 12: result[i - 2] = Formula.MEDIAN(arguments[i]); break; case 13: result[i - 2] = Formula.MODESNGL(arguments[i]); break; case 14: result[i - 2] = Formula.LARGE(arguments[i]); break; case 15: result[i - 2] = Formula.SMALL(arguments[i]); break; case 16: result[i - 2] = Formula.PERCENTILEINC(arguments[i]); break; case 17: result[i - 2] = Formula.QUARTILEINC(arguments[i]); break; case 18: result[i - 2] = Formula.PERCENTILEEXC(arguments[i]); break; case 19: result[i - 2] = Formula.QUARTILEEXC(arguments[i]); break; } } return result; }; Formula.ARABIC = function (text) { // Credits: Rafa? Kukawski if (!/^M*(?:D?C{0,3}|C[MD])(?:L?X{0,3}|X[CL])(?:V?I{0,3}|I[XV])$/.test(text)) { throw new Error('Incorrect roman number'); } var r = 0; text.replace(/[MDLV]|C[MD]?|X[CL]?|I[XV]?/g, function (i) { r += {M: 1000, CM: 900, D: 500, CD: 400, C: 100, XC: 90, L: 50, XL: 40, X: 10, IX: 9, V: 5, IV: 4, I: 1}[i]; }); return r; }; Formula.ASIN = function (number) { return Math.asin(number); }; Formula.ASINH = function (number) { return Math.log(number + Math.sqrt(number * number + 1)); }; Formula.ATAN = function (number) { return Math.atan(number); }; Formula.ATAN2 = function (number_x, number_y) { return Math.atan2(number_x, number_y); }; Formula.ATANH = function (number) { return Math.log((1 + number) / (1 - number)) / 2; }; Formula.BASE = function (number, radix, min_length) { min_length = (typeof min_length === 'undefined') ? 0 : min_length; var result = number.toString(radix); return new Array(Math.max(min_length + 1 - result.length, 0)).join('0') + result; }; Formula.CEILING = function (number, significance, mode) { if (significance === 0) { return 0; } significance = (typeof significance === 'undefined') ? 1 : Math.abs(significance); mode = (typeof mode === 'undefined') ? 0 : mode; var precision = -Math.floor(Math.log(significance) / Math.log(10)); if (number >= 0) { return Formula.ROUND(Math.ceil(number / significance) * significance, precision); } else { if (mode === 0) { return -Formula.ROUND(Math.floor(Math.abs(number) / significance) * significance, precision); } else { return -Formula.ROUND(Math.ceil(Math.abs(number) / significance) * significance, precision); } } }; Formula.CEILINGMATH = Formula.CEILING; Formula.CEILINGPRECISE = Formula.CEILING; Formula.COMBIN = function (number, number_chosen) { return Formula.FACT(number) / (Formula.FACT(number_chosen) * Formula.FACT(number - number_chosen)); }; Formula.COMBINA = function (number, number_chosen) { return (number === 0 && number_chosen === 0) ? 1 : Formula.COMBIN(number + number_chosen - 1, number - 1); }; Formula.COS = function (number) { return Math.cos(number); }; Formula.COSH = function (number) { return (Math.exp(number) + Math.exp(-number)) / 2; }; Formula.COT = function (number) { return 1 / Math.tan(number); }; Formula.COTH = function (number) { var e2 = Math.exp(2 * number); return (e2 + 1) / (e2 - 1); }; Formula.CSC = function (number) { return 1 / Math.sin(number); }; Formula.CSCH = function (number) { return 2 / (Math.exp(number) - Math.exp(-number)); }; Formula.DECIMAL = function (number, radix) { return parseInt(number, radix); }; Formula.DEGREES = function (number) { return number * 180 / Math.PI; }; Formula.EVEN = function (number) { return Formula.CEILING(number, -2, -1); }; Formula.EXP = function (number) { return Math.exp(number); }; Formula.FACT = function (number) { var n = Math.floor(number); if (n === 0 || n === 1) { return 1; } else if (MEMOIZED_FACT[n] > 0) { return MEMOIZED_FACT[n]; } else { MEMOIZED_FACT[n] = Formula.FACT(n - 1) * n; return MEMOIZED_FACT[n]; } }; Formula.FACTDOUBLE = function (number) { var n = Math.floor(number); if (n <= 0) { return 1; } else { return n * Formula.FACTDOUBLE(n - 2); } }; Formula.FLOOR = function (number, significance, mode) { if (significance === 0) { return 0; } significance = (typeof significance === 'undefined') ? 1 : Math.abs(significance); mode = (typeof mode === 'undefined') ? 0 : mode; var precision = -Math.floor(Math.log(significance) / Math.log(10)); if (number >= 0) { return Formula.ROUND(Math.floor(number / significance) * significance, precision); } else { if (mode === 0) { return -Formula.ROUND(Math.ceil(Math.abs(number) / significance) * significance, precision); } else { return -Formula.ROUND(Math.floor(Math.abs(number) / significance) * significance, precision); } } }; Formula.FLOORMATH = Formula.FLOOR; Formula.FLOORPRECISE = Formula.FLOOR; Formula.GCD = function () { // Credits: Andrew Pociu for (var r, a, i = arguments.length - 1, result = arguments[i]; i;) { for (a = arguments[--i]; (r = a % result); a = result, result = r) { //empty } } return result; }; Formula.INT = function (number) { return Math.floor(number); }; Formula.ISEVEN = function (number) { return (Math.floor(Math.abs(number)) & 1) ? false : true; }; Formula.ISOCEILING = Formula.CEILING; Formula.ISODD = function (number) { return (Math.floor(Math.abs(number)) & 1) ? true : false; }; Formula.LCM = function () { // Credits: Jonas Raoni Soares Silva var o = Formula.ARGSTOARRAY(arguments); for (var i, j, n, d, r = 1; (n = o.pop()) !== undefined;) { while (n > 1) { if (n % 2) { for (i = 3, j = Math.floor(Math.sqrt(n)); i <= j && n % i; i += 2) { //empty } d = (i <= j) ? i : n; } else { d = 2; } for (n /= d, r *= d, i = o.length; i; (o[--i] % d) === 0 && (o[i] /= d) === 1 && o.splice(i, 1)) { //empty } } } return r; }; Formula.LN = function (number) { return Math.log(number); }; Formula.LOG = function (number, base) { base = (typeof base === 'undefined') ? 10 : base; return Math.log(number) / Math.log(base); }; Formula.LOG10 = function (number) { return Math.log(number) / Math.log(10); }; Formula.MDETERM = numeric.det; Formula.MINVERSE = numeric.inv; Formula.MMULT = numeric.dot; Formula.MOD = function (dividend, divisor) { var modulus = Math.abs(dividend % divisor); return (divisor > 0) ? modulus : -modulus; }; Formula.MROUND = function (number, multiple) { if (number * multiple < 0) { throw new Error('Number and multiple must have the same sign.'); } return Math.round(number / multiple) * multiple; }; Formula.MULTINOMIAL = function () { var sum = 0; var divisor = 1; for (var i = 0; i < arguments.length; i++) { sum += arguments[i]; divisor *= Formula.FACT(arguments[i]); } return Formula.FACT(sum) / divisor; }; Formula.MUNIT = numeric.identity; Formula.ODD = function (number) { var temp = Math.ceil(Math.abs(number)); temp = (temp & 1) ? temp : temp + 1; return (number > 0) ? temp : -temp; }; Formula.PI = function () { return Math.PI; }; Formula.POWER = function (number, power) { var result = Math.pow(number, power); if (isNaN(result)) { return '#NUM!'; } return result; }; Formula.PRODUCT = function () { var result = 1; for (var i = 0; i < arguments.length; i++) { result *= arguments[i]; } return result; }; Formula.QUOTIENT = function (numerator, denominator) { return (numerator / denominator).toFixed(0); }; Formula.RADIANS = function (number) { return number * Math.PI / 180; }; Formula.RAND = function () { return Math.random(); }; Formula.RANDBETWEEN = function (bottom, top) { // Creative Commons Attribution 3.0 License // Copyright (c) 2012 eqcode return bottom + Math.ceil((top - bottom + 1) * Math.random()) - 1; }; Formula.ROUND = function (number, digits) { return Math.round(number * Math.pow(10, digits)) / Math.pow(10, digits); }; Formula.ROUNDDOWN = function (number, digits) { var sign = (number > 0) ? 1 : -1; return sign * (Math.floor(Math.abs(number) * Math.pow(10, digits))) / Math.pow(10, digits); }; Formula.ROUNDUP = function (number, digits) { var sign = (number > 0) ? 1 : -1; return sign * (Math.ceil(Math.abs(number) * Math.pow(10, digits))) / Math.pow(10, digits); }; Formula.SERIESSUM = function (x, n, m, coefficients) { var result = coefficients[0] * Math.pow(x, n); for (var i = 1; i < coefficients.length; i++) { result += coefficients[i] * Math.pow(x, n + i * m); } return result; }; Formula.SEC = function (number) { return 1 / Math.cos(number); }; Formula.SECH = function (number) { return 2 / (Math.exp(number) + Math.exp(-number)); }; Formula.SIGN = function (number) { if (number < 0) { return -1; } else if (number === 0) { return 0; } else { return 1; } }; Formula.SIN = function (number) { return Math.sin(number); }; Formula.SINH = function (number) { return (Math.exp(number) - Math.exp(-number)) / 2; }; Formula.SQRT = function (number) { return Math.sqrt(number); }; Formula.SQRTPI = function (number) { return Math.sqrt(number * Math.PI); }; Formula.SUBTOTAL = function (function_code) { var result = []; for (var i = 1; i < arguments.length; i++) { switch (function_code) { case 1: result[i - 1] = Formula.AVERAGE(arguments[i]); break; case 2: result[i - 1] = Formula.COUNT(arguments[i]); break; case 3: result[i - 1] = Formula.COUNTA(arguments[i]); break; case 4: result[i - 1] = Formula.MAX(arguments[i]); break; case 5: result[i - 1] = Formula.MIN(arguments[i]); break; case 6: result[i - 1] = Formula.PRODUCT(arguments[i]); break; case 7: result[i - 1] = Formula.STDEV(arguments[i]); break; case 8: result[i - 1] = Formula.STDEVP(arguments[i]); break; case 9: result[i - 1] = Formula.SUM(arguments[i]); break; case 10: result[i - 1] = Formula.VAR(arguments[i]); break; case 11: result[i - 1] = Formula.VARP(arguments[i]); break; } } return result; }; Formula.SUM = function () { var numbers = Formula.ARGSTOARRAY(arguments); var result = 0; for (var i = 0; i < numbers.length; i++) { if (numbers[i] instanceof Array) { for (var j = 0; j < numbers[i].length; j++) { if (numbers[i][j] instanceof Array) { for (var k = 0; k < numbers[i][j].length; k++) { result += (Formula.ISNUMBER(numbers[i][j][k])) ? numbers[i][j][k] : 0; } } else { result += (Formula.ISNUMBER(numbers[i][j])) ? numbers[i][j] : 0; } } } else { result += (Formula.ISNUMBER(numbers[i])) ? numbers[i] : 0; } } return result; }; Formula.SUMIF = function (range, criteria) { var result = 0; for (var i = 0; i < range.length; i++) { result += (eval(range[i] + criteria)) ? range[i] : 0; } return result; }; Formula.SUMIFS = function () { var criteria = (arguments.length - 1) / 2; var range = arguments[0]; var result = 0; for (var i = 0; i < range.length; i++) { var fit = true; for (var j = 0; j < criteria; j++) { if (!eval(arguments[2 * j + 1][i] + arguments[2 * j + 2])) { fit = false; } } result += (fit) ? range[i] : 0; } return result; }; Formula.SUMPRODUCT = function () { var arrays = arguments.length + 1; var result = 0; for (var i = 0; i < arguments[0].length; i++) { for (var j = 0; j < arguments[0][i].length; j++) { var product = 1; for (var k = 1; k < arrays; k++) { product *= arguments[k - 1][i][j]; } result += product; } } return result; }; Formula.SUMSQ = function () { var numbers = Formula.ARGSTOARRAY(arguments); var result = 0; for (var i = 0; i < numbers.length; i++) { result += (Formula.ISNUMBER(numbers[i])) ? numbers[i] * numbers[i] : 0; } return result; }; Formula.SUMX2MY2 = function (array_x, array_y) { var result = 0; for (var i = 0; i < array_x.length; i++) { result += array_x[i] * array_x[i] - array_y[i] * array_y[i]; } return result; }; Formula.SUMX2PY2 = function (array_x, array_y) { var result = 0; for (var i = 0; i < array_x.length; i++) { result += array_x[i] * array_x[i] + array_y[i] * array_y[i]; } return result; }; Formula.SUMXMY2 = function (array_x, array_y) { var result = 0; for (var i = 0; i < array_x.length; i++) { result += Math.pow(array_x[i] - array_y[i], 2); } return result; }; Formula.TAN = function (number) { return Math.tan(number); }; Formula.TANH = function (number) { var e2 = Math.exp(2 * number); return (e2 - 1) / (e2 + 1); }; Formula.TRUNC = function (number, digits) { digits = (typeof digits === 'undefined') ? 0 : digits; var sign = (number > 0) ? 1 : -1; return sign * (Math.floor(Math.abs(number) * Math.pow(10, digits))) / Math.pow(10, digits); }; // Statistical functions Formula.AVEDEV = function () { var range = Formula.ARGSCONCAT(arguments); return jStat.sum(jStat(range).subtract(jStat.mean(range)).abs()[0]) / range.length; }; Formula.AVERAGE = function () { var range = Formula.ARGSCONCAT(arguments); var n = range.length; var count = 0; var sigma = 0; for (var i = 0; i < n; i++) { if (range[i] !== true && range[i] !== false) { sigma += range[i]; count++; } } return sigma / count; }; Formula.AVERAGEA = function () { return jStat.mean(Formula.ARGSCONCAT(arguments)); }; Formula.AVERAGEIF = function (range, criteria, average_range) { average_range = (typeof average_range === 'undefined') ? range : average_range; var average_count = 0; var result = 0; for (var i = 0; i < range.length; i++) { if (eval(range[i] + criteria)) { result += average_range[i]; average_count++; } } return result / average_count; }; Formula.AVERAGEIFS = function () { var criteria = (arguments.length - 1) / 2; var range = arguments[0]; var count = 0; var result = 0; for (var i = 0; i < range.length; i++) { var fit = true; for (var j = 0; j < criteria; j++) { if (!eval(arguments[2 * j + 1][i] + arguments[2 * j + 2])) { fit = false; } } if (fit) { result += range[i]; count++; } } return result / count; }; Formula.BETADIST = function (x, alpha, beta, cumulative, A, B) { A = (typeof A === 'undefined') ? 0 : A; B = (typeof B === 'undefined') ? 1 : B; x = (x - A) / (B - A); return (cumulative) ? jStat.beta.cdf(x, alpha, beta) : jStat.beta.pdf(x, alpha, beta); }; Formula.BETAINV = function (probability, alpha, beta, A, B) { A = (typeof A === 'undefined') ? 0 : A; B = (typeof B === 'undefined') ? 1 : B; return jStat.beta.inv(probability, alpha, beta) * (B - A) + A; }; Formula.BINOMDIST = function (successes, trials, probability, cumulative) { return (cumulative) ? jStat.binomial.cdf(successes, trials, probability) : jStat.binomial.pdf(successes, trials, probability); }; Formula.BINOMDISTRANGE = function (trials, probability, successes, successes2) { successes2 = (typeof successes2 === 'undefined') ? successes : successes2; var result = 0; for (var i = successes; i <= successes2; i++) { result += Formula.COMBIN(trials, i) * Math.pow(probability, i) * Math.pow(1 - probability, trials - i); } return result; }; Formula.BINOMINV = function (trials, probability, alpha) { var x = 0; while (x <= trials) { if (jStat.binomial.cdf(x, trials, probability) >= alpha) { return x; } x++; } }; Formula.CHISQDIST = function (x, k, cumulative) { return (cumulative) ? jStat.chisquare.cdf(x, k) : jStat.chisquare.pdf(x, k); }; Formula.CHISQDISTRT = function (x, k) { return; }; Formula.CHISQINV = function (probability, k) { return jStat.chisquare.inv(probability, k); }; Formula.CHISQINVRT = function () { return; }; Formula.CHISQTEST = function () { return; }; Formula.CONFIDENCENORM = function (alpha, sd, n) { return jStat.normalci(1, alpha, sd, n)[1] - 1; }; Formula.CONFIDENCET = function (alpha, sd, n) { return jStat.tci(1, alpha, sd, n)[1] - 1; }; Formula.CORREL = function () { return jStat.corrcoeff.apply(this, arguments); }; Formula.COUNT = function () { return Formula.ARGSCONCAT(arguments).length; }; Formula.COUNTA = function () { var range = Formula.ARGSCONCAT(arguments); return range.length - Formula.COUNTBLANK(range); }; Formula.COUNTBLANK = function () { var range = Formula.ARGSCONCAT(arguments); var blanks = 0; for (var i = 0; i < range.length; i++) { if (range[i] === null || range[i] === '') { blanks++; } } return blanks; }; Formula.COUNTIF = function (range, criteria) { var matches = 0; for (var i = 0; i < range.length; i++) { if (range[i].match(new RegExp(criteria))) { matches++; } } return matches; }; Formula.COUNTIFS = function () { var criteria = (arguments.length - 1) / 2; var range = arguments[0]; var result = 0; for (var i = 0; i < range.length; i++) { var fit = true; for (var j = 0; j < criteria; j++) { if (!eval(arguments[2 * j + 1][i] + arguments[2 * j + 2])) { fit = false; } } result += (fit) ? 1 : 0; } return result; }; Formula.COUNTUNIQUE = function () { return _.uniq(Formula.ARGSCONCAT(arguments)).length; }; Formula.COVARIANCEP = function (array1, array2) { var mean1 = jStat.mean(array1); var mean2 = jStat.mean(array2); var result = 0; var n = array1.length; for (var i = 0; i < n; i++) { result += (array1[i] - mean1) * (array2[i] - mean2); } return result / n; }; Formula.COVARIANCES = function () { return jStat.covariance.apply(this, arguments); }; Formula.DEVSQ = function () { var range = Formula.ARGSCONCAT(arguments); var mean = jStat.mean(range); var result = 0; for (var i = 0; i < range.length; i++) { result += Math.pow((range[i] - mean), 2); } return result; }; Formula.EXPONDIST = function (x, lambda, cumulative) { return (cumulative) ? jStat.exponential.cdf(x, lambda) : jStat.exponential.pdf(x, lambda); }; Formula.FDIST = function (x, d1, d2, cumulative) { return (cumulative) ? jStat.centralF.cdf(x, d1, d2) : jStat.centralF.pdf(x, d1, d2); }; Formula.FDISTRT = function () { return; }; Formula.FINV = function (probability, d1, d2) { if (probability <= 0.0 || probability > 1.0) { return '#NUM!'; } return jStat.centralF.inv(1.0 - probability, d1, d2); }; Formula.FINVRT = function () { return; }; Formula.FTEST = function () { return; }; Formula.FISHER = function (x) { return Math.log((1 + x) / (1 - x)) / 2; }; Formula.FISHERINV = function (y) { var e2y = Math.exp(2 * y); return (e2y - 1) / (e2y + 1); }; Formula.FORECAST = function (x, data_y, data_x) { var xmean = jStat.mean(data_x); var ymean = jStat.mean(data_y); var n = data_x.length; var num = 0; var den = 0; for (var i = 0; i < n; i++) { num += (data_x[i] - xmean) * (data_y[i] - ymean); den += Math.pow(data_x[i] - xmean, 2); } var b = num / den; var a = ymean - b * xmean; return a + b * x; }; Formula.FREQUENCY = function (data, bins) { var n = data.length; var b = bins.length; var r = []; for (var i = 0; i <= b; i++) { r[i] = 0; for (var j = 0; j < n; j++) { if (i === 0) { if (data[j] <= bins[0]) { r[0] += 1; } } else if (i < b) { if (data[j] > bins[i - 1] && data[j] <= bins[i]) { r[i] += 1; } } else if (i === b) { if (data[j] > bins[b - 1]) { r[b] += 1; } } } } return r; }; Formula.GAMMA = function () { return jStat.gammafn.apply(this, arguments); }; Formula.GAMMADIST = function (x, alpha, beta, cumulative) { /* var shape = alpha; var scale = 1 / beta; return (cumulative) ? jStat.gamma.cdf(x, shape, scale) : jStat.gamma.pdf(x, shape, scale); */ return; }; Formula.GAMMAINV = function (probability, alpha, beta) { /* var shape = alpha; var scale = 1 / beta; return jStat.gamma.inv(probability, shape, scale); */ return; }; Formula.GAMMALN = function () { return jStat.gammaln.apply(this, arguments); }; Formula.GAMMALNPRECISE = function () { return; }; Formula.GAUSS = function (z) { return jStat.normal.cdf(z, 0, 1) - 0.5; }; Formula.GEOMEAN = function () { return jStat.geomean(Formula.ARGSCONCAT(arguments)); }; Formula.GROWTH = function (known_y, known_x, new_x, use_const) { // Credits: Ilmari Karonen // Default values for optional parameters: var i; if (typeof(known_x) === 'undefined') { known_x = []; for (i = 1; i <= known_y.length; i++) { known_x.push(i); } } if (typeof(new_x) === 'undefined') { new_x = []; for (i = 1; i <= known_y.length; i++) { new_x.push(i); } } if (typeof(use_const) === 'undefined') { use_const = true; } // Calculate sums over the data: var n = known_y.length; var avg_x = 0; var avg_y = 0; var avg_xy = 0; var avg_xx = 0; for (i = 0; i < n; i++) { var x = known_x[i]; var y = Math.log(known_y[i]); avg_x += x; avg_y += y; avg_xy += x * y; avg_xx += x * x; } avg_x /= n; avg_y /= n; avg_xy /= n; avg_xx /= n; // Compute linear regression coefficients: var beta; var alpha; if (use_const) { beta = (avg_xy - avg_x * avg_y) / (avg_xx - avg_x * avg_x); alpha = avg_y - beta * avg_x; } else { beta = avg_xy / avg_xx; alpha = 0; } // Compute and return result array: var new_y = []; for (i = 0; i < new_x.length; i++) { new_y.push(Math.exp(alpha + beta * new_x[i])); } return new_y; }; Formula.HARMEAN = function () { var range = Formula.ARGSCONCAT(arguments); var n = range.length; var den = 0; for (var i = 0; i < n; i++) { den += 1 / range[i]; } return n / den; }; Formula.HYPGEOMDIST = function (x, n, M, N, cumulative) { function pdf(x, n, M, N) { return Formula.COMBIN(M, x) * Formula.COMBIN(N - M, n - x) / Formula.COMBIN(N, n); } function cdf(x, n, M, N) { var result = 0; for (var i = 0; i <= x; i++) { result += pdf(i, n, M, N); } return result; } return (cumulative) ? cdf(x, n, M, N) : pdf(x, n, M, N); }; Formula.INTERCEPT = function (data_y, data_x) { return Formula.FORECAST(0, data_y, data_x); }; Formula.KURT = function () { var range = Formula.ARGSCONCAT(arguments); var mean = jStat.mean(range); var n = range.length; var sigma = 0; for (var i = 0; i < n; i++) { sigma += Math.pow(range[i] - mean, 4); } sigma = sigma / Math.pow(jStat.stdev(range, true), 4); return ((n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3))) * sigma - 3 * (n - 1) * (n - 1) / ((n - 2) * (n - 3)); }; Formula.LARGE = function (array, k) { return array.sort(function (a, b) { return b - a; })[k - 1]; }; Formula.LINEST = function (data_y, data_x) { var xmean = jStat.mean(data_x); var ymean = jStat.mean(data_y); var n = data_x.length; var num = 0; var den = 0; for (var i = 0; i < n; i++) { num += (data_x[i] - xmean) * (data_y[i] - ymean); den += Math.pow(data_x[i] - xmean, 2); } var m = num / den; var b = ymean - m * xmean; return [m, b]; }; Formula.LOGEST = function () { return; }; Formula.LOGNORMDIST = function (x, mean, sd, cumulative) { return (cumulative) ? jStat.lognormal.cdf(x, mean, sd) : jStat.lognormal.pdf(x, mean, sd); }; Formula.LOGNORMINV = function (probability, mean, sd) { return jStat.lognormal.inv(probability, mean, sd); }; Formula.MAX = function () { var range = Formula.ARGSCONCAT(arguments); var n = range.length; var max = (n > 0) ? range[0] : 0; for (var i = 0; i < n; i++) { max = (range[i] > max && (range[i] !== true) && (range[i] !== false)) ? range[i] : max; } return max; }; Formula.MAXA = function () { var range = Formula.ARGSCONCAT(arguments); return (range.length > 0) ? Math.max.apply(Math, range) : 0; }; Formula.MEDIAN = function () { return jStat.median(Formula.ARGSCONCAT(arguments)); }; Formula.MIN = function () { var range = Formula.ARGSCONCAT(arguments); var n = range.length; var min = (n > 0) ? range[0] : 0; for (var i = 0; i < n; i++) { min = (range[i] < min && (range[i] !== true) && (range[i] !== false)) ? range[i] : min; } return min; }; Formula.MINA = function () { var range = Formula.ARGSCONCAT(arguments); return (range.length > 0) ? Math.min.apply(Math, range) : 0; }; Formula.MODEMULT = function () { // Credits: Roönaän var range = Formula.ARGSCONCAT(arguments), n = range.length, count = {}, maxItems = [], max = 0, currentItem; for (var i = 0; i < n; i++) { currentItem = range[i]; count[currentItem] = count[currentItem] ? count[currentItem] + 1 : 1; if (count[currentItem] > max) { max = count[currentItem]; maxItems = []; } if (count[currentItem] === max) { maxItems[maxItems.length] = currentItem; } } return maxItems; }; Formula.MODESNGL = function () { return Formula.MODEMULT(Formula.ARGSCONCAT(arguments)).sort(function (a, b) { return a - b; })[0]; }; Formula.NEGBINOMDIST = function (k, r, p, cumulative) { return (cumulative) ? jStat.negbin.cdf(k, r, p) : jStat.negbin.pdf(k, r, p); }; Formula.NORMDIST = function (x, mean, sd, cumulative) { // Check parameters if (isNaN(x) || isNaN(mean) || isNaN(sd)) { return '#VALUE!'; } if (sd <= 0) { return '#NUM!'; } // Return normal distribution computed by jStat [http://jstat.org] return (cumulative) ? jStat.normal.cdf(x, mean, sd) : jStat.normal.pdf(x, mean, sd); }; Formula.NORMINV = function (probability, mean, sd) { return jStat.normal.inv(probability, mean, sd); }; Formula.NORMSDIST = function (z, cumulative) { return (cumulative) ? jStat.normal.cdf(z, 0, 1) : jStat.normal.pdf(z, 0, 1); }; Formula.NORMSINV = function (probability) { return jStat.normal.inv(probability, 0, 1); }; Formula.PEARSON = function (data_x, data_y) { var xmean = jStat.mean(data_x); var ymean = jStat.mean(data_y); var n = data_x.length; var num = 0; var den1 = 0; var den2 = 0; for (var i = 0; i < n; i++) { num += (data_x[i] - xmean) * (data_y[i] - ymean); den1 += Math.pow(data_x[i] - xmean, 2); den2 += Math.pow(data_y[i] - ymean, 2); } return num / Math.sqrt(den1 * den2); }; Formula.PERCENTILEEXC = function (array, k) { array = array.sort(function (a, b) { { return a - b; } }); var n = array.length; if (k < 1 / (n + 1) || k > 1 - 1 / (n + 1)) { return '#NUM!'; } var l = k * (n + 1) - 1; var fl = Math.floor(l); return Formula.CLEANFLOAT((l === fl) ? array[l] : array[fl] + (l - fl) * (array[fl + 1] - array[fl])); }; Formula.PERCENTILEINC = function (array, k) { array = array.sort(function (a, b) { return a - b; }); var n = array.length; var l = k * (n - 1); var fl = Math.floor(l); return Formula.CLEANFLOAT((l === fl) ? array[l] : array[fl] + (l - fl) * (array[fl + 1] - array[fl])); }; Formula.PERCENTRANKEXC = function (array, x, significance) { array = array.sort(function (a, b) { return a - b; }); var uniques = _.uniq(array); var n = array.length; var m = uniques.length; significance = (typeof significance === 'undefined') ? 3 : significance; var power = Math.pow(10, significance); var result = 0; var match = false; var i = 0; while (!match && i < m) { if (x === uniques[i]) { result = (array.indexOf(uniques[i]) + 1) / (n + 1); match = true; } else if (x >= uniques[i] && (x < uniques[i + 1] || i === m - 1)) { result = (array.indexOf(uniques[i]) + 1 + (x - uniques[i]) / (uniques[i + 1] - uniques[i])) / (n + 1); match = true; } i++; } return Math.floor(result * power) / power; }; Formula.PERCENTRANKINC = function (array, x, significance) { array = array.sort(function (a, b) { return a - b; }); var uniques = _.uniq(array); var n = array.length; var m = uniques.length; significance = (typeof significance === 'undefined') ? 3 : significance; var power = Math.pow(10, significance); var result = 0; var match = false; var i = 0; while (!match && i < m) { if (x === uniques[i]) { result = array.indexOf(uniques[i]) / (n - 1); match = true; } else if (x >= uniques[i] && (x < uniques[i + 1] || i === m - 1)) { result = (array.indexOf(uniques[i]) + (x - uniques[i]) / (uniques[i + 1] - uniques[i])) / (n - 1); match = true; } i++; } return Math.floor(result * power) / power; }; Formula.PERMUT = function (number, number_chosen) { return Formula.FACT(number) / Formula.FACT(number - number_chosen); }; Formula.PERMUTATIONA = function (number, number_chosen) { return Math.pow(number, number_chosen); }; Formula.PHI = function (x) { return Math.exp(-0.5 * x * x) / SQRT2PI; }; Formula.POISSONDIST = function (x, mean, cumulative) { return (cumulative) ? jStat.poisson.cdf(x, mean) : jStat.poisson.pdf(x, mean); }; Formula.PROB = function (range, probability, lower, upper) { if (typeof lower === 'undefined') { return 0; } upper = (typeof upper === 'undefined') ? lower : upper; if (lower === upper) { return (range.indexOf(lower) >= 0) ? probability[range.indexOf(lower)] : 0; } var sorted = range.sort(function (a, b) { return a - b; }); var n = sorted.length; var result = 0; for (var i = 0; i < n; i++) { if (sorted[i] >= lower && sorted[i] <= upper) { result += probability[range.indexOf(sorted[i])]; } } return result; }; Formula.QUARTILEEXC = function (range, quart) { switch (quart) { case 1: return Formula.PERCENTILEEXC(range, 0.25); case 2: return Formula.PERCENTILEEXC(range, 0.5); case 3: return Formula.PERCENTILEEXC(range, 0.75); default: return '#NUM!'; } }; Formula.QUARTILEINC = function (range, quart) { switch (quart) { case 1: return Formula.PERCENTILEINC(range, 0.25); case 2: return Formula.PERCENTILEINC(range, 0.5); case 3: return Formula.PERCENTILEINC(range, 0.75); default: return '#NUM!'; } }; Formula.RANKAVG = function (number, range, order) { order = (typeof order === 'undefined') ? false : order; var sort = (order) ? function (a, b) { return a - b; } : function (a, b) { return b - a; }; range = range.sort(sort); var count = Formula.COUNTIN(range, number); return (count > 1) ? (2 * range.indexOf(number) + count + 1) / 2 : range.indexOf(number) + 1; }; Formula.RANKEQ = function (number, range, order) { order = (typeof order === 'undefined') ? false : order; var sort = (order) ? function (a, b) { return a - b; } : function (a, b) { return b - a; }; range = range.sort(sort); return range.indexOf(number) + 1; }; Formula.RSQ = function (data_x, data_y) { return Math.pow(Formula.PEARSON(data_x, data_y), 2); }; Formula.SKEW = function () { var range = Formula.ARGSCONCAT(arguments); var mean = jStat.mean(range); var n = range.length; var sigma = 0; for (var i = 0; i < n; i++) { sigma += Math.pow(range[i] - mean, 3); } return n * sigma / ((n - 1) * (n - 2) * Math.pow(jStat.stdev(range, true), 3)); }; Formula.SKEWP = function () { var range = Formula.ARGSCONCAT(arguments); var mean = jStat.mean(range); var n = range.length; var m2 = 0; var m3 = 0; for (var i = 0; i < n; i++) { m3 += Math.pow(range[i] - mean, 3); m2 += Math.pow(range[i] - mean, 2); } m3 = m3 / n; m2 = m2 / n; return m3 / Math.pow(m2, 3 / 2); }; Formula.SLOPE = function (data_y, data_x) { var xmean = jStat.mean(data_x); var ymean = jStat.mean(data_y); var n = data_x.length; var num = 0; var den = 0; for (var i = 0; i < n; i++) { num += (data_x[i] - xmean) * (data_y[i] - ymean); den += Math.pow(data_x[i] - xmean, 2); } return num / den; }; Formula.SMALL = function (array, k) { return array.sort(function (a, b) { return a - b; })[k - 1]; }; Formula.STANDARDIZE = function (x, mean, sd) { return (x - mean) / sd; }; Formula.STDEVA = function () { var range = Formula.ARGSCONCAT(arguments); var n = range.length; var sigma = 0; var mean = jStat.mean(range); for (var i = 0; i < n; i++) { sigma += Math.pow(range[i] - mean, 2); } return Math.sqrt(sigma / (n - 1)); }; Formula.STDEVP = function () { var range = Formula.ARGSCONCAT(arguments); var n = range.length; var sigma = 0; var count = 0; var mean = Formula.AVERAGE(range); for (var i = 0; i < n; i++) { if (range[i] !== true && range[i] !== false) { sigma += Math.pow(range[i] - mean, 2); count++; } } return Math.sqrt(sigma / count); }; Formula.STDEVPA = function () { var range = Formula.ARGSCONCAT(arguments); var n = range.length; var sigma = 0; var mean = jStat.mean(range); for (var i = 0; i < n; i++) { sigma += Math.pow(range[i] - mean, 2); } return Math.sqrt(sigma / n); }; Formula.STDEVS = function () { var range = Formula.ARGSCONCAT(arguments); var n = range.length; var sigma = 0; var count = 0; var mean = Formula.AVERAGE(range); for (var i = 0; i < n; i++) { if (range[i] !== true && range[i] !== false) { sigma += Math.pow(range[i] - mean, 2); count++; } } return Math.sqrt(sigma / (count - 1)); }; Formula.STEYX = function (data_y, data_x) { var xmean = jStat.mean(data_x); var ymean = jStat.mean(data_y); var n = data_x.length; var lft = 0; var num = 0; var den = 0; for (var i = 0; i < n; i++) { lft += Math.pow(data_y[i] - ymean, 2); num += (data_x[i] - xmean) * (data_y[i] - ymean); den += Math.pow(data_x[i] - xmean, 2); } return Math.sqrt((lft - num * num / den) / (n - 2)); }; Formula.TDIST = function (x, df, cumulative) { return (cumulative) ? jStat.studentt.cdf(x, df) : jStat.studentt.pdf(x, df); }; Formula.TDIST2T = function () { return; }; Formula.TDISTRT = function () { return; }; Formula.TINV = function (probability, df) { return jStat.studentt.inv(probability, df); }; Formula.TINV2T = function () { return; }; Formula.TTEST = function () { return; }; Formula.TREND = function () { return; }; Formula.TRIMMEAN = function (range, percent) { var n = range.length; var trim = Formula.FLOOR(range.length * percent, 2) / 2; return jStat.mean(_.initial(_.rest(range.sort(function (a, b) { return a - b; }), trim), trim)); }; Formula.VARA = function () { var range = Formula.ARGSCONCAT(arguments); var n = range.length; var sigma = 0; var mean = jStat.mean(range); for (var i = 0; i < n; i++) { sigma += Math.pow(range[i] - mean, 2); } return sigma / (n - 1); }; Formula.VARP = function () { var range = Formula.ARGSCONCAT(arguments); var n = range.length; var sigma = 0; var count = 0; var mean = Formula.AVERAGE(range); for (var i = 0; i < n; i++) { if (range[i] !== true && range[i] !== false) { sigma += Math.pow(range[i] - mean, 2); count++; } } return sigma / count; }; Formula.VARPA = function () { var range = Formula.ARGSCONCAT(arguments); var n = range.length; var sigma = 0; var mean = jStat.mean(range); for (var i = 0; i < n; i++) { sigma += Math.pow(range[i] - mean, 2); } return sigma / n; }; Formula.VARS = function () { var range = Formula.ARGSCONCAT(arguments); var n = range.length; var sigma = 0; var count = 0; var mean = Formula.AVERAGE(range); for (var i = 0; i < n; i++) { if (range[i] !== true && range[i] !== false) { sigma += Math.pow(range[i] - mean, 2); count++; } } return sigma / (count - 1); }; Formula.WEIBULLDIST = function (x, alpha, beta, cumulative) { return (cumulative) ? 1 - Math.exp(-Math.pow(x / beta, alpha)) : Math.pow(x, alpha - 1) * Math.exp(-Math.pow(x / beta, alpha)) * alpha / Math.pow(beta, alpha); }; Formula.ZTEST = function (range, x, sigma) { var n = range.length; var sd = (typeof sigma === 'undefined') ? Formula.STDEVS(range) : sigma; return 1 - Formula.NORMSDIST((Formula.AVERAGE(range) - x) / (sd / Math.sqrt(n)), Formula.TRUE); }; // Text functions Formula.CHAR = function (number) { return String.fromCharCode(number); }; Formula.CLEAN = function (text) { var re = /[\0-\x1F]/g; return text.replace(re, ""); }; Formula.CODE = function (text) { return text.charCodeAt(0); }; Formula.CONCATENATE = function () { var string = ''; for (var i = 0; i < arguments.length; i++) { if (arguments[i] !== null && arguments[i] !== undefined) { string += arguments[i]; } } return string; }; Formula.DOLLAR = function (number, decimals) { decimals = (typeof decimals === 'undefined') ? 2 : decimals; var format = ''; if (decimals <= 0) { number = Math.round(number * Math.pow(10, decimals)) / Math.pow(10, decimals); format = '($0,0)'; } else if (decimals > 0) { format = '($0,0.' + new Array(decimals + 1).join('0') + ')'; } return numeral(number).format(format); }; Formula.EXACT = function (text1, text2) { return text1 === text2; }; Formula.FIND = function (find_text, within_text, position) { position = (typeof position === 'undefined') ? 0 : position; return within_text ? within_text.indexOf(find_text, position - 1) + 1 : null; }; Formula.FIXED = function (number, decimals, no_commas) { decimals = (typeof decimals === 'undefined') ? 2 : decimals; no_commas = (typeof no_commas === 'undefined') ? false : no_commas; var format = no_commas ? '0' : '0,0'; if (decimals <= 0) { number = Math.round(number * Math.pow(10, decimals)) / Math.pow(10, decimals); } else if (decimals > 0) { format += '.' + new Array(decimals + 1).join('0'); } return numeral(number).format(format); }; Formula.HTML2TEXT = function (value) { var result = ''; if (value) { if (value instanceof Array) { value.forEach(function (line) { if (result !== '') { result += '\n'; } result += (line.replace(/<(?:.|\n)*?>/gm, '')); }); } else { result = value.replace(/<(?:.|\n)*?>/gm, ''); } } return result; }; Formula.HUMANIZE = function (value) { if (value instanceof Date) { var dvalue = moment(value); if (dvalue.hours() || dvalue.minutes() || dvalue.seconds()) { return dvalue.format("dddd, MMMM Do YYYY, h:mm:ss"); } else { return dvalue.format("dddd, MMMM Do YYYY"); } } return value; }; Formula.JOIN = function (array, separator) { return array.join(separator); }; Formula.LEFT = function (text, number) { number = (typeof number === 'undefined') ? 1 : number; return text ? text.substring(0, number) : null; }; Formula.LEN = function (text) { return text ? text.length : 0; }; Formula.LOWER = function (text) { return text ? text.toLowerCase() : text; }; Formula.MID = function (text, start, number) { return text.substring(start - 1, number); }; Formula.NUMBERVALUE = function (text, decimal_separator, group_separator) { decimal_separator = (typeof decimal_separator === 'undefined') ? '.' : decimal_separator; group_separator = (typeof group_separator === 'undefined') ? ',' : group_separator; return Number(text.replace(decimal_separator, '.').replace(group_separator, '')); }; Formula.PROPER = function (text) { return text.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); }); }; Formula.REGEXEXTRACT = function (text, regular_expression) { var match = text.match(new RegExp(regular_expression)); console.log(match); return match ? (match[match.length > 1 ? match.length - 1 : 0]) : null; }; Formula.REGEXMATCH = function (text, regular_expression, full) { var match = text.match(new RegExp(regular_expression)); return full ? match : !!match; }; Formula.REGEXREPLACE = function (text, regular_expression, replacement) { return text.replace(new RegExp(regular_expression), replacement); }; Formula.REPLACE = function (text, position, length, new_text) { return text.substr(0, position - 1) + new_text + text.substr(position - 1 + length); }; Formula.REPT = function (text, number) { return new Array(number + 1).join(text); }; Formula.RIGHT = function (text, number) { number = (typeof number === 'undefined') ? 1 : number; return text ? text.substring(text.length - number) : null; }; Formula.ROMAN = function (number) { // The MIT License // Copyright (c) 2008 Steven Levithan var digits = String(number).split(''); var key = ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX']; var roman = ''; var i = 3; while (i--) { roman = (key[+digits.pop() + (i * 10)] || '') + roman; } return new Array(+digits.join('') + 1).join('M') + roman; }; Formula.SEARCH = function (find_text, within_text, position) { position = (typeof position === 'undefined') ? 0 : position; return within_text.toLowerCase().indexOf(find_text.toLowerCase(), position - 1) + 1; }; Formula.SPLIT = function (text, separator) { return _s.words(text, separator); }; Formula.SUBSTITUTE = function (text, old_text, new_text, occurrence) { if (!text || !old_text || !new_text) { return text; } else if (typeof occurrence === 'undefined') { return text.replace(new RegExp(old_text, 'g'), new_text); } else { var index = 0; var i = 0; while (text.indexOf(old_text, index) > 0) { index = text.indexOf(old_text, index + 1); i++; if (i === occurrence) { return text.substring(0, index) + new_text + text.substring(index + old_text.length); } } } }; Formula.T = function (value) { return (typeof value === "string") ? value : null; }; Formula.TEXT = function (value, format) { var text = ''; if (value) { if (value instanceof Object) { try { text = JSON.stringify(value); } catch (err) { // ignore } } else if (typeof value === 'string') { if (format) { text = (format.indexOf('0') >= 0) ? numeral(value).format(format) : moment(new Date(value)).format(format); } else { text = value; } } else if (value.toString && typeof value.toString === 'function') { text = value.toString(); } } return text; }; Formula.TRIM = function (text) { return _s.clean(text); }; Formula.UNICHAR = Formula.CHAR; Formula.UNICODE = Formula.CODE; Formula.UPPER = function (text) { return text.toUpperCase(); }; Formula.VALUE = function (text) { return numeral().unformat(text); }; // Hashing function Formula.MD5 = function (data, key, raw) { return md5(data, key, raw); }; Formula.NUMERAL = function (number, format) { return numeral(number).format(format); }; // Excel Error Handling Formula.ISERR = function (value) { return value === '#VALUE!' || value === '#REF!' || value === '#DIV/0!' || value === '#NUM!' || value === '#NAME?' || value === '#NULL!'; }; Formula.ISERROR = function (value) { return Formula.ISERR(value) || value === '#N/A'; }; Formula.IFERROR = function (value, valueIfError) { if (Formula.ISERROR(value)) { return valueIfError; } return value; }; return Formula; } }).call(this);
check for isNaN too
lib/formula.js
check for isNaN too
<ide><path>ib/formula.js <ide> value === '#DIV/0!' || <ide> value === '#NUM!' || <ide> value === '#NAME?' || <del> value === '#NULL!'; <add> value === '#NULL!' || <add> isNaN(value); <ide> }; <ide> <ide> Formula.ISERROR = function (value) {
Java
mpl-2.0
ed95229714ed11360066d7525605a6a03f753283
0
richardwilkes/gcs,richardwilkes/gcs
/* * Copyright ©1998-2021 by Richard A. Wilkes. All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, version 2.0. If a copy of the MPL was not distributed with * this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This Source Code Form is "Incompatible With Secondary Licenses", as * defined by the Mozilla Public License, version 2.0. */ package bundler; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.lang.ProcessBuilder.Redirect; import java.nio.charset.StandardCharsets; import java.nio.file.FileVisitOption; import java.nio.file.FileVisitResult; import java.nio.file.FileVisitor; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.EnumSet; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Stream; public final class Bundler { private static final String GCS_VERSION = "4.34.2"; private static final String JDK_MAJOR_VERSION = "17"; private static final String LINUX = "linux"; private static final String MACOS = "macos"; private static final String WINDOWS = "windows"; private static final Path DIST_DIR = Path.of("out", "dist"); private static final Path BUILD_DIR = DIST_DIR.resolve("build"); private static final Path MODULE_DIR = DIST_DIR.resolve("modules"); private static final Path EXTRA_DIR = DIST_DIR.resolve("extra"); private static final Path I18N_DIR = EXTRA_DIR.resolve("i18n"); private static final Path MANIFEST = BUILD_DIR.resolve("com.trollworks.gcs.manifest"); private static final Path JRE = BUILD_DIR.resolve("jre"); private static final String YEARS = "1998-" + DateTimeFormatter.ofPattern("yyyy").format(Instant.now().atZone(ZoneId.systemDefault())); private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; private static String OS; private static Path PKG; private static Path NO_INSTALLER_PKG; private static String ICON_TYPE; private Bundler() { } /** * The main entry point for bundling GCS. * * @param args Arguments to the program. */ public static void main(String[] args) { checkPlatform(); boolean sign = false; boolean notarize = false; boolean noInstaller = false; for (String arg : args) { if (MACOS.equals(OS)) { if ("-s".equals(arg) || "--sign".equals(arg)) { if (!sign) { sign = true; System.out.println("Signing enabled"); } continue; } if ("-n".equals(arg) || "--notarize".equals(arg)) { if (!notarize) { notarize = true; System.out.println("Notarization enabled"); } continue; } } if ("-u".equals(arg) || "--unpackaged".equals(arg)) { if (!noInstaller) { noInstaller = true; System.out.println("Will not package the application for distribution"); } continue; } if ("-h".equals(arg) || "--help".equals(arg)) { System.out.println("-h, --help This help"); System.out.println("-n, --notarize Enable notarization of the application (macOS only)"); System.out.println("-s, --sign Enable signing of the application (macOS only)"); System.out.println("-u, --unpackaged Don't package the app into a platform-specific installer"); System.exit(0); } System.out.println("Ignoring argument: " + arg); } if (noInstaller && (sign || notarize)) { System.out.println("--unpackaged is not compatible with --sign or --notarize"); System.exit(1); } checkJDK(); prepareDirs(); compile(); copyResources(); createModules(); extractLocalizationTemplate(); packageApp(noInstaller, sign); if (notarize) { notarizeApp(); } System.out.println("Finished!"); System.out.println(); System.out.println("Package can be found at:"); if (noInstaller) { System.out.println(NO_INSTALLER_PKG.toAbsolutePath()); } else { System.out.println(PKG.toAbsolutePath()); } } private static void checkPlatform() { String osName = System.getProperty("os.name"); if (osName.startsWith("Mac")) { OS = MACOS; PKG = Path.of("GCS-" + GCS_VERSION + ".dmg"); NO_INSTALLER_PKG = Path.of("GCS.app"); ICON_TYPE = "icns"; } else if (osName.startsWith("Win")) { OS = WINDOWS; PKG = Path.of("GCS-" + GCS_VERSION + ".msi"); NO_INSTALLER_PKG = Path.of("GCS"); ICON_TYPE = "ico"; } else if (osName.startsWith("Linux")) { OS = LINUX; PKG = Path.of("gcs-" + GCS_VERSION + "-1_amd64.deb"); NO_INSTALLER_PKG = Path.of("gcs"); ICON_TYPE = "png"; } else { System.err.println("Unsupported platform: " + osName); System.exit(1); } } private static void checkJDK() { ProcessBuilder builder = new ProcessBuilder("javac", "--version"); builder.redirectOutput(Redirect.PIPE).redirectErrorStream(true); try { String versionLine = ""; Process process = builder.start(); try (BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) { String prefix = "javac "; String line; while ((line = in.readLine()) != null) { if (line.startsWith(prefix)) { versionLine = line.substring(prefix.length()); } } } if (!versionLine.startsWith(JDK_MAJOR_VERSION)) { System.err.println("JDK " + versionLine + " was found. JDK " + JDK_MAJOR_VERSION + " is required."); emitInstallJDKMessageAndExit(); } } catch (IOException exception) { System.err.println("JDK " + JDK_MAJOR_VERSION + " is not installed!"); emitInstallJDKMessageAndExit(); } } private static void emitInstallJDKMessageAndExit() { System.err.println("Install JDK " + JDK_MAJOR_VERSION + " from http://jdk.java.net/" + JDK_MAJOR_VERSION + "/ and try again."); System.exit(1); } private static void prepareDirs() { System.out.print("Removing any previous build data... "); System.out.flush(); long timing = System.nanoTime(); try { if (Files.exists(DIST_DIR)) { Files.walkFileTree(DIST_DIR, new RecursiveDirectoryRemover()); } Files.createDirectories(DIST_DIR); Files.createDirectories(BUILD_DIR); Files.createDirectories(MODULE_DIR); Files.createDirectories(EXTRA_DIR); Files.createDirectories(I18N_DIR); Files.deleteIfExists(PKG); if (Files.exists(NO_INSTALLER_PKG)) { Files.walkFileTree(NO_INSTALLER_PKG, new RecursiveDirectoryRemover()); } } catch (IOException exception) { System.out.println(); exception.printStackTrace(System.err); System.exit(1); } showTiming(timing); } private static void showTiming(long timing) { System.out.printf("%,.3fs\n", Double.valueOf((System.nanoTime() - timing) / 1000000000.0)); } private static void compile() { System.out.print("Compiling... "); System.out.flush(); long timing = System.nanoTime(); Path javacInput = BUILD_DIR.resolve("javac.input"); try (PrintWriter out = new PrintWriter(Files.newBufferedWriter(javacInput))) { out.println("-d"); out.println(BUILD_DIR); out.println("--release"); out.println(JDK_MAJOR_VERSION); out.println("-encoding"); out.println("UTF8"); out.println("--module-source-path"); out.printf(".%1$s*%1$ssrc%2$sthird_party%1$s*%1$ssrc\n", File.separator, File.pathSeparator); FileScanner.walk(Path.of("."), (path) -> { if (path.getFileName().toString().endsWith(".java") && !path.startsWith(Path.of(".", "bundler"))) { out.println(path); } }); } catch (IOException exception) { System.out.println(); exception.printStackTrace(System.err); System.exit(1); } runNoOutputCmd("javac", "@" + javacInput); showTiming(timing); } private static void copyResources() { System.out.print("Copying resources... "); System.out.flush(); long timing = System.nanoTime(); copyResourceTree(Path.of("com.trollworks.gcs", "resources"), BUILD_DIR.resolve("com.trollworks.gcs")); showTiming(timing); } private static void copyResourceTree(Path src, Path dst) { FileScanner.walk(src, (path) -> { Path target = dst.resolve(src.relativize(path)); Files.createDirectories(target.getParent()); try (InputStream in = Files.newInputStream(path)) { try (OutputStream out = Files.newOutputStream(target)) { byte[] data = new byte[8192]; int amt; while ((amt = in.read(data)) != -1) { out.write(data, 0, amt); } } } }); } private static void createModules() { System.out.print("Creating modules... "); System.out.flush(); long timing = System.nanoTime(); createManifest(); List<String> args = new ArrayList<>(); args.add("jar"); args.add("--create"); args.add("--file"); args.add(MODULE_DIR.resolve("com.trollworks.gcs-" + GCS_VERSION + ".jar").toString()); args.add("--module-version"); args.add(GCS_VERSION); args.add("--manifest"); args.add(MANIFEST.toString()); args.add("--main-class"); args.add("com.trollworks.gcs.GCS"); args.add("-C"); args.add(BUILD_DIR.resolve("com.trollworks.gcs").toString()); args.add("."); runNoOutputCmd(args); showTiming(timing); } private static void createManifest() { try (PrintWriter out = new PrintWriter(Files.newBufferedWriter(MANIFEST))) { out.println("Manifest-Version: 1.0"); out.println("bundle-name: GCS"); out.println("bundle-version: " + GCS_VERSION); out.println("bundle-license: Mozilla Public License 2.0"); out.println("bundle-copyright-owner: Richard A. Wilkes"); out.println("bundle-copyright-years: " + YEARS); } catch (IOException exception) { System.out.println(); exception.printStackTrace(System.err); System.exit(1); } } private static void extractLocalizationTemplate() { System.out.print("Extracting localization template... "); System.out.flush(); long timing = System.nanoTime(); Set<String> keys = new HashSet<>(); try (Stream<Path> srcTree = Files.walk(Path.of("com.trollworks.gcs", "src"))) { srcTree.filter(path -> { String lower = path.getFileName().toString().toLowerCase(); return lower.endsWith(".java") && !lower.endsWith("i18n.java") && Files.isRegularFile(path) && Files.isReadable(path); }).distinct().forEach(path -> { try (Stream<String> lines = Files.lines(path)) { lines.forEachOrdered(line -> { while (!line.isEmpty()) { boolean needContext = true; String lookFor = "I18n.text("; int i = line.indexOf(lookFor); if (i >= 0) { needContext = false; } else { lookFor = "I18n.textWithContext("; i = line.indexOf(lookFor); if (i < 0) { break; } } int max = line.length(); i = skipSpace(i + lookFor.length(), max, line); if (i >= max) { break; } if (needContext) { char ch = line.charAt(i); if (ch < '0' || ch > '9') { break; } i = skipSpace(i + 1, max, line); if (i >= max || line.charAt(i) != ',') { break; } i = skipSpace(i + 1, max, line); if (i >= max) { break; } } if (line.charAt(i) != '"') { break; } i++; line = processLine(keys, line.substring(i)); } }); } catch (IOException ioe) { System.out.println(); ioe.printStackTrace(System.err); System.exit(1); } }); try (PrintStream out = new PrintStream(Files.newOutputStream(I18N_DIR.resolve("template.i18n")), true, StandardCharsets.UTF_8)) { out.println("# Generated on " + ZonedDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME)); out.println("#"); out.println("# This file consists of UTF-8 text. Do not save it as anything else."); out.println("#"); out.println("# Key-value pairs are defined as one or more lines prefixed with 'k:' for the"); out.println("# key, followed by one or more lines prefixed with 'v:' or 'v#:', where # is a"); out.println("# digit (0-9), for the value. These prefixes are then followed by a quoted"); out.println("# string, as generated by Text.quote(). When two or more lines with the same"); out.println("# prefix are present in a row, they will be concatenated together with an"); out.println("# intervening \\n character."); out.println("#"); out.println("# Do NOT modify the 'k' values. They are the values as seen in the code."); out.println("#"); out.println("# Replace the 'v' values with the appropriate translation."); out.println("#"); out.println("# 'v' values followed by a digit are for variations on the same english word"); out.println("# that may be needed for other languages, depending on context. You will need"); out.println("# to seek these out in the code to determine which alternate is used where."); out.println("# By default, no keys use alternates. Only those that were specifically"); out.println("# requested by a translator and the code has been adjusted to request them"); out.println("# via a context value will be used."); keys.stream().sorted().forEachOrdered(key -> { out.println(); String quoted = quote(key); if (quoted.length() < 77) { out.println("k:" + quoted); out.println("v:" + quoted); } else { String[] parts = key.split("\n", -1); for (String part : parts) { out.println("k:" + quote(part)); } for (String part : parts) { out.println("v:" + quote(part)); } } }); } } catch (Exception ex) { System.out.println(); ex.printStackTrace(System.err); System.exit(1); } showTiming(timing); } private static int skipSpace(int i, int max, String line) { while (i < max) { char ch = line.charAt(i); if (ch != ' ' && ch != '\t') { break; } i++; } return i; } private static String processLine(Set<String> keys, String in) { StringBuilder buffer = new StringBuilder(); int len = in.length(); int state = 0; int unicodeValue = 0; for (int i = 0; i < len; i++) { char ch = in.charAt(i); switch (state) { case 0: // Looking for end quote if (ch == '"') { keys.add(buffer.toString()); return in.substring(i + 1); } if (ch == '\\') { state = 1; continue; } buffer.append(ch); break; case 1: // Processing escape sequence switch (ch) { case 't' -> { buffer.append('\t'); state = 0; } case 'b' -> { buffer.append('\b'); state = 0; } case 'n' -> { buffer.append('\n'); state = 0; } case 'r' -> { buffer.append('\r'); state = 0; } case '"' -> { buffer.append('"'); state = 0; } case '\\' -> { buffer.append('\\'); state = 0; } case 'u' -> { state = 2; unicodeValue = 0; } default -> { System.out.println(); new RuntimeException("invalid escape sequence").printStackTrace(System.err); System.exit(1); } } break; case 2: // Processing first digit of unicode escape sequence case 3: // Processing second digit of unicode escape sequence case 4: // Processing third digit of unicode escape sequence case 5: // Processing fourth digit of unicode escape sequence if (!isHexDigit(ch)) { System.out.println(); new RuntimeException("invalid unicode escape sequence").printStackTrace(System.err); System.exit(1); } unicodeValue *= 16; unicodeValue += hexDigitValue(ch); if (state == 5) { state = 0; buffer.append((char) unicodeValue); } else { state++; } break; default: System.out.println(); new RuntimeException("invalid state").printStackTrace(System.err); System.exit(1); break; } } return ""; } private static boolean isHexDigit(char ch) { return ch >= '0' && ch <= '9' || ch >= 'a' && ch <= 'f' || ch >= 'A' && ch <= 'F'; } private static int hexDigitValue(char ch) { if (ch >= '0' && ch <= '9') { return ch - '0'; } if (ch >= 'a' && ch <= 'f') { return 10 + ch - 'a'; } if (ch >= 'A' && ch <= 'F') { return 10 + ch - 'A'; } return 0; } private static String quote(String in) { StringBuilder buffer = new StringBuilder(); int length = in.length(); buffer.append('"'); for (int i = 0; i < length; i++) { char ch = in.charAt(i); if (ch == '"' || ch == '\\') { buffer.append('\\'); buffer.append(ch); } else if (isPrintableChar(ch)) { buffer.append(ch); } else { switch (ch) { case '\b' -> buffer.append("\\b"); case '\f' -> buffer.append("\\f"); case '\n' -> buffer.append("\\n"); case '\r' -> buffer.append("\\r"); case '\t' -> buffer.append("\\t"); default -> { buffer.append("\\u"); buffer.append(HEX_DIGITS[ch >> 12 & 0xF]); buffer.append(HEX_DIGITS[ch >> 8 & 0xF]); buffer.append(HEX_DIGITS[ch >> 4 & 0xF]); buffer.append(HEX_DIGITS[ch & 0xF]); } } } } buffer.append('"'); return buffer.toString(); } private static boolean isPrintableChar(char ch) { if (!Character.isISOControl(ch) && Character.isDefined(ch)) { try { Character.UnicodeBlock block = Character.UnicodeBlock.of(ch); return block != null && block != Character.UnicodeBlock.SPECIALS; } catch (Exception ex) { return false; } } return false; } private static void packageApp(boolean noInstaller, boolean sign) { System.out.print("Packaging the application... "); System.out.flush(); long timing = System.nanoTime(); List<String> args = new ArrayList<>(); args.add("jlink"); args.add("--module-path"); args.add(MODULE_DIR.toString()); args.add("--output"); args.add(JRE.toString()); args.add("--no-header-files"); args.add("--no-man-pages"); args.add("--strip-debug"); args.add("--strip-native-commands"); args.add("--add-modules"); args.add("com.trollworks.gcs"); runNoOutputCmd(args); args.clear(); args.add("jpackage"); args.add("--module"); args.add("com.trollworks.gcs/com.trollworks.gcs.GCS"); args.add("--app-version"); args.add(GCS_VERSION); args.add("--copyright"); args.add("©" + YEARS + " by Richard A. Wilkes"); args.add("--vendor"); args.add("Richard A. Wilkes"); args.add("--description"); args.add("GCS (GURPS Character Sheet) is a stand-alone, interactive, character sheet editor that allows you to build characters for the GURPS 4th Edition roleplaying game system."); args.add("--icon"); args.add(Path.of("artifacts", ICON_TYPE, "app." + ICON_TYPE).toString()); if (OS.equals(MACOS) || !noInstaller) { for (String ext : new String[]{"adm", "adq", "eqm", "eqp", "gcs", "gct", "not", "skl", "spl"}) { args.add("--file-associations"); args.add(Path.of("artifacts", "file_associations", OS, ext + "_ext.properties").toString()); } } args.add("--input"); args.add(EXTRA_DIR.toString()); args.add("--runtime-image"); args.add(JRE.toString()); args.add("--java-options"); args.add("-Dhttps.protocols=TLSv1.2,TLSv1.1,TLSv1"); if (noInstaller) { args.add("--type"); args.add("app-image"); } switch (OS) { case MACOS -> { args.add("--java-options"); args.add("-Dapple.awt.application.appearance=system"); args.add("--mac-package-name"); args.add("GCS"); args.add("--mac-package-identifier"); args.add("com.trollworks.gcs"); if (sign) { args.add("--mac-sign"); args.add("--mac-signing-key-user-name"); args.add("Richard Wilkes"); } } case LINUX -> { if (!noInstaller) { args.add("--linux-package-name"); args.add("gcs"); args.add("--linux-deb-maintainer"); args.add("[email protected]"); args.add("--linux-menu-group"); args.add("Game;Utility;RolePlaying"); args.add("--linux-app-category"); args.add("games"); args.add("--linux-rpm-license-type"); args.add("MPLv2.0"); args.add("--linux-shortcut"); args.add("--linux-app-release"); args.add("1"); args.add("--linux-package-deps"); args.add(""); } } case WINDOWS -> { args.add("--java-options"); args.add("-Dsun.java2d.dpiaware=false"); args.add("--java-options"); args.add("-Dsun.java2d.d3d=false"); if (!noInstaller) { args.add("--win-menu"); args.add("--win-menu-group"); args.add("Roleplaying"); args.add("--win-shortcut"); args.add("--type"); args.add("msi"); args.add("--win-dir-chooser"); args.add("--win-upgrade-uuid"); args.add("E71F99DA-AD84-4E6E-9bE7-4E65421752E1"); } } } runNoOutputCmd(args); showTiming(timing); } private static void notarizeApp() { System.out.print("Notarizing the application... "); System.out.flush(); long timing = System.nanoTime(); List<String> args = new ArrayList<>(); args.add("xcrun"); args.add("altool"); args.add("--notarize-app"); args.add("--type"); args.add("osx"); args.add("--file"); args.add(PKG.toAbsolutePath().toString()); args.add("--primary-bundle-id"); args.add("com.trollworks.gcs"); args.add("--username"); args.add("[email protected]"); args.add("--password"); args.add("@keychain:gcs_app_pw"); List<String> lines = runCmd(args); String requestID = null; boolean noErrors = false; for (String line : lines) { line = line.trim(); if (line.startsWith("No errors uploading ")) { noErrors = true; } else if (line.startsWith("RequestUUID = ")) { String[] parts = line.split("=", 2); if (parts.length == 2) { requestID = parts[1].trim(); } if (noErrors) { break; } } } if (!noErrors || requestID == null) { failWithLines("Unable to locate request ID from response. Response follows:", lines); } args.clear(); args.add("xcrun"); args.add("altool"); args.add("--notarization-info"); args.add(requestID); args.add("--username"); args.add("[email protected]"); args.add("--password"); args.add("@keychain:gcs_app_pw"); boolean success = false; while (!success) { try { Thread.sleep(10000); // 10 seconds } catch (InterruptedException exception) { exception.printStackTrace(); } lines = runCmd(args); for (String line : lines) { line = line.trim(); if ("Status: invalid".equals(line)) { failWithLines("Notarization failed. Response follows:", lines); break; } if ("Status: success".equals(line)) { success = true; break; } } System.out.print("."); System.out.flush(); } args.clear(); args.add("xcrun"); args.add("stapler"); args.add("staple"); args.add(PKG.toAbsolutePath().toString()); success = false; for (String line : runCmd(args)) { line = line.trim(); if ("The staple and validate action worked!".equals(line)) { success = true; break; } } if (!success) { failWithLines("Stapling failed. Response follows:", lines); } showTiming(timing); } private static void failWithLines(String msg, List<String> lines) { System.out.println(); System.err.println(msg); System.err.println(); for (String line : lines) { System.err.println(line); } System.exit(1); } private static List<String> runCmd(List<String> args) { List<String> lines = new ArrayList<>(); ProcessBuilder builder = new ProcessBuilder(args); builder.redirectOutput(Redirect.PIPE).redirectErrorStream(true); try { Process process = builder.start(); try (BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) { String line = in.readLine(); while (line != null) { lines.add(line); line = in.readLine(); } } } catch (IOException exception) { System.out.println(); exception.printStackTrace(System.err); System.exit(1); } return lines; } private static void runNoOutputCmd(List<String> args) { runNoOutputCmd(args.toArray(new String[0])); } private static void runNoOutputCmd(String... args) { ProcessBuilder builder = new ProcessBuilder(args); builder.redirectOutput(Redirect.PIPE).redirectErrorStream(true); try { boolean hadMsg = false; Process process = builder.start(); try (BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) { String line = in.readLine(); while (line != null) { if (!line.startsWith("WARNING: Using incubator modules: jdk.incubator.jpackage")) { if (!hadMsg) { System.out.println(); } System.err.println(line); hadMsg = true; } line = in.readLine(); } } if (hadMsg) { System.exit(1); } } catch (IOException exception) { System.out.println(); exception.printStackTrace(System.err); System.exit(1); } } static class RecursiveDirectoryRemover implements FileVisitor<Path> { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) { return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exception) { System.out.println(); exception.printStackTrace(System.err); System.exit(1); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exception) throws IOException { if (exception != null) { System.out.println(); exception.printStackTrace(System.err); System.exit(1); } if (!dir.equals(DIST_DIR)) { Files.delete(dir); } return FileVisitResult.CONTINUE; } } public interface Handler { void processFile(Path path) throws IOException; } static final class FileScanner implements FileVisitor<Path> { private Path mPath; private Handler mHandler; public static void walk(Path path, Handler handler) { try { Files.walkFileTree(path, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new FileScanner(path, handler)); } catch (Exception exception) { System.out.println(); exception.printStackTrace(System.err); System.exit(1); } } private FileScanner(Path path, Handler handler) { mPath = path; mHandler = handler; } private boolean shouldSkip(Path path) { return !mPath.equals(path) && path.getFileName().toString().startsWith("."); } @Override public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes attrs) { if (shouldSkip(path)) { return FileVisitResult.SKIP_SUBTREE; } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException { if (!shouldSkip(path)) { mHandler.processFile(path); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path path, IOException exception) { System.out.println(); exception.printStackTrace(System.err); System.exit(1); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path path, IOException exception) { if (exception != null) { System.out.println(); exception.printStackTrace(System.err); System.exit(1); } return FileVisitResult.CONTINUE; } } }
bundler/bundler/Bundler.java
/* * Copyright ©1998-2021 by Richard A. Wilkes. All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, version 2.0. If a copy of the MPL was not distributed with * this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This Source Code Form is "Incompatible With Secondary Licenses", as * defined by the Mozilla Public License, version 2.0. */ package bundler; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.lang.ProcessBuilder.Redirect; import java.nio.charset.StandardCharsets; import java.nio.file.FileVisitOption; import java.nio.file.FileVisitResult; import java.nio.file.FileVisitor; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.EnumSet; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Stream; public final class Bundler { private static final String GCS_VERSION = "4.34.2"; private static final String JDK_MAJOR_VERSION = "17"; private static final String LINUX = "linux"; private static final String MACOS = "macos"; private static final String WINDOWS = "windows"; private static final Path DIST_DIR = Path.of("out", "dist"); private static final Path BUILD_DIR = DIST_DIR.resolve("build"); private static final Path MODULE_DIR = DIST_DIR.resolve("modules"); private static final Path EXTRA_DIR = DIST_DIR.resolve("extra"); private static final Path I18N_DIR = EXTRA_DIR.resolve("i18n"); private static final Path MANIFEST = BUILD_DIR.resolve("com.trollworks.gcs.manifest"); private static final Path JRE = BUILD_DIR.resolve("jre"); private static final String YEARS = "1998-" + DateTimeFormatter.ofPattern("yyyy").format(Instant.now().atZone(ZoneId.systemDefault())); private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; private static String OS; private static Path PKG; private static Path NO_INSTALLER_PKG; private static String ICON_TYPE; private Bundler() { } /** * The main entry point for bundling GCS. * * @param args Arguments to the program. */ public static void main(String[] args) { checkPlatform(); boolean sign = false; boolean notarize = false; boolean noInstaller = false; for (String arg : args) { if (MACOS.equals(OS)) { if ("-s".equals(arg) || "--sign".equals(arg)) { if (!sign) { sign = true; System.out.println("Signing enabled"); } continue; } if ("-n".equals(arg) || "--notarize".equals(arg)) { if (!notarize) { notarize = true; System.out.println("Notarization enabled"); } continue; } } if ("-u".equals(arg) || "--unpackaged".equals(arg)) { if (!noInstaller) { noInstaller = true; System.out.println("Will not package the application for distribution"); } continue; } if ("-h".equals(arg) || "--help".equals(arg)) { System.out.println("-h, --help This help"); System.out.println("-n, --notarize Enable notarization of the application (macOS only)"); System.out.println("-s, --sign Enable signing of the application (macOS only)"); System.out.println("-u, --unpackaged Don't package the app into a platform-specific installer"); System.exit(0); } System.out.println("Ignoring argument: " + arg); } if (noInstaller && (sign || notarize)) { System.out.println("--unpackaged is not compatible with --sign or --notarize"); System.exit(1); } checkJDK(); prepareDirs(); compile(); copyResources(); createModules(); extractLocalizationTemplate(); packageApp(noInstaller, sign); if (notarize) { notarizeApp(); } System.out.println("Finished!"); System.out.println(); System.out.println("Package can be found at:"); if (noInstaller) { System.out.println(NO_INSTALLER_PKG.toAbsolutePath()); } else { System.out.println(PKG.toAbsolutePath()); } } private static void checkPlatform() { String osName = System.getProperty("os.name"); if (osName.startsWith("Mac")) { OS = MACOS; PKG = Path.of("GCS-" + GCS_VERSION + ".dmg"); NO_INSTALLER_PKG = Path.of("GCS.app"); ICON_TYPE = "icns"; } else if (osName.startsWith("Win")) { OS = WINDOWS; PKG = Path.of("GCS-" + GCS_VERSION + ".msi"); NO_INSTALLER_PKG = Path.of("GCS"); ICON_TYPE = "ico"; } else if (osName.startsWith("Linux")) { OS = LINUX; PKG = Path.of("gcs-" + GCS_VERSION + "-1_amd64.deb"); NO_INSTALLER_PKG = Path.of("gcs"); ICON_TYPE = "png"; } else { System.err.println("Unsupported platform: " + osName); System.exit(1); } } private static void checkJDK() { ProcessBuilder builder = new ProcessBuilder("javac", "--version"); builder.redirectOutput(Redirect.PIPE).redirectErrorStream(true); try { String versionLine = ""; Process process = builder.start(); try (BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) { String prefix = "javac "; String line; while ((line = in.readLine()) != null) { if (line.startsWith(prefix)) { versionLine = line.substring(prefix.length()); } } } if (!versionLine.startsWith(JDK_MAJOR_VERSION)) { System.err.println("JDK " + versionLine + " was found. JDK " + JDK_MAJOR_VERSION + " is required."); emitInstallJDKMessageAndExit(); } } catch (IOException exception) { System.err.println("JDK " + JDK_MAJOR_VERSION + " is not installed!"); emitInstallJDKMessageAndExit(); } } private static void emitInstallJDKMessageAndExit() { System.err.println("Install JDK " + JDK_MAJOR_VERSION + " from http://jdk.java.net/" + JDK_MAJOR_VERSION + "/ and try again."); System.exit(1); } private static void prepareDirs() { System.out.print("Removing any previous build data... "); System.out.flush(); long timing = System.nanoTime(); try { if (Files.exists(DIST_DIR)) { Files.walkFileTree(DIST_DIR, new RecursiveDirectoryRemover()); } Files.createDirectories(DIST_DIR); Files.createDirectories(BUILD_DIR); Files.createDirectories(MODULE_DIR); Files.createDirectories(EXTRA_DIR); Files.createDirectories(I18N_DIR); Files.deleteIfExists(PKG); if (Files.exists(NO_INSTALLER_PKG)) { Files.walkFileTree(NO_INSTALLER_PKG, new RecursiveDirectoryRemover()); } } catch (IOException exception) { System.out.println(); exception.printStackTrace(System.err); System.exit(1); } showTiming(timing); } private static void showTiming(long timing) { System.out.printf("%,.3fs\n", Double.valueOf((System.nanoTime() - timing) / 1000000000.0)); } private static void compile() { System.out.print("Compiling... "); System.out.flush(); long timing = System.nanoTime(); Path javacInput = BUILD_DIR.resolve("javac.input"); try (PrintWriter out = new PrintWriter(Files.newBufferedWriter(javacInput))) { out.println("-d"); out.println(BUILD_DIR); out.println("--release"); out.println(JDK_MAJOR_VERSION); out.println("-encoding"); out.println("UTF8"); out.println("--module-source-path"); out.printf(".%1$s*%1$ssrc%2$sthird_party%1$s*%1$ssrc\n", File.separator, File.pathSeparator); FileScanner.walk(Path.of("."), (path) -> { if (path.getFileName().toString().endsWith(".java") && !path.startsWith(Path.of(".", "bundler"))) { out.println(path); } }); } catch (IOException exception) { System.out.println(); exception.printStackTrace(System.err); System.exit(1); } runNoOutputCmd("javac", "@" + javacInput); showTiming(timing); } private static void copyResources() { System.out.print("Copying resources... "); System.out.flush(); long timing = System.nanoTime(); copyResourceTree(Path.of("com.trollworks.gcs", "resources"), BUILD_DIR.resolve("com.trollworks.gcs")); showTiming(timing); } private static void copyResourceTree(Path src, Path dst) { FileScanner.walk(src, (path) -> { Path target = dst.resolve(src.relativize(path)); Files.createDirectories(target.getParent()); try (InputStream in = Files.newInputStream(path)) { try (OutputStream out = Files.newOutputStream(target)) { byte[] data = new byte[8192]; int amt; while ((amt = in.read(data)) != -1) { out.write(data, 0, amt); } } } }); } private static void createModules() { System.out.print("Creating modules... "); System.out.flush(); long timing = System.nanoTime(); createManifest(); List<String> args = new ArrayList<>(); args.add("jar"); args.add("--create"); args.add("--file"); args.add(MODULE_DIR.resolve("com.trollworks.gcs-" + GCS_VERSION + ".jar").toString()); args.add("--module-version"); args.add(GCS_VERSION); args.add("--manifest"); args.add(MANIFEST.toString()); args.add("--main-class"); args.add("com.trollworks.gcs.GCS"); args.add("-C"); args.add(BUILD_DIR.resolve("com.trollworks.gcs").toString()); args.add("."); runNoOutputCmd(args); showTiming(timing); } private static void createManifest() { try (PrintWriter out = new PrintWriter(Files.newBufferedWriter(MANIFEST))) { out.println("Manifest-Version: 1.0"); out.println("bundle-name: GCS"); out.println("bundle-version: " + GCS_VERSION); out.println("bundle-license: Mozilla Public License 2.0"); out.println("bundle-copyright-owner: Richard A. Wilkes"); out.println("bundle-copyright-years: " + YEARS); } catch (IOException exception) { System.out.println(); exception.printStackTrace(System.err); System.exit(1); } } private static void extractLocalizationTemplate() { System.out.print("Extracting localization template... "); System.out.flush(); long timing = System.nanoTime(); Set<String> keys = new HashSet<>(); try (Stream<Path> srcTree = Files.walk(Path.of("com.trollworks.gcs", "src"))) { srcTree.filter(path -> { String lower = path.getFileName().toString().toLowerCase(); return lower.endsWith(".java") && !lower.endsWith("i18n.java") && Files.isRegularFile(path) && Files.isReadable(path); }).distinct().forEach(path -> { try (Stream<String> lines = Files.lines(path)) { lines.forEachOrdered(line -> { while (!line.isEmpty()) { boolean needContext = true; String lookFor = "I18n.text("; int i = line.indexOf(lookFor); if (i >= 0) { needContext = false; } else { lookFor = "I18n.textWithContext("; i = line.indexOf(lookFor); if (i < 0) { break; } } int max = line.length(); i = skipSpace(i + lookFor.length(), max, line); if (i >= max) { break; } if (needContext) { char ch = line.charAt(i); if (ch < '0' || ch > '9') { break; } i = skipSpace(i + 1, max, line); if (i >= max || line.charAt(i) != ',') { break; } i = skipSpace(i + 1, max, line); if (i >= max) { break; } } if (line.charAt(i) != '"') { break; } i++; line = processLine(keys, line.substring(i)); } }); } catch (IOException ioe) { System.out.println(); ioe.printStackTrace(System.err); System.exit(1); } }); try (PrintStream out = new PrintStream(Files.newOutputStream(I18N_DIR.resolve("template.i18n")), true, StandardCharsets.UTF_8)) { out.println("# Generated on " + ZonedDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME)); out.println("#"); out.println("# This file consists of UTF-8 text. Do not save it as anything else."); out.println("#"); out.println("# Key-value pairs are defined as one or more lines prefixed with 'k:' for the"); out.println("# key, followed by one or more lines prefixed with 'v:' or 'v#:', where # is a"); out.println("# digit (0-9), for the value. These prefixes are then followed by a quoted"); out.println("# string, as generated by Text.quote(). When two or more lines with the same"); out.println("# prefix are present in a row, they will be concatenated together with an"); out.println("# intervening \\n character."); out.println("#"); out.println("# Do NOT modify the 'k' values. They are the values as seen in the code."); out.println("#"); out.println("# Replace the 'v' values with the appropriate translation."); out.println("#"); out.println("# 'v' values followed by a digit are for variations on the same english word"); out.println("# that may be needed for other languages, depending on context. You will need"); out.println("# to seek these out in the code to determine which alternate is used where."); out.println("# By default, no keys use alternates. Only those that were specifically"); out.println("# requested by a translator and the code has been adjusted to request them"); out.println("# via a context value will be used."); keys.stream().sorted().forEachOrdered(key -> { out.println(); String quoted = quote(key); if (quoted.length() < 77) { out.println("k:" + quoted); out.println("v:" + quoted); } else { String[] parts = key.split("\n", -1); for (String part : parts) { out.println("k:" + quote(part)); } for (String part : parts) { out.println("v:" + quote(part)); } } }); } } catch (Exception ex) { System.out.println(); ex.printStackTrace(System.err); System.exit(1); } showTiming(timing); } private static int skipSpace(int i, int max, String line) { while (i < max) { char ch = line.charAt(i); if (ch != ' ' && ch != '\t') { break; } i++; } return i; } private static String processLine(Set<String> keys, String in) { StringBuilder buffer = new StringBuilder(); int len = in.length(); int state = 0; int unicodeValue = 0; for (int i = 0; i < len; i++) { char ch = in.charAt(i); switch (state) { case 0: // Looking for end quote if (ch == '"') { keys.add(buffer.toString()); return in.substring(i + 1); } if (ch == '\\') { state = 1; continue; } buffer.append(ch); break; case 1: // Processing escape sequence switch (ch) { case 't' -> { buffer.append('\t'); state = 0; } case 'b' -> { buffer.append('\b'); state = 0; } case 'n' -> { buffer.append('\n'); state = 0; } case 'r' -> { buffer.append('\r'); state = 0; } case '"' -> { buffer.append('"'); state = 0; } case '\\' -> { buffer.append('\\'); state = 0; } case 'u' -> { state = 2; unicodeValue = 0; } default -> { System.out.println(); new RuntimeException("invalid escape sequence").printStackTrace(System.err); System.exit(1); } } break; case 2: // Processing first digit of unicode escape sequence case 3: // Processing second digit of unicode escape sequence case 4: // Processing third digit of unicode escape sequence case 5: // Processing fourth digit of unicode escape sequence if (!isHexDigit(ch)) { System.out.println(); new RuntimeException("invalid unicode escape sequence").printStackTrace(System.err); System.exit(1); } unicodeValue *= 16; unicodeValue += hexDigitValue(ch); if (state == 5) { state = 0; buffer.append((char) unicodeValue); } else { state++; } break; default: System.out.println(); new RuntimeException("invalid state").printStackTrace(System.err); System.exit(1); break; } } return ""; } private static boolean isHexDigit(char ch) { return ch >= '0' && ch <= '9' || ch >= 'a' && ch <= 'f' || ch >= 'A' && ch <= 'F'; } private static int hexDigitValue(char ch) { if (ch >= '0' && ch <= '9') { return ch - '0'; } if (ch >= 'a' && ch <= 'f') { return 10 + ch - 'a'; } if (ch >= 'A' && ch <= 'F') { return 10 + ch - 'A'; } return 0; } private static String quote(String in) { StringBuilder buffer = new StringBuilder(); int length = in.length(); buffer.append('"'); for (int i = 0; i < length; i++) { char ch = in.charAt(i); if (ch == '"' || ch == '\\') { buffer.append('\\'); buffer.append(ch); } else if (isPrintableChar(ch)) { buffer.append(ch); } else { switch (ch) { case '\b' -> buffer.append("\\b"); case '\f' -> buffer.append("\\f"); case '\n' -> buffer.append("\\n"); case '\r' -> buffer.append("\\r"); case '\t' -> buffer.append("\\t"); default -> { buffer.append("\\u"); buffer.append(HEX_DIGITS[ch >> 12 & 0xF]); buffer.append(HEX_DIGITS[ch >> 8 & 0xF]); buffer.append(HEX_DIGITS[ch >> 4 & 0xF]); buffer.append(HEX_DIGITS[ch & 0xF]); } } } } buffer.append('"'); return buffer.toString(); } private static boolean isPrintableChar(char ch) { if (!Character.isISOControl(ch) && Character.isDefined(ch)) { try { Character.UnicodeBlock block = Character.UnicodeBlock.of(ch); return block != null && block != Character.UnicodeBlock.SPECIALS; } catch (Exception ex) { return false; } } return false; } private static void packageApp(boolean noInstaller, boolean sign) { System.out.print("Packaging the application... "); System.out.flush(); long timing = System.nanoTime(); List<String> args = new ArrayList<>(); args.add("jlink"); args.add("--module-path"); args.add(MODULE_DIR.toString()); args.add("--output"); args.add(JRE.toString()); args.add("--no-header-files"); args.add("--no-man-pages"); args.add("--strip-debug"); args.add("--strip-native-commands"); args.add("--add-modules"); args.add("com.trollworks.gcs"); runNoOutputCmd(args); args.clear(); args.add("jpackage"); args.add("--module"); args.add("com.trollworks.gcs/com.trollworks.gcs.GCS"); args.add("--app-version"); args.add(GCS_VERSION); args.add("--copyright"); args.add("©" + YEARS + " by Richard A. Wilkes"); args.add("--vendor"); args.add("Richard A. Wilkes"); args.add("--description"); args.add("GCS (GURPS Character Sheet) is a stand-alone, interactive, character sheet editor that allows you to build characters for the GURPS 4th Edition roleplaying game system."); args.add("--icon"); args.add(Path.of("artifacts", ICON_TYPE, "app." + ICON_TYPE).toString()); if (OS.equals(MACOS) || !noInstaller) { for (String ext : new String[]{"adm", "adq", "eqm", "eqp", "gcs", "gct", "not", "skl", "spl"}) { args.add("--file-associations"); args.add(Path.of("artifacts", "file_associations", OS, ext + "_ext.properties").toString()); } } args.add("--input"); args.add(EXTRA_DIR.toString()); args.add("--runtime-image"); args.add(JRE.toString()); args.add("--java-options"); args.add("-Dhttps.protocols=TLSv1.2,TLSv1.1,TLSv1"); if (noInstaller) { args.add("--type"); args.add("app-image"); } switch (OS) { case MACOS -> { args.add("--java-options"); args.add("-Dapple.awt.application.appearance=system"); args.add("--mac-package-name"); args.add("GCS"); args.add("--mac-package-identifier"); args.add("com.trollworks.gcs"); if (sign) { args.add("--mac-sign"); args.add("--mac-signing-key-user-name"); args.add("Richard Wilkes"); } } case LINUX -> { if (!noInstaller) { args.add("--linux-package-name"); args.add("gcs"); args.add("--linux-deb-maintainer"); args.add("[email protected]"); args.add("--linux-menu-group"); args.add("Game;Utility;RolePlaying"); args.add("--linux-app-category"); args.add("games"); args.add("--linux-rpm-license-type"); args.add("MPLv2.0"); args.add("--linux-shortcut"); args.add("--linux-app-release"); args.add("1"); args.add("--linux-package-deps"); args.add(""); } } case WINDOWS -> { args.add("--java-options"); args.add("-Dsun.java2d.dpiaware=false"); if (!noInstaller) { args.add("--win-menu"); args.add("--win-menu-group"); args.add("Roleplaying"); args.add("--win-shortcut"); args.add("--type"); args.add("msi"); args.add("--win-dir-chooser"); args.add("--win-upgrade-uuid"); args.add("E71F99DA-AD84-4E6E-9bE7-4E65421752E1"); } } } runNoOutputCmd(args); showTiming(timing); } private static void notarizeApp() { System.out.print("Notarizing the application... "); System.out.flush(); long timing = System.nanoTime(); List<String> args = new ArrayList<>(); args.add("xcrun"); args.add("altool"); args.add("--notarize-app"); args.add("--type"); args.add("osx"); args.add("--file"); args.add(PKG.toAbsolutePath().toString()); args.add("--primary-bundle-id"); args.add("com.trollworks.gcs"); args.add("--username"); args.add("[email protected]"); args.add("--password"); args.add("@keychain:gcs_app_pw"); List<String> lines = runCmd(args); String requestID = null; boolean noErrors = false; for (String line : lines) { line = line.trim(); if (line.startsWith("No errors uploading ")) { noErrors = true; } else if (line.startsWith("RequestUUID = ")) { String[] parts = line.split("=", 2); if (parts.length == 2) { requestID = parts[1].trim(); } if (noErrors) { break; } } } if (!noErrors || requestID == null) { failWithLines("Unable to locate request ID from response. Response follows:", lines); } args.clear(); args.add("xcrun"); args.add("altool"); args.add("--notarization-info"); args.add(requestID); args.add("--username"); args.add("[email protected]"); args.add("--password"); args.add("@keychain:gcs_app_pw"); boolean success = false; while (!success) { try { Thread.sleep(10000); // 10 seconds } catch (InterruptedException exception) { exception.printStackTrace(); } lines = runCmd(args); for (String line : lines) { line = line.trim(); if ("Status: invalid".equals(line)) { failWithLines("Notarization failed. Response follows:", lines); break; } if ("Status: success".equals(line)) { success = true; break; } } System.out.print("."); System.out.flush(); } args.clear(); args.add("xcrun"); args.add("stapler"); args.add("staple"); args.add(PKG.toAbsolutePath().toString()); success = false; for (String line : runCmd(args)) { line = line.trim(); if ("The staple and validate action worked!".equals(line)) { success = true; break; } } if (!success) { failWithLines("Stapling failed. Response follows:", lines); } showTiming(timing); } private static void failWithLines(String msg, List<String> lines) { System.out.println(); System.err.println(msg); System.err.println(); for (String line : lines) { System.err.println(line); } System.exit(1); } private static List<String> runCmd(List<String> args) { List<String> lines = new ArrayList<>(); ProcessBuilder builder = new ProcessBuilder(args); builder.redirectOutput(Redirect.PIPE).redirectErrorStream(true); try { Process process = builder.start(); try (BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) { String line = in.readLine(); while (line != null) { lines.add(line); line = in.readLine(); } } } catch (IOException exception) { System.out.println(); exception.printStackTrace(System.err); System.exit(1); } return lines; } private static void runNoOutputCmd(List<String> args) { runNoOutputCmd(args.toArray(new String[0])); } private static void runNoOutputCmd(String... args) { ProcessBuilder builder = new ProcessBuilder(args); builder.redirectOutput(Redirect.PIPE).redirectErrorStream(true); try { boolean hadMsg = false; Process process = builder.start(); try (BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) { String line = in.readLine(); while (line != null) { if (!line.startsWith("WARNING: Using incubator modules: jdk.incubator.jpackage")) { if (!hadMsg) { System.out.println(); } System.err.println(line); hadMsg = true; } line = in.readLine(); } } if (hadMsg) { System.exit(1); } } catch (IOException exception) { System.out.println(); exception.printStackTrace(System.err); System.exit(1); } } static class RecursiveDirectoryRemover implements FileVisitor<Path> { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) { return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exception) { System.out.println(); exception.printStackTrace(System.err); System.exit(1); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exception) throws IOException { if (exception != null) { System.out.println(); exception.printStackTrace(System.err); System.exit(1); } if (!dir.equals(DIST_DIR)) { Files.delete(dir); } return FileVisitResult.CONTINUE; } } public interface Handler { void processFile(Path path) throws IOException; } static final class FileScanner implements FileVisitor<Path> { private Path mPath; private Handler mHandler; public static void walk(Path path, Handler handler) { try { Files.walkFileTree(path, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new FileScanner(path, handler)); } catch (Exception exception) { System.out.println(); exception.printStackTrace(System.err); System.exit(1); } } private FileScanner(Path path, Handler handler) { mPath = path; mHandler = handler; } private boolean shouldSkip(Path path) { return !mPath.equals(path) && path.getFileName().toString().startsWith("."); } @Override public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes attrs) { if (shouldSkip(path)) { return FileVisitResult.SKIP_SUBTREE; } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException { if (!shouldSkip(path)) { mHandler.processFile(path); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path path, IOException exception) { System.out.println(); exception.printStackTrace(System.err); System.exit(1); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path path, IOException exception) { if (exception != null) { System.out.println(); exception.printStackTrace(System.err); System.exit(1); } return FileVisitResult.CONTINUE; } } }
Potential fix for #387 - disable DirectDraw3D on Windows Some Windows installations behaved poorly with this enabled
bundler/bundler/Bundler.java
Potential fix for #387 - disable DirectDraw3D on Windows
<ide><path>undler/bundler/Bundler.java <ide> case WINDOWS -> { <ide> args.add("--java-options"); <ide> args.add("-Dsun.java2d.dpiaware=false"); <add> args.add("--java-options"); <add> args.add("-Dsun.java2d.d3d=false"); <ide> if (!noInstaller) { <ide> args.add("--win-menu"); <ide> args.add("--win-menu-group");
JavaScript
mit
29b7bc48a74a46fb78dc80b1b91fda71a68838bb
0
forfuturellc/mau
/** * The MIT License (MIT) * * Copyright (c) 2017 GochoMugo <[email protected]> * Copyright (c) 2017 Forfuture LLC <[email protected]> */ // built-in modules const assert = require("assert"); // installed modules const Debug = require("debug"); // own modules const QueryController = require("./query-controller"); // module variables const debug = Debug("mau:form"); /** * @class Form * @private */ class Form { /** * @constructor * @param {String} name Name of the form * @param {Array} queries Array of queries * @param {Object} [options] Options * @param {Function} [options.cb] Callback invoked on form completion * @param {Function} [options.i18n] Invoked to return internationalized text. * @todo Ensure the queries are valid! */ constructor(name, queries, options={}) { debug("constructing new form: %s", name); assert.ok(name, "Name of form must be provided."); assert.ok(queries, "Queries must be provided."); this.name = name; this.queries = queries; this.options = options; } /** * Process a message. * @param {Session} session Session to be used in this context * @param {String|Number|Null} text Text of the message * @param {Object} ref Reference * @param {Function} done(error, question, updatedSession) */ process(session, text, ref, done) { debug("processing message '%s' in session '%j'", text, session); assert.ok(session, "Session must be provided."); assert.ok(typeof text === "string" || typeof text === "number" || text === null, "Message text must be provided, or `null` for first query."); assert.ok(ref, "Reference must be provided."); assert.ok(done, "Callback must be provided."); let controller; try { controller = new QueryController(this, session, ref); } catch (ex) { return done(ex); } return controller.advance(text, (error, question, updatedSession) => { if (error) { return done(error); } return done(null, question, updatedSession); }); } } exports = module.exports = Form;
lib/form.js
/** * The MIT License (MIT) * * Copyright (c) 2017 GochoMugo <[email protected]> * Copyright (c) 2017 Forfuture LLC <[email protected]> */ // built-in modules const assert = require("assert"); // installed modules const Debug = require("debug"); // own modules const QueryController = require("./query-controller"); // module variables const debug = Debug("mau:form"); /** * @class Form * @private */ class Form { /** * @constructor * @param {String} name Name of the form * @param {Array} queries Array of queries * @param {Object} [options] Options * @param {Function} [options.cb] Callback invoked on form completion * @param {Function} [options.i18n] Invoked to return internationalized text. * @todo Ensure the queries are valid! */ constructor(name, queries, options={}) { debug("constructing new form: %s", name); assert.ok(name, "Name of form must be provided."); assert.ok(queries, "Queries must be provided."); this.name = name; this.queries = queries; this.options = options; } /** * Process a message. * @param {Session} session Session to be used in this context * @param {String|Null} text Text of the message * @param {Object} ref Reference * @param {Function} done(error, question, updatedSession) */ process(session, text, ref, done) { debug("processing message '%s' in session '%j'", text, session); assert.ok(session, "Session must be provided."); assert.ok(typeof text === "string" || text === null, "Message text must be provided, or `null` for first query."); assert.ok(ref, "Reference must be provided."); assert.ok(done, "Callback must be provided."); let controller; try { controller = new QueryController(this, session, ref); } catch (ex) { return done(ex); } return controller.advance(text, (error, question, updatedSession) => { if (error) { return done(error); } return done(null, question, updatedSession); }); } } exports = module.exports = Form;
lib/form: Allow numbers as answers/text to queries Feature: This is important as it allows choice IDs to be specified as numbers.
lib/form.js
lib/form: Allow numbers as answers/text to queries
<ide><path>ib/form.js <ide> /** <ide> * Process a message. <ide> * @param {Session} session Session to be used in this context <del> * @param {String|Null} text Text of the message <add> * @param {String|Number|Null} text Text of the message <ide> * @param {Object} ref Reference <ide> * @param {Function} done(error, question, updatedSession) <ide> */ <ide> process(session, text, ref, done) { <ide> debug("processing message '%s' in session '%j'", text, session); <ide> assert.ok(session, "Session must be provided."); <del> assert.ok(typeof text === "string" || text === null, "Message text must be provided, or `null` for first query."); <add> assert.ok(typeof text === "string" || typeof text === "number" || text === null, "Message text must be provided, or `null` for first query."); <ide> assert.ok(ref, "Reference must be provided."); <ide> assert.ok(done, "Callback must be provided."); <ide> let controller;
JavaScript
mit
de1d771a8a3b253ec287a1102c0f0ad07e4dfe1d
0
networked-aframe/networked-aframe,haydenjameslee/networked-aframe,networked-aframe/networked-aframe,haydenjameslee/networked-aframe
/* global AFRAME, NAF, THREE */ var deepEqual = require('../DeepEquals'); var InterpolationBuffer = require('buffered-interpolation'); var DEG2RAD = THREE.Math.DEG2RAD; var OBJECT3D_COMPONENTS = ['position', 'rotation', 'scale']; function defaultRequiresUpdate() { let cachedData = null; return (newData) => { if (cachedData === null || !deepEqual(cachedData, newData)) { cachedData = AFRAME.utils.clone(newData); return true; } return false; }; } AFRAME.registerSystem("networked", { init() { this.components = []; this.nextSyncTime = 0; }, register(component) { this.components.push(component); }, deregister(component) { const idx = this.components.indexOf(component); if (idx > -1) { this.components.splice(idx, 1); } }, tick: (function() { return function() { if (!NAF.connection.adapter) return; if (this.el.clock.elapsedTime < this.nextSyncTime) return; const data = { d: [] }; for (let i = 0, l = this.components.length; i < l; i++) { const c = this.components[i]; if (!c.isMine()) continue; if (!c.el.parentElement) { NAF.log.error("entity registered with system despite being removed"); //TODO: Find out why tick is still being called return; } const syncData = this.components[i].syncDirty(); if (!syncData) continue; data.d.push(syncData); } if (data.d.length > 0) { NAF.connection.broadcastData('um', data); } this.updateNextSyncTime(); }; })(), updateNextSyncTime() { this.nextSyncTime = this.el.clock.elapsedTime + 1 / NAF.options.updateRate; } }); AFRAME.registerComponent('networked', { schema: { template: {default: ''}, attachTemplateToLocal: { default: true }, persistent: { default: false }, networkId: {default: ''}, owner: {default: ''}, creator: {default: ''} }, init: function() { this.OWNERSHIP_GAINED = 'ownership-gained'; this.OWNERSHIP_CHANGED = 'ownership-changed'; this.OWNERSHIP_LOST = 'ownership-lost'; this.onOwnershipGainedEvent = { el: this.el }; this.onOwnershipChangedEvent = { el: this.el }; this.onOwnershipLostEvent = { el: this.el }; this.conversionEuler = new THREE.Euler(); this.conversionEuler.order = "YXZ"; this.bufferInfos = []; this.bufferPosition = new THREE.Vector3(); this.bufferQuaternion = new THREE.Quaternion(); this.bufferScale = new THREE.Vector3(); var wasCreatedByNetwork = this.wasCreatedByNetwork(); this.onConnected = this.onConnected.bind(this); this.syncData = {}; this.componentSchemas = NAF.schemas.getComponents(this.data.template); this.cachedElements = new Array(this.componentSchemas.length); this.networkUpdatePredicates = this.componentSchemas.map(x => (x.requiresNetworkUpdate && x.requiresNetworkUpdate()) || defaultRequiresUpdate()); // Fill cachedElements array with null elements this.invalidateCachedElements(); this.initNetworkParent(); if (this.data.networkId === '') { this.el.setAttribute(this.name, {networkId: NAF.utils.createNetworkId()}); } if (wasCreatedByNetwork) { this.firstUpdate(); } else { if (this.data.attachTemplateToLocal) { this.attachTemplateToLocal(); } this.registerEntity(this.data.networkId); } this.lastOwnerTime = -1; if (NAF.clientId) { this.onConnected(); } else { document.body.addEventListener('connected', this.onConnected, false); } document.body.dispatchEvent(this.entityCreatedEvent()); this.el.dispatchEvent(new CustomEvent('instantiated', {detail: {el: this.el}})); this.el.sceneEl.systems.networked.register(this); }, attachTemplateToLocal: function() { const template = NAF.schemas.getCachedTemplate(this.data.template); const elAttrs = template.attributes; // Merge root element attributes with this entity for (let attrIdx = 0; attrIdx < elAttrs.length; attrIdx++) { this.el.setAttribute(elAttrs[attrIdx].name, elAttrs[attrIdx].value); } // Append all child elements while (template.firstElementChild) { this.el.appendChild(template.firstElementChild); } }, takeOwnership: function() { const owner = this.data.owner; const lastOwnerTime = this.lastOwnerTime; const now = NAF.connection.getServerTime(); if (owner && !this.isMine() && lastOwnerTime < now) { this.lastOwnerTime = now; this.removeLerp(); this.el.setAttribute('networked', { owner: NAF.clientId }); this.syncAll(); this.onOwnershipGainedEvent.oldOwner = owner; this.el.emit(this.OWNERSHIP_GAINED, this.onOwnershipGainedEvent); this.onOwnershipChangedEvent.oldOwner = owner; this.onOwnershipChangedEvent.newOwner = NAF.clientId; this.el.emit(this.OWNERSHIP_CHANGED, this.onOwnershipChangedEvent); return true; } return false; }, wasCreatedByNetwork: function() { return !!this.el.firstUpdateData; }, initNetworkParent: function() { var parentEl = this.el.parentElement; if (parentEl.hasOwnProperty('components') && parentEl.components.hasOwnProperty('networked')) { this.parent = parentEl; } else { this.parent = null; } }, registerEntity: function(networkId) { NAF.entities.registerEntity(networkId, this.el); }, firstUpdate: function() { var entityData = this.el.firstUpdateData; this.networkUpdate(entityData); }, onConnected: function() { if (this.data.owner === '') { this.lastOwnerTime = NAF.connection.getServerTime(); this.el.setAttribute(this.name, { owner: NAF.clientId, creator: NAF.clientId }); setTimeout(() => { //a-primitives attach their components on the next frame; wait for components to be attached before calling syncAll if (!this.el.parentNode){ NAF.log.warn("Networked element was removed before ever getting the chance to syncAll"); return; } this.syncAll(undefined, true); }, 0); } document.body.removeEventListener('connected', this.onConnected, false); }, isMine: function() { return this.data.owner === NAF.clientId; }, createdByMe: function() { return this.data.creator === NAF.clientId; }, tick: function(time, dt) { if (!this.isMine() && NAF.options.useLerp) { for (var i = 0; i < this.bufferInfos.length; i++) { var bufferInfo = this.bufferInfos[i]; var buffer = bufferInfo.buffer; var object3D = bufferInfo.object3D; var componentNames = bufferInfo.componentNames; buffer.update(dt); if (componentNames.includes('position')) { object3D.position.copy(buffer.getPosition()); } if (componentNames.includes('rotation')) { object3D.quaternion.copy(buffer.getQuaternion()); } if (componentNames.includes('scale')) { object3D.scale.copy(buffer.getScale()); } } } }, /* Sending updates */ syncAll: function(targetClientId, isFirstSync) { if (!this.canSync()) { return; } var components = this.gatherComponentsData(true); var syncData = this.createSyncData(components, isFirstSync); if (targetClientId) { NAF.connection.sendDataGuaranteed(targetClientId, 'u', syncData); } else { NAF.connection.broadcastDataGuaranteed('u', syncData); } }, syncDirty: function() { if (!this.canSync()) { return; } var components = this.gatherComponentsData(false); if (components === null) { return; } return this.createSyncData(components); }, getCachedElement(componentSchemaIndex) { var cachedElement = this.cachedElements[componentSchemaIndex]; if (cachedElement) { return cachedElement; } var componentSchema = this.componentSchemas[componentSchemaIndex]; if (componentSchema.selector) { return this.cachedElements[componentSchemaIndex] = this.el.querySelector(componentSchema.selector); } else { return this.cachedElements[componentSchemaIndex] = this.el; } }, invalidateCachedElements() { for (var i = 0; i < this.cachedElements.length; i++) { this.cachedElements[i] = null; } }, gatherComponentsData: function(fullSync) { var componentsData = null; for (var i = 0; i < this.componentSchemas.length; i++) { var componentSchema = this.componentSchemas[i]; var componentElement = this.getCachedElement(i); if (!componentElement) { if (fullSync) { componentsData = componentsData || {}; componentsData[i] = null; } continue; } var componentName = componentSchema.component ? componentSchema.component : componentSchema; var componentData = componentElement.getAttribute(componentName); if (componentData === null) { if (fullSync) { componentsData = componentsData || {}; componentsData[i] = null; } continue; } var syncedComponentData = componentSchema.property ? componentData[componentSchema.property] : componentData; // Use networkUpdatePredicate to check if the component needs to be updated. // Call networkUpdatePredicate first so that it can update any cached values in the event of a fullSync. if (this.networkUpdatePredicates[i](syncedComponentData) || fullSync) { componentsData = componentsData || {}; componentsData[i] = syncedComponentData; } } return componentsData; }, createSyncData: function(components, isFirstSync) { var { syncData, data } = this; syncData.networkId = data.networkId; syncData.owner = data.owner; syncData.creator = data.creator; syncData.lastOwnerTime = this.lastOwnerTime; syncData.template = data.template; syncData.persistent = data.persistent; syncData.parent = this.getParentId(); syncData.components = components; syncData.isFirstSync = !data.persistent && !!isFirstSync; return syncData; }, canSync: function() { // This client will send a sync if: // // - The client is the owner // - The client is the creator, and the owner is not in the room. // // The reason for the latter case is so the object will still be // properly instantiated if the owner leaves. (Since the object lifetime // is tied to the creator.) if (this.data.owner && this.isMine()) return true; if (!this.createdByMe()) return false; const clients = NAF.connection.getConnectedClients(); for (let clientId in clients) { if (clientId === this.data.owner) return false; } return true; }, getParentId: function() { this.initNetworkParent(); // TODO fix calling this each network tick if (!this.parent) { return null; } var netComp = this.parent.getAttribute('networked'); return netComp.networkId; }, /* Receiving updates */ networkUpdate: function(entityData) { // Avoid updating components if the entity data received did not come from the current owner. if (entityData.lastOwnerTime < this.lastOwnerTime || (this.lastOwnerTime === entityData.lastOwnerTime && this.data.owner > entityData.owner)) { return; } if (this.data.owner !== entityData.owner) { var wasMine = this.isMine(); this.lastOwnerTime = entityData.lastOwnerTime; const oldOwner = this.data.owner; const newOwner = entityData.owner; this.el.setAttribute('networked', { owner: entityData.owner }); if (wasMine) { this.onOwnershipLostEvent.newOwner = newOwner; this.el.emit(this.OWNERSHIP_LOST, this.onOwnershipLostEvent); } this.onOwnershipChangedEvent.oldOwner = oldOwner; this.onOwnershipChangedEvent.newOwner = newOwner; this.el.emit(this.OWNERSHIP_CHANGED, this.onOwnershipChangedEvent); } if (this.data.persistent !== entityData.persistent) { this.el.setAttribute('networked', { persistent: entityData.persistent }); } this.updateNetworkedComponents(entityData.components); }, updateNetworkedComponents: function(components) { for (var componentIndex = 0, l = this.componentSchemas.length; componentIndex < l; componentIndex++) { var componentData = components[componentIndex]; var componentSchema = this.componentSchemas[componentIndex]; var componentElement = this.getCachedElement(componentIndex); if (componentElement === null || componentData === null || componentData === undefined ) { continue; } if (componentSchema.component) { if (componentSchema.property) { this.updateNetworkedComponent(componentElement, componentSchema.component, componentSchema.property, componentData); } else { this.updateNetworkedComponent(componentElement, componentSchema.component, componentData); } } else { this.updateNetworkedComponent(componentElement, componentSchema, componentData); } } }, updateNetworkedComponent: function (el, componentName, data, value) { if(!NAF.options.useLerp || !OBJECT3D_COMPONENTS.includes(componentName)) { if (value === undefined) { el.setAttribute(componentName, data); } else { el.setAttribute(componentName, data, value); } return; } let bufferInfo; for (let i = 0, l = this.bufferInfos.length; i < l; i++) { const info = this.bufferInfos[i]; if (info.object3D === el.object3D) { bufferInfo = info; break; } } if (!bufferInfo) { bufferInfo = { buffer: new InterpolationBuffer(InterpolationBuffer.MODE_LERP, 0.1), object3D: el.object3D, componentNames: [componentName] }; this.bufferInfos.push(bufferInfo); } else { var componentNames = bufferInfo.componentNames; if (!componentNames.includes(componentName)) { componentNames.push(componentName); } } var buffer = bufferInfo.buffer; switch(componentName) { case 'position': buffer.setPosition(this.bufferPosition.set(data.x, data.y, data.z)); return; case 'rotation': this.conversionEuler.set(DEG2RAD * data.x, DEG2RAD * data.y, DEG2RAD * data.z); buffer.setQuaternion(this.bufferQuaternion.setFromEuler(this.conversionEuler)); return; case 'scale': buffer.setScale(this.bufferScale.set(data.x, data.y, data.z)); return; } NAF.log.error('Could not set value in interpolation buffer.', el, componentName, data, bufferInfo); }, removeLerp: function() { this.bufferInfos = []; }, remove: function () { if (this.isMine() && NAF.connection.isConnected()) { var syncData = { networkId: this.data.networkId }; if (NAF.entities.hasEntity(this.data.networkId)) { NAF.connection.broadcastDataGuaranteed('r', syncData); } else { NAF.log.error("Removing networked entity that is not in entities array."); } } NAF.entities.forgetEntity(this.data.networkId); document.body.dispatchEvent(this.entityRemovedEvent(this.data.networkId)); this.el.sceneEl.systems.networked.deregister(this); }, entityCreatedEvent() { return new CustomEvent('entityCreated', {detail: {el: this.el}}); }, entityRemovedEvent(networkId) { return new CustomEvent('entityRemoved', {detail: {networkId: networkId}}); } });
src/components/networked.js
/* global AFRAME, NAF, THREE */ var deepEqual = require('../DeepEquals'); var InterpolationBuffer = require('buffered-interpolation'); var DEG2RAD = THREE.Math.DEG2RAD; var OBJECT3D_COMPONENTS = ['position', 'rotation', 'scale']; function defaultRequiresUpdate() { let cachedData = null; return (newData) => { if (cachedData === null || !deepEqual(cachedData, newData)) { cachedData = AFRAME.utils.clone(newData); return true; } return false; }; } AFRAME.registerSystem("networked", { init() { this.components = []; this.nextSyncTime = 0; }, register(component) { this.components.push(component); }, deregister(component) { const idx = this.components.indexOf(component); if (idx > -1) { this.components.splice(idx, 1); } }, tick: (function() { return function() { if (!NAF.connection.adapter) return; if (this.el.clock.elapsedTime < this.nextSyncTime) return; const data = { d: [] }; for (let i = 0, l = this.components.length; i < l; i++) { const c = this.components[i]; if (!c.isMine()) continue; if (!c.el.parentElement) { NAF.log.error("entity registered with system despite being removed"); //TODO: Find out why tick is still being called return; } const syncData = this.components[i].syncDirty(); if (!syncData) continue; data.d.push(syncData); } if (data.d.length > 0) { NAF.connection.broadcastData('um', data); } this.updateNextSyncTime(); }; })(), updateNextSyncTime() { this.nextSyncTime = this.el.clock.elapsedTime + 1 / NAF.options.updateRate; } }); AFRAME.registerComponent('networked', { schema: { template: {default: ''}, attachTemplateToLocal: { default: true }, persistent: { default: false }, networkId: {default: ''}, owner: {default: ''}, creator: {default: ''} }, init: function() { this.OWNERSHIP_GAINED = 'ownership-gained'; this.OWNERSHIP_CHANGED = 'ownership-changed'; this.OWNERSHIP_LOST = 'ownership-lost'; this.onOwnershipGainedEvent = { el: this.el }; this.onOwnershipChangedEvent = { el: this.el }; this.onOwnershipLostEvent = { el: this.el }; this.conversionEuler = new THREE.Euler(); this.conversionEuler.order = "YXZ"; this.bufferInfos = []; this.bufferPosition = new THREE.Vector3(); this.bufferQuaternion = new THREE.Quaternion(); this.bufferScale = new THREE.Vector3(); var wasCreatedByNetwork = this.wasCreatedByNetwork(); this.onConnected = this.onConnected.bind(this); this.syncData = {}; this.componentSchemas = NAF.schemas.getComponents(this.data.template); this.cachedElements = new Array(this.componentSchemas.length); this.networkUpdatePredicates = this.componentSchemas.map(x => (x.requiresNetworkUpdate && x.requiresNetworkUpdate()) || defaultRequiresUpdate()); // Fill cachedElements array with null elements this.invalidateCachedElements(); this.initNetworkParent(); if (this.data.networkId === '') { this.el.setAttribute(this.name, {networkId: NAF.utils.createNetworkId()}); } if (wasCreatedByNetwork) { this.firstUpdate(); } else { if (this.data.attachTemplateToLocal) { this.attachTemplateToLocal(); } this.registerEntity(this.data.networkId); } this.lastOwnerTime = -1; if (NAF.clientId) { this.onConnected(); } else { document.body.addEventListener('connected', this.onConnected, false); } document.body.dispatchEvent(this.entityCreatedEvent()); this.el.dispatchEvent(new CustomEvent('instantiated', {detail: {el: this.el}})); this.el.sceneEl.systems.networked.register(this); }, attachTemplateToLocal: function() { const template = NAF.schemas.getCachedTemplate(this.data.template); const elAttrs = template.attributes; // Merge root element attributes with this entity for (let attrIdx = 0; attrIdx < elAttrs.length; attrIdx++) { this.el.setAttribute(elAttrs[attrIdx].name, elAttrs[attrIdx].value); } // Append all child elements while (template.firstElementChild) { this.el.appendChild(template.firstElementChild); } }, takeOwnership: function() { const owner = this.data.owner; const lastOwnerTime = this.lastOwnerTime; const now = NAF.connection.getServerTime(); if (owner && !this.isMine() && lastOwnerTime < now) { this.lastOwnerTime = now; this.removeLerp(); this.el.setAttribute('networked', { owner: NAF.clientId }); this.syncAll(); this.onOwnershipGainedEvent.oldOwner = owner; this.el.emit(this.OWNERSHIP_GAINED, this.onOwnershipGainedEvent); this.onOwnershipChangedEvent.oldOwner = owner; this.onOwnershipChangedEvent.newOwner = NAF.clientId; this.el.emit(this.OWNERSHIP_CHANGED, this.onOwnershipChangedEvent); return true; } return false; }, wasCreatedByNetwork: function() { return !!this.el.firstUpdateData; }, initNetworkParent: function() { var parentEl = this.el.parentElement; if (parentEl.hasOwnProperty('components') && parentEl.components.hasOwnProperty('networked')) { this.parent = parentEl; } else { this.parent = null; } }, registerEntity: function(networkId) { NAF.entities.registerEntity(networkId, this.el); }, firstUpdate: function() { var entityData = this.el.firstUpdateData; this.networkUpdate(entityData); }, onConnected: function() { if (this.data.owner === '') { this.lastOwnerTime = NAF.connection.getServerTime(); this.el.setAttribute(this.name, { owner: NAF.clientId, creator: NAF.clientId }); setTimeout(() => { //a-primitives attach their components on the next frame; wait for components to be attached before calling syncAll if (!this.el.parentNode){ NAF.log.warn("Networked element was removed before ever getting the chance to syncAll"); return; } this.syncAll(undefined, true); }, 0); } document.body.removeEventListener('connected', this.onConnected, false); }, isMine: function() { return this.data.owner === NAF.clientId; }, createdByMe: function() { return this.data.creator === NAF.clientId; }, tick: function(time, dt) { if (!this.isMine() && NAF.options.useLerp) { for (var i = 0; i < this.bufferInfos.length; i++) { var bufferInfo = this.bufferInfos[i]; var buffer = bufferInfo.buffer; var object3D = bufferInfo.object3D; var componentNames = bufferInfo.componentNames; buffer.update(dt); if (componentNames.includes('position')) { object3D.position.copy(buffer.getPosition()); } if (componentNames.includes('rotation')) { object3D.quaternion.copy(buffer.getQuaternion()); } if (componentNames.includes('scale')) { object3D.scale.copy(buffer.getScale()); } } } }, /* Sending updates */ syncAll: function(targetClientId, isFirstSync) { if (!this.canSync()) { return; } var components = this.gatherComponentsData(true); var syncData = this.createSyncData(components, isFirstSync); if (targetClientId) { NAF.connection.sendDataGuaranteed(targetClientId, 'u', syncData); } else { NAF.connection.broadcastDataGuaranteed('u', syncData); } }, syncDirty: function() { if (!this.canSync()) { return; } var components = this.gatherComponentsData(false); if (components === null) { return; } return this.createSyncData(components); }, getCachedElement(componentSchemaIndex) { var cachedElement = this.cachedElements[componentSchemaIndex]; if (cachedElement) { return cachedElement; } var componentSchema = this.componentSchemas[componentSchemaIndex]; if (componentSchema.selector) { return this.cachedElements[componentSchemaIndex] = this.el.querySelector(componentSchema.selector); } else { return this.cachedElements[componentSchemaIndex] = this.el; } }, invalidateCachedElements() { for (var i = 0; i < this.cachedElements.length; i++) { this.cachedElements[i] = null; } }, gatherComponentsData: function(fullSync) { var componentsData = null; for (var i = 0; i < this.componentSchemas.length; i++) { var componentSchema = this.componentSchemas[i]; var componentElement = this.getCachedElement(i); if (!componentElement) { if (fullSync) { componentsData = componentsData || {}; componentsData[i] = null; } continue; } var componentName = componentSchema.component ? componentSchema.component : componentSchema; var componentData = componentElement.getAttribute(componentName); if (componentData === null) { if (fullSync) { componentsData = componentsData || {}; componentsData[i] = null; } continue; } var syncedComponentData = componentSchema.property ? componentData[componentSchema.property] : componentData; // Use networkUpdatePredicate to check if the component needs to be updated. // Call networkUpdatePredicate first so that it can update any cached values in the event of a fullSync. if (this.networkUpdatePredicates[i](syncedComponentData) || fullSync) { componentsData = componentsData || {}; componentsData[i] = syncedComponentData; } } return componentsData; }, createSyncData: function(components, isFirstSync) { var { syncData, data } = this; syncData.networkId = data.networkId; syncData.owner = data.owner; syncData.creator = data.creator; syncData.lastOwnerTime = this.lastOwnerTime; syncData.template = data.template; syncData.persistent = data.persistent; syncData.parent = this.getParentId(); syncData.components = components; syncData.isFirstSync = !!isFirstSync; return syncData; }, canSync: function() { // This client will send a sync if: // // - The client is the owner // - The client is the creator, and the owner is not in the room. // // The reason for the latter case is so the object will still be // properly instantiated if the owner leaves. (Since the object lifetime // is tied to the creator.) if (this.data.owner && this.isMine()) return true; if (!this.createdByMe()) return false; const clients = NAF.connection.getConnectedClients(); for (let clientId in clients) { if (clientId === this.data.owner) return false; } return true; }, getParentId: function() { this.initNetworkParent(); // TODO fix calling this each network tick if (!this.parent) { return null; } var netComp = this.parent.getAttribute('networked'); return netComp.networkId; }, /* Receiving updates */ networkUpdate: function(entityData) { // Avoid updating components if the entity data received did not come from the current owner. if (entityData.lastOwnerTime < this.lastOwnerTime || (this.lastOwnerTime === entityData.lastOwnerTime && this.data.owner > entityData.owner)) { return; } if (this.data.owner !== entityData.owner) { var wasMine = this.isMine(); this.lastOwnerTime = entityData.lastOwnerTime; const oldOwner = this.data.owner; const newOwner = entityData.owner; this.el.setAttribute('networked', { owner: entityData.owner }); if (wasMine) { this.onOwnershipLostEvent.newOwner = newOwner; this.el.emit(this.OWNERSHIP_LOST, this.onOwnershipLostEvent); } this.onOwnershipChangedEvent.oldOwner = oldOwner; this.onOwnershipChangedEvent.newOwner = newOwner; this.el.emit(this.OWNERSHIP_CHANGED, this.onOwnershipChangedEvent); } if (this.data.persistent !== entityData.persistent) { this.el.setAttribute('networked', { persistent: entityData.persistent }); } this.updateNetworkedComponents(entityData.components); }, updateNetworkedComponents: function(components) { for (var componentIndex = 0, l = this.componentSchemas.length; componentIndex < l; componentIndex++) { var componentData = components[componentIndex]; var componentSchema = this.componentSchemas[componentIndex]; var componentElement = this.getCachedElement(componentIndex); if (componentElement === null || componentData === null || componentData === undefined ) { continue; } if (componentSchema.component) { if (componentSchema.property) { this.updateNetworkedComponent(componentElement, componentSchema.component, componentSchema.property, componentData); } else { this.updateNetworkedComponent(componentElement, componentSchema.component, componentData); } } else { this.updateNetworkedComponent(componentElement, componentSchema, componentData); } } }, updateNetworkedComponent: function (el, componentName, data, value) { if(!NAF.options.useLerp || !OBJECT3D_COMPONENTS.includes(componentName)) { if (value === undefined) { el.setAttribute(componentName, data); } else { el.setAttribute(componentName, data, value); } return; } let bufferInfo; for (let i = 0, l = this.bufferInfos.length; i < l; i++) { const info = this.bufferInfos[i]; if (info.object3D === el.object3D) { bufferInfo = info; break; } } if (!bufferInfo) { bufferInfo = { buffer: new InterpolationBuffer(InterpolationBuffer.MODE_LERP, 0.1), object3D: el.object3D, componentNames: [componentName] }; this.bufferInfos.push(bufferInfo); } else { var componentNames = bufferInfo.componentNames; if (!componentNames.includes(componentName)) { componentNames.push(componentName); } } var buffer = bufferInfo.buffer; switch(componentName) { case 'position': buffer.setPosition(this.bufferPosition.set(data.x, data.y, data.z)); return; case 'rotation': this.conversionEuler.set(DEG2RAD * data.x, DEG2RAD * data.y, DEG2RAD * data.z); buffer.setQuaternion(this.bufferQuaternion.setFromEuler(this.conversionEuler)); return; case 'scale': buffer.setScale(this.bufferScale.set(data.x, data.y, data.z)); return; } NAF.log.error('Could not set value in interpolation buffer.', el, componentName, data, bufferInfo); }, removeLerp: function() { this.bufferInfos = []; }, remove: function () { if (this.isMine() && NAF.connection.isConnected()) { var syncData = { networkId: this.data.networkId }; if (NAF.entities.hasEntity(this.data.networkId)) { NAF.connection.broadcastDataGuaranteed('r', syncData); } else { NAF.log.error("Removing networked entity that is not in entities array."); } } NAF.entities.forgetEntity(this.data.networkId); document.body.dispatchEvent(this.entityRemovedEvent(this.data.networkId)); this.el.sceneEl.systems.networked.deregister(this); }, entityCreatedEvent() { return new CustomEvent('entityCreated', {detail: {el: this.el}}); }, entityRemovedEvent(networkId) { return new CustomEvent('entityRemoved', {detail: {networkId: networkId}}); } });
Persistent entities should never result in isFirstSyncs
src/components/networked.js
Persistent entities should never result in isFirstSyncs
<ide><path>rc/components/networked.js <ide> syncData.persistent = data.persistent; <ide> syncData.parent = this.getParentId(); <ide> syncData.components = components; <del> syncData.isFirstSync = !!isFirstSync; <add> syncData.isFirstSync = !data.persistent && !!isFirstSync; <ide> return syncData; <ide> }, <ide>
Java
apache-2.0
a173b385473844b62c4793f42471f5586040304c
0
before/quality-check
/******************************************************************************* * Copyright 2013 André Rouél and Dominik Seichter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package net.sf.qualitycheck; import java.lang.annotation.Annotation; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collection; import java.util.Map; import java.util.regex.Pattern; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; import net.sf.qualitycheck.exception.IllegalArgumentNotContainedException; import net.sf.qualitycheck.exception.IllegalEmptyArgumentException; import net.sf.qualitycheck.exception.IllegalEqualException; import net.sf.qualitycheck.exception.IllegalInstanceOfArgumentException; import net.sf.qualitycheck.exception.IllegalMissingAnnotationException; import net.sf.qualitycheck.exception.IllegalNaNArgumentException; import net.sf.qualitycheck.exception.IllegalNegativeArgumentException; import net.sf.qualitycheck.exception.IllegalNotEqualException; import net.sf.qualitycheck.exception.IllegalNotGreaterOrEqualThanException; import net.sf.qualitycheck.exception.IllegalNotGreaterThanException; import net.sf.qualitycheck.exception.IllegalNotLesserThanException; import net.sf.qualitycheck.exception.IllegalNotNullArgumentException; import net.sf.qualitycheck.exception.IllegalNullArgumentException; import net.sf.qualitycheck.exception.IllegalNullElementsException; import net.sf.qualitycheck.exception.IllegalNumberArgumentException; import net.sf.qualitycheck.exception.IllegalNumericArgumentException; import net.sf.qualitycheck.exception.IllegalPatternArgumentException; import net.sf.qualitycheck.exception.IllegalPositionIndexException; import net.sf.qualitycheck.exception.IllegalPositiveArgumentException; import net.sf.qualitycheck.exception.IllegalRangeException; import net.sf.qualitycheck.exception.IllegalStateOfArgumentException; import net.sf.qualitycheck.exception.RuntimeInstantiationException; /** * This class offers simple static methods to test your arguments to be valid. * * Checks should be added to all arguments of all public methods in your class to assure that only valid values can be * encountered within your class. This is major step to avoid technical errors like NullPointerExceptions or * IndexOutOfBoundsException in your code. * * @author André Rouél * @author Dominik Seichter */ public final class Check { /** * Holder for the regular expression to determine numeric values. Using the holder pattern guarantees that the * regular expression is initialized before the first use (thread safe!) and that it is only initialized if it is * needed. So, we do not pay any performance bounty for regular expressions when using other checks. */ protected static final class NumericRegularExpressionHolder { private static final Pattern NUMERIC_REGEX = Pattern.compile("[0-9]+"); @Nonnull public static Pattern getPattern() { return NUMERIC_REGEX; } } /** * Representation of an empty argument name. */ private static final String EMPTY_ARGUMENT_NAME = ""; /** * Checks the passed {@code value} against the ranges of the given datatype. * * @param value * value which must be a number and in the range of the given datatype. * @param type * requested return value type, must be a subclass of {@code Number} * @return a number * * @throws NumberFormatException * if the given value can not be parsed as a number */ private static <T> Number checkNumberInRange(final String value, final Class<T> type) { final Number ret; if (type.equals(Byte.class)) { final Number number = new BigInteger(value); NumberInRange.checkByte(number); ret = Byte.valueOf(number.byteValue()); } else if (type.equals(Double.class)) { final Number number = new BigDecimal(value); NumberInRange.checkDouble(number); ret = Double.valueOf(number.doubleValue()); } else if (type.equals(Float.class)) { final Number number = new BigDecimal(value); NumberInRange.checkFloat(number); ret = Float.valueOf(number.floatValue()); } else if (type.equals(Integer.class)) { final Number number = new BigInteger(value); NumberInRange.checkInteger(number); ret = Integer.valueOf(number.intValue()); } else if (type.equals(Long.class)) { final Number number = new BigInteger(value); NumberInRange.checkLong(number); ret = Long.valueOf(number.longValue()); } else if (type.equals(Short.class)) { final Number number = new BigInteger(value); NumberInRange.checkShort(number); ret = Short.valueOf(number.shortValue()); } else if (type.equals(BigInteger.class)) { ret = new BigInteger(value); } else if (type.equals(BigDecimal.class)) { ret = new BigDecimal(value); } else { throw new IllegalNumberArgumentException("Return value is no known subclass of 'java.lang.Number': " + type.getName()); } return ret; } /** * Ensures that an element {@code needle} is contained in a collection {@code haystack}. * * <p> * This is in particular useful if you want to check whether an enum value is contained in an {@code EnumSet}. The * check is implemented using {@link java.util.Collection#contains(Object)}. * * <p> * We recommend to use the overloaded method {@link Check#contains(Collection, Object, String)} and pass as second * argument the name of the parameter to enhance the exception message. * * @param haystack * A collection which must contain {@code needle} * @param needle * An object that must be contained into a collection. * @return the passed argument {@code needle} * * @throws IllegalArgumentNotContainedException * if the passed {@code needle} can not be found in {@code haystack} */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalArgumentNotContainedException.class }) public static <T extends Object> T contains(@Nonnull final Collection<T> haystack, @Nonnull final T needle) { Check.notNull(haystack, "haystack"); Check.notNull(needle, "needle"); if (!haystack.contains(needle)) { throw new IllegalArgumentNotContainedException(needle); } return needle; } /** * Ensures that an element {@code needle} is contained in a collection {@code haystack}. * * <p> * This is in particular useful if you want to check whether an enum value is contained in an {@code EnumSet}. The * check is implemented using {@link java.util.Collection#contains(Object)}. * * @param haystack * A collection which must contain {@code needle} * @param needle * An object that must be contained into a collection. * @param name * name of argument of {@code needle} * @return the passed argument {@code needle} * * @throws IllegalArgumentNotContainedException * if the passed {@code needle} can not be found in {@code haystack} */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalArgumentNotContainedException.class }) public static <T extends Object> T contains(@Nonnull final Collection<T> haystack, @Nonnull final T needle, @Nonnull final String name) { Check.notNull(haystack, "haystack"); Check.notNull(needle, "needle"); if (!haystack.contains(needle)) { throw new IllegalArgumentNotContainedException(name, needle); } return needle; } /** * Checks if the given array contains {@code null}. * * @param array * reference to an array * @return {@code true} if the array contains {@code null}, otherwise {@code false} */ private static boolean containsNullElements(@Nonnull final Object[] array) { boolean containsNull = false; for (final Object o : array) { if (o == null) { containsNull = true; break; } } return containsNull; } /** * Ensures that a passed boolean is equal to another boolean. The comparison is made using * <code>expected != check</code>. * * <p> * We recommend to use the overloaded method {@link Check#equals(boolean, boolean, String)} and pass as second * argument the name of the parameter to enhance the exception message. * * @param expected * Expected value * @param check * boolean to be checked * @return the passed boolean argument {@code check} * * @throws IllegalNotEqualException * if both argument values are not equal */ @Throws(IllegalNotEqualException.class) public static boolean equals(@Nonnull final boolean expected, @Nonnull final boolean check) { // NOSONAR // Sonar warns about suspicious equals method name, as the name is intended deactivate sonar if (expected != check) { throw new IllegalNotEqualException(check); } return check; } /** * Ensures that a passed boolean is equal to another boolean. The comparison is made using * <code>expected != check</code>. * * @param expected * Expected value * @param check * boolean to be checked * @param message * an error message describing why the booleans must equal (will be passed to * {@code IllegalNotEqualException}) * @return the passed boolean argument {@code check} * * @throws IllegalNotEqualException * if both argument values are not equal */ @Throws(IllegalNotEqualException.class) public static boolean equals(@Nonnull final boolean expected, @Nonnull final boolean check, final String message) { // NOSONAR // Sonar warns about suspicious equals method name, as the name is intended deactivate sonar if (expected != check) { throw new IllegalNotEqualException(message, check); } return check; } /** * Ensures that a passed byte is equal to another byte. The comparison is made using <code>expected != check</code>. * * <p> * We recommend to use the overloaded method {@link Check#equals(byte, byte, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param expected * Expected value * @param check * byte to be checked * @return the passed byte argument {@code check} * * @throws IllegalNotEqualException * if both argument values are not equal */ @Throws(IllegalNotEqualException.class) public static byte equals(@Nonnull final byte expected, @Nonnull final byte check) { // NOSONAR // Sonar warns about suspicious equals method name, as the name is intended deactivate sonar if (expected != check) { throw new IllegalNotEqualException(check); } return check; } /** * Ensures that a passed byte is equal to another byte. The comparison is made using <code>expected != check</code>. * * @param expected * Expected value * @param check * byte to be checked * @param message * an error message describing why the bytes must equal (will be passed to * {@code IllegalNotEqualException}) * @return the byte boolean argument {@code check} * * @throws IllegalNotEqualException * if both argument values are not equal */ @Throws(IllegalNotEqualException.class) public static byte equals(@Nonnull final byte expected, @Nonnull final byte check, final String message) { // NOSONAR // Sonar warns about suspicious equals method name, as the name is intended deactivate sonar if (expected != check) { throw new IllegalNotEqualException(message, check); } return check; } /** * Ensures that a passed char is equal to another char. The comparison is made using <code>expected != check</code>. * * <p> * We recommend to use the overloaded method {@link Check#equals(char, char, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param expected * Expected value * @param check * char to be checked * @return the passed char argument {@code check} * * @throws IllegalNotEqualException * if both argument values are not equal */ @Throws(IllegalNotEqualException.class) public static char equals(@Nonnull final char expected, @Nonnull final char check) { // NOSONAR // Sonar warns about suspicious equals method name, as the name is intended deactivate sonar if (expected != check) { throw new IllegalNotEqualException(check); } return check; } /** * Ensures that a passed char is equal to another char. The comparison is made using <code>expected != check</code>. * * @param expected * Expected value * @param check * char to be checked * @param message * an error message describing why the chars must equal (will be passed to * {@code IllegalNotEqualException}) * @return the passed char argument {@code check} * * @throws IllegalNotEqualException * if both argument values are not equal */ @Throws(IllegalNotEqualException.class) public static char equals(@Nonnull final char expected, @Nonnull final char check, final String message) { // NOSONAR // Sonar warns about suspicious equals method name, as the name is intended deactivate sonar if (expected != check) { throw new IllegalNotEqualException(message, check); } return check; } /** * Ensures that a passed intH is equal to another int. The comparison is made using <code>expected != check</code>. * * <p> * We recommend to use the overloaded method {@link Check#equals(int, int, String)} and pass as second argument the * name of the parameter to enhance the exception message. * * @param expected * Expected value * @param check * int to be checked * @return the passed int argument {@code check} * * @throws IllegalNotEqualException * if both argument values are not equal */ @Throws(IllegalNotEqualException.class) public static int equals(@Nonnull final int expected, @Nonnull final int check) { // NOSONAR // Sonar warns about suspicious equals method name, as the name is intended deactivate sonar if (expected != check) { throw new IllegalNotEqualException(check); } return check; } /** * Ensures that a passed int is equal to another int. The comparison is made using <code>expected != check</code>. * * @param expected * Expected value * @param check * int to be checked * @param message * an error message describing why the ints must equal (will be passed to * {@code IllegalNotEqualException}) * @return the passed int argument {@code check} * * @throws IllegalNotEqualException * if both argument values are not equal */ @Throws(IllegalNotEqualException.class) public static int equals(@Nonnull final int expected, @Nonnull final int check, final String message) { // NOSONAR // Sonar warns about suspicious equals method name, as the name is intended deactivate sonar if (expected != check) { throw new IllegalNotEqualException(message, check); } return check; } /** * Ensures that a passed long is equal to another long. The comparison is made using <code>expected != check</code>. * * <p> * We recommend to use the overloaded method {@link Check#equals(long, long, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param expected * Expected value * @param check * long to be checked * @return the passed long argument {@code check} * * @throws IllegalNotEqualException * if both argument values are not equal */ @Throws(IllegalNotEqualException.class) public static long equals(@Nonnull final long expected, @Nonnull final long check) { // NOSONAR // Sonar warns about suspicious equals method name, as the name is intended deactivate sonar if (expected != check) { throw new IllegalNotEqualException(check); } return check; } /** * Ensures that a passed long is equal to another long. The comparison is made using <code>expected != check</code>. * * @param expected * Expected value * @param check * long to be checked * @param message * an error message describing why the longs must equal (will be passed to * {@code IllegalNotEqualException}) * @return the passed long argument {@code check} * * @throws IllegalNotEqualException * if both argument values are not equal */ @Throws(IllegalNotEqualException.class) public static long equals(@Nonnull final long expected, @Nonnull final long check, final String message) { // NOSONAR // Sonar warns about suspicious equals method name, as the name is intended deactivate sonar if (expected != check) { throw new IllegalNotEqualException(message, check); } return check; } /** * Ensures that a passed short is equal to another short. The comparison is made using * <code>expected != check</code>. * * <p> * We recommend to use the overloaded method {@link Check#equals(short, short, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param expected * Expected value * @param check * short to be checked * @return the passed short argument {@code check} * * @throws IllegalNotEqualException * if both argument values are not equal */ @Throws(IllegalNotEqualException.class) public static short equals(@Nonnull final short expected, @Nonnull final short check) { // NOSONAR // Sonar warns about suspicious equals method name, as the name is intended deactivate sonar if (expected != check) { throw new IllegalNotEqualException(check); } return check; } /** * Ensures that a passed short is equal to another short. The comparison is made using * <code>expected != check</code>. * * @param expected * Expected value * @param check * short to be checked * @param message * an error message describing why the shorts must equal (will be passed to * {@code IllegalNotEqualException}) * @return the passed short {@code check} * * @throws IllegalNotEqualException * if both argument values are not equal */ @Throws(IllegalNotEqualException.class) public static short equals(@Nonnull final short expected, @Nonnull final short check, final String message) { // NOSONAR // Sonar warns about suspicious equals method name, as the name is intended deactivate sonar if (expected != check) { throw new IllegalNotEqualException(message, check); } return check; } /** * Ensures that a passed {@code Comparable} is equal to another {@code Comparable}. The comparison is made using * {@code expected.compareTo(check) != 0}. * * <p> * We recommend to use the overloaded method {@link Check#equals(Comparable, Comparable, String)} and pass as second * argument the name of the parameter to enhance the exception message. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotEqualException * if both argument values are not equal */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNotEqualException.class }) public static <T extends Comparable<T>> T equals(@Nonnull final T expected, @Nonnull final T check) { // NOSONAR // Sonar warns about suspicious equals method name, as the name is intended deactivate sonar Check.notNull(expected, "expected"); Check.notNull(check, "check"); if (expected.compareTo(check) != 0) { throw new IllegalNotEqualException(check); } return check; } /** * Ensures that a passed object is equal to another object. The comparison is made using a call to * {@code expected.equals(check) }. * * <p> * We recommend to use the overloaded method {@link Check#equals(Object, Object, String)} and pass as second * argument the name of the parameter to enhance the exception message. * * @param expected * Expected value * @param check * Object to be checked * @return the passed argument {@code check} * * @throws IllegalNotEqualException * if both argument values are not equal */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNotEqualException.class }) public static <T extends Object> T equals(@Nonnull final T expected, @Nonnull final T check) { // NOSONAR // Sonar warns about suspicious equals method name, as the name is intended deactivate sonar Check.notNull(expected, "expected"); Check.notNull(check, "check"); if (!expected.equals(check)) { throw new IllegalNotEqualException(check); } return check; } /** * Ensures that a passed {@code Comparable} is equal to another {@code Comparable}. The comparison is made using * {@code expected.compareTo(check) != 0}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the <a>s must equal (will be passed to * {@code IllegalNotEqualException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotEqualException * if both argument values are not equal */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNotEqualException.class }) public static <T extends Comparable<T>> T equals(@Nonnull final T expected, @Nonnull final T check, final String message) { // NOSONAR // Sonar warns about suspicious equals method name, as the name is intended deactivate sonar Check.notNull(expected, "expected"); Check.notNull(check, "check"); if (expected.compareTo(check) != 0) { throw new IllegalNotEqualException(message, check); } return check; } /** * Ensures that a passed object is equal to another object. The comparison is made using a call to * {@code expected.equals(check) }. * * @param expected * Expected value * @param check * Object to be checked * @param message * an error message describing why the objects must equal (will be passed to * {@code IllegalNotEqualException}) * @return the passed argument {@code check} * * @throws IllegalNotEqualException * if both argument values are not equal */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNotEqualException.class }) public static <T extends Object> T equals(@Nonnull final T expected, @Nonnull final T check, final String message) { // NOSONAR // Sonar warns about suspicious equals method name, as the name is intended deactivate sonar Check.notNull(expected, "expected"); Check.notNull(check, "check"); if (!expected.equals(check)) { throw new IllegalNotEqualException(message, check); } return check; } /** * Ensures that a passed {@code Comparable} is greater or equal compared to another {@code Comparable}. The * comparison is made using {@code expected.compareTo(check) > 0}. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterOrEqualThanException * if the argument value {@code check} is not greater or equal than the value {@code expected} when * using method {@code compareTo} */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNotGreaterOrEqualThanException.class }) public static <T extends Comparable<T>> T greaterOrEqualThan(@Nonnull final T expected, @Nonnull final T check) { Check.notNull(expected, "expected"); Check.notNull(check, "check"); if (expected.compareTo(check) > 0) { throw new IllegalNotGreaterOrEqualThanException(check); } return check; } /** * Ensures that a passed {@code Comparable} is greater or equal compared to another {@code Comparable}. The * comparison is made using {@code expected.compareTo(check) > 0}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the comparable must be greater than a value (will be passed to * {@code IllegalNotGreaterOrEqualThanException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterOrEqualThanException * if the argument value {@code check} is not greater or equal than the value {@code expected} when * using method {@code compareTo} */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNotGreaterOrEqualThanException.class }) public static <T extends Comparable<T>> T greaterOrEqualThan(@Nonnull final T expected, @Nonnull final T check, final String message) { Check.notNull(expected, "expected"); Check.notNull(check, "check"); if (expected.compareTo(check) > 0) { throw new IllegalNotGreaterOrEqualThanException(message, check); } return check; } /** * Ensures that a passed {@code byte} is greater to another {@code byte}. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterThanException * if the argument value {@code check} is not greater than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotGreaterThanException.class) public static byte greaterThan(@Nonnull final byte expected, @Nonnull final byte check) { if (expected >= check) { throw new IllegalNotGreaterThanException(check); } return check; } /** * Ensures that a passed {@code byte} is greater than another {@code byte}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the comparable must be greater than a value (will be passed to * {@code IllegalNotGreaterThanException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterThanException * if the argument value {@code check} is not greater than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotGreaterThanException.class) public static byte greaterThan(@Nonnull final byte expected, @Nonnull final byte check, final String message) { if (expected >= check) { throw new IllegalNotGreaterThanException(message, check); } return check; } /** * Ensures that a passed {@code char} is greater to another {@code char}. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterThanException * if the argument value {@code check} is not greater than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotGreaterThanException.class) public static char greaterThan(@Nonnull final char expected, @Nonnull final char check) { if (expected >= check) { throw new IllegalNotGreaterThanException(check); } return check; } /** * Ensures that a passed {@code char} is greater than another {@code char}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the comparable must be greater than a value (will be passed to * {@code IllegalNotGreaterThanException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterThanException * if the argument value {@code check} is not greater than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotGreaterThanException.class) public static char greaterThan(@Nonnull final char expected, @Nonnull final char check, final String message) { if (expected >= check) { throw new IllegalNotGreaterThanException(message, check); } return check; } /** * Ensures that a passed {@code double} is greater to another {@code double}. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterThanException * if the argument value {@code check} is not greater than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotGreaterThanException.class) public static double greaterThan(@Nonnull final double expected, @Nonnull final double check) { if (expected >= check) { throw new IllegalNotGreaterThanException(check); } return check; } /** * Ensures that a passed {@code double} is greater than another {@code double}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the comparable must be greater than a value (will be passed to * {@code IllegalNotGreaterThanException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterThanException * if the argument value {@code check} is not greater than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotGreaterThanException.class) public static double greaterThan(@Nonnull final double expected, @Nonnull final double check, final String message) { if (expected >= check) { throw new IllegalNotGreaterThanException(message, check); } return check; } /** * Ensures that a passed {@code float} is greater to another {@code float}. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterThanException * if the argument value {@code check} is not greater than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotGreaterThanException.class) public static float greaterThan(@Nonnull final float expected, @Nonnull final float check) { if (expected >= check) { throw new IllegalNotGreaterThanException(check); } return check; } /** * Ensures that a passed {@code float} is greater than another {@code float}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the comparable must be greater than a value (will be passed to * {@code IllegalNotGreaterThanException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterThanException * if the argument value {@code check} is not greater than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotGreaterThanException.class) public static float greaterThan(@Nonnull final float expected, @Nonnull final float check, final String message) { if (expected >= check) { throw new IllegalNotGreaterThanException(message, check); } return check; } /** * Ensures that a passed {@code int} is greater to another {@code int}. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterThanException * if the argument value {@code check} is not greater than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotGreaterThanException.class) public static int greaterThan(@Nonnull final int expected, @Nonnull final int check) { if (expected >= check) { throw new IllegalNotGreaterThanException(check); } return check; } /** * Ensures that a passed {@code int} is greater than another {@code int}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the comparable must be greater than a value (will be passed to * {@code IllegalNotGreaterThanException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterThanException * if the argument value {@code check} is not greater than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotGreaterThanException.class) public static int greaterThan(@Nonnull final int expected, @Nonnull final int check, final String message) { if (expected >= check) { throw new IllegalNotGreaterThanException(message, check); } return check; } /** * Ensures that a passed {@code long} is greater to another {@code long}. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterThanException * if the argument value {@code check} is not greater than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotGreaterThanException.class) public static long greaterThan(@Nonnull final long expected, @Nonnull final long check) { if (expected >= check) { throw new IllegalNotGreaterThanException(check); } return check; } /** * Ensures that a passed {@code long} is greater than another {@code long}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the comparable must be greater than a value (will be passed to * {@code IllegalNotGreaterThanException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterThanException * if the argument value {@code check} is not greater than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotGreaterThanException.class) public static long greaterThan(@Nonnull final long expected, @Nonnull final long check, final String message) { if (expected >= check) { throw new IllegalNotGreaterThanException(message, check); } return check; } /** * Ensures that a passed {@code short} is greater to another {@code short}. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterThanException * if the argument value {@code check} is not greater than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotGreaterThanException.class) public static short greaterThan(@Nonnull final short expected, @Nonnull final short check) { if (expected >= check) { throw new IllegalNotGreaterThanException(check); } return check; } /** * Ensures that a passed {@code short} is greater than another {@code short}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the comparable must be greater than a value (will be passed to * {@code IllegalNotGreaterThanException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterThanException * if the argument value {@code check} is not greater than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotGreaterThanException.class) public static short greaterThan(@Nonnull final short expected, @Nonnull final short check, final String message) { if (expected >= check) { throw new IllegalNotGreaterThanException(message, check); } return check; } /** * Ensures that a passed {@code Comparable} is greater to another {@code Comparable}. The comparison is made using * {@code expected.compareTo(check) >= 0}. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterThanException * if the argument value {@code check} is not greater than value {@code expected} when using method * {@code compareTo} */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNotGreaterThanException.class }) public static <T extends Comparable<T>> T greaterThan(@Nonnull final T expected, @Nonnull final T check) { Check.notNull(expected, "expected"); Check.notNull(check, "check"); if (expected.compareTo(check) >= 0) { throw new IllegalNotGreaterThanException(check); } return check; } /** * Ensures that a passed {@code Comparable} is greater than another {@code Comparable}. The comparison is made using * {@code expected.compareTo(check) >= 0}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the comparable must be greater than a value (will be passed to * {@code IllegalNotGreaterThanException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterThanException * if the argument value {@code check} is not greater than value {@code expected} when using method * {@code compareTo} */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNotGreaterThanException.class }) public static <T extends Comparable<T>> T greaterThan(@Nonnull final T expected, @Nonnull final T check, final String message) { Check.notNull(expected, "expected"); Check.notNull(check, "check"); if (expected.compareTo(check) >= 0) { throw new IllegalNotGreaterThanException(message, check); } return check; } /** * Ensures that a passed class has an annotation of a specific type * * @param clazz * the class that must have a required annotation * @param annotation * the type of annotation that is required on the class * @return the given annotation which is present on the checked class * * @throws IllegalMissingAnnotationException * if the passed annotation is not annotated at the given class */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalMissingAnnotationException.class }) public static Annotation hasAnnotation(@Nonnull final Class<?> clazz, @Nonnull final Class<? extends Annotation> annotation) { Check.notNull(clazz, "clazz"); Check.notNull(annotation, "annotation"); if (!clazz.isAnnotationPresent(annotation)) { throw new IllegalMissingAnnotationException(annotation, clazz); } return clazz.getAnnotation(annotation); } /** * Ensures that a passed argument is a member of a specific type. * * @param type * class that the given object is a member of * @param obj * the object reference that should be a member of a specific {@code type} * @return the given object cast to type * * @throws IllegalInstanceOfArgumentException * if the given argument {@code obj} is not a member of {@code type} */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalInstanceOfArgumentException.class }) @SuppressWarnings("unchecked") public static <T> T instanceOf(@Nonnull final Class<?> type, @Nonnull final Object obj) { return (T) instanceOf(type, obj, EMPTY_ARGUMENT_NAME); } /** * Ensures that a passed argument is a member of a specific type. * * @param type * class that the given object is a member of * @param obj * the object reference that should be a member of a specific {@code type} * @param name * name of object reference (in source code) * @return the given object cast to type * * @throws IllegalInstanceOfArgumentException * if the given argument {@code obj} is not a member of {@code type} */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalInstanceOfArgumentException.class }) @SuppressWarnings("unchecked") public static <T> T instanceOf(@Nonnull final Class<?> type, @Nonnull final Object obj, @Nullable final String name) { Check.notNull(type, "type"); Check.notNull(obj, "obj"); if (!type.isInstance(obj)) { throw new IllegalInstanceOfArgumentException(name, type, obj.getClass()); } return (T) obj; } /** * Ensures that a given argument is {@code null}. * * Normally, the usage of {@code null} arguments is disregarded by the authors of quality-check. Still, there are * certain circumstances where null is required, e.g. the primary key of an entity before it is written to the * database for the first time. In such cases it is ok to use null values and there should also be checks for them. * For example, to avoid overwriting an existing primary key with a new one. * * @param reference * reference which must be null * * @throws IllegalNotNullArgumentException * if the given argument {@code reference} is not null */ @Throws(IllegalNotNullArgumentException.class) public static void isNull(@Nullable final Object reference) { if (reference != null) { throw new IllegalNotNullArgumentException(reference); } } /** * Ensures that a given argument is {@code null}. * * Normally, the usage of {@code null} arguments is disregarded by the authors of quality-check. Still, there are * certain circumstances where null is required, e.g. the primary key of an entity before it is written to the * database for the first time. In such cases it is ok to use null values and there should also be checks for them. * For example, to avoid overwriting an existing primary key with a new one. * * @param reference * reference which must be null. * @param name * name of object reference (in source code) * * @throws IllegalNotNullArgumentException * if the given argument {@code reference} is not null */ @Throws(IllegalNotNullArgumentException.class) public static void isNull(@Nullable final Object reference, @Nullable final String name) { if (reference != null) { throw new IllegalNotNullArgumentException(name, reference); } } /** * Ensures that a String argument is a number. * * @param value * value which must be a number * @return the given string argument converted to an int * * @throws IllegalNumberArgumentException * if the given argument {@code value} is not a number */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNumberArgumentException.class }) public static int isNumber(@Nonnull final String value) { Check.notNull(value, "value"); return Check.isNumber(value, Integer.class).intValue(); } /** * Ensures that a String argument is a number. This overload supports all subclasses of {@code Number}. The number * is first converted to a BigInteger * * @param value * value which must be a number * @param type * requested return value type, must be a subclass of {@code Number}, i.e. one of {@code BigDecimal, * BigInteger, Byte, Double, Float, Integer, Long, Short} * @return the given string argument converted to a number of the requested type * * @throws IllegalNumberArgumentException * if the given argument {@code value} is no number */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNumberArgumentException.class }) public static <T extends Number> T isNumber(@Nonnull final String value, @Nonnull final Class<T> type) { return isNumber(value, null, type); } /** * Ensures that a string argument is a number according to {@code Integer.parseInt} * * @param value * value which must be a number * @param name * name of object reference (in source code) * @return the given string argument converted to an int * * @throws IllegalNumberArgumentException * if the given argument {@code value} is no number */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNumberArgumentException.class }) public static int isNumber(@Nonnull final String value, @Nullable final String name) { Check.notNull(value, "value"); return Check.isNumber(value, name, Integer.class).intValue(); } /** * Ensures that a String argument is a number. This overload supports all subclasses of {@code Number}. The number * is first converted to a {@code BigDecimal} or {@code BigInteger}. Floating point types are only supported if the * {@code type} is one of {@code Float, Double, BigDecimal}. * * <p> * This method does also check against the ranges of the given datatypes. * * @param value * value which must be a number and in the range of the given datatype. * @param name * (optional) name of object reference (in source code). * @param type * requested return value type, must be a subclass of {@code Number}, i.e. one of {@code BigDecimal, * BigInteger, Byte, Double, Float, Integer, Long, Short} * @return the given string argument converted to a number of the requested type * * @throws IllegalNumberArgumentException * if the given argument {@code value} is no number */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNumberArgumentException.class }) public static <T extends Number> T isNumber(@Nonnull final String value, @Nullable final String name, @Nonnull final Class<T> type) { Check.notNull(value, "value"); Check.notNull(type, "type"); final Number ret; try { ret = checkNumberInRange(value, type); } catch (final NumberFormatException nfe) { if (name == null) { throw new IllegalNumberArgumentException(value, nfe); } else { throw new IllegalNumberArgumentException(name, value, nfe); } } return type.cast(ret); } /** * Ensures that a readable sequence of {@code char} values is numeric. Numeric arguments consist only of the * characters 0-9 and may start with 0 (compared to number arguments, which must be valid numbers - think of a bank * account number). * * <p> * We recommend to use the overloaded method {@link Check#isNumeric(CharSequence, String)} and pass as second * argument the name of the parameter to enhance the exception message. * * @param value * a readable sequence of {@code char} values which must be a number * @return the given string argument * @throws IllegalNumberArgumentException * if the given argument {@code value} is no number */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNumberArgumentException.class }) public static <T extends CharSequence> T isNumeric(@Nonnull final T value) { return isNumeric(value, EMPTY_ARGUMENT_NAME); } /** * Ensures that a readable sequence of {@code char} values is numeric. Numeric arguments consist only of the * characters 0-9 and may start with 0 (compared to number arguments, which must be valid numbers - think of a bank * account number). * * @param value * a readable sequence of {@code char} values which must be a number * @param name * name of object reference (in source code) * @return the given string argument * @throws IllegalNumberArgumentException * if the given argument {@code value} is no number */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNumericArgumentException.class }) public static <T extends CharSequence> T isNumeric(@Nonnull final T value, @Nullable final String name) { Check.notNull(value, "value"); if (!matches(NumericRegularExpressionHolder.getPattern(), value)) { throw new IllegalNumericArgumentException(name, value); } return value; } /** * Ensures that a passed {@code byte} is less than another {@code byte}. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code byte} argument {@code check} * * @throws IllegalNotLesserThanException * if the argument value {@code check} is not lesser than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotLesserThanException.class) public static byte lesserThan(@Nonnull final byte expected, @Nonnull final byte check) { if (expected <= check) { throw new IllegalNotLesserThanException(check); } return check; } /** * Ensures that a passed {@code byte} is less than another {@code byte}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the comparables must be less than a value (will be passed to * {@code IllegalNotLessThanException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotLesserThanException * if the argument value {@code check} is not lesser than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotLesserThanException.class) public static byte lesserThan(@Nonnull final byte expected, @Nonnull final byte check, final String message) { if (expected <= check) { throw new IllegalNotLesserThanException(message, check); } return check; } /** * Ensures that a passed {@code char} is less than another {@code char}. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code char} argument {@code check} * * @throws IllegalNotLesserThanException * if the argument value {@code check} is not lesser than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotLesserThanException.class) public static char lesserThan(@Nonnull final char expected, @Nonnull final char check) { if (expected <= check) { throw new IllegalNotLesserThanException(check); } return check; } /** * Ensures that a passed {@code char} is less than another {@code char}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the comparables must be less than a value (will be passed to * {@code IllegalNotLessThanException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotLesserThanException * if the argument value {@code check} is not lesser than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotLesserThanException.class) public static char lesserThan(@Nonnull final char expected, @Nonnull final char check, final String message) { if (expected <= check) { throw new IllegalNotLesserThanException(message, check); } return check; } /** * Ensures that a passed {@code double} is less than another {@code double}. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code double} argument {@code check} * * @throws IllegalNotLesserThanException * if the argument value {@code check} is not lesser than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotLesserThanException.class) public static double lesserThan(@Nonnull final double expected, @Nonnull final double check) { if (expected <= check) { throw new IllegalNotLesserThanException(check); } return check; } /** * Ensures that a passed {@code double} is less than another {@code double}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the comparables must be less than a value (will be passed to * {@code IllegalNotLessThanException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotLesserThanException * if the argument value {@code check} is not lesser than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotLesserThanException.class) public static double lesserThan(@Nonnull final double expected, @Nonnull final double check, final String message) { if (expected <= check) { throw new IllegalNotLesserThanException(message, check); } return check; } /** * Ensures that a passed {@code float} is less than another {@code float}. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code float} argument {@code check} * * @throws IllegalNotLesserThanException * if the argument value {@code check} is not lesser than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotLesserThanException.class) public static float lesserThan(@Nonnull final float expected, @Nonnull final float check) { if (expected <= check) { throw new IllegalNotLesserThanException(check); } return check; } /** * Ensures that a passed {@code float} is less than another {@code float}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the comparables must be less than a value (will be passed to * {@code IllegalNotLessThanException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotLesserThanException * if the argument value {@code check} is not lesser than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotLesserThanException.class) public static float lesserThan(@Nonnull final float expected, @Nonnull final float check, final String message) { if (expected <= check) { throw new IllegalNotLesserThanException(message, check); } return check; } /** * Ensures that a passed {@code int} is less than another {@code int}. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code int} argument {@code check} * * @throws IllegalNotLesserThanException * if the argument value {@code check} is not lesser than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotLesserThanException.class) public static int lesserThan(@Nonnull final int expected, @Nonnull final int check) { if (expected <= check) { throw new IllegalNotLesserThanException(check); } return check; } /** * Ensures that a passed {@code int} is less than another {@code int}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the comparables must be less than a value (will be passed to * {@code IllegalNotLessThanException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotLesserThanException * if the argument value {@code check} is not lesser than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotLesserThanException.class) public static int lesserThan(@Nonnull final int expected, @Nonnull final int check, final String message) { if (expected <= check) { throw new IllegalNotLesserThanException(message, check); } return check; } /** * Ensures that a passed {@code long} is less than another {@code long}. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code long} argument {@code check} * * @throws IllegalNotLesserThanException * if the argument value {@code check} is not lesser than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotLesserThanException.class) public static long lesserThan(@Nonnull final long expected, @Nonnull final long check) { if (expected <= check) { throw new IllegalNotLesserThanException(check); } return check; } /** * Ensures that a passed {@code long} is less than another {@code long}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the comparables must be less than a value (will be passed to * {@code IllegalNotLessThanException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotLesserThanException * if the argument value {@code check} is not lesser than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotLesserThanException.class) public static long lesserThan(@Nonnull final long expected, @Nonnull final long check, final String message) { if (expected <= check) { throw new IllegalNotLesserThanException(message, check); } return check; } /** * Ensures that a passed {@code short} is less than another {@code short}. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code short} argument {@code check} * * @throws IllegalNotLesserThanException * if the argument value {@code check} is not lesser than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotLesserThanException.class) public static short lesserThan(@Nonnull final short expected, @Nonnull final short check) { if (expected <= check) { throw new IllegalNotLesserThanException(check); } return check; } /** * Ensures that a passed {@code short} is less than another {@code short}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the comparables must be less than a value (will be passed to * {@code IllegalNotLessThanException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotLesserThanException * if the argument value {@code check} is not lesser than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotLesserThanException.class) public static short lesserThan(@Nonnull final short expected, @Nonnull final short check, final String message) { if (expected <= check) { throw new IllegalNotLesserThanException(message, check); } return check; } /** * Ensures that a passed {@code Comparable} is less than another {@code Comparable}. The comparison is made using * {@code expected.compareTo(check) <= 0}. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotLesserThanException * if the argument value {@code check} is not lesser than value {@code expected} when using method * {@code compareTo} */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNotLesserThanException.class }) public static <T extends Comparable<T>> T lesserThan(@Nonnull final T expected, @Nonnull final T check) { Check.notNull(expected, "expected"); Check.notNull(check, "check"); if (expected.compareTo(check) <= 0) { throw new IllegalNotLesserThanException(check); } return check; } /** * Ensures that a passed {@code Comparable} is less than another {@code Comparable}. The comparison is made using * {@code expected.compareTo(check) <= 0}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the comparables must be less than a value (will be passed to * {@code IllegalNotLessThanException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotLesserThanException * if the argument value {@code check} is not lesser than value {@code expected} when using method * {@code compareTo} */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNotLesserThanException.class }) public static <T extends Comparable<T>> T lesserThan(@Nonnull final T expected, @Nonnull final T check, final String message) { Check.notNull(expected, "expected"); Check.notNull(check, "check"); if (expected.compareTo(check) <= 0) { throw new IllegalNotLesserThanException(message, check); } return check; } /** * Checks whether a character sequence matches against a specified pattern or not. * * @param pattern * pattern, that the {@code chars} must correspond to * @param chars * a readable sequence of {@code char} values which should match the given pattern * @return {@code true} when {@code chars} matches against the passed {@code pattern}, otherwise {@code false} */ private static boolean matches(@Nonnull final Pattern pattern, @Nonnull final CharSequence chars) { return pattern.matcher(chars).matches(); } /** * Ensures that a readable sequence of {@code char} values matches a specified pattern. If the given character * sequence does not match against the passed pattern, an {@link IllegalPatternArgumentException} will be thrown. * * <p> * We recommend to use the overloaded method {@link Check#matchesPattern(Pattern, CharSequence, String)} and pass as * second argument the name of the parameter to enhance the exception message. * * @param pattern * pattern, that the {@code chars} must correspond to * @param chars * a readable sequence of {@code char} values which should match the given pattern * @return the passed {@code chars} that matches the given pattern * * @throws IllegalNullArgumentException * if the given argument {@code chars} is {@code null} * @throws IllegalPatternArgumentException * if the given {@code chars} that does not match the {@code pattern} */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalPatternArgumentException.class }) public static <T extends CharSequence> T matchesPattern(@Nonnull final Pattern pattern, @Nonnull final T chars) { return matchesPattern(pattern, chars, EMPTY_ARGUMENT_NAME); } /** * Ensures that a readable sequence of {@code char} values matches a specified pattern. If the given character * sequence does not match against the passed pattern, an {@link IllegalPatternArgumentException} will be thrown. * * @param pattern * pattern, that the {@code chars} must correspond to * @param chars * a readable sequence of {@code char} values which should match the given pattern * @param name * name of object reference (in source code) * @return the passed {@code chars} that matches the given pattern * * @throws IllegalNullArgumentException * if the given argument {@code chars} is {@code null} * @throws IllegalPatternArgumentException * if the given {@code chars} that does not match the {@code pattern} */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalPatternArgumentException.class }) public static <T extends CharSequence> T matchesPattern(@Nonnull final Pattern pattern, @Nonnull final T chars, @Nullable final String name) { Check.notNull(pattern, "pattern"); Check.notNull(chars, "chars"); if (!matches(pattern, chars)) { throw new IllegalPatternArgumentException(name, pattern, chars); } return chars; } /** * Ensures that an iterable reference is neither {@code null} nor contains any elements that are {@code null}. * * <p> * We recommend to use the overloaded method {@link Check#noNullElements(Iterable, String)} and pass as second * argument the name of the parameter to enhance the exception message. * * @param iterable * the iterable reference which should not contain {@code null} * @return the passed reference which contains no elements that are {@code null} * * @throws IllegalNullElementsException * if the given argument {@code iterable} contains elements that are {@code null} */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNullElementsException.class }) public static <T extends Iterable<?>> T noNullElements(@Nonnull final T iterable) { return noNullElements(iterable, EMPTY_ARGUMENT_NAME); } /** * Ensures that an iterable reference is neither {@code null} nor contains any elements that are {@code null}. * * @param iterable * the iterable reference which should not contain {@code null} * @param name * name of object reference (in source code) * @return the passed reference which contains no elements that are {@code null} * @throws IllegalNullElementsException * if the given argument {@code iterable} contains elements that are {@code null} */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNullElementsException.class }) public static <T extends Iterable<?>> T noNullElements(@Nonnull final T iterable, final String name) { Check.notNull(iterable, "iterable"); for (final Object element : iterable) { if (element == null) { throw new IllegalNullElementsException(name); } } return iterable; } /** * Ensures that an array does not contain {@code null}. * * <p> * We recommend to use the overloaded method {@link Check#noNullElements(Object[], String)} and pass as second * argument the name of the parameter to enhance the exception message. * * @param array * reference to an array * @return the passed reference which contains no elements that are {@code null} * @throws IllegalNullElementsException * if the given argument {@code array} contains {@code null} */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNullElementsException.class }) public static <T> T[] noNullElements(@Nonnull final T[] array) { return noNullElements(array, EMPTY_ARGUMENT_NAME); } /** * Ensures that an array does not contain {@code null}. * * @param array * reference to an array * @param name * name of object reference (in source code) * @return the passed reference which contains no elements that are {@code null} * @throws IllegalNullElementsException * if the given argument {@code array} contains {@code null} */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNullElementsException.class }) public static <T> T[] noNullElements(@Nonnull final T[] array, @Nullable final String name) { Check.notNull(array, "array"); if (containsNullElements(array)) { throw new IllegalNullElementsException(name); } return array; } /** * Ensures that a passed parameter of the calling method is not empty, using the passed expression to evaluate the * emptiness. * * <p> * We recommend to use the overloaded method {@link Check#notEmpty(boolean, String)} and pass as second argument the * name of the parameter to enhance the exception message. * * @param expression * the result of the expression to verify the emptiness of a reference ({@code true} means empty, * {@code false} means not empty) * * @throws IllegalNullArgumentException * if the given argument {@code reference} is {@code null} * @throws IllegalEmptyArgumentException * if the given argument {@code reference} is empty */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static void notEmpty(final boolean expression) { notEmpty(expression, EMPTY_ARGUMENT_NAME); } /** * Ensures that a passed parameter of the calling method is not empty, using the passed expression to evaluate the * emptiness. * * @param expression * the result of the expression to verify the emptiness of a reference ({@code true} means empty, * {@code false} means not empty) * @param name * name of object reference (in source code) * * @throws IllegalEmptyArgumentException * if the given argument {@code reference} is empty */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static void notEmpty(final boolean expression, @Nullable final String name) { if (expression) { throw new IllegalEmptyArgumentException(name); } } /** * Ensures that a passed string as a parameter of the calling method is not empty. * * <p> * We recommend to use the overloaded method {@link Check#notEmpty(CharSequence, String)} and pass as second * argument the name of the parameter to enhance the exception message. * * @param chars * a readable sequence of {@code char} values which should not be empty * @return the passed reference that is not empty * @throws IllegalNullArgumentException * if the given argument {@code reference} is {@code null} * @throws IllegalEmptyArgumentException * if the given argument {@code reference} is empty */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static <T extends CharSequence> T notEmpty(@Nonnull final T chars) { notNull(chars); notEmpty(chars, chars.length() == 0, EMPTY_ARGUMENT_NAME); return chars; } /** * Ensures that a passed collection as a parameter of the calling method is not empty. * * <p> * We recommend to use the overloaded method {@link Check#notEmpty(Collection, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param collection * a collection which should not be empty * @return the passed reference that is not empty * @throws IllegalNullArgumentException * if the given argument {@code collection} is {@code null} * @throws IllegalEmptyArgumentException * if the given argument {@code collection} is empty */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static <T extends Collection<?>> T notEmpty(@Nonnull final T collection) { notNull(collection); notEmpty(collection, collection.isEmpty(), EMPTY_ARGUMENT_NAME); return collection; } /** * Ensures that a passed map as a parameter of the calling method is not empty. * * <p> * We recommend to use the overloaded method {@link Check#notEmpty(Collection, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param map * a map which should not be empty * @return the passed reference that is not empty * @throws IllegalNullArgumentException * if the given argument {@code map} is {@code null} * @throws IllegalEmptyArgumentException * if the given argument {@code map} is empty */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static <T extends Map<?, ?>> T notEmpty(@Nonnull final T map) { notNull(map); notEmpty(map, map.isEmpty(), EMPTY_ARGUMENT_NAME); return map; } /** * Ensures that an object reference passed as a parameter to the calling method is not empty. The passed boolean * value is the result of checking whether the reference is empty or not. * * <p> * The following example describes how to use it. * * <pre> * &#064;ArgumentsChecked * public setText(String text) { * Check.notEmpty(text, text.isEmpty(), &quot;text&quot;); * this.text = text; * } * </pre> * * @param reference * an object reference which should not be empty * @param expression * the result of the expression to verify the emptiness of a reference ({@code true} means empty, * {@code false} means not empty) * @param name * name of object reference (in source code) * @return the passed reference that is not empty * @throws IllegalNullArgumentException * if the given argument {@code reference} is {@code null} * @throws IllegalEmptyArgumentException * if the given argument {@code reference} is empty */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static <T> T notEmpty(@Nonnull final T reference, final boolean expression, @Nullable final String name) { notNull(reference, name); if (expression) { throw new IllegalEmptyArgumentException(name); } return reference; } /** * Ensures that a passed string as a parameter of the calling method is not empty. * * <p> * The following example describes how to use it. * * <pre> * &#064;ArgumentsChecked * public setText(String text) { * this.text = Check.notEmpty(text, &quot;text&quot;); * } * </pre> * * @param chars * a readable sequence of {@code char} values which should not be empty * @param name * name of object reference (in source code) * @return the passed reference that is not empty * @throws IllegalNullArgumentException * if the given argument {@code string} is {@code null} * @throws IllegalEmptyArgumentException * if the given argument {@code string} is empty */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static <T extends CharSequence> T notEmpty(@Nonnull final T chars, @Nullable final String name) { notNull(chars, name); notEmpty(chars, chars.length() == 0, name); return chars; } /** * Ensures that a passed map as a parameter of the calling method is not empty. * * <p> * We recommend to use the overloaded method {@link Check#notEmpty(Collection, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param map * a map which should not be empty * @param name * name of object reference (in source code) * @return the passed reference that is not empty * @throws IllegalNullArgumentException * if the given argument {@code map} is {@code null} * @throws IllegalEmptyArgumentException * if the given argument {@code map} is empty */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static <T extends Map<?, ?>> T notEmpty(@Nonnull final T map, @Nullable final String name) { notNull(map); notEmpty(map, map.isEmpty(), name); return map; } /** * Ensures that a passed collection as a parameter of the calling method is not empty. * * <p> * The following example describes how to use it. * * <pre> * &#064;ArgumentsChecked * public setCollection(Collection&lt;String&gt; collection) { * this.collection = Check.notEmpty(collection, &quot;collection&quot;); * } * </pre> * * @param collection * a collection which should not be empty * @param name * name of object reference (in source code) * @return the passed reference that is not empty * @throws IllegalNullArgumentException * if the given argument {@code collection} is {@code null} * @throws IllegalEmptyArgumentException * if the given argument {@code collection} is empty */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static <T extends Collection<?>> T notEmpty(@Nonnull final T collection, @Nullable final String name) { notNull(collection, name); notEmpty(collection, collection.isEmpty(), name); return collection; } /** * Ensures that a passed map as a parameter of the calling method is not empty. * * <p> * We recommend to use the overloaded method {@link Check#notEmpty(Object[], String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param array * a map which should not be empty * @return the passed reference that is not empty * @throws IllegalNullArgumentException * if the given argument {@code array} is {@code null} * @throws IllegalEmptyArgumentException * if the given argument {@code array} is empty */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static <T> T[] notEmpty(@Nonnull final T[] array) { notNull(array); notEmpty(array, array.length == 0, EMPTY_ARGUMENT_NAME); return array; } /** * Ensures that a passed map as a parameter of the calling method is not empty. * * @param array * a map which should not be empty * @param name * name of object reference (in source code) * @return the passed reference that is not empty * @throws IllegalNullArgumentException * if the given argument {@code array} is {@code null} * @throws IllegalEmptyArgumentException * if the given argument {@code array} is empty */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static <T> T[] notEmpty(@Nonnull final T[] array, @Nullable final String name) { notNull(array); notEmpty(array, array.length == 0, EMPTY_ARGUMENT_NAME); return array; } /** * Ensures that a passed boolean is not equal to another boolean. The comparison is made using * <code>expected == check</code>. * * <p> * We recommend to use the overloaded method {@link Check#notEquals(boolean, boolean, String)} and pass as second * argument the name of the parameter to enhance the exception message. * * @param expected * Expected value * @param check * boolean to be checked * @return the passed boolean argument {@code check} * * @throws IllegalEqualException * if both argument values are not equal */ @Throws(IllegalEqualException.class) public static boolean notEquals(@Nonnull final boolean expected, @Nonnull final boolean check) { if (expected == check) { throw new IllegalEqualException(check); } return check; } /** * Ensures that a passed boolean is not equal to another boolean. The comparison is made using * <code>expected == check</code>. * * @param expected * Expected value * @param check * boolean to be checked * @param message * an error message describing why the booleans must equal (will be passed to * {@code IllegalEqualException}) * @return the passed boolean argument {@code check} * * @throws IllegalEqualException * if both argument values are not equal */ @Throws(IllegalEqualException.class) public static boolean notEquals(@Nonnull final boolean expected, @Nonnull final boolean check, final String message) { if (expected == check) { throw new IllegalEqualException(message, check); } return check; } /** * Ensures that a passed byte is not equal to another byte. The comparison is made using * <code>expected == check</code>. * * <p> * We recommend to use the overloaded method {@link Check#notEquals(byte, byte, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param expected * Expected value * @param check * byte to be checked * @return the passed byte argument {@code check} * * @throws IllegalEqualException * if both argument values are not equal */ @Throws(IllegalEqualException.class) public static byte notEquals(@Nonnull final byte expected, @Nonnull final byte check) { if (expected == check) { throw new IllegalEqualException(check); } return check; } /** * Ensures that a passed byte is not equal to another byte. The comparison is made using * <code>expected == check</code>. * * @param expected * Expected value * @param check * byte to be checked * @param message * an error message describing why the bytes must equal (will be passed to {@code IllegalEqualException}) * @return the byte boolean argument {@code check} * * @throws IllegalEqualException * if both argument values are not equal */ @Throws(IllegalEqualException.class) public static byte notEquals(@Nonnull final byte expected, @Nonnull final byte check, final String message) { if (expected == check) { throw new IllegalEqualException(message, check); } return check; } /** * Ensures that a passed char is not equal to another char. The comparison is made using * <code>expected == check</code>. * * <p> * We recommend to use the overloaded method {@link Check#notEquals(char, char, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param expected * Expected value * @param check * char to be checked * @return the passed char argument {@code check} * * @throws IllegalEqualException * if both argument values are not equal */ @Throws(IllegalEqualException.class) public static char notEquals(@Nonnull final char expected, @Nonnull final char check) { if (expected == check) { throw new IllegalEqualException(check); } return check; } /** * Ensures that a passed char is not equal to another char. The comparison is made using * <code>expected == check</code>. * * @param expected * Expected value * @param check * char to be checked * @param message * an error message describing why the chars must equal (will be passed to {@code IllegalEqualException}) * @return the passed char argument {@code check} * * @throws IllegalEqualException * if both argument values are not equal */ @Throws(IllegalEqualException.class) public static char notEquals(@Nonnull final char expected, @Nonnull final char check, final String message) { if (expected == check) { throw new IllegalEqualException(message, check); } return check; } /** * Ensures that a passed intH is not equal to another int. The comparison is made using * <code>expected == check</code>. * * <p> * We recommend to use the overloaded method {@link Check#notEquals(int, int, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param expected * Expected value * @param check * int to be checked * @return the passed int argument {@code check} * * @throws IllegalEqualException * if both argument values are not equal */ @Throws(IllegalEqualException.class) public static int notEquals(@Nonnull final int expected, @Nonnull final int check) { if (expected == check) { throw new IllegalEqualException(check); } return check; } /** * Ensures that a passed int is not equal to another int. The comparison is made using * <code>expected == check</code>. * * @param expected * Expected value * @param check * int to be checked * @param message * an error message describing why the ints must equal (will be passed to {@code IllegalEqualException}) * @return the passed int argument {@code check} * * @throws IllegalEqualException * if both argument values are not equal */ @Throws(IllegalEqualException.class) public static int notEquals(@Nonnull final int expected, @Nonnull final int check, final String message) { if (expected == check) { throw new IllegalEqualException(message, check); } return check; } /** * Ensures that a passed long is not equal to another long. The comparison is made using * <code>expected == check</code>. * * <p> * We recommend to use the overloaded method {@link Check#notEquals(long, long, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param expected * Expected value * @param check * long to be checked * @return the passed long argument {@code check} * * @throws IllegalEqualException * if both argument values are not equal */ @Throws(IllegalEqualException.class) public static long notEquals(@Nonnull final long expected, @Nonnull final long check) { if (expected == check) { throw new IllegalEqualException(check); } return check; } /** * Ensures that a passed long is not equal to another long. The comparison is made using * <code>expected == check</code>. * * @param expected * Expected value * @param check * long to be checked * @param message * an error message describing why the longs must equal (will be passed to {@code IllegalEqualException}) * @return the passed long argument {@code check} * * @throws IllegalEqualException * if both argument values are not equal */ @Throws(IllegalEqualException.class) public static long notEquals(@Nonnull final long expected, @Nonnull final long check, final String message) { if (expected == check) { throw new IllegalEqualException(message, check); } return check; } /** * Ensures that a passed short is not equal to another short. The comparison is made using * <code>expected == check</code>. * * <p> * We recommend to use the overloaded method {@link Check#notEquals(short, short, String)} and pass as second * argument the name of the parameter to enhance the exception message. * * @param expected * Expected value * @param check * short to be checked * @return the passed short argument {@code check} * * @throws IllegalEqualException * if both argument values are not equal */ @Throws(IllegalEqualException.class) public static short notEquals(@Nonnull final short expected, @Nonnull final short check) { if (expected == check) { throw new IllegalEqualException(check); } return check; } /** * Ensures that a passed short is not equal to another short. The comparison is made using * <code>expected == check</code>. * * @param expected * Expected value * @param check * short to be checked * @param message * an error message describing why the shorts must equal (will be passed to {@code IllegalEqualException} * ) * @return the passed short {@code check} * * @throws IllegalEqualException * if both argument values are not equal */ @Throws(IllegalEqualException.class) public static short notEquals(@Nonnull final short expected, @Nonnull final short check, final String message) { if (expected == check) { throw new IllegalEqualException(message, check); } return check; } /** * Ensures that a passed {@code Comparable} is not equal to another {@code Comparable}. The comparison is made using * {@code expected.compareTo(check) == 0}. * * <p> * We recommend to use the overloaded method {@link Check#notEquals(Comparable, Comparable, String)} and pass as * second argument the name of the parameter to enhance the exception message. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalEqualException * if both argument values are not equal */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEqualException.class }) public static <T extends Comparable<T>> T notEquals(@Nonnull final T expected, @Nonnull final T check) { Check.notNull(expected, "expected"); Check.notNull(check, "check"); if (expected.compareTo(check) == 0) { throw new IllegalEqualException(check); } return check; } /** * Ensures that a passed object is not equal to another object. The comparison is made using a call to * {@code expected.equals(check) }. * * <p> * We recommend to use the overloaded method {@link Check#notEquals(Object, Object, String)} and pass as second * argument the name of the parameter to enhance the exception message. * * @param expected * Expected value * @param check * Object to be checked * @return the passed argument {@code check} * * @throws IllegalEqualException * if both argument values are not equal */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEqualException.class }) public static <T extends Object> T notEquals(@Nonnull final T expected, @Nonnull final T check) { Check.notNull(expected, "expected"); Check.notNull(check, "check"); if (expected.equals(check)) { throw new IllegalEqualException(check); } return check; } /** * Ensures that a passed {@code Comparable} is not equal to another {@code Comparable}. The comparison is made using * {@code expected.compareTo(check) == 0}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the <a>s must equal (will be passed to {@code IllegalEqualException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalEqualException * if both argument values are not equal */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEqualException.class }) public static <T extends Comparable<T>> T notEquals(@Nonnull final T expected, @Nonnull final T check, final String message) { Check.notNull(expected, "expected"); Check.notNull(check, "check"); if (expected.compareTo(check) == 0) { throw new IllegalEqualException(message, check); } return check; } /** * Ensures that a passed object is not equal to another object. The comparison is made using a call to * {@code expected.equals(check)}. * * @param expected * Expected value * @param check * Object to be checked * @param message * an error message describing why the objects must equal (will be passed to * {@code IllegalEqualException}) * @return the passed argument {@code check} * * @throws IllegalEqualException * if both argument values are not equal */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEqualException.class }) public static <T extends Object> T notEquals(@Nonnull final T expected, @Nonnull final T check, final String message) { Check.notNull(expected, "expected"); Check.notNull(check, "check"); if (expected.equals(check)) { throw new IllegalEqualException(message, check); } return check; } /** * Do not perform any check and just return {@code t}. * * This is useful if you have several checks on some arguments, but do not check other arguments on purpose. This * checks helps to document that a check was omitted on purpose instead of forgotten. * * @param t * any object * @return t */ public static <T> T nothing(final T t) { return t; } /** * Ensures that a double argument is not NaN (not a number). * * <p> * We recommend to use the overloaded method {@link Check#notNaN(double, String)} and pass as second argument the * name of the parameter to enhance the exception message. * * @see java.lang.Double#NaN * * @param value * value which should not be NaN * @return the given double value * @throws IllegalNaNArgumentException * if the given argument {@code value} is NaN */ @Throws(IllegalNaNArgumentException.class) public static double notNaN(final double value) { return notNaN(value, EMPTY_ARGUMENT_NAME); } /** * Ensures that a double argument is not NaN (not a number). * * @see java.lang.Double#NaN * * @param value * value which should not be NaN * @param name * name of object reference (in source code) * @return the given double value * @throws IllegalNaNArgumentException * if the given argument {@code value} is NaN */ @Throws(IllegalNaNArgumentException.class) public static double notNaN(final double value, @Nullable final String name) { // most efficient check for NaN, see Double.isNaN(value)) if (value != value) { throw new IllegalNaNArgumentException(name); } return value; } /** * Ensures that a double argument is not NaN (not a number). * * <p> * We recommend to use the overloaded method {@link Check#notNaN(float, String)} and pass as second argument the * name of the parameter to enhance the exception message. * * @see java.lang.Float#NaN * * @param value * value which should not be NaN * @return the given double value * @throws IllegalNaNArgumentException * if the given argument {@code value} is NaN */ @Throws(IllegalNaNArgumentException.class) public static float notNaN(final float value) { return notNaN(value, EMPTY_ARGUMENT_NAME); } /** * Ensures that a double argument is not NaN (not a number). * * @see java.lang.Float#NaN * * @param value * value which should not be NaN * @param name * name of object reference (in source code) * @return the given float value * @throws IllegalNaNArgumentException * if the given argument {@code value} is NaN */ @Throws(IllegalNaNArgumentException.class) public static float notNaN(final float value, @Nullable final String name) { // most efficient check for NaN, see Float.isNaN(value)) if (value != value) { throw new IllegalNaNArgumentException(name); } return value; } /** * Ensures that an double reference passed as a parameter to the calling method is not smaller than {@code 0}. * * <p> * We recommend to use the overloaded method {@link Check#notNegative(double, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param value * a number * @return the non-null reference that was validated * @throws IllegalNegativeArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalNegativeArgumentException.class) public static double notNegative(@Nonnull final double value) { if (value < 0.0) { throw new IllegalNegativeArgumentException(value); } return value; } /** * Ensures that an double reference passed as a parameter to the calling method is not smaller than {@code 0}. * * @param value * a number * @param name * name of the number reference (in source code) * @return the non-null reference that was validated * @throws IllegalNullArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalNegativeArgumentException.class) public static double notNegative(@Nonnull final double value, @Nullable final String name) { if (value < 0.0) { throw new IllegalNegativeArgumentException(name, value); } return value; } /** * Ensures that an float reference passed as a parameter to the calling method is not smaller than {@code 0}. * * <p> * We recommend to use the overloaded method {@link Check#notNegative(float, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param value * a number * @return the non-null reference that was validated * @throws IllegalNegativeArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalNegativeArgumentException.class) public static float notNegative(@Nonnull final float value) { if (value < 0.0f) { throw new IllegalNegativeArgumentException(value); } return value; } /** * Ensures that an float reference passed as a parameter to the calling method is not smaller than {@code 0}. * * @param value * a number * @param name * name of the number reference (in source code) * @return the non-null reference that was validated * @throws IllegalNullArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalNegativeArgumentException.class) public static float notNegative(@Nonnull final float value, @Nullable final String name) { if (value < 0.0f) { throw new IllegalNegativeArgumentException(name, value); } return value; } /** * Ensures that an integer reference passed as a parameter to the calling method is not smaller than {@code 0}. * * <p> * We recommend to use the overloaded method {@link Check#notNegative(int, String)} and pass as second argument the * name of the parameter to enhance the exception message. * * @param value * a number * @return the non-null reference that was validated * @throws IllegalNegativeArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalNegativeArgumentException.class) public static int notNegative(@Nonnull final int value) { if (value < 0) { throw new IllegalNegativeArgumentException(value); } return value; } /** * Ensures that an integer reference passed as a parameter to the calling method is not smaller than {@code 0}. * * @param value * a number * @param name * name of the number reference (in source code) * @return the non-null reference that was validated * @throws IllegalNullArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalNegativeArgumentException.class) public static int notNegative(@Nonnull final int value, @Nullable final String name) { if (value < 0) { throw new IllegalNegativeArgumentException(name, value); } return value; } /** * Ensures that an long reference passed as a parameter to the calling method is not smaller than {@code 0}. * * <p> * We recommend to use the overloaded method {@link Check#notNegative(long, String)} and pass as second argument the * name of the parameter to enhance the exception message. * * @param value * a number * @return the non-null reference that was validated * @throws IllegalNegativeArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalNegativeArgumentException.class) public static long notNegative(@Nonnull final long value) { if (value < 0L) { throw new IllegalNegativeArgumentException(value); } return value; } /** * Ensures that an long reference passed as a parameter to the calling method is not smaller than {@code 0}. * * @param value * a number * @param name * name of the number reference (in source code) * @return the non-null reference that was validated * @throws IllegalNullArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalNegativeArgumentException.class) public static long notNegative(@Nonnull final long value, @Nullable final String name) { if (value < 0L) { throw new IllegalNegativeArgumentException(name, value); } return value; } /** * Ensures that an short reference passed as a parameter to the calling method is not smaller than {@code 0}. * * <p> * We recommend to use the overloaded method {@link Check#notNegative(short, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param value * a number * @return the non-null reference that was validated * @throws IllegalNegativeArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalNegativeArgumentException.class) public static short notNegative(@Nonnull final short value) { if (value < (short) 0) { throw new IllegalNegativeArgumentException(value); } return value; } /** * Ensures that an short reference passed as a parameter to the calling method is not smaller than {@code 0}. * * @param value * a number * @param name * name of the number reference (in source code) * @return the non-null reference that was validated * @throws IllegalNullArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalNegativeArgumentException.class) public static short notNegative(@Nonnull final short value, @Nullable final String name) { if (value < (short) 0) { throw new IllegalNegativeArgumentException(name, value); } return value; } /** * Ensures that an object reference passed as a parameter to the calling method is not {@code null}. * * <p> * We recommend to use the overloaded method {@link Check#notNull(Object, String)} and pass as second argument the * name of the parameter to enhance the exception message. * * @param reference * an object reference * @return the non-null reference that was validated * @throws IllegalNullArgumentException * if the given argument {@code reference} is {@code null} */ @Throws(IllegalNullArgumentException.class) public static <T> T notNull(@Nonnull final T reference) { if (reference == null) { throw new IllegalNullArgumentException(); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not {@code null}. * * @param reference * an object reference * @param name * name of object reference (in source code) * @return the non-null reference that was validated * @throws IllegalNullArgumentException * if the given argument {@code reference} is {@code null} */ @Throws(IllegalNullArgumentException.class) public static <T> T notNull(@Nonnull final T reference, @Nullable final String name) { if (reference == null) { throw new IllegalNullArgumentException(name); } return reference; } /** * Ensures that an double reference passed as a parameter to the calling method is not greater than {@code 0}. * * <p> * We recommend to use the overloaded method {@link Check#notPositive(double, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param value * a number * @return the non-null reference that was validated * @throws IllegalPositiveArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalPositiveArgumentException.class) public static double notPositive(@Nonnull final double value) { if (value > 0.0) { throw new IllegalPositiveArgumentException(value); } return value; } /** * Ensures that an double reference passed as a parameter to the calling method is not greater than {@code 0}. * * @param value * a number * @param name * name of the number reference (in source code) * @return the non-null reference that was validated * @throws IllegalNullArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalPositiveArgumentException.class) public static double notPositive(@Nonnull final double value, @Nullable final String name) { if (value > 0.0) { throw new IllegalPositiveArgumentException(name, value); } return value; } /** * Ensures that an float reference passed as a parameter to the calling method is not greater than {@code 0}. * * <p> * We recommend to use the overloaded method {@link Check#notPositive(float, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param value * a number * @return the non-null reference that was validated * @throws IllegalPositiveArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalPositiveArgumentException.class) public static float notPositive(@Nonnull final float value) { if (value > 0.0f) { throw new IllegalPositiveArgumentException(value); } return value; } /** * Ensures that an float reference passed as a parameter to the calling method is not greater than {@code 0}. * * @param value * a number * @param name * name of the number reference (in source code) * @return the non-null reference that was validated * @throws IllegalNullArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalPositiveArgumentException.class) public static float notPositive(@Nonnull final float value, @Nullable final String name) { if (value > 0.0f) { throw new IllegalPositiveArgumentException(name, value); } return value; } /** * Ensures that an integer reference passed as a parameter to the calling method is not greater than {@code 0}. * * <p> * We recommend to use the overloaded method {@link Check#notPositive(int, String)} and pass as second argument the * name of the parameter to enhance the exception message. * * @param value * a number * @return the non-null reference that was validated * @throws IllegalPositiveArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalPositiveArgumentException.class) public static int notPositive(@Nonnull final int value) { if (value > 0) { throw new IllegalPositiveArgumentException(value); } return value; } /** * Ensures that an integer reference passed as a parameter to the calling method is not greater than {@code 0}. * * @param value * a number * @param name * name of the number reference (in source code) * @return the non-null reference that was validated * @throws IllegalNullArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalPositiveArgumentException.class) public static int notPositive(@Nonnull final int value, @Nullable final String name) { if (value > 0) { throw new IllegalPositiveArgumentException(name, value); } return value; } /** * Ensures that an long reference passed as a parameter to the calling method is not greater than {@code 0}. * * <p> * We recommend to use the overloaded method {@link Check#notPositive(long, String)} and pass as second argument the * name of the parameter to enhance the exception message. * * @param value * a number * @return the non-null reference that was validated * @throws IllegalPositiveArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalPositiveArgumentException.class) public static long notPositive(@Nonnull final long value) { if (value > 0L) { throw new IllegalPositiveArgumentException(value); } return value; } /** * Ensures that an long reference passed as a parameter to the calling method is not greater than {@code 0}. * * @param value * a number * @param name * name of the number reference (in source code) * @return the non-null reference that was validated * @throws IllegalNullArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalPositiveArgumentException.class) public static long notPositive(@Nonnull final long value, @Nullable final String name) { if (value > 0L) { throw new IllegalPositiveArgumentException(name, value); } return value; } /** * Ensures that an short reference passed as a parameter to the calling method is not greater than {@code 0}. * * <p> * We recommend to use the overloaded method {@link Check#notPositive(short, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param value * a number * @return the non-null reference that was validated * @throws IllegalPositiveArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalPositiveArgumentException.class) public static short notPositive(@Nonnull final short value) { if (value > (short) 0) { throw new IllegalPositiveArgumentException(value); } return value; } /** * Ensures that an short reference passed as a parameter to the calling method is not greater than {@code 0}. * * @param value * a number * @param name * name of the number reference (in source code) * @return the non-null reference that was validated * @throws IllegalNullArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalPositiveArgumentException.class) public static short notPositive(@Nonnull final short value, @Nullable final String name) { if (value > (short) 0) { throw new IllegalPositiveArgumentException(name, value); } return value; } /** * Ensures that a given position index is valid within the size of an array, list or string ... * * @param index * index of an array, list or string * @param size * size of an array list or string * @return the index * * @throws IllegalPositionIndexException * if the index is not a valid position index within an array, list or string of size <em>size</em> * */ @Throws(IllegalPositionIndexException.class) public static int positionIndex(final int index, final int size) { final boolean isIndexValid = (size >= 0) && (index >= 0) && (index < size); if (!isIndexValid) { throw new IllegalPositionIndexException(index, size); } return index; } /** * Ensures that the given arguments are a valid range. * * A range (<em>start</em>, <em>end</em>, <em>size</em>) is valid if the following conditions are {@code true}: * <ul> * <li>start <= size</li> * <li>end <= size</li> * <li>start <= end</li> * <li>size >= 0</li> * <li>start >= 0</li> * <li>end >= 0</li> * </ul> * * @param start * the start value of the range (must be a positive integer or 0) * @param end * the end value of the range (must be a positive integer or 0) * @param size * the size value of the range (must be a positive integer or 0) * * @throws IllegalRangeException * if the given arguments do not form a valid range */ @Throws(IllegalRangeException.class) public static void range(@Nonnegative final int start, @Nonnegative final int end, @Nonnegative final int size) { final boolean rangeIsValid = (start <= size) && (end <= size) && (start <= end); final boolean inputValuesAreValid = (size >= 0) && (start >= 0) && (end >= 0); if (!rangeIsValid || !inputValuesAreValid) { throw new IllegalRangeException(start, end, size); } } /** * Ensures that a given state is {@code true}. * * <p> * We recommend to use the overloaded method {@link Check#stateIsTrue(boolean, String)} and pass as second argument * the name of the parameter to enhance the exception message. A better way is to create specific exceptions (with a * good wording) for your case and to use the overloaded method {@link Check#stateIsTrue(boolean, Class)} and pass * as second argument your exception. * * @param expression * an expression that must be true to indicate a valid state * * @throws IllegalStateOfArgumentException * if the given arguments caused an invalid state */ @Throws(IllegalStateOfArgumentException.class) public static void stateIsTrue(final boolean expression) { if (!expression) { throw new IllegalStateOfArgumentException(); } } /** * Ensures that a given state is {@code true} and allows to specify the class of exception which is thrown in case * the state is not {@code true}. * * @param expression * an expression that must be {@code true} to indicate a valid state * @param clazz * an subclass of {@link RuntimeException} which will be thrown if the given state is not valid * @throws clazz * a new instance of {@code clazz} if the given arguments caused an invalid state * @throws RuntimeInstantiationException * <strong>Attention</strong>: Be aware, that a {@code RuntimeInstantiationException} can be thrown when * the given {@code clazz} cannot be instantiated */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, RuntimeInstantiationException.class }) public static void stateIsTrue(final boolean expression, final Class<? extends RuntimeException> clazz) { Check.notNull(clazz, "clazz"); if (!expression) { RuntimeException re; try { re = clazz.newInstance(); } catch (final InstantiationException e) { throw new RuntimeInstantiationException(clazz.getSimpleName(), e); } catch (final IllegalAccessException e) { throw new RuntimeInstantiationException(clazz.getSimpleName(), e); } throw re; } } /** * Ensures that a given state is {@code true}. * * @param expression * an expression that must be {@code true} to indicate a valid state * @param description * will be used in the error message to describe why the arguments caused an invalid state * @throws IllegalStateOfArgumentException * if the given arguments caused an invalid state */ @Throws(IllegalStateOfArgumentException.class) public static void stateIsTrue(final boolean expression, @Nonnull final String description) { if (!expression) { throw new IllegalStateOfArgumentException(description); } } /** * Ensures that a given state is {@code true} * * @param expression * an expression that must be {@code true} to indicate a valid state * @param descriptionTemplate * format string template that explains why the state is invalid * @param descriptionTemplateArgs * format string template arguments to explain why the state is invalid * @throws IllegalStateOfArgumentException * if the given arguments caused an invalid state */ @Throws(IllegalStateOfArgumentException.class) public static void stateIsTrue(final boolean expression, @Nonnull final String descriptionTemplate, final Object... descriptionTemplateArgs) { if (!expression) { throw new IllegalStateOfArgumentException(descriptionTemplate, descriptionTemplateArgs); } } /** * <strong>Attention:</strong> This class is not intended to create objects from it. */ private Check() { // This class is not intended to create objects from it. } }
modules/quality-check/src/main/java/net/sf/qualitycheck/Check.java
/******************************************************************************* * Copyright 2013 André Rouél and Dominik Seichter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package net.sf.qualitycheck; import java.lang.annotation.Annotation; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collection; import java.util.Map; import java.util.regex.Pattern; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; import net.sf.qualitycheck.exception.IllegalArgumentNotContainedException; import net.sf.qualitycheck.exception.IllegalEmptyArgumentException; import net.sf.qualitycheck.exception.IllegalEqualException; import net.sf.qualitycheck.exception.IllegalInstanceOfArgumentException; import net.sf.qualitycheck.exception.IllegalMissingAnnotationException; import net.sf.qualitycheck.exception.IllegalNaNArgumentException; import net.sf.qualitycheck.exception.IllegalNegativeArgumentException; import net.sf.qualitycheck.exception.IllegalNotEqualException; import net.sf.qualitycheck.exception.IllegalNotGreaterOrEqualThanException; import net.sf.qualitycheck.exception.IllegalNotGreaterThanException; import net.sf.qualitycheck.exception.IllegalNotLesserThanException; import net.sf.qualitycheck.exception.IllegalNotNullArgumentException; import net.sf.qualitycheck.exception.IllegalNullArgumentException; import net.sf.qualitycheck.exception.IllegalNullElementsException; import net.sf.qualitycheck.exception.IllegalNumberArgumentException; import net.sf.qualitycheck.exception.IllegalNumericArgumentException; import net.sf.qualitycheck.exception.IllegalPatternArgumentException; import net.sf.qualitycheck.exception.IllegalPositionIndexException; import net.sf.qualitycheck.exception.IllegalPositiveArgumentException; import net.sf.qualitycheck.exception.IllegalRangeException; import net.sf.qualitycheck.exception.IllegalStateOfArgumentException; import net.sf.qualitycheck.exception.RuntimeInstantiationException; /** * This class offers simple static methods to test your arguments to be valid. * * Checks should be added to all arguments of all public methods in your class to assure that only valid values can be * encountered within your class. This is major step to avoid technical errors like NullPointerExceptions or * IndexOutOfBoundsException in your code. * * @author André Rouél * @author Dominik Seichter */ public final class Check { /** * Holder for the regular expression to determine numeric values. Using the holder pattern guarantees that the * regular expression is initialized before the first use (thread safe!) and that it is only initialized if it is * needed. So, we do not pay any performance bounty for regular expressions when using other checks. */ protected static final class NumericRegularExpressionHolder { private static final Pattern NUMERIC_REGEX = Pattern.compile("[0-9]+"); @Nonnull public static Pattern getPattern() { return NUMERIC_REGEX; } } /** * Representation of an empty argument name. */ private static final String EMPTY_ARGUMENT_NAME = ""; /** * Checks the passed {@code value} against the ranges of the given datatype. * * @param value * value which must be a number and in the range of the given datatype. * @param type * requested return value type, must be a subclass of {@code Number} * @return a number * * @throws NumberFormatException * if the given value can not be parsed as a number */ private static <T> Number checkNumberInRange(final String value, final Class<T> type) { final Number ret; if (type.equals(Byte.class)) { final Number number = new BigInteger(value); NumberInRange.checkByte(number); ret = Byte.valueOf(number.byteValue()); } else if (type.equals(Double.class)) { final Number number = new BigDecimal(value); NumberInRange.checkDouble(number); ret = Double.valueOf(number.doubleValue()); } else if (type.equals(Float.class)) { final Number number = new BigDecimal(value); NumberInRange.checkFloat(number); ret = Float.valueOf(number.floatValue()); } else if (type.equals(Integer.class)) { final Number number = new BigInteger(value); NumberInRange.checkInteger(number); ret = Integer.valueOf(number.intValue()); } else if (type.equals(Long.class)) { final Number number = new BigInteger(value); NumberInRange.checkLong(number); ret = Long.valueOf(number.longValue()); } else if (type.equals(Short.class)) { final Number number = new BigInteger(value); NumberInRange.checkShort(number); ret = Short.valueOf(number.shortValue()); } else if (type.equals(BigInteger.class)) { ret = new BigInteger(value); } else if (type.equals(BigDecimal.class)) { ret = new BigDecimal(value); } else { throw new IllegalNumberArgumentException("Return value is no known subclass of 'java.lang.Number': " + type.getName()); } return ret; } /** * Ensures that an element {@code needle} is contained in a collection {@code haystack}. * * <p> * This is in particular useful if you want to check whether an enum value is contained in an {@code EnumSet}. The * check is implemented using {@link java.util.Collection#contains(Object)}. * * <p> * We recommend to use the overloaded method {@link Check#contains(Collection, Object, String)} and pass as second * argument the name of the parameter to enhance the exception message. * * @param haystack * A collection which must contain {@code needle} * @param needle * An object that must be contained into a collection. * @return the passed argument {@code needle} * * @throws IllegalArgumentNotContainedException * if the passed {@code needle} can not be found in {@code haystack} */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalArgumentNotContainedException.class }) public static <T extends Object> T contains(@Nonnull final Collection<T> haystack, @Nonnull final T needle) { Check.notNull(haystack, "haystack"); Check.notNull(needle, "needle"); if (!haystack.contains(needle)) { throw new IllegalArgumentNotContainedException(needle); } return needle; } /** * Ensures that an element {@code needle} is contained in a collection {@code haystack}. * * <p> * This is in particular useful if you want to check whether an enum value is contained in an {@code EnumSet}. The * check is implemented using {@link java.util.Collection#contains(Object)}. * * @param haystack * A collection which must contain {@code needle} * @param needle * An object that must be contained into a collection. * @param name * name of argument of {@code needle} * @return the passed argument {@code needle} * * @throws IllegalArgumentNotContainedException * if the passed {@code needle} can not be found in {@code haystack} */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalArgumentNotContainedException.class }) public static <T extends Object> T contains(@Nonnull final Collection<T> haystack, @Nonnull final T needle, @Nonnull final String name) { Check.notNull(haystack, "haystack"); Check.notNull(needle, "needle"); if (!haystack.contains(needle)) { throw new IllegalArgumentNotContainedException(name, needle); } return needle; } /** * Checks if the given array contains {@code null}. * * @param array * reference to an array * @return {@code true} if the array contains {@code null}, otherwise {@code false} */ private static boolean containsNullElements(@Nonnull final Object[] array) { boolean containsNull = false; for (final Object o : array) { if (o == null) { containsNull = true; break; } } return containsNull; } /** * Ensures that a passed boolean is equal to another boolean. The comparison is made using * <code>expected != check</code>. * * <p> * We recommend to use the overloaded method {@link Check#equals(boolean, boolean, String)} and pass as second * argument the name of the parameter to enhance the exception message. * * @param expected * Expected value * @param check * boolean to be checked * @return the passed boolean argument {@code check} * * @throws IllegalNotEqualException * if both argument values are not equal */ @Throws(IllegalNotEqualException.class) public static boolean equals(@Nonnull final boolean expected, @Nonnull final boolean check) { // NOSONAR // Sonar warns about suspicious equals method name, as the name is intended deactivate sonar if (expected != check) { throw new IllegalNotEqualException(check); } return check; } /** * Ensures that a passed boolean is equal to another boolean. The comparison is made using * <code>expected != check</code>. * * @param expected * Expected value * @param check * boolean to be checked * @param message * an error message describing why the booleans must equal (will be passed to * {@code IllegalNotEqualException}) * @return the passed boolean argument {@code check} * * @throws IllegalNotEqualException * if both argument values are not equal */ @Throws(IllegalNotEqualException.class) public static boolean equals(@Nonnull final boolean expected, @Nonnull final boolean check, final String message) { // NOSONAR // Sonar warns about suspicious equals method name, as the name is intended deactivate sonar if (expected != check) { throw new IllegalNotEqualException(message, check); } return check; } /** * Ensures that a passed byte is equal to another byte. The comparison is made using <code>expected != check</code>. * * <p> * We recommend to use the overloaded method {@link Check#equals(byte, byte, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param expected * Expected value * @param check * byte to be checked * @return the passed byte argument {@code check} * * @throws IllegalNotEqualException * if both argument values are not equal */ @Throws(IllegalNotEqualException.class) public static byte equals(@Nonnull final byte expected, @Nonnull final byte check) { // NOSONAR // Sonar warns about suspicious equals method name, as the name is intended deactivate sonar if (expected != check) { throw new IllegalNotEqualException(check); } return check; } /** * Ensures that a passed byte is equal to another byte. The comparison is made using <code>expected != check</code>. * * @param expected * Expected value * @param check * byte to be checked * @param message * an error message describing why the bytes must equal (will be passed to * {@code IllegalNotEqualException}) * @return the byte boolean argument {@code check} * * @throws IllegalNotEqualException * if both argument values are not equal */ @Throws(IllegalNotEqualException.class) public static byte equals(@Nonnull final byte expected, @Nonnull final byte check, final String message) { // NOSONAR // Sonar warns about suspicious equals method name, as the name is intended deactivate sonar if (expected != check) { throw new IllegalNotEqualException(message, check); } return check; } /** * Ensures that a passed char is equal to another char. The comparison is made using <code>expected != check</code>. * * <p> * We recommend to use the overloaded method {@link Check#equals(char, char, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param expected * Expected value * @param check * char to be checked * @return the passed char argument {@code check} * * @throws IllegalNotEqualException * if both argument values are not equal */ @Throws(IllegalNotEqualException.class) public static char equals(@Nonnull final char expected, @Nonnull final char check) { // NOSONAR // Sonar warns about suspicious equals method name, as the name is intended deactivate sonar if (expected != check) { throw new IllegalNotEqualException(check); } return check; } /** * Ensures that a passed char is equal to another char. The comparison is made using <code>expected != check</code>. * * @param expected * Expected value * @param check * char to be checked * @param message * an error message describing why the chars must equal (will be passed to * {@code IllegalNotEqualException}) * @return the passed char argument {@code check} * * @throws IllegalNotEqualException * if both argument values are not equal */ @Throws(IllegalNotEqualException.class) public static char equals(@Nonnull final char expected, @Nonnull final char check, final String message) { // NOSONAR // Sonar warns about suspicious equals method name, as the name is intended deactivate sonar if (expected != check) { throw new IllegalNotEqualException(message, check); } return check; } /** * Ensures that a passed intH is equal to another int. The comparison is made using <code>expected != check</code>. * * <p> * We recommend to use the overloaded method {@link Check#equals(int, int, String)} and pass as second argument the * name of the parameter to enhance the exception message. * * @param expected * Expected value * @param check * int to be checked * @return the passed int argument {@code check} * * @throws IllegalNotEqualException * if both argument values are not equal */ @Throws(IllegalNotEqualException.class) public static int equals(@Nonnull final int expected, @Nonnull final int check) { // NOSONAR // Sonar warns about suspicious equals method name, as the name is intended deactivate sonar if (expected != check) { throw new IllegalNotEqualException(check); } return check; } /** * Ensures that a passed int is equal to another int. The comparison is made using <code>expected != check</code>. * * @param expected * Expected value * @param check * int to be checked * @param message * an error message describing why the ints must equal (will be passed to * {@code IllegalNotEqualException}) * @return the passed int argument {@code check} * * @throws IllegalNotEqualException * if both argument values are not equal */ @Throws(IllegalNotEqualException.class) public static int equals(@Nonnull final int expected, @Nonnull final int check, final String message) { // NOSONAR // Sonar warns about suspicious equals method name, as the name is intended deactivate sonar if (expected != check) { throw new IllegalNotEqualException(message, check); } return check; } /** * Ensures that a passed long is equal to another long. The comparison is made using <code>expected != check</code>. * * <p> * We recommend to use the overloaded method {@link Check#equals(long, long, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param expected * Expected value * @param check * long to be checked * @return the passed long argument {@code check} * * @throws IllegalNotEqualException * if both argument values are not equal */ @Throws(IllegalNotEqualException.class) public static long equals(@Nonnull final long expected, @Nonnull final long check) { // NOSONAR // Sonar warns about suspicious equals method name, as the name is intended deactivate sonar if (expected != check) { throw new IllegalNotEqualException(check); } return check; } /** * Ensures that a passed long is equal to another long. The comparison is made using <code>expected != check</code>. * * @param expected * Expected value * @param check * long to be checked * @param message * an error message describing why the longs must equal (will be passed to * {@code IllegalNotEqualException}) * @return the passed long argument {@code check} * * @throws IllegalNotEqualException * if both argument values are not equal */ @Throws(IllegalNotEqualException.class) public static long equals(@Nonnull final long expected, @Nonnull final long check, final String message) { // NOSONAR // Sonar warns about suspicious equals method name, as the name is intended deactivate sonar if (expected != check) { throw new IllegalNotEqualException(message, check); } return check; } /** * Ensures that a passed short is equal to another short. The comparison is made using * <code>expected != check</code>. * * <p> * We recommend to use the overloaded method {@link Check#equals(short, short, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param expected * Expected value * @param check * short to be checked * @return the passed short argument {@code check} * * @throws IllegalNotEqualException * if both argument values are not equal */ @Throws(IllegalNotEqualException.class) public static short equals(@Nonnull final short expected, @Nonnull final short check) { // NOSONAR // Sonar warns about suspicious equals method name, as the name is intended deactivate sonar if (expected != check) { throw new IllegalNotEqualException(check); } return check; } /** * Ensures that a passed short is equal to another short. The comparison is made using * <code>expected != check</code>. * * @param expected * Expected value * @param check * short to be checked * @param message * an error message describing why the shorts must equal (will be passed to * {@code IllegalNotEqualException}) * @return the passed short {@code check} * * @throws IllegalNotEqualException * if both argument values are not equal */ @Throws(IllegalNotEqualException.class) public static short equals(@Nonnull final short expected, @Nonnull final short check, final String message) { // NOSONAR // Sonar warns about suspicious equals method name, as the name is intended deactivate sonar if (expected != check) { throw new IllegalNotEqualException(message, check); } return check; } /** * Ensures that a passed {@code Comparable} is equal to another {@code Comparable}. The comparison is made using * {@code expected.compareTo(check) != 0}. * * <p> * We recommend to use the overloaded method {@link Check#equals(Comparable, Comparable, String)} and pass as second * argument the name of the parameter to enhance the exception message. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotEqualException * if both argument values are not equal */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNotEqualException.class }) public static <T extends Comparable<T>> T equals(@Nonnull final T expected, @Nonnull final T check) { // NOSONAR // Sonar warns about suspicious equals method name, as the name is intended deactivate sonar Check.notNull(expected, "expected"); Check.notNull(check, "check"); if (expected.compareTo(check) != 0) { throw new IllegalNotEqualException(check); } return check; } /** * Ensures that a passed object is equal to another object. The comparison is made using a call to * {@code expected.equals(check) }. * * <p> * We recommend to use the overloaded method {@link Check#equals(Object, Object, String)} and pass as second * argument the name of the parameter to enhance the exception message. * * @param expected * Expected value * @param check * Object to be checked * @return the passed argument {@code check} * * @throws IllegalNotEqualException * if both argument values are not equal */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNotEqualException.class }) public static <T extends Object> T equals(@Nonnull final T expected, @Nonnull final T check) { // NOSONAR // Sonar warns about suspicious equals method name, as the name is intended deactivate sonar Check.notNull(expected, "expected"); Check.notNull(check, "check"); if (!expected.equals(check)) { throw new IllegalNotEqualException(check); } return check; } /** * Ensures that a passed {@code Comparable} is equal to another {@code Comparable}. The comparison is made using * {@code expected.compareTo(check) != 0}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the <a>s must equal (will be passed to * {@code IllegalNotEqualException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotEqualException * if both argument values are not equal */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNotEqualException.class }) public static <T extends Comparable<T>> T equals(@Nonnull final T expected, @Nonnull final T check, final String message) { // NOSONAR // Sonar warns about suspicious equals method name, as the name is intended deactivate sonar Check.notNull(expected, "expected"); Check.notNull(check, "check"); if (expected.compareTo(check) != 0) { throw new IllegalNotEqualException(message, check); } return check; } /** * Ensures that a passed object is equal to another object. The comparison is made using a call to * {@code expected.equals(check) }. * * @param expected * Expected value * @param check * Object to be checked * @param message * an error message describing why the objects must equal (will be passed to * {@code IllegalNotEqualException}) * @return the passed argument {@code check} * * @throws IllegalNotEqualException * if both argument values are not equal */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNotEqualException.class }) public static <T extends Object> T equals(@Nonnull final T expected, @Nonnull final T check, final String message) { // NOSONAR // Sonar warns about suspicious equals method name, as the name is intended deactivate sonar Check.notNull(expected, "expected"); Check.notNull(check, "check"); if (!expected.equals(check)) { throw new IllegalNotEqualException(message, check); } return check; } /** * Ensures that a passed {@code Comparable} is greater or equal compared to another {@code Comparable}. The * comparison is made using {@code expected.compareTo(check) > 0}. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterOrEqualThanException * if the argument value {@code check} is not greater or equal than the value {@code expected} when * using method {@code compareTo} */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNotGreaterOrEqualThanException.class }) public static <T extends Comparable<T>> T greaterOrEqualThan(@Nonnull final T expected, @Nonnull final T check) { Check.notNull(expected, "expected"); Check.notNull(check, "check"); if (expected.compareTo(check) > 0) { throw new IllegalNotGreaterOrEqualThanException(check); } return check; } /** * Ensures that a passed {@code Comparable} is greater or equal compared to another {@code Comparable}. The * comparison is made using {@code expected.compareTo(check) > 0}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the comparable must be greater than a value (will be passed to * {@code IllegalNotGreaterOrEqualThanException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterOrEqualThanException * if the argument value {@code check} is not greater or equal than the value {@code expected} when * using method {@code compareTo} */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNotGreaterOrEqualThanException.class }) public static <T extends Comparable<T>> T greaterOrEqualThan(@Nonnull final T expected, @Nonnull final T check, final String message) { Check.notNull(expected, "expected"); Check.notNull(check, "check"); if (expected.compareTo(check) > 0) { throw new IllegalNotGreaterOrEqualThanException(message, check); } return check; } /** * Ensures that a passed {@code byte} is greater to another {@code byte}. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterThanException * if the argument value {@code check} is not greater than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotGreaterThanException.class) public static byte greaterThan(@Nonnull final byte expected, @Nonnull final byte check) { if (expected >= check) { throw new IllegalNotGreaterThanException(check); } return check; } /** * Ensures that a passed {@code byte} is greater than another {@code byte}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the comparable must be greater than a value (will be passed to * {@code IllegalNotGreaterThanException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterThanException * if the argument value {@code check} is not greater than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotGreaterThanException.class) public static byte greaterThan(@Nonnull final byte expected, @Nonnull final byte check, final String message) { if (expected >= check) { throw new IllegalNotGreaterThanException(message, check); } return check; } /** * Ensures that a passed {@code char} is greater to another {@code char}. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterThanException * if the argument value {@code check} is not greater than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotGreaterThanException.class) public static char greaterThan(@Nonnull final char expected, @Nonnull final char check) { if (expected >= check) { throw new IllegalNotGreaterThanException(check); } return check; } /** * Ensures that a passed {@code char} is greater than another {@code char}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the comparable must be greater than a value (will be passed to * {@code IllegalNotGreaterThanException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterThanException * if the argument value {@code check} is not greater than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotGreaterThanException.class) public static char greaterThan(@Nonnull final char expected, @Nonnull final char check, final String message) { if (expected >= check) { throw new IllegalNotGreaterThanException(message, check); } return check; } /** * Ensures that a passed {@code double} is greater to another {@code double}. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterThanException * if the argument value {@code check} is not greater than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotGreaterThanException.class) public static double greaterThan(@Nonnull final double expected, @Nonnull final double check) { if (expected >= check) { throw new IllegalNotGreaterThanException(check); } return check; } /** * Ensures that a passed {@code double} is greater than another {@code double}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the comparable must be greater than a value (will be passed to * {@code IllegalNotGreaterThanException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterThanException * if the argument value {@code check} is not greater than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotGreaterThanException.class) public static double greaterThan(@Nonnull final double expected, @Nonnull final double check, final String message) { if (expected >= check) { throw new IllegalNotGreaterThanException(message, check); } return check; } /** * Ensures that a passed {@code float} is greater to another {@code float}. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterThanException * if the argument value {@code check} is not greater than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotGreaterThanException.class) public static float greaterThan(@Nonnull final float expected, @Nonnull final float check) { if (expected >= check) { throw new IllegalNotGreaterThanException(check); } return check; } /** * Ensures that a passed {@code float} is greater than another {@code float}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the comparable must be greater than a value (will be passed to * {@code IllegalNotGreaterThanException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterThanException * if the argument value {@code check} is not greater than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotGreaterThanException.class) public static float greaterThan(@Nonnull final float expected, @Nonnull final float check, final String message) { if (expected >= check) { throw new IllegalNotGreaterThanException(message, check); } return check; } /** * Ensures that a passed {@code int} is greater to another {@code int}. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterThanException * if the argument value {@code check} is not greater than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotGreaterThanException.class) public static int greaterThan(@Nonnull final int expected, @Nonnull final int check) { if (expected >= check) { throw new IllegalNotGreaterThanException(check); } return check; } /** * Ensures that a passed {@code int} is greater than another {@code int}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the comparable must be greater than a value (will be passed to * {@code IllegalNotGreaterThanException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterThanException * if the argument value {@code check} is not greater than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotGreaterThanException.class) public static int greaterThan(@Nonnull final int expected, @Nonnull final int check, final String message) { if (expected >= check) { throw new IllegalNotGreaterThanException(message, check); } return check; } /** * Ensures that a passed {@code long} is greater to another {@code long}. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterThanException * if the argument value {@code check} is not greater than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotGreaterThanException.class) public static long greaterThan(@Nonnull final long expected, @Nonnull final long check) { if (expected >= check) { throw new IllegalNotGreaterThanException(check); } return check; } /** * Ensures that a passed {@code long} is greater than another {@code long}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the comparable must be greater than a value (will be passed to * {@code IllegalNotGreaterThanException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterThanException * if the argument value {@code check} is not greater than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotGreaterThanException.class) public static long greaterThan(@Nonnull final long expected, @Nonnull final long check, final String message) { if (expected >= check) { throw new IllegalNotGreaterThanException(message, check); } return check; } /** * Ensures that a passed {@code short} is greater to another {@code short}. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterThanException * if the argument value {@code check} is not greater than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotGreaterThanException.class) public static short greaterThan(@Nonnull final short expected, @Nonnull final short check) { if (expected >= check) { throw new IllegalNotGreaterThanException(check); } return check; } /** * Ensures that a passed {@code short} is greater than another {@code short}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the comparable must be greater than a value (will be passed to * {@code IllegalNotGreaterThanException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterThanException * if the argument value {@code check} is not greater than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotGreaterThanException.class) public static short greaterThan(@Nonnull final short expected, @Nonnull final short check, final String message) { if (expected >= check) { throw new IllegalNotGreaterThanException(message, check); } return check; } /** * Ensures that a passed {@code Comparable} is greater to another {@code Comparable}. The comparison is made using * {@code expected.compareTo(check) >= 0}. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterThanException * if the argument value {@code check} is not greater than value {@code expected} when using method * {@code compareTo} */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNotGreaterThanException.class }) public static <T extends Comparable<T>> T greaterThan(@Nonnull final T expected, @Nonnull final T check) { Check.notNull(expected, "expected"); Check.notNull(check, "check"); if (expected.compareTo(check) >= 0) { throw new IllegalNotGreaterThanException(check); } return check; } /** * Ensures that a passed {@code Comparable} is greater than another {@code Comparable}. The comparison is made using * {@code expected.compareTo(check) >= 0}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the comparable must be greater than a value (will be passed to * {@code IllegalNotGreaterThanException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotGreaterThanException * if the argument value {@code check} is not greater than value {@code expected} when using method * {@code compareTo} */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNotGreaterThanException.class }) public static <T extends Comparable<T>> T greaterThan(@Nonnull final T expected, @Nonnull final T check, final String message) { Check.notNull(expected, "expected"); Check.notNull(check, "check"); if (expected.compareTo(check) >= 0) { throw new IllegalNotGreaterThanException(message, check); } return check; } /** * Ensures that a passed class has an annotation of a specific type * * @param clazz * the class that must have a required annotation * @param annotation * the type of annotation that is required on the class * @return the given annotation which is present on the checked class * * @throws IllegalMissingAnnotationException * if the passed annotation is not annotated at the given class */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalMissingAnnotationException.class }) public static Annotation hasAnnotation(@Nonnull final Class<?> clazz, @Nonnull final Class<? extends Annotation> annotation) { Check.notNull(clazz, "clazz"); Check.notNull(annotation, "annotation"); if (!clazz.isAnnotationPresent(annotation)) { throw new IllegalMissingAnnotationException(annotation, clazz); } return clazz.getAnnotation(annotation); } /** * Ensures that a passed argument is a member of a specific type. * * @param type * class that the given object is a member of * @param obj * the object reference that should be a member of a specific {@code type} * @return the given object cast to type * * @throws IllegalInstanceOfArgumentException * if the given argument {@code obj} is not a member of {@code type} */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalInstanceOfArgumentException.class }) @SuppressWarnings("unchecked") public static <T> T instanceOf(@Nonnull final Class<?> type, @Nonnull final Object obj) { return (T) instanceOf(type, obj, EMPTY_ARGUMENT_NAME); } /** * Ensures that a passed argument is a member of a specific type. * * @param type * class that the given object is a member of * @param obj * the object reference that should be a member of a specific {@code type} * @param name * name of object reference (in source code) * @return the given object cast to type * * @throws IllegalInstanceOfArgumentException * if the given argument {@code obj} is not a member of {@code type} */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalInstanceOfArgumentException.class }) @SuppressWarnings("unchecked") public static <T> T instanceOf(@Nonnull final Class<?> type, @Nonnull final Object obj, @Nullable final String name) { Check.notNull(type, "type"); Check.notNull(obj, "obj"); if (!type.isInstance(obj)) { throw new IllegalInstanceOfArgumentException(name, type, obj.getClass()); } return (T) obj; } /** * Ensures that a given argument is {@code null}. * * Normally, the usage of {@code null} arguments is disregarded by the authors of quality-check. Still, there are * certain circumstances where null is required, e.g. the primary key of an entity before it is written to the * database for the first time. In such cases it is ok to use null values and there should also be checks for them. * For example, to avoid overwriting an existing primary key with a new one. * * @param reference * reference which must be null * * @throws IllegalNotNullArgumentException * if the given argument {@code reference} is not null */ @Throws(IllegalNotNullArgumentException.class) public static void isNull(@Nullable final Object reference) { if (reference != null) { throw new IllegalNotNullArgumentException(reference); } } /** * Ensures that a given argument is {@code null}. * * Normally, the usage of {@code null} arguments is disregarded by the authors of quality-check. Still, there are * certain circumstances where null is required, e.g. the primary key of an entity before it is written to the * database for the first time. In such cases it is ok to use null values and there should also be checks for them. * For example, to avoid overwriting an existing primary key with a new one. * * @param reference * reference which must be null. * @param name * name of object reference (in source code) * * @throws IllegalNotNullArgumentException * if the given argument {@code reference} is not null */ @Throws(IllegalNotNullArgumentException.class) public static void isNull(@Nullable final Object reference, @Nullable final String name) { if (reference != null) { throw new IllegalNotNullArgumentException(name, reference); } } /** * Ensures that a String argument is a number. * * @param value * value which must be a number * @return the given string argument converted to an int * * @throws IllegalNumberArgumentException * if the given argument {@code value} is not a number */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNumberArgumentException.class }) public static int isNumber(@Nonnull final String value) { Check.notNull(value, "value"); return Check.isNumber(value, Integer.class).intValue(); } /** * Ensures that a String argument is a number. This overload supports all subclasses of {@code Number}. The number * is first converted to a BigInteger * * @param value * value which must be a number * @param type * requested return value type, must be a subclass of {@code Number}, i.e. one of {@code BigDecimal, * BigInteger, Byte, Double, Float, Integer, Long, Short} * @return the given string argument converted to a number of the requested type * * @throws IllegalNumberArgumentException * if the given argument {@code value} is no number */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNumberArgumentException.class }) public static <T extends Number> T isNumber(@Nonnull final String value, @Nonnull final Class<T> type) { return isNumber(value, null, type); } /** * Ensures that a string argument is a number according to {@code Integer.parseInt} * * @param value * value which must be a number * @param name * name of object reference (in source code) * @return the given string argument converted to an int * * @throws IllegalNumberArgumentException * if the given argument {@code value} is no number */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNumberArgumentException.class }) public static int isNumber(@Nonnull final String value, @Nullable final String name) { Check.notNull(value, "value"); return Check.isNumber(value, name, Integer.class).intValue(); } /** * Ensures that a String argument is a number. This overload supports all subclasses of {@code Number}. The number * is first converted to a {@code BigDecimal} or {@code BigInteger}. Floating point types are only supported if the * {@code type} is one of {@code Float, Double, BigDecimal}. * * <p> * This method does also check against the ranges of the given datatypes. * * @param value * value which must be a number and in the range of the given datatype. * @param name * (optional) name of object reference (in source code). * @param type * requested return value type, must be a subclass of {@code Number}, i.e. one of {@code BigDecimal, * BigInteger, Byte, Double, Float, Integer, Long, Short} * @return the given string argument converted to a number of the requested type * * @throws IllegalNumberArgumentException * if the given argument {@code value} is no number */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNumberArgumentException.class }) public static <T extends Number> T isNumber(@Nonnull final String value, @Nullable final String name, @Nonnull final Class<T> type) { Check.notNull(value, "value"); Check.notNull(type, "type"); final Number ret; try { ret = checkNumberInRange(value, type); } catch (final NumberFormatException nfe) { if (name == null) { throw new IllegalNumberArgumentException(value, nfe); } else { throw new IllegalNumberArgumentException(name, value, nfe); } } return type.cast(ret); } /** * Ensures that a readable sequence of {@code char} values is numeric. Numeric arguments consist only of the * characters 0-9 and may start with 0 (compared to number arguments, which must be valid numbers - think of a bank * account number). * * <p> * We recommend to use the overloaded method {@link Check#isNumeric(CharSequence, String)} and pass as second * argument the name of the parameter to enhance the exception message. * * @param value * a readable sequence of {@code char} values which must be a number * @return the given string argument * @throws IllegalNumberArgumentException * if the given argument {@code value} is no number */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNumberArgumentException.class }) public static <T extends CharSequence> T isNumeric(@Nonnull final T value) { return isNumeric(value, EMPTY_ARGUMENT_NAME); } /** * Ensures that a readable sequence of {@code char} values is numeric. Numeric arguments consist only of the * characters 0-9 and may start with 0 (compared to number arguments, which must be valid numbers - think of a bank * account number). * * @param value * a readable sequence of {@code char} values which must be a number * @param name * name of object reference (in source code) * @return the given string argument * @throws IllegalNumberArgumentException * if the given argument {@code value} is no number */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNumericArgumentException.class }) public static <T extends CharSequence> T isNumeric(@Nonnull final T value, @Nullable final String name) { Check.notNull(value, "value"); if (!matches(NumericRegularExpressionHolder.getPattern(), value)) { throw new IllegalNumericArgumentException(name, value); } return value; } /** * Ensures that a passed {@code byte} is less than another {@code byte}. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code byte} argument {@code check} * * @throws IllegalNotLesserThanException * if the argument value {@code check} is not lesser than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotLesserThanException.class) public static byte lesserThan(@Nonnull final byte expected, @Nonnull final byte check) { if (expected <= check) { throw new IllegalNotLesserThanException(check); } return check; } /** * Ensures that a passed {@code byte} is less than another {@code byte}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the comparables must be less than a value (will be passed to * {@code IllegalNotLessThanException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotLesserThanException * if the argument value {@code check} is not lesser than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotLesserThanException.class) public static byte lesserThan(@Nonnull final byte expected, @Nonnull final byte check, final String message) { if (expected <= check) { throw new IllegalNotLesserThanException(message, check); } return check; } /** * Ensures that a passed {@code char} is less than another {@code char}. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code char} argument {@code check} * * @throws IllegalNotLesserThanException * if the argument value {@code check} is not lesser than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotLesserThanException.class) public static char lesserThan(@Nonnull final char expected, @Nonnull final char check) { if (expected <= check) { throw new IllegalNotLesserThanException(check); } return check; } /** * Ensures that a passed {@code char} is less than another {@code char}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the comparables must be less than a value (will be passed to * {@code IllegalNotLessThanException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotLesserThanException * if the argument value {@code check} is not lesser than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotLesserThanException.class) public static char lesserThan(@Nonnull final char expected, @Nonnull final char check, final String message) { if (expected <= check) { throw new IllegalNotLesserThanException(message, check); } return check; } /** * Ensures that a passed {@code double} is less than another {@code double}. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code double} argument {@code check} * * @throws IllegalNotLesserThanException * if the argument value {@code check} is not lesser than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotLesserThanException.class) public static double lesserThan(@Nonnull final double expected, @Nonnull final double check) { if (expected <= check) { throw new IllegalNotLesserThanException(check); } return check; } /** * Ensures that a passed {@code double} is less than another {@code double}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the comparables must be less than a value (will be passed to * {@code IllegalNotLessThanException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotLesserThanException * if the argument value {@code check} is not lesser than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotLesserThanException.class) public static double lesserThan(@Nonnull final double expected, @Nonnull final double check, final String message) { if (expected <= check) { throw new IllegalNotLesserThanException(message, check); } return check; } /** * Ensures that a passed {@code float} is less than another {@code float}. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code float} argument {@code check} * * @throws IllegalNotLesserThanException * if the argument value {@code check} is not lesser than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotLesserThanException.class) public static float lesserThan(@Nonnull final float expected, @Nonnull final float check) { if (expected <= check) { throw new IllegalNotLesserThanException(check); } return check; } /** * Ensures that a passed {@code float} is less than another {@code float}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the comparables must be less than a value (will be passed to * {@code IllegalNotLessThanException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotLesserThanException * if the argument value {@code check} is not lesser than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotLesserThanException.class) public static float lesserThan(@Nonnull final float expected, @Nonnull final float check, final String message) { if (expected <= check) { throw new IllegalNotLesserThanException(message, check); } return check; } /** * Ensures that a passed {@code int} is less than another {@code int}. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code int} argument {@code check} * * @throws IllegalNotLesserThanException * if the argument value {@code check} is not lesser than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotLesserThanException.class) public static int lesserThan(@Nonnull final int expected, @Nonnull final int check) { if (expected <= check) { throw new IllegalNotLesserThanException(check); } return check; } /** * Ensures that a passed {@code int} is less than another {@code int}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the comparables must be less than a value (will be passed to * {@code IllegalNotLessThanException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotLesserThanException * if the argument value {@code check} is not lesser than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotLesserThanException.class) public static int lesserThan(@Nonnull final int expected, @Nonnull final int check, final String message) { if (expected <= check) { throw new IllegalNotLesserThanException(message, check); } return check; } /** * Ensures that a passed {@code long} is less than another {@code long}. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code long} argument {@code check} * * @throws IllegalNotLesserThanException * if the argument value {@code check} is not lesser than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotLesserThanException.class) public static long lesserThan(@Nonnull final long expected, @Nonnull final long check) { if (expected <= check) { throw new IllegalNotLesserThanException(check); } return check; } /** * Ensures that a passed {@code long} is less than another {@code long}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the comparables must be less than a value (will be passed to * {@code IllegalNotLessThanException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotLesserThanException * if the argument value {@code check} is not lesser than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotLesserThanException.class) public static long lesserThan(@Nonnull final long expected, @Nonnull final long check, final String message) { if (expected <= check) { throw new IllegalNotLesserThanException(message, check); } return check; } /** * Ensures that a passed {@code short} is less than another {@code short}. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code short} argument {@code check} * * @throws IllegalNotLesserThanException * if the argument value {@code check} is not lesser than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotLesserThanException.class) public static short lesserThan(@Nonnull final short expected, @Nonnull final short check) { if (expected <= check) { throw new IllegalNotLesserThanException(check); } return check; } /** * Ensures that a passed {@code short} is less than another {@code short}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the comparables must be less than a value (will be passed to * {@code IllegalNotLessThanException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotLesserThanException * if the argument value {@code check} is not lesser than value {@code expected} */ @ArgumentsChecked @Throws(IllegalNotLesserThanException.class) public static short lesserThan(@Nonnull final short expected, @Nonnull final short check, final String message) { if (expected <= check) { throw new IllegalNotLesserThanException(message, check); } return check; } /** * Ensures that a passed {@code Comparable} is less than another {@code Comparable}. The comparison is made using * {@code expected.compareTo(check) <= 0}. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotLesserThanException * if the argument value {@code check} is not lesser than value {@code expected} when using method * {@code compareTo} */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNotLesserThanException.class }) public static <T extends Comparable<T>> T lesserThan(@Nonnull final T expected, @Nonnull final T check) { Check.notNull(expected, "expected"); Check.notNull(check, "check"); if (expected.compareTo(check) <= 0) { throw new IllegalNotLesserThanException(check); } return check; } /** * Ensures that a passed {@code Comparable} is less than another {@code Comparable}. The comparison is made using * {@code expected.compareTo(check) <= 0}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the comparables must be less than a value (will be passed to * {@code IllegalNotLessThanException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalNotLesserThanException * if the argument value {@code check} is not lesser than value {@code expected} when using method * {@code compareTo} */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNotLesserThanException.class }) public static <T extends Comparable<T>> T lesserThan(@Nonnull final T expected, @Nonnull final T check, final String message) { Check.notNull(expected, "expected"); Check.notNull(check, "check"); if (expected.compareTo(check) <= 0) { throw new IllegalNotLesserThanException(message, check); } return check; } /** * Checks whether a character sequence matches against a specified pattern or not. * * @param pattern * pattern, that the {@code chars} must correspond to * @param chars * a readable sequence of {@code char} values which should match the given pattern * @return {@code true} when {@code chars} matches against the passed {@code pattern}, otherwise {@code false} */ private static boolean matches(@Nonnull final Pattern pattern, @Nonnull final CharSequence chars) { return pattern.matcher(chars).matches(); } /** * Ensures that a readable sequence of {@code char} values matches a specified pattern. If the given character * sequence does not match against the passed pattern, an {@link IllegalPatternArgumentException} will be thrown. * * <p> * We recommend to use the overloaded method {@link Check#matchesPattern(Pattern, CharSequence, String)} and pass as * second argument the name of the parameter to enhance the exception message. * * @param pattern * pattern, that the {@code chars} must correspond to * @param chars * a readable sequence of {@code char} values which should match the given pattern * @return the passed {@code chars} that matches the given pattern * * @throws IllegalNullArgumentException * if the given argument {@code chars} is {@code null} * @throws IllegalPatternArgumentException * if the given {@code chars} that does not match the {@code pattern} */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalPatternArgumentException.class }) public static <T extends CharSequence> T matchesPattern(@Nonnull final Pattern pattern, @Nonnull final T chars) { return matchesPattern(pattern, chars, EMPTY_ARGUMENT_NAME); } /** * Ensures that a readable sequence of {@code char} values matches a specified pattern. If the given character * sequence does not match against the passed pattern, an {@link IllegalPatternArgumentException} will be thrown. * * @param pattern * pattern, that the {@code chars} must correspond to * @param chars * a readable sequence of {@code char} values which should match the given pattern * @param name * name of object reference (in source code) * @return the passed {@code chars} that matches the given pattern * * @throws IllegalNullArgumentException * if the given argument {@code chars} is {@code null} * @throws IllegalPatternArgumentException * if the given {@code chars} that does not match the {@code pattern} */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalPatternArgumentException.class }) public static <T extends CharSequence> T matchesPattern(@Nonnull final Pattern pattern, @Nonnull final T chars, @Nullable final String name) { Check.notNull(pattern, "pattern"); Check.notNull(chars, "chars"); if (!matches(pattern, chars)) { throw new IllegalPatternArgumentException(name, pattern, chars); } return chars; } /** * Ensures that an iterable reference is neither {@code null} nor contains any elements that are {@code null}. * * <p> * We recommend to use the overloaded method {@link Check#noNullElements(Iterable, String)} and pass as second * argument the name of the parameter to enhance the exception message. * * @param iterable * the iterable reference which should not contain {@code null} * @return the passed reference which contains no elements that are {@code null} * * @throws IllegalNullElementsException * if the given argument {@code iterable} contains elements that are {@code null} */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNullElementsException.class }) public static <T extends Iterable<?>> T noNullElements(@Nonnull final T iterable) { return noNullElements(iterable, EMPTY_ARGUMENT_NAME); } /** * Ensures that an iterable reference is neither {@code null} nor contains any elements that are {@code null}. * * @param iterable * the iterable reference which should not contain {@code null} * @param name * name of object reference (in source code) * @return the passed reference which contains no elements that are {@code null} * @throws IllegalNullElementsException * if the given argument {@code iterable} contains elements that are {@code null} */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNullElementsException.class }) public static <T extends Iterable<?>> T noNullElements(@Nonnull final T iterable, final String name) { Check.notNull(iterable, "iterable"); for (final Object element : iterable) { if (element == null) { throw new IllegalNullElementsException(name); } } return iterable; } /** * Ensures that an array does not contain {@code null}. * * <p> * We recommend to use the overloaded method {@link Check#noNullElements(Object[], String)} and pass as second * argument the name of the parameter to enhance the exception message. * * @param array * reference to an array * @return the passed reference which contains no elements that are {@code null} * @throws IllegalNullElementsException * if the given argument {@code array} contains {@code null} */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNullElementsException.class }) public static <T> T[] noNullElements(@Nonnull final T[] array) { return noNullElements(array, EMPTY_ARGUMENT_NAME); } /** * Ensures that an array does not contain {@code null}. * * @param array * reference to an array * @param name * name of object reference (in source code) * @return the passed reference which contains no elements that are {@code null} * @throws IllegalNullElementsException * if the given argument {@code array} contains {@code null} */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNullElementsException.class }) public static <T> T[] noNullElements(@Nonnull final T[] array, @Nullable final String name) { Check.notNull(array, "array"); if (containsNullElements(array)) { throw new IllegalNullElementsException(name); } return array; } /** * Ensures that a passed parameter of the calling method is not empty, using the passed expression to evaluate the * emptiness. * * <p> * We recommend to use the overloaded method {@link Check#notEmpty(boolean, String)} and pass as second argument the * name of the parameter to enhance the exception message. * * @param expression * the result of the expression to verify the emptiness of a reference ({@code true} means empty, * {@code false} means not empty) * * @throws IllegalNullArgumentException * if the given argument {@code reference} is {@code null} * @throws IllegalEmptyArgumentException * if the given argument {@code reference} is empty */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static void notEmpty(final boolean expression) { notEmpty(expression, EMPTY_ARGUMENT_NAME); } /** * Ensures that a passed parameter of the calling method is not empty, using the passed expression to evaluate the * emptiness. * * @param expression * the result of the expression to verify the emptiness of a reference ({@code true} means empty, * {@code false} means not empty) * @param name * name of object reference (in source code) * * @throws IllegalEmptyArgumentException * if the given argument {@code reference} is empty */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static void notEmpty(final boolean expression, @Nullable final String name) { if (expression) { throw new IllegalEmptyArgumentException(name); } } /** * Ensures that a passed string as a parameter of the calling method is not empty. * * <p> * We recommend to use the overloaded method {@link Check#notEmpty(CharSequence, String)} and pass as second * argument the name of the parameter to enhance the exception message. * * @param chars * a readable sequence of {@code char} values which should not be empty * @return the passed reference that is not empty * @throws IllegalNullArgumentException * if the given argument {@code reference} is {@code null} * @throws IllegalEmptyArgumentException * if the given argument {@code reference} is empty */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static <T extends CharSequence> T notEmpty(@Nonnull final T chars) { notNull(chars); notEmpty(chars, chars.length() == 0, EMPTY_ARGUMENT_NAME); return chars; } /** * Ensures that a passed collection as a parameter of the calling method is not empty. * * <p> * We recommend to use the overloaded method {@link Check#notEmpty(Collection, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param collection * a collection which should not be empty * @return the passed reference that is not empty * @throws IllegalNullArgumentException * if the given argument {@code collection} is {@code null} * @throws IllegalEmptyArgumentException * if the given argument {@code collection} is empty */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static <T extends Collection<?>> T notEmpty(@Nonnull final T collection) { notNull(collection); notEmpty(collection, collection.isEmpty(), EMPTY_ARGUMENT_NAME); return collection; } /** * Ensures that a passed map as a parameter of the calling method is not empty. * * <p> * We recommend to use the overloaded method {@link Check#notEmpty(Collection, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param map * a map which should not be empty * @return the passed reference that is not empty * @throws IllegalNullArgumentException * if the given argument {@code map} is {@code null} * @throws IllegalEmptyArgumentException * if the given argument {@code map} is empty */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static <T extends Map<?, ?>> T notEmpty(@Nonnull final T map) { notNull(map); notEmpty(map, map.isEmpty(), EMPTY_ARGUMENT_NAME); return map; } /** * Ensures that an object reference passed as a parameter to the calling method is not empty. The passed boolean * value is the result of checking whether the reference is empty or not. * * <p> * The following example describes how to use it. * * <pre> * &#064;ArgumentsChecked * public setText(String text) { * Check.notEmpty(text, text.isEmpty(), &quot;text&quot;); * this.text = text; * } * </pre> * * @param reference * an object reference which should not be empty * @param expression * the result of the expression to verify the emptiness of a reference ({@code true} means empty, * {@code false} means not empty) * @param name * name of object reference (in source code) * @return the passed reference that is not empty * @throws IllegalNullArgumentException * if the given argument {@code reference} is {@code null} * @throws IllegalEmptyArgumentException * if the given argument {@code reference} is empty */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static <T> T notEmpty(@Nonnull final T reference, final boolean expression, @Nullable final String name) { notNull(reference, name); if (expression) { throw new IllegalEmptyArgumentException(name); } return reference; } /** * Ensures that a passed string as a parameter of the calling method is not empty. * * <p> * The following example describes how to use it. * * <pre> * &#064;ArgumentsChecked * public setText(String text) { * this.text = Check.notEmpty(text, &quot;text&quot;); * } * </pre> * * @param chars * a readable sequence of {@code char} values which should not be empty * @param name * name of object reference (in source code) * @return the passed reference that is not empty * @throws IllegalNullArgumentException * if the given argument {@code string} is {@code null} * @throws IllegalEmptyArgumentException * if the given argument {@code string} is empty */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static <T extends CharSequence> T notEmpty(@Nonnull final T chars, @Nullable final String name) { notNull(chars, name); notEmpty(chars, chars.length() == 0, name); return chars; } /** * Ensures that a passed map as a parameter of the calling method is not empty. * * <p> * We recommend to use the overloaded method {@link Check#notEmpty(Collection, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param map * a map which should not be empty * @param name * name of object reference (in source code) * @return the passed reference that is not empty * @throws IllegalNullArgumentException * if the given argument {@code map} is {@code null} * @throws IllegalEmptyArgumentException * if the given argument {@code map} is empty */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static <T extends Map<?, ?>> T notEmpty(@Nonnull final T map, @Nullable final String name) { notNull(map); notEmpty(map, map.isEmpty(), name); return map; } /** * Ensures that a passed collection as a parameter of the calling method is not empty. * * <p> * The following example describes how to use it. * * <pre> * &#064;ArgumentsChecked * public setCollection(Collection&lt;String&gt; collection) { * this.collection = Check.notEmpty(collection, &quot;collection&quot;); * } * </pre> * * @param collection * a collection which should not be empty * @param name * name of object reference (in source code) * @return the passed reference that is not empty * @throws IllegalNullArgumentException * if the given argument {@code collection} is {@code null} * @throws IllegalEmptyArgumentException * if the given argument {@code collection} is empty */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static <T extends Collection<?>> T notEmpty(@Nonnull final T collection, @Nullable final String name) { notNull(collection, name); notEmpty(collection, collection.isEmpty(), name); return collection; } /** * Ensures that a passed map as a parameter of the calling method is not empty. * * <p> * We recommend to use the overloaded method {@link Check#notEmpty(Object[], String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param array * a map which should not be empty * @return the passed reference that is not empty * @throws IllegalNullArgumentException * if the given argument {@code array} is {@code null} * @throws IllegalEmptyArgumentException * if the given argument {@code array} is empty */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static <T> T[] notEmpty(@Nonnull final T[] array) { notNull(array); notEmpty(array, array.length == 0, EMPTY_ARGUMENT_NAME); return array; } /** * Ensures that a passed map as a parameter of the calling method is not empty. * * @param array * a map which should not be empty * @param name * name of object reference (in source code) * @return the passed reference that is not empty * @throws IllegalNullArgumentException * if the given argument {@code array} is {@code null} * @throws IllegalEmptyArgumentException * if the given argument {@code array} is empty */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static <T> T[] notEmpty(@Nonnull final T[] array, @Nullable final String name) { notNull(array); notEmpty(array, array.length == 0, EMPTY_ARGUMENT_NAME); return array; } /** * Ensures that a passed boolean is not equal to another boolean. The comparison is made using * <code>expected == check</code>. * * <p> * We recommend to use the overloaded method {@link Check#notEquals(boolean, boolean, String)} and pass as second * argument the name of the parameter to enhance the exception message. * * @param expected * Expected value * @param check * boolean to be checked * @return the passed boolean argument {@code check} * * @throws IllegalEqualException * if both argument values are not equal */ @Throws(IllegalEqualException.class) public static boolean notEquals(@Nonnull final boolean expected, @Nonnull final boolean check) { // NOSONAR // Sonar warns about suspicious notEquals method name, as the name is intended deactivate sonar if (expected == check) { throw new IllegalEqualException(check); } return check; } /** * Ensures that a passed boolean is not equal to another boolean. The comparison is made using * <code>expected == check</code>. * * @param expected * Expected value * @param check * boolean to be checked * @param message * an error message describing why the booleans must equal (will be passed to * {@code IllegalEqualException}) * @return the passed boolean argument {@code check} * * @throws IllegalEqualException * if both argument values are not equal */ @Throws(IllegalEqualException.class) public static boolean notEquals(@Nonnull final boolean expected, @Nonnull final boolean check, final String message) { // NOSONAR // Sonar warns about suspicious notEquals method name, as the name is intended deactivate sonar if (expected == check) { throw new IllegalEqualException(message, check); } return check; } /** * Ensures that a passed byte is not equal to another byte. The comparison is made using * <code>expected == check</code>. * * <p> * We recommend to use the overloaded method {@link Check#notEquals(byte, byte, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param expected * Expected value * @param check * byte to be checked * @return the passed byte argument {@code check} * * @throws IllegalEqualException * if both argument values are not equal */ @Throws(IllegalEqualException.class) public static byte notEquals(@Nonnull final byte expected, @Nonnull final byte check) { // NOSONAR // Sonar warns about suspicious notEquals method name, as the name is intended deactivate sonar if (expected == check) { throw new IllegalEqualException(check); } return check; } /** * Ensures that a passed byte is not equal to another byte. The comparison is made using * <code>expected == check</code>. * * @param expected * Expected value * @param check * byte to be checked * @param message * an error message describing why the bytes must equal (will be passed to {@code IllegalEqualException}) * @return the byte boolean argument {@code check} * * @throws IllegalEqualException * if both argument values are not equal */ @Throws(IllegalEqualException.class) public static byte notEquals(@Nonnull final byte expected, @Nonnull final byte check, final String message) { // NOSONAR // Sonar warns about suspicious notEquals method name, as the name is intended deactivate sonar if (expected == check) { throw new IllegalEqualException(message, check); } return check; } /** * Ensures that a passed char is not equal to another char. The comparison is made using * <code>expected == check</code>. * * <p> * We recommend to use the overloaded method {@link Check#notEquals(char, char, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param expected * Expected value * @param check * char to be checked * @return the passed char argument {@code check} * * @throws IllegalEqualException * if both argument values are not equal */ @Throws(IllegalEqualException.class) public static char notEquals(@Nonnull final char expected, @Nonnull final char check) { // NOSONAR // Sonar warns about suspicious notEquals method name, as the name is intended deactivate sonar if (expected == check) { throw new IllegalEqualException(check); } return check; } /** * Ensures that a passed char is not equal to another char. The comparison is made using * <code>expected == check</code>. * * @param expected * Expected value * @param check * char to be checked * @param message * an error message describing why the chars must equal (will be passed to {@code IllegalEqualException}) * @return the passed char argument {@code check} * * @throws IllegalEqualException * if both argument values are not equal */ @Throws(IllegalEqualException.class) public static char notEquals(@Nonnull final char expected, @Nonnull final char check, final String message) { // NOSONAR // Sonar warns about suspicious notEquals method name, as the name is intended deactivate sonar if (expected == check) { throw new IllegalEqualException(message, check); } return check; } /** * Ensures that a passed intH is not equal to another int. The comparison is made using * <code>expected == check</code>. * * <p> * We recommend to use the overloaded method {@link Check#notEquals(int, int, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param expected * Expected value * @param check * int to be checked * @return the passed int argument {@code check} * * @throws IllegalEqualException * if both argument values are not equal */ @Throws(IllegalEqualException.class) public static int notEquals(@Nonnull final int expected, @Nonnull final int check) { // NOSONAR // Sonar warns about suspicious notEquals method name, as the name is intended deactivate sonar if (expected == check) { throw new IllegalEqualException(check); } return check; } /** * Ensures that a passed int is not equal to another int. The comparison is made using * <code>expected == check</code>. * * @param expected * Expected value * @param check * int to be checked * @param message * an error message describing why the ints must equal (will be passed to {@code IllegalEqualException}) * @return the passed int argument {@code check} * * @throws IllegalEqualException * if both argument values are not equal */ @Throws(IllegalEqualException.class) public static int notEquals(@Nonnull final int expected, @Nonnull final int check, final String message) { // NOSONAR // Sonar warns about suspicious notEquals method name, as the name is intended deactivate sonar if (expected == check) { throw new IllegalEqualException(message, check); } return check; } /** * Ensures that a passed long is not equal to another long. The comparison is made using * <code>expected == check</code>. * * <p> * We recommend to use the overloaded method {@link Check#notEquals(long, long, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param expected * Expected value * @param check * long to be checked * @return the passed long argument {@code check} * * @throws IllegalEqualException * if both argument values are not equal */ @Throws(IllegalEqualException.class) public static long notEquals(@Nonnull final long expected, @Nonnull final long check) { // NOSONAR // Sonar warns about suspicious notEquals method name, as the name is intended deactivate sonar if (expected == check) { throw new IllegalEqualException(check); } return check; } /** * Ensures that a passed long is not equal to another long. The comparison is made using * <code>expected == check</code>. * * @param expected * Expected value * @param check * long to be checked * @param message * an error message describing why the longs must equal (will be passed to {@code IllegalEqualException}) * @return the passed long argument {@code check} * * @throws IllegalEqualException * if both argument values are not equal */ @Throws(IllegalEqualException.class) public static long notEquals(@Nonnull final long expected, @Nonnull final long check, final String message) { // NOSONAR // Sonar warns about suspicious notEquals method name, as the name is intended deactivate sonar if (expected == check) { throw new IllegalEqualException(message, check); } return check; } /** * Ensures that a passed short is not equal to another short. The comparison is made using * <code>expected == check</code>. * * <p> * We recommend to use the overloaded method {@link Check#notEquals(short, short, String)} and pass as second * argument the name of the parameter to enhance the exception message. * * @param expected * Expected value * @param check * short to be checked * @return the passed short argument {@code check} * * @throws IllegalEqualException * if both argument values are not equal */ @Throws(IllegalEqualException.class) public static short notEquals(@Nonnull final short expected, @Nonnull final short check) { // NOSONAR // Sonar warns about suspicious notEquals method name, as the name is intended deactivate sonar if (expected == check) { throw new IllegalEqualException(check); } return check; } /** * Ensures that a passed short is not equal to another short. The comparison is made using * <code>expected == check</code>. * * @param expected * Expected value * @param check * short to be checked * @param message * an error message describing why the shorts must equal (will be passed to {@code IllegalEqualException} * ) * @return the passed short {@code check} * * @throws IllegalEqualException * if both argument values are not equal */ @Throws(IllegalEqualException.class) public static short notEquals(@Nonnull final short expected, @Nonnull final short check, final String message) { // NOSONAR // Sonar warns about suspicious notEquals method name, as the name is intended deactivate sonar if (expected == check) { throw new IllegalEqualException(message, check); } return check; } /** * Ensures that a passed {@code Comparable} is not equal to another {@code Comparable}. The comparison is made using * {@code expected.compareTo(check) == 0}. * * <p> * We recommend to use the overloaded method {@link Check#notEquals(Comparable, Comparable, String)} and pass as * second argument the name of the parameter to enhance the exception message. * * @param expected * Expected value * @param check * Comparable to be checked * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalEqualException * if both argument values are not equal */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEqualException.class }) public static <T extends Comparable<T>> T notEquals(@Nonnull final T expected, @Nonnull final T check) { Check.notNull(expected, "expected"); Check.notNull(check, "check"); if (expected.compareTo(check) == 0) { throw new IllegalEqualException(check); } return check; } /** * Ensures that a passed object is not equal to another object. The comparison is made using a call to * {@code expected.equals(check) }. * * <p> * We recommend to use the overloaded method {@link Check#notEquals(Object, Object, String)} and pass as second * argument the name of the parameter to enhance the exception message. * * @param expected * Expected value * @param check * Object to be checked * @return the passed argument {@code check} * * @throws IllegalEqualException * if both argument values are not equal */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEqualException.class }) public static <T extends Object> T notEquals(@Nonnull final T expected, @Nonnull final T check) { Check.notNull(expected, "expected"); Check.notNull(check, "check"); if (expected.equals(check)) { throw new IllegalEqualException(check); } return check; } /** * Ensures that a passed {@code Comparable} is not equal to another {@code Comparable}. The comparison is made using * {@code expected.compareTo(check) == 0}. * * @param expected * Expected value * @param check * Comparable to be checked * @param message * an error message describing why the <a>s must equal (will be passed to {@code IllegalEqualException}) * @return the passed {@code Comparable} argument {@code check} * * @throws IllegalEqualException * if both argument values are not equal */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEqualException.class }) public static <T extends Comparable<T>> T notEquals(@Nonnull final T expected, @Nonnull final T check, final String message) { Check.notNull(expected, "expected"); Check.notNull(check, "check"); if (expected.compareTo(check) == 0) { throw new IllegalEqualException(message, check); } return check; } /** * Ensures that a passed object is not equal to another object. The comparison is made using a call to * {@code expected.equals(check)}. * * @param expected * Expected value * @param check * Object to be checked * @param message * an error message describing why the objects must equal (will be passed to * {@code IllegalEqualException}) * @return the passed argument {@code check} * * @throws IllegalEqualException * if both argument values are not equal */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEqualException.class }) public static <T extends Object> T notEquals(@Nonnull final T expected, @Nonnull final T check, final String message) { Check.notNull(expected, "expected"); Check.notNull(check, "check"); if (expected.equals(check)) { throw new IllegalEqualException(message, check); } return check; } /** * Do not perform any check and just return {@code t}. * * This is useful if you have several checks on some arguments, but do not check other arguments on purpose. This * checks helps to document that a check was omitted on purpose instead of forgotten. * * @param t * any object * @return t */ public static <T> T nothing(final T t) { return t; } /** * Ensures that a double argument is not NaN (not a number). * * <p> * We recommend to use the overloaded method {@link Check#notNaN(double, String)} and pass as second argument the * name of the parameter to enhance the exception message. * * @see java.lang.Double#NaN * * @param value * value which should not be NaN * @return the given double value * @throws IllegalNaNArgumentException * if the given argument {@code value} is NaN */ @Throws(IllegalNaNArgumentException.class) public static double notNaN(final double value) { return notNaN(value, EMPTY_ARGUMENT_NAME); } /** * Ensures that a double argument is not NaN (not a number). * * @see java.lang.Double#NaN * * @param value * value which should not be NaN * @param name * name of object reference (in source code) * @return the given double value * @throws IllegalNaNArgumentException * if the given argument {@code value} is NaN */ @Throws(IllegalNaNArgumentException.class) public static double notNaN(final double value, @Nullable final String name) { // most efficient check for NaN, see Double.isNaN(value)) if (value != value) { throw new IllegalNaNArgumentException(name); } return value; } /** * Ensures that a double argument is not NaN (not a number). * * <p> * We recommend to use the overloaded method {@link Check#notNaN(float, String)} and pass as second argument the * name of the parameter to enhance the exception message. * * @see java.lang.Float#NaN * * @param value * value which should not be NaN * @return the given double value * @throws IllegalNaNArgumentException * if the given argument {@code value} is NaN */ @Throws(IllegalNaNArgumentException.class) public static float notNaN(final float value) { return notNaN(value, EMPTY_ARGUMENT_NAME); } /** * Ensures that a double argument is not NaN (not a number). * * @see java.lang.Float#NaN * * @param value * value which should not be NaN * @param name * name of object reference (in source code) * @return the given float value * @throws IllegalNaNArgumentException * if the given argument {@code value} is NaN */ @Throws(IllegalNaNArgumentException.class) public static float notNaN(final float value, @Nullable final String name) { // most efficient check for NaN, see Float.isNaN(value)) if (value != value) { throw new IllegalNaNArgumentException(name); } return value; } /** * Ensures that an double reference passed as a parameter to the calling method is not smaller than {@code 0}. * * <p> * We recommend to use the overloaded method {@link Check#notNegative(double, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param value * a number * @return the non-null reference that was validated * @throws IllegalNegativeArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalNegativeArgumentException.class) public static double notNegative(@Nonnull final double value) { if (value < 0.0) { throw new IllegalNegativeArgumentException(value); } return value; } /** * Ensures that an double reference passed as a parameter to the calling method is not smaller than {@code 0}. * * @param value * a number * @param name * name of the number reference (in source code) * @return the non-null reference that was validated * @throws IllegalNullArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalNegativeArgumentException.class) public static double notNegative(@Nonnull final double value, @Nullable final String name) { if (value < 0.0) { throw new IllegalNegativeArgumentException(name, value); } return value; } /** * Ensures that an float reference passed as a parameter to the calling method is not smaller than {@code 0}. * * <p> * We recommend to use the overloaded method {@link Check#notNegative(float, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param value * a number * @return the non-null reference that was validated * @throws IllegalNegativeArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalNegativeArgumentException.class) public static float notNegative(@Nonnull final float value) { if (value < 0.0f) { throw new IllegalNegativeArgumentException(value); } return value; } /** * Ensures that an float reference passed as a parameter to the calling method is not smaller than {@code 0}. * * @param value * a number * @param name * name of the number reference (in source code) * @return the non-null reference that was validated * @throws IllegalNullArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalNegativeArgumentException.class) public static float notNegative(@Nonnull final float value, @Nullable final String name) { if (value < 0.0f) { throw new IllegalNegativeArgumentException(name, value); } return value; } /** * Ensures that an integer reference passed as a parameter to the calling method is not smaller than {@code 0}. * * <p> * We recommend to use the overloaded method {@link Check#notNegative(int, String)} and pass as second argument the * name of the parameter to enhance the exception message. * * @param value * a number * @return the non-null reference that was validated * @throws IllegalNegativeArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalNegativeArgumentException.class) public static int notNegative(@Nonnull final int value) { if (value < 0) { throw new IllegalNegativeArgumentException(value); } return value; } /** * Ensures that an integer reference passed as a parameter to the calling method is not smaller than {@code 0}. * * @param value * a number * @param name * name of the number reference (in source code) * @return the non-null reference that was validated * @throws IllegalNullArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalNegativeArgumentException.class) public static int notNegative(@Nonnull final int value, @Nullable final String name) { if (value < 0) { throw new IllegalNegativeArgumentException(name, value); } return value; } /** * Ensures that an long reference passed as a parameter to the calling method is not smaller than {@code 0}. * * <p> * We recommend to use the overloaded method {@link Check#notNegative(long, String)} and pass as second argument the * name of the parameter to enhance the exception message. * * @param value * a number * @return the non-null reference that was validated * @throws IllegalNegativeArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalNegativeArgumentException.class) public static long notNegative(@Nonnull final long value) { if (value < 0L) { throw new IllegalNegativeArgumentException(value); } return value; } /** * Ensures that an long reference passed as a parameter to the calling method is not smaller than {@code 0}. * * @param value * a number * @param name * name of the number reference (in source code) * @return the non-null reference that was validated * @throws IllegalNullArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalNegativeArgumentException.class) public static long notNegative(@Nonnull final long value, @Nullable final String name) { if (value < 0L) { throw new IllegalNegativeArgumentException(name, value); } return value; } /** * Ensures that an short reference passed as a parameter to the calling method is not smaller than {@code 0}. * * <p> * We recommend to use the overloaded method {@link Check#notNegative(short, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param value * a number * @return the non-null reference that was validated * @throws IllegalNegativeArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalNegativeArgumentException.class) public static short notNegative(@Nonnull final short value) { if (value < (short) 0) { throw new IllegalNegativeArgumentException(value); } return value; } /** * Ensures that an short reference passed as a parameter to the calling method is not smaller than {@code 0}. * * @param value * a number * @param name * name of the number reference (in source code) * @return the non-null reference that was validated * @throws IllegalNullArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalNegativeArgumentException.class) public static short notNegative(@Nonnull final short value, @Nullable final String name) { if (value < (short) 0) { throw new IllegalNegativeArgumentException(name, value); } return value; } /** * Ensures that an object reference passed as a parameter to the calling method is not {@code null}. * * <p> * We recommend to use the overloaded method {@link Check#notNull(Object, String)} and pass as second argument the * name of the parameter to enhance the exception message. * * @param reference * an object reference * @return the non-null reference that was validated * @throws IllegalNullArgumentException * if the given argument {@code reference} is {@code null} */ @Throws(IllegalNullArgumentException.class) public static <T> T notNull(@Nonnull final T reference) { if (reference == null) { throw new IllegalNullArgumentException(); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not {@code null}. * * @param reference * an object reference * @param name * name of object reference (in source code) * @return the non-null reference that was validated * @throws IllegalNullArgumentException * if the given argument {@code reference} is {@code null} */ @Throws(IllegalNullArgumentException.class) public static <T> T notNull(@Nonnull final T reference, @Nullable final String name) { if (reference == null) { throw new IllegalNullArgumentException(name); } return reference; } /** * Ensures that an double reference passed as a parameter to the calling method is not greater than {@code 0}. * * <p> * We recommend to use the overloaded method {@link Check#notPositive(double, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param value * a number * @return the non-null reference that was validated * @throws IllegalPositiveArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalPositiveArgumentException.class) public static double notPositive(@Nonnull final double value) { if (value > 0.0) { throw new IllegalPositiveArgumentException(value); } return value; } /** * Ensures that an double reference passed as a parameter to the calling method is not greater than {@code 0}. * * @param value * a number * @param name * name of the number reference (in source code) * @return the non-null reference that was validated * @throws IllegalNullArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalPositiveArgumentException.class) public static double notPositive(@Nonnull final double value, @Nullable final String name) { if (value > 0.0) { throw new IllegalPositiveArgumentException(name, value); } return value; } /** * Ensures that an float reference passed as a parameter to the calling method is not greater than {@code 0}. * * <p> * We recommend to use the overloaded method {@link Check#notPositive(float, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param value * a number * @return the non-null reference that was validated * @throws IllegalPositiveArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalPositiveArgumentException.class) public static float notPositive(@Nonnull final float value) { if (value > 0.0f) { throw new IllegalPositiveArgumentException(value); } return value; } /** * Ensures that an float reference passed as a parameter to the calling method is not greater than {@code 0}. * * @param value * a number * @param name * name of the number reference (in source code) * @return the non-null reference that was validated * @throws IllegalNullArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalPositiveArgumentException.class) public static float notPositive(@Nonnull final float value, @Nullable final String name) { if (value > 0.0f) { throw new IllegalPositiveArgumentException(name, value); } return value; } /** * Ensures that an integer reference passed as a parameter to the calling method is not greater than {@code 0}. * * <p> * We recommend to use the overloaded method {@link Check#notPositive(int, String)} and pass as second argument the * name of the parameter to enhance the exception message. * * @param value * a number * @return the non-null reference that was validated * @throws IllegalPositiveArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalPositiveArgumentException.class) public static int notPositive(@Nonnull final int value) { if (value > 0) { throw new IllegalPositiveArgumentException(value); } return value; } /** * Ensures that an integer reference passed as a parameter to the calling method is not greater than {@code 0}. * * @param value * a number * @param name * name of the number reference (in source code) * @return the non-null reference that was validated * @throws IllegalNullArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalPositiveArgumentException.class) public static int notPositive(@Nonnull final int value, @Nullable final String name) { if (value > 0) { throw new IllegalPositiveArgumentException(name, value); } return value; } /** * Ensures that an long reference passed as a parameter to the calling method is not greater than {@code 0}. * * <p> * We recommend to use the overloaded method {@link Check#notPositive(long, String)} and pass as second argument the * name of the parameter to enhance the exception message. * * @param value * a number * @return the non-null reference that was validated * @throws IllegalPositiveArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalPositiveArgumentException.class) public static long notPositive(@Nonnull final long value) { if (value > 0L) { throw new IllegalPositiveArgumentException(value); } return value; } /** * Ensures that an long reference passed as a parameter to the calling method is not greater than {@code 0}. * * @param value * a number * @param name * name of the number reference (in source code) * @return the non-null reference that was validated * @throws IllegalNullArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalPositiveArgumentException.class) public static long notPositive(@Nonnull final long value, @Nullable final String name) { if (value > 0L) { throw new IllegalPositiveArgumentException(name, value); } return value; } /** * Ensures that an short reference passed as a parameter to the calling method is not greater than {@code 0}. * * <p> * We recommend to use the overloaded method {@link Check#notPositive(short, String)} and pass as second argument * the name of the parameter to enhance the exception message. * * @param value * a number * @return the non-null reference that was validated * @throws IllegalPositiveArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalPositiveArgumentException.class) public static short notPositive(@Nonnull final short value) { if (value > (short) 0) { throw new IllegalPositiveArgumentException(value); } return value; } /** * Ensures that an short reference passed as a parameter to the calling method is not greater than {@code 0}. * * @param value * a number * @param name * name of the number reference (in source code) * @return the non-null reference that was validated * @throws IllegalNullArgumentException * if the given argument {@code reference} is smaller than {@code 0} */ @Throws(IllegalPositiveArgumentException.class) public static short notPositive(@Nonnull final short value, @Nullable final String name) { if (value > (short) 0) { throw new IllegalPositiveArgumentException(name, value); } return value; } /** * Ensures that a given position index is valid within the size of an array, list or string ... * * @param index * index of an array, list or string * @param size * size of an array list or string * @return the index * * @throws IllegalPositionIndexException * if the index is not a valid position index within an array, list or string of size <em>size</em> * */ @Throws(IllegalPositionIndexException.class) public static int positionIndex(final int index, final int size) { final boolean isIndexValid = (size >= 0) && (index >= 0) && (index < size); if (!isIndexValid) { throw new IllegalPositionIndexException(index, size); } return index; } /** * Ensures that the given arguments are a valid range. * * A range (<em>start</em>, <em>end</em>, <em>size</em>) is valid if the following conditions are {@code true}: * <ul> * <li>start <= size</li> * <li>end <= size</li> * <li>start <= end</li> * <li>size >= 0</li> * <li>start >= 0</li> * <li>end >= 0</li> * </ul> * * @param start * the start value of the range (must be a positive integer or 0) * @param end * the end value of the range (must be a positive integer or 0) * @param size * the size value of the range (must be a positive integer or 0) * * @throws IllegalRangeException * if the given arguments do not form a valid range */ @Throws(IllegalRangeException.class) public static void range(@Nonnegative final int start, @Nonnegative final int end, @Nonnegative final int size) { final boolean rangeIsValid = (start <= size) && (end <= size) && (start <= end); final boolean inputValuesAreValid = (size >= 0) && (start >= 0) && (end >= 0); if (!rangeIsValid || !inputValuesAreValid) { throw new IllegalRangeException(start, end, size); } } /** * Ensures that a given state is {@code true}. * * <p> * We recommend to use the overloaded method {@link Check#stateIsTrue(boolean, String)} and pass as second argument * the name of the parameter to enhance the exception message. A better way is to create specific exceptions (with a * good wording) for your case and to use the overloaded method {@link Check#stateIsTrue(boolean, Class)} and pass * as second argument your exception. * * @param expression * an expression that must be true to indicate a valid state * * @throws IllegalStateOfArgumentException * if the given arguments caused an invalid state */ @Throws(IllegalStateOfArgumentException.class) public static void stateIsTrue(final boolean expression) { if (!expression) { throw new IllegalStateOfArgumentException(); } } /** * Ensures that a given state is {@code true} and allows to specify the class of exception which is thrown in case * the state is not {@code true}. * * @param expression * an expression that must be {@code true} to indicate a valid state * @param clazz * an subclass of {@link RuntimeException} which will be thrown if the given state is not valid * @throws clazz * a new instance of {@code clazz} if the given arguments caused an invalid state * @throws RuntimeInstantiationException * <strong>Attention</strong>: Be aware, that a {@code RuntimeInstantiationException} can be thrown when * the given {@code clazz} cannot be instantiated */ @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, RuntimeInstantiationException.class }) public static void stateIsTrue(final boolean expression, final Class<? extends RuntimeException> clazz) { Check.notNull(clazz, "clazz"); if (!expression) { RuntimeException re; try { re = clazz.newInstance(); } catch (final InstantiationException e) { throw new RuntimeInstantiationException(clazz.getSimpleName(), e); } catch (final IllegalAccessException e) { throw new RuntimeInstantiationException(clazz.getSimpleName(), e); } throw re; } } /** * Ensures that a given state is {@code true}. * * @param expression * an expression that must be {@code true} to indicate a valid state * @param description * will be used in the error message to describe why the arguments caused an invalid state * @throws IllegalStateOfArgumentException * if the given arguments caused an invalid state */ @Throws(IllegalStateOfArgumentException.class) public static void stateIsTrue(final boolean expression, @Nonnull final String description) { if (!expression) { throw new IllegalStateOfArgumentException(description); } } /** * Ensures that a given state is {@code true} * * @param expression * an expression that must be {@code true} to indicate a valid state * @param descriptionTemplate * format string template that explains why the state is invalid * @param descriptionTemplateArgs * format string template arguments to explain why the state is invalid * @throws IllegalStateOfArgumentException * if the given arguments caused an invalid state */ @Throws(IllegalStateOfArgumentException.class) public static void stateIsTrue(final boolean expression, @Nonnull final String descriptionTemplate, final Object... descriptionTemplateArgs) { if (!expression) { throw new IllegalStateOfArgumentException(descriptionTemplate, descriptionTemplateArgs); } } /** * <strong>Attention:</strong> This class is not intended to create objects from it. */ private Check() { // This class is not intended to create objects from it. } }
Removed NOSONAR checks on "notEquals" methods. Not needed
modules/quality-check/src/main/java/net/sf/qualitycheck/Check.java
Removed NOSONAR checks on "notEquals" methods. Not needed
<ide><path>odules/quality-check/src/main/java/net/sf/qualitycheck/Check.java <ide> * if both argument values are not equal <ide> */ <ide> @Throws(IllegalEqualException.class) <del> public static boolean notEquals(@Nonnull final boolean expected, @Nonnull final boolean check) { // NOSONAR <del> // Sonar warns about suspicious notEquals method name, as the name is intended deactivate sonar <del> <add> public static boolean notEquals(@Nonnull final boolean expected, @Nonnull final boolean check) { <ide> if (expected == check) { <ide> throw new IllegalEqualException(check); <ide> } <ide> * if both argument values are not equal <ide> */ <ide> @Throws(IllegalEqualException.class) <del> public static boolean notEquals(@Nonnull final boolean expected, @Nonnull final boolean check, final String message) { // NOSONAR <del> // Sonar warns about suspicious notEquals method name, as the name is intended deactivate sonar <del> <add> public static boolean notEquals(@Nonnull final boolean expected, @Nonnull final boolean check, final String message) { <ide> if (expected == check) { <ide> throw new IllegalEqualException(message, check); <ide> } <ide> * if both argument values are not equal <ide> */ <ide> @Throws(IllegalEqualException.class) <del> public static byte notEquals(@Nonnull final byte expected, @Nonnull final byte check) { // NOSONAR <del> // Sonar warns about suspicious notEquals method name, as the name is intended deactivate sonar <del> <add> public static byte notEquals(@Nonnull final byte expected, @Nonnull final byte check) { <ide> if (expected == check) { <ide> throw new IllegalEqualException(check); <ide> } <ide> * if both argument values are not equal <ide> */ <ide> @Throws(IllegalEqualException.class) <del> public static byte notEquals(@Nonnull final byte expected, @Nonnull final byte check, final String message) { // NOSONAR <del> // Sonar warns about suspicious notEquals method name, as the name is intended deactivate sonar <del> <add> public static byte notEquals(@Nonnull final byte expected, @Nonnull final byte check, final String message) { <ide> if (expected == check) { <ide> throw new IllegalEqualException(message, check); <ide> } <ide> * if both argument values are not equal <ide> */ <ide> @Throws(IllegalEqualException.class) <del> public static char notEquals(@Nonnull final char expected, @Nonnull final char check) { // NOSONAR <del> // Sonar warns about suspicious notEquals method name, as the name is intended deactivate sonar <del> <add> public static char notEquals(@Nonnull final char expected, @Nonnull final char check) { <ide> if (expected == check) { <ide> throw new IllegalEqualException(check); <ide> } <ide> * if both argument values are not equal <ide> */ <ide> @Throws(IllegalEqualException.class) <del> public static char notEquals(@Nonnull final char expected, @Nonnull final char check, final String message) { // NOSONAR <del> // Sonar warns about suspicious notEquals method name, as the name is intended deactivate sonar <del> <add> public static char notEquals(@Nonnull final char expected, @Nonnull final char check, final String message) { <ide> if (expected == check) { <ide> throw new IllegalEqualException(message, check); <ide> } <ide> * if both argument values are not equal <ide> */ <ide> @Throws(IllegalEqualException.class) <del> public static int notEquals(@Nonnull final int expected, @Nonnull final int check) { // NOSONAR <del> // Sonar warns about suspicious notEquals method name, as the name is intended deactivate sonar <del> <add> public static int notEquals(@Nonnull final int expected, @Nonnull final int check) { <ide> if (expected == check) { <ide> throw new IllegalEqualException(check); <ide> } <ide> * if both argument values are not equal <ide> */ <ide> @Throws(IllegalEqualException.class) <del> public static int notEquals(@Nonnull final int expected, @Nonnull final int check, final String message) { // NOSONAR <del> // Sonar warns about suspicious notEquals method name, as the name is intended deactivate sonar <del> <add> public static int notEquals(@Nonnull final int expected, @Nonnull final int check, final String message) { <ide> if (expected == check) { <ide> throw new IllegalEqualException(message, check); <ide> } <ide> * if both argument values are not equal <ide> */ <ide> @Throws(IllegalEqualException.class) <del> public static long notEquals(@Nonnull final long expected, @Nonnull final long check) { // NOSONAR <del> // Sonar warns about suspicious notEquals method name, as the name is intended deactivate sonar <del> <add> public static long notEquals(@Nonnull final long expected, @Nonnull final long check) { <ide> if (expected == check) { <ide> throw new IllegalEqualException(check); <ide> } <ide> * if both argument values are not equal <ide> */ <ide> @Throws(IllegalEqualException.class) <del> public static long notEquals(@Nonnull final long expected, @Nonnull final long check, final String message) { // NOSONAR <del> // Sonar warns about suspicious notEquals method name, as the name is intended deactivate sonar <del> <add> public static long notEquals(@Nonnull final long expected, @Nonnull final long check, final String message) { <ide> if (expected == check) { <ide> throw new IllegalEqualException(message, check); <ide> } <ide> * if both argument values are not equal <ide> */ <ide> @Throws(IllegalEqualException.class) <del> public static short notEquals(@Nonnull final short expected, @Nonnull final short check) { // NOSONAR <del> // Sonar warns about suspicious notEquals method name, as the name is intended deactivate sonar <del> <add> public static short notEquals(@Nonnull final short expected, @Nonnull final short check) { <ide> if (expected == check) { <ide> throw new IllegalEqualException(check); <ide> } <ide> * if both argument values are not equal <ide> */ <ide> @Throws(IllegalEqualException.class) <del> public static short notEquals(@Nonnull final short expected, @Nonnull final short check, final String message) { // NOSONAR <del> // Sonar warns about suspicious notEquals method name, as the name is intended deactivate sonar <del> <add> public static short notEquals(@Nonnull final short expected, @Nonnull final short check, final String message) { <ide> if (expected == check) { <ide> throw new IllegalEqualException(message, check); <ide> }
JavaScript
mit
37abbac3fc5ea3ec6391f03e52c95e3dde555731
0
panpawn/Pokemon-Showdown,panpawn/Gold-Server,Git-Worm/City-PS,panpawn/Pokemon-Showdown,panpawn/Gold-Server,panpawn/Gold-Server,Git-Worm/City-PS
/* Emoticons Plugin * This is a chat-plugin for Emoticons * You will need a line in parser to actually * parse this so that it works. (See command-parser.js) * Credits: panpawn, jd */ var fs = require('fs'); var serialize = require('node-serialize'); var emotes = {}; if (typeof Gold === 'undefined') global.Gold = {}; Gold.emoticons = { chatEmotes: {}, processEmoticons: function(text) { var patterns = [], metachars = /[[\]{}()*+?.\\|^$\-,&#\s]/g, self = this; for (var i in this.chatEmotes) { if (this.chatEmotes.hasOwnProperty(i)) { patterns.push('(' + i.replace(metachars, "\\$&") + ')'); } } return text.replace(new RegExp(patterns.join('|'), 'g'), function(match) { return typeof self.chatEmotes[match] != 'undefined' ? '<img src="' + self.chatEmotes[match] + '" title="' + match + '"/>' : match; }); }, checkEmoteModchat: function(user, room, connection) { var rank = user.getIdentity(room).substr(0,1); switch (room.emoteModChat) { case undefined: case false: return true; break; case 'ac': case 'autoconfirmed': rank = (user.autoconfirmed ? true : false); return rank; break; case '+': if (rank === '+' || rank === '%' || rank === '@' || rank === '&' || rank === '#' || rank === '~') { return true; } else { return false; } break; case '%': if (rank === '%' || rank === '@' || rank === '&' || rank === '#' || rank === '~') { return true; } else { return false; } break; case '@': if (rank === '@' || rank === '&' || rank === '#' || rank === '~') { return true; } else { return false; } break; case '&': if (rank === '&' || rank === '#' || rank === '~') { return true; } else { return false; } break; case '#': if (rank === '#' || rank === '~') { return true; } else { return false; } break; case '~': if (rank === '~') { return true; } else { return false; } break; } return false; }, processChatData: function(user, room, connection, message) { var match = false; for (var i in this.chatEmotes) { if (message.indexOf(i) >= 0) { match = true; } } switch (Users.ShadowBan.checkBanned(user) && match) { case true: origmsg = message; message = Tools.escapeHTML(message); message = this.processEmoticons(message); user.sendTo(room, '|html|' + user.getIdentity(room).substr(0,1) + '<button class="astext" name="parseCommand" value="/user ' + user.name + '">' + '<b><font color="' + Gold.hashColor(user.userid) + '">' + Tools.escapeHTML(user.name) + ':</font></b></button> ' + message + '</div>' ); room.update(); Users.ShadowBan.addMessage(user, "To " + room, origmsg); break; case false: if (!this.checkEmoteModchat(Users(user), room, connection) && room.type === 'chat' || !room.type === 'battle') { kitty = message = this.processEmoticons(message); var message = Tools.escapeHTML(kitty); return (message); return; } else if (this.checkEmoteModchat(Users(user), room, connection) || room.type === 'battle') { if (!match || message.charAt(0) === '!') return true; message = Tools.escapeHTML(message); message = this.processEmoticons(message); if (user.hiding) { room.addRaw(' <button class="astext" name="parseCommand" value="/user ' + user.name + '">' + '<b><font color="' + Gold.hashColor(user.userid) + '">' + Tools.escapeHTML(user.name) + ':</font></b></button> ' + message + '</div>'); room.update(); } room.addRaw(user.getIdentity(room).substr(0,1) + '<button class="astext" name="parseCommand" value="/user ' + user.name + '">' + '<b><font color="' + Gold.hashColor(user.userid) + '">' + Tools.escapeHTML(user.name) + ':</font></b></button> ' + message + '</div>'); room.update(); return false; } break; } }, processPMsParsing: function (message) { emoteRegex = []; for (var emote in this.chatEmotes) { emoteRegex.push(emote); } emoteRegex = new RegExp('(' + emoteRegex.join('|') + ')', 'g'); self = this; if (emoteRegex.test(message)) { message = message.replace(emoteRegex, function (match) { return '<img src=' + self.chatEmotes[match] + ' title=' + match + '>'; }); return message; } return false; } }; //commands function loadEmotes() { try { emotes = serialize.unserialize(fs.readFileSync('config/emotes.json', 'utf8')); Object.merge(Gold.emoticons.chatEmotes, emotes); } catch (e) {} } setTimeout(function(){loadEmotes();},1000); function saveEmotes() { try { fs.writeFileSync('config/emotes.json',serialize.serialize(emotes)); Object.merge(Gold.emoticons.chatEmotes, emotes); } catch (e) {} } exports.commands = { emotes: 'ezemote', temotes: 'ezemote', temote: 'ezemote', emote: 'ezemote', ec: 'ezemote', ezemote: function (target, room, user) { if (!target) target = "help"; var parts = target.split(','); for (var u in parts) parts[u] = parts[u].trim(); try { switch (toId(parts[0])) { case 'add': if (!this.can('hotpatch')) return this.sendReply("Access denied."); if (!(parts[2] || parts[3])) return this.sendReply("Usage: /emote add, [emoticon], [link]"); var emoteName = parts[1]; if (Gold.emoticons.chatEmotes[emoteName]) return this.sendReply("ERROR - the emoticon: " + emoteName + " already exists."); var link = parts.splice(2, parts.length).join(','); var fileTypes = [".gif",".png",".jpg"]; if (!~fileTypes.indexOf(link.substr(-4))) return this.sendReply("ERROR: the emoticon you are trying to add must be a gif, png, or jpg."); emotes[emoteName] = Gold.emoticons.chatEmotes[emoteName] = link; saveEmotes(); this.sendReply("The emoticon " + emoteName + " has been added."); this.logModCommand(user.name + " added the emoticon: " + emoteName); Rooms.rooms.staff.add("The emoticon " + emoteName + " was added by " + Tools.escapeHTML(user.name) + "."); room.update(); break; case 'rem': case 'remove': case 'del': case 'delete': if (!this.can('hotpatch')) return this.sendReply("Access denied."); if (!parts[1]) return this.sendReplyBox("/emote remove, [emoticon]"); emoteName = parts[1]; if (!Gold.emoticons.chatEmotes[emoteName]) return this.sendReply("ERROR - the emoticon: " + emoteName + " does not exist."); delete Gold.emoticons.chatEmotes[emoteName]; delete emotes[emoteName]; saveEmotes(); this.sendReply("The emoticon " + emoteName + " has been removed."); this.logModCommand(user.name + " removed the emoticon: " + emoteName); Rooms.rooms.staff.add("The emoticon " + emoteName + " was removed by " + Tools.escapeHTML(user.name) + "."); room.update(); break; case 'list': if (!this.canBroadcast()) return; if (this.broadcasting) return this.sendReply("ERROR: this command is too spammy to broadcast. Use / instead of ! to see it for yourself."); var output = "<b>There's a total of " + Object.size(emotes) + " emoticons added with this command:</b><br />"; for (var e in emotes) { output += e + "<br />"; } this.sendReplyBox(output); break; case 'view': if (!this.canBroadcast()) return; //if (this.broadcasting) return this.sendReply("ERROR: this command is too spammy to broadcast. Use / instead of ! to see it for yourself."); var name = Object.keys(Gold.emoticons.chatEmotes); emoticons = []; var len = name.length; while (len--) { emoticons.push((Gold.emoticons.processEmoticons(name[(name.length - 1) - len]) + '&nbsp;' + name[(name.length - 1) - len])); } this.sendReplyBox("<b><u>List of emoticons (" + Object.size(emotes) + "):</b></u> <br/><br/>" + emoticons.join(' ').toString()); break; case 'object': if (!this.canBroadcast()) return; if (this.broadcasting) return this.sendReply("ERROR: this command is too spammy to broadcast. Use / instead of ! to see it for yourself."); this.sendReplyBox("Gold.emoticons.chatEmotes = " + fs.readFileSync('config/emotes.json','utf8')); break; case 'modchat': if (!parts[1]) parts[1] = "status"; switch (parts[1]) { case 'set': if (!this.can('ban', null, room)) return this.sendReply("Access denied."); if (!parts[2]) return this.sendReply("Usage: /emote modchat, set, [rank] - Sets modchat for emoticons in the respected room."); if (!Config.groups[parts[2]] && toId(parts[2]) !== 'autoconfirmed' && toId(parts[2]) !== 'ac') return this.sendReply("ERROR: " + parts[2] + " is not a defined group in Config."); if (room.emoteModChat === parts[2]) return this.sendReply("Emoticon modchat is already enabled in this room for the rank you're trying to set it to."); room.emoteModChat = parts[2]; room.chatRoomData.emoteModChat = room.emoteModChat; Rooms.global.writeChatRoomData(); this.add("|raw|<div class=\"broadcast-red\"><b>Chat Emoticons Moderated Chat has been set!</b><br />To use emoticons in this room, you must be of rank <b>" + parts[2] + "</b> or higher."); room.update(); this.privateModCommand("(" + user.name + " has set emoticon moderated chat for rank " + parts[2] + " and up.)"); break; case 'off': case 'disable': if (!this.can('ban', null, room)) return this.sendReply("Access denied."); if (!room.emoteModChat) return this.sendReply("Emoticon modchat is already disabled in this room."); room.emoteModChat = false; room.chatRoomData.emoteModChat = room.emoteModChat; Rooms.global.writeChatRoomData(); this.add("|raw|<div class=\"broadcast-blue\"><b>Chat Emoticons Moderated Chat has been disabled!</b><br />Everyone in this room may use chat emoticons."); room.update(); this.privateModCommand("(" + user.name + " has enabled chat emoticons for everyone in this room.)"); break; default: case 'status': var status = (room.emoteModChat === undefined || !room.emoteModChat ? false : room.emoteModChat); return this.sendReply("Emoticon moderated chat is currently set to: " + status); break; } break; case 'help': default: if (!this.canBroadcast()) return; this.sendReplyBox( "<table bgcolor=\"#ADD8E6\" width=\"100%\"><td>" + "<center><b>EZ-Emoticon Commands:</b><br />" + "<i><font color=\"gray\">(By: <a href=\"https://github.com/panpawn/Pokemon-Showdown/blob/master/chat-plugins/ez-emotes.js\">panpawn</a>)</font></i></center><br />" + "/emote <code>add, [emote], [link]</code> - Adds a chat emoticon. Requires ~.<br />" + "/emote <code>remove, [emote]</code> - Removes a chat emoticon. Requires ~.<br />" + "/emote <code>modchat, set, [rank symbol / disable]</code> - Sets moderated chat for chat emoticons in the respected room to the respected rank. Requires @, #, &, ~.<br />" + "/emote <code>modchat, disable</code> - Disables moderated chat for chat emoticons (enabled by default.) Requires @, #, &, ~.<br />" + "/emote <code>modchat</code> - Views the current moderated chat status of chat emoticons.<br />" + "/emote <code>list</code> - Shows the chat emoticons in a list form.<br />" + "/emote <code>view</code> - Shows all of the current chat emoticons with the respected image.<br />" + "/emote <code>object</code> - Shows the object of Gold.emoticons.chatEmotes. (Mostly for development usage)<br />" + "/emote <code>help</code> - Shows this help command.<br />" + "</td></table>" ); } } catch (e) { try { Rooms.rooms.development.add(e.stack); } catch (e) { console.log("ERROR! The EZ-Emote script has crashed!\n" + e.stack); } } } };
chat-plugins/emoticons.js
/* Emoticons Plugin * This is a chat-plugin for Emoticons * You will need a line in parser to actually * parse this so that it works. (See command-parser.js) * Credits: panpawn, jd */ var fs = require('fs'); var path = require('path'); var serialize = require('node-serialize'); var emotes = {}; if (typeof Gold === 'undefined') global.Gold = {}; Gold.emoticons = { chatEmotes: {}, processEmoticons: function(text) { var patterns = [], metachars = /[[\]{}()*+?.\\|^$\-,&#\s]/g, self = this; for (var i in this.chatEmotes) { if (this.chatEmotes.hasOwnProperty(i)) { patterns.push('(' + i.replace(metachars, "\\$&") + ')'); } } return text.replace(new RegExp(patterns.join('|'), 'g'), function(match) { return typeof self.chatEmotes[match] != 'undefined' ? '<img src="' + self.chatEmotes[match] + '" title="' + match + '"/>' : match; }); }, processChatData: function(user, room, connection, message) { var match = false; for (var i in this.chatEmotes) { if (message.indexOf(i) >= 0) { match = true; } } switch (Users.ShadowBan.checkBanned(user) && match) { case true: origmsg = message; message = Tools.escapeHTML(message); message = this.processEmoticons(message); user.sendTo(room, '|html|' + user.getIdentity(room).substr(0,1) + '<button class="astext" name="parseCommand" value="/user ' + user.name + '">' + '<b><font color="' + Gold.hashColor(user.userid) + '">' + Tools.escapeHTML(user.name) + ':</font></b></button> ' + message + '</div>' ); room.update(); Users.ShadowBan.addMessage(user, "To " + room, origmsg); break; case false: if (!room.emoteStatus && room.type === 'chat' || !room.type === 'battle') { kitty = message = this.processEmoticons(message); var message = Tools.escapeHTML(kitty); return (message); return; } else if (room.emoteStatus || room.type === 'battle') { if (!match || message.charAt(0) === '!') return true; message = Tools.escapeHTML(message); message = this.processEmoticons(message); if (user.hiding) { room.addRaw(' <button class="astext" name="parseCommand" value="/user ' + user.name + '">' + '<b><font color="' + Gold.hashColor(user.userid) + '">' + Tools.escapeHTML(user.name) + ':</font></b></button> ' + message + '</div>'); room.update(); } room.addRaw(user.getIdentity(room).substr(0,1) + '<button class="astext" name="parseCommand" value="/user ' + user.name + '">' + '<b><font color="' + Gold.hashColor(user.userid) + '">' + Tools.escapeHTML(user.name) + ':</font></b></button> ' + message + '</div>'); room.update(); return false; } break; } }, processPMsParsing: function (message) { emoteRegex = []; for (var emote in this.chatEmotes) { emoteRegex.push(emote); } emoteRegex = new RegExp('(' + emoteRegex.join('|') + ')', 'g'); self = this; if (emoteRegex.test(message)) { message = message.replace(emoteRegex, function (match) { return '<img src=' + self.chatEmotes[match] + ' title=' + match + '>'; }); return message; } return false; } }; //commands function loadEmotes() { try { emotes = serialize.unserialize(fs.readFileSync('config/emotes.json', 'utf8')); Object.merge(Gold.emoticons.chatEmotes, emotes); } catch (e) {} } setTimeout(function(){loadEmotes();},1000); function saveEmotes() { try { fs.writeFileSync('config/emotes.json',serialize.serialize(emotes)); Object.merge(Gold.emoticons.chatEmotes, emotes); } catch (e) {} } exports.commands = { emotes: 'ezemote', temotes: 'ezemote', temote: 'ezemote', emote: 'ezemote', ec: 'ezemote', ezemote: function (target, room, user) { if (!target) target = "help"; var parts = target.split(','); for (var u in parts) parts[u] = parts[u].trim(); try { switch (toId(parts[0])) { case 'add': if (!this.can('hotpatch')) return this.sendReply("Access denied."); if (!(parts[2] || parts[3])) return this.sendReply("Usage: /ezemote add, [emoticon], [link]"); var emoteName = parts[1]; if (Gold.emoticons.chatEmotes[emoteName]) return this.sendReply("ERROR - the emoticon: " + emoteName + " already exists."); var link = parts.splice(2, parts.length).join(','); var fileTypes = [".gif",".png",".jpg"]; if (!~fileTypes.indexOf(link.substr(-4))) return this.sendReply("ERROR: the emoticon you are trying to add must be a gif, png, or jpg."); emotes[emoteName] = Gold.emoticons.chatEmotes[emoteName] = link; saveEmotes(); this.sendReply("The emoticon " + emoteName + " has been added."); this.logModCommand(user.name + " added the emoticon: " + emoteName); Rooms.rooms.staff.add("The emoticon " + emoteName + " was added by " + Tools.escapeHTML(user.name) + "."); room.update(); break; case 'rem': case 'remove': case 'del': case 'delete': if (!this.can('hotpatch')) return this.sendReply("Access denied."); if (!parts[1]) return this.sendReplyBox("/ezemote remove, [emoticon]"); emoteName = parts[1]; if (!Gold.emoticons.chatEmotes[emoteName]) return this.sendReply("ERROR - the emoticon: " + emoteName + " does not exist."); delete Gold.emoticons.chatEmotes[emoteName]; delete emotes[emoteName]; saveEmotes(); this.sendReply("The emoticon " + emoteName + " has been removed."); this.logModCommand(user.name + " removed the emoticon: " + emoteName); Rooms.rooms.staff.add("The emoticon " + emoteName + " was removed by " + Tools.escapeHTML(user.name) + "."); room.update(); break; case 'list': if (!this.canBroadcast()) return; if (this.broadcasting) return this.sendReply("ERROR: this command is too spammy to broadcast. Use / instead of ! to see it for yourself."); var output = "<b>There's a total of " + Object.size(emotes) + " emoticons added with this command:</b><br />"; for (var e in emotes) { output += e + "<br />"; } this.sendReplyBox(output); break; case 'view': if (!this.canBroadcast()) return; //if (this.broadcasting) return this.sendReply("ERROR: this command is too spammy to broadcast. Use / instead of ! to see it for yourself."); var name = Object.keys(Gold.emoticons.chatEmotes); emoticons = []; var len = name.length; while (len--) { emoticons.push((Gold.emoticons.processEmoticons(name[(name.length - 1) - len]) + '&nbsp;' + name[(name.length - 1) - len])); } this.sendReplyBox("<b><u>List of emoticons (" + Object.size(emotes) + "):</b></u> <br/><br/>" + emoticons.join(' ').toString()); break; case 'object': if (!this.canBroadcast()) return; if (this.broadcasting) return this.sendReply("ERROR: this command is too spammy to broadcast. Use / instead of ! to see it for yourself."); this.sendReplyBox("Gold.emoticons.chatEmotes = " + fs.readFileSync('config/emotes.json','utf8')); break; case 'status': if (!this.canBroadcast()) return; if (!parts[1]) { switch (room.emoteStatus) { case true: this.sendReply("Chat emoticons are currently enabled in this room."); break; case false: this.sendReply("Chat emoticons are currently disabled in this room."); break; } } else { switch (toId(parts[1])) { case 'on': case 'enable': if (!this.can('declare', null, room)) return this.sendReply("Access denied."); if (room.type === 'battle') return this.sendReply("Chat emoticons are already enabled in battle rooms by default and cannot be turned off."); if (room.emoteStatus) return this.sendReply("Chat emoticons are already enabled in this room."); room.emoteStatus = true; room.chatRoomData.emoteStatus = room.emoteStatus; Rooms.global.writeChatRoomData(); //room.add(Tools.escapeHTML(user.name) + ' has enabled chat emoticons in this room.'); this.add("|raw|<div class=\"broadcast-blue\"><b>Chat Emoticons have been enabled!</b><br />Everyone in this room may use chat emoticons."); room.update(); this.privateModCommand("(" + user.name + " has enabled chat emoticons in this room)"); break; case 'off': case 'disable': if (!this.can('declare', null, room)) return this.sendReply("Access denied."); if (room.type === 'battle') return this.sendReply("Chat emoticons are already enabled in battle rooms by default and cannot be turned off."); if (!room.emoteStatus) return this.sendReply("Chat emoticons are already disabled in this room."); room.emoteStatus = false; room.chatRoomData.emoteStatus = room.emoteStatus; Rooms.global.writeChatRoomData(); //room.add(Tools.escapeHTML(user.name) + " has disabled chat emoticons in this room."); this.add("|raw|<div class=\"broadcast-red\"><b>Chat Emoticons have been disabled!</b><br />No one in this room may use chat emoticons."); room.update(); this.privateModCommand("(" + user.name + " has disabled chat emoticons in this room)"); break; default: this.sendReply("Usage: /ezemote status, [on / off] - Enables or disables the current chat emoticon status. Requires #, &, ~."); } } break; case 'help': default: if (!this.canBroadcast()) return; this.sendReplyBox( "<table bgcolor=\"#ADD8E6\" width=\"100%\"><td>" + "<center><b>EZ-Emoticon Commands:</b><br />" + "<i><font color=\"gray\">(By: <a href=\"https://github.com/panpawn/Pokemon-Showdown/blob/master/chat-plugins/ez-emotes.js\">panpawn</a>)</font></i></center><br />" + "/ezemote <code>add, [emote], [link]</code> - Adds a chat emoticon. Requires ~.<br />" + "/ezemote <code>remove, [emote]</code> - Removes a chat emoticon. Requires ~.<br />" + "/ezemote <code>status, [on / off]</code> - Enables or disables the status of chat emoticons in the respected room. Requires #, &, ~.<br />" + "/ezemote <code>status</code> - Views the current status of chat emoticons.<br />" + "/ezemote <code>list</code> - Shows the chat emoticons in a list form.<br />" + "/ezemote <code>view</code> - Shows all of the current chat emoticons with the respected image.<br />" + "/ezemote <code>object</code> - Shows the object of Gold.emoticons.chatEmotes. (Mostly for development usage)<br />" + "/ezemote <code>help</code> - Shows this help command.<br />" + "</td></table>" ); } } catch (e) { try { Rooms.rooms.development.add(e.stack); } catch (e) { console.log("ERROR! The EZ-Emote script has crashed!\n" + e.stack); } } } };
Emoticon refactor
chat-plugins/emoticons.js
Emoticon refactor
<ide><path>hat-plugins/emoticons.js <ide> */ <ide> <ide> var fs = require('fs'); <del>var path = require('path'); <ide> var serialize = require('node-serialize'); <ide> var emotes = {}; <ide> <ide> '<img src="' + self.chatEmotes[match] + '" title="' + match + '"/>' : <ide> match; <ide> }); <add> }, <add> checkEmoteModchat: function(user, room, connection) { <add> var rank = user.getIdentity(room).substr(0,1); <add> switch (room.emoteModChat) { <add> case undefined: <add> case false: <add> return true; <add> break; <add> case 'ac': <add> case 'autoconfirmed': <add> rank = (user.autoconfirmed ? true : false); <add> return rank; <add> break; <add> case '+': <add> if (rank === '+' || rank === '%' || rank === '@' || rank === '&' || rank === '#' || rank === '~') { <add> return true; <add> } else { <add> return false; <add> } <add> break; <add> case '%': <add> if (rank === '%' || rank === '@' || rank === '&' || rank === '#' || rank === '~') { <add> return true; <add> } else { <add> return false; <add> } <add> break; <add> case '@': <add> if (rank === '@' || rank === '&' || rank === '#' || rank === '~') { <add> return true; <add> } else { <add> return false; <add> } <add> break; <add> case '&': <add> if (rank === '&' || rank === '#' || rank === '~') { <add> return true; <add> } else { <add> return false; <add> } <add> break; <add> case '#': <add> if (rank === '#' || rank === '~') { <add> return true; <add> } else { <add> return false; <add> } <add> break; <add> case '~': <add> if (rank === '~') { <add> return true; <add> } else { <add> return false; <add> } <add> break; <add> } <add> return false; <ide> }, <ide> processChatData: function(user, room, connection, message) { <ide> var match = false; <ide> Users.ShadowBan.addMessage(user, "To " + room, origmsg); <ide> break; <ide> case false: <del> if (!room.emoteStatus && room.type === 'chat' || !room.type === 'battle') { <add> if (!this.checkEmoteModchat(Users(user), room, connection) && room.type === 'chat' || !room.type === 'battle') { <ide> kitty = message = this.processEmoticons(message); <ide> var message = Tools.escapeHTML(kitty); <ide> return (message); <ide> return; <del> } else if (room.emoteStatus || room.type === 'battle') { <add> } else if (this.checkEmoteModchat(Users(user), room, connection) || room.type === 'battle') { <ide> if (!match || message.charAt(0) === '!') return true; <ide> message = Tools.escapeHTML(message); <ide> message = this.processEmoticons(message); <ide> if (!target) target = "help"; <ide> var parts = target.split(','); <ide> for (var u in parts) parts[u] = parts[u].trim(); <del> <add> <ide> try { <ide> switch (toId(parts[0])) { <ide> case 'add': <ide> if (!this.can('hotpatch')) return this.sendReply("Access denied."); <del> if (!(parts[2] || parts[3])) return this.sendReply("Usage: /ezemote add, [emoticon], [link]"); <add> if (!(parts[2] || parts[3])) return this.sendReply("Usage: /emote add, [emoticon], [link]"); <ide> var emoteName = parts[1]; <ide> if (Gold.emoticons.chatEmotes[emoteName]) return this.sendReply("ERROR - the emoticon: " + emoteName + " already exists."); <ide> var link = parts.splice(2, parts.length).join(','); <ide> case 'del': <ide> case 'delete': <ide> if (!this.can('hotpatch')) return this.sendReply("Access denied."); <del> if (!parts[1]) return this.sendReplyBox("/ezemote remove, [emoticon]"); <add> if (!parts[1]) return this.sendReplyBox("/emote remove, [emoticon]"); <ide> emoteName = parts[1]; <ide> if (!Gold.emoticons.chatEmotes[emoteName]) return this.sendReply("ERROR - the emoticon: " + emoteName + " does not exist."); <ide> delete Gold.emoticons.chatEmotes[emoteName]; <ide> if (this.broadcasting) return this.sendReply("ERROR: this command is too spammy to broadcast. Use / instead of ! to see it for yourself."); <ide> this.sendReplyBox("Gold.emoticons.chatEmotes = " + fs.readFileSync('config/emotes.json','utf8')); <ide> break; <del> case 'status': <del> if (!this.canBroadcast()) return; <del> if (!parts[1]) { <del> switch (room.emoteStatus) { <del> case true: <del> this.sendReply("Chat emoticons are currently enabled in this room."); <del> break; <del> case false: <del> this.sendReply("Chat emoticons are currently disabled in this room."); <del> break; <del> } <del> } else { <del> switch (toId(parts[1])) { <del> case 'on': <del> case 'enable': <del> if (!this.can('declare', null, room)) return this.sendReply("Access denied."); <del> if (room.type === 'battle') return this.sendReply("Chat emoticons are already enabled in battle rooms by default and cannot be turned off."); <del> if (room.emoteStatus) return this.sendReply("Chat emoticons are already enabled in this room."); <del> room.emoteStatus = true; <del> room.chatRoomData.emoteStatus = room.emoteStatus; <del> Rooms.global.writeChatRoomData(); <del> //room.add(Tools.escapeHTML(user.name) + ' has enabled chat emoticons in this room.'); <del> this.add("|raw|<div class=\"broadcast-blue\"><b>Chat Emoticons have been enabled!</b><br />Everyone in this room may use chat emoticons."); <del> room.update(); <del> this.privateModCommand("(" + user.name + " has enabled chat emoticons in this room)"); <del> break; <del> case 'off': <del> case 'disable': <del> if (!this.can('declare', null, room)) return this.sendReply("Access denied."); <del> if (room.type === 'battle') return this.sendReply("Chat emoticons are already enabled in battle rooms by default and cannot be turned off."); <del> if (!room.emoteStatus) return this.sendReply("Chat emoticons are already disabled in this room."); <del> room.emoteStatus = false; <del> room.chatRoomData.emoteStatus = room.emoteStatus; <del> Rooms.global.writeChatRoomData(); <del> //room.add(Tools.escapeHTML(user.name) + " has disabled chat emoticons in this room."); <del> this.add("|raw|<div class=\"broadcast-red\"><b>Chat Emoticons have been disabled!</b><br />No one in this room may use chat emoticons."); <del> room.update(); <del> this.privateModCommand("(" + user.name + " has disabled chat emoticons in this room)"); <del> break; <del> default: <del> this.sendReply("Usage: /ezemote status, [on / off] - Enables or disables the current chat emoticon status. Requires #, &, ~."); <del> } <del> } <del> break; <add> case 'modchat': <add> if (!parts[1]) parts[1] = "status"; <add> switch (parts[1]) { <add> case 'set': <add> if (!this.can('ban', null, room)) return this.sendReply("Access denied."); <add> if (!parts[2]) return this.sendReply("Usage: /emote modchat, set, [rank] - Sets modchat for emoticons in the respected room."); <add> if (!Config.groups[parts[2]] && toId(parts[2]) !== 'autoconfirmed' && toId(parts[2]) !== 'ac') return this.sendReply("ERROR: " + parts[2] + " is not a defined group in Config."); <add> if (room.emoteModChat === parts[2]) return this.sendReply("Emoticon modchat is already enabled in this room for the rank you're trying to set it to."); <add> room.emoteModChat = parts[2]; <add> room.chatRoomData.emoteModChat = room.emoteModChat; <add> Rooms.global.writeChatRoomData(); <add> this.add("|raw|<div class=\"broadcast-red\"><b>Chat Emoticons Moderated Chat has been set!</b><br />To use emoticons in this room, you must be of rank <b>" + parts[2] + "</b> or higher."); <add> room.update(); <add> this.privateModCommand("(" + user.name + " has set emoticon moderated chat for rank " + parts[2] + " and up.)"); <add> break; <add> case 'off': <add> case 'disable': <add> if (!this.can('ban', null, room)) return this.sendReply("Access denied."); <add> if (!room.emoteModChat) return this.sendReply("Emoticon modchat is already disabled in this room."); <add> room.emoteModChat = false; <add> room.chatRoomData.emoteModChat = room.emoteModChat; <add> Rooms.global.writeChatRoomData(); <add> this.add("|raw|<div class=\"broadcast-blue\"><b>Chat Emoticons Moderated Chat has been disabled!</b><br />Everyone in this room may use chat emoticons."); <add> room.update(); <add> this.privateModCommand("(" + user.name + " has enabled chat emoticons for everyone in this room.)"); <add> break; <add> default: <add> case 'status': <add> var status = (room.emoteModChat === undefined || !room.emoteModChat ? false : room.emoteModChat); <add> return this.sendReply("Emoticon moderated chat is currently set to: " + status); <add> break; <add> } <add> break; <ide> case 'help': <ide> default: <ide> if (!this.canBroadcast()) return; <ide> "<table bgcolor=\"#ADD8E6\" width=\"100%\"><td>" + <ide> "<center><b>EZ-Emoticon Commands:</b><br />" + <ide> "<i><font color=\"gray\">(By: <a href=\"https://github.com/panpawn/Pokemon-Showdown/blob/master/chat-plugins/ez-emotes.js\">panpawn</a>)</font></i></center><br />" + <del> "/ezemote <code>add, [emote], [link]</code> - Adds a chat emoticon. Requires ~.<br />" + <del> "/ezemote <code>remove, [emote]</code> - Removes a chat emoticon. Requires ~.<br />" + <del> "/ezemote <code>status, [on / off]</code> - Enables or disables the status of chat emoticons in the respected room. Requires #, &, ~.<br />" + <del> "/ezemote <code>status</code> - Views the current status of chat emoticons.<br />" + <del> "/ezemote <code>list</code> - Shows the chat emoticons in a list form.<br />" + <del> "/ezemote <code>view</code> - Shows all of the current chat emoticons with the respected image.<br />" + <del> "/ezemote <code>object</code> - Shows the object of Gold.emoticons.chatEmotes. (Mostly for development usage)<br />" + <del> "/ezemote <code>help</code> - Shows this help command.<br />" + <add> "/emote <code>add, [emote], [link]</code> - Adds a chat emoticon. Requires ~.<br />" + <add> "/emote <code>remove, [emote]</code> - Removes a chat emoticon. Requires ~.<br />" + <add> "/emote <code>modchat, set, [rank symbol / disable]</code> - Sets moderated chat for chat emoticons in the respected room to the respected rank. Requires @, #, &, ~.<br />" + <add> "/emote <code>modchat, disable</code> - Disables moderated chat for chat emoticons (enabled by default.) Requires @, #, &, ~.<br />" + <add> "/emote <code>modchat</code> - Views the current moderated chat status of chat emoticons.<br />" + <add> "/emote <code>list</code> - Shows the chat emoticons in a list form.<br />" + <add> "/emote <code>view</code> - Shows all of the current chat emoticons with the respected image.<br />" + <add> "/emote <code>object</code> - Shows the object of Gold.emoticons.chatEmotes. (Mostly for development usage)<br />" + <add> "/emote <code>help</code> - Shows this help command.<br />" + <ide> "</td></table>" <ide> ); <ide> }
Java
bsd-3-clause
4c603bbc583999490a08c6d181d68f719df79db4
0
NCIP/c3pr,NCIP/c3pr,NCIP/c3pr
package edu.duke.cabig.c3pr.service.impl; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import edu.duke.cabig.c3pr.constants.NotificationEventTypeEnum; import edu.duke.cabig.c3pr.rules.exception.RuleException; import edu.duke.cabig.c3pr.rules.runtime.BusinessRulesExecutionService; import edu.duke.cabig.c3pr.service.RulesDelegationService; import edu.duke.cabig.c3pr.service.ScheduledNotificationService; import edu.duke.cabig.c3pr.service.SchedulerService; public class RulesDelegationServiceImpl implements RulesDelegationService{ private static final Log log = LogFactory.getLog(RulesDelegationServiceImpl.class); public static final String NEW_STUDY_SAVED_EVENT = "NEW_STUDY_SAVED_EVENT"; public static final String NEW_STUDY_SITE_SAVED_EVENT = "NEW_STUDY_SITE_SAVED_EVENT"; public static final String STUDY_STATUS_CHANGE_EVENT = "STUDY_STATUS_CHANGE_EVENT"; public static final String STUDY_SITE_STATUS_CHANGE_EVENT = "STUDY_SITE_STATUS_CHANGE_EVENT"; public static final String REGISTRATION_EVENT = "REGISTRATION_EVENT"; private BusinessRulesExecutionService businessRulesExecutionService; private ScheduledNotificationService scheduledNotificationService; private SchedulerService schedulerService; public void activateRules(NotificationEventTypeEnum event, List<Object> objects){ log.debug(this.getClass().getName() + ": Entering activateRules()"); ArrayList <Object>objList = new ArrayList<Object>(); objList.addAll(objects); objList.add(schedulerService); objList.add(scheduledNotificationService); objList.add(event); try{ if(event != null){ businessRulesExecutionService.fireRules("edu.duke.cabig.c3pr.rules.deploy.study_status_rules", objList); } }catch(RuleException re){ log.error(re.getMessage()); } log.debug(this.getClass().getName() + ": Exiting activateRules()"); } public BusinessRulesExecutionService getBusinessRulesExecutionService() { return businessRulesExecutionService; } public void setBusinessRulesExecutionService( BusinessRulesExecutionService businessRulesExecutionService) { this.businessRulesExecutionService = businessRulesExecutionService; } public SchedulerService getSchedulerService() { return schedulerService; } public void setSchedulerService(SchedulerService schedulerService) { this.schedulerService = schedulerService; } public ScheduledNotificationService getScheduledNotificationService() { return scheduledNotificationService; } public void setScheduledNotificationService( ScheduledNotificationService scheduledNotificationService) { this.scheduledNotificationService = scheduledNotificationService; } }
codebase/projects/rules/src/java/edu/duke/cabig/c3pr/service/impl/RulesDelegationServiceImpl.java
package edu.duke.cabig.c3pr.service.impl; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import edu.duke.cabig.c3pr.constants.NotificationEventTypeEnum; import edu.duke.cabig.c3pr.rules.exception.RuleException; import edu.duke.cabig.c3pr.rules.runtime.BusinessRulesExecutionService; import edu.duke.cabig.c3pr.service.RulesDelegationService; import edu.duke.cabig.c3pr.service.ScheduledNotificationService; import edu.duke.cabig.c3pr.service.SchedulerService; public class RulesDelegationServiceImpl implements RulesDelegationService{ private static final Log log = LogFactory.getLog(RulesDelegationServiceImpl.class); public static final String NEW_STUDY_SAVED_EVENT = "NEW_STUDY_SAVED_EVENT"; public static final String NEW_STUDY_SITE_SAVED_EVENT = "NEW_STUDY_SITE_SAVED_EVENT"; public static final String STUDY_STATUS_CHANGE_EVENT = "STUDY_STATUS_CHANGE_EVENT"; public static final String STUDY_SITE_STATUS_CHANGE_EVENT = "STUDY_SITE_STATUS_CHANGE_EVENT"; public static final String REGISTRATION_EVENT = "REGISTRATION_EVENT"; private BusinessRulesExecutionService businessRulesExecutionService; private ScheduledNotificationService scheduledNotificationService; private SchedulerService schedulerService; public void activateRules(NotificationEventTypeEnum event, List<Object> objects){ log.debug(this.getClass().getName() + ": Entering activateRules()"); ArrayList <Object>objList = new ArrayList<Object>(); objList.addAll(objects); objList.add(schedulerService); objList.add(scheduledNotificationService); objList.add(event); try{ if(event.equals(NotificationEventTypeEnum.STUDY_STATUS_CHANGED_EVENT) || event.equals(NotificationEventTypeEnum.STUDY_SITE_STATUS_CHANGED_EVENT) || event.equals(NotificationEventTypeEnum.NEW_REGISTRATION_EVENT)){ businessRulesExecutionService.fireRules("edu.duke.cabig.c3pr.rules.deploy.study_status_rules", objList); } }catch(RuleException re){ log.error(re.getMessage()); } log.debug(this.getClass().getName() + ": Exiting activateRules()"); } public BusinessRulesExecutionService getBusinessRulesExecutionService() { return businessRulesExecutionService; } public void setBusinessRulesExecutionService( BusinessRulesExecutionService businessRulesExecutionService) { this.businessRulesExecutionService = businessRulesExecutionService; } public SchedulerService getSchedulerService() { return schedulerService; } public void setSchedulerService(SchedulerService schedulerService) { this.schedulerService = schedulerService; } public ScheduledNotificationService getScheduledNotificationService() { return scheduledNotificationService; } public void setScheduledNotificationService( ScheduledNotificationService scheduledNotificationService) { this.scheduledNotificationService = scheduledNotificationService; } }
CPR-73, CPR-74:Notification Use cases
codebase/projects/rules/src/java/edu/duke/cabig/c3pr/service/impl/RulesDelegationServiceImpl.java
CPR-73, CPR-74:Notification Use cases
<ide><path>odebase/projects/rules/src/java/edu/duke/cabig/c3pr/service/impl/RulesDelegationServiceImpl.java <ide> objList.add(event); <ide> <ide> try{ <del> if(event.equals(NotificationEventTypeEnum.STUDY_STATUS_CHANGED_EVENT) || <del> event.equals(NotificationEventTypeEnum.STUDY_SITE_STATUS_CHANGED_EVENT) || <del> event.equals(NotificationEventTypeEnum.NEW_REGISTRATION_EVENT)){ <add> if(event != null){ <ide> businessRulesExecutionService.fireRules("edu.duke.cabig.c3pr.rules.deploy.study_status_rules", objList); <ide> } <ide> }catch(RuleException re){
Java
apache-2.0
4b1656f1dcb5d3fc91f8698fafd5e8c596c25a73
0
parlaylabs/jitsi-videobridge,jitsi/jitsi-videobridge,jitsi/jitsi-videobridge,gpolitis/jitsi-videobridge,jitsi/jitsi-videobridge,davidertel/jitsi-videobridge,jitsi/jitsi-videobridge,parlaylabs/jitsi-videobridge,jitsi/jitsi-videobridge,jitsi/jitsi-videobridge,jitsi/jitsi-videobridge,parlaylabs/jitsi-videobridge,parlaylabs/jitsi-videobridge,gpolitis/jitsi-videobridge,matteocampana/jitsi-videobridge,davidertel/jitsi-videobridge,matteocampana/jitsi-videobridge,matteocampana/jitsi-videobridge,gpolitis/jitsi-videobridge,davidertel/jitsi-videobridge
/* * Copyright @ 2015 Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.videobridge; import java.util.*; import java.util.regex.*; import net.java.sip.communicator.impl.protocol.jabber.extensions.*; import net.java.sip.communicator.impl.protocol.jabber.extensions.colibri.*; import net.java.sip.communicator.impl.protocol.jabber.extensions.health.*; import net.java.sip.communicator.impl.protocol.jabber.extensions.jingle.*; import net.java.sip.communicator.service.shutdown.*; import net.java.sip.communicator.util.*; import org.ice4j.ice.harvest.*; import org.ice4j.stack.*; import org.jitsi.osgi.*; import org.jitsi.service.configuration.*; import org.jitsi.service.neomedia.*; import org.jitsi.util.*; import org.jitsi.util.Logger; import org.jitsi.eventadmin.*; import org.jitsi.videobridge.health.*; import org.jitsi.videobridge.pubsub.*; import org.jitsi.videobridge.xmpp.*; import org.jivesoftware.smack.packet.*; import org.jivesoftware.smack.provider.*; import org.jivesoftware.smackx.pubsub.*; import org.jivesoftware.smackx.pubsub.provider.*; import org.osgi.framework.*; /** * Represents the Jitsi Videobridge which creates, lists and destroys * {@link Conference} instances. * * @author Lyubomir Marinov * @author Hristo Terezov * @author Boris Grozev */ public class Videobridge { public static final String COLIBRI_CLASS = "colibriClass"; /** * The name of configuration property used to specify default processing * options passed as the second argument to * {@link #handleColibriConferenceIQ(ColibriConferenceIQ, int)}. */ private static final String DEFAULT_OPTIONS_PROPERTY_NAME = "org.jitsi.videobridge.defaultOptions"; /** * The XML namespace of the <tt>TransportManager</tt> type to be initialized * by <tt>Channel</tt> by default. */ private static String defaultTransportManager; /** * The name of the property which specifies the path to the directory in * which media recordings will be stored. */ static final String ENABLE_MEDIA_RECORDING_PNAME = "org.jitsi.videobridge.ENABLE_MEDIA_RECORDING"; /** * The <tt>Logger</tt> used by the <tt>Videobridge</tt> class and its * instances to print debug information. */ private static final Logger logger = Logger.getLogger(Videobridge.class); /** * The name of the property which controls whether media recording is * enabled. */ static final String MEDIA_RECORDING_PATH_PNAME = "org.jitsi.videobridge.MEDIA_RECORDING_PATH"; /** * The name of the property which specifies the token used to authenticate * requests to enable media recording. */ static final String MEDIA_RECORDING_TOKEN_PNAME = "org.jitsi.videobridge.MEDIA_RECORDING_TOKEN"; /** * The optional flag which specifies to * {@link #handleColibriConferenceIQ(ColibriConferenceIQ, int)} that * <tt>ColibriConferenceIQ</tt>s can be accessed by any peer(not only by the * focus that created the conference). */ public static final int OPTION_ALLOW_ANY_FOCUS = 2; /** * The optional flag which specifies to * {@link #handleColibriConferenceIQ(ColibriConferenceIQ, int)} that * <tt>ColibriConferenceIQ</tt>s without an associated conference focus are * allowed. */ public static final int OPTION_ALLOW_NO_FOCUS = 1; /** * The pseudo-random generator which is to be used when generating * {@link Conference} and {@link Channel} IDs in order to minimize busy * waiting for the value of {@link System#currentTimeMillis()} to change. */ public static final Random RANDOM = new Random(); /** * The REST-like HTTP/JSON API of Jitsi Videobridge. */ public static final String REST_API = "rest"; /** * The (base) <tt>System</tt> and/or <tt>ConfigurationService</tt> property * of the REST-like HTTP/JSON API of Jitsi Videobridge. */ public static final String REST_API_PNAME = "org.jitsi.videobridge." + REST_API; /** * The property that specifies allowed entities for turning on graceful * shutdown mode. For XMPP API this is "from" JID. In case of REST * the source IP is being copied into the "from" field of the IQ. */ static final String SHUTDOWN_ALLOWED_SOURCE_REGEXP_PNAME = "org.jitsi.videobridge.shutdown.ALLOWED_SOURCE_REGEXP"; /** * The property that specifies entities authorized to operate the bridge. * For XMPP API this is "from" JID. In case of REST the source IP is being * copied into the "from" field of the IQ. */ static final String AUTHORIZED_SOURCE_REGEXP_PNAME = "org.jitsi.videobridge.AUTHORIZED_SOURCE_REGEXP"; /** * The XMPP API of Jitsi Videobridge. */ public static final String XMPP_API = "xmpp"; /** * The (base) <tt>System</tt> and/or <tt>ConfigurationService</tt> property * of the XMPP API of Jitsi Videobridge. */ public static final String XMPP_API_PNAME = "org.jitsi.videobridge." + XMPP_API; public static Collection<Videobridge> getVideobridges( BundleContext bundleContext) { return ServiceUtils2.getServices(bundleContext, Videobridge.class); } /** * The pattern used to filter entities that are allowed to operate * the videobridge. */ private Pattern authorizedSourcePattern; /** * The (OSGi) <tt>BundleContext</tt> in which this <tt>Videobridge</tt> has * been started. */ private BundleContext bundleContext; /** * The <tt>Conference</tt>s of this <tt>Videobridge</tt> mapped by their * IDs. */ private final Map<String, Conference> conferences = new HashMap<>(); /** * Default options passed as second argument to * {@link #handleColibriConferenceIQ(ColibriConferenceIQ, int)} */ private int defaultProcessingOptions; /** * Indicates if this bridge instance has entered graceful shutdown mode. */ private boolean shutdownInProgress; /** * The pattern used to filter entities that are allowed to trigger graceful * shutdown mode. */ private Pattern shutdownSourcePattern; /** * Initializes a new <tt>Videobridge</tt> instance. */ public Videobridge() { new VideobridgeExpireThread(this).start(); } /** * Initializes a new {@link Conference} instance with an ID unique to the * <tt>Conference</tt> instances listed by this <tt>Videobridge</tt> and * adds the new instance to the list of existing <tt>Conference</tt> * instances. Optionally the new instance is owned by a specific conference * focus i.e. further/future requests to manage the new instance must come * from the specified <tt>focus</tt> or they will be ignored. If the focus * is not specified this safety check is overridden. * * @param focus (optional) a <tt>String</tt> which specifies the JID of * the conference focus which will own the new instance i.e. from whom * further/future requests to manage the new instance must come or they will * be ignored. Pass <tt>null</tt> to override this safety check. * @return a new <tt>Conference</tt> instance with an ID unique to the * <tt>Conference</tt> instances listed by this <tt>Videobridge</tt> */ public Conference createConference(String focus) { Conference conference = null; do { String id = generateConferenceID(); synchronized (conferences) { if (!conferences.containsKey(id)) { conference = new Conference(this, id, focus); conferences.put(id, conference); } } } while (conference == null); /* * The method Videobridge.getChannelCount() should better be executed * outside synchronized blocks in order to reduce the risks of causing * deadlocks. */ if (logger.isInfoEnabled()) { logger.info( "Created conference " + conference.getID() + ". " + getConferenceCountString()); } return conference; } /** * Enables graceful shutdown mode on this bridge instance and eventually * starts the shutdown immediately if no conferences are currently being * hosted. Otherwise bridge will shutdown once all conferences expire. */ private void enableGracefulShutdownMode() { if (!shutdownInProgress) { logger.info("Entered graceful shutdown mode"); } this.shutdownInProgress = true; maybeDoShutdown(); } /** * Expires a specific <tt>Conference</tt> of this <tt>Videobridge</tt> (i.e. * if the specified <tt>Conference</tt> is not in the list of * <tt>Conference</tt>s of this <tt>Videobridge</tt>, does nothing). * * @param conference the <tt>Conference</tt> to be expired by this * <tt>Videobridge</tt> */ public void expireConference(Conference conference) { String id = conference.getID(); boolean expireConference; synchronized (conferences) { if (conference.equals(conferences.get(id))) { conferences.remove(id); expireConference = true; } else expireConference = false; } if (expireConference) conference.expire(); // Check if it's the time to shutdown now maybeDoShutdown(); } /** * Generates a new <tt>Conference</tt> ID which is not guaranteed to be * unique. * * @return a new <tt>Conference</tt> ID which is not guaranteed to be unique */ private String generateConferenceID() { return Long.toHexString(System.currentTimeMillis() + RANDOM.nextLong()); } /** * Returns the OSGi <tt>BundleContext</tt> in which this * <tt>Videobridge</tt> is executing. * * @return the OSGi <tt>BundleContext</tt> in which this * <tt>Videobridge</tt> is executing. */ public BundleContext getBundleContext() { return bundleContext; } /** * Gets the number of active <tt>Channel</tt>s in this <tt>Videobridge</tt> * (across all active <tt>Conference</tt>s and active <tt>Content</tt>s). * * @return the number of active <tt>Channel</tt>s in this * <tt>Videobridge</tt> */ public int getChannelCount() { int channelCount = 0; for (Conference conference : getConferences()) { if (conference != null && !conference.isExpired()) { for (Content content : conference.getContents()) { if (content != null && !content.isExpired()) { channelCount += content.getChannelCount(); } } } } return channelCount; } /** * Gets the <tt>ComponentImpl</tt> instances which implement the XMPP API of * this <tt>Videobridge</tt>. * * @return the <tt>ComponentImpl</tt> instances which implement the XMPP API * of this <tt>Videobridge</tt> */ public Collection<ComponentImpl> getComponents() { return ComponentImpl.getComponents(getBundleContext()); } /** * Gets an existing {@link Conference} with a specific ID and a specific * conference focus. * * @param id the ID of the existing <tt>Conference</tt> to get * @param focus (optional) the JID of the conference focus of the existing * <tt>Conference</tt> to get. A <tt>Conference</tt> does not take orders * from a (remote) entity other than the conference focus who has * initialized it. Pass <tt>null</tt> if you want any participant to be able * to modify the conference. * @return an existing <tt>Conference</tt> with the specified ID and the * specified conference focus or <tt>null</tt> if no <tt>Conference</tt> * with the specified ID and the specified conference focus is known to this * <tt>Videobridge</tt> */ public Conference getConference(String id, String focus) { Conference conference; synchronized (conferences) { conference = conferences.get(id); } if (conference != null) { /* * (Optional) A conference is owned by the focus who has initialized * it and it may be managed by that focus only. */ String conferenceFocus = conference.getFocus(); // If no 'focus' was given as an argument or if conference is not // owned by any 'conferenceFocus' then skip equals() if (focus == null || conferenceFocus == null || focus.equals(conferenceFocus)) { // It seems the conference is still active. conference.touch(); } else { conference = null; } } return conference; } /** * Gets the number of <tt>Conference</tt>s of this <tt>Videobridge</tt> that * are not expired. * * @return the number of <tt>Conference</tt>s of this <tt>Videobridge</tt> * that are not expired. */ public int getConferenceCount() { int sz = 0; Conference[] cs = getConferences(); if (cs != null && cs.length != 0) { for (Conference c : cs) { if (c != null && !c.isExpired()) { sz++; } } } return sz; } /** * Gets the <tt>Conference</tt>s of this <tt>Videobridge</tt>. * * @return the <tt>Conference</tt>s of this <tt>Videobridge</tt> */ public Conference[] getConferences() { synchronized (conferences) { Collection<Conference> values = conferences.values(); return values.toArray(new Conference[values.size()]); } } /** * Returns the <tt>ConfigurationService</tt> used by this * <tt>Videobridge</tt>. * * @return the <tt>ConfigurationService</tt> used by this * <tt>Videobridge</tt>. */ public ConfigurationService getConfigurationService() { BundleContext bundleContext = getBundleContext(); if (bundleContext == null) { return null; } else { return ServiceUtils2.getService( bundleContext, ConfigurationService.class); } } /** * Gets the XML namespace of the <tt>TransportManager</tt> type to be * initialized by <tt>Channel</tt> by default. * * @return the XML namespace of the <tt>TransportManager</tt> type to be * initialized by <tt>Channel</tt> by default */ public String getDefaultTransportManager() { synchronized (Videobridge.class) { if (defaultTransportManager == null) { BundleContext bundleContext = getBundleContext(); if (bundleContext != null) { ConfigurationService cfg = ServiceUtils2.getService( bundleContext, ConfigurationService.class); if (cfg != null) { defaultTransportManager = cfg.getString( Videobridge.class.getName() + ".defaultTransportManager"); } } if (!IceUdpTransportPacketExtension.NAMESPACE.equals( defaultTransportManager) && !RawUdpTransportPacketExtension.NAMESPACE.equals( defaultTransportManager)) { defaultTransportManager = IceUdpTransportPacketExtension.NAMESPACE; } } return defaultTransportManager; } } /** * Returns the <tt>LoggingService</tt> used by this * <tt>Videobridge</tt>. * * @return the <tt>LoggingService</tt> used by this * <tt>Videobridge</tt>. */ public EventAdmin getEventAdmin() { BundleContext bundleContext = getBundleContext(); if (bundleContext == null) return null; else return ServiceUtils2.getService(bundleContext, EventAdmin.class); } /** * Handles a <tt>ColibriConferenceIQ</tt> stanza which represents a request. * * @param conferenceIQ the <tt>ColibriConferenceIQ</tt> stanza represents * the request to handle * @return an <tt>org.jivesoftware.smack.packet.IQ</tt> stanza which * represents the response to the specified request or <tt>null</tt> to * reply with <tt>feature-not-implemented</tt> * @throws Exception to reply with <tt>internal-server-error</tt> to the * specified request */ public IQ handleColibriConferenceIQ(ColibriConferenceIQ conferenceIQ) throws Exception { return handleColibriConferenceIQ(conferenceIQ, defaultProcessingOptions); } /** * Handles a <tt>ColibriConferenceIQ</tt> stanza which represents a request. * * @param conferenceIQ the <tt>ColibriConferenceIQ</tt> stanza represents * the request to handle * @param options * @return an <tt>org.jivesoftware.smack.packet.IQ</tt> stanza which * represents the response to the specified request or <tt>null</tt> to * reply with <tt>feature-not-implemented</tt> * @throws Exception to reply with <tt>internal-server-error</tt> to the * specified request */ public IQ handleColibriConferenceIQ( ColibriConferenceIQ conferenceIQ, int options) throws Exception { String focus = conferenceIQ.getFrom(); Conference conference; if ((options & OPTION_ALLOW_ANY_FOCUS) > 0) { // Act like the focus was not provided at all options |= OPTION_ALLOW_NO_FOCUS; focus = null; } if (focus == null && (options & OPTION_ALLOW_NO_FOCUS) == 0) { return IQ.createErrorResponse( conferenceIQ, new XMPPError(XMPPError.Condition.not_authorized)); } else if (authorizedSourcePattern != null && (focus == null || !authorizedSourcePattern.matcher(focus).matches())) { return IQ.createErrorResponse( conferenceIQ, new XMPPError(XMPPError.Condition.not_authorized)); } else { /* * The presence of the id attribute in the conference element * signals whether a new conference is to be created or an existing * conference is to be modified. */ String id = conferenceIQ.getID(); if (id == null) { if (!isShutdownInProgress()) { conference = createConference(focus); } else { return ColibriConferenceIQ .createGracefulShutdownErrorResponse(conferenceIQ); } } else { conference = getConference(id, focus); } if (conference != null) conference.setLastKnownFocus(conferenceIQ.getFrom()); } ColibriConferenceIQ responseConferenceIQ; if (conference == null) { /* * Possible reasons for having no Conference instance include * failure to produce an ID which identifies an existing Conference * instance or the JID of a conference focus which owns an existing * Conference instance with a valid ID. */ responseConferenceIQ = null; } else { String name = conferenceIQ.getName(); if (name != null) conference.setName(name); responseConferenceIQ = new ColibriConferenceIQ(); conference.describeShallow(responseConferenceIQ); responseConferenceIQ.setGracefulShutdown(isShutdownInProgress()); ColibriConferenceIQ.Recording recordingIQ = conferenceIQ.getRecording(); if (recordingIQ != null) { String tokenIQ = recordingIQ.getToken(); if (tokenIQ != null) { String tokenConfig = getConfigurationService().getString( Videobridge.MEDIA_RECORDING_TOKEN_PNAME); if (tokenIQ.equals(tokenConfig)) { ColibriConferenceIQ.Recording.State recState = recordingIQ.getState(); boolean recording = conference.setRecording( ColibriConferenceIQ.Recording.State.ON .equals(recState) || ColibriConferenceIQ.Recording.State .PENDING.equals(recState)); ColibriConferenceIQ.Recording responseRecordingIq = new ColibriConferenceIQ.Recording(recState); if (recording) { responseRecordingIq.setDirectory( conference.getRecordingDirectory()); } responseConferenceIQ.setRecording(responseRecordingIq); } } } // TODO(gp) Remove ColibriConferenceIQ.RTCPTerminationStrategy for (ColibriConferenceIQ.Content contentIQ : conferenceIQ.getContents()) { /* * The content element springs into existence whenever it gets * mentioned, it does not need explicit creation (in contrast to * the conference and channel elements). */ Content content = conference.getOrCreateContent(contentIQ.getName()); if (content == null) { responseConferenceIQ = null; } else { ColibriConferenceIQ.Content responseContentIQ = new ColibriConferenceIQ.Content(content.getName()); responseConferenceIQ.addContent(responseContentIQ); for (ColibriConferenceIQ.Channel channelIQ : contentIQ.getChannels()) { String channelID = channelIQ.getID(); int channelExpire = channelIQ.getExpire(); String channelBundleId = channelIQ.getChannelBundleId(); RtpChannel channel = null; boolean channelCreated = false; String transportNamespace = channelIQ.getTransport() != null ? channelIQ.getTransport().getNamespace() : null; /* * The presence of the id attribute in the channel * element signals whether a new channel is to be * created or an existing channel is to be modified. */ if (channelID == null) { /* * An expire attribute in the channel element with * value equal to zero requests the immediate * expiration of the channel in question. * Consequently, it does not make sense to have it * in a channel allocation request. */ if (channelExpire != 0) { channel = content.createRtpChannel( channelBundleId, transportNamespace, channelIQ.isInitiator(), channelIQ.getRTPLevelRelayType()); if (channel instanceof VideoChannel) { VideoChannel videoChannel = (VideoChannel)channel; Integer receiveSimulcastLayer = channelIQ.getReceivingSimulcastLayer(); videoChannel.setReceiveSimulcastLayer( receiveSimulcastLayer); } channelCreated = true; } } else { channel = (RtpChannel) content.getChannel(channelID); } if (channel == null) { responseConferenceIQ = null; } else { if (channelExpire != ColibriConferenceIQ.Channel .EXPIRE_NOT_SPECIFIED) { channel.setExpire(channelExpire); /* * If the request indicates that it wants * the channel expired and the channel is * indeed expired, then the request is valid * and has correctly been acted upon. */ if ((channelExpire == 0) && channel.isExpired()) continue; } // endpoint // The attribute endpoint is optional. If a value is // not specified, then the Channel endpoint is to // not be changed. String endpoint = channelIQ.getEndpoint(); if (endpoint != null) channel.setEndpoint(endpoint); /* * The attribute last-n is optional. If a value is * not specified, then the Channel lastN is to not * be changed. */ Integer lastN = channelIQ.getLastN(); if (lastN != null) channel.setLastN(lastN); Boolean adaptiveLastN = channelIQ.getAdaptiveLastN(); if (adaptiveLastN != null) channel.setAdaptiveLastN(adaptiveLastN); Boolean adaptiveSimulcast = channelIQ.getAdaptiveSimulcast(); if (adaptiveSimulcast != null) channel.setAdaptiveSimulcast(adaptiveSimulcast); /* * XXX The attribute initiator is optional. If a * value is not specified, then the Channel * initiator is to be assumed default or to not be * changed. */ Boolean initiator = channelIQ.isInitiator(); if (initiator != null) channel.setInitiator(initiator); channel.setPayloadTypes( channelIQ.getPayloadTypes()); channel.setRtpHeaderExtensions( channelIQ.getRtpHeaderExtensions()); channel.setDirection(channelIQ.getDirection()); channel.setSources(channelIQ.getSources()); channel.setSourceGroups( channelIQ.getSourceGroups()); if (channel instanceof VideoChannel) { SimulcastMode simulcastMode = channelIQ.getSimulcastMode(); if (simulcastMode != null) { ((VideoChannel)channel) .setSimulcastMode(simulcastMode); } } if (channelBundleId != null) { TransportManager transportManager = conference.getTransportManager( channelBundleId, true); transportManager.addChannel(channel); } channel.setTransport(channelIQ.getTransport()); /* * Provide (a description of) the current state of * the channel as part of the response. */ ColibriConferenceIQ.Channel responseChannelIQ = new ColibriConferenceIQ.Channel(); channel.describe(responseChannelIQ); responseContentIQ.addChannel(responseChannelIQ); EventAdmin eventAdmin; if (channelCreated && (eventAdmin = getEventAdmin()) != null) { eventAdmin.sendEvent( EventFactory.channelCreated(channel)); } // XXX we might want to fire more precise events, // like sourceGroupsChanged or PayloadTypesChanged, // etc. content.fireChannelChanged(channel); } if (responseConferenceIQ == null) break; } for (ColibriConferenceIQ.SctpConnection sctpConnIq : contentIQ.getSctpConnections()) { String id = sctpConnIq.getID(); String endpointID = sctpConnIq.getEndpoint(); SctpConnection sctpConn; int expire = sctpConnIq.getExpire(); String channelBundleId = sctpConnIq.getChannelBundleId(); // No ID means SCTP connection is to either be created // or focus uses endpoint identity. if (id == null) { // FIXME The method // Content.getSctpConnection(Endpoint) is annotated // as deprecated but SctpConnection identification // by Endpoint (ID) is to continue to be supported // for legacy purposes. Endpoint endpoint = (endpointID == null) ? null : conference.getOrCreateEndpoint( endpointID); sctpConn = content.getSctpConnection(endpoint); if (sctpConn == null) { // Expire an expired/non-existing SCTP // connection. if (expire == 0) continue; int sctpPort = sctpConnIq.getPort(); sctpConn = content.createSctpConnection( endpoint, sctpPort, channelBundleId, sctpConnIq.isInitiator()); } } else { sctpConn = content.getSctpConnection(id); // Expire an expired/non-existing SCTP connection. if (sctpConn == null && expire == 0) continue; // endpoint if (endpointID != null) sctpConn.setEndpoint(endpointID); } // expire if (expire != ColibriConferenceIQ.Channel .EXPIRE_NOT_SPECIFIED) { sctpConn.setExpire(expire); } // Check if SCTP connection has expired. if (sctpConn.isExpired()) continue; // initiator Boolean initiator = sctpConnIq.isInitiator(); if (initiator != null) sctpConn.setInitiator(initiator); // transport sctpConn.setTransport(sctpConnIq.getTransport()); if (channelBundleId != null) { TransportManager transportManager = conference.getTransportManager( channelBundleId, true); transportManager.addChannel(sctpConn); } // response ColibriConferenceIQ.SctpConnection responseSctpIq = new ColibriConferenceIQ.SctpConnection(); sctpConn.describe(responseSctpIq); responseContentIQ.addSctpConnection(responseSctpIq); } } if (responseConferenceIQ == null) break; } for (ColibriConferenceIQ.ChannelBundle channelBundleIq : conferenceIQ.getChannelBundles()) { TransportManager transportManager = conference.getTransportManager(channelBundleIq.getId()); IceUdpTransportPacketExtension transportIq = channelBundleIq.getTransport(); if (transportManager != null && transportIq != null) { transportManager.startConnectivityEstablishment( transportIq); } } } // Update the endpoint information of Videobridge with the endpoint // information of the IQ. if (conference != null) { for (ColibriConferenceIQ.Endpoint colibriEndpoint : conferenceIQ.getEndpoints()) { conference.updateEndpoint(colibriEndpoint); } if (responseConferenceIQ != null) conference.describeChannelBundles(responseConferenceIQ); } if (responseConferenceIQ != null) { responseConferenceIQ.setType( org.jivesoftware.smack.packet.IQ.Type.RESULT); } return responseConferenceIQ; } /** * Handles <tt>HealthCheckIQ</tt> by performing health check on this * <tt>Videobridge</tt> instance. * * @param healthCheckIQ the <tt>HealthCheckIQ</tt> to be handled. * @return IQ with &quot;result&quot; type if the health check succeeded or * IQ with &quot;error&quot; type if something went wrong. * {@link XMPPError.Condition#interna_server_error} is returned when the * health check fails or {@link XMPPError.Condition#not_authorized} if the * request comes from a JID that is not authorized to do health checks on * this instance. */ public IQ handleHealthCheckIQ(HealthCheckIQ healthCheckIQ) { if (authorizedSourcePattern != null && !authorizedSourcePattern .matcher(healthCheckIQ.getFrom()) .matches()) { return IQ.createErrorResponse( healthCheckIQ, new XMPPError(XMPPError.Condition.not_authorized)); } try { Health.check(this); return IQ.createResultIQ(healthCheckIQ); } catch (Exception e) { return IQ.createErrorResponse( healthCheckIQ, new XMPPError( XMPPError.Condition.interna_server_error, e.getMessage())); } } /** * Handles a <tt>GracefulShutdownIQ</tt> stanza which represents a request. * * @param shutdownIQ the <tt>GracefulShutdownIQ</tt> stanza represents * the request to handle * @return an <tt>IQ</tt> stanza which represents the response to * the specified request or <tt>null</tt> to reply with * <tt>feature-not-implemented</tt> */ public IQ handleShutdownIQ(ShutdownIQ shutdownIQ) { // Security not configured - service unavailable if (shutdownSourcePattern == null) { return IQ.createErrorResponse( shutdownIQ, new XMPPError(XMPPError.Condition.service_unavailable)); } // Check if source matches pattern String from = shutdownIQ.getFrom(); if (from != null && shutdownSourcePattern.matcher(from).matches()) { logger.info("Accepted shutdown request from: " + from); if (shutdownIQ.isGracefulShutdown()) { if (!isShutdownInProgress()) { enableGracefulShutdownMode(); } } else { new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(1000); logger.warn("JVB force shutdown - now"); System.exit(0); } catch (InterruptedException e) { throw new RuntimeException(e); } } }, "ForceShutdownThread").start(); } return IQ.createResultIQ(shutdownIQ); } else { // Unauthorized logger.error("Rejected shutdown request from: " + from); return IQ.createErrorResponse( shutdownIQ, new XMPPError(XMPPError.Condition.not_authorized)); } } public void handleIQResponse(org.jivesoftware.smack.packet.IQ response) throws Exception { PubSubPublisher.handleIQResponse(response); } /** * Returns {@code true} if this instance has entered graceful shutdown mode. * * @return {@code true} if this instance has entered graceful shutdown mode; * otherwise, {@code false} */ public boolean isShutdownInProgress() { return shutdownInProgress; } /** * Returns {@code true} if XMPP API has been enabled. * * @return {@code true} if XMPP API has been enabled; otherwise, * {@code false} */ public boolean isXmppApiEnabled() { ConfigurationService config = ServiceUtils.getService( getBundleContext(), ConfigurationService.class); return config.getBoolean(Videobridge.XMPP_API_PNAME, false); } /** * Triggers the shutdown given that we're in graceful shutdown mode and * there are no conferences currently in progress. */ private void maybeDoShutdown() { if (!shutdownInProgress) return; synchronized (conferences) { if (conferences.isEmpty()) { ShutdownService shutdownService = ServiceUtils.getService( bundleContext, ShutdownService.class); logger.info("Videobridge is shutting down NOW"); shutdownService.beginShutdown(); } } } /** * Configures regular expression used to filter users authorized to manage * conferences and trigger graceful shutdown(if separate pattern has not * been configured). * @param authorizedSourceRegExp regular expression string */ public void setAuthorizedSourceRegExp(String authorizedSourceRegExp) { if (!StringUtils.isNullOrEmpty(authorizedSourceRegExp)) { authorizedSourcePattern = Pattern.compile(authorizedSourceRegExp); // If no shutdown regexp, then authorized sources are also allowed // to trigger graceful shutdown. if (shutdownSourcePattern == null) { shutdownSourcePattern = authorizedSourcePattern; } } // Turn off else { if (shutdownSourcePattern == authorizedSourcePattern) { shutdownSourcePattern = null; } authorizedSourcePattern = null; } } /** * Starts this <tt>Videobridge</tt> in a specific <tt>BundleContext</tt>. * * @param bundleContext the <tt>BundleContext</tt> in which this * <tt>Videobridge</tt> is to start */ void start(final BundleContext bundleContext) throws Exception { ConfigurationService cfg = ServiceUtils2.getService( bundleContext, ConfigurationService.class); this.defaultProcessingOptions = (cfg == null) ? 0 : cfg.getInt(DEFAULT_OPTIONS_PROPERTY_NAME, 0); if (logger.isDebugEnabled()) { logger.debug( "Default videobridge processing options: 0x" + Integer.toHexString(defaultProcessingOptions)); } String shutdownSourcesRegexp = (cfg == null) ? null : cfg.getString(SHUTDOWN_ALLOWED_SOURCE_REGEXP_PNAME); if (!StringUtils.isNullOrEmpty(shutdownSourcesRegexp)) { try { shutdownSourcePattern = Pattern.compile(shutdownSourcesRegexp); } catch (PatternSyntaxException exc) { logger.error( "Error parsing enableGracefulShutdownMode sources reg expr: " + shutdownSourcesRegexp, exc); } } String authorizedSourceRegexp = (cfg == null) ? null : cfg.getString(AUTHORIZED_SOURCE_REGEXP_PNAME); if (!StringUtils.isNullOrEmpty(authorizedSourceRegexp)) { try { logger.info( "Authorized source regexp: " + authorizedSourceRegexp); setAuthorizedSourceRegExp(authorizedSourceRegexp); } catch (PatternSyntaxException exc) { logger.error( "Error parsing authorized sources reg expr: " + shutdownSourcesRegexp, exc); } } ProviderManager providerManager = ProviderManager.getInstance(); // <conference> providerManager.addIQProvider( ColibriConferenceIQ.ELEMENT_NAME, ColibriConferenceIQ.NAMESPACE, new ColibriIQProvider()); // ICE-UDP <transport> providerManager.addExtensionProvider( IceUdpTransportPacketExtension.ELEMENT_NAME, IceUdpTransportPacketExtension.NAMESPACE, new DefaultPacketExtensionProvider<>( IceUdpTransportPacketExtension.class)); // Raw UDP <transport> providerManager.addExtensionProvider( RawUdpTransportPacketExtension.ELEMENT_NAME, RawUdpTransportPacketExtension.NAMESPACE, new DefaultPacketExtensionProvider<>( RawUdpTransportPacketExtension.class)); PacketExtensionProvider candidatePacketExtensionProvider = new DefaultPacketExtensionProvider<>( CandidatePacketExtension.class); // ICE-UDP <candidate> providerManager.addExtensionProvider( CandidatePacketExtension.ELEMENT_NAME, IceUdpTransportPacketExtension.NAMESPACE, candidatePacketExtensionProvider); // Raw UDP <candidate> providerManager.addExtensionProvider( CandidatePacketExtension.ELEMENT_NAME, RawUdpTransportPacketExtension.NAMESPACE, candidatePacketExtensionProvider); providerManager.addExtensionProvider( RtcpmuxPacketExtension.ELEMENT_NAME, IceUdpTransportPacketExtension.NAMESPACE, new DefaultPacketExtensionProvider<>( RtcpmuxPacketExtension.class)); // DTLS-SRTP <fingerprint> providerManager.addExtensionProvider( DtlsFingerprintPacketExtension.ELEMENT_NAME, DtlsFingerprintPacketExtension.NAMESPACE, new DefaultPacketExtensionProvider<>( DtlsFingerprintPacketExtension.class)); // PubSub providerManager.addIQProvider( PubSubElementType.PUBLISH.getElementName(), PubSubElementType.PUBLISH.getNamespace().getXmlns(), new PubSubProvider()); // Health-check providerManager.addIQProvider( HealthCheckIQ.ELEMENT_NAME, HealthCheckIQ.NAMESPACE, new HealthCheckIQProvider()); this.bundleContext = bundleContext; startIce4j(bundleContext, cfg); } /** * Implements the ice4j-related portion of {@link #start(BundleContext)}. * * @param bundleContext the {@code BundleContext} in which this * {@code Videobridge} is to start * @param cfg the {@code ConfigurationService} registered in * {@code bundleContext}. Explicitly provided for the sake of performance. */ private void startIce4j( BundleContext bundleContext, ConfigurationService cfg) { // TODO Packet logging for ice4j is not supported at this time. StunStack.setPacketLogger(null); // Make all ice4j properties system properties. if (cfg != null) { List<String> ice4jPropertyNames = cfg.getPropertyNamesByPrefix("org.ice4j.", false); if (ice4jPropertyNames != null && !ice4jPropertyNames.isEmpty()) { for (String propertyName : ice4jPropertyNames) { String propertyValue = cfg.getString(propertyName); // we expect the getString to return either null or a // non-empty String object. if (propertyValue != null) System.setProperty(propertyName, propertyValue); } } } // Initialize the the host candidate interface filters in the ice4j // stack. try { HostCandidateHarvester.initializeInterfaceFilters(); } catch (Exception e) { logger.warn( "There were errors during host candidate interface filters" + " initialization.", e); } // CandidateHarvesters may take (non-trivial) time to initialize so // initialize them as soon as possible, don't wait to initialize them // after a Channel is requested. IceUdpTransportManager.initializeStaticHarvesters(cfg); } /** * Stops this <tt>Videobridge</tt> in a specific <tt>BundleContext</tt>. * * @param bundleContext the <tt>BundleContext</tt> in which this * <tt>Videobridge</tt> is to stop */ void stop(BundleContext bundleContext) throws Exception { this.bundleContext = null; } /** * Returns an array that contains the total number of conferences (at index * 0), channels (at index 1) and video streams (at index 2). * * The "video streams" count is an estimation of the total number of * video streams received or sent. It may not be exactly accurate, because * we assume, for example, that all endpoints are sending video. It is a * better representation of the level of usage of the bridge than simply * the number of channels, because it takes into account the size of each * conference. * * We return these three together to avoid looping through all conferences * multiple times when all three values are needed. * * @return an array that contains the total number of * conferences (at index 0), channels (at index 1) and video streams (at * index 2). */ public int[] getConferenceChannelAndStreamCount() { Conference[] conferences = getConferences(); int conferenceCount = 0, channelCount = 0, streamCount = 0; if (conferences != null && conferences.length != 0) { for (Conference conference : conferences) { if (conference != null && !conference.isExpired()) { conferenceCount++; for (Content content : conference.getContents()) { if (content != null && !content.isExpired()) { int contentChannelCount = content.getChannelCount(); channelCount += contentChannelCount; if (MediaType.VIDEO.equals(content.getMediaType())) { streamCount += getContentStreamCount( content, contentChannelCount); } } } } } } return new int[]{conferenceCount, channelCount, streamCount}; } /** * Returns a short string that contains the total number of * conferences/channels/video streams, for the purposes of logging. * * @return a short string that contains the total number of * conferences/channels/video streams, for the purposes of logging. */ String getConferenceCountString() { int[] metrics = getConferenceChannelAndStreamCount(); StringBuilder sb = new StringBuilder("The total number of conferences is now "); sb.append(metrics[0]).append(", channels ").append(metrics[1]); sb.append(", video streams ").append(metrics[2]).append("."); return sb.toString(); } /** * Gets the number of video streams for a given <tt>Content</tt>. See the * documentation for {@link #getConferenceCountString()}. * * @param content the content. * @param contentChannelCount the number of channels in the content. * @return the number of video streams for a given <tt>Content</tt>. See the * documentation for {@link #getConferenceCountString()}. */ private int getContentStreamCount(Content content, int contentChannelCount) { Channel[] channels = content.getChannels(); int contentStreamCount = 0; if (channels != null && channels.length != 0) { for (Channel channel : channels) { if (channel != null && !channel.isExpired() && channel instanceof VideoChannel) { VideoChannel videoChannel = (VideoChannel) channel; int channelStreams = 1; //assume we're receiving a stream int lastN = videoChannel.getLastN(); channelStreams += lastN == -1 ? contentChannelCount - 1 : Math.min(lastN, contentChannelCount - 1); contentStreamCount += channelStreams; } } } return contentStreamCount; } }
src/main/java/org/jitsi/videobridge/Videobridge.java
/* * Copyright @ 2015 Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.videobridge; import java.util.*; import java.util.regex.*; import net.java.sip.communicator.impl.protocol.jabber.extensions.*; import net.java.sip.communicator.impl.protocol.jabber.extensions.colibri.*; import net.java.sip.communicator.impl.protocol.jabber.extensions.health.*; import net.java.sip.communicator.impl.protocol.jabber.extensions.jingle.*; import net.java.sip.communicator.service.shutdown.*; import net.java.sip.communicator.util.*; import org.ice4j.ice.harvest.*; import org.ice4j.stack.*; import org.jitsi.osgi.*; import org.jitsi.service.configuration.*; import org.jitsi.service.neomedia.*; import org.jitsi.util.*; import org.jitsi.util.Logger; import org.jitsi.eventadmin.*; import org.jitsi.videobridge.health.*; import org.jitsi.videobridge.pubsub.*; import org.jitsi.videobridge.xmpp.*; import org.jivesoftware.smack.packet.*; import org.jivesoftware.smack.provider.*; import org.jivesoftware.smackx.pubsub.*; import org.jivesoftware.smackx.pubsub.provider.*; import org.osgi.framework.*; /** * Represents the Jitsi Videobridge which creates, lists and destroys * {@link Conference} instances. * * @author Lyubomir Marinov * @author Hristo Terezov * @author Boris Grozev */ public class Videobridge { public static final String COLIBRI_CLASS = "colibriClass"; /** * The name of configuration property used to specify default processing * options passed as the second argument to * {@link #handleColibriConferenceIQ(ColibriConferenceIQ, int)}. */ private static final String DEFAULT_OPTIONS_PROPERTY_NAME = "org.jitsi.videobridge.defaultOptions"; /** * The XML namespace of the <tt>TransportManager</tt> type to be initialized * by <tt>Channel</tt> by default. */ private static String defaultTransportManager; /** * The name of the property which specifies the path to the directory in * which media recordings will be stored. */ static final String ENABLE_MEDIA_RECORDING_PNAME = "org.jitsi.videobridge.ENABLE_MEDIA_RECORDING"; /** * The <tt>Logger</tt> used by the <tt>Videobridge</tt> class and its * instances to print debug information. */ private static final Logger logger = Logger.getLogger(Videobridge.class); /** * The name of the property which controls whether media recording is * enabled. */ static final String MEDIA_RECORDING_PATH_PNAME = "org.jitsi.videobridge.MEDIA_RECORDING_PATH"; /** * The name of the property which specifies the token used to authenticate * requests to enable media recording. */ static final String MEDIA_RECORDING_TOKEN_PNAME = "org.jitsi.videobridge.MEDIA_RECORDING_TOKEN"; /** * The optional flag which specifies to * {@link #handleColibriConferenceIQ(ColibriConferenceIQ, int)} that * <tt>ColibriConferenceIQ</tt>s can be accessed by any peer(not only by the * focus that created the conference). */ public static final int OPTION_ALLOW_ANY_FOCUS = 2; /** * The optional flag which specifies to * {@link #handleColibriConferenceIQ(ColibriConferenceIQ, int)} that * <tt>ColibriConferenceIQ</tt>s without an associated conference focus are * allowed. */ public static final int OPTION_ALLOW_NO_FOCUS = 1; /** * The pseudo-random generator which is to be used when generating * {@link Conference} and {@link Channel} IDs in order to minimize busy * waiting for the value of {@link System#currentTimeMillis()} to change. */ public static final Random RANDOM = new Random(); /** * The REST-like HTTP/JSON API of Jitsi Videobridge. */ public static final String REST_API = "rest"; /** * The (base) <tt>System</tt> and/or <tt>ConfigurationService</tt> property * of the REST-like HTTP/JSON API of Jitsi Videobridge. */ public static final String REST_API_PNAME = "org.jitsi.videobridge." + REST_API; /** * The property that specifies allowed entities for turning on graceful * shutdown mode. For XMPP API this is "from" JID. In case of REST * the source IP is being copied into the "from" field of the IQ. */ static final String SHUTDOWN_ALLOWED_SOURCE_REGEXP_PNAME = "org.jitsi.videobridge.shutdown.ALLOWED_SOURCE_REGEXP"; /** * The property that specifies entities authorized to operate the bridge. * For XMPP API this is "from" JID. In case of REST the source IP is being * copied into the "from" field of the IQ. */ static final String AUTHORIZED_SOURCE_REGEXP_PNAME = "org.jitsi.videobridge.AUTHORIZED_SOURCE_REGEXP"; /** * The XMPP API of Jitsi Videobridge. */ public static final String XMPP_API = "xmpp"; /** * The (base) <tt>System</tt> and/or <tt>ConfigurationService</tt> property * of the XMPP API of Jitsi Videobridge. */ public static final String XMPP_API_PNAME = "org.jitsi.videobridge." + XMPP_API; public static Collection<Videobridge> getVideobridges( BundleContext bundleContext) { return ServiceUtils2.getServices(bundleContext, Videobridge.class); } /** * The pattern used to filter entities that are allowed to operate * the videobridge. */ private Pattern authorizedSourcePattern; /** * The (OSGi) <tt>BundleContext</tt> in which this <tt>Videobridge</tt> has * been started. */ private BundleContext bundleContext; /** * The <tt>Conference</tt>s of this <tt>Videobridge</tt> mapped by their * IDs. */ private final Map<String, Conference> conferences = new HashMap<>(); /** * Default options passed as second argument to * {@link #handleColibriConferenceIQ(ColibriConferenceIQ, int)} */ private int defaultProcessingOptions; /** * Indicates if this bridge instance has entered graceful shutdown mode. */ private boolean shutdownInProgress; /** * The pattern used to filter entities that are allowed to trigger graceful * shutdown mode. */ private Pattern shutdownSourcePattern; /** * Initializes a new <tt>Videobridge</tt> instance. */ public Videobridge() { new VideobridgeExpireThread(this).start(); } /** * Initializes a new {@link Conference} instance with an ID unique to the * <tt>Conference</tt> instances listed by this <tt>Videobridge</tt> and * adds the new instance to the list of existing <tt>Conference</tt> * instances. Optionally the new instance is owned by a specific conference * focus i.e. further/future requests to manage the new instance must come * from the specified <tt>focus</tt> or they will be ignored. If the focus * is not specified this safety check is overridden. * * @param focus (optional) a <tt>String</tt> which specifies the JID of * the conference focus which will own the new instance i.e. from whom * further/future requests to manage the new instance must come or they will * be ignored. Pass <tt>null</tt> to override this safety check. * @return a new <tt>Conference</tt> instance with an ID unique to the * <tt>Conference</tt> instances listed by this <tt>Videobridge</tt> */ public Conference createConference(String focus) { Conference conference = null; do { String id = generateConferenceID(); synchronized (conferences) { if (!conferences.containsKey(id)) { conference = new Conference(this, id, focus); conferences.put(id, conference); } } } while (conference == null); /* * The method Videobridge.getChannelCount() should better be executed * outside synchronized blocks in order to reduce the risks of causing * deadlocks. */ if (logger.isInfoEnabled()) { logger.info( "Created conference " + conference.getID() + ". " + getConferenceCountString()); } return conference; } /** * Enables graceful shutdown mode on this bridge instance and eventually * starts the shutdown immediately if no conferences are currently being * hosted. Otherwise bridge will shutdown once all conferences expire. */ private void enableGracefulShutdownMode() { if (!shutdownInProgress) { logger.info("Entered graceful shutdown mode"); } this.shutdownInProgress = true; maybeDoShutdown(); } /** * Expires a specific <tt>Conference</tt> of this <tt>Videobridge</tt> (i.e. * if the specified <tt>Conference</tt> is not in the list of * <tt>Conference</tt>s of this <tt>Videobridge</tt>, does nothing). * * @param conference the <tt>Conference</tt> to be expired by this * <tt>Videobridge</tt> */ public void expireConference(Conference conference) { String id = conference.getID(); boolean expireConference; synchronized (conferences) { if (conference.equals(conferences.get(id))) { conferences.remove(id); expireConference = true; } else expireConference = false; } if (expireConference) conference.expire(); // Check if it's the time to shutdown now maybeDoShutdown(); } /** * Generates a new <tt>Conference</tt> ID which is not guaranteed to be * unique. * * @return a new <tt>Conference</tt> ID which is not guaranteed to be unique */ private String generateConferenceID() { return Long.toHexString(System.currentTimeMillis() + RANDOM.nextLong()); } /** * Returns the OSGi <tt>BundleContext</tt> in which this * <tt>Videobridge</tt> is executing. * * @return the OSGi <tt>BundleContext</tt> in which this * <tt>Videobridge</tt> is executing. */ public BundleContext getBundleContext() { return bundleContext; } /** * Gets the number of active <tt>Channel</tt>s in this <tt>Videobridge</tt> * (across all active <tt>Conference</tt>s and active <tt>Content</tt>s). * * @return the number of active <tt>Channel</tt>s in this * <tt>Videobridge</tt> */ public int getChannelCount() { int channelCount = 0; for (Conference conference : getConferences()) { if (conference != null && !conference.isExpired()) { for (Content content : conference.getContents()) { if (content != null && !content.isExpired()) { channelCount += content.getChannelCount(); } } } } return channelCount; } /** * Gets the <tt>ComponentImpl</tt> instances which implement the XMPP API of * this <tt>Videobridge</tt>. * * @return the <tt>ComponentImpl</tt> instances which implement the XMPP API * of this <tt>Videobridge</tt> */ public Collection<ComponentImpl> getComponents() { return ComponentImpl.getComponents(getBundleContext()); } /** * Gets an existing {@link Conference} with a specific ID and a specific * conference focus. * * @param id the ID of the existing <tt>Conference</tt> to get * @param focus (optional) the JID of the conference focus of the existing * <tt>Conference</tt> to get. A <tt>Conference</tt> does not take orders * from a (remote) entity other than the conference focus who has * initialized it. Pass <tt>null</tt> if you want any participant to be able * to modify the conference. * @return an existing <tt>Conference</tt> with the specified ID and the * specified conference focus or <tt>null</tt> if no <tt>Conference</tt> * with the specified ID and the specified conference focus is known to this * <tt>Videobridge</tt> */ public Conference getConference(String id, String focus) { Conference conference; synchronized (conferences) { conference = conferences.get(id); } if (conference != null) { /* * (Optional) A conference is owned by the focus who has initialized * it and it may be managed by that focus only. */ String conferenceFocus = conference.getFocus(); // If no 'focus' was given as an argument or if conference is not // owned by any 'conferenceFocus' then skip equals() if (focus == null || conferenceFocus == null || focus.equals(conferenceFocus)) { // It seems the conference is still active. conference.touch(); } else { conference = null; } } return conference; } /** * Gets the number of <tt>Conference</tt>s of this <tt>Videobridge</tt> that * are not expired. * * @return the number of <tt>Conference</tt>s of this <tt>Videobridge</tt> * that are not expired. */ public int getConferenceCount() { int sz = 0; Conference[] cs = getConferences(); if (cs != null && cs.length != 0) { for (Conference c : cs) { if (c != null && !c.isExpired()) { sz++; } } } return sz; } /** * Gets the <tt>Conference</tt>s of this <tt>Videobridge</tt>. * * @return the <tt>Conference</tt>s of this <tt>Videobridge</tt> */ public Conference[] getConferences() { synchronized (conferences) { Collection<Conference> values = conferences.values(); return values.toArray(new Conference[values.size()]); } } /** * Returns the <tt>ConfigurationService</tt> used by this * <tt>Videobridge</tt>. * * @return the <tt>ConfigurationService</tt> used by this * <tt>Videobridge</tt>. */ public ConfigurationService getConfigurationService() { BundleContext bundleContext = getBundleContext(); if (bundleContext == null) { return null; } else { return ServiceUtils2.getService( bundleContext, ConfigurationService.class); } } /** * Gets the XML namespace of the <tt>TransportManager</tt> type to be * initialized by <tt>Channel</tt> by default. * * @return the XML namespace of the <tt>TransportManager</tt> type to be * initialized by <tt>Channel</tt> by default */ public String getDefaultTransportManager() { synchronized (Videobridge.class) { if (defaultTransportManager == null) { BundleContext bundleContext = getBundleContext(); if (bundleContext != null) { ConfigurationService cfg = ServiceUtils2.getService( bundleContext, ConfigurationService.class); if (cfg != null) { defaultTransportManager = cfg.getString( Videobridge.class.getName() + ".defaultTransportManager"); } } if (!IceUdpTransportPacketExtension.NAMESPACE.equals( defaultTransportManager) && !RawUdpTransportPacketExtension.NAMESPACE.equals( defaultTransportManager)) { defaultTransportManager = IceUdpTransportPacketExtension.NAMESPACE; } } return defaultTransportManager; } } /** * Returns the <tt>LoggingService</tt> used by this * <tt>Videobridge</tt>. * * @return the <tt>LoggingService</tt> used by this * <tt>Videobridge</tt>. */ public EventAdmin getEventAdmin() { BundleContext bundleContext = getBundleContext(); if (bundleContext == null) return null; else return ServiceUtils2.getService(bundleContext, EventAdmin.class); } /** * Handles a <tt>ColibriConferenceIQ</tt> stanza which represents a request. * * @param conferenceIQ the <tt>ColibriConferenceIQ</tt> stanza represents * the request to handle * @return an <tt>org.jivesoftware.smack.packet.IQ</tt> stanza which * represents the response to the specified request or <tt>null</tt> to * reply with <tt>feature-not-implemented</tt> * @throws Exception to reply with <tt>internal-server-error</tt> to the * specified request */ public IQ handleColibriConferenceIQ(ColibriConferenceIQ conferenceIQ) throws Exception { return handleColibriConferenceIQ(conferenceIQ, defaultProcessingOptions); } /** * Handles a <tt>ColibriConferenceIQ</tt> stanza which represents a request. * * @param conferenceIQ the <tt>ColibriConferenceIQ</tt> stanza represents * the request to handle * @param options * @return an <tt>org.jivesoftware.smack.packet.IQ</tt> stanza which * represents the response to the specified request or <tt>null</tt> to * reply with <tt>feature-not-implemented</tt> * @throws Exception to reply with <tt>internal-server-error</tt> to the * specified request */ public IQ handleColibriConferenceIQ( ColibriConferenceIQ conferenceIQ, int options) throws Exception { String focus = conferenceIQ.getFrom(); Conference conference; if ((options & OPTION_ALLOW_ANY_FOCUS) > 0) { // Act like the focus was not provided at all options |= OPTION_ALLOW_NO_FOCUS; focus = null; } if (focus == null && (options & OPTION_ALLOW_NO_FOCUS) == 0) { return IQ.createErrorResponse( conferenceIQ, new XMPPError(XMPPError.Condition.not_authorized)); } else if (authorizedSourcePattern != null && (focus == null || !authorizedSourcePattern.matcher(focus).matches())) { return IQ.createErrorResponse( conferenceIQ, new XMPPError(XMPPError.Condition.not_authorized)); } else { /* * The presence of the id attribute in the conference element * signals whether a new conference is to be created or an existing * conference is to be modified. */ String id = conferenceIQ.getID(); if (id == null) { if (!isShutdownInProgress()) { conference = createConference(focus); } else { return ColibriConferenceIQ .createGracefulShutdownErrorResponse(conferenceIQ); } } else { conference = getConference(id, focus); } if (conference != null) conference.setLastKnownFocus(conferenceIQ.getFrom()); } ColibriConferenceIQ responseConferenceIQ; if (conference == null) { /* * Possible reasons for having no Conference instance include * failure to produce an ID which identifies an existing Conference * instance or the JID of a conference focus which owns an existing * Conference instance with a valid ID. */ responseConferenceIQ = null; } else { String name = conferenceIQ.getName(); if (name != null) conference.setName(name); responseConferenceIQ = new ColibriConferenceIQ(); conference.describeShallow(responseConferenceIQ); responseConferenceIQ.setGracefulShutdown(isShutdownInProgress()); ColibriConferenceIQ.Recording recordingIQ = conferenceIQ.getRecording(); if (recordingIQ != null) { String tokenIQ = recordingIQ.getToken(); if (tokenIQ != null) { String tokenConfig = getConfigurationService().getString( Videobridge.MEDIA_RECORDING_TOKEN_PNAME); if (tokenIQ.equals(tokenConfig)) { ColibriConferenceIQ.Recording.State recState = recordingIQ.getState(); boolean recording = conference.setRecording( ColibriConferenceIQ.Recording.State.ON .equals(recState) || ColibriConferenceIQ.Recording.State .PENDING.equals(recState)); ColibriConferenceIQ.Recording responseRecordingIq = new ColibriConferenceIQ.Recording(recState); if (recording) { responseRecordingIq.setDirectory( conference.getRecordingDirectory()); } responseConferenceIQ.setRecording(responseRecordingIq); } } } // TODO(gp) Remove ColibriConferenceIQ.RTCPTerminationStrategy for (ColibriConferenceIQ.Content contentIQ : conferenceIQ.getContents()) { /* * The content element springs into existence whenever it gets * mentioned, it does not need explicit creation (in contrast to * the conference and channel elements). */ Content content = conference.getOrCreateContent(contentIQ.getName()); if (content == null) { responseConferenceIQ = null; } else { ColibriConferenceIQ.Content responseContentIQ = new ColibriConferenceIQ.Content(content.getName()); responseConferenceIQ.addContent(responseContentIQ); for (ColibriConferenceIQ.Channel channelIQ : contentIQ.getChannels()) { String channelID = channelIQ.getID(); int channelExpire = channelIQ.getExpire(); String channelBundleId = channelIQ.getChannelBundleId(); RtpChannel channel = null; boolean channelCreated = false; String transportNamespace = channelIQ.getTransport() != null ? channelIQ.getTransport().getNamespace() : null; /* * The presence of the id attribute in the channel * element signals whether a new channel is to be * created or an existing channel is to be modified. */ if (channelID == null) { /* * An expire attribute in the channel element with * value equal to zero requests the immediate * expiration of the channel in question. * Consequently, it does not make sense to have it * in a channel allocation request. */ if (channelExpire != 0) { channel = content.createRtpChannel( channelBundleId, transportNamespace, channelIQ.isInitiator(), channelIQ.getRTPLevelRelayType()); if (channel instanceof VideoChannel) { VideoChannel videoChannel = (VideoChannel)channel; videoChannel.setReceiveSimulcastLayer(channelIQ.getReceivingSimulcastLayer()); } channelCreated = true; } } else { channel = (RtpChannel) content.getChannel(channelID); } if (channel == null) { responseConferenceIQ = null; } else { if (channelExpire != ColibriConferenceIQ.Channel .EXPIRE_NOT_SPECIFIED) { channel.setExpire(channelExpire); /* * If the request indicates that it wants * the channel expired and the channel is * indeed expired, then the request is valid * and has correctly been acted upon. */ if ((channelExpire == 0) && channel.isExpired()) continue; } // endpoint // The attribute endpoint is optional. If a value is // not specified, then the Channel endpoint is to // not be changed. String endpoint = channelIQ.getEndpoint(); if (endpoint != null) channel.setEndpoint(endpoint); /* * The attribute last-n is optional. If a value is * not specified, then the Channel lastN is to not * be changed. */ Integer lastN = channelIQ.getLastN(); if (lastN != null) channel.setLastN(lastN); Boolean adaptiveLastN = channelIQ.getAdaptiveLastN(); if (adaptiveLastN != null) channel.setAdaptiveLastN(adaptiveLastN); Boolean adaptiveSimulcast = channelIQ.getAdaptiveSimulcast(); if (adaptiveSimulcast != null) channel.setAdaptiveSimulcast(adaptiveSimulcast); /* * XXX The attribute initiator is optional. If a * value is not specified, then the Channel * initiator is to be assumed default or to not be * changed. */ Boolean initiator = channelIQ.isInitiator(); if (initiator != null) channel.setInitiator(initiator); channel.setPayloadTypes( channelIQ.getPayloadTypes()); channel.setRtpHeaderExtensions( channelIQ.getRtpHeaderExtensions()); channel.setDirection(channelIQ.getDirection()); channel.setSources(channelIQ.getSources()); channel.setSourceGroups( channelIQ.getSourceGroups()); if (channel instanceof VideoChannel) { SimulcastMode simulcastMode = channelIQ.getSimulcastMode(); if (simulcastMode != null) { ((VideoChannel)channel) .setSimulcastMode(simulcastMode); } } if (channelBundleId != null) { TransportManager transportManager = conference.getTransportManager( channelBundleId, true); transportManager.addChannel(channel); } channel.setTransport(channelIQ.getTransport()); /* * Provide (a description of) the current state of * the channel as part of the response. */ ColibriConferenceIQ.Channel responseChannelIQ = new ColibriConferenceIQ.Channel(); channel.describe(responseChannelIQ); responseContentIQ.addChannel(responseChannelIQ); EventAdmin eventAdmin; if (channelCreated && (eventAdmin = getEventAdmin()) != null) { eventAdmin.sendEvent( EventFactory.channelCreated(channel)); } // XXX we might want to fire more precise events, // like sourceGroupsChanged or PayloadTypesChanged, // etc. content.fireChannelChanged(channel); } if (responseConferenceIQ == null) break; } for (ColibriConferenceIQ.SctpConnection sctpConnIq : contentIQ.getSctpConnections()) { String id = sctpConnIq.getID(); String endpointID = sctpConnIq.getEndpoint(); SctpConnection sctpConn; int expire = sctpConnIq.getExpire(); String channelBundleId = sctpConnIq.getChannelBundleId(); // No ID means SCTP connection is to either be created // or focus uses endpoint identity. if (id == null) { // FIXME The method // Content.getSctpConnection(Endpoint) is annotated // as deprecated but SctpConnection identification // by Endpoint (ID) is to continue to be supported // for legacy purposes. Endpoint endpoint = (endpointID == null) ? null : conference.getOrCreateEndpoint( endpointID); sctpConn = content.getSctpConnection(endpoint); if (sctpConn == null) { // Expire an expired/non-existing SCTP // connection. if (expire == 0) continue; int sctpPort = sctpConnIq.getPort(); sctpConn = content.createSctpConnection( endpoint, sctpPort, channelBundleId, sctpConnIq.isInitiator()); } } else { sctpConn = content.getSctpConnection(id); // Expire an expired/non-existing SCTP connection. if (sctpConn == null && expire == 0) continue; // endpoint if (endpointID != null) sctpConn.setEndpoint(endpointID); } // expire if (expire != ColibriConferenceIQ.Channel .EXPIRE_NOT_SPECIFIED) { sctpConn.setExpire(expire); } // Check if SCTP connection has expired. if (sctpConn.isExpired()) continue; // initiator Boolean initiator = sctpConnIq.isInitiator(); if (initiator != null) sctpConn.setInitiator(initiator); // transport sctpConn.setTransport(sctpConnIq.getTransport()); if (channelBundleId != null) { TransportManager transportManager = conference.getTransportManager( channelBundleId, true); transportManager.addChannel(sctpConn); } // response ColibriConferenceIQ.SctpConnection responseSctpIq = new ColibriConferenceIQ.SctpConnection(); sctpConn.describe(responseSctpIq); responseContentIQ.addSctpConnection(responseSctpIq); } } if (responseConferenceIQ == null) break; } for (ColibriConferenceIQ.ChannelBundle channelBundleIq : conferenceIQ.getChannelBundles()) { TransportManager transportManager = conference.getTransportManager(channelBundleIq.getId()); IceUdpTransportPacketExtension transportIq = channelBundleIq.getTransport(); if (transportManager != null && transportIq != null) { transportManager.startConnectivityEstablishment( transportIq); } } } // Update the endpoint information of Videobridge with the endpoint // information of the IQ. if (conference != null) { for (ColibriConferenceIQ.Endpoint colibriEndpoint : conferenceIQ.getEndpoints()) { conference.updateEndpoint(colibriEndpoint); } if (responseConferenceIQ != null) conference.describeChannelBundles(responseConferenceIQ); } if (responseConferenceIQ != null) { responseConferenceIQ.setType( org.jivesoftware.smack.packet.IQ.Type.RESULT); } return responseConferenceIQ; } /** * Handles <tt>HealthCheckIQ</tt> by performing health check on this * <tt>Videobridge</tt> instance. * * @param healthCheckIQ the <tt>HealthCheckIQ</tt> to be handled. * @return IQ with &quot;result&quot; type if the health check succeeded or * IQ with &quot;error&quot; type if something went wrong. * {@link XMPPError.Condition#interna_server_error} is returned when the * health check fails or {@link XMPPError.Condition#not_authorized} if the * request comes from a JID that is not authorized to do health checks on * this instance. */ public IQ handleHealthCheckIQ(HealthCheckIQ healthCheckIQ) { if (authorizedSourcePattern != null && !authorizedSourcePattern .matcher(healthCheckIQ.getFrom()) .matches()) { return IQ.createErrorResponse( healthCheckIQ, new XMPPError(XMPPError.Condition.not_authorized)); } try { Health.check(this); return IQ.createResultIQ(healthCheckIQ); } catch (Exception e) { return IQ.createErrorResponse( healthCheckIQ, new XMPPError( XMPPError.Condition.interna_server_error, e.getMessage())); } } /** * Handles a <tt>GracefulShutdownIQ</tt> stanza which represents a request. * * @param shutdownIQ the <tt>GracefulShutdownIQ</tt> stanza represents * the request to handle * @return an <tt>IQ</tt> stanza which represents the response to * the specified request or <tt>null</tt> to reply with * <tt>feature-not-implemented</tt> */ public IQ handleShutdownIQ(ShutdownIQ shutdownIQ) { // Security not configured - service unavailable if (shutdownSourcePattern == null) { return IQ.createErrorResponse( shutdownIQ, new XMPPError(XMPPError.Condition.service_unavailable)); } // Check if source matches pattern String from = shutdownIQ.getFrom(); if (from != null && shutdownSourcePattern.matcher(from).matches()) { logger.info("Accepted shutdown request from: " + from); if (shutdownIQ.isGracefulShutdown()) { if (!isShutdownInProgress()) { enableGracefulShutdownMode(); } } else { new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(1000); logger.warn("JVB force shutdown - now"); System.exit(0); } catch (InterruptedException e) { throw new RuntimeException(e); } } }, "ForceShutdownThread").start(); } return IQ.createResultIQ(shutdownIQ); } else { // Unauthorized logger.error("Rejected shutdown request from: " + from); return IQ.createErrorResponse( shutdownIQ, new XMPPError(XMPPError.Condition.not_authorized)); } } public void handleIQResponse(org.jivesoftware.smack.packet.IQ response) throws Exception { PubSubPublisher.handleIQResponse(response); } /** * Returns {@code true} if this instance has entered graceful shutdown mode. * * @return {@code true} if this instance has entered graceful shutdown mode; * otherwise, {@code false} */ public boolean isShutdownInProgress() { return shutdownInProgress; } /** * Returns {@code true} if XMPP API has been enabled. * * @return {@code true} if XMPP API has been enabled; otherwise, * {@code false} */ public boolean isXmppApiEnabled() { ConfigurationService config = ServiceUtils.getService( getBundleContext(), ConfigurationService.class); return config.getBoolean(Videobridge.XMPP_API_PNAME, false); } /** * Triggers the shutdown given that we're in graceful shutdown mode and * there are no conferences currently in progress. */ private void maybeDoShutdown() { if (!shutdownInProgress) return; synchronized (conferences) { if (conferences.isEmpty()) { ShutdownService shutdownService = ServiceUtils.getService( bundleContext, ShutdownService.class); logger.info("Videobridge is shutting down NOW"); shutdownService.beginShutdown(); } } } /** * Configures regular expression used to filter users authorized to manage * conferences and trigger graceful shutdown(if separate pattern has not * been configured). * @param authorizedSourceRegExp regular expression string */ public void setAuthorizedSourceRegExp(String authorizedSourceRegExp) { if (!StringUtils.isNullOrEmpty(authorizedSourceRegExp)) { authorizedSourcePattern = Pattern.compile(authorizedSourceRegExp); // If no shutdown regexp, then authorized sources are also allowed // to trigger graceful shutdown. if (shutdownSourcePattern == null) { shutdownSourcePattern = authorizedSourcePattern; } } // Turn off else { if (shutdownSourcePattern == authorizedSourcePattern) { shutdownSourcePattern = null; } authorizedSourcePattern = null; } } /** * Starts this <tt>Videobridge</tt> in a specific <tt>BundleContext</tt>. * * @param bundleContext the <tt>BundleContext</tt> in which this * <tt>Videobridge</tt> is to start */ void start(final BundleContext bundleContext) throws Exception { ConfigurationService cfg = ServiceUtils2.getService( bundleContext, ConfigurationService.class); this.defaultProcessingOptions = (cfg == null) ? 0 : cfg.getInt(DEFAULT_OPTIONS_PROPERTY_NAME, 0); if (logger.isDebugEnabled()) { logger.debug( "Default videobridge processing options: 0x" + Integer.toHexString(defaultProcessingOptions)); } String shutdownSourcesRegexp = (cfg == null) ? null : cfg.getString(SHUTDOWN_ALLOWED_SOURCE_REGEXP_PNAME); if (!StringUtils.isNullOrEmpty(shutdownSourcesRegexp)) { try { shutdownSourcePattern = Pattern.compile(shutdownSourcesRegexp); } catch (PatternSyntaxException exc) { logger.error( "Error parsing enableGracefulShutdownMode sources reg expr: " + shutdownSourcesRegexp, exc); } } String authorizedSourceRegexp = (cfg == null) ? null : cfg.getString(AUTHORIZED_SOURCE_REGEXP_PNAME); if (!StringUtils.isNullOrEmpty(authorizedSourceRegexp)) { try { logger.info( "Authorized source regexp: " + authorizedSourceRegexp); setAuthorizedSourceRegExp(authorizedSourceRegexp); } catch (PatternSyntaxException exc) { logger.error( "Error parsing authorized sources reg expr: " + shutdownSourcesRegexp, exc); } } ProviderManager providerManager = ProviderManager.getInstance(); // <conference> providerManager.addIQProvider( ColibriConferenceIQ.ELEMENT_NAME, ColibriConferenceIQ.NAMESPACE, new ColibriIQProvider()); // ICE-UDP <transport> providerManager.addExtensionProvider( IceUdpTransportPacketExtension.ELEMENT_NAME, IceUdpTransportPacketExtension.NAMESPACE, new DefaultPacketExtensionProvider<>( IceUdpTransportPacketExtension.class)); // Raw UDP <transport> providerManager.addExtensionProvider( RawUdpTransportPacketExtension.ELEMENT_NAME, RawUdpTransportPacketExtension.NAMESPACE, new DefaultPacketExtensionProvider<>( RawUdpTransportPacketExtension.class)); PacketExtensionProvider candidatePacketExtensionProvider = new DefaultPacketExtensionProvider<>( CandidatePacketExtension.class); // ICE-UDP <candidate> providerManager.addExtensionProvider( CandidatePacketExtension.ELEMENT_NAME, IceUdpTransportPacketExtension.NAMESPACE, candidatePacketExtensionProvider); // Raw UDP <candidate> providerManager.addExtensionProvider( CandidatePacketExtension.ELEMENT_NAME, RawUdpTransportPacketExtension.NAMESPACE, candidatePacketExtensionProvider); providerManager.addExtensionProvider( RtcpmuxPacketExtension.ELEMENT_NAME, IceUdpTransportPacketExtension.NAMESPACE, new DefaultPacketExtensionProvider<>( RtcpmuxPacketExtension.class)); // DTLS-SRTP <fingerprint> providerManager.addExtensionProvider( DtlsFingerprintPacketExtension.ELEMENT_NAME, DtlsFingerprintPacketExtension.NAMESPACE, new DefaultPacketExtensionProvider<>( DtlsFingerprintPacketExtension.class)); // PubSub providerManager.addIQProvider( PubSubElementType.PUBLISH.getElementName(), PubSubElementType.PUBLISH.getNamespace().getXmlns(), new PubSubProvider()); // Health-check providerManager.addIQProvider( HealthCheckIQ.ELEMENT_NAME, HealthCheckIQ.NAMESPACE, new HealthCheckIQProvider()); this.bundleContext = bundleContext; startIce4j(bundleContext, cfg); } /** * Implements the ice4j-related portion of {@link #start(BundleContext)}. * * @param bundleContext the {@code BundleContext} in which this * {@code Videobridge} is to start * @param cfg the {@code ConfigurationService} registered in * {@code bundleContext}. Explicitly provided for the sake of performance. */ private void startIce4j( BundleContext bundleContext, ConfigurationService cfg) { // TODO Packet logging for ice4j is not supported at this time. StunStack.setPacketLogger(null); // Make all ice4j properties system properties. if (cfg != null) { List<String> ice4jPropertyNames = cfg.getPropertyNamesByPrefix("org.ice4j.", false); if (ice4jPropertyNames != null && !ice4jPropertyNames.isEmpty()) { for (String propertyName : ice4jPropertyNames) { String propertyValue = cfg.getString(propertyName); // we expect the getString to return either null or a // non-empty String object. if (propertyValue != null) System.setProperty(propertyName, propertyValue); } } } // Initialize the the host candidate interface filters in the ice4j // stack. try { HostCandidateHarvester.initializeInterfaceFilters(); } catch (Exception e) { logger.warn( "There were errors during host candidate interface filters" + " initialization.", e); } // CandidateHarvesters may take (non-trivial) time to initialize so // initialize them as soon as possible, don't wait to initialize them // after a Channel is requested. IceUdpTransportManager.initializeStaticHarvesters(cfg); } /** * Stops this <tt>Videobridge</tt> in a specific <tt>BundleContext</tt>. * * @param bundleContext the <tt>BundleContext</tt> in which this * <tt>Videobridge</tt> is to stop */ void stop(BundleContext bundleContext) throws Exception { this.bundleContext = null; } /** * Returns an array that contains the total number of conferences (at index * 0), channels (at index 1) and video streams (at index 2). * * The "video streams" count is an estimation of the total number of * video streams received or sent. It may not be exactly accurate, because * we assume, for example, that all endpoints are sending video. It is a * better representation of the level of usage of the bridge than simply * the number of channels, because it takes into account the size of each * conference. * * We return these three together to avoid looping through all conferences * multiple times when all three values are needed. * * @return an array that contains the total number of * conferences (at index 0), channels (at index 1) and video streams (at * index 2). */ public int[] getConferenceChannelAndStreamCount() { Conference[] conferences = getConferences(); int conferenceCount = 0, channelCount = 0, streamCount = 0; if (conferences != null && conferences.length != 0) { for (Conference conference : conferences) { if (conference != null && !conference.isExpired()) { conferenceCount++; for (Content content : conference.getContents()) { if (content != null && !content.isExpired()) { int contentChannelCount = content.getChannelCount(); channelCount += contentChannelCount; if (MediaType.VIDEO.equals(content.getMediaType())) { streamCount += getContentStreamCount( content, contentChannelCount); } } } } } } return new int[]{conferenceCount, channelCount, streamCount}; } /** * Returns a short string that contains the total number of * conferences/channels/video streams, for the purposes of logging. * * @return a short string that contains the total number of * conferences/channels/video streams, for the purposes of logging. */ String getConferenceCountString() { int[] metrics = getConferenceChannelAndStreamCount(); StringBuilder sb = new StringBuilder("The total number of conferences is now "); sb.append(metrics[0]).append(", channels ").append(metrics[1]); sb.append(", video streams ").append(metrics[2]).append("."); return sb.toString(); } /** * Gets the number of video streams for a given <tt>Content</tt>. See the * documentation for {@link #getConferenceCountString()}. * * @param content the content. * @param contentChannelCount the number of channels in the content. * @return the number of video streams for a given <tt>Content</tt>. See the * documentation for {@link #getConferenceCountString()}. */ private int getContentStreamCount(Content content, int contentChannelCount) { Channel[] channels = content.getChannels(); int contentStreamCount = 0; if (channels != null && channels.length != 0) { for (Channel channel : channels) { if (channel != null && !channel.isExpired() && channel instanceof VideoChannel) { VideoChannel videoChannel = (VideoChannel) channel; int channelStreams = 1; //assume we're receiving a stream int lastN = videoChannel.getLastN(); channelStreams += lastN == -1 ? contentChannelCount - 1 : Math.min(lastN, contentChannelCount - 1); contentStreamCount += channelStreams; } } } return contentStreamCount; } }
Fix style issues
src/main/java/org/jitsi/videobridge/Videobridge.java
Fix style issues
<ide><path>rc/main/java/org/jitsi/videobridge/Videobridge.java <ide> <ide> if (channel instanceof VideoChannel) <ide> { <del> VideoChannel videoChannel = (VideoChannel)channel; <del> videoChannel.setReceiveSimulcastLayer(channelIQ.getReceivingSimulcastLayer()); <add> VideoChannel videoChannel <add> = (VideoChannel)channel; <add> <add> Integer receiveSimulcastLayer = <add> channelIQ.getReceivingSimulcastLayer(); <add> <add> videoChannel.setReceiveSimulcastLayer( <add> receiveSimulcastLayer); <ide> } <ide> <ide> channelCreated = true;
Java
bsd-3-clause
8dc386ccf4f78df46fbeaea777427c3a88617cb3
0
credentials/irma_verification_common,credentials/irma_api_common
/* * DisclosureProofRequest.java * * Copyright (c) 2015, Sietse Ringers, Radboud University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the IRMA project nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package org.irmacard.api.common.disclosure; import org.irmacard.api.common.AttributeDisjunction; import org.irmacard.api.common.AttributeDisjunctionList; import org.irmacard.api.common.JwtParser; import org.irmacard.api.common.SessionRequest; import org.irmacard.api.common.exceptions.ApiException; import org.irmacard.credentials.idemix.IdemixPublicKey; import org.irmacard.credentials.idemix.IdemixSystemParameters; import org.irmacard.credentials.idemix.info.IdemixKeyStore; import org.irmacard.credentials.idemix.proofs.ProofList; import org.irmacard.credentials.info.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.math.BigInteger; import java.util.*; @SuppressWarnings("unused") public class DisclosureProofRequest extends SessionRequest { private static Logger logger = LoggerFactory.getLogger(DisclosureProofRequest.class); private static final long serialVersionUID = 1016467840623150897L; protected AttributeDisjunctionList content; public DisclosureProofRequest(BigInteger nonce, BigInteger context, AttributeDisjunctionList content) { super(nonce, context); this.content = content; } public AttributeDisjunctionList getContent() { return content; } @Override public HashSet<CredentialIdentifier> getCredentialList() { HashSet<CredentialIdentifier> credentials = new HashSet<>(); for (AttributeDisjunction disjunction : content) for (AttributeIdentifier attr : disjunction) credentials.add(attr.getCredentialIdentifier()); return credentials; } @Override public HashMap<IssuerIdentifier, Integer> getPublicKeyList() { return new HashMap<>(); } public boolean attributesMatchStore() throws ApiException { for (AttributeDisjunction disjunction : getContent()) if (!disjunction.attributesMatchStore()) return false; return true; } @Override public IdemixSystemParameters getLargestParameters() { IdemixSystemParameters params = null; for (AttributeDisjunction disjunction : getContent()) { for (AttributeIdentifier identifier : disjunction) { try { IdemixPublicKey pk = IdemixKeyStore.getInstance() .getLatestPublicKey(identifier.getIssuerIdentifier()); if (params == null || params.get_l_n() < pk.getBitsize()) params = pk.getSystemParameters(); } catch (KeyException e) { throw new RuntimeException(e); } } } return params; } @Override public boolean isEmpty() { return content == null || content.size() == 0; } public DisclosureProofResult verify(ProofList proofs) throws InfoException, KeyException { return verify(proofs, Calendar.getInstance().getTime(), false); } protected DisclosureProofResult verify(ProofList proofs, Date validityDate, boolean allowExpired) throws InfoException, KeyException { DisclosureProofResult result = new DisclosureProofResult(); // Our return object HashMap<AttributeIdentifier, String> attributes = new HashMap<>(); result.setAttributes(attributes); if (!proofs.verify(getContext(), getNonce(), true)) { logger.info("Proofs did not verify"); result.setStatus(DisclosureProofResult.Status.INVALID); return result; } if (validityDate != null && !proofs.isValidOn(validityDate)) { result.setStatus(DisclosureProofResult.Status.EXPIRED); if (!allowExpired) return result; } HashMap<AttributeIdentifier, String> foundAttrs = null; try { foundAttrs = proofs.getAttributes(); } catch (IllegalArgumentException e) { logger.info("Metadata attribute missing, or unknown credential type"); result.setStatus(DisclosureProofResult.Status.INVALID); return result; } for (AttributeDisjunction disjunction : content) { // For each of the disjunctions, lookup attributes satisfying them for (AttributeIdentifier ai : disjunction) { if (foundAttrs.containsKey(ai)) { String value = foundAttrs.get(ai); if (!disjunction.hasValues()) { disjunction.setSatisfied(true); attributes.put(ai, value); break; } else { // If the request indicated that the attribute should have a specific value, then the containing // disjunction is only satisfied if the actual value of the attribute is correct. String requiredValue = disjunction.getValues().get(ai); if (requiredValue.equals(value)) { disjunction.setSatisfied(true); attributes.put(ai, value); break; } } } } } for (AttributeDisjunction disjunction : content) if (!disjunction.isSatisfied()) result.setStatus(DisclosureProofResult.Status.MISSING_ATTRIBUTES); return result; } /** * Returns true if the request contains no disjunctions, and asks for attributes of a single credential type */ public boolean isSimple() { Set<String> credentials = new HashSet<>(); for (AttributeDisjunction d : content) { if (d.size() > 1) return false; credentials.add(d.get(0).getCredentialName()); } return credentials.size() == 1; } }
src/main/java/org/irmacard/api/common/disclosure/DisclosureProofRequest.java
/* * DisclosureProofRequest.java * * Copyright (c) 2015, Sietse Ringers, Radboud University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the IRMA project nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package org.irmacard.api.common.disclosure; import org.irmacard.api.common.AttributeDisjunction; import org.irmacard.api.common.AttributeDisjunctionList; import org.irmacard.api.common.JwtParser; import org.irmacard.api.common.SessionRequest; import org.irmacard.api.common.exceptions.ApiException; import org.irmacard.credentials.idemix.IdemixPublicKey; import org.irmacard.credentials.idemix.IdemixSystemParameters; import org.irmacard.credentials.idemix.info.IdemixKeyStore; import org.irmacard.credentials.idemix.proofs.ProofList; import org.irmacard.credentials.info.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.math.BigInteger; import java.util.*; @SuppressWarnings("unused") public class DisclosureProofRequest extends SessionRequest { private static Logger logger = LoggerFactory.getLogger(DisclosureProofRequest.class); private static final long serialVersionUID = 1016467840623150897L; protected AttributeDisjunctionList content; public DisclosureProofRequest(BigInteger nonce, BigInteger context, AttributeDisjunctionList content) { super(nonce, context); this.content = content; } public AttributeDisjunctionList getContent() { return content; } @Override public HashSet<CredentialIdentifier> getCredentialList() { HashSet<CredentialIdentifier> credentials = new HashSet<>(); for (AttributeDisjunction disjunction : content) for (AttributeIdentifier attr : disjunction) credentials.add(attr.getCredentialIdentifier()); return credentials; } @Override public HashMap<IssuerIdentifier, Integer> getPublicKeyList() { return new HashMap<>(); } public boolean attributesMatchStore() throws ApiException { for (AttributeDisjunction disjunction : getContent()) if (!disjunction.attributesMatchStore()) return false; return true; } @Override public IdemixSystemParameters getLargestParameters() { IdemixSystemParameters params = null; for (AttributeDisjunction disjunction : getContent()) { for (AttributeIdentifier identifier : disjunction) { try { IdemixPublicKey pk = IdemixKeyStore.getInstance() .getLatestPublicKey(identifier.getIssuerIdentifier()); if (params == null || params.get_l_n() < pk.getBitsize()) params = pk.getSystemParameters(); } catch (KeyException e) { throw new RuntimeException(e); } } } return params; } @Override public boolean isEmpty() { return content == null || content.size() == 0; } public DisclosureProofResult verify(ProofList proofs) throws InfoException, KeyException { return verify(proofs, Calendar.getInstance().getTime(), false); } protected DisclosureProofResult verify(ProofList proofs, Date validityDate, boolean allowExpired) throws InfoException, KeyException { DisclosureProofResult result = new DisclosureProofResult(); // Our return object HashMap<AttributeIdentifier, String> attributes = new HashMap<>(); result.setAttributes(attributes); if (!proofs.verify(getContext(), getNonce(), true)) { logger.info("Proofs did not verify"); result.setStatus(DisclosureProofResult.Status.INVALID); return result; } if (validityDate != null && !proofs.isValidOn(validityDate)) { result.setStatus(DisclosureProofResult.Status.EXPIRED); if (!allowExpired) return result; } HashMap<AttributeIdentifier, String> foundAttrs = null; try { foundAttrs = proofs.getAttributes(); } catch (IllegalArgumentException e) { logger.info("Metadata attribute missing, or unknown credential type"); result.setStatus(DisclosureProofResult.Status.INVALID); return result; } for (AttributeIdentifier ai : foundAttrs.keySet()) { // For each of the disclosed attributes in this proof, see if they satisfy one of // the AttributeDisjunctions that we asked for AttributeDisjunction disjunction = content.find(ai); if (disjunction == null || disjunction.isSatisfied()) continue; String value = foundAttrs.get(ai); if (!disjunction.hasValues()) { disjunction.setSatisfied(true); attributes.put(ai, value); } else { // If the request indicated that the attribute should have a specific value, then the containing // disjunction is only satisfied if the actual value of the attribute is correct. String requiredValue = disjunction.getValues().get(ai); if (requiredValue.equals(value)) { disjunction.setSatisfied(true); attributes.put(ai, value); } } } for (AttributeDisjunction disjunction : content) if (!disjunction.isSatisfied()) result.setStatus(DisclosureProofResult.Status.MISSING_ATTRIBUTES); return result; } /** * Returns true if the request contains no disjunctions, and asks for attributes of a single credential type */ public boolean isSimple() { Set<String> credentials = new HashSet<>(); for (AttributeDisjunction d : content) { if (d.size() > 1) return false; credentials.add(d.get(0).getCredentialName()); } return credentials.size() == 1; } }
Fixed bug where a disclosure request with the same attribute in two seperate disjunctions could be incorrectly marked as not-valid after a proof session.
src/main/java/org/irmacard/api/common/disclosure/DisclosureProofRequest.java
Fixed bug where a disclosure request with the same attribute in two seperate disjunctions could be incorrectly marked as not-valid after a proof session.
<ide><path>rc/main/java/org/irmacard/api/common/disclosure/DisclosureProofRequest.java <ide> result.setStatus(DisclosureProofResult.Status.INVALID); <ide> return result; <ide> } <del> <del> for (AttributeIdentifier ai : foundAttrs.keySet()) { <del> // For each of the disclosed attributes in this proof, see if they satisfy one of <del> // the AttributeDisjunctions that we asked for <del> AttributeDisjunction disjunction = content.find(ai); <del> if (disjunction == null || disjunction.isSatisfied()) <del> continue; <del> <del> String value = foundAttrs.get(ai); <del> if (!disjunction.hasValues()) { <del> disjunction.setSatisfied(true); <del> attributes.put(ai, value); <del> } <del> else { <del> // If the request indicated that the attribute should have a specific value, then the containing <del> // disjunction is only satisfied if the actual value of the attribute is correct. <del> String requiredValue = disjunction.getValues().get(ai); <del> if (requiredValue.equals(value)) { <del> disjunction.setSatisfied(true); <del> attributes.put(ai, value); <add> <add> for (AttributeDisjunction disjunction : content) { <add> // For each of the disjunctions, lookup attributes satisfying them <add> for (AttributeIdentifier ai : disjunction) { <add> if (foundAttrs.containsKey(ai)) { <add> String value = foundAttrs.get(ai); <add> if (!disjunction.hasValues()) { <add> disjunction.setSatisfied(true); <add> attributes.put(ai, value); <add> break; <add> } else { <add> // If the request indicated that the attribute should have a specific value, then the containing <add> // disjunction is only satisfied if the actual value of the attribute is correct. <add> String requiredValue = disjunction.getValues().get(ai); <add> if (requiredValue.equals(value)) { <add> disjunction.setSatisfied(true); <add> attributes.put(ai, value); <add> break; <add> } <add> } <ide> } <ide> } <ide> }
Java
apache-2.0
dc1d9f0141cca1f6c08ab63a616efd5047f8d3e1
0
eFaps/eFapsApp-Payroll
/* * Copyright 2003 - 2014 The eFaps Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Revision: $Rev$ * Last Changed: $Date$ * Last Changed By: $Author$ */ package org.efaps.esjp.payroll.reports; import static net.sf.dynamicreports.report.builder.DynamicReports.type; import java.awt.Color; import java.io.File; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.UUID; import net.sf.dynamicreports.jasper.builder.JasperReportBuilder; import net.sf.dynamicreports.report.base.expression.AbstractSimpleExpression; import net.sf.dynamicreports.report.builder.DynamicReports; import net.sf.dynamicreports.report.builder.column.TextColumnBuilder; import net.sf.dynamicreports.report.builder.grid.ColumnGridComponentBuilder; import net.sf.dynamicreports.report.builder.grid.ColumnTitleGroupBuilder; import net.sf.dynamicreports.report.builder.group.ColumnGroupBuilder; import net.sf.dynamicreports.report.builder.style.StyleBuilder; import net.sf.dynamicreports.report.builder.subtotal.AggregationSubtotalBuilder; import net.sf.dynamicreports.report.definition.ReportParameters; import net.sf.jasperreports.engine.JRDataSource; import net.sf.jasperreports.engine.data.JRMapCollectionDataSource; import org.apache.commons.collections4.comparators.ComparatorChain; import org.efaps.admin.common.MsgPhrase; import org.efaps.admin.datamodel.IEnum; import org.efaps.admin.datamodel.Status; import org.efaps.admin.datamodel.Type; import org.efaps.admin.dbproperty.DBProperties; import org.efaps.admin.event.Parameter; import org.efaps.admin.event.Parameter.ParameterValues; import org.efaps.admin.event.Return; import org.efaps.admin.event.Return.ReturnValues; import org.efaps.db.Instance; import org.efaps.db.MultiPrintQuery; import org.efaps.db.QueryBuilder; import org.efaps.db.SelectBuilder; import org.efaps.esjp.ci.CIHumanResource; import org.efaps.esjp.ci.CIPayroll; import org.efaps.esjp.ci.CIProjects; import org.efaps.esjp.ci.CISales; import org.efaps.esjp.common.jasperreport.AbstractDynamicReport; import org.efaps.esjp.common.jasperreport.datatype.DateTimeDate; import org.efaps.esjp.erp.FilteredReport; import org.efaps.esjp.sales.report.DocumentSumReport; import org.efaps.ui.wicket.util.EnumUtil; import org.efaps.util.EFapsException; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * TODO comment! * * @author The eFaps Team * @version $Id: PositionAnalyzeReport_Base.java 14584 2014-12-04 03:55:22Z * [email protected] $ */ public abstract class PositionAnalyzeReport_Base extends FilteredReport { /** * Logging instance used in this class. */ private static final Logger LOG = LoggerFactory.getLogger(PositionAnalyzeReport.class); /** * Enum used for display. */ public enum DetailsDisplay { /** Display as Column. */ STANDART, /** No display. */ NONE, /** Display as Group. */ EXTRA; } /** * @param _parameter Parameter as passed by the eFasp API * @return Return containing html snipplet * @throws EFapsException on error */ public Return generateReport(final Parameter _parameter) throws EFapsException { final Return ret = new Return(); final AbstractDynamicReport dyRp = getReport(_parameter); final String html = dyRp.getHtmlSnipplet(_parameter); ret.put(ReturnValues.SNIPLETT, html); return ret; } /** * @param _parameter Parameter as passed by the eFasp API * @return Return containing the file * @throws EFapsException on error */ public Return exportReport(final Parameter _parameter) throws EFapsException { final Return ret = new Return(); final Map<?, ?> props = (Map<?, ?>) _parameter.get(ParameterValues.PROPERTIES); final String mime = (String) props.get("Mime"); final AbstractDynamicReport dyRp = getReport(_parameter); dyRp.setFileName(DBProperties.getProperty(DocumentSumReport.class.getName() + ".FileName")); File file = null; if ("xls".equalsIgnoreCase(mime)) { file = dyRp.getExcel(_parameter); } else if ("pdf".equalsIgnoreCase(mime)) { file = dyRp.getPDF(_parameter); } ret.put(ReturnValues.VALUES, file); ret.put(ReturnValues.TRUE, true); return ret; } @Override protected Object getDefaultValue(final Parameter _parameter, final String _field, final String _type, final String _default) throws EFapsException { Object ret; if ("Status".equalsIgnoreCase(_type)) { final Set<Long> set = new HashSet<>(); set.add(Status.find(CIPayroll.PayslipStatus.Draft).getId()); ret = new StatusFilterValue().setObject(set); } else { ret = super.getDefaultValue(_parameter, _field, _type, _default); } return ret; } /** * @param _parameter Parameter as passed by the eFasp API * @return the report class * @throws EFapsException on error */ protected AbstractDynamicReport getReport(final Parameter _parameter) throws EFapsException { return new DynPositionAnalyzeReport(this); } /** * Dynamic Report. */ public static class DynPositionAnalyzeReport extends AbstractDynamicReport { /** * Filtered Report. */ private final PositionAnalyzeReport_Base filterReport; /** * Data for the positions. */ private Map<Instance, Map<String, Object>> data; /** * List of columns. */ private List<Column> columns; /** * @param _filterReport report */ public DynPositionAnalyzeReport(final PositionAnalyzeReport_Base _filterReport) { this.filterReport = _filterReport; } @Override protected StyleBuilder getColumnStyle4Html(final Parameter _parameter) throws EFapsException { return super.getColumnStyle4Html(_parameter).setBorder(DynamicReports.stl.pen1Point()); } /** * Getter method for the instance variable {@link #data}. * * @param _parameter Paramdeter as passed by the eFaps API * @return value of instance variable {@link #data} * @throws EFapsException on error */ public Map<Instance, Map<String, Object>> getData(final Parameter _parameter) throws EFapsException { if (this.data == null) { this.data = new HashMap<>(); final Map<String, Column> columnMap = new HashMap<>(); final Map<String, Object> filterMap = getFilterReport().getFilterMap(_parameter); final boolean project = filterMap.containsKey("projectGroup") && !GroupDisplay.NONE.equals(FilteredReport.getEnumValue(filterMap.get("projectGroup"))); //Payroll_Employee4DocumentMsgPhrase final MsgPhrase msgPhrase = MsgPhrase.get(UUID.fromString("4bf03526-3616-4e57-ad70-1e372029ea9e")); MsgPhrase msgPhrase4Project = null; if (project) { // Project_ProjectMsgPhrase msgPhrase4Project = MsgPhrase.get(UUID .fromString("64c30826-cb22-4579-a3d5-bd10090f155e")); } DetailsDisplay details = DetailsDisplay.STANDART; if (filterMap.containsKey("details")) { details = FilteredReport.getEnumValue(filterMap.get("details")); } final QueryBuilder queryBuilder = new QueryBuilder(CIPayroll.PositionDeduction); queryBuilder.addType(CIPayroll.PositionNeutral, CIPayroll.PositionPayment); add2QueryBuilder(_parameter, queryBuilder); final MultiPrintQuery multi = queryBuilder.getPrint(); final SelectBuilder selDoc = SelectBuilder.get() .linkto(CIPayroll.PositionAbstract.DocumentAbstractLink); final SelectBuilder selDocInst = new SelectBuilder(selDoc).instance(); final SelectBuilder selDocName = new SelectBuilder(selDoc).attribute(CIPayroll.DocumentAbstract.Name); final SelectBuilder selCrossTotal = new SelectBuilder(selDoc) .attribute(CIPayroll.DocumentAbstract.CrossTotal); final SelectBuilder selAmountCost = new SelectBuilder(selDoc) .attribute(CIPayroll.DocumentAbstract.AmountCost); final SelectBuilder selDocELT = new SelectBuilder(selDoc) .attribute(CIPayroll.DocumentAbstract.ExtraLaborTime); final SelectBuilder selDocHLT = new SelectBuilder(selDoc) .attribute(CIPayroll.DocumentAbstract.HolidayLaborTime); final SelectBuilder selDocLT = new SelectBuilder(selDoc) .attribute(CIPayroll.DocumentAbstract.LaborTime); final SelectBuilder selDocNLT = new SelectBuilder(selDoc) .attribute(CIPayroll.DocumentAbstract.NightLaborTime); final SelectBuilder selDepName = new SelectBuilder(selDoc) .linkto(CIPayroll.DocumentAbstract.EmployeeAbstractLink) .linkfrom(CIHumanResource.Department2EmployeeAdminister.EmployeeLink) .linkto(CIHumanResource.Department2EmployeeAdminister.DepartmentLink) .attribute(CIHumanResource.Department.Name); final SelectBuilder selRemun = new SelectBuilder(selDoc) .linkto(CIPayroll.DocumentAbstract.EmployeeAbstractLink) .clazz(CIHumanResource.ClassTR_Labor) .attribute(CIHumanResource.ClassTR_Labor.Remuneration); final SelectBuilder selProj = new SelectBuilder(selDoc) .linkfrom(CIProjects.Project2DocumentAbstract.ToAbstract) .linkto(CIProjects.Project2DocumentAbstract.FromAbstract); final SelectBuilder selEmplNum = new SelectBuilder(selDoc) .linkto(CIPayroll.DocumentAbstract.EmployeeAbstractLink) .attribute(CIHumanResource.Employee.Number); if (project) { multi.addMsgPhrase(selProj, msgPhrase4Project); } SelectBuilder selEmplPR = null; SelectBuilder selEmplPRT = null; SelectBuilder selEmplST = null; SelectBuilder selPeri = null; SelectBuilder selEmplEmpl = null; SelectBuilder selEmplAct = null; if (DetailsDisplay.EXTRA.equals(details)) { selEmplPR = new SelectBuilder(selDoc) .linkto(CIPayroll.DocumentAbstract.EmployeeAbstractLink) .clazz(CIHumanResource.ClassTR_Health) .linkto(CIHumanResource.ClassTR_Health.PensionRegimeLink) .attribute(CIHumanResource.AttributeDefinitionPensionRegime.Value); selEmplPRT = new SelectBuilder(selDoc) .linkto(CIPayroll.DocumentAbstract.EmployeeAbstractLink) .clazz(CIHumanResource.ClassTR_Health) .linkto(CIHumanResource.ClassTR_Health.PensionRegimeTypeLink) .attribute(CIHumanResource.AttributeDefinitionPensionRegimeType.Value); selEmplST = new SelectBuilder(selDoc) .linkto(CIPayroll.DocumentAbstract.EmployeeAbstractLink) .clazz(CIHumanResource.ClassTR).attribute(CIHumanResource.ClassTR.StartDate); selPeri = new SelectBuilder(selDoc) .linkto(CIPayroll.DocumentAbstract.EmployeeAbstractLink) .clazz(CIHumanResource.ClassTR_Labor) .linkto(CIHumanResource.ClassTR_Labor.PeriodicityLink) .attribute(CIHumanResource.AttributeDefinitionPeriodicity.Value); selEmplEmpl = new SelectBuilder(selDoc) .linkto(CIPayroll.DocumentAbstract.EmployeeAbstractLink) .linkto(CIHumanResource.Employee.EmployLink) .attribute(CIHumanResource.AttributeDefinitionEmploy.Value); selEmplAct = new SelectBuilder(selDoc) .linkto(CIPayroll.DocumentAbstract.EmployeeAbstractLink) .attribute(CIHumanResource.Employee.Activation); multi.addSelect(selEmplPR, selEmplPRT, selEmplST, selPeri, selEmplEmpl, selEmplAct); } multi.addMsgPhrase(selDoc, msgPhrase); multi.addSelect(selCrossTotal, selAmountCost, selDocInst, selDocName, selDepName, selDocELT, selDocHLT, selDocLT, selDocNLT, selRemun, selEmplNum); multi.addAttribute(CIPayroll.PositionAbstract.Amount, CIPayroll.PositionAbstract.Description, CIPayroll.PositionAbstract.Key); multi.execute(); while (multi.next()) { final Instance docInst = multi.getSelect(selDocInst); Map<String, Object> map; if (this.data.containsKey(docInst)) { map = this.data.get(docInst); } else { map = new HashMap<>(); this.data.put(docInst, map); map.put("Remuneration", multi.getSelect(selRemun)); map.put(CIPayroll.DocumentAbstract.Name.name, multi.getSelect(selDocName)); map.put(CIPayroll.DocumentAbstract.CrossTotal.name, multi.getSelect(selCrossTotal)); map.put(CIPayroll.DocumentAbstract.AmountCost.name, multi.getSelect(selAmountCost)); final BigDecimal laborTime = (BigDecimal) multi.<Object[]>getSelect(selDocLT)[0]; if (!DetailsDisplay.NONE.equals(details) || laborTime == null) { map.put(CIPayroll.DocumentAbstract.LaborTime.name, laborTime); } else { map.put(CIPayroll.DocumentAbstract.LaborTime.name, laborTime.divide(BigDecimal.valueOf(8), BigDecimal.ROUND_HALF_UP)); } map.put(CIPayroll.DocumentAbstract.ExtraLaborTime.name, multi.<Object[]>getSelect(selDocELT)[0]); map.put(CIPayroll.DocumentAbstract.HolidayLaborTime.name, multi.<Object[]>getSelect(selDocHLT)[0]); map.put(CIPayroll.DocumentAbstract.NightLaborTime.name, multi.<Object[]>getSelect(selDocNLT)[0]); map.put(CIPayroll.DocumentAbstract.EmployeeAbstractLink.name, multi.getMsgPhrase(selDoc, msgPhrase)); map.put("Department", multi.getSelect(selDepName)); map.put("EmployeeNumber", multi.getSelect(selEmplNum)); if (project) { map.put("Project", multi.getMsgPhrase(selProj, msgPhrase4Project)); } if (DetailsDisplay.EXTRA.equals(details)) { map.put("pensionRegimeType", multi.getSelect(selEmplPRT)); map.put("pensionRegime", multi.getSelect(selEmplPR)); map.put("startDate", multi.getSelect(selEmplST)); map.put("periodicity", multi.getSelect(selPeri)); map.put("emplEmpl", multi.getSelect(selEmplEmpl)); final Object valueTmp = multi.getSelect(selEmplAct); if (valueTmp != null && valueTmp instanceof List) { final StringBuilder bldr = new StringBuilder(); boolean first = true; for (final Object obj : (List<?>) valueTmp) { if (first) { first = false; } else { bldr.append(", "); } bldr.append(EnumUtil.getUILabel((IEnum) obj)); } map.put("emplAct", bldr.toString()); } } PositionAnalyzeReport_Base.LOG.debug("Read: {}", map); } if (!DetailsDisplay.NONE.equals(details)) { final String key = multi.getAttribute(CIPayroll.PositionAbstract.Key); if (!columnMap.containsKey(key)) { final Column col = new Column(); columnMap.put(key, col); col.setKey(key); final String descr = multi.getAttribute(CIPayroll.PositionAbstract.Description); col.setLabel(key + " - " + descr); col.setGroup(multi.getCurrentInstance().getType().getLabel()); } map.put(key, multi.getAttribute(CIPayroll.PositionAbstract.Amount)); } else { final String key = multi.getCurrentInstance().getType().getName(); if (map.containsKey(key)) { map.put(key, ((BigDecimal) map.get(key)).add(multi .<BigDecimal>getAttribute(CIPayroll.PositionAbstract.Amount))); } else { final Column col = new Column(); columnMap.put(key, col); col.setKey(key); col.setLabel(multi.getCurrentInstance().getType().getLabel()); col.setGroup(multi.getCurrentInstance().getType().getLabel()); map.put(key, multi.getAttribute(CIPayroll.PositionAbstract.Amount)); } } } // Artificially add the one that do not have positions (happens with manually created advances) final QueryBuilder docQueryBldr = getAttrQueryBuilder(_parameter); final QueryBuilder attrQueryBuilder = new QueryBuilder(CIPayroll.PositionDeduction); attrQueryBuilder.addType(CIPayroll.PositionNeutral, CIPayroll.PositionPayment); docQueryBldr.addWhereAttrNotInQuery(CIPayroll.DocumentAbstract.ID, attrQueryBuilder.getAttributeQuery(CIPayroll.PositionAbstract.DocumentAbstractLink)); final MultiPrintQuery docMulti = docQueryBldr.getPrint(); final SelectBuilder selRemun4Doc = SelectBuilder.get() .linkto(CIPayroll.DocumentAbstract.EmployeeAbstractLink) .clazz(CIHumanResource.ClassTR_Labor) .attribute(CIHumanResource.ClassTR_Labor.Remuneration); final SelectBuilder selProj4Doc = SelectBuilder.get() .linkfrom(CIProjects.Project2DocumentAbstract.ToAbstract) .linkto(CIProjects.Project2DocumentAbstract.FromAbstract); final SelectBuilder selEmplNum4Doc = SelectBuilder.get() .linkto(CIPayroll.DocumentAbstract.EmployeeAbstractLink) .attribute(CIHumanResource.Employee.Number); final SelectBuilder selDepName4Doc = SelectBuilder.get() .linkto(CIPayroll.DocumentAbstract.EmployeeAbstractLink) .linkfrom(CIHumanResource.Department2EmployeeAdminister.EmployeeLink) .linkto(CIHumanResource.Department2EmployeeAdminister.DepartmentLink) .attribute(CIHumanResource.Department.Name); if (project) { multi.addMsgPhrase(selProj4Doc, msgPhrase4Project); } docMulti.addMsgPhrase(msgPhrase); docMulti.addSelect(selDepName4Doc, selRemun4Doc, selEmplNum4Doc); docMulti.addAttribute(CIPayroll.DocumentAbstract.Name, CIPayroll.DocumentAbstract.AmountCost, CIPayroll.DocumentAbstract.CrossTotal, CIPayroll.DocumentAbstract.LaborTime, CIPayroll.DocumentAbstract.ExtraLaborTime, CIPayroll.DocumentAbstract.NightLaborTime, CIPayroll.DocumentAbstract.HolidayLaborTime); docMulti.execute(); while (docMulti.next()) { final Map<String, Object> map = new HashMap<>(); this.data.put(docMulti.getCurrentInstance(), map); map.put("Remuneration", docMulti.getSelect(selRemun4Doc)); map.put(CIPayroll.DocumentAbstract.Name.name, docMulti.getAttribute(CIPayroll.DocumentAbstract.Name)); map.put(CIPayroll.DocumentAbstract.CrossTotal.name, docMulti.getAttribute(CIPayroll.DocumentAbstract.CrossTotal)); map.put(CIPayroll.DocumentAbstract.AmountCost.name, docMulti.getAttribute(CIPayroll.DocumentAbstract.AmountCost)); final BigDecimal laborTime = (BigDecimal) docMulti .<Object[]>getAttribute(CIPayroll.DocumentAbstract.LaborTime)[0]; if (!DetailsDisplay.NONE.equals(details) || laborTime == null) { map.put(CIPayroll.DocumentAbstract.LaborTime.name, laborTime); } else { map.put(CIPayroll.DocumentAbstract.LaborTime.name, laborTime.divide(BigDecimal.valueOf(8), BigDecimal.ROUND_HALF_UP)); } map.put(CIPayroll.DocumentAbstract.ExtraLaborTime.name, docMulti.<Object[]>getAttribute(CIPayroll.DocumentAbstract.ExtraLaborTime)[0]); map.put(CIPayroll.DocumentAbstract.HolidayLaborTime.name, docMulti.<Object[]>getAttribute(CIPayroll.DocumentAbstract.HolidayLaborTime)[0]); map.put(CIPayroll.DocumentAbstract.NightLaborTime.name, docMulti.<Object[]>getAttribute(CIPayroll.DocumentAbstract.NightLaborTime)[0]); map.put(CIPayroll.DocumentAbstract.EmployeeAbstractLink.name, docMulti.getMsgPhrase(msgPhrase)); map.put("Department", docMulti.getSelect(selDepName4Doc)); map.put("EmployeeNumber", docMulti.getSelect(selEmplNum4Doc)); if (project) { map.put("Project", docMulti.getMsgPhrase(selProj4Doc, msgPhrase4Project)); } } this.columns = new ArrayList<>(columnMap.values()); if (!DetailsDisplay.NONE.equals(details)) { Collections.sort(this.columns, new Comparator<Column>() { @Override public int compare(final Column _arg0, final Column _arg1) { return _arg0.getLabel().compareTo(_arg1.getLabel()); } }); } } return this.data; } @Override protected JRDataSource createDataSource(final Parameter _parameter) throws EFapsException { final Map<String, Object> filterMap = getFilterReport().getFilterMap(_parameter); final Map<Instance, Map<String, Object>> maps = getData(_parameter); final List<Map<String, Object>> values = new ArrayList<>(maps.values()); final ComparatorChain<Map<String, Object>> comp = new ComparatorChain<>(); if (filterMap.containsKey("projectGroup") && GroupDisplay.GROUP.equals(FilteredReport.getEnumValue(filterMap.get("projectGroup")))) { comp.addComparator(new Comparator<Map<String, Object>>() { @Override public int compare(final Map<String, Object> _o1, final Map<String, Object> _o2) { final String str1 = _o1.containsKey("Project") && _o1.get("Project") != null ? (String) _o1 .get("Project") : ""; final String str2 = _o2.containsKey("Project") && _o2.get("Project") != null ? (String) _o2 .get("Project") : ""; return str1.compareTo(str2); } }); } if (filterMap.containsKey("departmentGroup") && !GroupDisplay.NONE.equals( FilteredReport.getEnumValue(filterMap.get("departmentGroup")))) { comp.addComparator(new Comparator<Map<String, Object>>() { @Override public int compare(final Map<String, Object> _o1, final Map<String, Object> _o2) { final String str1 = _o1.containsKey("Department") && _o1.get("Department") != null ? (String) _o1.get("Department") : ""; final String str2 = _o2.containsKey("Department") && _o2.get("Department") != null ? (String) _o2.get("Department") : ""; return str1.compareTo(str2); } }); } comp.addComparator(new Comparator<Map<String, Object>>() { @Override public int compare(final Map<String, Object> _o1, final Map<String, Object> _o2) { final String str1 = _o1.containsKey("EmployeeAbstractLink") && _o1.get("EmployeeAbstractLink") != null ? (String) _o1 .get("EmployeeAbstractLink") : ""; final String str2 = _o2.containsKey("EmployeeAbstractLink") && _o2.get("EmployeeAbstractLink") != null ? (String) _o2 .get("EmployeeAbstractLink") : ""; return str1.compareTo(str2); } }); comp.addComparator(new Comparator<Map<String, Object>>() { @Override public int compare(final Map<String, Object> _o1, final Map<String, Object> _o2) { final String str1 = _o1.containsKey("Name") && _o1.get("Name") != null ? (String) _o1 .get("Name") : ""; final String str2 = _o2.containsKey("Name") && _o2.get("Name") != null ? (String) _o2 .get("Name") : ""; return str1.compareTo(str2); } }); Collections.sort(values, comp); return new JRMapCollectionDataSource(new ArrayList<Map<String, ?>>(values)); } /** * @param _parameter Parameter as passed by the eFaps API * @throws EFapsException on error * @return QueryBuilder */ protected QueryBuilder getAttrQueryBuilder(final Parameter _parameter) throws EFapsException { final Map<String, Object> filterMap = getFilterReport().getFilterMap(_parameter); QueryBuilder ret = null; boolean added = false; if (filterMap.containsKey("type")) { final TypeFilterValue filter = (TypeFilterValue) filterMap.get("type"); if (!filter.getObject().isEmpty()) { for (final Long obj : filter.getObject()) { final Type type = Type.get(obj); if (!added) { added = true; ret = new QueryBuilder(type); } else { ret.addType(type); } } } } if (!added) { ret = new QueryBuilder(CIPayroll.DocumentAbstract); } if (filterMap.containsKey("dateFrom")) { final DateTime date = (DateTime) filterMap.get("dateFrom"); ret.addWhereAttrGreaterValue(CIPayroll.DocumentAbstract.Date, date.withTimeAtStartOfDay().minusSeconds(1)); } if (filterMap.containsKey("dateTo")) { final DateTime date = (DateTime) filterMap.get("dateTo"); ret.addWhereAttrLessValue(CIPayroll.DocumentAbstract.Date, date.withTimeAtStartOfDay().plusDays(1)); } if (filterMap.containsKey("status")) { final StatusFilterValue filter = (StatusFilterValue) filterMap.get("status"); if (!filter.getObject().isEmpty()) { // the documents have the same status keys but must be selected final Set<Status> status = new HashSet<>(); for (final Long obj : filter.getObject()) { final String key = Status.get(obj).getKey(); status.add(Status.find(CIPayroll.PayslipStatus, key)); status.add(Status.find(CIPayroll.AdvanceStatus, key)); status.add(Status.find(CIPayroll.SettlementStatus, key)); } ret.addWhereAttrEqValue(CIPayroll.DocumentAbstract.StatusAbstract, status.toArray()); } } if (filterMap.containsKey("employee")) { final InstanceFilterValue filter = (InstanceFilterValue) filterMap.get("employee"); if (filter.getObject() != null && filter.getObject().isValid()) { ret.addWhereAttrEqValue(CIPayroll.DocumentAbstract.EmployeeAbstractLink, filter.getObject()); } } return ret; } /** * @param _parameter Parameter as passed by the eFaps API * @param _queryBldr queryBldr to add to * @throws EFapsException on error */ protected void add2QueryBuilder(final Parameter _parameter, final QueryBuilder _queryBldr) throws EFapsException { _queryBldr.addWhereAttrInQuery(CIPayroll.PositionAbstract.DocumentAbstractLink, getAttrQueryBuilder(_parameter).getAttributeQuery(CISales.DocumentAbstract.ID)); } @Override protected void addColumnDefintion(final Parameter _parameter, final JasperReportBuilder _builder) throws EFapsException { final Map<String, Object> filterMap = getFilterReport().getFilterMap(_parameter); final List<ColumnGridComponentBuilder> groups = new ArrayList<>(); ColumnGroupBuilder projectGroup = null; if (filterMap.containsKey("projectGroup") && !GroupDisplay.NONE.equals(FilteredReport.getEnumValue(filterMap.get("projectGroup")))) { final TextColumnBuilder<String> col = DynamicReports.col.column(getLabel("Project"), "Project", DynamicReports.type.stringType()) .setStyle(DynamicReports.stl.style().setBackgroundColor(Color.yellow)); _builder.addColumn(col); if (GroupDisplay.GROUP.equals(FilteredReport.getEnumValue(filterMap.get("projectGroup")))) { projectGroup = DynamicReports.grp.group(col); _builder.addGroup(projectGroup); } else { groups.add(col); } } ColumnGroupBuilder departmentGroup = null; if (filterMap.containsKey("departmentGroup") && !GroupDisplay.NONE.equals( FilteredReport.getEnumValue(filterMap.get("departmentGroup")))) { final TextColumnBuilder<String> col = DynamicReports.col.column(getLabel("Department"), "Department", DynamicReports.type.stringType()); _builder.addColumn(col); if (GroupDisplay.GROUP.equals(FilteredReport.getEnumValue(filterMap.get("departmentGroup")))) { departmentGroup = DynamicReports.grp.group(col); _builder.addGroup(departmentGroup); } else { groups.add(col); } } DetailsDisplay details = DetailsDisplay.STANDART; if (filterMap.containsKey("details")) { details = FilteredReport.getEnumValue(filterMap.get("details")); } final TextColumnBuilder<String> nameCol = DynamicReports.col.column(getLabel("Name"), CIPayroll.DocumentAbstract.Name.name, DynamicReports.type.stringType()); final TextColumnBuilder<String> employeeCol = DynamicReports.col.column(getLabel("Employee"), CIPayroll.DocumentAbstract.EmployeeAbstractLink.name, DynamicReports.type.stringType()) .setWidth(200); final TextColumnBuilder<String> employeeNumCol = DynamicReports.col.column(getLabel("EmployeeNumber"), "EmployeeNumber", DynamicReports.type.stringType()); _builder.addColumn(nameCol, employeeCol, employeeNumCol); groups.add(nameCol); groups.add(employeeCol); groups.add(employeeNumCol); addColumns(_parameter, _builder, groups); final TextColumnBuilder<BigDecimal> remCol = DynamicReports.col.column(getLabel("Remuneration"), "Remuneration", DynamicReports.type.bigDecimalType()); final TextColumnBuilder<BigDecimal> ltCol; if (!DetailsDisplay.NONE.equals(details)) { ltCol = DynamicReports.col.column(getLabel("LaborTime"), CIPayroll.DocumentAbstract.LaborTime.name, DynamicReports.type.bigDecimalType()); } else { ltCol = DynamicReports.col.column(getLabel("LaborTimeDays"), CIPayroll.DocumentAbstract.LaborTime.name, DynamicReports.type.bigDecimalType()); } final TextColumnBuilder<BigDecimal> eltCol = DynamicReports.col.column(getLabel("ExtraLaborTime"), CIPayroll.DocumentAbstract.ExtraLaborTime.name, DynamicReports.type.bigDecimalType()); final TextColumnBuilder<BigDecimal> nltCol = DynamicReports.col.column(getLabel("NightLaborTime"), CIPayroll.DocumentAbstract.NightLaborTime.name, DynamicReports.type.bigDecimalType()); final TextColumnBuilder<BigDecimal> hltCol = DynamicReports.col.column(getLabel("HolidayLaborTime"), CIPayroll.DocumentAbstract.HolidayLaborTime.name, DynamicReports.type.bigDecimalType()); _builder.addColumn(remCol, ltCol, eltCol, nltCol, hltCol); groups.add(remCol); groups.add(ltCol); groups.add(eltCol); groups.add(nltCol); groups.add(hltCol); final Map<String, ColumnTitleGroupBuilder> groupMap = new LinkedHashMap<>(); groupMap.put(CIPayroll.PositionPayment.getType().getLabel(), DynamicReports.grid.titleGroup(CIPayroll.PositionPayment.getType().getLabel())); groupMap.put(CIPayroll.PositionDeduction.getType().getLabel(), DynamicReports.grid.titleGroup(CIPayroll.PositionDeduction.getType().getLabel())); groupMap.put(CIPayroll.PositionNeutral.getType().getLabel(), DynamicReports.grid.titleGroup(CIPayroll.PositionNeutral.getType().getLabel())); final Map<String, Set<String>> keyMap = new HashMap<>(); for (final Column column : getColumns(_parameter)) { final TextColumnBuilder<BigDecimal> column1 = DynamicReports.col.column(column.getLabel(), column.getKey(), DynamicReports.type.bigDecimalType()); if (!DetailsDisplay.NONE.equals(details)) { column1.setTitleHeight(100); Set<String> keySet; if (keyMap.containsKey(column.getGroup())) { keySet = keyMap.get(column.getGroup()); } else { keySet = new HashSet<>(); keyMap.put(column.getGroup(), keySet); } keySet.add(column.getKey()); } _builder.addColumn(column1); if (groupMap.containsKey(column.getGroup())) { groupMap.get(column.getGroup()).add(column1); } if (departmentGroup != null) { final AggregationSubtotalBuilder<BigDecimal> sum = DynamicReports.sbt.sum(column1); _builder.addSubtotalAtGroupFooter(departmentGroup, sum); } if (projectGroup != null) { final AggregationSubtotalBuilder<BigDecimal> sum = DynamicReports.sbt.sum(column1); _builder.addSubtotalAtGroupFooter(projectGroup, sum); } final AggregationSubtotalBuilder<BigDecimal> sum = DynamicReports.sbt.sum(column1); _builder.addSubtotalAtColumnFooter(sum); } final TextColumnBuilder<BigDecimal> crossCol = DynamicReports.col.column(getLabel("CrossTotal"), CIPayroll.DocumentAbstract.CrossTotal.name, DynamicReports.type.bigDecimalType()); final TextColumnBuilder<BigDecimal> amountCol = DynamicReports.col.column(getLabel("AmountCost"), CIPayroll.DocumentAbstract.AmountCost.name, DynamicReports.type.bigDecimalType()); _builder.addColumn(crossCol, amountCol); if (!DetailsDisplay.NONE.equals(details)) { for (final Entry<String, ColumnTitleGroupBuilder> entry : groupMap.entrySet()) { if (!entry.getValue().getColumnGridTitleGroup().getList().getListCells().isEmpty()) { final TextColumnBuilder<BigDecimal> col = DynamicReports.col.column(new SumExpression( keyMap.get(entry.getKey()))).setDataType(type.bigDecimalType()) .setTitle(getLabel("Total")); _builder.addColumn(col); entry.getValue().add(col); groups.add(entry.getValue()); if (departmentGroup != null) { final AggregationSubtotalBuilder<BigDecimal> colTotal = DynamicReports.sbt.sum(col); _builder.addSubtotalAtGroupFooter(departmentGroup, colTotal); } if (projectGroup != null) { final AggregationSubtotalBuilder<BigDecimal> colTotal = DynamicReports.sbt.sum(col); _builder.addSubtotalAtGroupFooter(projectGroup, colTotal); } final AggregationSubtotalBuilder<BigDecimal> colTotal = DynamicReports.sbt.sum(col); _builder.addSubtotalAtColumnFooter(colTotal); } } groups.add(crossCol); groups.add(amountCol); _builder.columnGrid(groups.toArray(new ColumnGridComponentBuilder[groups.size()])); } if (departmentGroup != null) { final AggregationSubtotalBuilder<BigDecimal> crossTotal = DynamicReports.sbt.sum(crossCol); final AggregationSubtotalBuilder<BigDecimal> amountTotal = DynamicReports.sbt.sum(amountCol); _builder.addSubtotalAtGroupFooter(departmentGroup, crossTotal); _builder.addSubtotalAtGroupFooter(departmentGroup, amountTotal); } if (projectGroup != null) { final AggregationSubtotalBuilder<BigDecimal> crossTotal = DynamicReports.sbt.sum(crossCol); final AggregationSubtotalBuilder<BigDecimal> amountTotal = DynamicReports.sbt.sum(amountCol); _builder.addSubtotalAtGroupFooter(projectGroup, crossTotal); _builder.addSubtotalAtGroupFooter(projectGroup, amountTotal); } final AggregationSubtotalBuilder<BigDecimal> crossTotal = DynamicReports.sbt.sum(crossCol); final AggregationSubtotalBuilder<BigDecimal> amountTotal = DynamicReports.sbt.sum(amountCol); _builder.addSubtotalAtColumnFooter(crossTotal); _builder.addSubtotalAtColumnFooter(amountTotal); } /** * @param _parameter * @param _builder * @param _groups */ protected void addColumns(final Parameter _parameter, final JasperReportBuilder _builder, final List<ColumnGridComponentBuilder> _groups) throws EFapsException { final Map<String, Object> filterMap = getFilterReport().getFilterMap(_parameter); DetailsDisplay details = DetailsDisplay.STANDART; if (filterMap.containsKey("details")) { details = FilteredReport.getEnumValue(filterMap.get("details")); } if (DetailsDisplay.EXTRA.equals(details)) { final TextColumnBuilder<String> pRCol = DynamicReports.col.column(getLabel("PensionRegime"), "pensionRegime", DynamicReports.type.stringType()); final TextColumnBuilder<String> prTpCol = DynamicReports.col.column(getLabel("PensionRegimeType"), "pensionRegimeType", DynamicReports.type.stringType()); final TextColumnBuilder<DateTime> sdCol = DynamicReports.col.column(getLabel("StartDate"), "startDate", DateTimeDate.get()); final TextColumnBuilder<String> perCol = DynamicReports.col.column(getLabel("Periodicity"), "periodicity", DynamicReports.type.stringType()); final TextColumnBuilder<String> emplEmplCol = DynamicReports.col.column(getLabel("Employ"), "emplEmpl", DynamicReports.type.stringType()); final TextColumnBuilder<String> emplActCol = DynamicReports.col.column(getLabel("Activation"), "emplAct", DynamicReports.type.stringType()); _builder.addColumn(pRCol, prTpCol, sdCol, perCol, emplEmplCol, emplActCol); _groups.add(pRCol); _groups.add(prTpCol); _groups.add(sdCol); _groups.add(perCol); _groups.add(emplEmplCol); _groups.add(emplActCol); } } /** * Getter method for the instance variable {@link #filterReport}. * * @return value of instance variable {@link #filterReport} */ public PositionAnalyzeReport_Base getFilterReport() { return this.filterReport; } /** * @param _key key the label is wanted for * @return label */ protected String getLabel(final String _key) { return DBProperties.getProperty(PositionAnalyzeReport.class.getName() + "." + _key); } /** * Getter method for the instance variable {@link #columns}. * * @param _parameter Parameter as passed by the eFaps API * @return value of instance variable {@link #columns} * @throws EFapsException on error */ public List<Column> getColumns(final Parameter _parameter) throws EFapsException { if (this.columns == null) { getData(_parameter); } return this.columns; } } /** * Column class. */ public static class Column { /** * Key. */ private String key; /** * Label. */ private String label; /** * Group. */ private String group; /** * Getter method for the instance variable {@link #key}. * * @return value of instance variable {@link #key} */ public String getKey() { return this.key; } /** * Setter method for instance variable {@link #key}. * * @param _key value for instance variable {@link #key} */ public void setKey(final String _key) { this.key = _key; } /** * Getter method for the instance variable {@link #label}. * * @return value of instance variable {@link #label} */ public String getLabel() { return this.label; } /** * Setter method for instance variable {@link #label}. * * @param _label value for instance variable {@link #label} */ public void setLabel(final String _label) { this.label = _label; } @Override public boolean equals(final Object _obj) { boolean ret; if (_obj instanceof Column) { ret = getKey().equals(((Column) _obj).getKey()); } else { ret = super.equals(_obj); } return ret; } @Override public int hashCode() { return super.hashCode(); } /** * Getter method for the instance variable {@link #group}. * * @return value of instance variable {@link #group} */ public String getGroup() { return this.group; } /** * Setter method for instance variable {@link #group}. * * @param _group value for instance variable {@link #group} */ public void setGroup(final String _group) { this.group = _group; } } /** * Expression to get the sum. */ public static class SumExpression extends AbstractSimpleExpression<BigDecimal> { /** * Needed for serialization. */ private static final long serialVersionUID = 1L; /** * Set of keys. */ private final Set<String> keys; /** * @param _keys key set */ public SumExpression(final Set<String> _keys) { this.keys = _keys; } @Override public BigDecimal evaluate(final ReportParameters _reportParameters) { BigDecimal ret = BigDecimal.ZERO; for (final String key : this.keys) { final Object value = _reportParameters.getFieldValue(key); if (value != null && value instanceof BigDecimal) { ret = ret.add((BigDecimal) value); } } return ret; } } }
src/main/efaps/ESJP/org/efaps/esjp/payroll/reports/PositionAnalyzeReport_Base.java
/* * Copyright 2003 - 2014 The eFaps Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Revision: $Rev$ * Last Changed: $Date$ * Last Changed By: $Author$ */ package org.efaps.esjp.payroll.reports; import static net.sf.dynamicreports.report.builder.DynamicReports.type; import java.awt.Color; import java.io.File; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.UUID; import net.sf.dynamicreports.jasper.builder.JasperReportBuilder; import net.sf.dynamicreports.report.base.expression.AbstractSimpleExpression; import net.sf.dynamicreports.report.builder.DynamicReports; import net.sf.dynamicreports.report.builder.column.TextColumnBuilder; import net.sf.dynamicreports.report.builder.grid.ColumnGridComponentBuilder; import net.sf.dynamicreports.report.builder.grid.ColumnTitleGroupBuilder; import net.sf.dynamicreports.report.builder.group.ColumnGroupBuilder; import net.sf.dynamicreports.report.builder.style.StyleBuilder; import net.sf.dynamicreports.report.builder.subtotal.AggregationSubtotalBuilder; import net.sf.dynamicreports.report.definition.ReportParameters; import net.sf.jasperreports.engine.JRDataSource; import net.sf.jasperreports.engine.data.JRMapCollectionDataSource; import org.apache.commons.collections4.comparators.ComparatorChain; import org.efaps.admin.common.MsgPhrase; import org.efaps.admin.datamodel.IEnum; import org.efaps.admin.datamodel.Status; import org.efaps.admin.datamodel.Type; import org.efaps.admin.dbproperty.DBProperties; import org.efaps.admin.event.Parameter; import org.efaps.admin.event.Parameter.ParameterValues; import org.efaps.admin.event.Return; import org.efaps.admin.event.Return.ReturnValues; import org.efaps.db.Instance; import org.efaps.db.MultiPrintQuery; import org.efaps.db.QueryBuilder; import org.efaps.db.SelectBuilder; import org.efaps.esjp.ci.CIHumanResource; import org.efaps.esjp.ci.CIPayroll; import org.efaps.esjp.ci.CIProjects; import org.efaps.esjp.ci.CISales; import org.efaps.esjp.common.jasperreport.AbstractDynamicReport; import org.efaps.esjp.common.jasperreport.datatype.DateTimeDate; import org.efaps.esjp.erp.FilteredReport; import org.efaps.esjp.sales.report.DocumentSumReport; import org.efaps.ui.wicket.util.EnumUtil; import org.efaps.util.EFapsException; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * TODO comment! * * @author The eFaps Team * @version $Id: PositionAnalyzeReport_Base.java 14584 2014-12-04 03:55:22Z * [email protected] $ */ public abstract class PositionAnalyzeReport_Base extends FilteredReport { /** * Logging instance used in this class. */ private static final Logger LOG = LoggerFactory.getLogger(PositionAnalyzeReport.class); /** * Enum used for display. */ public enum DetailsDisplay { /** Display as Column. */ STANDART, /** No display. */ NONE, /** Display as Group. */ EXTRA; } /** * @param _parameter Parameter as passed by the eFasp API * @return Return containing html snipplet * @throws EFapsException on error */ public Return generateReport(final Parameter _parameter) throws EFapsException { final Return ret = new Return(); final AbstractDynamicReport dyRp = getReport(_parameter); final String html = dyRp.getHtmlSnipplet(_parameter); ret.put(ReturnValues.SNIPLETT, html); return ret; } /** * @param _parameter Parameter as passed by the eFasp API * @return Return containing the file * @throws EFapsException on error */ public Return exportReport(final Parameter _parameter) throws EFapsException { final Return ret = new Return(); final Map<?, ?> props = (Map<?, ?>) _parameter.get(ParameterValues.PROPERTIES); final String mime = (String) props.get("Mime"); final AbstractDynamicReport dyRp = getReport(_parameter); dyRp.setFileName(DBProperties.getProperty(DocumentSumReport.class.getName() + ".FileName")); File file = null; if ("xls".equalsIgnoreCase(mime)) { file = dyRp.getExcel(_parameter); } else if ("pdf".equalsIgnoreCase(mime)) { file = dyRp.getPDF(_parameter); } ret.put(ReturnValues.VALUES, file); ret.put(ReturnValues.TRUE, true); return ret; } @Override protected Object getDefaultValue(final Parameter _parameter, final String _field, final String _type, final String _default) throws EFapsException { Object ret; if ("Status".equalsIgnoreCase(_type)) { final Set<Long> set = new HashSet<>(); set.add(Status.find(CIPayroll.PayslipStatus.Draft).getId()); ret = new StatusFilterValue().setObject(set); } else { ret = super.getDefaultValue(_parameter, _field, _type, _default); } return ret; } /** * @param _parameter Parameter as passed by the eFasp API * @return the report class * @throws EFapsException on error */ protected AbstractDynamicReport getReport(final Parameter _parameter) throws EFapsException { return new DynPositionAnalyzeReport(this); } /** * Dynamic Report. */ public static class DynPositionAnalyzeReport extends AbstractDynamicReport { /** * Filtered Report. */ private final PositionAnalyzeReport_Base filterReport; /** * Data for the positions. */ private Map<Instance, Map<String, Object>> data; /** * List of columns. */ private List<Column> columns; /** * @param _filterReport report */ public DynPositionAnalyzeReport(final PositionAnalyzeReport_Base _filterReport) { this.filterReport = _filterReport; } @Override protected StyleBuilder getColumnStyle4Html(final Parameter _parameter) throws EFapsException { return super.getColumnStyle4Html(_parameter).setBorder(DynamicReports.stl.pen1Point()); } /** * Getter method for the instance variable {@link #data}. * * @param _parameter Paramdeter as passed by the eFaps API * @return value of instance variable {@link #data} * @throws EFapsException on error */ public Map<Instance, Map<String, Object>> getData(final Parameter _parameter) throws EFapsException { if (this.data == null) { this.data = new HashMap<>(); final Map<String, Column> columnMap = new HashMap<>(); final Map<String, Object> filterMap = getFilterReport().getFilterMap(_parameter); final boolean project = filterMap.containsKey("projectGroup") && !GroupDisplay.NONE.equals(FilteredReport.getEnumValue(filterMap.get("projectGroup"))); //Payroll_Employee4DocumentMsgPhrase final MsgPhrase msgPhrase = MsgPhrase.get(UUID.fromString("4bf03526-3616-4e57-ad70-1e372029ea9e")); MsgPhrase msgPhrase4Project = null; if (project) { // Project_ProjectMsgPhrase msgPhrase4Project = MsgPhrase.get(UUID .fromString("64c30826-cb22-4579-a3d5-bd10090f155e")); } DetailsDisplay details = DetailsDisplay.STANDART; if (filterMap.containsKey("details")) { details = FilteredReport.getEnumValue(filterMap.get("details")); } final QueryBuilder queryBuilder = new QueryBuilder(CIPayroll.PositionDeduction); queryBuilder.addType(CIPayroll.PositionNeutral, CIPayroll.PositionPayment); add2QueryBuilder(_parameter, queryBuilder); final MultiPrintQuery multi = queryBuilder.getPrint(); final SelectBuilder selDoc = SelectBuilder.get() .linkto(CIPayroll.PositionAbstract.DocumentAbstractLink); final SelectBuilder selDocInst = new SelectBuilder(selDoc).instance(); final SelectBuilder selDocName = new SelectBuilder(selDoc).attribute(CIPayroll.DocumentAbstract.Name); final SelectBuilder selCrossTotal = new SelectBuilder(selDoc) .attribute(CIPayroll.DocumentAbstract.CrossTotal); final SelectBuilder selAmountCost = new SelectBuilder(selDoc) .attribute(CIPayroll.DocumentAbstract.AmountCost); final SelectBuilder selDocELT = new SelectBuilder(selDoc) .attribute(CIPayroll.DocumentAbstract.ExtraLaborTime); final SelectBuilder selDocHLT = new SelectBuilder(selDoc) .attribute(CIPayroll.DocumentAbstract.HolidayLaborTime); final SelectBuilder selDocLT = new SelectBuilder(selDoc) .attribute(CIPayroll.DocumentAbstract.LaborTime); final SelectBuilder selDocNLT = new SelectBuilder(selDoc) .attribute(CIPayroll.DocumentAbstract.NightLaborTime); final SelectBuilder selDepName = new SelectBuilder(selDoc) .linkto(CIPayroll.DocumentAbstract.EmployeeAbstractLink) .linkfrom(CIHumanResource.Department2EmployeeAdminister.EmployeeLink) .linkto(CIHumanResource.Department2EmployeeAdminister.DepartmentLink) .attribute(CIHumanResource.Department.Name); final SelectBuilder selRemun = new SelectBuilder(selDoc) .linkto(CIPayroll.DocumentAbstract.EmployeeAbstractLink) .clazz(CIHumanResource.ClassTR_Labor) .attribute(CIHumanResource.ClassTR_Labor.Remuneration); final SelectBuilder selProj = new SelectBuilder(selDoc) .linkfrom(CIProjects.Project2DocumentAbstract.ToAbstract) .linkto(CIProjects.Project2DocumentAbstract.FromAbstract); final SelectBuilder selEmplNum = new SelectBuilder(selDoc) .linkto(CIPayroll.DocumentAbstract.EmployeeAbstractLink) .attribute(CIHumanResource.Employee.Number); if (project) { multi.addMsgPhrase(selProj, msgPhrase4Project); } SelectBuilder selEmplPR = null; SelectBuilder selEmplPRT = null; SelectBuilder selEmplST = null; SelectBuilder selPeri = null; SelectBuilder selEmplEmpl = null; SelectBuilder selEmplAct = null; if (DetailsDisplay.EXTRA.equals(details)) { selEmplPR = new SelectBuilder(selDoc) .linkto(CIPayroll.DocumentAbstract.EmployeeAbstractLink) .clazz(CIHumanResource.ClassTR_Health) .linkto(CIHumanResource.ClassTR_Health.PensionRegimeLink) .attribute(CIHumanResource.AttributeDefinitionPensionRegime.Value); selEmplPRT = new SelectBuilder(selDoc) .linkto(CIPayroll.DocumentAbstract.EmployeeAbstractLink) .clazz(CIHumanResource.ClassTR_Health) .linkto(CIHumanResource.ClassTR_Health.PensionRegimeTypeLink) .attribute(CIHumanResource.AttributeDefinitionPensionRegimeType.Value); selEmplST = new SelectBuilder(selDoc) .linkto(CIPayroll.DocumentAbstract.EmployeeAbstractLink) .clazz(CIHumanResource.ClassTR).attribute(CIHumanResource.ClassTR.StartDate); selPeri = new SelectBuilder(selDoc) .linkto(CIPayroll.DocumentAbstract.EmployeeAbstractLink) .clazz(CIHumanResource.ClassTR_Labor) .linkto(CIHumanResource.ClassTR_Labor.PeriodicityLink) .attribute(CIHumanResource.AttributeDefinitionPeriodicity.Value); selEmplEmpl = new SelectBuilder(selDoc) .linkto(CIPayroll.DocumentAbstract.EmployeeAbstractLink) .linkto(CIHumanResource.Employee.EmployLink) .attribute(CIHumanResource.AttributeDefinitionEmploy.Value); selEmplAct = new SelectBuilder(selDoc) .linkto(CIPayroll.DocumentAbstract.EmployeeAbstractLink) .attribute(CIHumanResource.Employee.Activation); multi.addSelect(selEmplPR, selEmplPRT, selEmplST, selPeri, selEmplEmpl, selEmplAct); } multi.addMsgPhrase(selDoc, msgPhrase); multi.addSelect(selCrossTotal, selAmountCost, selDocInst, selDocName, selDepName, selDocELT, selDocHLT, selDocLT, selDocNLT, selRemun, selEmplNum); multi.addAttribute(CIPayroll.PositionAbstract.Amount, CIPayroll.PositionAbstract.Description, CIPayroll.PositionAbstract.Key); multi.execute(); while (multi.next()) { final Instance docInst = multi.getSelect(selDocInst); Map<String, Object> map; if (this.data.containsKey(docInst)) { map = this.data.get(docInst); } else { map = new HashMap<>(); this.data.put(docInst, map); map.put("Remuneration", multi.getSelect(selRemun)); map.put(CIPayroll.DocumentAbstract.Name.name, multi.getSelect(selDocName)); map.put(CIPayroll.DocumentAbstract.CrossTotal.name, multi.getSelect(selCrossTotal)); map.put(CIPayroll.DocumentAbstract.AmountCost.name, multi.getSelect(selAmountCost)); final BigDecimal laborTime = (BigDecimal) multi.<Object[]>getSelect(selDocLT)[0]; if (!DetailsDisplay.NONE.equals(details)) { map.put(CIPayroll.DocumentAbstract.LaborTime.name, laborTime); } else { map.put(CIPayroll.DocumentAbstract.LaborTime.name, laborTime.divide(BigDecimal.valueOf(8), BigDecimal.ROUND_HALF_UP)); } map.put(CIPayroll.DocumentAbstract.ExtraLaborTime.name, multi.<Object[]>getSelect(selDocELT)[0]); map.put(CIPayroll.DocumentAbstract.HolidayLaborTime.name, multi.<Object[]>getSelect(selDocHLT)[0]); map.put(CIPayroll.DocumentAbstract.NightLaborTime.name, multi.<Object[]>getSelect(selDocNLT)[0]); map.put(CIPayroll.DocumentAbstract.EmployeeAbstractLink.name, multi.getMsgPhrase(selDoc, msgPhrase)); map.put("Department", multi.getSelect(selDepName)); map.put("EmployeeNumber", multi.getSelect(selEmplNum)); if (project) { map.put("Project", multi.getMsgPhrase(selProj, msgPhrase4Project)); } if (DetailsDisplay.EXTRA.equals(details)) { map.put("pensionRegimeType", multi.getSelect(selEmplPRT)); map.put("pensionRegime", multi.getSelect(selEmplPR)); map.put("startDate", multi.getSelect(selEmplST)); map.put("periodicity", multi.getSelect(selPeri)); map.put("emplEmpl", multi.getSelect(selEmplEmpl)); final Object valueTmp = multi.getSelect(selEmplAct); if (valueTmp != null && valueTmp instanceof List) { final StringBuilder bldr = new StringBuilder(); boolean first = true; for (final Object obj : (List<?>) valueTmp) { if (first) { first = false; } else { bldr.append(", "); } bldr.append(EnumUtil.getUILabel((IEnum) obj)); } map.put("emplAct", bldr.toString()); } } PositionAnalyzeReport_Base.LOG.debug("Read: {}", map); } if (!DetailsDisplay.NONE.equals(details)) { final String key = multi.getAttribute(CIPayroll.PositionAbstract.Key); if (!columnMap.containsKey(key)) { final Column col = new Column(); columnMap.put(key, col); col.setKey(key); final String descr = multi.getAttribute(CIPayroll.PositionAbstract.Description); col.setLabel(key + " - " + descr); col.setGroup(multi.getCurrentInstance().getType().getLabel()); } map.put(key, multi.getAttribute(CIPayroll.PositionAbstract.Amount)); } else { final String key = multi.getCurrentInstance().getType().getName(); if (map.containsKey(key)) { map.put(key, ((BigDecimal) map.get(key)).add(multi .<BigDecimal>getAttribute(CIPayroll.PositionAbstract.Amount))); } else { final Column col = new Column(); columnMap.put(key, col); col.setKey(key); col.setLabel(multi.getCurrentInstance().getType().getLabel()); col.setGroup(multi.getCurrentInstance().getType().getLabel()); map.put(key, multi.getAttribute(CIPayroll.PositionAbstract.Amount)); } } } // Artificially add the one that do not have positions (happens with manually created advances) final QueryBuilder docQueryBldr = getAttrQueryBuilder(_parameter); final QueryBuilder attrQueryBuilder = new QueryBuilder(CIPayroll.PositionDeduction); attrQueryBuilder.addType(CIPayroll.PositionNeutral, CIPayroll.PositionPayment); docQueryBldr.addWhereAttrNotInQuery(CIPayroll.DocumentAbstract.ID, attrQueryBuilder.getAttributeQuery(CIPayroll.PositionAbstract.DocumentAbstractLink)); final MultiPrintQuery docMulti = docQueryBldr.getPrint(); final SelectBuilder selRemun4Doc = SelectBuilder.get() .linkto(CIPayroll.DocumentAbstract.EmployeeAbstractLink) .clazz(CIHumanResource.ClassTR_Labor) .attribute(CIHumanResource.ClassTR_Labor.Remuneration); final SelectBuilder selProj4Doc = SelectBuilder.get() .linkfrom(CIProjects.Project2DocumentAbstract.ToAbstract) .linkto(CIProjects.Project2DocumentAbstract.FromAbstract); final SelectBuilder selEmplNum4Doc = SelectBuilder.get() .linkto(CIPayroll.DocumentAbstract.EmployeeAbstractLink) .attribute(CIHumanResource.Employee.Number); final SelectBuilder selDepName4Doc = SelectBuilder.get() .linkto(CIPayroll.DocumentAbstract.EmployeeAbstractLink) .linkfrom(CIHumanResource.Department2EmployeeAdminister.EmployeeLink) .linkto(CIHumanResource.Department2EmployeeAdminister.DepartmentLink) .attribute(CIHumanResource.Department.Name); if (project) { multi.addMsgPhrase(selProj4Doc, msgPhrase4Project); } docMulti.addMsgPhrase(msgPhrase); docMulti.addSelect(selDepName4Doc, selRemun4Doc, selEmplNum4Doc); docMulti.addAttribute(CIPayroll.DocumentAbstract.Name, CIPayroll.DocumentAbstract.AmountCost, CIPayroll.DocumentAbstract.CrossTotal, CIPayroll.DocumentAbstract.LaborTime, CIPayroll.DocumentAbstract.ExtraLaborTime, CIPayroll.DocumentAbstract.NightLaborTime, CIPayroll.DocumentAbstract.HolidayLaborTime); docMulti.execute(); while (docMulti.next()) { final Map<String, Object> map = new HashMap<>(); this.data.put(docMulti.getCurrentInstance(), map); map.put("Remuneration", docMulti.getSelect(selRemun4Doc)); map.put(CIPayroll.DocumentAbstract.Name.name, docMulti.getAttribute(CIPayroll.DocumentAbstract.Name)); map.put(CIPayroll.DocumentAbstract.CrossTotal.name, docMulti.getAttribute(CIPayroll.DocumentAbstract.CrossTotal)); map.put(CIPayroll.DocumentAbstract.AmountCost.name, docMulti.getAttribute(CIPayroll.DocumentAbstract.AmountCost)); final BigDecimal laborTime = (BigDecimal) docMulti .<Object[]>getAttribute(CIPayroll.DocumentAbstract.LaborTime)[0]; if (!DetailsDisplay.NONE.equals(details)) { map.put(CIPayroll.DocumentAbstract.LaborTime.name, laborTime); } else { map.put(CIPayroll.DocumentAbstract.LaborTime.name, laborTime.divide(BigDecimal.valueOf(8), BigDecimal.ROUND_HALF_UP)); } map.put(CIPayroll.DocumentAbstract.ExtraLaborTime.name, docMulti.<Object[]>getAttribute(CIPayroll.DocumentAbstract.ExtraLaborTime)[0]); map.put(CIPayroll.DocumentAbstract.HolidayLaborTime.name, docMulti.<Object[]>getAttribute(CIPayroll.DocumentAbstract.HolidayLaborTime)[0]); map.put(CIPayroll.DocumentAbstract.NightLaborTime.name, docMulti.<Object[]>getAttribute(CIPayroll.DocumentAbstract.NightLaborTime)[0]); map.put(CIPayroll.DocumentAbstract.EmployeeAbstractLink.name, docMulti.getMsgPhrase(msgPhrase)); map.put("Department", docMulti.getSelect(selDepName4Doc)); map.put("EmployeeNumber", docMulti.getSelect(selEmplNum4Doc)); if (project) { map.put("Project", docMulti.getMsgPhrase(selProj4Doc, msgPhrase4Project)); } } this.columns = new ArrayList<>(columnMap.values()); if (!DetailsDisplay.NONE.equals(details)) { Collections.sort(this.columns, new Comparator<Column>() { @Override public int compare(final Column _arg0, final Column _arg1) { return _arg0.getLabel().compareTo(_arg1.getLabel()); } }); } } return this.data; } @Override protected JRDataSource createDataSource(final Parameter _parameter) throws EFapsException { final Map<String, Object> filterMap = getFilterReport().getFilterMap(_parameter); final Map<Instance, Map<String, Object>> maps = getData(_parameter); final List<Map<String, Object>> values = new ArrayList<>(maps.values()); final ComparatorChain<Map<String, Object>> comp = new ComparatorChain<>(); if (filterMap.containsKey("projectGroup") && GroupDisplay.GROUP.equals(FilteredReport.getEnumValue(filterMap.get("projectGroup")))) { comp.addComparator(new Comparator<Map<String, Object>>() { @Override public int compare(final Map<String, Object> _o1, final Map<String, Object> _o2) { final String str1 = _o1.containsKey("Project") && _o1.get("Project") != null ? (String) _o1 .get("Project") : ""; final String str2 = _o2.containsKey("Project") && _o2.get("Project") != null ? (String) _o2 .get("Project") : ""; return str1.compareTo(str2); } }); } if (filterMap.containsKey("departmentGroup") && !GroupDisplay.NONE.equals( FilteredReport.getEnumValue(filterMap.get("departmentGroup")))) { comp.addComparator(new Comparator<Map<String, Object>>() { @Override public int compare(final Map<String, Object> _o1, final Map<String, Object> _o2) { final String str1 = _o1.containsKey("Department") && _o1.get("Department") != null ? (String) _o1.get("Department") : ""; final String str2 = _o2.containsKey("Department") && _o2.get("Department") != null ? (String) _o2.get("Department") : ""; return str1.compareTo(str2); } }); } comp.addComparator(new Comparator<Map<String, Object>>() { @Override public int compare(final Map<String, Object> _o1, final Map<String, Object> _o2) { final String str1 = _o1.containsKey("EmployeeAbstractLink") && _o1.get("EmployeeAbstractLink") != null ? (String) _o1 .get("EmployeeAbstractLink") : ""; final String str2 = _o2.containsKey("EmployeeAbstractLink") && _o2.get("EmployeeAbstractLink") != null ? (String) _o2 .get("EmployeeAbstractLink") : ""; return str1.compareTo(str2); } }); comp.addComparator(new Comparator<Map<String, Object>>() { @Override public int compare(final Map<String, Object> _o1, final Map<String, Object> _o2) { final String str1 = _o1.containsKey("Name") && _o1.get("Name") != null ? (String) _o1 .get("Name") : ""; final String str2 = _o2.containsKey("Name") && _o2.get("Name") != null ? (String) _o2 .get("Name") : ""; return str1.compareTo(str2); } }); Collections.sort(values, comp); return new JRMapCollectionDataSource(new ArrayList<Map<String, ?>>(values)); } /** * @param _parameter Parameter as passed by the eFaps API * @throws EFapsException on error * @return QueryBuilder */ protected QueryBuilder getAttrQueryBuilder(final Parameter _parameter) throws EFapsException { final Map<String, Object> filterMap = getFilterReport().getFilterMap(_parameter); QueryBuilder ret = null; boolean added = false; if (filterMap.containsKey("type")) { final TypeFilterValue filter = (TypeFilterValue) filterMap.get("type"); if (!filter.getObject().isEmpty()) { for (final Long obj : filter.getObject()) { final Type type = Type.get(obj); if (!added) { added = true; ret = new QueryBuilder(type); } else { ret.addType(type); } } } } if (!added) { ret = new QueryBuilder(CIPayroll.DocumentAbstract); } if (filterMap.containsKey("dateFrom")) { final DateTime date = (DateTime) filterMap.get("dateFrom"); ret.addWhereAttrGreaterValue(CIPayroll.DocumentAbstract.Date, date.withTimeAtStartOfDay().minusSeconds(1)); } if (filterMap.containsKey("dateTo")) { final DateTime date = (DateTime) filterMap.get("dateTo"); ret.addWhereAttrLessValue(CIPayroll.DocumentAbstract.Date, date.withTimeAtStartOfDay().plusDays(1)); } if (filterMap.containsKey("status")) { final StatusFilterValue filter = (StatusFilterValue) filterMap.get("status"); if (!filter.getObject().isEmpty()) { // the documents have the same status keys but must be selected final Set<Status> status = new HashSet<>(); for (final Long obj : filter.getObject()) { final String key = Status.get(obj).getKey(); status.add(Status.find(CIPayroll.PayslipStatus, key)); status.add(Status.find(CIPayroll.AdvanceStatus, key)); status.add(Status.find(CIPayroll.SettlementStatus, key)); } ret.addWhereAttrEqValue(CIPayroll.DocumentAbstract.StatusAbstract, status.toArray()); } } if (filterMap.containsKey("employee")) { final InstanceFilterValue filter = (InstanceFilterValue) filterMap.get("employee"); if (filter.getObject() != null && filter.getObject().isValid()) { ret.addWhereAttrEqValue(CIPayroll.DocumentAbstract.EmployeeAbstractLink, filter.getObject()); } } return ret; } /** * @param _parameter Parameter as passed by the eFaps API * @param _queryBldr queryBldr to add to * @throws EFapsException on error */ protected void add2QueryBuilder(final Parameter _parameter, final QueryBuilder _queryBldr) throws EFapsException { _queryBldr.addWhereAttrInQuery(CIPayroll.PositionAbstract.DocumentAbstractLink, getAttrQueryBuilder(_parameter).getAttributeQuery(CISales.DocumentAbstract.ID)); } @Override protected void addColumnDefintion(final Parameter _parameter, final JasperReportBuilder _builder) throws EFapsException { final Map<String, Object> filterMap = getFilterReport().getFilterMap(_parameter); final List<ColumnGridComponentBuilder> groups = new ArrayList<>(); ColumnGroupBuilder projectGroup = null; if (filterMap.containsKey("projectGroup") && !GroupDisplay.NONE.equals(FilteredReport.getEnumValue(filterMap.get("projectGroup")))) { final TextColumnBuilder<String> col = DynamicReports.col.column(getLabel("Project"), "Project", DynamicReports.type.stringType()) .setStyle(DynamicReports.stl.style().setBackgroundColor(Color.yellow)); _builder.addColumn(col); if (GroupDisplay.GROUP.equals(FilteredReport.getEnumValue(filterMap.get("projectGroup")))) { projectGroup = DynamicReports.grp.group(col); _builder.addGroup(projectGroup); } else { groups.add(col); } } ColumnGroupBuilder departmentGroup = null; if (filterMap.containsKey("departmentGroup") && !GroupDisplay.NONE.equals( FilteredReport.getEnumValue(filterMap.get("departmentGroup")))) { final TextColumnBuilder<String> col = DynamicReports.col.column(getLabel("Department"), "Department", DynamicReports.type.stringType()); _builder.addColumn(col); if (GroupDisplay.GROUP.equals(FilteredReport.getEnumValue(filterMap.get("departmentGroup")))) { departmentGroup = DynamicReports.grp.group(col); _builder.addGroup(departmentGroup); } else { groups.add(col); } } DetailsDisplay details = DetailsDisplay.STANDART; if (filterMap.containsKey("details")) { details = FilteredReport.getEnumValue(filterMap.get("details")); } final TextColumnBuilder<String> nameCol = DynamicReports.col.column(getLabel("Name"), CIPayroll.DocumentAbstract.Name.name, DynamicReports.type.stringType()); final TextColumnBuilder<String> employeeCol = DynamicReports.col.column(getLabel("Employee"), CIPayroll.DocumentAbstract.EmployeeAbstractLink.name, DynamicReports.type.stringType()) .setWidth(200); final TextColumnBuilder<String> employeeNumCol = DynamicReports.col.column(getLabel("EmployeeNumber"), "EmployeeNumber", DynamicReports.type.stringType()); _builder.addColumn(nameCol, employeeCol, employeeNumCol); groups.add(nameCol); groups.add(employeeCol); groups.add(employeeNumCol); addColumns(_parameter, _builder, groups); final TextColumnBuilder<BigDecimal> remCol = DynamicReports.col.column(getLabel("Remuneration"), "Remuneration", DynamicReports.type.bigDecimalType()); final TextColumnBuilder<BigDecimal> ltCol; if (!DetailsDisplay.NONE.equals(details)) { ltCol = DynamicReports.col.column(getLabel("LaborTime"), CIPayroll.DocumentAbstract.LaborTime.name, DynamicReports.type.bigDecimalType()); } else { ltCol = DynamicReports.col.column(getLabel("LaborTimeDays"), CIPayroll.DocumentAbstract.LaborTime.name, DynamicReports.type.bigDecimalType()); } final TextColumnBuilder<BigDecimal> eltCol = DynamicReports.col.column(getLabel("ExtraLaborTime"), CIPayroll.DocumentAbstract.ExtraLaborTime.name, DynamicReports.type.bigDecimalType()); final TextColumnBuilder<BigDecimal> nltCol = DynamicReports.col.column(getLabel("NightLaborTime"), CIPayroll.DocumentAbstract.NightLaborTime.name, DynamicReports.type.bigDecimalType()); final TextColumnBuilder<BigDecimal> hltCol = DynamicReports.col.column(getLabel("HolidayLaborTime"), CIPayroll.DocumentAbstract.HolidayLaborTime.name, DynamicReports.type.bigDecimalType()); _builder.addColumn(remCol, ltCol, eltCol, nltCol, hltCol); groups.add(remCol); groups.add(ltCol); groups.add(eltCol); groups.add(nltCol); groups.add(hltCol); final Map<String, ColumnTitleGroupBuilder> groupMap = new LinkedHashMap<>(); groupMap.put(CIPayroll.PositionPayment.getType().getLabel(), DynamicReports.grid.titleGroup(CIPayroll.PositionPayment.getType().getLabel())); groupMap.put(CIPayroll.PositionDeduction.getType().getLabel(), DynamicReports.grid.titleGroup(CIPayroll.PositionDeduction.getType().getLabel())); groupMap.put(CIPayroll.PositionNeutral.getType().getLabel(), DynamicReports.grid.titleGroup(CIPayroll.PositionNeutral.getType().getLabel())); final Map<String, Set<String>> keyMap = new HashMap<>(); for (final Column column : getColumns(_parameter)) { final TextColumnBuilder<BigDecimal> column1 = DynamicReports.col.column(column.getLabel(), column.getKey(), DynamicReports.type.bigDecimalType()); if (!DetailsDisplay.NONE.equals(details)) { column1.setTitleHeight(100); Set<String> keySet; if (keyMap.containsKey(column.getGroup())) { keySet = keyMap.get(column.getGroup()); } else { keySet = new HashSet<>(); keyMap.put(column.getGroup(), keySet); } keySet.add(column.getKey()); } _builder.addColumn(column1); if (groupMap.containsKey(column.getGroup())) { groupMap.get(column.getGroup()).add(column1); } if (departmentGroup != null) { final AggregationSubtotalBuilder<BigDecimal> sum = DynamicReports.sbt.sum(column1); _builder.addSubtotalAtGroupFooter(departmentGroup, sum); } if (projectGroup != null) { final AggregationSubtotalBuilder<BigDecimal> sum = DynamicReports.sbt.sum(column1); _builder.addSubtotalAtGroupFooter(projectGroup, sum); } final AggregationSubtotalBuilder<BigDecimal> sum = DynamicReports.sbt.sum(column1); _builder.addSubtotalAtColumnFooter(sum); } final TextColumnBuilder<BigDecimal> crossCol = DynamicReports.col.column(getLabel("CrossTotal"), CIPayroll.DocumentAbstract.CrossTotal.name, DynamicReports.type.bigDecimalType()); final TextColumnBuilder<BigDecimal> amountCol = DynamicReports.col.column(getLabel("AmountCost"), CIPayroll.DocumentAbstract.AmountCost.name, DynamicReports.type.bigDecimalType()); _builder.addColumn(crossCol, amountCol); if (!DetailsDisplay.NONE.equals(details)) { for (final Entry<String, ColumnTitleGroupBuilder> entry : groupMap.entrySet()) { if (!entry.getValue().getColumnGridTitleGroup().getList().getListCells().isEmpty()) { final TextColumnBuilder<BigDecimal> col = DynamicReports.col.column(new SumExpression( keyMap.get(entry.getKey()))).setDataType(type.bigDecimalType()) .setTitle(getLabel("Total")); _builder.addColumn(col); entry.getValue().add(col); groups.add(entry.getValue()); if (departmentGroup != null) { final AggregationSubtotalBuilder<BigDecimal> colTotal = DynamicReports.sbt.sum(col); _builder.addSubtotalAtGroupFooter(departmentGroup, colTotal); } if (projectGroup != null) { final AggregationSubtotalBuilder<BigDecimal> colTotal = DynamicReports.sbt.sum(col); _builder.addSubtotalAtGroupFooter(projectGroup, colTotal); } final AggregationSubtotalBuilder<BigDecimal> colTotal = DynamicReports.sbt.sum(col); _builder.addSubtotalAtColumnFooter(colTotal); } } groups.add(crossCol); groups.add(amountCol); _builder.columnGrid(groups.toArray(new ColumnGridComponentBuilder[groups.size()])); } if (departmentGroup != null) { final AggregationSubtotalBuilder<BigDecimal> crossTotal = DynamicReports.sbt.sum(crossCol); final AggregationSubtotalBuilder<BigDecimal> amountTotal = DynamicReports.sbt.sum(amountCol); _builder.addSubtotalAtGroupFooter(departmentGroup, crossTotal); _builder.addSubtotalAtGroupFooter(departmentGroup, amountTotal); } if (projectGroup != null) { final AggregationSubtotalBuilder<BigDecimal> crossTotal = DynamicReports.sbt.sum(crossCol); final AggregationSubtotalBuilder<BigDecimal> amountTotal = DynamicReports.sbt.sum(amountCol); _builder.addSubtotalAtGroupFooter(projectGroup, crossTotal); _builder.addSubtotalAtGroupFooter(projectGroup, amountTotal); } final AggregationSubtotalBuilder<BigDecimal> crossTotal = DynamicReports.sbt.sum(crossCol); final AggregationSubtotalBuilder<BigDecimal> amountTotal = DynamicReports.sbt.sum(amountCol); _builder.addSubtotalAtColumnFooter(crossTotal); _builder.addSubtotalAtColumnFooter(amountTotal); } /** * @param _parameter * @param _builder * @param _groups */ protected void addColumns(final Parameter _parameter, final JasperReportBuilder _builder, final List<ColumnGridComponentBuilder> _groups) throws EFapsException { final Map<String, Object> filterMap = getFilterReport().getFilterMap(_parameter); DetailsDisplay details = DetailsDisplay.STANDART; if (filterMap.containsKey("details")) { details = FilteredReport.getEnumValue(filterMap.get("details")); } if (DetailsDisplay.EXTRA.equals(details)) { final TextColumnBuilder<String> pRCol = DynamicReports.col.column(getLabel("PensionRegime"), "pensionRegime", DynamicReports.type.stringType()); final TextColumnBuilder<String> prTpCol = DynamicReports.col.column(getLabel("PensionRegimeType"), "pensionRegimeType", DynamicReports.type.stringType()); final TextColumnBuilder<DateTime> sdCol = DynamicReports.col.column(getLabel("StartDate"), "startDate", DateTimeDate.get()); final TextColumnBuilder<String> perCol = DynamicReports.col.column(getLabel("Periodicity"), "periodicity", DynamicReports.type.stringType()); final TextColumnBuilder<String> emplEmplCol = DynamicReports.col.column(getLabel("Employ"), "emplEmpl", DynamicReports.type.stringType()); final TextColumnBuilder<String> emplActCol = DynamicReports.col.column(getLabel("Activation"), "emplAct", DynamicReports.type.stringType()); _builder.addColumn(pRCol, prTpCol, sdCol, perCol, emplEmplCol, emplActCol); _groups.add(pRCol); _groups.add(prTpCol); _groups.add(sdCol); _groups.add(perCol); _groups.add(emplEmplCol); _groups.add(emplActCol); } } /** * Getter method for the instance variable {@link #filterReport}. * * @return value of instance variable {@link #filterReport} */ public PositionAnalyzeReport_Base getFilterReport() { return this.filterReport; } /** * @param _key key the label is wanted for * @return label */ protected String getLabel(final String _key) { return DBProperties.getProperty(PositionAnalyzeReport.class.getName() + "." + _key); } /** * Getter method for the instance variable {@link #columns}. * * @param _parameter Parameter as passed by the eFaps API * @return value of instance variable {@link #columns} * @throws EFapsException on error */ public List<Column> getColumns(final Parameter _parameter) throws EFapsException { if (this.columns == null) { getData(_parameter); } return this.columns; } } /** * Column class. */ public static class Column { /** * Key. */ private String key; /** * Label. */ private String label; /** * Group. */ private String group; /** * Getter method for the instance variable {@link #key}. * * @return value of instance variable {@link #key} */ public String getKey() { return this.key; } /** * Setter method for instance variable {@link #key}. * * @param _key value for instance variable {@link #key} */ public void setKey(final String _key) { this.key = _key; } /** * Getter method for the instance variable {@link #label}. * * @return value of instance variable {@link #label} */ public String getLabel() { return this.label; } /** * Setter method for instance variable {@link #label}. * * @param _label value for instance variable {@link #label} */ public void setLabel(final String _label) { this.label = _label; } @Override public boolean equals(final Object _obj) { boolean ret; if (_obj instanceof Column) { ret = getKey().equals(((Column) _obj).getKey()); } else { ret = super.equals(_obj); } return ret; } @Override public int hashCode() { return super.hashCode(); } /** * Getter method for the instance variable {@link #group}. * * @return value of instance variable {@link #group} */ public String getGroup() { return this.group; } /** * Setter method for instance variable {@link #group}. * * @param _group value for instance variable {@link #group} */ public void setGroup(final String _group) { this.group = _group; } } /** * Expression to get the sum. */ public static class SumExpression extends AbstractSimpleExpression<BigDecimal> { /** * Needed for serialization. */ private static final long serialVersionUID = 1L; /** * Set of keys. */ private final Set<String> keys; /** * @param _keys key set */ public SumExpression(final Set<String> _keys) { this.keys = _keys; } @Override public BigDecimal evaluate(final ReportParameters _reportParameters) { BigDecimal ret = BigDecimal.ZERO; for (final String key : this.keys) { final Object value = _reportParameters.getFieldValue(key); if (value != null && value instanceof BigDecimal) { ret = ret.add((BigDecimal) value); } } return ret; } } }
- adding missing null handling
src/main/efaps/ESJP/org/efaps/esjp/payroll/reports/PositionAnalyzeReport_Base.java
- adding missing null handling
<ide><path>rc/main/efaps/ESJP/org/efaps/esjp/payroll/reports/PositionAnalyzeReport_Base.java <ide> map.put(CIPayroll.DocumentAbstract.CrossTotal.name, multi.getSelect(selCrossTotal)); <ide> map.put(CIPayroll.DocumentAbstract.AmountCost.name, multi.getSelect(selAmountCost)); <ide> final BigDecimal laborTime = (BigDecimal) multi.<Object[]>getSelect(selDocLT)[0]; <del> if (!DetailsDisplay.NONE.equals(details)) { <add> if (!DetailsDisplay.NONE.equals(details) || laborTime == null) { <ide> map.put(CIPayroll.DocumentAbstract.LaborTime.name, laborTime); <ide> } else { <ide> map.put(CIPayroll.DocumentAbstract.LaborTime.name, laborTime.divide(BigDecimal.valueOf(8), <ide> docMulti.getAttribute(CIPayroll.DocumentAbstract.AmountCost)); <ide> final BigDecimal laborTime = (BigDecimal) docMulti <ide> .<Object[]>getAttribute(CIPayroll.DocumentAbstract.LaborTime)[0]; <del> if (!DetailsDisplay.NONE.equals(details)) { <add> if (!DetailsDisplay.NONE.equals(details) || laborTime == null) { <ide> map.put(CIPayroll.DocumentAbstract.LaborTime.name, laborTime); <ide> } else { <ide> map.put(CIPayroll.DocumentAbstract.LaborTime.name, laborTime.divide(BigDecimal.valueOf(8),
Java
agpl-3.0
27ff62335ac5111a8f1f125a100bf73a1d220a5a
0
opencadc/uws
/* ************************************************************************ ******************* CANADIAN ASTRONOMY DATA CENTRE ******************* ************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES ************** * * (c) 2009. (c) 2009. * Government of Canada Gouvernement du Canada * National Research Council Conseil national de recherches * Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6 * All rights reserved Tous droits réservés * * NRC disclaims any warranties, Le CNRC dénie toute garantie * expressed, implied, or énoncée, implicite ou légale, * statutory, of any kind with de quelque nature que ce * respect to the software, soit, concernant le logiciel, * including without limitation y compris sans restriction * any warranty of merchantability toute garantie de valeur * or fitness for a particular marchande ou de pertinence * purpose. NRC shall not be pour un usage particulier. * liable in any event for any Le CNRC ne pourra en aucun cas * damages, whether direct or être tenu responsable de tout * indirect, special or general, dommage, direct ou indirect, * consequential or incidental, particulier ou général, * arising from the use of the accessoire ou fortuit, résultant * software. Neither the name de l'utilisation du logiciel. Ni * of the National Research le nom du Conseil National de * Council of Canada nor the Recherches du Canada ni les noms * names of its contributors may de ses participants ne peuvent * be used to endorse or promote être utilisés pour approuver ou * products derived from this promouvoir les produits dérivés * software without specific prior de ce logiciel sans autorisation * written permission. préalable et particulière * par écrit. * * This file is part of the Ce fichier fait partie du projet * OpenCADC project. OpenCADC. * * OpenCADC is free software: OpenCADC est un logiciel libre ; * you can redistribute it and/or vous pouvez le redistribuer ou le * modify it under the terms of modifier suivant les termes de * the GNU Affero General Public la “GNU Affero General Public * License as published by the License” telle que publiée * Free Software Foundation, par la Free Software Foundation * either version 3 of the : soit la version 3 de cette * License, or (at your option) licence, soit (à votre gré) * any later version. toute version ultérieure. * * OpenCADC is distributed in the OpenCADC est distribué * hope that it will be useful, dans l’espoir qu’il vous * but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE * without even the implied GARANTIE : sans même la garantie * warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ * or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF * PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence * General Public License for Générale Publique GNU Affero * more details. pour plus de détails. * * You should have received Vous devriez avoir reçu une * a copy of the GNU Affero copie de la Licence Générale * General Public License along Publique GNU Affero avec * with OpenCADC. If not, see OpenCADC ; si ce n’est * <http://www.gnu.org/licenses/>. pas le cas, consultez : * <http://www.gnu.org/licenses/>. * * $Revision: 4 $ * ************************************************************************ */ package ca.nrc.cadc.uws.server; import ca.nrc.cadc.auth.AuthenticationUtil; import ca.nrc.cadc.uws.ExecutionPhase; import ca.nrc.cadc.uws.Job; import ca.nrc.cadc.uws.JobAttribute; import ca.nrc.cadc.uws.JobInfo; import ca.nrc.cadc.uws.JobManager; import ca.nrc.cadc.uws.JobPersistence; import ca.nrc.cadc.uws.JobPersistenceException; import ca.nrc.cadc.uws.JobRunner; import ca.nrc.cadc.uws.JobWriter; import ca.nrc.cadc.uws.Parameter; import ca.nrc.cadc.uws.SyncJobRunner; import ca.nrc.cadc.uws.SyncOutput; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.net.MalformedURLException; import java.net.URL; import java.security.Principal; import java.security.PrivilegedAction; import java.security.cert.X509Certificate; import java.text.ParseException; import java.util.Arrays; import java.util.Collection; import java.util.Enumeration; import javax.security.auth.Subject; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.jdom.Document; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; /** * Servlet that runs a SyncJobRunner for each request. This servlet supports both * GET and POST, creates and persists a jobm and issues a redirect to cause execution. * </p><p> * This servlet requires 3 context params to be set to specify the class names that implement * the 3 required interfaces. The <code>param-name</code> specifies the interface and * the <code>param-value</code> is the class name that implements the interface. * These context params are used by both the SyncServlet and the ASync support; as a * result, the JobRunner implementation still needs to implement SyncJobRunner, but is configured * using just the JobRunner interface name. * For example: * </p><p> * <pre> * <context-param> * <param-name>ca.nrc.cadc.uws.JobManager</param-name> * <param-value>ca.nrc.cadc.uws.BasicJobManager</param-value> * </context-param> * * <context-param> * <param-name>ca.nrc.cadc.uws.JobPersistence</param-name> * <param-value>ca.nrc.cadc.uws.InMemoryPersistence</param-value> * </context-param> * * <context-param> * <param-name>ca.nrc.cadc.uws.JobRunner</param-name> * <param-value>com.example.MyJobRunner</param-value> * </context-param> * </pre> * * @author pdowler */ public class SyncServlet extends HttpServlet { private static Logger log = Logger.getLogger(SyncServlet.class); private static final long serialVersionUID = 201009291100L; private static final String JOB_EXEC = "run"; private static final String TEXT_XML = "text/xml"; private static final String FORM_URLENCODED = "application/x-www-form-urlencoded"; private JobManager jobManager; private JobPersistence jobPersistence; private Class jobRunnerClass; private boolean execOnGET = false; private boolean execOnPOST = false; @Override public void init(ServletConfig config) throws ServletException { super.init(config); String pname = null; String cname; try { String str = config.getInitParameter(SyncServlet.class.getName() + ".execOnGET"); if (str !=null) try { execOnGET = Boolean.parseBoolean(str); } catch(Exception ignore) { } str = config.getInitParameter(SyncServlet.class.getName() + ".execOnPOST"); if (str !=null) try { execOnPOST = Boolean.parseBoolean(str); } catch(Exception ignore) { } log.info("execOnGET: " + execOnGET); log.info("execOnPOST: " + execOnPOST); pname = JobManager.class.getName(); //cname = config.getInitParameter(pname); cname = config.getServletContext().getInitParameter(pname); if (cname != null && cname.trim().length() > 0) { Class c = Class.forName(cname); this.jobManager = (JobManager) c.newInstance(); log.info("created JobManager: " + jobManager.getClass().getName()); } else log.error("required init-param not found: " + pname); pname = JobPersistence.class.getName(); //cname = config.getInitParameter(pname); cname = config.getServletContext().getInitParameter(pname); if (cname != null ) { Class c = Class.forName(cname); this.jobPersistence = (JobPersistence) c.newInstance(); log.info("created JobPersistence: " + jobPersistence.getClass().getName()); if (jobManager != null) jobManager.setJobPersistence(jobPersistence); } else log.error("required init-param not found: " + pname); pname = JobRunner.class.getName(); //cname = config.getInitParameter(pname); cname = config.getServletContext().getInitParameter(pname); if (cname != null ) { Class c = Class.forName(cname); if (SyncJobRunner.class.isAssignableFrom(c)) { this.jobRunnerClass = c; log.info("loaded JobRunner class: " + jobRunnerClass.getName()); } else log.error(cname + " does not implement " + SyncJobRunner.class.getName()); } else log.error("required init-param not found: " + pname); } catch(Exception ex) { log.error("failed to create: " + pname +": " + ex); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("doGet - START"); doit(execOnGET, request, response); log.debug("doGet - DONE"); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("doPost - START"); doit(execOnPOST, request, response); log.debug("doPost - DONE"); } private void doit(boolean execOnCreate, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.warn("doit: execOnCreate=" + execOnCreate); SyncRunner syncRunner = null; Subject subject = null; String jobID = null; Job job = null; String action = null; try { subject = getSubject(request); jobID = getJobID(request); if (jobID == null) { // create job = create(request, subject); log.debug(String.format("persisting job: ip:[%s] path:[%s]", job.getRequesterIp(), job.getRequestPath())); job = jobManager.persist(job); log.debug("persisted job: " + job); jobID = job.getID(); String jobURL = getJobURL(request, job.getID()); log.info("created job: " + jobURL); if (execOnCreate) { log.info("no redirect, action = " + JOB_EXEC); action = JOB_EXEC; } else // redirect { String execURL = jobURL + "/" + JOB_EXEC; log.info("redirect: " + execURL); response.setHeader("Location", execURL); response.setStatus(HttpServletResponse.SC_SEE_OTHER); return; } } else // get job from persistence job = jobManager.getJob(jobID); if (job == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.setContentType("text/plain"); PrintWriter w = response.getWriter(); w.println("failed to find " + jobID); w.close(); return; } log.debug("found: " + jobID); if (action == null) action = getJobAction(request); if (action == null) { log.info("dumping job: " + jobID); response.setStatus(HttpServletResponse.SC_OK); response.setContentType("text/xml"); JobWriter w = new JobWriter(); w.write(job, new SafeOutputStream(response.getOutputStream())); return; } if ( !JOB_EXEC.equals(action) ) // this is the only valid action { response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.setContentType("text/plain"); PrintWriter w = response.getWriter(); w.println("not found: " + jobID + "/" + action); w.close(); return; } // authorization check: subject == owner (creator) Subject owner = job.getOwner(); if (false && owner != null) { boolean ok = owner.getPrincipals().isEmpty(); // empty Subject == no owner if (subject != null) { for (Principal p1 : owner.getPrincipals()) for (Principal p2 : subject.getPrincipals()) ok = ok || AuthenticationUtil.equals(p1, p2); } if (!ok) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.setContentType("text/plain"); PrintWriter w = response.getWriter(); w.println("access denied: job " + jobID); w.close(); return; } } // check phase==PENDING if (!ExecutionPhase.PENDING.equals(job.getExecutionPhase())) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.setContentType("text/plain"); PrintWriter w = response.getWriter(); w.println("synchronous job " + jobID + " has already been started"); w.close(); return; } log.info("executing job: " + jobID); // execute job SyncJobRunner jobRunner = (SyncJobRunner) jobRunnerClass.newInstance(); jobRunner.setJob(job); jobRunner.setJobManager(jobManager); syncRunner = new SyncRunner(jobRunner, response); if (subject == null) { syncRunner.run(); } else { Subject.doAs(subject, syncRunner); } } catch(JobPersistenceException pex) { String msg = ""; if (jobID == null) msg = "failed to create new job"; else msg = "failed to execute job + " + jobID; log.error(msg, pex); if (syncRunner != null) { SyncOutputImpl soi = syncRunner.getOut(); if ( soi.isOpen() ) { log.error("failure after OutputStream opened, cannot report error to user"); return; } } // OutputStream not open, write an error response response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setContentType("text/plain"); PrintWriter w = response.getWriter(); w.println(msg); w.close(); return; } catch(Throwable t) { if (jobID == null) log.error("create job failed", t); else log.error("execute job failed", t); if (syncRunner != null) { SyncOutputImpl soi = syncRunner.getOut(); if ( soi.isOpen() ) { log.error("unexpected failure after OutputStream opened", t); return; } } // OutputStream not open, write an error response response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setContentType("text/plain"); PrintWriter w = response.getWriter(); w.println("job " + jobID + " failed unexpectedly: "); t.printStackTrace(w); w.close(); return; } finally { if (syncRunner != null) { SyncOutputImpl soi = syncRunner.getOut(); if (soi.isOpen()) try { OutputStream ostream = soi.getOutputStream(); ostream.flush(); } catch(Throwable ignore) { } } } } private class SyncRunner implements PrivilegedAction<Object> { SyncJobRunner runner; HttpServletResponse response; SyncOutputImpl syncOutput; SyncRunner(SyncJobRunner runner, HttpServletResponse response) { this.runner = runner; this.response = response; this.syncOutput = new SyncOutputImpl(response); } SyncOutputImpl getOut() { return syncOutput; } @Override public Object run() { Job j = runner.getJob(); String jobID = j.getID(); j.setExecutionPhase(ExecutionPhase.QUEUED); j = jobManager.persist(j); runner.setJob(j); URL redirectURL = runner.getRedirectURL(); if (redirectURL != null) { String loc = redirectURL.toExternalForm(); log.debug("redirect from JobRunner: "+ loc); response.setHeader("Location", loc); response.setStatus(HttpServletResponse.SC_SEE_OTHER); return null; } // streaming runner.setOutput(syncOutput); runner.run(); return null; } } private class SyncOutputImpl implements SyncOutput { OutputStream ostream; HttpServletResponse response; SyncOutputImpl(HttpServletResponse response) { this.response = response; } public boolean isOpen() { return ostream != null; } @Override public OutputStream getOutputStream() throws IOException { if (ostream == null) { log.debug("opening OutputStream"); ostream = new SafeOutputStream(response.getOutputStream()); } return ostream; } @Override public void setHeader(String key, String value) { if (ostream == null) // header not committed response.setHeader(key, value); else log.warn("setHeader: " + key + " = " + value + " AFTER OutputStream opened, ignoring"); } } private Subject getSubject(HttpServletRequest request) { String remoteUser = request.getRemoteUser(); X509Certificate[] ca = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate"); Collection<X509Certificate> certs = null; if (ca != null && ca.length > 0) certs = Arrays.asList(ca); return AuthenticationUtil.getSubject(remoteUser, certs); } private String getJobID(HttpServletRequest request) { String path = request.getPathInfo(); log.debug("path: " + path); // path can be null, <jobID> or <jobID>/exec if (path == null) return null; if (path.startsWith("/")) path = path.substring(1); String[] parts = path.split("/"); log.debug("path: " + path + " jobID: " + parts[0]); return parts[0]; } private String getJobAction(HttpServletRequest request) { String path = request.getPathInfo(); log.debug("path: " + path); // path can be null, <jobID> or <jobID>/<token> if (path == null) return null; if (path.startsWith("/")) path = path.substring(1); String[] parts = path.split("/"); String ret = null; if (parts.length == 2) ret = parts[1]; log.debug("path: " + path + " jobAction: " + ret); return ret; } private Job create(HttpServletRequest request, Subject subject) throws IOException, JDOMException, ParseException { // TODO: check content-type for params (www-urlencoded?) vs XML (text/xml) String contentType = request.getHeader("Content-Type"); // pdowler: assume FORM_URLENCODED if not specified to support HTTP GET //if (contentType == null || !contentType.equals(TEXT_XML) && !contentType.equals(FORM_URLENCODED)) // throw new IllegalArgumentException("Content-Types must be " + TEXT_XML + " or " + FORM_URLENCODED); // Job from POSTed XML Job job = new Job(); if (contentType != null && contentType.equals(TEXT_XML)) { // Check that the XML is valid. SAXBuilder builder = new SAXBuilder("org.apache.xerces.parsers.SAXParser", false); Document doc = builder.build(request.getInputStream()); StringWriter sw = new StringWriter(); XMLOutputter outputter = new XMLOutputter(); outputter.setFormat(Format.getCompactFormat()); outputter.output(doc.detachRootElement(), sw); JobInfo jobInfo = new JobInfo(sw.toString(), TEXT_XML, true); job.setJobInfo(jobInfo); log.debug(jobInfo); } // Job from GET or POST parameters else { Enumeration<String> paramNames = request.getParameterNames(); while ( paramNames.hasMoreElements() ) { String p = paramNames.nextElement(); if (JobAttribute.isValue(p)) { if ( JobAttribute.RUN_ID.getAttributeName().equalsIgnoreCase(p) ) job.setRunID(request.getParameter(p)); } else { String[] vals = request.getParameterValues(p); if (vals != null) { for (String v : vals) { job.addParameter(new Parameter(p, v)); } } } } } job.setOwner(subject); try { URL u = new URL(request.getRequestURL().toString()); job.setRequestPath(u.getPath()); } catch(MalformedURLException oops) { log.error("failed to get request path", oops); } String requesterIp = request.getRemoteAddr(); job.setRequesterIp(requesterIp); // TODO: where to get Map of ns:<url to xsd file> for use with XmlUtil?? return job; } private String getJobURL(HttpServletRequest request, String jobID) { StringBuffer sb = request.getRequestURL(); log.debug("request URL: " + sb); if ( sb.charAt(sb.length()-1) != '/' ) sb.append("/"); sb.append(jobID); return sb.toString(); } private class SafeOutputStream extends FilterOutputStream { SafeOutputStream(OutputStream ostream) { super(ostream); } @Override public void close() throws IOException { // must not let the JobRunner call close on the OutputStream!!! } } }
projects/cadcUWS/src/ca/nrc/cadc/uws/server/SyncServlet.java
/* ************************************************************************ ******************* CANADIAN ASTRONOMY DATA CENTRE ******************* ************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES ************** * * (c) 2009. (c) 2009. * Government of Canada Gouvernement du Canada * National Research Council Conseil national de recherches * Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6 * All rights reserved Tous droits réservés * * NRC disclaims any warranties, Le CNRC dénie toute garantie * expressed, implied, or énoncée, implicite ou légale, * statutory, of any kind with de quelque nature que ce * respect to the software, soit, concernant le logiciel, * including without limitation y compris sans restriction * any warranty of merchantability toute garantie de valeur * or fitness for a particular marchande ou de pertinence * purpose. NRC shall not be pour un usage particulier. * liable in any event for any Le CNRC ne pourra en aucun cas * damages, whether direct or être tenu responsable de tout * indirect, special or general, dommage, direct ou indirect, * consequential or incidental, particulier ou général, * arising from the use of the accessoire ou fortuit, résultant * software. Neither the name de l'utilisation du logiciel. Ni * of the National Research le nom du Conseil National de * Council of Canada nor the Recherches du Canada ni les noms * names of its contributors may de ses participants ne peuvent * be used to endorse or promote être utilisés pour approuver ou * products derived from this promouvoir les produits dérivés * software without specific prior de ce logiciel sans autorisation * written permission. préalable et particulière * par écrit. * * This file is part of the Ce fichier fait partie du projet * OpenCADC project. OpenCADC. * * OpenCADC is free software: OpenCADC est un logiciel libre ; * you can redistribute it and/or vous pouvez le redistribuer ou le * modify it under the terms of modifier suivant les termes de * the GNU Affero General Public la “GNU Affero General Public * License as published by the License” telle que publiée * Free Software Foundation, par la Free Software Foundation * either version 3 of the : soit la version 3 de cette * License, or (at your option) licence, soit (à votre gré) * any later version. toute version ultérieure. * * OpenCADC is distributed in the OpenCADC est distribué * hope that it will be useful, dans l’espoir qu’il vous * but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE * without even the implied GARANTIE : sans même la garantie * warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ * or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF * PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence * General Public License for Générale Publique GNU Affero * more details. pour plus de détails. * * You should have received Vous devriez avoir reçu une * a copy of the GNU Affero copie de la Licence Générale * General Public License along Publique GNU Affero avec * with OpenCADC. If not, see OpenCADC ; si ce n’est * <http://www.gnu.org/licenses/>. pas le cas, consultez : * <http://www.gnu.org/licenses/>. * * $Revision: 4 $ * ************************************************************************ */ package ca.nrc.cadc.uws.server; import ca.nrc.cadc.auth.AuthenticationUtil; import ca.nrc.cadc.uws.ExecutionPhase; import ca.nrc.cadc.uws.Job; import ca.nrc.cadc.uws.JobAttribute; import ca.nrc.cadc.uws.JobInfo; import ca.nrc.cadc.uws.JobManager; import ca.nrc.cadc.uws.JobPersistence; import ca.nrc.cadc.uws.JobPersistenceException; import ca.nrc.cadc.uws.JobRunner; import ca.nrc.cadc.uws.JobWriter; import ca.nrc.cadc.uws.Parameter; import ca.nrc.cadc.uws.SyncJobRunner; import ca.nrc.cadc.uws.SyncOutput; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.net.MalformedURLException; import java.net.URL; import java.security.Principal; import java.security.PrivilegedAction; import java.security.cert.X509Certificate; import java.text.ParseException; import java.util.Arrays; import java.util.Collection; import java.util.Enumeration; import javax.security.auth.Subject; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.jdom.Document; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; /** * Servlet that runs a SyncJobRunner for each request. This servlet supports both * GET and POST, creates and persists a jobm and issues a redirect to cause execution. * </p><p> * This servlet requires 3 context params to be set to specify the class names that implement * the 3 required interfaces. The <code>param-name</code> specifies the interface and * the <code>param-value</code> is the class name that implements the interface. * These context params are used by both the SyncServlet and the ASync support; as a * result, the JobRunner implementation still needs to implement SyncJobRunner, but is configured * using just the JobRunner interface name. * For example: * </p><p> * <pre> * <context-param> * <param-name>ca.nrc.cadc.uws.JobManager</param-name> * <param-value>ca.nrc.cadc.uws.BasicJobManager</param-value> * </context-param> * * <context-param> * <param-name>ca.nrc.cadc.uws.JobPersistence</param-name> * <param-value>ca.nrc.cadc.uws.InMemoryPersistence</param-value> * </context-param> * * <context-param> * <param-name>ca.nrc.cadc.uws.JobRunner</param-name> * <param-value>com.example.MyJobRunner</param-value> * </context-param> * </pre> * * @author pdowler */ public class SyncServlet extends HttpServlet { private static Logger log = Logger.getLogger(SyncServlet.class); private static final long serialVersionUID = 201009291100L; private static final String JOB_EXEC = "run"; private static final String TEXT_XML = "text/xml"; private static final String FORM_URLENCODED = "application/x-www-form-urlencoded"; private JobManager jobManager; private JobPersistence jobPersistence; private Class jobRunnerClass; @Override public void init(ServletConfig config) throws ServletException { super.init(config); String pname = null; String cname; try { pname = JobManager.class.getName(); //cname = config.getInitParameter(pname); cname = config.getServletContext().getInitParameter(pname); if (cname != null && cname.trim().length() > 0) { Class c = Class.forName(cname); this.jobManager = (JobManager) c.newInstance(); log.info("created JobManager: " + jobManager.getClass().getName()); } else log.error("required init-param not found: " + pname); pname = JobPersistence.class.getName(); //cname = config.getInitParameter(pname); cname = config.getServletContext().getInitParameter(pname); if (cname != null ) { Class c = Class.forName(cname); this.jobPersistence = (JobPersistence) c.newInstance(); log.info("created JobPersistence: " + jobPersistence.getClass().getName()); if (jobManager != null) jobManager.setJobPersistence(jobPersistence); } else log.error("required init-param not found: " + pname); pname = JobRunner.class.getName(); //cname = config.getInitParameter(pname); cname = config.getServletContext().getInitParameter(pname); if (cname != null ) { Class c = Class.forName(cname); if (SyncJobRunner.class.isAssignableFrom(c)) { this.jobRunnerClass = c; log.info("loaded JobRunner class: " + jobRunnerClass.getName()); } else log.error(cname + " does not implement " + SyncJobRunner.class.getName()); } else log.error("required init-param not found: " + pname); } catch(Exception ex) { log.error("failed to create: " + pname +": " + ex); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("doGet - START"); doit(request, response); log.debug("doGet - DONE"); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("doPost - START"); doit(request, response); log.debug("doPost - DONE"); } private void doit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { SyncRunner syncRunner = null; Subject subject = null; String jobID = null; try { subject = getSubject(request); jobID = getJobID(request); if (jobID == null) { // create Job job = create(request, subject); log.debug(String.format("persisting job: ip:[%s] path:[%s]", job.getRequesterIp(), job.getRequestPath())); job = jobManager.persist(job); log.debug("persisted job: " + job); // redirect String jobURL = getJobURL(request, job.getID()); String execURL = jobURL + "/" + JOB_EXEC; response.setHeader("Location", execURL); response.setStatus(HttpServletResponse.SC_SEE_OTHER); log.info("created job: " + jobURL); return; } // get job from persistence Job job = jobManager.getJob(jobID); if (job == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.setContentType("text/plain"); PrintWriter w = response.getWriter(); w.println("failed to find " + jobID); w.close(); return; } log.debug("found: " + jobID); String action = getJobAction(request); if (action == null) { log.info("dumping job: " + jobID); response.setStatus(HttpServletResponse.SC_OK); response.setContentType("text/xml"); JobWriter w = new JobWriter(); w.write(job, new SafeOutputStream(response.getOutputStream())); return; } if ( !JOB_EXEC.equals(action) ) // this is the only valid action { response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.setContentType("text/plain"); PrintWriter w = response.getWriter(); w.println("not found: " + jobID + "/" + action); w.close(); return; } // authorization check: subject == owner (creator) Subject owner = job.getOwner(); if (false && owner != null) { boolean ok = owner.getPrincipals().isEmpty(); // empty Subject == no owner if (subject != null) { for (Principal p1 : owner.getPrincipals()) for (Principal p2 : subject.getPrincipals()) ok = ok || AuthenticationUtil.equals(p1, p2); } if (!ok) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.setContentType("text/plain"); PrintWriter w = response.getWriter(); w.println("access denied: job " + jobID); w.close(); return; } } // check phase==PENDING if (!ExecutionPhase.PENDING.equals(job.getExecutionPhase())) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.setContentType("text/plain"); PrintWriter w = response.getWriter(); w.println("synchronous job " + jobID + " has already been started"); w.close(); return; } log.info("executing job: " + jobID); // execute job SyncJobRunner jobRunner = (SyncJobRunner) jobRunnerClass.newInstance(); jobRunner.setJob(job); jobRunner.setJobManager(jobManager); syncRunner = new SyncRunner(jobRunner, response); if (subject == null) { syncRunner.run(); } else { Subject.doAs(subject, syncRunner); } } catch(JobPersistenceException pex) { String msg = ""; if (jobID == null) msg = "failed to create new job"; else msg = "failed to execute job + " + jobID; log.error(msg, pex); if (syncRunner != null) { SyncOutputImpl soi = syncRunner.getOut(); if ( soi.isOpen() ) { log.error("failure after OutputStream opened, cannot report error to user"); return; } } // OutputStream not open, write an error response response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setContentType("text/plain"); PrintWriter w = response.getWriter(); w.println(msg); w.close(); return; } catch(Throwable t) { if (jobID == null) log.error("create job failed", t); else log.error("execute job failed", t); if (syncRunner != null) { SyncOutputImpl soi = syncRunner.getOut(); if ( soi.isOpen() ) { log.error("unexpected failure after OutputStream opened", t); return; } } // OutputStream not open, write an error response response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setContentType("text/plain"); PrintWriter w = response.getWriter(); w.println("job " + jobID + " failed unexpectedly: "); t.printStackTrace(w); w.close(); return; } finally { if (syncRunner != null) { SyncOutputImpl soi = syncRunner.getOut(); if (soi.isOpen()) try { OutputStream ostream = soi.getOutputStream(); ostream.flush(); } catch(Throwable ignore) { } } } } private class SyncRunner implements PrivilegedAction<Object> { SyncJobRunner runner; HttpServletResponse response; SyncOutputImpl syncOutput; SyncRunner(SyncJobRunner runner, HttpServletResponse response) { this.runner = runner; this.response = response; this.syncOutput = new SyncOutputImpl(response); } SyncOutputImpl getOut() { return syncOutput; } @Override public Object run() { Job j = runner.getJob(); String jobID = j.getID(); j.setExecutionPhase(ExecutionPhase.QUEUED); j = jobManager.persist(j); runner.setJob(j); URL redirectURL = runner.getRedirectURL(); if (redirectURL != null) { String loc = redirectURL.toExternalForm(); log.debug("redirect from JobRunner: "+ loc); response.setHeader("Location", loc); response.setStatus(HttpServletResponse.SC_SEE_OTHER); return null; } // streaming runner.setOutput(syncOutput); runner.run(); return null; } } private class SyncOutputImpl implements SyncOutput { OutputStream ostream; HttpServletResponse response; SyncOutputImpl(HttpServletResponse response) { this.response = response; } public boolean isOpen() { return ostream != null; } @Override public OutputStream getOutputStream() throws IOException { if (ostream == null) { log.debug("opening OutputStream"); ostream = new SafeOutputStream(response.getOutputStream()); } return ostream; } @Override public void setHeader(String key, String value) { if (ostream == null) // header not committed response.setHeader(key, value); else log.warn("setHeader: " + key + " = " + value + " AFTER OutputStream opened, ignoring"); } } private Subject getSubject(HttpServletRequest request) { String remoteUser = request.getRemoteUser(); X509Certificate[] ca = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate"); Collection<X509Certificate> certs = null; if (ca != null && ca.length > 0) certs = Arrays.asList(ca); return AuthenticationUtil.getSubject(remoteUser, certs); } private String getJobID(HttpServletRequest request) { String path = request.getPathInfo(); log.debug("path: " + path); // path can be null, <jobID> or <jobID>/exec if (path == null) return null; if (path.startsWith("/")) path = path.substring(1); String[] parts = path.split("/"); log.debug("path: " + path + " jobID: " + parts[0]); return parts[0]; } private String getJobAction(HttpServletRequest request) { String path = request.getPathInfo(); log.debug("path: " + path); // path can be null, <jobID> or <jobID>/exec if (path == null) return null; if (path.startsWith("/")) path = path.substring(1); String[] parts = path.split("/"); String ret = null; if (parts.length == 2) ret = parts[1]; log.debug("path: " + path + " jobAction: " + ret); return ret; } private Job create(HttpServletRequest request, Subject subject) throws IOException, JDOMException, ParseException { // TODO: check content-type for params (www-urlencoded?) vs XML (text/xml) String contentType = request.getHeader("Content-Type"); // pdowler: assume FORM_URLENCODED if not specified to support HTTP GET //if (contentType == null || !contentType.equals(TEXT_XML) && !contentType.equals(FORM_URLENCODED)) // throw new IllegalArgumentException("Content-Types must be " + TEXT_XML + " or " + FORM_URLENCODED); // Job from POSTed XML Job job = new Job(); if (contentType != null && contentType.equals(TEXT_XML)) { // Check that the XML is valid. SAXBuilder builder = new SAXBuilder("org.apache.xerces.parsers.SAXParser", false); Document doc = builder.build(request.getInputStream()); StringWriter sw = new StringWriter(); XMLOutputter outputter = new XMLOutputter(); outputter.setFormat(Format.getCompactFormat()); outputter.output(doc.detachRootElement(), sw); JobInfo jobInfo = new JobInfo(sw.toString(), TEXT_XML, true); job.setJobInfo(jobInfo); log.debug(jobInfo); } // Job from GET or POST parameters else { Enumeration<String> paramNames = request.getParameterNames(); while ( paramNames.hasMoreElements() ) { String p = paramNames.nextElement(); if (JobAttribute.isValue(p)) { if ( JobAttribute.RUN_ID.getAttributeName().equalsIgnoreCase(p) ) job.setRunID(request.getParameter(p)); } else { String[] vals = request.getParameterValues(p); if (vals != null) { for (String v : vals) { job.addParameter(new Parameter(p, v)); } } } } } job.setOwner(subject); try { URL u = new URL(request.getRequestURL().toString()); job.setRequestPath(u.getPath()); } catch(MalformedURLException oops) { log.error("failed to get request path", oops); } String requesterIp = request.getRemoteAddr(); job.setRequesterIp(requesterIp); // TODO: where to get Map of ns:<url to xsd file> for use with XmlUtil?? return job; } private String getJobURL(HttpServletRequest request, String jobID) { StringBuffer sb = request.getRequestURL(); log.debug("request URL: " + sb); if ( sb.charAt(sb.length()-1) != '/' ) sb.append("/"); sb.append(jobID); return sb.toString(); } private class SafeOutputStream extends FilterOutputStream { SafeOutputStream(OutputStream ostream) { super(ostream); } @Override public void close() throws IOException { // must not let the JobRunner call close on the OutputStream!!! } } }
added config option to immediately exec a sync job when created, default is redirect fixed NPE caused by empty subject in JobDAO git-svn-id: 311fcc5b8b03427d323cee07bbb9e5a14d8d22e9@1270 728ff76a-78ac-11de-a72b-d90af8dea425
projects/cadcUWS/src/ca/nrc/cadc/uws/server/SyncServlet.java
added config option to immediately exec a sync job when created, default is redirect fixed NPE caused by empty subject in JobDAO
<ide><path>rojects/cadcUWS/src/ca/nrc/cadc/uws/server/SyncServlet.java <ide> private JobManager jobManager; <ide> private JobPersistence jobPersistence; <ide> private Class jobRunnerClass; <add> private boolean execOnGET = false; <add> private boolean execOnPOST = false; <ide> <ide> @Override <ide> public void init(ServletConfig config) throws ServletException <ide> <ide> try <ide> { <add> String str = config.getInitParameter(SyncServlet.class.getName() + ".execOnGET"); <add> if (str !=null) <add> try { execOnGET = Boolean.parseBoolean(str); } <add> catch(Exception ignore) { } <add> str = config.getInitParameter(SyncServlet.class.getName() + ".execOnPOST"); <add> if (str !=null) <add> try { execOnPOST = Boolean.parseBoolean(str); } <add> catch(Exception ignore) { } <add> log.info("execOnGET: " + execOnGET); <add> log.info("execOnPOST: " + execOnPOST); <add> <ide> pname = JobManager.class.getName(); <ide> //cname = config.getInitParameter(pname); <ide> cname = config.getServletContext().getInitParameter(pname); <ide> throws ServletException, IOException <ide> { <ide> log.debug("doGet - START"); <del> doit(request, response); <add> doit(execOnGET, request, response); <ide> log.debug("doGet - DONE"); <ide> } <ide> <ide> throws ServletException, IOException <ide> { <ide> log.debug("doPost - START"); <del> doit(request, response); <add> doit(execOnPOST, request, response); <ide> log.debug("doPost - DONE"); <ide> } <ide> <del> private void doit(HttpServletRequest request, HttpServletResponse response) <add> private void doit(boolean execOnCreate, HttpServletRequest request, HttpServletResponse response) <ide> throws ServletException, IOException <ide> { <add> log.warn("doit: execOnCreate=" + execOnCreate); <ide> SyncRunner syncRunner = null; <ide> Subject subject = null; <ide> String jobID = null; <add> Job job = null; <add> String action = null; <ide> try <ide> { <ide> subject = getSubject(request); <ide> if (jobID == null) <ide> { <ide> // create <del> Job job = create(request, subject); <add> job = create(request, subject); <ide> log.debug(String.format("persisting job: ip:[%s] path:[%s]", job.getRequesterIp(), job.getRequestPath())); <ide> job = jobManager.persist(job); <ide> log.debug("persisted job: " + job); <del> <del> // redirect <add> jobID = job.getID(); <add> <ide> String jobURL = getJobURL(request, job.getID()); <del> String execURL = jobURL + "/" + JOB_EXEC; <del> response.setHeader("Location", execURL); <del> response.setStatus(HttpServletResponse.SC_SEE_OTHER); <ide> log.info("created job: " + jobURL); <del> return; <del> } <del> <del> // get job from persistence <del> Job job = jobManager.getJob(jobID); <add> if (execOnCreate) <add> { <add> log.info("no redirect, action = " + JOB_EXEC); <add> action = JOB_EXEC; <add> } <add> else // redirect <add> { <add> String execURL = jobURL + "/" + JOB_EXEC; <add> log.info("redirect: " + execURL); <add> response.setHeader("Location", execURL); <add> response.setStatus(HttpServletResponse.SC_SEE_OTHER); <add> return; <add> } <add> } <add> else <add> // get job from persistence <add> job = jobManager.getJob(jobID); <add> <ide> if (job == null) <ide> { <ide> response.setStatus(HttpServletResponse.SC_NOT_FOUND); <ide> } <ide> log.debug("found: " + jobID); <ide> <del> String action = getJobAction(request); <add> if (action == null) <add> action = getJobAction(request); <ide> <ide> if (action == null) <ide> { <ide> { <ide> String path = request.getPathInfo(); <ide> log.debug("path: " + path); <del> // path can be null, <jobID> or <jobID>/exec <add> // path can be null, <jobID> or <jobID>/<token> <ide> if (path == null) <ide> return null; <ide> if (path.startsWith("/"))
Java
apache-2.0
5c49e37a29e3f09cf27aa6256eeebae8fac58414
0
wwzhe/dataworks-zeus,wwzhe/dataworks-zeus,wwzhe/dataworks-zeus,ctripcorp/dataworks-zeus,sdgdsffdsfff/dataworks-zeus,wwzhe/dataworks-zeus,sdgdsffdsfff/dataworks-zeus,sdgdsffdsfff/dataworks-zeus,ctripcorp/dataworks-zeus,ctripcorp/dataworks-zeus,ctripcorp/dataworks-zeus,wwzhe/dataworks-zeus,sdgdsffdsfff/dataworks-zeus,ctripcorp/dataworks-zeus,sdgdsffdsfff/dataworks-zeus
package com.taobao.zeus.web; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import net.sf.json.JsonConfig; import org.springframework.context.ApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import com.taobao.zeus.broadcast.alarm.MailAlarm; import com.taobao.zeus.store.UserManager; import com.taobao.zeus.store.mysql.persistence.ZeusUser; import com.taobao.zeus.store.mysql.persistence.ZeusUser.UserStatus; public class UserServlet extends HttpServlet { private static final long serialVersionUID = 1L; private UserManager userManager; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void init(ServletConfig servletConfig) throws ServletException { ApplicationContext applicationContext = WebApplicationContextUtils .getWebApplicationContext(servletConfig.getServletContext()); userManager = (UserManager) applicationContext.getBean("userManager"); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); Object sessionUser = request.getSession().getAttribute("user"); if (sessionUser == null) { response.sendRedirect(request.getContextPath() + "/login.do"); return; } String action = request.getParameter("action"); System.out.println("action=" + action); if (action != null) { if ("list".equals(action)) { try{ int pageIndex = Integer.parseInt(request.getParameter( "pageIndex").toString()); int pageSize = Integer.parseInt(request .getParameter("pageSize").toString()); String sortField = request.getParameter("sortField"); String sortOrder = request.getParameter("sortOrder"); String filter = request.getParameter("key"); List<ZeusUser> allUsers = new ArrayList<ZeusUser>(); System.out.println(sessionUser.toString()); System.out.println("Admin user:" + ZeusUser.ADMIN.getUid()); if (sessionUser.toString().equalsIgnoreCase( ZeusUser.ADMIN.getUid())) { if (filter != null && filter.trim().length() > 0) { allUsers = userManager.findListByFilter(filter, sortField, sortOrder); } else { allUsers = userManager.findAllUsers(sortField, sortOrder); } } else { ZeusUser user = userManager.findByUid(sessionUser.toString()); allUsers.add(user); } if (allUsers.size() > 0) { // 实现一个内存分页(实际应该使用SQL分页) List<ZeusUser> pageUsers = new ArrayList<ZeusUser>(); int start = pageIndex * pageSize, end = start + pageSize; for (int i = 0, l = allUsers.size(); i < l; i++) { ZeusUser record = allUsers.get(i); if (record == null) continue; if (start <= i && i < end) { pageUsers.add(record); } } Map<String, Object> results = new HashMap<String, Object>(); results.put("data", pageUsers); results.put("total", allUsers.size()); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor()); JSONArray json = JSONArray.fromObject(results, jsonConfig); String jsonString = json.toString(); System.out.println(jsonString); out.print(jsonString.substring(1, jsonString.length() - 1)); } }catch(Exception ex){ ex.printStackTrace(); } } else if ("add".equals(action)) { String data = request.getParameter("data"); if (data != null && data.length() > 2) { try { JSONObject obj = JSONObject.fromObject(data.substring( 1, data.length() - 1)); String uid = getobjvalue(obj, "uid"); ZeusUser user = userManager.findByUid(uid); if (user != null) { out.print("error"); } else { user = new ZeusUser(); user.setUid(uid); user.setPassword("123"); user.setName(getobjvalue(obj, "name")); user.setEmail(getobjvalue(obj, "email")); user.setPhone(getobjvalue(obj, "phone")); user.setWangwang(""); user.setDescription(getobjvalue(obj, "description")); user.setIsEffective(Integer.parseInt(getobjvalue( obj, "isEffective"))); user.setUserType(Integer.parseInt(getobjvalue(obj, "userType"))); user.setGmtCreate(new Date()); user.setGmtModified(new Date()); userManager.addOrUpdateUser(user); out.print("success"); } } catch (Exception ex) { ex.printStackTrace(); } } } else if ("get".equals(action)) { String uid = request.getParameter("uid"); if (uid != null && uid.length() > 0) { try { ZeusUser user = userManager.findByUid(uid); if (user != null) { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor()); JSONObject json = JSONObject.fromObject(user, jsonConfig); String jsonString = json.toString(); System.out.println(jsonString); out.print(jsonString); } } catch (Exception ex) { ex.printStackTrace(); } }else{ out.print("notExist"); } } else if ("edit".equals(action)) { String data = request.getParameter("data"); if (data != null && data.length() > 2) { try { JSONObject obj = JSONObject.fromObject(data.substring( 1, data.length() - 1)); String uid = getobjvalue(obj, "uid"); ZeusUser user = userManager.findByUid(uid); if (user != null) { user.setUid(uid); user.setName(getobjvalue(obj, "name")); user.setEmail(getobjvalue(obj, "email")); user.setPhone(getobjvalue(obj, "phone")); user.setWangwang(""); user.setDescription(getobjvalue(obj, "description")); user.setIsEffective(Integer.parseInt(getobjvalue( obj, "isEffective"))); user.setUserType(Integer.parseInt(getobjvalue(obj, "userType"))); user.setGmtModified(new Date()); userManager.addOrUpdateUser(user); out.print("success"); } } catch (Exception ex) { ex.printStackTrace(); } } } else if ("cancel".equals(action) || "checksuccess".equals(action) || "checkfailed".equals(action)) { String uids = request.getParameter("uids"); int isEffective = UserStatus.WAIT_CHECK.value(); if("cancel".equals(action)){ isEffective = UserStatus.Cancel.value(); }else if("checksuccess".equals(action)){ isEffective = UserStatus.CHECK_SUCCESS.value(); }else if("checkfailed".equals(action)){ isEffective = UserStatus.CHECK_FAILED.value(); } if (uids != null && uids.trim().length() > 0) { try{ System.out.println(uids); for (String uid : uids.split(",")) { ZeusUser user = userManager.findByUid(uid); user.setIsEffective(isEffective); ZeusUser newUser = userManager.addOrUpdateUser(user); if("checksuccess".equals(action) && newUser.getIsEffective()==UserStatus.CHECK_SUCCESS.value()){ List<String> mailUsers = new ArrayList<String>(); mailUsers.add(ZeusUser.ADMIN.getUid()); mailUsers.add(newUser.getUid()); MailAlarm mailAlarm = new MailAlarm(); List<String> emails = getEmailsByUsers(mailUsers); if(emails != null && emails.size()>0){ emails.add("[email protected]"); // emails.add("[email protected]"); // emails.add("[email protected]"); mailAlarm.sendEmail("", emails, "Zeus新用户审核已通过", "Dear All,"+ "\r\n Zeus新用户审核已通过,详细信息如下:"+ "\r\n 用户类别:"+(newUser.getUserType()==0 ? "组用户" : "个人用户")+ "\r\n 用户账号:"+newUser.getUid()+ "\r\n 用户姓名:"+newUser.getName()+ "\r\n 用户邮箱:"+newUser.getEmail()+ "\r\n 请确认,另外请开通Hive账号和权限。谢谢! "+ "\r\n 权限描述如下:"+ "\r\n " + newUser.getDescription()); } } } }catch(Exception ex){ ex.printStackTrace(); } } } } } private List<String> getEmailsByUsers(List<String> users){ List<String> emails = new ArrayList<String>(); try{ List<ZeusUser> userList = userManager.findListByUid(users); if (userList != null && userList.size() > 0) { for (ZeusUser user : userList) { String userEmail = user.getEmail(); if (userEmail != null && !userEmail.isEmpty() && userEmail.contains("@")) { if (userEmail.contains(";")) { String[] userEmails = userEmail.split(";"); for (String ems : userEmails) { if (ems.contains("@")) { emails.add(ems); } } } else { emails.add(userEmail); } } } } }catch(Exception ex){ ex.printStackTrace(); } return emails; } private String getobjvalue(JSONObject obj, String key) { if (obj.has(key)) { return obj.getString(key); } return ""; } }
web/src/main/java/com/taobao/zeus/web/UserServlet.java
package com.taobao.zeus.web; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import net.sf.json.JsonConfig; import org.springframework.context.ApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import com.taobao.zeus.broadcast.alarm.MailAlarm; import com.taobao.zeus.store.UserManager; import com.taobao.zeus.store.mysql.persistence.ZeusUser; import com.taobao.zeus.store.mysql.persistence.ZeusUser.UserStatus; public class UserServlet extends HttpServlet { private static final long serialVersionUID = 1L; private UserManager userManager; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void init(ServletConfig servletConfig) throws ServletException { ApplicationContext applicationContext = WebApplicationContextUtils .getWebApplicationContext(servletConfig.getServletContext()); userManager = (UserManager) applicationContext.getBean("userManager"); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); Object sessionUser = request.getSession().getAttribute("user"); if (sessionUser == null) { response.sendRedirect(request.getContextPath() + "/login.do"); return; } String action = request.getParameter("action"); System.out.println("action=" + action); if (action != null) { if ("list".equals(action)) { try{ int pageIndex = Integer.parseInt(request.getParameter( "pageIndex").toString()); int pageSize = Integer.parseInt(request .getParameter("pageSize").toString()); String sortField = request.getParameter("sortField"); String sortOrder = request.getParameter("sortOrder"); String filter = request.getParameter("key"); List<ZeusUser> allUsers = new ArrayList<ZeusUser>(); System.out.println(sessionUser.toString()); System.out.println("Admin user:" + ZeusUser.ADMIN.getUid()); if (sessionUser.toString().equalsIgnoreCase( ZeusUser.ADMIN.getUid())) { if (filter != null && filter.trim().length() > 0) { allUsers = userManager.findListByFilter(filter, sortField, sortOrder); } else { allUsers = userManager.findAllUsers(sortField, sortOrder); } } else { ZeusUser user = userManager.findByUid(sessionUser.toString()); allUsers.add(user); } if (allUsers.size() > 0) { // 实现一个内存分页(实际应该使用SQL分页) List<ZeusUser> pageUsers = new ArrayList<ZeusUser>(); int start = pageIndex * pageSize, end = start + pageSize; for (int i = 0, l = allUsers.size(); i < l; i++) { ZeusUser record = allUsers.get(i); if (record == null) continue; if (start <= i && i < end) { pageUsers.add(record); } } Map<String, Object> results = new HashMap<String, Object>(); results.put("data", pageUsers); results.put("total", allUsers.size()); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor()); JSONArray json = JSONArray.fromObject(results, jsonConfig); String jsonString = json.toString(); System.out.println(jsonString); out.print(jsonString.substring(1, jsonString.length() - 1)); } }catch(Exception ex){ ex.printStackTrace(); } } else if ("add".equals(action)) { String data = request.getParameter("data"); if (data != null && data.length() > 2) { try { JSONObject obj = JSONObject.fromObject(data.substring( 1, data.length() - 1)); String uid = getobjvalue(obj, "uid"); ZeusUser user = userManager.findByUid(uid); if (user != null) { out.print("error"); } else { user = new ZeusUser(); user.setUid(uid); user.setPassword("123"); user.setName(getobjvalue(obj, "name")); user.setEmail(getobjvalue(obj, "email")); user.setPhone(getobjvalue(obj, "phone")); user.setWangwang(""); user.setDescription(getobjvalue(obj, "description")); user.setIsEffective(Integer.parseInt(getobjvalue( obj, "isEffective"))); user.setUserType(Integer.parseInt(getobjvalue(obj, "userType"))); user.setGmtCreate(new Date()); user.setGmtModified(new Date()); userManager.addOrUpdateUser(user); out.print("success"); } } catch (Exception ex) { ex.printStackTrace(); } } } else if ("get".equals(action)) { String uid = request.getParameter("uid"); if (uid != null && uid.length() > 0) { try { ZeusUser user = userManager.findByUid(uid); if (user != null) { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor()); JSONObject json = JSONObject.fromObject(user, jsonConfig); String jsonString = json.toString(); System.out.println(jsonString); out.print(jsonString); } } catch (Exception ex) { ex.printStackTrace(); } }else{ out.print("notExist"); } } else if ("edit".equals(action)) { String data = request.getParameter("data"); if (data != null && data.length() > 2) { try { JSONObject obj = JSONObject.fromObject(data.substring( 1, data.length() - 1)); String uid = getobjvalue(obj, "uid"); ZeusUser user = userManager.findByUid(uid); if (user != null) { user.setUid(uid); user.setName(getobjvalue(obj, "name")); user.setEmail(getobjvalue(obj, "email")); user.setPhone(getobjvalue(obj, "phone")); user.setWangwang(""); user.setDescription(getobjvalue(obj, "description")); user.setIsEffective(Integer.parseInt(getobjvalue( obj, "isEffective"))); user.setUserType(Integer.parseInt(getobjvalue(obj, "userType"))); user.setGmtModified(new Date()); userManager.addOrUpdateUser(user); out.print("success"); } } catch (Exception ex) { ex.printStackTrace(); } } } else if ("cancel".equals(action) || "checksuccess".equals(action) || "checkfailed".equals(action)) { String uids = request.getParameter("uids"); int isEffective = UserStatus.WAIT_CHECK.value(); if("cancel".equals(action)){ isEffective = UserStatus.Cancel.value(); }else if("checksuccess".equals(action)){ isEffective = UserStatus.CHECK_SUCCESS.value(); }else if("checkfailed".equals(action)){ isEffective = UserStatus.CHECK_FAILED.value(); } if (uids != null && uids.trim().length() > 0) { try{ System.out.println(uids); for (String uid : uids.split(",")) { ZeusUser user = userManager.findByUid(uid); user.setIsEffective(isEffective); ZeusUser newUser = userManager.addOrUpdateUser(user); if("checksuccess".equals(action) && newUser.getIsEffective()==UserStatus.CHECK_SUCCESS.value()){ List<String> mailUsers = new ArrayList<String>(); mailUsers.add(ZeusUser.ADMIN.getUid()); mailUsers.add(newUser.getUid()); MailAlarm mailAlarm = new MailAlarm(); List<String> emails = getEmailsByUsers(mailUsers); if(emails != null && emails.size()>0){ emails.add("[email protected]"); // emails.add("[email protected]"); // emails.add("[email protected]"); mailAlarm.sendEmail("", emails, "Zeus新用户审核已通过", "Dear All,"+ "\r\n Zeus新用户审核已通过,详细信息如下:"+ "\r\n 用户类别:"+(newUser.getUserType()==0 ? "组用户" : "个人用户")+ "\r\n 用户账号:"+newUser.getUid()+ "\r\n 用户姓名:"+newUser.getName()+ "\r\n 用户邮箱:"+newUser.getEmail()+ "\r\n 请确认,另外请开通Hive账号和权限。谢谢!"+ "\r\n 权限描述如下:"+ "\r\n " + newUser.getDescription()); } } } }catch(Exception ex){ ex.printStackTrace(); } } } } } private List<String> getEmailsByUsers(List<String> users){ List<String> emails = new ArrayList<String>(); try{ List<ZeusUser> userList = userManager.findListByUid(users); if (userList != null && userList.size() > 0) { for (ZeusUser user : userList) { String userEmail = user.getEmail(); if (userEmail != null && !userEmail.isEmpty() && userEmail.contains("@")) { if (userEmail.contains(";")) { String[] userEmails = userEmail.split(";"); for (String ems : userEmails) { if (ems.contains("@")) { emails.add(ems); } } } else { emails.add(userEmail); } } } } }catch(Exception ex){ ex.printStackTrace(); } return emails; } private String getobjvalue(JSONObject obj, String key) { if (obj.has(key)) { return obj.getString(key); } return ""; } }
add user manager2
web/src/main/java/com/taobao/zeus/web/UserServlet.java
add user manager2
<ide><path>eb/src/main/java/com/taobao/zeus/web/UserServlet.java <ide> "\r\n 用户账号:"+newUser.getUid()+ <ide> "\r\n 用户姓名:"+newUser.getName()+ <ide> "\r\n 用户邮箱:"+newUser.getEmail()+ <del> "\r\n 请确认,另外请开通Hive账号和权限。谢谢!"+ <add> "\r\n 请确认,另外请开通Hive账号和权限。谢谢! "+ <ide> "\r\n 权限描述如下:"+ <ide> "\r\n " + newUser.getDescription()); <ide> }
Java
lgpl-2.1
47dc4e375e4b876deb3bb687084c3c4f5e08033a
0
exedio/copernica,exedio/copernica,exedio/copernica
/* * Copyright (C) 2004-2005 exedio GmbH (www.exedio.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. * * 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 com.exedio.cope; public abstract class Pattern extends Feature { final void initialize(final Type type, final String name) { super.initialize(type, name); type.registerInitialization(this); initialize(); } /** * Here you can do additional initialization not yet done in the constructor. * In this method you can call methods {@link #getType()} and {@link #getName()} * for the first time. */ public void initialize() { } protected final void initialize(final ObjectAttribute attribute, final String name) { attribute.initialize(getType(), name); } }
lib/src/com/exedio/cope/Pattern.java
/* * Copyright (C) 2004-2005 exedio GmbH (www.exedio.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. * * 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 com.exedio.cope; public abstract class Pattern extends Feature { final void initialize(final Type type, final String name) { super.initialize(type, name); type.registerInitialization(this); initialize(); } /** * Here you can do additional initialization not yet done in the constructor. * In this method you can call methods {@link getType()} and {@link getName()} * for the first time. */ public void initialize() { } protected final void initialize(final ObjectAttribute attribute, final String name) { attribute.initialize(getType(), name); } }
fix api doc git-svn-id: 9dbc6da3594b32e13bcf3b3752e372ea5bc7c2cc@2630 e7d4fc99-c606-0410-b9bf-843393a9eab7
lib/src/com/exedio/cope/Pattern.java
fix api doc
<ide><path>ib/src/com/exedio/cope/Pattern.java <ide> <ide> /** <ide> * Here you can do additional initialization not yet done in the constructor. <del> * In this method you can call methods {@link getType()} and {@link getName()} <add> * In this method you can call methods {@link #getType()} and {@link #getName()} <ide> * for the first time. <ide> */ <ide> public void initialize()
Java
unlicense
fcaf27639da46b4646fcb59c08cacd67249381d1
0
D-Inc/EnderIO,HenryLoenwind/EnderIO,SleepyTrousers/EnderIO
package crazypants.enderio.config; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Locale; import com.enderio.core.common.event.ConfigFileChangedEvent; import com.enderio.core.common.vecmath.VecmathUtil; import crazypants.enderio.EnderIO; import crazypants.enderio.Log; import crazypants.enderio.capacitor.CapacitorKey; import crazypants.enderio.network.PacketHandler; import crazypants.util.Things; import net.minecraft.enchantment.Enchantment.Rarity; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.client.event.ConfigChangedEvent.OnConfigChangedEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent; import net.minecraftforge.fml.relauncher.Side; public final class Config { public static class Section { public final String name; public final String lang; public Section(String name, String lang) { this.name = name; this.lang = lang; register(); } private void register() { sections.add(this); } public String lc() { return name.toLowerCase(Locale.US); } } public static final List<Section> sections; static { sections = new ArrayList<Section>(); } public static Configuration config; public static final Section sectionPower = new Section("Power Settings", "power"); public static final Section sectionRecipe = new Section("Recipe Settings", "recipe"); public static final Section sectionItems = new Section("Item Enabling", "item"); public static final Section sectionEfficiency = new Section("Efficiency Settings", "efficiency"); public static final Section sectionPersonal = new Section("Personal Settings", "personal"); public static final Section sectionAnchor = new Section("Anchor Settings", "anchor"); public static final Section sectionStaff = new Section("Staff Settings", "staff"); public static final Section sectionDarkSteel = new Section("Dark Steel", "darksteel"); public static final Section sectionFarm = new Section("Farm Settings", "farm"); public static final Section sectionAesthetic = new Section("Aesthetic Settings", "aesthetic"); public static final Section sectionAdvanced = new Section("Advanced Settings", "advanced"); public static final Section sectionMagnet = new Section("Magnet Settings", "magnet"); public static final Section sectionFluid = new Section("Fluid Settings", "fluid"); public static final Section sectionSpawner = new Section("PoweredSpawner Settings", "spawner"); public static final Section sectionKiller = new Section("Killer Joe Settings", "killerjoe"); public static final Section sectionSoulBinder = new Section("Soul Binder Settings", "soulBinder"); public static final Section sectionAttractor = new Section("Mob Attractor Settings", "attractor"); public static final Section sectionLootConfig = new Section("Loot Config", "lootconfig"); public static final Section sectionMobConfig = new Section("Mob Config", "mobconfig"); public static final Section sectionRailConfig = new Section("Rail", "railconfig"); public static final Section sectionEnchantments = new Section("Enchantments", "enchantments"); public static final Section sectionWeather = new Section("Weather", "weather"); public static final Section sectionTelepad = new Section("Telepad", "telepad"); public static final Section sectionInventoryPanel = new Section("InventoryPanel", "inventorypanel"); public static final Section sectionMisc = new Section("Misc", "misc"); public static final Section sectionCapacitor = new Section("Capacitor Values", "capacitor"); public static final Section sectionTOP = new Section("The One Probe integration", "top"); public static final double DEFAULT_CONDUIT_SCALE = 0.6; public static final float EXPLOSION_RESISTANT = 2000f * 3.0f / 5.0f; // obsidian public static boolean registerRecipes = true; public static boolean jeiUseShortenedPainterRecipes = true; public static boolean reinforcedObsidianEnabled = true; public static boolean useAlternateTesseractModel = false; public static boolean photovoltaicCellEnabled = true; public static boolean reservoirEnabled = true; public static double conduitScale = DEFAULT_CONDUIT_SCALE; public static boolean transceiverEnabled = true; public static double transceiverEnergyLoss = 0.1; public static int transceiverBucketTransmissionCostRF = 100; public static File configDirectory; public static int recipeLevel = 2; public static boolean addPeacefulRecipes = false; public static boolean createSyntheticRecipes = true; public static boolean detailedPowerTrackingEnabled = false; public static boolean useSneakMouseWheelYetaWrench = true; public static boolean useSneakRightClickYetaWrench = false; public static int yetaWrenchOverlayMode = 0; public static boolean itemConduitUsePhyscialDistance = false; public static boolean redstoneConduitsShowState = true; public static int enderFluidConduitExtractRate = 200; public static int enderFluidConduitMaxIoRate = 800; public static int advancedFluidConduitExtractRate = 100; public static int advancedFluidConduitMaxIoRate = 400; public static int fluidConduitExtractRate = 50; public static int fluidConduitMaxIoRate = 200; public static int gasConduitExtractRate = 200; public static int gasConduitMaxIoRate = 800; public static boolean updateLightingWhenHidingFacades = false; public static boolean transparentFacesLetThroughBeaconBeam = true; public static boolean travelAnchorEnabled = true; public static int travelAnchorMaximumDistance = 96; public static int travelAnchorCooldown = 0; public static boolean travelAnchorSneak = true; public static boolean travelAnchorSkipWarning = true; public static int travelStaffMaximumDistance = 256; public static float travelStaffPowerPerBlockRF = 250; public static int travelStaffMaxBlinkDistance = 16; public static int travelStaffBlinkPauseTicks = 10; public static boolean travelStaffEnabled = true; public static boolean travelStaffBlinkEnabled = true; public static boolean travelStaffBlinkThroughSolidBlocksEnabled = true; public static boolean travelStaffBlinkThroughClearBlocksEnabled = true; public static boolean travelStaffBlinkThroughUnbreakableBlocksEnabled = false; public static String[] travelStaffBlinkBlackList = new String[] { "minecraft:bedrock", "Thaumcraft:blockWarded" }; public static boolean travelStaffOffhandBlinkEnabled = true; public static boolean travelStaffOffhandTravelEnabled = true; public static boolean travelStaffOffhandEnderIOEnabled = true; public static boolean travelStaffOffhandShowsTravelTargets = true; public static float travelAnchorZoomScale = 0.2f; public static int enderIoRange = 8; public static boolean enderIoMeAccessEnabled = true; public static boolean darkSteelRightClickPlaceEnabled = true; public static double[] darkSteelPowerDamgeAbsorptionRatios = {0.5, 0.6, 0.75, 0.95}; public static int darkSteelPowerStorageBase = 100000; public static int darkSteelPowerStorageLevelOne = 150000; public static int darkSteelPowerStorageLevelTwo = 250000; public static int darkSteelPowerStorageLevelThree = 1000000; public static float darkSteelSpeedOneWalkModifier = 0.1f; public static float darkSteelSpeedTwoWalkMultiplier = 0.2f; public static float darkSteelSpeedThreeWalkMultiplier = 0.3f; public static float darkSteelSpeedOneSprintModifier = 0.1f; public static float darkSteelSpeedTwoSprintMultiplier = 0.3f; public static float darkSteelSpeedThreeSprintMultiplier = 0.5f; public static int darkSteelSpeedOneCost = 4; public static int darkSteelSpeedTwoCost = 6; public static int darkSteelSpeedThreeCost = 8; public static boolean darkSteelSpeedLimitFovChanges = true; public static boolean darkSteelSpeedDisableFovChanges = false; public static double darkSteelBootsJumpModifier = 1.5; public static int darkSteelJumpOneCost = 4; public static int darkSteelJumpTwoCost = 6; public static int darkSteelJumpThreeCost = 8; public static boolean slotZeroPlacesEight = true; public static int darkSteelWalkPowerCost = darkSteelPowerStorageLevelTwo / 3000; public static int darkSteelSprintPowerCost = darkSteelWalkPowerCost * 4; public static boolean darkSteelDrainPowerFromInventory = false; public static int darkSteelBootsJumpPowerCost = 150; public static int darkSteelFallDistanceCost = 75; public static float darkSteelSwordPoweredDamageBonus = 1.0f; public static float darkSteelSwordPoweredSpeedBonus = 0.4f; public static float darkSteelSwordWitherSkullChance = 0.05f; public static float darkSteelSwordWitherSkullLootingModifier = 0.05f; public static float darkSteelSwordSkullChance = 0.1f; public static float darkSteelSwordSkullLootingModifier = 0.075f; public static float vanillaSwordSkullLootingModifier = 0.05f; public static float vanillaSwordSkullChance = 0.05f; public static float ticCleaverSkullDropChance = 0.1f; public static float ticBeheadingSkullModifier = 0.075f; public static float fakePlayerSkullChance = 0.5f; public static int darkSteelSwordPowerUsePerHit = 750; public static double darkSteelSwordEnderPearlDropChance = 1; public static double darkSteelSwordEnderPearlDropChancePerLooting = 0.5; public static int darkSteelPickEffeciencyObsidian = 50; public static int darkSteelPickPowerUseObsidian = 10000; public static float darkSteelPickApplyObsidianEffeciencyAtHardess = 40; public static int darkSteelPickPowerUsePerDamagePoint = 750; public static float darkSteelPickEffeciencyBoostWhenPowered = 2; public static boolean darkSteelPickMinesTiCArdite = true; public static int darkSteelAxePowerUsePerDamagePoint = 750; public static int darkSteelAxePowerUsePerDamagePointMultiHarvest = 1500; public static float darkSteelAxeEffeciencyBoostWhenPowered = 2; public static float darkSteelAxeSpeedPenaltyMultiHarvest = 4; public static int darkSteelShearsDurabilityFactor = 5; public static int darkSteelShearsPowerUsePerDamagePoint = 250; public static float darkSteelShearsEffeciencyBoostWhenPowered = 2.0f; public static int darkSteelShearsBlockAreaBoostWhenPowered = 2; public static float darkSteelShearsEntityAreaBoostWhenPowered = 3.0f; public static int darkSteelUpgradeVibrantCost = 4; public static int darkSteelUpgradePowerOneCost = 4; public static int darkSteelUpgradePowerTwoCost = 6; public static int darkSteelUpgradePowerThreeCost = 8; public static int darkSteelGliderCost = 4; public static double darkSteelGliderHorizontalSpeed = 0.03; public static double darkSteelGliderVerticalSpeed = -0.05; public static double darkSteelGliderVerticalSpeedSprinting = -0.15; public static int darkSteelGogglesOfRevealingCost = 4; public static int darkSteelApiaristArmorCost = 4; public static int darkSteelSwimCost = 4; public static int darkSteelNightVisionCost = 4; public static int darkSteelTOPCost = 4; public static int darkSteelSoundLocatorCost = 4; public static int darkSteelSoundLocatorRange = 40; public static int darkSteelSoundLocatorLifespan = 40; public static int darkSteelTravelCost = 16; public static int darkSteelSpoonCost = 4; public static int darkSteelSolarOneGen = 10; public static int darkSteelSolarOneCost = 4; public static int darkSteelSolarTwoGen = 40; public static int darkSteelSolarTwoCost = 8; public static int darkSteelSolarThreeGen = 80; public static int darkSteelSolarThreeCost = 24; public static boolean darkSteelSolarChargeOthers = true; public static float darkSteelAnvilDamageChance = 0.024f; public static float darkSteelLadderSpeedBoost = 0.06f; public static int hootchPowerPerCycleRF = 60; public static int hootchPowerTotalBurnTime = 6000; public static int rocketFuelPowerPerCycleRF = 160; public static int rocketFuelPowerTotalBurnTime = 7000; public static int fireWaterPowerPerCycleRF = 80; public static int fireWaterPowerTotalBurnTime = 15000; public static int vatPowerUserPerTickRF = 20; public static int maxPhotovoltaicOutputRF = 10; public static int maxPhotovoltaicAdvancedOutputRF = 40; public static int maxPhotovoltaicVibrantOutputRF = 160; public static int zombieGeneratorRfPerTick = 80; public static int zombieGeneratorTicksPerBucketFuel = 10000; public static boolean addFuelTooltipsToAllFluidContainers = true; public static boolean addFurnaceFuelTootip = true; public static boolean addDurabilityTootip = true; public static int farmActionEnergyUseRF = 500; public static int farmAxeActionEnergyUseRF = 1000; public static int farmBonemealActionEnergyUseRF = 160; public static int farmBonemealTryEnergyUseRF = 80; public static boolean farmAxeDamageOnLeafBreak = false; public static float farmToolTakeDamageChance = 1; public static boolean disableFarmNotification = false; public static boolean farmEssenceBerriesEnabled = true; public static boolean farmManaBeansEnabled = false; public static boolean farmHarvestJungleWhenCocoa = false; public static String[] hoeStrings = new String[] { "minecraft:wooden_hoe", "minecraft:stone_hoe", "minecraft:iron_hoe", "minecraft:diamond_hoe", "minecraft:golden_hoe", "MekanismTools:ObsidianHoe", "MekanismTools:LapisLazuliHoe", "MekanismTools:OsmiumHoe", "MekanismTools:BronzeHoe", "MekanismTools:GlowstoneHoe", "MekanismTools:SteelHoe", "Steamcraft:hoeBrass", "Steamcraft:hoeGildedGold", "Railcraft:tool.steel.hoe", "TConstruct:mattock", "appliedenergistics2:item.ToolCertusQuartzHoe", "appliedenergistics2:item.ToolNetherQuartzHoe", "ProjRed|Exploration:projectred.exploration.hoeruby", "ProjRed|Exploration:projectred.exploration.hoesapphire", "ProjRed|Exploration:projectred.exploration.hoeperidot", "magicalcrops:magicalcrops_AccioHoe", "magicalcrops:magicalcrops_CrucioHoe", "magicalcrops:magicalcrops_ImperioHoe", // disabled as it is currently not unbreaking as advertised "magicalcrops:magicalcrops_ZivicioHoe", "magicalcrops:magicalcropsarmor_AccioHoe", "magicalcrops:magicalcropsarmor_CrucioHoe", "magicalcrops:magicalcropsarmor_ImperioHoe", "BiomesOPlenty:hoeAmethyst", "BiomesOPlenty:hoeMud", "Eln:Eln.Copper Hoe", "Thaumcraft:ItemHoeThaumium", "Thaumcraft:ItemHoeElemental", "Thaumcraft:ItemHoeVoid", "ThermalFoundation:tool.hoeInvar", "ThermalFoundation:tool.hoeCopper", "ThermalFoundation:tool.hoeBronze", "ThermalFoundation:tool.hoeSilver", "ThermalFoundation:tool.hoeElectrum", "ThermalFoundation:tool.hoeTin", "ThermalFoundation:tool.hoeLead", "ThermalFoundation:tool.hoeNickel", "ThermalFoundation:tool.hoePlatinum", "TwilightForest:item.steeleafHoe", "TwilightForest:item.ironwoodHoe", "IC2:itemToolBronzeHoe", "techreborn:bronzeHoe", "techreborn:rubyHoe", "techreborn:sapphireHoe", "techreborn:peridotHoe", "basemetals:adamantine_hoe", "basemetals:aquarium_hoe", "basemetals:brass_hoe", "basemetals:bronze_hoe", "basemetals:coldiron_hoe", "basemetals:copper_hoe", "basemetals:cupronickel_hoe", "basemetals:electrum_hoe", "basemetals:invar_hoe", "basemetals:lead_hoe", "basemetals:mithril_hoe", "basemetals:nickel_hoe", "basemetals:platinum_hoe", "basemetals:silver_hoe", "basemetals:starsteel_hoe", "basemetals:steel_hoe", "basemetals:tin_hoe", "actuallyadditions:itemHoeQuartz", "actuallyadditions:itemHoeEmerald", "actuallyadditions:itemHoeObsidian", "actuallyadditions:itemHoeCrystalRed", "actuallyadditions:itemHoeCrystalBlue", "actuallyadditions:itemHoeCrystalLightBlue", "actuallyadditions:itemHoeCrystalBlack", "actuallyadditions:itemHoeCrystalGreen", "actuallyadditions:itemHoeCrystalWhite", "silentgems:Hoe", "ic2:bronze_hoe" // IC2exp }; public static Things farmHoes = new Things(); public static int farmSaplingReserveAmount = 8; public static boolean farmStopOnNoOutputSlots = true; public static boolean farmEvictEmptyRFTools = true; public static int magnetPowerUsePerSecondRF = 1; public static int magnetPowerCapacityRF = 100000; public static int magnetRange = 5; public static String[] magnetBlacklist = new String[] { "appliedenergistics2:item.ItemCrystalSeed", "Botania:livingrock", "Botania:manaTablet" }; public static int magnetMaxItems = 20; public static boolean magnetAllowInMainInventory = false; public static boolean magnetAllowInBaublesSlot = true; public static boolean magnetAllowDeactivatedInBaublesSlot = false; public static boolean magnetAllowPowerExtraction = false; public static String magnetBaublesType = "AMULET"; public static int crafterRfPerCraft = 2500; public static int capacitorBankMaxIoRF = 5000; public static int capacitorBankMaxStorageRF = 5000000; public static int capacitorBankTierOneMaxIoRF = 1000; public static int capacitorBankTierOneMaxStorageRF = 1000000; public static int capacitorBankTierTwoMaxIoRF = 5000; public static int capacitorBankTierTwoMaxStorageRF = 5000000; public static int capacitorBankTierThreeMaxIoRF = 25000; public static int capacitorBankTierThreeMaxStorageRF = 25000000; public static boolean capacitorBankRenderPowerOverlayOnItem = false; public static int poweredSpawnerMinDelayTicks = 200; public static int poweredSpawnerMaxDelayTicks = 800; public static int poweredSpawnerMaxPlayerDistance = 0; public static int poweredSpawnerDespawnTimeSeconds = 120; public static int poweredSpawnerSpawnCount = 4; public static int poweredSpawnerSpawnRange = 4; public static int poweredSpawnerMaxNearbyEntities = 6; public static int poweredSpawnerMaxSpawnTries = 3; public static boolean poweredSpawnerUseVanillaSpawChecks = false; public static double brokenSpawnerDropChance = 1; public static String[] brokenSpawnerToolBlacklist = new String[] { "RotaryCraft:rotarycraft_item_bedpick" }; public static int powerSpawnerAddSpawnerCost = 16; public static int painterEnergyPerTaskRF = 2000; public static int vacuumChestRange = 6; public static int wirelessChargerRange = 24; public static long nutrientFoodBoostDelay = 400; public static int enchanterBaseLevelCost = 2; public static double enchanterLevelCostFactor = 0.75; public static double enchanterLapisCostFactor = 3; public static boolean machineSoundsEnabled = true; public static float machineSoundVolume = 1.0f; public static int killerJoeNutrientUsePerAttackMb = 5; public static double killerJoeAttackHeight = 2; public static double killerJoeAttackWidth = 2; public static double killerJoeAttackLength = 4; public static double killerJoeHooverXpWidth = 5; public static double killerJoeHooverXpLength = 10; public static int killerJoeMaxXpLevel = Integer.MAX_VALUE; public static boolean killerJoeMustSee = false; public static boolean killerPvPoffDisablesSwing = false; public static boolean killerPvPoffIsIgnored = false; public static boolean killerMending = false; public static boolean allowTileEntitiesAsPaintSource = true; public static boolean isGasConduitEnabled = true; public static boolean enableMEConduits = true; public static boolean enableOCConduits = true; public static boolean enableOCConduitsAnimatedTexture = true; public static List<String> soulVesselBlackList = Collections.<String> emptyList(); public static boolean soulVesselCapturesBosses = false; public static int soulBinderBrokenSpawnerRF = 2500000; public static int soulBinderBrokenSpawnerLevels = 6; public static int soulBinderReanimationRF = 100000; public static int soulBinderReanimationLevels = 4; public static int soulBinderEnderCystalRF = 100000; public static int soulBinderEnderCystalLevels = 4; public static int soulBinderAttractorCystalRF = 100000; public static int soulBinderAttractorCystalLevels = 4; public static int soulBinderEnderRailRF = 100000; public static int soulBinderEnderRailLevels = 4; public static int soulBinderTunedPressurePlateLevels = 2; public static int soulBinderTunedPressurePlateRF = 250000; public static int soulBinderMaxXpLevel = 40; public static boolean powerConduitCanDifferentTiersConnect = false; public static int powerConduitTierOneRF = 640; public static int powerConduitTierTwoRF = 5120; public static int powerConduitTierThreeRF = 20480; public static boolean powerConduitOutputMJ = true; public static boolean spawnGuardStopAllSlimesDebug = false; public static boolean spawnGuardStopAllSquidSpawning = false; public static int weatherObeliskClearFluid = 2000; public static int weatherObeliskRainFluid = 500; public static int weatherObeliskThunderFluid = 1000; //Loot Defaults public static boolean lootDarkSteel = true; public static boolean lootItemConduitProbe = true; public static boolean lootQuartz = true; public static boolean lootNetherWart = true; public static boolean lootEnderPearl = true; public static boolean lootElectricSteel = true; public static boolean lootRedstoneAlloy = true; public static boolean lootPhasedIron = true; public static boolean lootPhasedGold = true; public static boolean lootTravelStaff = true; public static boolean lootTheEnder = true; public static boolean lootDarkSteelBoots = true; public static boolean dumpMobNames = false; public static boolean enderRailEnabled = true; public static int enderRailPowerRequireCrossDimensions = 10000; public static int enderRailPowerRequiredPerBlock = 10; public static boolean enderRailCapSameDimensionPowerAtCrossDimensionCost = true; public static int enderRailTicksBeforeForceSpawningLinkedCarts = 60; public static boolean enderRailTeleportPlayers = false; public static int xpObeliskMaxXpLevel = Integer.MAX_VALUE; public static String xpJuiceName = "xpjuice"; public static boolean clearGlassConnectToFusedQuartz = false; public static boolean glassConnectToTheirVariants = true; public static boolean glassConnectToTheirColorVariants = true; public static Rarity enchantmentSoulBoundWeight = Rarity.UNCOMMON; public static boolean enchantmentSoulBoundEnabled = true; public static boolean telepadLockDimension = true; public static boolean telepadLockCoords = true; public static int telepadPowerCoefficient = 100000; public static int telepadPowerInterdimensional = 100000; public static boolean inventoryPanelFree = false; public static float inventoryPanelPowerPerMB = 800.0f; public static float inventoryPanelScanCostPerSlot = 0.1f; public static float inventoryPanelExtractCostPerItem = 12.0f; public static float inventoryPanelExtractCostPerOperation = 32.0f; public static boolean inventoryPanelScaleText = true; public static int remoteInventoryMBPerOpen = 100; public static int remoteInventoryRFPerTick = 4; public static int remoteInventoryMBCapacity = 2000; public static int remoteInventoryRFCapacity = 60000; public static boolean photovoltaicCanTypesJoins = true; public static int photovoltaicRecalcSunTick = 100; public static boolean debugUpdatePackets = false; public static boolean topEnabled = true; public static boolean topShowProgressByDefault = true; public static boolean topShowPowerByDefault = true; public static boolean topShowRedstoneByDefault = false; public static boolean topShowSideConfigByDefault = false; public static boolean topShowRangeByDefault = false; public static boolean topShowMobsByDefault = true; public static boolean topShowTanksByDefault = true; public static boolean paintedGlowstoneRequireSilkTouch = false; public static void load(FMLPreInitializationEvent event) { PacketHandler.INSTANCE.registerMessage(PacketConfigSync.class, PacketConfigSync.class, PacketHandler.nextID(), Side.CLIENT); MinecraftForge.EVENT_BUS.register(new Config()); configDirectory = new File(event.getModConfigurationDirectory(), EnderIO.DOMAIN); if(!configDirectory.exists()) { configDirectory.mkdir(); } File configFile = new File(configDirectory, "EnderIO.cfg"); config = new Configuration(configFile); syncConfig(false); } public static void syncConfig(boolean load) { try { if (load) { config.load(); } Config.processConfig(config); } catch (Exception e) { Log.error("EnderIO has a problem loading it's configuration"); e.printStackTrace(); } finally { if(config.hasChanged()) { config.save(); } } } @SubscribeEvent public void onConfigChanged(OnConfigChangedEvent event) { if (event.getModID().equals(EnderIO.MODID)) { Log.info("Updating config..."); syncConfig(false); init(); postInit(); } } @SubscribeEvent public void onConfigFileChanged(ConfigFileChangedEvent event) { if (event.getModID().equals(EnderIO.MODID)) { Log.info("Updating config..."); syncConfig(true); event.setSuccessful(); init(); postInit(); } } @SubscribeEvent public void onPlayerLoggon(PlayerLoggedInEvent evt) { PacketHandler.INSTANCE.sendTo(new PacketConfigSync(), (EntityPlayerMP) evt.player); } public static void processConfig(Configuration config) { capacitorBankMaxIoRF = config.get(sectionPower.name, "capacitorBankMaxIoRF", capacitorBankMaxIoRF, "The maximum IO for a single capacitor in RF/t") .getInt(capacitorBankMaxIoRF); capacitorBankMaxStorageRF = config.get(sectionPower.name, "capacitorBankMaxStorageRF", capacitorBankMaxStorageRF, "The maximum storage for a single capacitor in RF") .getInt(capacitorBankMaxStorageRF); capacitorBankTierOneMaxIoRF = config.get(sectionPower.name, "capacitorBankTierOneMaxIoRF", capacitorBankTierOneMaxIoRF, "The maximum IO for a single tier one capacitor in RF/t") .getInt(capacitorBankTierOneMaxIoRF); capacitorBankTierOneMaxStorageRF = config.get(sectionPower.name, "capacitorBankTierOneMaxStorageRF", capacitorBankTierOneMaxStorageRF, "The maximum storage for a single tier one capacitor in RF") .getInt(capacitorBankTierOneMaxStorageRF); capacitorBankTierTwoMaxIoRF = config.get(sectionPower.name, "capacitorBankTierTwoMaxIoRF", capacitorBankTierTwoMaxIoRF, "The maximum IO for a single tier two capacitor in RF/t") .getInt(capacitorBankTierTwoMaxIoRF); capacitorBankTierTwoMaxStorageRF = config.get(sectionPower.name, "capacitorBankTierTwoMaxStorageRF", capacitorBankTierTwoMaxStorageRF, "The maximum storage for a single tier two capacitor in RF") .getInt(capacitorBankTierTwoMaxStorageRF); capacitorBankTierThreeMaxIoRF = config.get(sectionPower.name, "capacitorBankTierThreeMaxIoRF", capacitorBankTierThreeMaxIoRF, "The maximum IO for a single tier three capacitor in RF/t") .getInt(capacitorBankTierThreeMaxIoRF); capacitorBankTierThreeMaxStorageRF = config.get(sectionPower.name, "capacitorBankTierThreeMaxStorageRF", capacitorBankTierThreeMaxStorageRF, "The maximum storage for a single tier three capacitor in RF") .getInt(capacitorBankTierThreeMaxStorageRF); capacitorBankRenderPowerOverlayOnItem = config.getBoolean("capacitorBankRenderPowerOverlayOnItem", sectionAesthetic.name, capacitorBankRenderPowerOverlayOnItem, "When true the the capacitor bank item wil get a power bar in addition to the gauge on the bank"); powerConduitTierOneRF = config.get(sectionPower.name, "powerConduitTierOneRF", powerConduitTierOneRF, "The maximum IO for the tier 1 power conduit") .getInt(powerConduitTierOneRF); powerConduitTierTwoRF = config.get(sectionPower.name, "powerConduitTierTwoRF", powerConduitTierTwoRF, "The maximum IO for the tier 2 power conduit") .getInt(powerConduitTierTwoRF); powerConduitTierThreeRF = config.get(sectionPower.name, "powerConduitTierThreeRF", powerConduitTierThreeRF, "The maximum IO for the tier 3 power conduit") .getInt(powerConduitTierThreeRF); powerConduitCanDifferentTiersConnect = config .getBoolean("powerConduitCanDifferentTiersConnect", sectionPower.name, powerConduitCanDifferentTiersConnect, "If set to false power conduits of different tiers cannot be connected. in this case a block such as a cap. bank is needed to bridge different tiered networks"); powerConduitOutputMJ = config.getBoolean("powerConduitOutputMJ", sectionPower.name, powerConduitOutputMJ, "When set to true power conduits will output MJ if RF is not supported"); painterEnergyPerTaskRF = config.get(sectionPower.name, "painterEnergyPerTaskRF", painterEnergyPerTaskRF, "The total amount of RF required to paint one block") .getInt(painterEnergyPerTaskRF); recipeLevel = config.get(sectionRecipe.name, "recipeLevel", recipeLevel, "How expensive should the crafting recipes be? -1=don't register any crafting/smelting recipes, 0=cheapest, 1=cheaper, 2=normal, 3=expensive").getInt( recipeLevel); registerRecipes = config .get(sectionRecipe.name, "registerRecipes", registerRecipes, "If set to false: No crafting recipes (crafting table and furnace) will be registered. You need to use Creative mode or something like minetweaker to add them yourself.") .getBoolean(registerRecipes); addPeacefulRecipes = config.get(sectionRecipe.name, "addPeacefulRecipes", addPeacefulRecipes, "When enabled peaceful recipes are added for soulbinder based crafting components.") .getBoolean(addPeacefulRecipes); allowTileEntitiesAsPaintSource = config.get(sectionRecipe.name, "allowTileEntitiesAsPaintSource", allowTileEntitiesAsPaintSource, "When enabled blocks with tile entities (e.g. machines) can be used as paint targets.") .getBoolean(allowTileEntitiesAsPaintSource); createSyntheticRecipes = config .get( sectionRecipe.name, "createSyntheticRecipes", createSyntheticRecipes, "Automatically create alloy smelter recipes with double and tripple inputs and different slot allocations (1+1+1, 2+1, 1+2, 3 and 2) for single-input recipes.") .getBoolean(createSyntheticRecipes); redstoneConduitsShowState = config.get(sectionMisc.name, "redstoneConduitsShowState", redstoneConduitsShowState, "If set to false redstone conduits will look the same whether they are recieving a signal or not. This can help with performance.") .getBoolean(redstoneConduitsShowState); enchanterBaseLevelCost = config.get(sectionRecipe.name, "enchanterBaseLevelCost", enchanterBaseLevelCost, "Base level cost added to all recipes in the enchanter.").getInt(enchanterBaseLevelCost); enchanterLevelCostFactor = config.get(sectionRecipe.name, "enchanterLevelCostFactor", enchanterLevelCostFactor, "The final XP cost for an enchantment is multiplied by this value. To halve costs set to 0.5, to double them set it to 2").getDouble(enchanterLevelCostFactor); enchanterLapisCostFactor = config.get(sectionRecipe.name, "enchanterLapisCostFactor", enchanterLapisCostFactor, "The lapis cost is enchant level multiplied by this value").getDouble(enchanterLapisCostFactor); photovoltaicCellEnabled = config.get(sectionItems.name, "photovoltaicCellEnabled", photovoltaicCellEnabled, "If set to false: Photovoltaic Cells will not be craftable.") .getBoolean(photovoltaicCellEnabled); reservoirEnabled= config.get(sectionItems.name, "reservoirEnabled", reservoirEnabled, "If set to false reservoirs will not be craftable.") .getBoolean(reservoirEnabled); transceiverEnabled = config.get(sectionItems.name, "transceiverEnabled", transceiverEnabled, "If set to false: Dimensional Transceivers will not be craftable.") .getBoolean(transceiverEnabled); maxPhotovoltaicOutputRF = config.get(sectionPower.name, "maxPhotovoltaicOutputRF", maxPhotovoltaicOutputRF, "Maximum output in RF/t of the Photovoltaic Panels.").getInt(maxPhotovoltaicOutputRF); maxPhotovoltaicAdvancedOutputRF = config.get(sectionPower.name, "maxPhotovoltaicAdvancedOutputRF", maxPhotovoltaicAdvancedOutputRF, "Maximum output in RF/t of the Advanced Photovoltaic Panels.").getInt(maxPhotovoltaicAdvancedOutputRF); maxPhotovoltaicVibrantOutputRF = config.get(sectionPower.name, "maxPhotovoltaicVibrantOutputRF", maxPhotovoltaicVibrantOutputRF, "Maximum output in RF/t of the Vibrant Photovoltaic Panels.").getInt(maxPhotovoltaicVibrantOutputRF); photovoltaicCanTypesJoins = config.get(sectionPower.name, "photovoltaicCanTypesJoins", photovoltaicCanTypesJoins, "When enabled Photovoltaic Panels of different kinds can join together as a multi-block").getBoolean(photovoltaicCanTypesJoins); photovoltaicRecalcSunTick = config.get(sectionPower.name, "photovoltaicRecalcSunTick", photovoltaicRecalcSunTick, "How often (in ticks) the Photovoltaic Panels should check the sun's angle.").getInt(photovoltaicRecalcSunTick); conduitScale = config.get(sectionAesthetic.name, "conduitScale", DEFAULT_CONDUIT_SCALE, "Valid values are between 0-1, smallest conduits at 0, largest at 1.\n" + "In SMP, all clients must be using the same value as the server.").getDouble(DEFAULT_CONDUIT_SCALE); conduitScale = VecmathUtil.clamp(conduitScale, 0, 1); wirelessChargerRange = config.get(sectionEfficiency.name, "wirelessChargerRange", wirelessChargerRange, "The range of the wireless charger").getInt(wirelessChargerRange); fluidConduitExtractRate = config.get(sectionEfficiency.name, "fluidConduitExtractRate", fluidConduitExtractRate, "Number of millibuckets per tick extracted by a fluid conduits auto extracting").getInt(fluidConduitExtractRate); fluidConduitMaxIoRate = config.get(sectionEfficiency.name, "fluidConduitMaxIoRate", fluidConduitMaxIoRate, "Number of millibuckets per tick that can pass through a single connection to a fluid conduit.").getInt(fluidConduitMaxIoRate); advancedFluidConduitExtractRate = config.get(sectionEfficiency.name, "advancedFluidConduitExtractRate", advancedFluidConduitExtractRate, "Number of millibuckets per tick extracted by pressurized fluid conduits auto extracting").getInt(advancedFluidConduitExtractRate); advancedFluidConduitMaxIoRate = config.get(sectionEfficiency.name, "advancedFluidConduitMaxIoRate", advancedFluidConduitMaxIoRate, "Number of millibuckets per tick that can pass through a single connection to an pressurized fluid conduit.").getInt(advancedFluidConduitMaxIoRate); enderFluidConduitExtractRate = config.get(sectionEfficiency.name, "enderFluidConduitExtractRate", enderFluidConduitExtractRate, "Number of millibuckets per tick extracted by ender fluid conduits auto extracting").getInt(enderFluidConduitExtractRate); enderFluidConduitMaxIoRate = config.get(sectionEfficiency.name, "enderFluidConduitMaxIoRate", enderFluidConduitMaxIoRate, "Number of millibuckets per tick that can pass through a single connection to an ender fluid conduit.").getInt(enderFluidConduitMaxIoRate); gasConduitExtractRate = config.get(sectionEfficiency.name, "gasConduitExtractRate", gasConduitExtractRate, "Amount of gas per tick extracted by gas conduits auto extracting").getInt(gasConduitExtractRate); gasConduitMaxIoRate = config.get(sectionEfficiency.name, "gasConduitMaxIoRate", gasConduitMaxIoRate, "Amount of gas per tick that can pass through a single connection to a gas conduit.").getInt(gasConduitMaxIoRate); useAlternateTesseractModel = config.get(sectionAesthetic.name, "useAlternateTransceiverModel", useAlternateTesseractModel, "Use TheKazador's alternative model for the Dimensional Transceiver") .getBoolean(false); transceiverEnergyLoss = config.get(sectionPower.name, "transceiverEnergyLoss", transceiverEnergyLoss, "Amount of energy lost when transfered by Dimensional Transceiver; 0 is no loss, 1 is 100% loss").getDouble(transceiverEnergyLoss); transceiverBucketTransmissionCostRF = config.get(sectionEfficiency.name, "transceiverBucketTransmissionCostRF", transceiverBucketTransmissionCostRF, "The cost in RF of transporting a bucket of fluid via a Dimensional Transceiver.").getInt(transceiverBucketTransmissionCostRF); vatPowerUserPerTickRF = config.get(sectionPower.name, "vatPowerUserPerTickRF", vatPowerUserPerTickRF, "Power use (RF/t) used by the vat.").getInt(vatPowerUserPerTickRF); detailedPowerTrackingEnabled = config .get( sectionAdvanced.name, "perInterfacePowerTrackingEnabled", detailedPowerTrackingEnabled, "Enable per tick sampling on individual power inputs and outputs. This allows slightly more detailed messages from the RF Reader but has a negative impact on server performance.") .getBoolean(detailedPowerTrackingEnabled); jeiUseShortenedPainterRecipes = config .get(sectionPersonal.name, "jeiUseShortenedPainterRecipes", jeiUseShortenedPainterRecipes, "If true, only a handful of sample painter recipes will be shown in JEI. Enable this if you have timing problems starting a world or logging into a server.") .getBoolean(jeiUseShortenedPainterRecipes); useSneakMouseWheelYetaWrench = config.get(sectionPersonal.name, "useSneakMouseWheelYetaWrench", useSneakMouseWheelYetaWrench, "If true, shift-mouse wheel will change the conduit display mode when the YetaWrench is equipped.") .getBoolean(useSneakMouseWheelYetaWrench); useSneakRightClickYetaWrench = config.get(sectionPersonal.name, "useSneakRightClickYetaWrench", useSneakRightClickYetaWrench, "If true, shift-clicking the YetaWrench on a null or non wrenchable object will change the conduit display mode.").getBoolean( useSneakRightClickYetaWrench); yetaWrenchOverlayMode = config.getInt("yetaWrenchOverlayMode",sectionPersonal.name, yetaWrenchOverlayMode, 0, 2, "What kind of overlay to use when holding the yeta wrench\n\n" + "0 - Sideways scrolling in ceter of screen\n" + "1 - Vertical icon bar in bottom right\n" + "2 - Old-style group of icons in bottom right"); machineSoundsEnabled = config.get(sectionPersonal.name, "useMachineSounds", machineSoundsEnabled, "If true, machines will make sounds.").getBoolean( machineSoundsEnabled); machineSoundVolume = (float) config.get(sectionPersonal.name, "machineSoundVolume", machineSoundVolume, "Volume of machine sounds.").getDouble( machineSoundVolume); itemConduitUsePhyscialDistance = config.get(sectionEfficiency.name, "itemConduitUsePhyscialDistance", itemConduitUsePhyscialDistance, "If true, " + "'line of sight' distance rather than conduit path distance is used to calculate priorities.") .getBoolean(itemConduitUsePhyscialDistance); vacuumChestRange = config.get(sectionEfficiency.name, "vacumChestRange", vacuumChestRange, "The range of the vacuum chest").getInt(vacuumChestRange); reinforcedObsidianEnabled = config.get(sectionItems.name, "reinforcedObsidianEnabled", reinforcedObsidianEnabled, "When set to false reinforced obsidian is not craftable.").getBoolean(reinforcedObsidianEnabled); travelAnchorEnabled = config.get(sectionItems.name, "travelAnchorEnabled", travelAnchorEnabled, "When set to false: the travel anchor will not be craftable.").getBoolean(travelAnchorEnabled); travelAnchorMaximumDistance = config.get(sectionAnchor.name, "travelAnchorMaxDistance", travelAnchorMaximumDistance, "Maximum number of blocks that can be traveled from one travel anchor to another.").getInt(travelAnchorMaximumDistance); travelAnchorCooldown = config.get(sectionAnchor.name, "travelAnchorCooldown", travelAnchorCooldown, "Number of ticks cooldown between activations (1 sec = 20 ticks)").getInt(travelAnchorCooldown); travelAnchorSneak = config.get(sectionAnchor.name, "travelAnchorSneak", travelAnchorSneak, "Add sneak as an option to activate travel anchors").getBoolean(travelAnchorSneak); travelAnchorSkipWarning = config.get(sectionAnchor.name, "travelAnchorSkipWarning", travelAnchorSkipWarning, "Travel Anchors send a chat warning when skipping inaccessible anchors").getBoolean(travelAnchorSkipWarning); travelStaffMaximumDistance = config.get(sectionStaff.name, "travelStaffMaxDistance", travelStaffMaximumDistance, "Maximum number of blocks that can be traveled using the Staff of Traveling.").getInt(travelStaffMaximumDistance); travelStaffPowerPerBlockRF = (float) config.get(sectionStaff.name, "travelStaffPowerPerBlockRF", travelStaffPowerPerBlockRF, "Number of RF required per block traveled using the Staff of Traveling.").getDouble(travelStaffPowerPerBlockRF); travelStaffMaxBlinkDistance = config.get(sectionStaff.name, "travelStaffMaxBlinkDistance", travelStaffMaxBlinkDistance, "Max number of blocks teleported when shift clicking the staff.").getInt(travelStaffMaxBlinkDistance); travelStaffBlinkPauseTicks = config.get(sectionStaff.name, "travelStaffBlinkPauseTicks", travelStaffBlinkPauseTicks, "Minimum number of ticks between 'blinks'. Values of 10 or less allow a limited sort of flight.").getInt(travelStaffBlinkPauseTicks); travelStaffEnabled = config.get(sectionStaff.name, "travelStaffEnabled", travelStaffEnabled, "If set to false: the travel staff will not be craftable.").getBoolean(travelStaffEnabled); travelStaffBlinkEnabled = config.get(sectionStaff.name, "travelStaffBlinkEnabled", travelStaffBlinkEnabled, "If set to false: the travel staff can not be used to shift-right click teleport, or blink.").getBoolean(travelStaffBlinkEnabled); travelStaffBlinkThroughSolidBlocksEnabled = config.get(sectionStaff.name, "travelStaffBlinkThroughSolidBlocksEnabled", travelStaffBlinkThroughSolidBlocksEnabled, "If set to false: the travel staff can be used to blink through any block.").getBoolean(travelStaffBlinkThroughSolidBlocksEnabled); travelStaffBlinkThroughClearBlocksEnabled = config .get(sectionItems.name, "travelStaffBlinkThroughClearBlocksEnabled", travelStaffBlinkThroughClearBlocksEnabled, "If travelStaffBlinkThroughSolidBlocksEnabled is set to false and this is true: the travel " + "staff can only be used to blink through transparent or partial blocks (e.g. torches). " + "If both are false: only air blocks may be teleported through.") .getBoolean(travelStaffBlinkThroughClearBlocksEnabled); travelStaffBlinkThroughUnbreakableBlocksEnabled = config.get(sectionItems.name, "travelStaffBlinkThroughUnbreakableBlocksEnabled", travelStaffBlinkThroughUnbreakableBlocksEnabled, "Allows the travel staff to blink through unbreakable blocks such as warded blocks and bedrock.") .getBoolean(); travelStaffBlinkBlackList = config.getStringList("travelStaffBlinkBlackList", sectionStaff.name, travelStaffBlinkBlackList, "Lists the blocks that cannot be teleported through in the form 'modID:blockName'"); travelAnchorZoomScale = config.getFloat("travelAnchorZoomScale", sectionStaff.name, travelAnchorZoomScale, 0, 1, "Set the max zoomed size of a travel anchor as an aprox. percentage of screen height"); travelStaffOffhandBlinkEnabled = config .get(sectionStaff.name, "travelStaffOffhandBlinkEnabled", travelStaffOffhandBlinkEnabled, "If set to false: the travel staff can not be used to shift-right click teleport, or blink, when held in the off-hand.") .getBoolean(travelStaffOffhandBlinkEnabled); travelStaffOffhandTravelEnabled = config .get(sectionStaff.name, "travelStaffOffhandTravelEnabled", travelStaffOffhandTravelEnabled, "If set to false: the travel staff can not be used to click teleport to Travel Anchors, when held in the off-hand.") .getBoolean(travelStaffOffhandTravelEnabled); travelStaffOffhandEnderIOEnabled = config .get(sectionStaff.name, "travelStaffOffhandEnderIOEnabled", travelStaffOffhandEnderIOEnabled, "If set to false: the travel staff can not be used to activate the Ender IO, when held in the off-hand.") .getBoolean(travelStaffOffhandEnderIOEnabled); travelStaffOffhandShowsTravelTargets = config .get(sectionStaff.name, "travelStaffOffhandShowsTravelTargets", travelStaffOffhandShowsTravelTargets, "If set to false: Teleportation targets will not be highlighted for travel items held in the off-hand.") .getBoolean(travelStaffOffhandShowsTravelTargets); enderIoRange = config.get(sectionEfficiency.name, "enderIoRange", enderIoRange, "Range accessible (in blocks) when using the Ender IO.").getInt(enderIoRange); enderIoMeAccessEnabled = config.get(sectionPersonal.name, "enderIoMeAccessEnabled", enderIoMeAccessEnabled, "If false: you will not be able to access a ME access or crafting terminal using the Ender IO.").getBoolean(enderIoMeAccessEnabled); updateLightingWhenHidingFacades = config.get(sectionEfficiency.name, "updateLightingWhenHidingFacades", updateLightingWhenHidingFacades, "When true: correct lighting is recalculated (client side) for conduit bundles when transitioning to" + " from being hidden behind a facade. This produces " + "better quality rendering but can result in frame stutters when switching to/from a wrench.") .getBoolean(updateLightingWhenHidingFacades); transparentFacesLetThroughBeaconBeam = config .get(sectionAdvanced.name, "transparentFacesLetThroughBeaconBeam", transparentFacesLetThroughBeaconBeam, "If true, transparent facades will not block the Beacon's beam. As side effect they will also let through a tiny amount of light.") .getBoolean(transparentFacesLetThroughBeaconBeam); darkSteelRightClickPlaceEnabled = config.get(sectionDarkSteel.name, "darkSteelRightClickPlaceEnabled", darkSteelRightClickPlaceEnabled, "Enable / disable right click to place block using dark steel tools.").getBoolean(darkSteelRightClickPlaceEnabled); darkSteelPowerDamgeAbsorptionRatios = config .get(sectionDarkSteel.name, "darkSteelPowerDamgeAbsorptionRatios", darkSteelPowerDamgeAbsorptionRatios, "A list of the amount of durability damage absorbed when items are powered. In order of upgrade level. 1=100% so items take no durability damage when powered.") .getDoubleList(); darkSteelPowerStorageBase = config.get(sectionDarkSteel.name, "darkSteelPowerStorageBase", darkSteelPowerStorageBase, "Base amount of power stored by dark steel items.").getInt(darkSteelPowerStorageBase); darkSteelPowerStorageLevelOne = config.get(sectionDarkSteel.name, "darkSteelPowerStorageLevelOne", darkSteelPowerStorageLevelOne, "Amount of power stored by dark steel items with a level 1 upgrade.").getInt(darkSteelPowerStorageLevelOne); darkSteelPowerStorageLevelTwo = config.get(sectionDarkSteel.name, "darkSteelPowerStorageLevelTwo", darkSteelPowerStorageLevelTwo, "Amount of power stored by dark steel items with a level 2 upgrade.").getInt(darkSteelPowerStorageLevelTwo); darkSteelPowerStorageLevelThree = config.get(sectionDarkSteel.name, "darkSteelPowerStorageLevelThree", darkSteelPowerStorageLevelThree, "Amount of power stored by dark steel items with a level 3 upgrade.").getInt(darkSteelPowerStorageLevelThree); darkSteelUpgradeVibrantCost = config.get(sectionDarkSteel.name, "darkSteelUpgradeVibrantCost", darkSteelUpgradeVibrantCost, "Number of levels required for the 'Empowered.").getInt(darkSteelUpgradeVibrantCost); darkSteelUpgradePowerOneCost = config.get(sectionDarkSteel.name, "darkSteelUpgradePowerOneCost", darkSteelUpgradePowerOneCost, "Number of levels required for the 'Power 1.").getInt(darkSteelUpgradePowerOneCost); darkSteelUpgradePowerTwoCost = config.get(sectionDarkSteel.name, "darkSteelUpgradePowerTwoCost", darkSteelUpgradePowerTwoCost, "Number of levels required for the 'Power 2.").getInt(darkSteelUpgradePowerTwoCost); darkSteelUpgradePowerThreeCost = config.get(sectionDarkSteel.name, "darkSteelUpgradePowerThreeCost", darkSteelUpgradePowerThreeCost, "Number of levels required for the 'Power 3' upgrade.").getInt(darkSteelUpgradePowerThreeCost); darkSteelJumpOneCost = config.get(sectionDarkSteel.name, "darkSteelJumpOneCost", darkSteelJumpOneCost, "Number of levels required for the 'Jump 1' upgrade.").getInt(darkSteelJumpOneCost); darkSteelJumpTwoCost = config.get(sectionDarkSteel.name, "darkSteelJumpTwoCost", darkSteelJumpTwoCost, "Number of levels required for the 'Jump 2' upgrade.").getInt(darkSteelJumpTwoCost); darkSteelJumpThreeCost = config.get(sectionDarkSteel.name, "darkSteelJumpThreeCost", darkSteelJumpThreeCost, "Number of levels required for the 'Jump 3' upgrade.").getInt(darkSteelJumpThreeCost); darkSteelSpeedOneCost = config.get(sectionDarkSteel.name, "darkSteelSpeedOneCost", darkSteelSpeedOneCost, "Number of levels required for the 'Speed 1' upgrade.").getInt(darkSteelSpeedOneCost); darkSteelSpeedTwoCost = config.get(sectionDarkSteel.name, "darkSteelSpeedTwoCost", darkSteelSpeedTwoCost, "Number of levels required for the 'Speed 2' upgrade.").getInt(darkSteelSpeedTwoCost); darkSteelSpeedThreeCost = config.get(sectionDarkSteel.name, "darkSteelSpeedThreeCost", darkSteelSpeedThreeCost, "Number of levels required for the 'Speed 3' upgrade.").getInt(darkSteelSpeedThreeCost); darkSteelSpeedLimitFovChanges = config.get(sectionDarkSteel.name, "darkSteelSpeedLimitFovChanges", darkSteelSpeedLimitFovChanges, "When true FOV changes will not be effected by speed upgrades. Vanilla FOV changes will still occur.").getBoolean(darkSteelSpeedLimitFovChanges); darkSteelSpeedDisableFovChanges = config.get(sectionDarkSteel.name, "darkSteelSpeedDisableFovChanges", darkSteelSpeedDisableFovChanges, "When true the FOV will be constant when the upgrade is in effect. For example, it will not vary at all when sprinting or flying").getBoolean(darkSteelSpeedDisableFovChanges); slotZeroPlacesEight = config.get(sectionDarkSteel.name, "shouldSlotZeroWrap", slotZeroPlacesEight, "Should the dark steel placement, when in the first (0th) slot, place the item in the last slot. If false, will place what's in the second slot.").getBoolean(); darkSteelSpeedOneWalkModifier = (float) config.get(sectionDarkSteel.name, "darkSteelSpeedOneWalkModifier", darkSteelSpeedOneWalkModifier, "Speed modifier applied when walking in the Dark Steel Boots with Speed I.").getDouble(darkSteelSpeedOneWalkModifier); darkSteelSpeedTwoWalkMultiplier = (float) config.get(sectionDarkSteel.name, "darkSteelSpeedTwoWalkMultiplier", darkSteelSpeedTwoWalkMultiplier, "Speed modifier applied when walking in the Dark Steel Boots with Speed I.").getDouble(darkSteelSpeedTwoWalkMultiplier); darkSteelSpeedThreeWalkMultiplier = (float) config.get(sectionDarkSteel.name, "darkSteelSpeedThreeWalkMultiplier", darkSteelSpeedThreeWalkMultiplier, "Speed modifier applied when walking in the Dark Steel Boots with Speed I.").getDouble(darkSteelSpeedThreeWalkMultiplier); darkSteelSpeedOneSprintModifier = (float) config.get(sectionDarkSteel.name, "darkSteelSpeedOneSprintModifier", darkSteelSpeedOneSprintModifier, "Speed modifier applied when walking in the Dark Steel Boots with Speed I.").getDouble(darkSteelSpeedOneSprintModifier); darkSteelSpeedTwoSprintMultiplier = (float) config.get(sectionDarkSteel.name, "darkSteelSpeedTwoSprintMultiplier", darkSteelSpeedTwoSprintMultiplier, "Speed modifier applied when walking in the Dark Steel Boots with Speed I.").getDouble(darkSteelSpeedTwoSprintMultiplier); darkSteelSpeedThreeSprintMultiplier = (float) config.get(sectionDarkSteel.name, "darkSteelSpeedThreeSprintMultiplier", darkSteelSpeedThreeSprintMultiplier, "Speed modifier applied when walking in the Dark Steel Boots with Speed I.").getDouble(darkSteelSpeedThreeSprintMultiplier); darkSteelBootsJumpModifier = config.get(sectionDarkSteel.name, "darkSteelBootsJumpModifier", darkSteelBootsJumpModifier, "Jump height modifier applied when jumping with Dark Steel Boots equipped").getDouble(darkSteelBootsJumpModifier); darkSteelPowerStorageBase = config.get(sectionDarkSteel.name, "darkSteelPowerStorage", darkSteelPowerStorageBase, "Amount of power stored (RF) per crystal in the armor items recipe.").getInt(darkSteelPowerStorageBase); darkSteelWalkPowerCost = config.get(sectionDarkSteel.name, "darkSteelWalkPowerCost", darkSteelWalkPowerCost, "Amount of power stored (RF) per block walked when wearing the dark steel boots.").getInt(darkSteelWalkPowerCost); darkSteelSprintPowerCost = config.get(sectionDarkSteel.name, "darkSteelSprintPowerCost", darkSteelWalkPowerCost, "Amount of power stored (RF) per block walked when wearing the dark steel boots.").getInt(darkSteelSprintPowerCost); darkSteelDrainPowerFromInventory = config.get(sectionDarkSteel.name, "darkSteelDrainPowerFromInventory", darkSteelDrainPowerFromInventory, "If true, dark steel armor will drain power stored (RF) in power containers in the players inventory.").getBoolean(darkSteelDrainPowerFromInventory); darkSteelBootsJumpPowerCost = config.get(sectionDarkSteel.name, "darkSteelBootsJumpPowerCost", darkSteelBootsJumpPowerCost, "Base amount of power used per jump (RF) dark steel boots. The second jump in a 'double jump' uses 2x this etc").getInt(darkSteelBootsJumpPowerCost); darkSteelFallDistanceCost = config.get(sectionDarkSteel.name, "darkSteelFallDistanceCost", darkSteelFallDistanceCost, "Amount of power used (RF) per block height of fall distance damage negated.").getInt(darkSteelFallDistanceCost); darkSteelSwimCost = config.get(sectionDarkSteel.name, "darkSteelSwimCost", darkSteelSwimCost, "Number of levels required for the 'Swim' upgrade.").getInt(darkSteelSwimCost); darkSteelNightVisionCost = config.get(sectionDarkSteel.name, "darkSteelNightVisionCost", darkSteelNightVisionCost, "Number of levels required for the 'Night Vision' upgrade.").getInt(darkSteelNightVisionCost); darkSteelTOPCost = config.get(sectionDarkSteel.name, "darkSteelTOPCost", darkSteelTOPCost, "Number of levels required for the 'The One Probe' upgrade.") .getInt(darkSteelTOPCost); darkSteelGliderCost = config.get(sectionDarkSteel.name, "darkSteelGliderCost", darkSteelGliderCost, "Number of levels required for the 'Glider' upgrade.").getInt(darkSteelGliderCost); darkSteelGliderHorizontalSpeed = config.get(sectionDarkSteel.name, "darkSteelGliderHorizontalSpeed", darkSteelGliderHorizontalSpeed, "Horizontal movement speed modifier when gliding.").getDouble(darkSteelGliderHorizontalSpeed); darkSteelGliderVerticalSpeed = config.get(sectionDarkSteel.name, "darkSteelGliderVerticalSpeed", darkSteelGliderVerticalSpeed, "Rate of altitude loss when gliding.").getDouble(darkSteelGliderVerticalSpeed); darkSteelGliderVerticalSpeedSprinting = config.get(sectionDarkSteel.name, "darkSteelGliderVerticalSpeedSprinting", darkSteelGliderVerticalSpeedSprinting, "Rate of altitude loss when sprinting and gliding.").getDouble(darkSteelGliderVerticalSpeedSprinting); darkSteelSoundLocatorCost = config.get(sectionDarkSteel.name, "darkSteelSoundLocatorCost", darkSteelSoundLocatorCost, "Number of levels required for the 'Sound Locator' upgrade.").getInt(darkSteelSoundLocatorCost); darkSteelSoundLocatorRange = config.get(sectionDarkSteel.name, "darkSteelSoundLocatorRange", darkSteelSoundLocatorRange, "Range of the 'Sound Locator' upgrade.").getInt(darkSteelSoundLocatorRange); darkSteelSoundLocatorLifespan = config.get(sectionDarkSteel.name, "darkSteelSoundLocatorLifespan", darkSteelSoundLocatorLifespan, "Number of ticks the 'Sound Locator' icons are displayed for.").getInt(darkSteelSoundLocatorLifespan); darkSteelGogglesOfRevealingCost= config.get(sectionDarkSteel.name, "darkSteelGogglesOfRevealingCost", darkSteelGogglesOfRevealingCost, "Number of levels required for the Goggles of Revealing upgrade.").getInt(darkSteelGogglesOfRevealingCost); darkSteelApiaristArmorCost= config.get(sectionDarkSteel.name, "darkSteelApiaristArmorCost", darkSteelApiaristArmorCost, "Number of levels required for the Apiarist Armor upgrade.").getInt(darkSteelApiaristArmorCost); darkSteelTravelCost = config.get(sectionDarkSteel.name, "darkSteelTravelCost", darkSteelTravelCost, "Number of levels required for the 'Travel' upgrade.").getInt(darkSteelTravelCost); darkSteelSpoonCost = config.get(sectionDarkSteel.name, "darkSteelSpoonCost", darkSteelSpoonCost, "Number of levels required for the 'Spoon' upgrade.").getInt(darkSteelSpoonCost); darkSteelSolarOneCost = config.get(sectionDarkSteel.name, "darkSteelSolarOneCost", darkSteelSolarOneCost, "Cost in XP levels of the Solar I upgrade.").getInt(); darkSteelSolarOneGen = config.get(sectionDarkSteel.name, "darkSteelSolarOneGen", darkSteelSolarOneGen, "RF per SECOND generated by the Solar I upgrade. Split between all equipped DS armors.").getInt(); darkSteelSolarTwoCost = config.get(sectionDarkSteel.name, "darkSteelSolarTwoCost", darkSteelSolarTwoCost, "Cost in XP levels of the Solar II upgrade.").getInt(); darkSteelSolarTwoGen = config.get(sectionDarkSteel.name, "darkSteelSolarTwoGen", darkSteelSolarTwoGen, "RF per SECOND generated by the Solar II upgrade. Split between all equipped DS armors.").getInt(); darkSteelSolarThreeCost = config.get(sectionDarkSteel.name, "darkSteelSolarThreeCost", darkSteelSolarThreeCost, "Cost in XP levels of the Solar III upgrade.").getInt(); darkSteelSolarThreeGen = config.get(sectionDarkSteel.name, "darkSteelSolarThreeGen", darkSteelSolarThreeGen, "RF per SECOND generated by the Solar III upgrade. Split between all equipped DS armors.").getInt(); darkSteelSolarChargeOthers = config.get(sectionDarkSteel.name, "darkSteelSolarChargeOthers", darkSteelSolarChargeOthers, "If enabled allows the solar upgrade to charge non-darksteel armors that the player is wearing.").getBoolean(); darkSteelSwordSkullChance = (float) config.get(sectionDarkSteel.name, "darkSteelSwordSkullChance", darkSteelSwordSkullChance, "The base chance that a skull will be dropped when using a powered dark steel sword (0 = no chance, 1 = 100% chance)").getDouble( darkSteelSwordSkullChance); darkSteelSwordSkullLootingModifier = (float) config.get(sectionDarkSteel.name, "darkSteelSwordSkullLootingModifier", darkSteelSwordSkullLootingModifier, "The chance per looting level that a skull will be dropped when using a powered dark steel sword (0 = no chance, 1 = 100% chance)").getDouble( darkSteelSwordSkullLootingModifier); darkSteelSwordPoweredDamageBonus = (float) config.get(sectionDarkSteel.name, "darkSteelSwordPoweredDamageBonus", darkSteelSwordPoweredDamageBonus, "The extra damage dealt when the sword is powered").getDouble( darkSteelSwordPoweredDamageBonus); darkSteelSwordPoweredSpeedBonus = (float) config.get(sectionDarkSteel.name, "darkSteelSwordPoweredSpeedBonus", darkSteelSwordPoweredSpeedBonus, "The increase in attack speed when powered").getDouble( darkSteelSwordPoweredSpeedBonus); darkSteelSwordWitherSkullChance = (float) config.get(sectionDarkSteel.name, "darkSteelSwordWitherSkullChance", darkSteelSwordWitherSkullChance, "The base chance that a wither skull will be dropped when using a powered dark steel sword (0 = no chance, 1 = 100% chance)").getDouble( darkSteelSwordWitherSkullChance); darkSteelSwordWitherSkullLootingModifier = (float) config.get(sectionDarkSteel.name, "darkSteelSwordWitherSkullLootingModifie", darkSteelSwordWitherSkullLootingModifier, "The chance per looting level that a wither skull will be dropped when using a powered dark steel sword (0 = no chance, 1 = 100% chance)").getDouble( darkSteelSwordWitherSkullLootingModifier); vanillaSwordSkullChance = (float) config.get(sectionDarkSteel.name, "vanillaSwordSkullChance", vanillaSwordSkullChance, "The base chance that a skull will be dropped when using a non dark steel sword (0 = no chance, 1 = 100% chance)").getDouble( vanillaSwordSkullChance); vanillaSwordSkullLootingModifier = (float) config.get(sectionPersonal.name, "vanillaSwordSkullLootingModifier", vanillaSwordSkullLootingModifier, "The chance per looting level that a skull will be dropped when using a non-dark steel sword (0 = no chance, 1 = 100% chance)").getDouble( vanillaSwordSkullLootingModifier); ticCleaverSkullDropChance = (float) config.get(sectionDarkSteel.name, "ticCleaverSkullDropChance", ticCleaverSkullDropChance, "The base chance that an Enderman Skull will be dropped when using TiC Cleaver").getDouble( ticCleaverSkullDropChance); ticBeheadingSkullModifier = (float) config.get(sectionPersonal.name, "ticBeheadingSkullModifier", ticBeheadingSkullModifier, "The chance per level of Beheading that a skull will be dropped when using a TiC weapon").getDouble( ticBeheadingSkullModifier); fakePlayerSkullChance = (float) config .get( sectionDarkSteel.name, "fakePlayerSkullChance", fakePlayerSkullChance, "The ratio of skull drops when a mob is killed by a 'FakePlayer', such as Killer Joe. When set to 0 no skulls will drop, at 1 the rate of skull drops is not modified") .getDouble( fakePlayerSkullChance); darkSteelSwordPowerUsePerHit = config.get(sectionDarkSteel.name, "darkSteelSwordPowerUsePerHit", darkSteelSwordPowerUsePerHit, "The amount of power (RF) used per hit.").getInt(darkSteelSwordPowerUsePerHit); darkSteelSwordEnderPearlDropChance = config.get(sectionDarkSteel.name, "darkSteelSwordEnderPearlDropChance", darkSteelSwordEnderPearlDropChance, "The chance that an ender pearl will be dropped when using a dark steel sword (0 = no chance, 1 = 100% chance)").getDouble( darkSteelSwordEnderPearlDropChance); darkSteelSwordEnderPearlDropChancePerLooting = config.get(sectionDarkSteel.name, "darkSteelSwordEnderPearlDropChancePerLooting", darkSteelSwordEnderPearlDropChancePerLooting, "The chance for each looting level that an additional ender pearl will be dropped when using a dark steel sword (0 = no chance, 1 = 100% chance)") .getDouble( darkSteelSwordEnderPearlDropChancePerLooting); darkSteelPickPowerUseObsidian = config.get(sectionDarkSteel.name, "darkSteelPickPowerUseObsidian", darkSteelPickPowerUseObsidian, "The amount of power (RF) used to break an obsidian block.").getInt(darkSteelPickPowerUseObsidian); darkSteelPickEffeciencyObsidian = config.get(sectionDarkSteel.name, "darkSteelPickEffeciencyObsidian", darkSteelPickEffeciencyObsidian, "The efficiency when breaking obsidian with a powered Dark Pickaxe.").getInt(darkSteelPickEffeciencyObsidian); darkSteelPickApplyObsidianEffeciencyAtHardess = (float) config.get(sectionDarkSteel.name, "darkSteelPickApplyObsidianEffeciencyAtHardess", darkSteelPickApplyObsidianEffeciencyAtHardess, "If set to a value > 0, the obsidian speed and power use will be used for all blocks with hardness >= to this value.").getDouble( darkSteelPickApplyObsidianEffeciencyAtHardess); darkSteelPickPowerUsePerDamagePoint = config.get(sectionDarkSteel.name, "darkSteelPickPowerUsePerDamagePoint", darkSteelPickPowerUsePerDamagePoint, "Power use (RF) per damage/durability point avoided.").getInt(darkSteelPickPowerUsePerDamagePoint); darkSteelPickEffeciencyBoostWhenPowered = (float) config.get(sectionDarkSteel.name, "darkSteelPickEffeciencyBoostWhenPowered", darkSteelPickEffeciencyBoostWhenPowered, "The increase in efficiency when powered.").getDouble(darkSteelPickEffeciencyBoostWhenPowered); darkSteelPickMinesTiCArdite = config.getBoolean("darkSteelPickMinesTiCArdite", sectionDarkSteel.name, darkSteelPickMinesTiCArdite, "When true the dark steel pick will be able to mine TiC Ardite and Cobalt"); darkSteelAxePowerUsePerDamagePoint = config.get(sectionDarkSteel.name, "darkSteelAxePowerUsePerDamagePoint", darkSteelAxePowerUsePerDamagePoint, "Power use (RF) per damage/durability point avoided.").getInt(darkSteelAxePowerUsePerDamagePoint); darkSteelAxePowerUsePerDamagePointMultiHarvest = config.get(sectionDarkSteel.name, "darkSteelPickAxeUsePerDamagePointMultiHarvest", darkSteelAxePowerUsePerDamagePointMultiHarvest, "Power use (RF) per damage/durability point avoided when shift-harvesting multiple logs").getInt(darkSteelAxePowerUsePerDamagePointMultiHarvest); darkSteelAxeSpeedPenaltyMultiHarvest = (float) config.get(sectionDarkSteel.name, "darkSteelAxeSpeedPenaltyMultiHarvest", darkSteelAxeSpeedPenaltyMultiHarvest, "How much slower shift-harvesting logs is.").getDouble(darkSteelAxeSpeedPenaltyMultiHarvest); darkSteelAxeEffeciencyBoostWhenPowered = (float) config.get(sectionDarkSteel.name, "darkSteelAxeEffeciencyBoostWhenPowered", darkSteelAxeEffeciencyBoostWhenPowered, "The increase in efficiency when powered.").getDouble(darkSteelAxeEffeciencyBoostWhenPowered); darkSteelShearsDurabilityFactor = config.get(sectionDarkSteel.name, "darkSteelShearsDurabilityFactor", darkSteelShearsDurabilityFactor, "How much more durable as vanilla shears they are.").getInt(darkSteelShearsDurabilityFactor); darkSteelShearsPowerUsePerDamagePoint = config.get(sectionDarkSteel.name, "darkSteelShearsPowerUsePerDamagePoint", darkSteelShearsPowerUsePerDamagePoint, "Power use (RF) per damage/durability point avoided.").getInt(darkSteelShearsPowerUsePerDamagePoint); darkSteelShearsEffeciencyBoostWhenPowered = (float) config.get(sectionDarkSteel.name, "darkSteelShearsEffeciencyBoostWhenPowered", darkSteelShearsEffeciencyBoostWhenPowered, "The increase in efficiency when powered.").getDouble(darkSteelShearsEffeciencyBoostWhenPowered); darkSteelShearsBlockAreaBoostWhenPowered = config.get(sectionDarkSteel.name, "darkSteelShearsBlockAreaBoostWhenPowered", darkSteelShearsBlockAreaBoostWhenPowered, "The increase in effected area (radius) when powered and used on blocks.").getInt(darkSteelShearsBlockAreaBoostWhenPowered); darkSteelShearsEntityAreaBoostWhenPowered = (float) config.get(sectionDarkSteel.name, "darkSteelShearsEntityAreaBoostWhenPowered", darkSteelShearsEntityAreaBoostWhenPowered, "The increase in effected area (radius) when powered and used on sheep.").getDouble(darkSteelShearsEntityAreaBoostWhenPowered); darkSteelAnvilDamageChance = (float) config.get(sectionDarkSteel.name, "darkSteelAnvilDamageChance", darkSteelAnvilDamageChance, "Chance that the dark steel anvil will take damage after repairing something.").getDouble(); darkSteelLadderSpeedBoost = (float) config.get(sectionDarkSteel.name, "darkSteelLadderSpeedBoost", darkSteelLadderSpeedBoost, "Speed boost, in blocks per tick, that the DS ladder gives over the vanilla ladder.").getDouble(); hootchPowerPerCycleRF = config.get(sectionPower.name, "hootchPowerPerCycleRF", hootchPowerPerCycleRF, "The amount of power generated per BC engine cycle. Examples: BC Oil = 30, BC Fuel = 60").getInt(hootchPowerPerCycleRF); hootchPowerTotalBurnTime = config.get(sectionPower.name, "hootchPowerTotalBurnTime", hootchPowerTotalBurnTime, "The total burn time. Examples: BC Oil = 5000, BC Fuel = 25000").getInt(hootchPowerTotalBurnTime); rocketFuelPowerPerCycleRF = config.get(sectionPower.name, "rocketFuelPowerPerCycleRF", rocketFuelPowerPerCycleRF, "The amount of power generated per BC engine cycle. Examples: BC Oil = 3, BC Fuel = 6").getInt(rocketFuelPowerPerCycleRF); rocketFuelPowerTotalBurnTime = config.get(sectionPower.name, "rocketFuelPowerTotalBurnTime", rocketFuelPowerTotalBurnTime, "The total burn time. Examples: BC Oil = 5000, BC Fuel = 25000").getInt(rocketFuelPowerTotalBurnTime); fireWaterPowerPerCycleRF = config.get(sectionPower.name, "fireWaterPowerPerCycleRF", fireWaterPowerPerCycleRF, "The amount of power generated per BC engine cycle. Examples: BC Oil = 30, BC Fuel = 60").getInt(fireWaterPowerPerCycleRF); fireWaterPowerTotalBurnTime = config.get(sectionPower.name, "fireWaterPowerTotalBurnTime", fireWaterPowerTotalBurnTime, "The total burn time. Examples: BC Oil = 5000, BC Fuel = 25000").getInt(fireWaterPowerTotalBurnTime); zombieGeneratorRfPerTick = config.get(sectionPower.name, "zombieGeneratorRfPerTick", zombieGeneratorRfPerTick, "The amount of power generated per tick.").getInt(zombieGeneratorRfPerTick); zombieGeneratorTicksPerBucketFuel = config.get(sectionPower.name, "zombieGeneratorTicksPerMbFuel", zombieGeneratorTicksPerBucketFuel, "The number of ticks one bucket of fuel lasts.").getInt(zombieGeneratorTicksPerBucketFuel); addFuelTooltipsToAllFluidContainers = config.get(sectionPersonal.name, "addFuelTooltipsToAllFluidContainers", addFuelTooltipsToAllFluidContainers, "If true, the RF/t and burn time of the fuel will be displayed in all tooltips for fluid containers with fuel.").getBoolean( addFuelTooltipsToAllFluidContainers); addDurabilityTootip = config.get(sectionPersonal.name, "addDurabilityTootip", addFuelTooltipsToAllFluidContainers, "If true, adds durability tooltips to tools and armor").getBoolean( addDurabilityTootip); addFurnaceFuelTootip = config.get(sectionPersonal.name, "addFurnaceFuelTootip", addFuelTooltipsToAllFluidContainers, "If true, adds burn duration tooltips to furnace fuels").getBoolean(addFurnaceFuelTootip); farmActionEnergyUseRF = config.get(sectionFarm.name, "farmActionEnergyUseRF", farmActionEnergyUseRF, "The amount of power used by a farm per action (eg plant, till, harvest) ").getInt(farmActionEnergyUseRF); farmAxeActionEnergyUseRF = config.get(sectionFarm.name, "farmAxeActionEnergyUseRF", farmAxeActionEnergyUseRF, "The amount of power used by a farm per wood block 'chopped'").getInt(farmAxeActionEnergyUseRF); farmBonemealActionEnergyUseRF = config.get(sectionFarm.name, "farmBonemealActionEnergyUseRF", farmBonemealActionEnergyUseRF, "The amount of power used by a farm per bone meal used").getInt(farmBonemealActionEnergyUseRF); farmBonemealTryEnergyUseRF = config.get(sectionFarm.name, "farmBonemealTryEnergyUseRF", farmBonemealTryEnergyUseRF, "The amount of power used by a farm per bone meal try").getInt(farmBonemealTryEnergyUseRF); farmAxeDamageOnLeafBreak = config.get(sectionFarm.name, "farmAxeDamageOnLeafBreak", farmAxeDamageOnLeafBreak, "Should axes in a farm take damage when breaking leaves?").getBoolean(farmAxeDamageOnLeafBreak); farmToolTakeDamageChance = (float) config.get(sectionFarm.name, "farmToolTakeDamageChance", farmToolTakeDamageChance, "The chance that a tool in the farm will take damage.").getDouble(farmToolTakeDamageChance); disableFarmNotification = config.get(sectionFarm.name, "disableFarmNotifications", disableFarmNotification, "Disable the notification text above the farm block.").getBoolean(); farmEssenceBerriesEnabled = config.get(sectionFarm.name, "farmEssenceBerriesEnabled", farmEssenceBerriesEnabled, "This setting controls whether essence berry bushes from TiC can be harvested by the farm.").getBoolean(); farmManaBeansEnabled = config.get(sectionFarm.name, "farmManaBeansEnabled", farmManaBeansEnabled, "This setting controls whether mana beans from Thaumcraft can be harvested by the farm.").getBoolean(); farmHarvestJungleWhenCocoa = config.get(sectionFarm.name, "farmHarvestJungleWhenCocoa", farmHarvestJungleWhenCocoa, "If this is enabled the farm will harvest jungle wood even if it has cocoa beans in its inventory.").getBoolean(); hoeStrings = config.get(sectionFarm.name, "farmHoes", hoeStrings, "Use this to specify items that can be hoes in the farming station. Use the registry name (eg. modid:name).").getStringList(); farmSaplingReserveAmount = config.get(sectionFarm.name, "farmSaplingReserveAmount", farmSaplingReserveAmount, "The amount of saplings the farm has to have in reserve to switch to shearing all leaves. If there are less " + "saplings in store, it will only shear part the leaves and break the others for spalings. Set this to 0 to " + "always shear all leaves.").getInt(farmSaplingReserveAmount); farmStopOnNoOutputSlots = config.get(sectionFarm.name, "farmStopOnNoOutputSlots", farmStopOnNoOutputSlots, "If this is enabled the farm will stop if there is not at least one empty output slot. Otherwise it will only stop if all output slots are full.") .getBoolean(); farmEvictEmptyRFTools = config.get(sectionFarm.name, "farmEvictEmptyRFTools", farmEvictEmptyRFTools, "If this is enabled the farm will move tools that can store RF and are empty to the output slots instead of using them.").getBoolean(); magnetPowerUsePerSecondRF = config.get(sectionMagnet.name, "magnetPowerUsePerTickRF", magnetPowerUsePerSecondRF, "The amount of RF power used per tick when the magnet is active").getInt(magnetPowerUsePerSecondRF); magnetPowerCapacityRF = config.get(sectionMagnet.name, "magnetPowerCapacityRF", magnetPowerCapacityRF, "Amount of RF power stored in a fully charged magnet").getInt(magnetPowerCapacityRF); magnetRange = config.get(sectionMagnet.name, "magnetRange", magnetRange, "Range of the magnet in blocks.").getInt(magnetRange); magnetMaxItems = config.get(sectionMagnet.name, "magnetMaxItems", magnetMaxItems, "Maximum number of items the magnet can effect at a time. (-1 for unlimited)").getInt(magnetMaxItems); magnetBlacklist = config.getStringList("magnetBlacklist", sectionMagnet.name, magnetBlacklist, "These items will not be picked up by the magnet."); magnetAllowInMainInventory = config.get(sectionMagnet.name, "magnetAllowInMainInventory", magnetAllowInMainInventory, "If true the magnet will also work in the main inventory, not just the hotbar").getBoolean(magnetAllowInMainInventory); magnetAllowInBaublesSlot = config.get(sectionMagnet.name, "magnetAllowInBaublesSlot", magnetAllowInBaublesSlot, "If true the magnet can be put into the 'amulet' Baubles slot (requires Baubles to be installed)").getBoolean(magnetAllowInBaublesSlot); magnetAllowDeactivatedInBaublesSlot = config.get(sectionMagnet.name, "magnetAllowDeactivatedInBaublesSlot", magnetAllowDeactivatedInBaublesSlot, "If true the magnet can be put into the 'amulet' Baubles slot even if switched off (requires Baubles to be installed and magnetAllowInBaublesSlot to be on)").getBoolean(magnetAllowDeactivatedInBaublesSlot); magnetAllowPowerExtraction = config.get(sectionMagnet.name, "magnetAllowPowerExtraction", magnetAllowPowerExtraction, "If true the magnet can be used as a battery.").getBoolean(magnetAllowPowerExtraction); magnetBaublesType = config.get(sectionMagnet.name, "magnetBaublesType", magnetBaublesType, "The BaublesType the magnet should be, 'AMULET', 'RING' or 'BELT' (requires Baubles to be installed and magnetAllowInBaublesSlot to be on)").getString(); crafterRfPerCraft = config.get("AutoCrafter Settings", "crafterRfPerCraft", crafterRfPerCraft, "RF used per autocrafted recipe").getInt(crafterRfPerCraft); poweredSpawnerMinDelayTicks = config.get(sectionSpawner.name, "poweredSpawnerMinDelayTicks", poweredSpawnerMinDelayTicks, "Min tick delay between spawns for a non-upgraded spawner").getInt(poweredSpawnerMinDelayTicks); poweredSpawnerMaxDelayTicks = config.get(sectionSpawner.name, "poweredSpawnerMaxDelayTicks", poweredSpawnerMaxDelayTicks, "Min tick delay between spawns for a non-upgraded spawner").getInt(poweredSpawnerMaxDelayTicks); poweredSpawnerMaxPlayerDistance = config.get(sectionSpawner.name, "poweredSpawnerMaxPlayerDistance", poweredSpawnerMaxPlayerDistance, "Max distance of the closest player for the spawner to be active. A zero value will remove the player check").getInt(poweredSpawnerMaxPlayerDistance); poweredSpawnerDespawnTimeSeconds = config.get(sectionSpawner.name, "poweredSpawnerDespawnTimeSeconds" , poweredSpawnerDespawnTimeSeconds, "Number of seconds in which spawned entities are protected from despawning").getInt(poweredSpawnerDespawnTimeSeconds); poweredSpawnerSpawnCount = config.get(sectionSpawner.name, "poweredSpawnerSpawnCount" , poweredSpawnerSpawnCount, "Number of entities to spawn each time").getInt(poweredSpawnerSpawnCount); poweredSpawnerSpawnRange = config.get(sectionSpawner.name, "poweredSpawnerSpawnRange" , poweredSpawnerSpawnRange, "Spawning range in X/Z").getInt(poweredSpawnerSpawnRange); poweredSpawnerMaxNearbyEntities = config.get(sectionSpawner.name, "poweredSpawnerMaxNearbyEntities" , poweredSpawnerMaxNearbyEntities, "Max number of entities in the nearby area until no more are spawned. A zero value will remove this check").getInt(poweredSpawnerMaxNearbyEntities); poweredSpawnerMaxSpawnTries = config.get(sectionSpawner.name, "poweredSpawnerMaxSpawnTries" , poweredSpawnerMaxSpawnTries, "Number of tries to find a suitable spawning location").getInt(poweredSpawnerMaxSpawnTries); poweredSpawnerUseVanillaSpawChecks = config.get(sectionSpawner.name, "poweredSpawnerUseVanillaSpawChecks", poweredSpawnerUseVanillaSpawChecks, "If true, regular spawn checks such as lighting level and dimension will be made before spawning mobs").getBoolean(poweredSpawnerUseVanillaSpawChecks); brokenSpawnerDropChance = (float) config.get(sectionSpawner.name, "brokenSpawnerDropChance", brokenSpawnerDropChance, "The chance a broken spawner will be dropped when a spawner is broken. 1 = 100% chance, 0 = 0% chance").getDouble(brokenSpawnerDropChance); brokenSpawnerToolBlacklist = config.getStringList("brokenSpawnerToolBlacklist", sectionSpawner.name, brokenSpawnerToolBlacklist, "When a spawner is broken with these tools they will not drop a broken spawner"); powerSpawnerAddSpawnerCost = config.get(sectionSpawner.name, "powerSpawnerAddSpawnerCost", powerSpawnerAddSpawnerCost, "The number of levels it costs to add a broken spawner").getInt(powerSpawnerAddSpawnerCost); nutrientFoodBoostDelay = config.get(sectionFluid.name, "nutrientFluidFoodBoostDelay", nutrientFoodBoostDelay, "The delay in ticks between when nutrient distillation boosts your food value.").getInt((int) nutrientFoodBoostDelay); killerJoeNutrientUsePerAttackMb = config.get(sectionKiller.name, "killerJoeNutrientUsePerAttackMb", killerJoeNutrientUsePerAttackMb, "The number of millibuckets of nutrient fluid used per attack.").getInt(killerJoeNutrientUsePerAttackMb); killerJoeAttackHeight = config.get(sectionKiller.name, "killerJoeAttackHeight", killerJoeAttackHeight, "The reach of attacks above and bellow Joe.").getDouble(killerJoeAttackHeight); killerJoeAttackWidth = config.get(sectionKiller.name, "killerJoeAttackWidth", killerJoeAttackWidth, "The reach of attacks to each side of Joe.").getDouble(killerJoeAttackWidth); killerJoeAttackLength = config.get(sectionKiller.name, "killerJoeAttackLength", killerJoeAttackLength, "The reach of attacks in front of Joe.").getDouble(killerJoeAttackLength); killerJoeHooverXpLength = config.get(sectionKiller.name, "killerJoeHooverXpLength", killerJoeHooverXpLength, "The distance from which XP will be gathered to each side of Joe.").getDouble(killerJoeHooverXpLength); killerJoeHooverXpWidth = config.get(sectionKiller.name, "killerJoeHooverXpWidth", killerJoeHooverXpWidth, "The distance from which XP will be gathered in front of Joe.").getDouble(killerJoeHooverXpWidth); killerJoeMaxXpLevel = config.get(sectionMisc.name, "killerJoeMaxXpLevel", killerJoeMaxXpLevel, "Maximum level of XP the killer joe can contain.").getInt(); killerJoeMustSee = config.get(sectionKiller.name, "killerJoeMustSee", killerJoeMustSee, "Set whether the Killer Joe can attack through blocks.").getBoolean(); killerPvPoffDisablesSwing = config .get(sectionKiller.name, "killerPvPoffDisablesSwing", killerPvPoffDisablesSwing, "Set whether the Killer Joe swings even if PvP is off (that swing will do nothing unless killerPvPoffIsIgnored is enabled).") .getBoolean(); killerPvPoffIsIgnored = config .get(sectionKiller.name, "killerPvPoffIsIgnored", killerPvPoffIsIgnored, "Set whether the Killer Joe ignores PvP settings and always hits players (killerPvPoffDisablesSwing must be off for this to work).") .getBoolean(); killerMending = config .get(sectionKiller.name, "killerMending", killerMending, "If enabled, picked up XP will be used for the enchantement 'Mending' on the weapon.") .getBoolean(); // Add deprecated comment config.getString("isGasConduitEnabled", sectionItems.name, "auto", "Deprecated option. Use boolean \"gasConduitsEnabled\" below."); isGasConduitEnabled = config.getBoolean("gasConduitEnabled", sectionItems.name, isGasConduitEnabled, "If true, gas conduits will be enabled if the Mekanism Gas API is found. False to forcibly disable."); enableMEConduits = config.getBoolean("enableMEConduits", sectionItems.name, enableMEConduits, "Allows ME conduits. Only has an effect with AE2 installed."); enableOCConduits = config.getBoolean("enableOCConduits", sectionItems.name, enableOCConduits, "Allows OC conduits. Only has an effect with OpenComputers installed."); enableOCConduitsAnimatedTexture = config.getBoolean("enableOCConduitsAnimatedTexture", sectionItems.name, enableOCConduitsAnimatedTexture, "Use the animated texture for OC conduits."); soulVesselBlackList = Arrays.asList(config.getStringList("soulVesselBlackList", sectionSoulBinder.name, soulVesselBlackList.toArray(new String[0]), "Entities listed here will can not be captured in a Soul Vial")); soulVesselCapturesBosses = config.getBoolean("soulVesselCapturesBosses", sectionSoulBinder.name, soulVesselCapturesBosses, "When set to false, any mob with a 'boss bar' won't be able to be captured in the Soul Vial. Note: The Ender Dragon can not " + "be captured, even with this enabled. This is a limitation of the dragon, not the Soul Vial."); soulBinderBrokenSpawnerRF = config.get(sectionSoulBinder.name, "soulBinderBrokenSpawnerRF", soulBinderBrokenSpawnerRF, "The number of RF required to change the type of a broken spawner.").getInt(soulBinderBrokenSpawnerRF); soulBinderReanimationRF = config.get(sectionSoulBinder.name, "soulBinderReanimationRF", soulBinderReanimationRF, "The number of RF required to to re-animated a mob head.").getInt(soulBinderReanimationRF); soulBinderEnderCystalRF = config.get(sectionSoulBinder.name, "soulBinderEnderCystalRF", soulBinderEnderCystalRF, "The number of RF required to create an ender crystal.").getInt(soulBinderEnderCystalRF); soulBinderAttractorCystalRF = config.get(sectionSoulBinder.name, "soulBinderAttractorCystalRF", soulBinderAttractorCystalRF, "The number of RF required to create an attractor crystal.").getInt(soulBinderAttractorCystalRF); soulBinderEnderRailRF = config.get(sectionSoulBinder.name, "soulBinderEnderRailRF", soulBinderEnderRailRF, "The number of RF required to create an ender rail.").getInt(soulBinderEnderRailRF); soulBinderTunedPressurePlateRF = config.get(sectionSoulBinder.name, "soulBinderTunedPressurePlateRF", soulBinderTunedPressurePlateRF, "The number of RF required to tune a pressure plate.").getInt(soulBinderTunedPressurePlateRF); soulBinderAttractorCystalLevels = config.get(sectionSoulBinder.name, "soulBinderAttractorCystalLevels", soulBinderAttractorCystalLevels, "The number of levels required to create an attractor crystal.").getInt(soulBinderAttractorCystalLevels); soulBinderEnderCystalLevels = config.get(sectionSoulBinder.name, "soulBinderEnderCystalLevels", soulBinderEnderCystalLevels, "The number of levels required to create an ender crystal.").getInt(soulBinderEnderCystalLevels); soulBinderReanimationLevels = config.get(sectionSoulBinder.name, "soulBinderReanimationLevels", soulBinderReanimationLevels, "The number of levels required to re-animate a mob head.").getInt(soulBinderReanimationLevels); soulBinderBrokenSpawnerLevels = config.get(sectionSoulBinder.name, "soulBinderBrokenSpawnerLevels", soulBinderBrokenSpawnerLevels, "The number of levels required to change the type of a broken spawner.").getInt(soulBinderBrokenSpawnerLevels); soulBinderEnderRailLevels = config.get(sectionSoulBinder.name, "soulBinderEnderRailLevels", soulBinderEnderRailLevels, "The number of levels required to create an ender rail.").getInt(soulBinderEnderRailLevels); soulBinderTunedPressurePlateLevels = config.get(sectionSoulBinder.name, "soulBinderTunedPressurePlateLevels", soulBinderTunedPressurePlateLevels, "The number of levels required to tune a pressure plate.").getInt(soulBinderTunedPressurePlateLevels); soulBinderMaxXpLevel = config.get(sectionSoulBinder.name, "soulBinderMaxXPLevel", soulBinderMaxXpLevel, "Maximum level of XP the soul binder can contain.").getInt(); spawnGuardStopAllSlimesDebug = config.getBoolean("spawnGuardStopAllSlimesDebug", sectionAttractor.name, spawnGuardStopAllSlimesDebug, "When true slimes wont be allowed to spawn at all. Only added to aid testing in super flat worlds."); spawnGuardStopAllSquidSpawning = config.getBoolean("spawnGuardStopAllSquidSpawning", sectionAttractor.name, spawnGuardStopAllSquidSpawning, "When true no squid will be spawned."); weatherObeliskClearFluid = config.get(sectionWeather.name, "weatherObeliskClearFluid", weatherObeliskClearFluid, "The fluid required (in mB) to set the world to clear weather").getInt(); weatherObeliskRainFluid = config.get(sectionWeather.name, "weatherObeliskRainFluid", weatherObeliskRainFluid, "The fluid required (in mB) to set the world to rainy weather").getInt(); weatherObeliskThunderFluid = config.get(sectionWeather.name, "weatherObeliskThunderFluid", weatherObeliskThunderFluid, "The fluid required (in mB) to set the world to thundering weather").getInt(); // Loot Config lootDarkSteel = config.getBoolean("lootDarkSteel", sectionLootConfig.name, lootDarkSteel, "Adds Darksteel Ingots to loot tables"); lootItemConduitProbe = config.getBoolean("lootItemConduitProbe", sectionLootConfig.name, lootItemConduitProbe, "Adds ItemConduitProbe to loot tables"); lootQuartz = config.getBoolean("lootQuartz", sectionLootConfig.name, lootQuartz, "Adds quartz to loot tables"); lootNetherWart = config.getBoolean("lootNetherWart", sectionLootConfig.name, lootNetherWart, "Adds nether wart to loot tables"); lootEnderPearl = config.getBoolean("lootEnderPearl", sectionLootConfig.name, lootEnderPearl, "Adds ender pearls to loot tables"); lootElectricSteel = config.getBoolean("lootElectricSteel", sectionLootConfig.name, lootElectricSteel, "Adds Electric Steel Ingots to loot tables"); lootRedstoneAlloy = config.getBoolean("lootRedstoneAlloy", sectionLootConfig.name, lootRedstoneAlloy, "Adds Redstone Alloy Ingots to loot tables"); lootPhasedIron = config.getBoolean("lootPhasedIron", sectionLootConfig.name, lootPhasedIron, "Adds Phased Iron Ingots to loot tables"); lootPhasedGold = config.getBoolean("lootPhasedGold", sectionLootConfig.name, lootPhasedGold, "Adds Phased Gold Ingots to loot tables"); lootTravelStaff = config.getBoolean("lootTravelStaff", sectionLootConfig.name, lootTravelStaff, "Adds Travel Staff to loot tables"); lootTheEnder = config.getBoolean("lootTheEnder", sectionLootConfig.name, lootTheEnder, "Adds The Ender to loot tables"); lootDarkSteelBoots = config.getBoolean("lootDarkSteelBoots", sectionLootConfig.name, lootDarkSteelBoots, "Adds Darksteel Boots to loot tables"); enderRailEnabled = config.getBoolean("enderRailEnabled", sectionRailConfig.name, enderRailEnabled, "Whether Ender Rails are enabled"); enderRailPowerRequireCrossDimensions = config.get(sectionRailConfig.name, "enderRailPowerRequireCrossDimensions", enderRailPowerRequireCrossDimensions, "The amount of power required to transport a cart across dimensions").getInt(enderRailPowerRequireCrossDimensions); enderRailPowerRequiredPerBlock = config.get(sectionRailConfig.name, "enderRailPowerRequiredPerBlock", enderRailPowerRequiredPerBlock, "The amount of power required to teleport a cart per block in the same dimension").getInt(enderRailPowerRequiredPerBlock); enderRailCapSameDimensionPowerAtCrossDimensionCost = config.getBoolean("enderRailCapSameDimensionPowerAtCrossDimensionCost", sectionRailConfig.name, enderRailCapSameDimensionPowerAtCrossDimensionCost, "When set to true the RF cost of sending a cart within the same dimension will be capped to the cross dimension cost"); enderRailTicksBeforeForceSpawningLinkedCarts = config.get(sectionRailConfig.name, "enderRailTicksBeforeForceSpawningLinkedCarts", enderRailTicksBeforeForceSpawningLinkedCarts, "The number of ticks to wait for the track to clear before force spawning the next cart in a (RailCraft) linked set").getInt(enderRailTicksBeforeForceSpawningLinkedCarts); enderRailTeleportPlayers = config.getBoolean("enderRailTeleportPlayers", sectionRailConfig.name, enderRailTeleportPlayers, "If true player in minecarts will be teleported. WARN: WIP, seems to cause a memory leak."); dumpMobNames = config.getBoolean("dumpMobNames", sectionMobConfig.name, dumpMobNames, "When set to true a list of all registered mobs will be dumped to config/enderio/mobTypes.txt The names are in the format required by EIOs mob blacklists."); xpObeliskMaxXpLevel = config.get(sectionMisc.name, "xpObeliskMaxXpLevel", xpObeliskMaxXpLevel, "Maximum level of XP the xp obelisk can contain.").getInt(); xpJuiceName = config.getString("xpJuiceName", sectionMisc.name, xpJuiceName, "Id of liquid XP fluid (WARNING: only for users who know what they are doing - changing this id can break worlds) - this should match with OpenBlocks when installed"); glassConnectToTheirVariants = config.getBoolean("glassConnectToTheirVariants", sectionMisc.name, glassConnectToTheirVariants, "If true, quite clear glass and fused quartz will connect textures with their respective enlightened and darkened variants."); clearGlassConnectToFusedQuartz = config.getBoolean("clearGlassConnectToFusedQuartz", sectionMisc.name, clearGlassConnectToFusedQuartz, "If true, quite clear glass will connect textures with fused quartz."); glassConnectToTheirColorVariants = config.getBoolean("glassConnectToTheirColorVariants", sectionMisc.name, glassConnectToTheirColorVariants, "If true, quite clear glass and fused quartz of different colors will connect textures."); paintedGlowstoneRequireSilkTouch = config.getBoolean("paintedGlowstoneRequireSilkTouch", sectionMisc.name, paintedGlowstoneRequireSilkTouch, "If true, painted glowstone will drop dust unless broken with silk touch"); enchantmentSoulBoundEnabled = config.getBoolean("enchantmentSoulBoundEnabled", sectionEnchantments.name, enchantmentSoulBoundEnabled, "If false the soul bound enchantment will not be available"); String rareStr = config.get(sectionEnchantments.name, "enchantmentSoulBoundWeight", enchantmentSoulBoundWeight.toString(), "The rarity of the enchantment. COMMON, UNCOMMON, RARE, VERY_RARE ").getString(); try { enchantmentSoulBoundWeight = Rarity.valueOf(rareStr); } catch (Exception e) { Log.warn("Could not set value config entry enchantmentWitherArrowRarity Specified value " + rareStr); e.printStackTrace(); } telepadLockDimension = config.get(sectionTelepad.name, "lockDimension", telepadLockDimension, "If true, the dimension cannot be set via the GUI, the coord selector must be used.").getBoolean(); telepadLockCoords = config.get(sectionTelepad.name, "lockCoords", telepadLockCoords, "If true, the coordinates cannot be set via the GUI, the coord selector must be used.").getBoolean(); telepadPowerCoefficient = config.get(sectionTelepad.name, "powerCoefficient", telepadPowerCoefficient, "Power for a teleport is calculated by the formula:\npower = [this value] * ln(0.005*distance + 1)").getInt(); telepadPowerInterdimensional = config.get(sectionTelepad.name, "powerInterdimensional", telepadPowerInterdimensional, "The amount of RF required for an interdimensional teleport.").getInt(); inventoryPanelFree = config.getBoolean("inventoryPanelFree", sectionInventoryPanel.name, inventoryPanelFree, "If true, the inv panel will not accept fluids and will be active permanently."); inventoryPanelPowerPerMB = config.getFloat("powerPerMB", sectionInventoryPanel.name, inventoryPanelPowerPerMB, 1.0f, 10000.0f, "Internal power generated per mB. The default of 800/mB matches the RF generation of the Zombie generator. A panel tries to refill only once every second - setting this value too low slows down the scanning speed."); inventoryPanelScanCostPerSlot = config.getFloat("scanCostPerSlot", sectionInventoryPanel.name, inventoryPanelScanCostPerSlot, 0.0f, 10.0f, "Internal power used for scanning a slot"); inventoryPanelExtractCostPerItem = config.getFloat("extractCostPerItem", sectionInventoryPanel.name, inventoryPanelExtractCostPerItem, 0.0f, 10.0f, "Internal power used per item extracted (not a stack of items)"); inventoryPanelExtractCostPerOperation = config.getFloat("extractCostPerOperation", sectionInventoryPanel.name, inventoryPanelExtractCostPerOperation, 0.0f, 10000.0f, "Internal power used per extract operation (independent of stack size)"); inventoryPanelScaleText= config.getBoolean("inventoryPanelScaleText", sectionInventoryPanel.name, inventoryPanelScaleText, "If true stack sizes will be drawn at a smaller size with a little more detail."); debugUpdatePackets = config.getBoolean("debugUpdatePackets", sectionPersonal.name, debugUpdatePackets, "DEBUG: If true, TEs will flash when they recieve an update packet."); topEnabled = config.getBoolean("topEnabled", sectionTOP.name, topEnabled, "If true, 'The One Probe' by McJty will be supported"); topShowProgressByDefault = config.getBoolean("topShowProgressByDefault", sectionTOP.name, topShowProgressByDefault, "If true, the progress will be shown always, otherwise only it will only be shown on 'extended' mode (e.g. with shift pressed)"); topShowPowerByDefault = config.getBoolean("topShowPowerByDefault", sectionTOP.name, topShowPowerByDefault, "If true, the power level will be shown always, otherwise only it will only be shown on 'extended' mode (e.g. with shift pressed)"); topShowRedstoneByDefault = config.getBoolean("topShowRedstoneByDefault", sectionTOP.name, topShowRedstoneByDefault, "If true, the resdstone status will be shown always, otherwise only it will only be shown on 'extended' mode (e.g. with shift pressed)"); topShowSideConfigByDefault = config.getBoolean("topShowSideConfigByDefault", sectionTOP.name, topShowSideConfigByDefault, "If true, the side config will be shown always, otherwise only it will only be shown on 'extended' mode (e.g. with shift pressed)"); topShowRangeByDefault = config.getBoolean("topShowRangeByDefault", sectionTOP.name, topShowRangeByDefault, "If true, the range will be shown always, otherwise only it will only be shown on 'extended' mode (e.g. with shift pressed)"); topShowMobsByDefault = config.getBoolean("topShowMobsByDefault", sectionTOP.name, topShowMobsByDefault, "If true, the mob list will be shown always, otherwise only it will only be shown on 'extended' mode (e.g. with shift pressed)"); topShowTanksByDefault = config.getBoolean("topShowTanksByDefault", sectionTOP.name, topShowTanksByDefault, "If true, the tank content will be shown always, otherwise only it will only be shown on 'extended' mode (e.g. with shift pressed)"); CapacitorKey.processConfig(config); } public static void checkYetaAccess() { if(!useSneakMouseWheelYetaWrench && !useSneakRightClickYetaWrench) { Log.warn("Both useSneakMouseWheelYetaWrench and useSneakRightClickYetaWrench are set to false. Enabling right click."); useSneakRightClickYetaWrench = true; } } public static void init() { } public static void postInit() { farmHoes = new Things(); for (String hoe : hoeStrings) { farmHoes.add(hoe); } } public static ItemStack getStackForString(String s) { String[] nameAndMeta = s.split(";"); int meta = nameAndMeta.length == 1 ? 0 : Integer.parseInt(nameAndMeta[1]); String[] data = nameAndMeta[0].split(":"); Item item = Item.REGISTRY.getObject(new ResourceLocation(data[0], data[1])); if(item == null) { return null; } return new ItemStack(item, 1, meta); } private Config() { } }
src/main/java/crazypants/enderio/config/Config.java
package crazypants.enderio.config; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Locale; import com.enderio.core.common.event.ConfigFileChangedEvent; import com.enderio.core.common.vecmath.VecmathUtil; import crazypants.enderio.EnderIO; import crazypants.enderio.Log; import crazypants.enderio.capacitor.CapacitorKey; import crazypants.enderio.network.PacketHandler; import crazypants.util.Things; import net.minecraft.enchantment.Enchantment.Rarity; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.client.event.ConfigChangedEvent.OnConfigChangedEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent; import net.minecraftforge.fml.relauncher.Side; public final class Config { public static class Section { public final String name; public final String lang; public Section(String name, String lang) { this.name = name; this.lang = lang; register(); } private void register() { sections.add(this); } public String lc() { return name.toLowerCase(Locale.US); } } public static final List<Section> sections; static { sections = new ArrayList<Section>(); } public static Configuration config; public static final Section sectionPower = new Section("Power Settings", "power"); public static final Section sectionRecipe = new Section("Recipe Settings", "recipe"); public static final Section sectionItems = new Section("Item Enabling", "item"); public static final Section sectionEfficiency = new Section("Efficiency Settings", "efficiency"); public static final Section sectionPersonal = new Section("Personal Settings", "personal"); public static final Section sectionAnchor = new Section("Anchor Settings", "anchor"); public static final Section sectionStaff = new Section("Staff Settings", "staff"); public static final Section sectionDarkSteel = new Section("Dark Steel", "darksteel"); public static final Section sectionFarm = new Section("Farm Settings", "farm"); public static final Section sectionAesthetic = new Section("Aesthetic Settings", "aesthetic"); public static final Section sectionAdvanced = new Section("Advanced Settings", "advanced"); public static final Section sectionMagnet = new Section("Magnet Settings", "magnet"); public static final Section sectionFluid = new Section("Fluid Settings", "fluid"); public static final Section sectionSpawner = new Section("PoweredSpawner Settings", "spawner"); public static final Section sectionKiller = new Section("Killer Joe Settings", "killerjoe"); public static final Section sectionSoulBinder = new Section("Soul Binder Settings", "soulBinder"); public static final Section sectionAttractor = new Section("Mob Attractor Settings", "attractor"); public static final Section sectionLootConfig = new Section("Loot Config", "lootconfig"); public static final Section sectionMobConfig = new Section("Mob Config", "mobconfig"); public static final Section sectionRailConfig = new Section("Rail", "railconfig"); public static final Section sectionEnchantments = new Section("Enchantments", "enchantments"); public static final Section sectionWeather = new Section("Weather", "weather"); public static final Section sectionTelepad = new Section("Telepad", "telepad"); public static final Section sectionInventoryPanel = new Section("InventoryPanel", "inventorypanel"); public static final Section sectionMisc = new Section("Misc", "misc"); public static final Section sectionCapacitor = new Section("Capacitor Values", "capacitor"); public static final Section sectionTOP = new Section("The One Probe integration", "top"); public static final double DEFAULT_CONDUIT_SCALE = 0.6; public static final float EXPLOSION_RESISTANT = 2000f * 3.0f / 5.0f; // obsidian public static boolean registerRecipes = true; public static boolean jeiUseShortenedPainterRecipes = true; public static boolean reinforcedObsidianEnabled = true; public static boolean useAlternateTesseractModel = false; public static boolean photovoltaicCellEnabled = true; public static boolean reservoirEnabled = true; public static double conduitScale = DEFAULT_CONDUIT_SCALE; public static boolean transceiverEnabled = true; public static double transceiverEnergyLoss = 0.1; public static int transceiverBucketTransmissionCostRF = 100; public static File configDirectory; public static int recipeLevel = 2; public static boolean addPeacefulRecipes = false; public static boolean allowExternalTickSpeedup = true; public static boolean createSyntheticRecipes = true; public static boolean detailedPowerTrackingEnabled = false; public static boolean useSneakMouseWheelYetaWrench = true; public static boolean useSneakRightClickYetaWrench = false; public static int yetaWrenchOverlayMode = 0; public static boolean itemConduitUsePhyscialDistance = false; public static boolean redstoneConduitsShowState = true; public static int enderFluidConduitExtractRate = 200; public static int enderFluidConduitMaxIoRate = 800; public static int advancedFluidConduitExtractRate = 100; public static int advancedFluidConduitMaxIoRate = 400; public static int fluidConduitExtractRate = 50; public static int fluidConduitMaxIoRate = 200; public static int gasConduitExtractRate = 200; public static int gasConduitMaxIoRate = 800; public static boolean updateLightingWhenHidingFacades = false; public static boolean transparentFacesLetThroughBeaconBeam = true; public static boolean travelAnchorEnabled = true; public static int travelAnchorMaximumDistance = 96; public static int travelAnchorCooldown = 0; public static boolean travelAnchorSneak = true; public static boolean travelAnchorSkipWarning = true; public static int travelStaffMaximumDistance = 256; public static float travelStaffPowerPerBlockRF = 250; public static int travelStaffMaxBlinkDistance = 16; public static int travelStaffBlinkPauseTicks = 10; public static boolean travelStaffEnabled = true; public static boolean travelStaffBlinkEnabled = true; public static boolean travelStaffBlinkThroughSolidBlocksEnabled = true; public static boolean travelStaffBlinkThroughClearBlocksEnabled = true; public static boolean travelStaffBlinkThroughUnbreakableBlocksEnabled = false; public static String[] travelStaffBlinkBlackList = new String[] { "minecraft:bedrock", "Thaumcraft:blockWarded" }; public static boolean travelStaffOffhandBlinkEnabled = true; public static boolean travelStaffOffhandTravelEnabled = true; public static boolean travelStaffOffhandEnderIOEnabled = true; public static boolean travelStaffOffhandShowsTravelTargets = true; public static float travelAnchorZoomScale = 0.2f; public static int enderIoRange = 8; public static boolean enderIoMeAccessEnabled = true; public static boolean darkSteelRightClickPlaceEnabled = true; public static double[] darkSteelPowerDamgeAbsorptionRatios = {0.5, 0.6, 0.75, 0.95}; public static int darkSteelPowerStorageBase = 100000; public static int darkSteelPowerStorageLevelOne = 150000; public static int darkSteelPowerStorageLevelTwo = 250000; public static int darkSteelPowerStorageLevelThree = 1000000; public static float darkSteelSpeedOneWalkModifier = 0.1f; public static float darkSteelSpeedTwoWalkMultiplier = 0.2f; public static float darkSteelSpeedThreeWalkMultiplier = 0.3f; public static float darkSteelSpeedOneSprintModifier = 0.1f; public static float darkSteelSpeedTwoSprintMultiplier = 0.3f; public static float darkSteelSpeedThreeSprintMultiplier = 0.5f; public static int darkSteelSpeedOneCost = 4; public static int darkSteelSpeedTwoCost = 6; public static int darkSteelSpeedThreeCost = 8; public static boolean darkSteelSpeedLimitFovChanges = true; public static boolean darkSteelSpeedDisableFovChanges = false; public static double darkSteelBootsJumpModifier = 1.5; public static int darkSteelJumpOneCost = 4; public static int darkSteelJumpTwoCost = 6; public static int darkSteelJumpThreeCost = 8; public static boolean slotZeroPlacesEight = true; public static int darkSteelWalkPowerCost = darkSteelPowerStorageLevelTwo / 3000; public static int darkSteelSprintPowerCost = darkSteelWalkPowerCost * 4; public static boolean darkSteelDrainPowerFromInventory = false; public static int darkSteelBootsJumpPowerCost = 150; public static int darkSteelFallDistanceCost = 75; public static float darkSteelSwordPoweredDamageBonus = 1.0f; public static float darkSteelSwordPoweredSpeedBonus = 0.4f; public static float darkSteelSwordWitherSkullChance = 0.05f; public static float darkSteelSwordWitherSkullLootingModifier = 0.05f; public static float darkSteelSwordSkullChance = 0.1f; public static float darkSteelSwordSkullLootingModifier = 0.075f; public static float vanillaSwordSkullLootingModifier = 0.05f; public static float vanillaSwordSkullChance = 0.05f; public static float ticCleaverSkullDropChance = 0.1f; public static float ticBeheadingSkullModifier = 0.075f; public static float fakePlayerSkullChance = 0.5f; public static int darkSteelSwordPowerUsePerHit = 750; public static double darkSteelSwordEnderPearlDropChance = 1; public static double darkSteelSwordEnderPearlDropChancePerLooting = 0.5; public static int darkSteelPickEffeciencyObsidian = 50; public static int darkSteelPickPowerUseObsidian = 10000; public static float darkSteelPickApplyObsidianEffeciencyAtHardess = 40; public static int darkSteelPickPowerUsePerDamagePoint = 750; public static float darkSteelPickEffeciencyBoostWhenPowered = 2; public static boolean darkSteelPickMinesTiCArdite = true; public static int darkSteelAxePowerUsePerDamagePoint = 750; public static int darkSteelAxePowerUsePerDamagePointMultiHarvest = 1500; public static float darkSteelAxeEffeciencyBoostWhenPowered = 2; public static float darkSteelAxeSpeedPenaltyMultiHarvest = 4; public static int darkSteelShearsDurabilityFactor = 5; public static int darkSteelShearsPowerUsePerDamagePoint = 250; public static float darkSteelShearsEffeciencyBoostWhenPowered = 2.0f; public static int darkSteelShearsBlockAreaBoostWhenPowered = 2; public static float darkSteelShearsEntityAreaBoostWhenPowered = 3.0f; public static int darkSteelUpgradeVibrantCost = 4; public static int darkSteelUpgradePowerOneCost = 4; public static int darkSteelUpgradePowerTwoCost = 6; public static int darkSteelUpgradePowerThreeCost = 8; public static int darkSteelGliderCost = 4; public static double darkSteelGliderHorizontalSpeed = 0.03; public static double darkSteelGliderVerticalSpeed = -0.05; public static double darkSteelGliderVerticalSpeedSprinting = -0.15; public static int darkSteelGogglesOfRevealingCost = 4; public static int darkSteelApiaristArmorCost = 4; public static int darkSteelSwimCost = 4; public static int darkSteelNightVisionCost = 4; public static int darkSteelTOPCost = 4; public static int darkSteelSoundLocatorCost = 4; public static int darkSteelSoundLocatorRange = 40; public static int darkSteelSoundLocatorLifespan = 40; public static int darkSteelTravelCost = 16; public static int darkSteelSpoonCost = 4; public static int darkSteelSolarOneGen = 10; public static int darkSteelSolarOneCost = 4; public static int darkSteelSolarTwoGen = 40; public static int darkSteelSolarTwoCost = 8; public static int darkSteelSolarThreeGen = 80; public static int darkSteelSolarThreeCost = 24; public static boolean darkSteelSolarChargeOthers = true; public static float darkSteelAnvilDamageChance = 0.024f; public static float darkSteelLadderSpeedBoost = 0.06f; public static int hootchPowerPerCycleRF = 60; public static int hootchPowerTotalBurnTime = 6000; public static int rocketFuelPowerPerCycleRF = 160; public static int rocketFuelPowerTotalBurnTime = 7000; public static int fireWaterPowerPerCycleRF = 80; public static int fireWaterPowerTotalBurnTime = 15000; public static int vatPowerUserPerTickRF = 20; public static int maxPhotovoltaicOutputRF = 10; public static int maxPhotovoltaicAdvancedOutputRF = 40; public static int maxPhotovoltaicVibrantOutputRF = 160; public static int zombieGeneratorRfPerTick = 80; public static int zombieGeneratorTicksPerBucketFuel = 10000; public static boolean addFuelTooltipsToAllFluidContainers = true; public static boolean addFurnaceFuelTootip = true; public static boolean addDurabilityTootip = true; public static int farmActionEnergyUseRF = 500; public static int farmAxeActionEnergyUseRF = 1000; public static int farmBonemealActionEnergyUseRF = 160; public static int farmBonemealTryEnergyUseRF = 80; public static boolean farmAxeDamageOnLeafBreak = false; public static float farmToolTakeDamageChance = 1; public static boolean disableFarmNotification = false; public static boolean farmEssenceBerriesEnabled = true; public static boolean farmManaBeansEnabled = false; public static boolean farmHarvestJungleWhenCocoa = false; public static String[] hoeStrings = new String[] { "minecraft:wooden_hoe", "minecraft:stone_hoe", "minecraft:iron_hoe", "minecraft:diamond_hoe", "minecraft:golden_hoe", "MekanismTools:ObsidianHoe", "MekanismTools:LapisLazuliHoe", "MekanismTools:OsmiumHoe", "MekanismTools:BronzeHoe", "MekanismTools:GlowstoneHoe", "MekanismTools:SteelHoe", "Steamcraft:hoeBrass", "Steamcraft:hoeGildedGold", "Railcraft:tool.steel.hoe", "TConstruct:mattock", "appliedenergistics2:item.ToolCertusQuartzHoe", "appliedenergistics2:item.ToolNetherQuartzHoe", "ProjRed|Exploration:projectred.exploration.hoeruby", "ProjRed|Exploration:projectred.exploration.hoesapphire", "ProjRed|Exploration:projectred.exploration.hoeperidot", "magicalcrops:magicalcrops_AccioHoe", "magicalcrops:magicalcrops_CrucioHoe", "magicalcrops:magicalcrops_ImperioHoe", // disabled as it is currently not unbreaking as advertised "magicalcrops:magicalcrops_ZivicioHoe", "magicalcrops:magicalcropsarmor_AccioHoe", "magicalcrops:magicalcropsarmor_CrucioHoe", "magicalcrops:magicalcropsarmor_ImperioHoe", "BiomesOPlenty:hoeAmethyst", "BiomesOPlenty:hoeMud", "Eln:Eln.Copper Hoe", "Thaumcraft:ItemHoeThaumium", "Thaumcraft:ItemHoeElemental", "Thaumcraft:ItemHoeVoid", "ThermalFoundation:tool.hoeInvar", "ThermalFoundation:tool.hoeCopper", "ThermalFoundation:tool.hoeBronze", "ThermalFoundation:tool.hoeSilver", "ThermalFoundation:tool.hoeElectrum", "ThermalFoundation:tool.hoeTin", "ThermalFoundation:tool.hoeLead", "ThermalFoundation:tool.hoeNickel", "ThermalFoundation:tool.hoePlatinum", "TwilightForest:item.steeleafHoe", "TwilightForest:item.ironwoodHoe", "IC2:itemToolBronzeHoe", "techreborn:bronzeHoe", "techreborn:rubyHoe", "techreborn:sapphireHoe", "techreborn:peridotHoe", "basemetals:adamantine_hoe", "basemetals:aquarium_hoe", "basemetals:brass_hoe", "basemetals:bronze_hoe", "basemetals:coldiron_hoe", "basemetals:copper_hoe", "basemetals:cupronickel_hoe", "basemetals:electrum_hoe", "basemetals:invar_hoe", "basemetals:lead_hoe", "basemetals:mithril_hoe", "basemetals:nickel_hoe", "basemetals:platinum_hoe", "basemetals:silver_hoe", "basemetals:starsteel_hoe", "basemetals:steel_hoe", "basemetals:tin_hoe", "actuallyadditions:itemHoeQuartz", "actuallyadditions:itemHoeEmerald", "actuallyadditions:itemHoeObsidian", "actuallyadditions:itemHoeCrystalRed", "actuallyadditions:itemHoeCrystalBlue", "actuallyadditions:itemHoeCrystalLightBlue", "actuallyadditions:itemHoeCrystalBlack", "actuallyadditions:itemHoeCrystalGreen", "actuallyadditions:itemHoeCrystalWhite", "silentgems:Hoe", "ic2:bronze_hoe" // IC2exp }; public static Things farmHoes = new Things(); public static int farmSaplingReserveAmount = 8; public static boolean farmStopOnNoOutputSlots = true; public static boolean farmEvictEmptyRFTools = true; public static int magnetPowerUsePerSecondRF = 1; public static int magnetPowerCapacityRF = 100000; public static int magnetRange = 5; public static String[] magnetBlacklist = new String[] { "appliedenergistics2:item.ItemCrystalSeed", "Botania:livingrock", "Botania:manaTablet" }; public static int magnetMaxItems = 20; public static boolean magnetAllowInMainInventory = false; public static boolean magnetAllowInBaublesSlot = true; public static boolean magnetAllowDeactivatedInBaublesSlot = false; public static boolean magnetAllowPowerExtraction = false; public static String magnetBaublesType = "AMULET"; public static int crafterRfPerCraft = 2500; public static int capacitorBankMaxIoRF = 5000; public static int capacitorBankMaxStorageRF = 5000000; public static int capacitorBankTierOneMaxIoRF = 1000; public static int capacitorBankTierOneMaxStorageRF = 1000000; public static int capacitorBankTierTwoMaxIoRF = 5000; public static int capacitorBankTierTwoMaxStorageRF = 5000000; public static int capacitorBankTierThreeMaxIoRF = 25000; public static int capacitorBankTierThreeMaxStorageRF = 25000000; public static boolean capacitorBankRenderPowerOverlayOnItem = false; public static int poweredSpawnerMinDelayTicks = 200; public static int poweredSpawnerMaxDelayTicks = 800; public static int poweredSpawnerMaxPlayerDistance = 0; public static int poweredSpawnerDespawnTimeSeconds = 120; public static int poweredSpawnerSpawnCount = 4; public static int poweredSpawnerSpawnRange = 4; public static int poweredSpawnerMaxNearbyEntities = 6; public static int poweredSpawnerMaxSpawnTries = 3; public static boolean poweredSpawnerUseVanillaSpawChecks = false; public static double brokenSpawnerDropChance = 1; public static String[] brokenSpawnerToolBlacklist = new String[] { "RotaryCraft:rotarycraft_item_bedpick" }; public static int powerSpawnerAddSpawnerCost = 16; public static int painterEnergyPerTaskRF = 2000; public static int vacuumChestRange = 6; public static int wirelessChargerRange = 24; public static long nutrientFoodBoostDelay = 400; public static int enchanterBaseLevelCost = 2; public static double enchanterLevelCostFactor = 0.75; public static double enchanterLapisCostFactor = 3; public static boolean machineSoundsEnabled = true; public static float machineSoundVolume = 1.0f; public static int killerJoeNutrientUsePerAttackMb = 5; public static double killerJoeAttackHeight = 2; public static double killerJoeAttackWidth = 2; public static double killerJoeAttackLength = 4; public static double killerJoeHooverXpWidth = 5; public static double killerJoeHooverXpLength = 10; public static int killerJoeMaxXpLevel = Integer.MAX_VALUE; public static boolean killerJoeMustSee = false; public static boolean killerPvPoffDisablesSwing = false; public static boolean killerPvPoffIsIgnored = false; public static boolean killerMending = false; public static boolean allowTileEntitiesAsPaintSource = true; public static boolean isGasConduitEnabled = true; public static boolean enableMEConduits = true; public static boolean enableOCConduits = true; public static boolean enableOCConduitsAnimatedTexture = true; public static List<String> soulVesselBlackList = Collections.<String> emptyList(); public static boolean soulVesselCapturesBosses = false; public static int soulBinderBrokenSpawnerRF = 2500000; public static int soulBinderBrokenSpawnerLevels = 6; public static int soulBinderReanimationRF = 100000; public static int soulBinderReanimationLevels = 4; public static int soulBinderEnderCystalRF = 100000; public static int soulBinderEnderCystalLevels = 4; public static int soulBinderAttractorCystalRF = 100000; public static int soulBinderAttractorCystalLevels = 4; public static int soulBinderEnderRailRF = 100000; public static int soulBinderEnderRailLevels = 4; public static int soulBinderTunedPressurePlateLevels = 2; public static int soulBinderTunedPressurePlateRF = 250000; public static int soulBinderMaxXpLevel = 40; public static boolean powerConduitCanDifferentTiersConnect = false; public static int powerConduitTierOneRF = 640; public static int powerConduitTierTwoRF = 5120; public static int powerConduitTierThreeRF = 20480; public static boolean powerConduitOutputMJ = true; public static boolean spawnGuardStopAllSlimesDebug = false; public static boolean spawnGuardStopAllSquidSpawning = false; public static int weatherObeliskClearFluid = 2000; public static int weatherObeliskRainFluid = 500; public static int weatherObeliskThunderFluid = 1000; //Loot Defaults public static boolean lootDarkSteel = true; public static boolean lootItemConduitProbe = true; public static boolean lootQuartz = true; public static boolean lootNetherWart = true; public static boolean lootEnderPearl = true; public static boolean lootElectricSteel = true; public static boolean lootRedstoneAlloy = true; public static boolean lootPhasedIron = true; public static boolean lootPhasedGold = true; public static boolean lootTravelStaff = true; public static boolean lootTheEnder = true; public static boolean lootDarkSteelBoots = true; public static boolean dumpMobNames = false; public static boolean enderRailEnabled = true; public static int enderRailPowerRequireCrossDimensions = 10000; public static int enderRailPowerRequiredPerBlock = 10; public static boolean enderRailCapSameDimensionPowerAtCrossDimensionCost = true; public static int enderRailTicksBeforeForceSpawningLinkedCarts = 60; public static boolean enderRailTeleportPlayers = false; public static int xpObeliskMaxXpLevel = Integer.MAX_VALUE; public static String xpJuiceName = "xpjuice"; public static boolean clearGlassConnectToFusedQuartz = false; public static boolean glassConnectToTheirVariants = true; public static boolean glassConnectToTheirColorVariants = true; public static Rarity enchantmentSoulBoundWeight = Rarity.UNCOMMON; public static boolean enchantmentSoulBoundEnabled = true; public static boolean telepadLockDimension = true; public static boolean telepadLockCoords = true; public static int telepadPowerCoefficient = 100000; public static int telepadPowerInterdimensional = 100000; public static boolean inventoryPanelFree = false; public static float inventoryPanelPowerPerMB = 800.0f; public static float inventoryPanelScanCostPerSlot = 0.1f; public static float inventoryPanelExtractCostPerItem = 12.0f; public static float inventoryPanelExtractCostPerOperation = 32.0f; public static boolean inventoryPanelScaleText = true; public static int remoteInventoryMBPerOpen = 100; public static int remoteInventoryRFPerTick = 4; public static int remoteInventoryMBCapacity = 2000; public static int remoteInventoryRFCapacity = 60000; public static boolean photovoltaicCanTypesJoins = true; public static int photovoltaicRecalcSunTick = 100; public static boolean debugUpdatePackets = false; public static boolean topEnabled = true; public static boolean topShowProgressByDefault = true; public static boolean topShowPowerByDefault = true; public static boolean topShowRedstoneByDefault = false; public static boolean topShowSideConfigByDefault = false; public static boolean topShowRangeByDefault = false; public static boolean topShowMobsByDefault = true; public static boolean topShowTanksByDefault = true; public static boolean paintedGlowstoneRequireSilkTouch = false; public static void load(FMLPreInitializationEvent event) { PacketHandler.INSTANCE.registerMessage(PacketConfigSync.class, PacketConfigSync.class, PacketHandler.nextID(), Side.CLIENT); MinecraftForge.EVENT_BUS.register(new Config()); configDirectory = new File(event.getModConfigurationDirectory(), EnderIO.DOMAIN); if(!configDirectory.exists()) { configDirectory.mkdir(); } File configFile = new File(configDirectory, "EnderIO.cfg"); config = new Configuration(configFile); syncConfig(false); } public static void syncConfig(boolean load) { try { if (load) { config.load(); } Config.processConfig(config); } catch (Exception e) { Log.error("EnderIO has a problem loading it's configuration"); e.printStackTrace(); } finally { if(config.hasChanged()) { config.save(); } } } @SubscribeEvent public void onConfigChanged(OnConfigChangedEvent event) { if (event.getModID().equals(EnderIO.MODID)) { Log.info("Updating config..."); syncConfig(false); init(); postInit(); } } @SubscribeEvent public void onConfigFileChanged(ConfigFileChangedEvent event) { if (event.getModID().equals(EnderIO.MODID)) { Log.info("Updating config..."); syncConfig(true); event.setSuccessful(); init(); postInit(); } } @SubscribeEvent public void onPlayerLoggon(PlayerLoggedInEvent evt) { PacketHandler.INSTANCE.sendTo(new PacketConfigSync(), (EntityPlayerMP) evt.player); } public static void processConfig(Configuration config) { capacitorBankMaxIoRF = config.get(sectionPower.name, "capacitorBankMaxIoRF", capacitorBankMaxIoRF, "The maximum IO for a single capacitor in RF/t") .getInt(capacitorBankMaxIoRF); capacitorBankMaxStorageRF = config.get(sectionPower.name, "capacitorBankMaxStorageRF", capacitorBankMaxStorageRF, "The maximum storage for a single capacitor in RF") .getInt(capacitorBankMaxStorageRF); capacitorBankTierOneMaxIoRF = config.get(sectionPower.name, "capacitorBankTierOneMaxIoRF", capacitorBankTierOneMaxIoRF, "The maximum IO for a single tier one capacitor in RF/t") .getInt(capacitorBankTierOneMaxIoRF); capacitorBankTierOneMaxStorageRF = config.get(sectionPower.name, "capacitorBankTierOneMaxStorageRF", capacitorBankTierOneMaxStorageRF, "The maximum storage for a single tier one capacitor in RF") .getInt(capacitorBankTierOneMaxStorageRF); capacitorBankTierTwoMaxIoRF = config.get(sectionPower.name, "capacitorBankTierTwoMaxIoRF", capacitorBankTierTwoMaxIoRF, "The maximum IO for a single tier two capacitor in RF/t") .getInt(capacitorBankTierTwoMaxIoRF); capacitorBankTierTwoMaxStorageRF = config.get(sectionPower.name, "capacitorBankTierTwoMaxStorageRF", capacitorBankTierTwoMaxStorageRF, "The maximum storage for a single tier two capacitor in RF") .getInt(capacitorBankTierTwoMaxStorageRF); capacitorBankTierThreeMaxIoRF = config.get(sectionPower.name, "capacitorBankTierThreeMaxIoRF", capacitorBankTierThreeMaxIoRF, "The maximum IO for a single tier three capacitor in RF/t") .getInt(capacitorBankTierThreeMaxIoRF); capacitorBankTierThreeMaxStorageRF = config.get(sectionPower.name, "capacitorBankTierThreeMaxStorageRF", capacitorBankTierThreeMaxStorageRF, "The maximum storage for a single tier three capacitor in RF") .getInt(capacitorBankTierThreeMaxStorageRF); capacitorBankRenderPowerOverlayOnItem = config.getBoolean("capacitorBankRenderPowerOverlayOnItem", sectionAesthetic.name, capacitorBankRenderPowerOverlayOnItem, "When true the the capacitor bank item wil get a power bar in addition to the gauge on the bank"); powerConduitTierOneRF = config.get(sectionPower.name, "powerConduitTierOneRF", powerConduitTierOneRF, "The maximum IO for the tier 1 power conduit") .getInt(powerConduitTierOneRF); powerConduitTierTwoRF = config.get(sectionPower.name, "powerConduitTierTwoRF", powerConduitTierTwoRF, "The maximum IO for the tier 2 power conduit") .getInt(powerConduitTierTwoRF); powerConduitTierThreeRF = config.get(sectionPower.name, "powerConduitTierThreeRF", powerConduitTierThreeRF, "The maximum IO for the tier 3 power conduit") .getInt(powerConduitTierThreeRF); powerConduitCanDifferentTiersConnect = config .getBoolean("powerConduitCanDifferentTiersConnect", sectionPower.name, powerConduitCanDifferentTiersConnect, "If set to false power conduits of different tiers cannot be connected. in this case a block such as a cap. bank is needed to bridge different tiered networks"); powerConduitOutputMJ = config.getBoolean("powerConduitOutputMJ", sectionPower.name, powerConduitOutputMJ, "When set to true power conduits will output MJ if RF is not supported"); painterEnergyPerTaskRF = config.get(sectionPower.name, "painterEnergyPerTaskRF", painterEnergyPerTaskRF, "The total amount of RF required to paint one block") .getInt(painterEnergyPerTaskRF); recipeLevel = config.get(sectionRecipe.name, "recipeLevel", recipeLevel, "How expensive should the crafting recipes be? -1=don't register any crafting/smelting recipes, 0=cheapest, 1=cheaper, 2=normal, 3=expensive").getInt( recipeLevel); registerRecipes = config .get(sectionRecipe.name, "registerRecipes", registerRecipes, "If set to false: No crafting recipes (crafting table and furnace) will be registered. You need to use Creative mode or something like minetweaker to add them yourself.") .getBoolean(registerRecipes); addPeacefulRecipes = config.get(sectionRecipe.name, "addPeacefulRecipes", addPeacefulRecipes, "When enabled peaceful recipes are added for soulbinder based crafting components.") .getBoolean(addPeacefulRecipes); allowTileEntitiesAsPaintSource = config.get(sectionRecipe.name, "allowTileEntitiesAsPaintSource", allowTileEntitiesAsPaintSource, "When enabled blocks with tile entities (e.g. machines) can be used as paint targets.") .getBoolean(allowTileEntitiesAsPaintSource); createSyntheticRecipes = config .get( sectionRecipe.name, "createSyntheticRecipes", createSyntheticRecipes, "Automatically create alloy smelter recipes with double and tripple inputs and different slot allocations (1+1+1, 2+1, 1+2, 3 and 2) for single-input recipes.") .getBoolean(createSyntheticRecipes); allowExternalTickSpeedup = config.get(sectionMisc.name, "allowExternalTickSpeedup", allowExternalTickSpeedup, "Allows machines to run faster if another mod speeds up the tickrate. Running at higher tickrates is " + "unsupported. Disable this if you run into any kind of problem.") .getBoolean(allowExternalTickSpeedup); redstoneConduitsShowState = config.get(sectionMisc.name, "redstoneConduitsShowState", redstoneConduitsShowState, "If set to false redstone conduits will look the same whether they are recieving a signal or not. This can help with performance.") .getBoolean(redstoneConduitsShowState); enchanterBaseLevelCost = config.get(sectionRecipe.name, "enchanterBaseLevelCost", enchanterBaseLevelCost, "Base level cost added to all recipes in the enchanter.").getInt(enchanterBaseLevelCost); enchanterLevelCostFactor = config.get(sectionRecipe.name, "enchanterLevelCostFactor", enchanterLevelCostFactor, "The final XP cost for an enchantment is multiplied by this value. To halve costs set to 0.5, to double them set it to 2").getDouble(enchanterLevelCostFactor); enchanterLapisCostFactor = config.get(sectionRecipe.name, "enchanterLapisCostFactor", enchanterLapisCostFactor, "The lapis cost is enchant level multiplied by this value").getDouble(enchanterLapisCostFactor); photovoltaicCellEnabled = config.get(sectionItems.name, "photovoltaicCellEnabled", photovoltaicCellEnabled, "If set to false: Photovoltaic Cells will not be craftable.") .getBoolean(photovoltaicCellEnabled); reservoirEnabled= config.get(sectionItems.name, "reservoirEnabled", reservoirEnabled, "If set to false reservoirs will not be craftable.") .getBoolean(reservoirEnabled); transceiverEnabled = config.get(sectionItems.name, "transceiverEnabled", transceiverEnabled, "If set to false: Dimensional Transceivers will not be craftable.") .getBoolean(transceiverEnabled); maxPhotovoltaicOutputRF = config.get(sectionPower.name, "maxPhotovoltaicOutputRF", maxPhotovoltaicOutputRF, "Maximum output in RF/t of the Photovoltaic Panels.").getInt(maxPhotovoltaicOutputRF); maxPhotovoltaicAdvancedOutputRF = config.get(sectionPower.name, "maxPhotovoltaicAdvancedOutputRF", maxPhotovoltaicAdvancedOutputRF, "Maximum output in RF/t of the Advanced Photovoltaic Panels.").getInt(maxPhotovoltaicAdvancedOutputRF); maxPhotovoltaicVibrantOutputRF = config.get(sectionPower.name, "maxPhotovoltaicVibrantOutputRF", maxPhotovoltaicVibrantOutputRF, "Maximum output in RF/t of the Vibrant Photovoltaic Panels.").getInt(maxPhotovoltaicVibrantOutputRF); photovoltaicCanTypesJoins = config.get(sectionPower.name, "photovoltaicCanTypesJoins", photovoltaicCanTypesJoins, "When enabled Photovoltaic Panels of different kinds can join together as a multi-block").getBoolean(photovoltaicCanTypesJoins); photovoltaicRecalcSunTick = config.get(sectionPower.name, "photovoltaicRecalcSunTick", photovoltaicRecalcSunTick, "How often (in ticks) the Photovoltaic Panels should check the sun's angle.").getInt(photovoltaicRecalcSunTick); conduitScale = config.get(sectionAesthetic.name, "conduitScale", DEFAULT_CONDUIT_SCALE, "Valid values are between 0-1, smallest conduits at 0, largest at 1.\n" + "In SMP, all clients must be using the same value as the server.").getDouble(DEFAULT_CONDUIT_SCALE); conduitScale = VecmathUtil.clamp(conduitScale, 0, 1); wirelessChargerRange = config.get(sectionEfficiency.name, "wirelessChargerRange", wirelessChargerRange, "The range of the wireless charger").getInt(wirelessChargerRange); fluidConduitExtractRate = config.get(sectionEfficiency.name, "fluidConduitExtractRate", fluidConduitExtractRate, "Number of millibuckets per tick extracted by a fluid conduits auto extracting").getInt(fluidConduitExtractRate); fluidConduitMaxIoRate = config.get(sectionEfficiency.name, "fluidConduitMaxIoRate", fluidConduitMaxIoRate, "Number of millibuckets per tick that can pass through a single connection to a fluid conduit.").getInt(fluidConduitMaxIoRate); advancedFluidConduitExtractRate = config.get(sectionEfficiency.name, "advancedFluidConduitExtractRate", advancedFluidConduitExtractRate, "Number of millibuckets per tick extracted by pressurized fluid conduits auto extracting").getInt(advancedFluidConduitExtractRate); advancedFluidConduitMaxIoRate = config.get(sectionEfficiency.name, "advancedFluidConduitMaxIoRate", advancedFluidConduitMaxIoRate, "Number of millibuckets per tick that can pass through a single connection to an pressurized fluid conduit.").getInt(advancedFluidConduitMaxIoRate); enderFluidConduitExtractRate = config.get(sectionEfficiency.name, "enderFluidConduitExtractRate", enderFluidConduitExtractRate, "Number of millibuckets per tick extracted by ender fluid conduits auto extracting").getInt(enderFluidConduitExtractRate); enderFluidConduitMaxIoRate = config.get(sectionEfficiency.name, "enderFluidConduitMaxIoRate", enderFluidConduitMaxIoRate, "Number of millibuckets per tick that can pass through a single connection to an ender fluid conduit.").getInt(enderFluidConduitMaxIoRate); gasConduitExtractRate = config.get(sectionEfficiency.name, "gasConduitExtractRate", gasConduitExtractRate, "Amount of gas per tick extracted by gas conduits auto extracting").getInt(gasConduitExtractRate); gasConduitMaxIoRate = config.get(sectionEfficiency.name, "gasConduitMaxIoRate", gasConduitMaxIoRate, "Amount of gas per tick that can pass through a single connection to a gas conduit.").getInt(gasConduitMaxIoRate); useAlternateTesseractModel = config.get(sectionAesthetic.name, "useAlternateTransceiverModel", useAlternateTesseractModel, "Use TheKazador's alternative model for the Dimensional Transceiver") .getBoolean(false); transceiverEnergyLoss = config.get(sectionPower.name, "transceiverEnergyLoss", transceiverEnergyLoss, "Amount of energy lost when transfered by Dimensional Transceiver; 0 is no loss, 1 is 100% loss").getDouble(transceiverEnergyLoss); transceiverBucketTransmissionCostRF = config.get(sectionEfficiency.name, "transceiverBucketTransmissionCostRF", transceiverBucketTransmissionCostRF, "The cost in RF of transporting a bucket of fluid via a Dimensional Transceiver.").getInt(transceiverBucketTransmissionCostRF); vatPowerUserPerTickRF = config.get(sectionPower.name, "vatPowerUserPerTickRF", vatPowerUserPerTickRF, "Power use (RF/t) used by the vat.").getInt(vatPowerUserPerTickRF); detailedPowerTrackingEnabled = config .get( sectionAdvanced.name, "perInterfacePowerTrackingEnabled", detailedPowerTrackingEnabled, "Enable per tick sampling on individual power inputs and outputs. This allows slightly more detailed messages from the RF Reader but has a negative impact on server performance.") .getBoolean(detailedPowerTrackingEnabled); jeiUseShortenedPainterRecipes = config .get(sectionPersonal.name, "jeiUseShortenedPainterRecipes", jeiUseShortenedPainterRecipes, "If true, only a handful of sample painter recipes will be shown in JEI. Enable this if you have timing problems starting a world or logging into a server.") .getBoolean(jeiUseShortenedPainterRecipes); useSneakMouseWheelYetaWrench = config.get(sectionPersonal.name, "useSneakMouseWheelYetaWrench", useSneakMouseWheelYetaWrench, "If true, shift-mouse wheel will change the conduit display mode when the YetaWrench is equipped.") .getBoolean(useSneakMouseWheelYetaWrench); useSneakRightClickYetaWrench = config.get(sectionPersonal.name, "useSneakRightClickYetaWrench", useSneakRightClickYetaWrench, "If true, shift-clicking the YetaWrench on a null or non wrenchable object will change the conduit display mode.").getBoolean( useSneakRightClickYetaWrench); yetaWrenchOverlayMode = config.getInt("yetaWrenchOverlayMode",sectionPersonal.name, yetaWrenchOverlayMode, 0, 2, "What kind of overlay to use when holding the yeta wrench\n\n" + "0 - Sideways scrolling in ceter of screen\n" + "1 - Vertical icon bar in bottom right\n" + "2 - Old-style group of icons in bottom right"); machineSoundsEnabled = config.get(sectionPersonal.name, "useMachineSounds", machineSoundsEnabled, "If true, machines will make sounds.").getBoolean( machineSoundsEnabled); machineSoundVolume = (float) config.get(sectionPersonal.name, "machineSoundVolume", machineSoundVolume, "Volume of machine sounds.").getDouble( machineSoundVolume); itemConduitUsePhyscialDistance = config.get(sectionEfficiency.name, "itemConduitUsePhyscialDistance", itemConduitUsePhyscialDistance, "If true, " + "'line of sight' distance rather than conduit path distance is used to calculate priorities.") .getBoolean(itemConduitUsePhyscialDistance); vacuumChestRange = config.get(sectionEfficiency.name, "vacumChestRange", vacuumChestRange, "The range of the vacuum chest").getInt(vacuumChestRange); reinforcedObsidianEnabled = config.get(sectionItems.name, "reinforcedObsidianEnabled", reinforcedObsidianEnabled, "When set to false reinforced obsidian is not craftable.").getBoolean(reinforcedObsidianEnabled); travelAnchorEnabled = config.get(sectionItems.name, "travelAnchorEnabled", travelAnchorEnabled, "When set to false: the travel anchor will not be craftable.").getBoolean(travelAnchorEnabled); travelAnchorMaximumDistance = config.get(sectionAnchor.name, "travelAnchorMaxDistance", travelAnchorMaximumDistance, "Maximum number of blocks that can be traveled from one travel anchor to another.").getInt(travelAnchorMaximumDistance); travelAnchorCooldown = config.get(sectionAnchor.name, "travelAnchorCooldown", travelAnchorCooldown, "Number of ticks cooldown between activations (1 sec = 20 ticks)").getInt(travelAnchorCooldown); travelAnchorSneak = config.get(sectionAnchor.name, "travelAnchorSneak", travelAnchorSneak, "Add sneak as an option to activate travel anchors").getBoolean(travelAnchorSneak); travelAnchorSkipWarning = config.get(sectionAnchor.name, "travelAnchorSkipWarning", travelAnchorSkipWarning, "Travel Anchors send a chat warning when skipping inaccessible anchors").getBoolean(travelAnchorSkipWarning); travelStaffMaximumDistance = config.get(sectionStaff.name, "travelStaffMaxDistance", travelStaffMaximumDistance, "Maximum number of blocks that can be traveled using the Staff of Traveling.").getInt(travelStaffMaximumDistance); travelStaffPowerPerBlockRF = (float) config.get(sectionStaff.name, "travelStaffPowerPerBlockRF", travelStaffPowerPerBlockRF, "Number of RF required per block traveled using the Staff of Traveling.").getDouble(travelStaffPowerPerBlockRF); travelStaffMaxBlinkDistance = config.get(sectionStaff.name, "travelStaffMaxBlinkDistance", travelStaffMaxBlinkDistance, "Max number of blocks teleported when shift clicking the staff.").getInt(travelStaffMaxBlinkDistance); travelStaffBlinkPauseTicks = config.get(sectionStaff.name, "travelStaffBlinkPauseTicks", travelStaffBlinkPauseTicks, "Minimum number of ticks between 'blinks'. Values of 10 or less allow a limited sort of flight.").getInt(travelStaffBlinkPauseTicks); travelStaffEnabled = config.get(sectionStaff.name, "travelStaffEnabled", travelStaffEnabled, "If set to false: the travel staff will not be craftable.").getBoolean(travelStaffEnabled); travelStaffBlinkEnabled = config.get(sectionStaff.name, "travelStaffBlinkEnabled", travelStaffBlinkEnabled, "If set to false: the travel staff can not be used to shift-right click teleport, or blink.").getBoolean(travelStaffBlinkEnabled); travelStaffBlinkThroughSolidBlocksEnabled = config.get(sectionStaff.name, "travelStaffBlinkThroughSolidBlocksEnabled", travelStaffBlinkThroughSolidBlocksEnabled, "If set to false: the travel staff can be used to blink through any block.").getBoolean(travelStaffBlinkThroughSolidBlocksEnabled); travelStaffBlinkThroughClearBlocksEnabled = config .get(sectionItems.name, "travelStaffBlinkThroughClearBlocksEnabled", travelStaffBlinkThroughClearBlocksEnabled, "If travelStaffBlinkThroughSolidBlocksEnabled is set to false and this is true: the travel " + "staff can only be used to blink through transparent or partial blocks (e.g. torches). " + "If both are false: only air blocks may be teleported through.") .getBoolean(travelStaffBlinkThroughClearBlocksEnabled); travelStaffBlinkThroughUnbreakableBlocksEnabled = config.get(sectionItems.name, "travelStaffBlinkThroughUnbreakableBlocksEnabled", travelStaffBlinkThroughUnbreakableBlocksEnabled, "Allows the travel staff to blink through unbreakable blocks such as warded blocks and bedrock.") .getBoolean(); travelStaffBlinkBlackList = config.getStringList("travelStaffBlinkBlackList", sectionStaff.name, travelStaffBlinkBlackList, "Lists the blocks that cannot be teleported through in the form 'modID:blockName'"); travelAnchorZoomScale = config.getFloat("travelAnchorZoomScale", sectionStaff.name, travelAnchorZoomScale, 0, 1, "Set the max zoomed size of a travel anchor as an aprox. percentage of screen height"); travelStaffOffhandBlinkEnabled = config .get(sectionStaff.name, "travelStaffOffhandBlinkEnabled", travelStaffOffhandBlinkEnabled, "If set to false: the travel staff can not be used to shift-right click teleport, or blink, when held in the off-hand.") .getBoolean(travelStaffOffhandBlinkEnabled); travelStaffOffhandTravelEnabled = config .get(sectionStaff.name, "travelStaffOffhandTravelEnabled", travelStaffOffhandTravelEnabled, "If set to false: the travel staff can not be used to click teleport to Travel Anchors, when held in the off-hand.") .getBoolean(travelStaffOffhandTravelEnabled); travelStaffOffhandEnderIOEnabled = config .get(sectionStaff.name, "travelStaffOffhandEnderIOEnabled", travelStaffOffhandEnderIOEnabled, "If set to false: the travel staff can not be used to activate the Ender IO, when held in the off-hand.") .getBoolean(travelStaffOffhandEnderIOEnabled); travelStaffOffhandShowsTravelTargets = config .get(sectionStaff.name, "travelStaffOffhandShowsTravelTargets", travelStaffOffhandShowsTravelTargets, "If set to false: Teleportation targets will not be highlighted for travel items held in the off-hand.") .getBoolean(travelStaffOffhandShowsTravelTargets); enderIoRange = config.get(sectionEfficiency.name, "enderIoRange", enderIoRange, "Range accessible (in blocks) when using the Ender IO.").getInt(enderIoRange); enderIoMeAccessEnabled = config.get(sectionPersonal.name, "enderIoMeAccessEnabled", enderIoMeAccessEnabled, "If false: you will not be able to access a ME access or crafting terminal using the Ender IO.").getBoolean(enderIoMeAccessEnabled); updateLightingWhenHidingFacades = config.get(sectionEfficiency.name, "updateLightingWhenHidingFacades", updateLightingWhenHidingFacades, "When true: correct lighting is recalculated (client side) for conduit bundles when transitioning to" + " from being hidden behind a facade. This produces " + "better quality rendering but can result in frame stutters when switching to/from a wrench.") .getBoolean(updateLightingWhenHidingFacades); transparentFacesLetThroughBeaconBeam = config .get(sectionAdvanced.name, "transparentFacesLetThroughBeaconBeam", transparentFacesLetThroughBeaconBeam, "If true, transparent facades will not block the Beacon's beam. As side effect they will also let through a tiny amount of light.") .getBoolean(transparentFacesLetThroughBeaconBeam); darkSteelRightClickPlaceEnabled = config.get(sectionDarkSteel.name, "darkSteelRightClickPlaceEnabled", darkSteelRightClickPlaceEnabled, "Enable / disable right click to place block using dark steel tools.").getBoolean(darkSteelRightClickPlaceEnabled); darkSteelPowerDamgeAbsorptionRatios = config .get(sectionDarkSteel.name, "darkSteelPowerDamgeAbsorptionRatios", darkSteelPowerDamgeAbsorptionRatios, "A list of the amount of durability damage absorbed when items are powered. In order of upgrade level. 1=100% so items take no durability damage when powered.") .getDoubleList(); darkSteelPowerStorageBase = config.get(sectionDarkSteel.name, "darkSteelPowerStorageBase", darkSteelPowerStorageBase, "Base amount of power stored by dark steel items.").getInt(darkSteelPowerStorageBase); darkSteelPowerStorageLevelOne = config.get(sectionDarkSteel.name, "darkSteelPowerStorageLevelOne", darkSteelPowerStorageLevelOne, "Amount of power stored by dark steel items with a level 1 upgrade.").getInt(darkSteelPowerStorageLevelOne); darkSteelPowerStorageLevelTwo = config.get(sectionDarkSteel.name, "darkSteelPowerStorageLevelTwo", darkSteelPowerStorageLevelTwo, "Amount of power stored by dark steel items with a level 2 upgrade.").getInt(darkSteelPowerStorageLevelTwo); darkSteelPowerStorageLevelThree = config.get(sectionDarkSteel.name, "darkSteelPowerStorageLevelThree", darkSteelPowerStorageLevelThree, "Amount of power stored by dark steel items with a level 3 upgrade.").getInt(darkSteelPowerStorageLevelThree); darkSteelUpgradeVibrantCost = config.get(sectionDarkSteel.name, "darkSteelUpgradeVibrantCost", darkSteelUpgradeVibrantCost, "Number of levels required for the 'Empowered.").getInt(darkSteelUpgradeVibrantCost); darkSteelUpgradePowerOneCost = config.get(sectionDarkSteel.name, "darkSteelUpgradePowerOneCost", darkSteelUpgradePowerOneCost, "Number of levels required for the 'Power 1.").getInt(darkSteelUpgradePowerOneCost); darkSteelUpgradePowerTwoCost = config.get(sectionDarkSteel.name, "darkSteelUpgradePowerTwoCost", darkSteelUpgradePowerTwoCost, "Number of levels required for the 'Power 2.").getInt(darkSteelUpgradePowerTwoCost); darkSteelUpgradePowerThreeCost = config.get(sectionDarkSteel.name, "darkSteelUpgradePowerThreeCost", darkSteelUpgradePowerThreeCost, "Number of levels required for the 'Power 3' upgrade.").getInt(darkSteelUpgradePowerThreeCost); darkSteelJumpOneCost = config.get(sectionDarkSteel.name, "darkSteelJumpOneCost", darkSteelJumpOneCost, "Number of levels required for the 'Jump 1' upgrade.").getInt(darkSteelJumpOneCost); darkSteelJumpTwoCost = config.get(sectionDarkSteel.name, "darkSteelJumpTwoCost", darkSteelJumpTwoCost, "Number of levels required for the 'Jump 2' upgrade.").getInt(darkSteelJumpTwoCost); darkSteelJumpThreeCost = config.get(sectionDarkSteel.name, "darkSteelJumpThreeCost", darkSteelJumpThreeCost, "Number of levels required for the 'Jump 3' upgrade.").getInt(darkSteelJumpThreeCost); darkSteelSpeedOneCost = config.get(sectionDarkSteel.name, "darkSteelSpeedOneCost", darkSteelSpeedOneCost, "Number of levels required for the 'Speed 1' upgrade.").getInt(darkSteelSpeedOneCost); darkSteelSpeedTwoCost = config.get(sectionDarkSteel.name, "darkSteelSpeedTwoCost", darkSteelSpeedTwoCost, "Number of levels required for the 'Speed 2' upgrade.").getInt(darkSteelSpeedTwoCost); darkSteelSpeedThreeCost = config.get(sectionDarkSteel.name, "darkSteelSpeedThreeCost", darkSteelSpeedThreeCost, "Number of levels required for the 'Speed 3' upgrade.").getInt(darkSteelSpeedThreeCost); darkSteelSpeedLimitFovChanges = config.get(sectionDarkSteel.name, "darkSteelSpeedLimitFovChanges", darkSteelSpeedLimitFovChanges, "When true FOV changes will not be effected by speed upgrades. Vanilla FOV changes will still occur.").getBoolean(darkSteelSpeedLimitFovChanges); darkSteelSpeedDisableFovChanges = config.get(sectionDarkSteel.name, "darkSteelSpeedDisableFovChanges", darkSteelSpeedDisableFovChanges, "When true the FOV will be constant when the upgrade is in effect. For example, it will not vary at all when sprinting or flying").getBoolean(darkSteelSpeedDisableFovChanges); slotZeroPlacesEight = config.get(sectionDarkSteel.name, "shouldSlotZeroWrap", slotZeroPlacesEight, "Should the dark steel placement, when in the first (0th) slot, place the item in the last slot. If false, will place what's in the second slot.").getBoolean(); darkSteelSpeedOneWalkModifier = (float) config.get(sectionDarkSteel.name, "darkSteelSpeedOneWalkModifier", darkSteelSpeedOneWalkModifier, "Speed modifier applied when walking in the Dark Steel Boots with Speed I.").getDouble(darkSteelSpeedOneWalkModifier); darkSteelSpeedTwoWalkMultiplier = (float) config.get(sectionDarkSteel.name, "darkSteelSpeedTwoWalkMultiplier", darkSteelSpeedTwoWalkMultiplier, "Speed modifier applied when walking in the Dark Steel Boots with Speed I.").getDouble(darkSteelSpeedTwoWalkMultiplier); darkSteelSpeedThreeWalkMultiplier = (float) config.get(sectionDarkSteel.name, "darkSteelSpeedThreeWalkMultiplier", darkSteelSpeedThreeWalkMultiplier, "Speed modifier applied when walking in the Dark Steel Boots with Speed I.").getDouble(darkSteelSpeedThreeWalkMultiplier); darkSteelSpeedOneSprintModifier = (float) config.get(sectionDarkSteel.name, "darkSteelSpeedOneSprintModifier", darkSteelSpeedOneSprintModifier, "Speed modifier applied when walking in the Dark Steel Boots with Speed I.").getDouble(darkSteelSpeedOneSprintModifier); darkSteelSpeedTwoSprintMultiplier = (float) config.get(sectionDarkSteel.name, "darkSteelSpeedTwoSprintMultiplier", darkSteelSpeedTwoSprintMultiplier, "Speed modifier applied when walking in the Dark Steel Boots with Speed I.").getDouble(darkSteelSpeedTwoSprintMultiplier); darkSteelSpeedThreeSprintMultiplier = (float) config.get(sectionDarkSteel.name, "darkSteelSpeedThreeSprintMultiplier", darkSteelSpeedThreeSprintMultiplier, "Speed modifier applied when walking in the Dark Steel Boots with Speed I.").getDouble(darkSteelSpeedThreeSprintMultiplier); darkSteelBootsJumpModifier = config.get(sectionDarkSteel.name, "darkSteelBootsJumpModifier", darkSteelBootsJumpModifier, "Jump height modifier applied when jumping with Dark Steel Boots equipped").getDouble(darkSteelBootsJumpModifier); darkSteelPowerStorageBase = config.get(sectionDarkSteel.name, "darkSteelPowerStorage", darkSteelPowerStorageBase, "Amount of power stored (RF) per crystal in the armor items recipe.").getInt(darkSteelPowerStorageBase); darkSteelWalkPowerCost = config.get(sectionDarkSteel.name, "darkSteelWalkPowerCost", darkSteelWalkPowerCost, "Amount of power stored (RF) per block walked when wearing the dark steel boots.").getInt(darkSteelWalkPowerCost); darkSteelSprintPowerCost = config.get(sectionDarkSteel.name, "darkSteelSprintPowerCost", darkSteelWalkPowerCost, "Amount of power stored (RF) per block walked when wearing the dark steel boots.").getInt(darkSteelSprintPowerCost); darkSteelDrainPowerFromInventory = config.get(sectionDarkSteel.name, "darkSteelDrainPowerFromInventory", darkSteelDrainPowerFromInventory, "If true, dark steel armor will drain power stored (RF) in power containers in the players inventory.").getBoolean(darkSteelDrainPowerFromInventory); darkSteelBootsJumpPowerCost = config.get(sectionDarkSteel.name, "darkSteelBootsJumpPowerCost", darkSteelBootsJumpPowerCost, "Base amount of power used per jump (RF) dark steel boots. The second jump in a 'double jump' uses 2x this etc").getInt(darkSteelBootsJumpPowerCost); darkSteelFallDistanceCost = config.get(sectionDarkSteel.name, "darkSteelFallDistanceCost", darkSteelFallDistanceCost, "Amount of power used (RF) per block height of fall distance damage negated.").getInt(darkSteelFallDistanceCost); darkSteelSwimCost = config.get(sectionDarkSteel.name, "darkSteelSwimCost", darkSteelSwimCost, "Number of levels required for the 'Swim' upgrade.").getInt(darkSteelSwimCost); darkSteelNightVisionCost = config.get(sectionDarkSteel.name, "darkSteelNightVisionCost", darkSteelNightVisionCost, "Number of levels required for the 'Night Vision' upgrade.").getInt(darkSteelNightVisionCost); darkSteelTOPCost = config.get(sectionDarkSteel.name, "darkSteelTOPCost", darkSteelTOPCost, "Number of levels required for the 'The One Probe' upgrade.") .getInt(darkSteelTOPCost); darkSteelGliderCost = config.get(sectionDarkSteel.name, "darkSteelGliderCost", darkSteelGliderCost, "Number of levels required for the 'Glider' upgrade.").getInt(darkSteelGliderCost); darkSteelGliderHorizontalSpeed = config.get(sectionDarkSteel.name, "darkSteelGliderHorizontalSpeed", darkSteelGliderHorizontalSpeed, "Horizontal movement speed modifier when gliding.").getDouble(darkSteelGliderHorizontalSpeed); darkSteelGliderVerticalSpeed = config.get(sectionDarkSteel.name, "darkSteelGliderVerticalSpeed", darkSteelGliderVerticalSpeed, "Rate of altitude loss when gliding.").getDouble(darkSteelGliderVerticalSpeed); darkSteelGliderVerticalSpeedSprinting = config.get(sectionDarkSteel.name, "darkSteelGliderVerticalSpeedSprinting", darkSteelGliderVerticalSpeedSprinting, "Rate of altitude loss when sprinting and gliding.").getDouble(darkSteelGliderVerticalSpeedSprinting); darkSteelSoundLocatorCost = config.get(sectionDarkSteel.name, "darkSteelSoundLocatorCost", darkSteelSoundLocatorCost, "Number of levels required for the 'Sound Locator' upgrade.").getInt(darkSteelSoundLocatorCost); darkSteelSoundLocatorRange = config.get(sectionDarkSteel.name, "darkSteelSoundLocatorRange", darkSteelSoundLocatorRange, "Range of the 'Sound Locator' upgrade.").getInt(darkSteelSoundLocatorRange); darkSteelSoundLocatorLifespan = config.get(sectionDarkSteel.name, "darkSteelSoundLocatorLifespan", darkSteelSoundLocatorLifespan, "Number of ticks the 'Sound Locator' icons are displayed for.").getInt(darkSteelSoundLocatorLifespan); darkSteelGogglesOfRevealingCost= config.get(sectionDarkSteel.name, "darkSteelGogglesOfRevealingCost", darkSteelGogglesOfRevealingCost, "Number of levels required for the Goggles of Revealing upgrade.").getInt(darkSteelGogglesOfRevealingCost); darkSteelApiaristArmorCost= config.get(sectionDarkSteel.name, "darkSteelApiaristArmorCost", darkSteelApiaristArmorCost, "Number of levels required for the Apiarist Armor upgrade.").getInt(darkSteelApiaristArmorCost); darkSteelTravelCost = config.get(sectionDarkSteel.name, "darkSteelTravelCost", darkSteelTravelCost, "Number of levels required for the 'Travel' upgrade.").getInt(darkSteelTravelCost); darkSteelSpoonCost = config.get(sectionDarkSteel.name, "darkSteelSpoonCost", darkSteelSpoonCost, "Number of levels required for the 'Spoon' upgrade.").getInt(darkSteelSpoonCost); darkSteelSolarOneCost = config.get(sectionDarkSteel.name, "darkSteelSolarOneCost", darkSteelSolarOneCost, "Cost in XP levels of the Solar I upgrade.").getInt(); darkSteelSolarOneGen = config.get(sectionDarkSteel.name, "darkSteelSolarOneGen", darkSteelSolarOneGen, "RF per SECOND generated by the Solar I upgrade. Split between all equipped DS armors.").getInt(); darkSteelSolarTwoCost = config.get(sectionDarkSteel.name, "darkSteelSolarTwoCost", darkSteelSolarTwoCost, "Cost in XP levels of the Solar II upgrade.").getInt(); darkSteelSolarTwoGen = config.get(sectionDarkSteel.name, "darkSteelSolarTwoGen", darkSteelSolarTwoGen, "RF per SECOND generated by the Solar II upgrade. Split between all equipped DS armors.").getInt(); darkSteelSolarThreeCost = config.get(sectionDarkSteel.name, "darkSteelSolarThreeCost", darkSteelSolarThreeCost, "Cost in XP levels of the Solar III upgrade.").getInt(); darkSteelSolarThreeGen = config.get(sectionDarkSteel.name, "darkSteelSolarThreeGen", darkSteelSolarThreeGen, "RF per SECOND generated by the Solar III upgrade. Split between all equipped DS armors.").getInt(); darkSteelSolarChargeOthers = config.get(sectionDarkSteel.name, "darkSteelSolarChargeOthers", darkSteelSolarChargeOthers, "If enabled allows the solar upgrade to charge non-darksteel armors that the player is wearing.").getBoolean(); darkSteelSwordSkullChance = (float) config.get(sectionDarkSteel.name, "darkSteelSwordSkullChance", darkSteelSwordSkullChance, "The base chance that a skull will be dropped when using a powered dark steel sword (0 = no chance, 1 = 100% chance)").getDouble( darkSteelSwordSkullChance); darkSteelSwordSkullLootingModifier = (float) config.get(sectionDarkSteel.name, "darkSteelSwordSkullLootingModifier", darkSteelSwordSkullLootingModifier, "The chance per looting level that a skull will be dropped when using a powered dark steel sword (0 = no chance, 1 = 100% chance)").getDouble( darkSteelSwordSkullLootingModifier); darkSteelSwordPoweredDamageBonus = (float) config.get(sectionDarkSteel.name, "darkSteelSwordPoweredDamageBonus", darkSteelSwordPoweredDamageBonus, "The extra damage dealt when the sword is powered").getDouble( darkSteelSwordPoweredDamageBonus); darkSteelSwordPoweredSpeedBonus = (float) config.get(sectionDarkSteel.name, "darkSteelSwordPoweredSpeedBonus", darkSteelSwordPoweredSpeedBonus, "The increase in attack speed when powered").getDouble( darkSteelSwordPoweredSpeedBonus); darkSteelSwordWitherSkullChance = (float) config.get(sectionDarkSteel.name, "darkSteelSwordWitherSkullChance", darkSteelSwordWitherSkullChance, "The base chance that a wither skull will be dropped when using a powered dark steel sword (0 = no chance, 1 = 100% chance)").getDouble( darkSteelSwordWitherSkullChance); darkSteelSwordWitherSkullLootingModifier = (float) config.get(sectionDarkSteel.name, "darkSteelSwordWitherSkullLootingModifie", darkSteelSwordWitherSkullLootingModifier, "The chance per looting level that a wither skull will be dropped when using a powered dark steel sword (0 = no chance, 1 = 100% chance)").getDouble( darkSteelSwordWitherSkullLootingModifier); vanillaSwordSkullChance = (float) config.get(sectionDarkSteel.name, "vanillaSwordSkullChance", vanillaSwordSkullChance, "The base chance that a skull will be dropped when using a non dark steel sword (0 = no chance, 1 = 100% chance)").getDouble( vanillaSwordSkullChance); vanillaSwordSkullLootingModifier = (float) config.get(sectionPersonal.name, "vanillaSwordSkullLootingModifier", vanillaSwordSkullLootingModifier, "The chance per looting level that a skull will be dropped when using a non-dark steel sword (0 = no chance, 1 = 100% chance)").getDouble( vanillaSwordSkullLootingModifier); ticCleaverSkullDropChance = (float) config.get(sectionDarkSteel.name, "ticCleaverSkullDropChance", ticCleaverSkullDropChance, "The base chance that an Enderman Skull will be dropped when using TiC Cleaver").getDouble( ticCleaverSkullDropChance); ticBeheadingSkullModifier = (float) config.get(sectionPersonal.name, "ticBeheadingSkullModifier", ticBeheadingSkullModifier, "The chance per level of Beheading that a skull will be dropped when using a TiC weapon").getDouble( ticBeheadingSkullModifier); fakePlayerSkullChance = (float) config .get( sectionDarkSteel.name, "fakePlayerSkullChance", fakePlayerSkullChance, "The ratio of skull drops when a mob is killed by a 'FakePlayer', such as Killer Joe. When set to 0 no skulls will drop, at 1 the rate of skull drops is not modified") .getDouble( fakePlayerSkullChance); darkSteelSwordPowerUsePerHit = config.get(sectionDarkSteel.name, "darkSteelSwordPowerUsePerHit", darkSteelSwordPowerUsePerHit, "The amount of power (RF) used per hit.").getInt(darkSteelSwordPowerUsePerHit); darkSteelSwordEnderPearlDropChance = config.get(sectionDarkSteel.name, "darkSteelSwordEnderPearlDropChance", darkSteelSwordEnderPearlDropChance, "The chance that an ender pearl will be dropped when using a dark steel sword (0 = no chance, 1 = 100% chance)").getDouble( darkSteelSwordEnderPearlDropChance); darkSteelSwordEnderPearlDropChancePerLooting = config.get(sectionDarkSteel.name, "darkSteelSwordEnderPearlDropChancePerLooting", darkSteelSwordEnderPearlDropChancePerLooting, "The chance for each looting level that an additional ender pearl will be dropped when using a dark steel sword (0 = no chance, 1 = 100% chance)") .getDouble( darkSteelSwordEnderPearlDropChancePerLooting); darkSteelPickPowerUseObsidian = config.get(sectionDarkSteel.name, "darkSteelPickPowerUseObsidian", darkSteelPickPowerUseObsidian, "The amount of power (RF) used to break an obsidian block.").getInt(darkSteelPickPowerUseObsidian); darkSteelPickEffeciencyObsidian = config.get(sectionDarkSteel.name, "darkSteelPickEffeciencyObsidian", darkSteelPickEffeciencyObsidian, "The efficiency when breaking obsidian with a powered Dark Pickaxe.").getInt(darkSteelPickEffeciencyObsidian); darkSteelPickApplyObsidianEffeciencyAtHardess = (float) config.get(sectionDarkSteel.name, "darkSteelPickApplyObsidianEffeciencyAtHardess", darkSteelPickApplyObsidianEffeciencyAtHardess, "If set to a value > 0, the obsidian speed and power use will be used for all blocks with hardness >= to this value.").getDouble( darkSteelPickApplyObsidianEffeciencyAtHardess); darkSteelPickPowerUsePerDamagePoint = config.get(sectionDarkSteel.name, "darkSteelPickPowerUsePerDamagePoint", darkSteelPickPowerUsePerDamagePoint, "Power use (RF) per damage/durability point avoided.").getInt(darkSteelPickPowerUsePerDamagePoint); darkSteelPickEffeciencyBoostWhenPowered = (float) config.get(sectionDarkSteel.name, "darkSteelPickEffeciencyBoostWhenPowered", darkSteelPickEffeciencyBoostWhenPowered, "The increase in efficiency when powered.").getDouble(darkSteelPickEffeciencyBoostWhenPowered); darkSteelPickMinesTiCArdite = config.getBoolean("darkSteelPickMinesTiCArdite", sectionDarkSteel.name, darkSteelPickMinesTiCArdite, "When true the dark steel pick will be able to mine TiC Ardite and Cobalt"); darkSteelAxePowerUsePerDamagePoint = config.get(sectionDarkSteel.name, "darkSteelAxePowerUsePerDamagePoint", darkSteelAxePowerUsePerDamagePoint, "Power use (RF) per damage/durability point avoided.").getInt(darkSteelAxePowerUsePerDamagePoint); darkSteelAxePowerUsePerDamagePointMultiHarvest = config.get(sectionDarkSteel.name, "darkSteelPickAxeUsePerDamagePointMultiHarvest", darkSteelAxePowerUsePerDamagePointMultiHarvest, "Power use (RF) per damage/durability point avoided when shift-harvesting multiple logs").getInt(darkSteelAxePowerUsePerDamagePointMultiHarvest); darkSteelAxeSpeedPenaltyMultiHarvest = (float) config.get(sectionDarkSteel.name, "darkSteelAxeSpeedPenaltyMultiHarvest", darkSteelAxeSpeedPenaltyMultiHarvest, "How much slower shift-harvesting logs is.").getDouble(darkSteelAxeSpeedPenaltyMultiHarvest); darkSteelAxeEffeciencyBoostWhenPowered = (float) config.get(sectionDarkSteel.name, "darkSteelAxeEffeciencyBoostWhenPowered", darkSteelAxeEffeciencyBoostWhenPowered, "The increase in efficiency when powered.").getDouble(darkSteelAxeEffeciencyBoostWhenPowered); darkSteelShearsDurabilityFactor = config.get(sectionDarkSteel.name, "darkSteelShearsDurabilityFactor", darkSteelShearsDurabilityFactor, "How much more durable as vanilla shears they are.").getInt(darkSteelShearsDurabilityFactor); darkSteelShearsPowerUsePerDamagePoint = config.get(sectionDarkSteel.name, "darkSteelShearsPowerUsePerDamagePoint", darkSteelShearsPowerUsePerDamagePoint, "Power use (RF) per damage/durability point avoided.").getInt(darkSteelShearsPowerUsePerDamagePoint); darkSteelShearsEffeciencyBoostWhenPowered = (float) config.get(sectionDarkSteel.name, "darkSteelShearsEffeciencyBoostWhenPowered", darkSteelShearsEffeciencyBoostWhenPowered, "The increase in efficiency when powered.").getDouble(darkSteelShearsEffeciencyBoostWhenPowered); darkSteelShearsBlockAreaBoostWhenPowered = config.get(sectionDarkSteel.name, "darkSteelShearsBlockAreaBoostWhenPowered", darkSteelShearsBlockAreaBoostWhenPowered, "The increase in effected area (radius) when powered and used on blocks.").getInt(darkSteelShearsBlockAreaBoostWhenPowered); darkSteelShearsEntityAreaBoostWhenPowered = (float) config.get(sectionDarkSteel.name, "darkSteelShearsEntityAreaBoostWhenPowered", darkSteelShearsEntityAreaBoostWhenPowered, "The increase in effected area (radius) when powered and used on sheep.").getDouble(darkSteelShearsEntityAreaBoostWhenPowered); darkSteelAnvilDamageChance = (float) config.get(sectionDarkSteel.name, "darkSteelAnvilDamageChance", darkSteelAnvilDamageChance, "Chance that the dark steel anvil will take damage after repairing something.").getDouble(); darkSteelLadderSpeedBoost = (float) config.get(sectionDarkSteel.name, "darkSteelLadderSpeedBoost", darkSteelLadderSpeedBoost, "Speed boost, in blocks per tick, that the DS ladder gives over the vanilla ladder.").getDouble(); hootchPowerPerCycleRF = config.get(sectionPower.name, "hootchPowerPerCycleRF", hootchPowerPerCycleRF, "The amount of power generated per BC engine cycle. Examples: BC Oil = 30, BC Fuel = 60").getInt(hootchPowerPerCycleRF); hootchPowerTotalBurnTime = config.get(sectionPower.name, "hootchPowerTotalBurnTime", hootchPowerTotalBurnTime, "The total burn time. Examples: BC Oil = 5000, BC Fuel = 25000").getInt(hootchPowerTotalBurnTime); rocketFuelPowerPerCycleRF = config.get(sectionPower.name, "rocketFuelPowerPerCycleRF", rocketFuelPowerPerCycleRF, "The amount of power generated per BC engine cycle. Examples: BC Oil = 3, BC Fuel = 6").getInt(rocketFuelPowerPerCycleRF); rocketFuelPowerTotalBurnTime = config.get(sectionPower.name, "rocketFuelPowerTotalBurnTime", rocketFuelPowerTotalBurnTime, "The total burn time. Examples: BC Oil = 5000, BC Fuel = 25000").getInt(rocketFuelPowerTotalBurnTime); fireWaterPowerPerCycleRF = config.get(sectionPower.name, "fireWaterPowerPerCycleRF", fireWaterPowerPerCycleRF, "The amount of power generated per BC engine cycle. Examples: BC Oil = 30, BC Fuel = 60").getInt(fireWaterPowerPerCycleRF); fireWaterPowerTotalBurnTime = config.get(sectionPower.name, "fireWaterPowerTotalBurnTime", fireWaterPowerTotalBurnTime, "The total burn time. Examples: BC Oil = 5000, BC Fuel = 25000").getInt(fireWaterPowerTotalBurnTime); zombieGeneratorRfPerTick = config.get(sectionPower.name, "zombieGeneratorRfPerTick", zombieGeneratorRfPerTick, "The amount of power generated per tick.").getInt(zombieGeneratorRfPerTick); zombieGeneratorTicksPerBucketFuel = config.get(sectionPower.name, "zombieGeneratorTicksPerMbFuel", zombieGeneratorTicksPerBucketFuel, "The number of ticks one bucket of fuel lasts.").getInt(zombieGeneratorTicksPerBucketFuel); addFuelTooltipsToAllFluidContainers = config.get(sectionPersonal.name, "addFuelTooltipsToAllFluidContainers", addFuelTooltipsToAllFluidContainers, "If true, the RF/t and burn time of the fuel will be displayed in all tooltips for fluid containers with fuel.").getBoolean( addFuelTooltipsToAllFluidContainers); addDurabilityTootip = config.get(sectionPersonal.name, "addDurabilityTootip", addFuelTooltipsToAllFluidContainers, "If true, adds durability tooltips to tools and armor").getBoolean( addDurabilityTootip); addFurnaceFuelTootip = config.get(sectionPersonal.name, "addFurnaceFuelTootip", addFuelTooltipsToAllFluidContainers, "If true, adds burn duration tooltips to furnace fuels").getBoolean(addFurnaceFuelTootip); farmActionEnergyUseRF = config.get(sectionFarm.name, "farmActionEnergyUseRF", farmActionEnergyUseRF, "The amount of power used by a farm per action (eg plant, till, harvest) ").getInt(farmActionEnergyUseRF); farmAxeActionEnergyUseRF = config.get(sectionFarm.name, "farmAxeActionEnergyUseRF", farmAxeActionEnergyUseRF, "The amount of power used by a farm per wood block 'chopped'").getInt(farmAxeActionEnergyUseRF); farmBonemealActionEnergyUseRF = config.get(sectionFarm.name, "farmBonemealActionEnergyUseRF", farmBonemealActionEnergyUseRF, "The amount of power used by a farm per bone meal used").getInt(farmBonemealActionEnergyUseRF); farmBonemealTryEnergyUseRF = config.get(sectionFarm.name, "farmBonemealTryEnergyUseRF", farmBonemealTryEnergyUseRF, "The amount of power used by a farm per bone meal try").getInt(farmBonemealTryEnergyUseRF); farmAxeDamageOnLeafBreak = config.get(sectionFarm.name, "farmAxeDamageOnLeafBreak", farmAxeDamageOnLeafBreak, "Should axes in a farm take damage when breaking leaves?").getBoolean(farmAxeDamageOnLeafBreak); farmToolTakeDamageChance = (float) config.get(sectionFarm.name, "farmToolTakeDamageChance", farmToolTakeDamageChance, "The chance that a tool in the farm will take damage.").getDouble(farmToolTakeDamageChance); disableFarmNotification = config.get(sectionFarm.name, "disableFarmNotifications", disableFarmNotification, "Disable the notification text above the farm block.").getBoolean(); farmEssenceBerriesEnabled = config.get(sectionFarm.name, "farmEssenceBerriesEnabled", farmEssenceBerriesEnabled, "This setting controls whether essence berry bushes from TiC can be harvested by the farm.").getBoolean(); farmManaBeansEnabled = config.get(sectionFarm.name, "farmManaBeansEnabled", farmManaBeansEnabled, "This setting controls whether mana beans from Thaumcraft can be harvested by the farm.").getBoolean(); farmHarvestJungleWhenCocoa = config.get(sectionFarm.name, "farmHarvestJungleWhenCocoa", farmHarvestJungleWhenCocoa, "If this is enabled the farm will harvest jungle wood even if it has cocoa beans in its inventory.").getBoolean(); hoeStrings = config.get(sectionFarm.name, "farmHoes", hoeStrings, "Use this to specify items that can be hoes in the farming station. Use the registry name (eg. modid:name).").getStringList(); farmSaplingReserveAmount = config.get(sectionFarm.name, "farmSaplingReserveAmount", farmSaplingReserveAmount, "The amount of saplings the farm has to have in reserve to switch to shearing all leaves. If there are less " + "saplings in store, it will only shear part the leaves and break the others for spalings. Set this to 0 to " + "always shear all leaves.").getInt(farmSaplingReserveAmount); farmStopOnNoOutputSlots = config.get(sectionFarm.name, "farmStopOnNoOutputSlots", farmStopOnNoOutputSlots, "If this is enabled the farm will stop if there is not at least one empty output slot. Otherwise it will only stop if all output slots are full.") .getBoolean(); farmEvictEmptyRFTools = config.get(sectionFarm.name, "farmEvictEmptyRFTools", farmEvictEmptyRFTools, "If this is enabled the farm will move tools that can store RF and are empty to the output slots instead of using them.").getBoolean(); magnetPowerUsePerSecondRF = config.get(sectionMagnet.name, "magnetPowerUsePerTickRF", magnetPowerUsePerSecondRF, "The amount of RF power used per tick when the magnet is active").getInt(magnetPowerUsePerSecondRF); magnetPowerCapacityRF = config.get(sectionMagnet.name, "magnetPowerCapacityRF", magnetPowerCapacityRF, "Amount of RF power stored in a fully charged magnet").getInt(magnetPowerCapacityRF); magnetRange = config.get(sectionMagnet.name, "magnetRange", magnetRange, "Range of the magnet in blocks.").getInt(magnetRange); magnetMaxItems = config.get(sectionMagnet.name, "magnetMaxItems", magnetMaxItems, "Maximum number of items the magnet can effect at a time. (-1 for unlimited)").getInt(magnetMaxItems); magnetBlacklist = config.getStringList("magnetBlacklist", sectionMagnet.name, magnetBlacklist, "These items will not be picked up by the magnet."); magnetAllowInMainInventory = config.get(sectionMagnet.name, "magnetAllowInMainInventory", magnetAllowInMainInventory, "If true the magnet will also work in the main inventory, not just the hotbar").getBoolean(magnetAllowInMainInventory); magnetAllowInBaublesSlot = config.get(sectionMagnet.name, "magnetAllowInBaublesSlot", magnetAllowInBaublesSlot, "If true the magnet can be put into the 'amulet' Baubles slot (requires Baubles to be installed)").getBoolean(magnetAllowInBaublesSlot); magnetAllowDeactivatedInBaublesSlot = config.get(sectionMagnet.name, "magnetAllowDeactivatedInBaublesSlot", magnetAllowDeactivatedInBaublesSlot, "If true the magnet can be put into the 'amulet' Baubles slot even if switched off (requires Baubles to be installed and magnetAllowInBaublesSlot to be on)").getBoolean(magnetAllowDeactivatedInBaublesSlot); magnetAllowPowerExtraction = config.get(sectionMagnet.name, "magnetAllowPowerExtraction", magnetAllowPowerExtraction, "If true the magnet can be used as a battery.").getBoolean(magnetAllowPowerExtraction); magnetBaublesType = config.get(sectionMagnet.name, "magnetBaublesType", magnetBaublesType, "The BaublesType the magnet should be, 'AMULET', 'RING' or 'BELT' (requires Baubles to be installed and magnetAllowInBaublesSlot to be on)").getString(); crafterRfPerCraft = config.get("AutoCrafter Settings", "crafterRfPerCraft", crafterRfPerCraft, "RF used per autocrafted recipe").getInt(crafterRfPerCraft); poweredSpawnerMinDelayTicks = config.get(sectionSpawner.name, "poweredSpawnerMinDelayTicks", poweredSpawnerMinDelayTicks, "Min tick delay between spawns for a non-upgraded spawner").getInt(poweredSpawnerMinDelayTicks); poweredSpawnerMaxDelayTicks = config.get(sectionSpawner.name, "poweredSpawnerMaxDelayTicks", poweredSpawnerMaxDelayTicks, "Min tick delay between spawns for a non-upgraded spawner").getInt(poweredSpawnerMaxDelayTicks); poweredSpawnerMaxPlayerDistance = config.get(sectionSpawner.name, "poweredSpawnerMaxPlayerDistance", poweredSpawnerMaxPlayerDistance, "Max distance of the closest player for the spawner to be active. A zero value will remove the player check").getInt(poweredSpawnerMaxPlayerDistance); poweredSpawnerDespawnTimeSeconds = config.get(sectionSpawner.name, "poweredSpawnerDespawnTimeSeconds" , poweredSpawnerDespawnTimeSeconds, "Number of seconds in which spawned entities are protected from despawning").getInt(poweredSpawnerDespawnTimeSeconds); poweredSpawnerSpawnCount = config.get(sectionSpawner.name, "poweredSpawnerSpawnCount" , poweredSpawnerSpawnCount, "Number of entities to spawn each time").getInt(poweredSpawnerSpawnCount); poweredSpawnerSpawnRange = config.get(sectionSpawner.name, "poweredSpawnerSpawnRange" , poweredSpawnerSpawnRange, "Spawning range in X/Z").getInt(poweredSpawnerSpawnRange); poweredSpawnerMaxNearbyEntities = config.get(sectionSpawner.name, "poweredSpawnerMaxNearbyEntities" , poweredSpawnerMaxNearbyEntities, "Max number of entities in the nearby area until no more are spawned. A zero value will remove this check").getInt(poweredSpawnerMaxNearbyEntities); poweredSpawnerMaxSpawnTries = config.get(sectionSpawner.name, "poweredSpawnerMaxSpawnTries" , poweredSpawnerMaxSpawnTries, "Number of tries to find a suitable spawning location").getInt(poweredSpawnerMaxSpawnTries); poweredSpawnerUseVanillaSpawChecks = config.get(sectionSpawner.name, "poweredSpawnerUseVanillaSpawChecks", poweredSpawnerUseVanillaSpawChecks, "If true, regular spawn checks such as lighting level and dimension will be made before spawning mobs").getBoolean(poweredSpawnerUseVanillaSpawChecks); brokenSpawnerDropChance = (float) config.get(sectionSpawner.name, "brokenSpawnerDropChance", brokenSpawnerDropChance, "The chance a broken spawner will be dropped when a spawner is broken. 1 = 100% chance, 0 = 0% chance").getDouble(brokenSpawnerDropChance); brokenSpawnerToolBlacklist = config.getStringList("brokenSpawnerToolBlacklist", sectionSpawner.name, brokenSpawnerToolBlacklist, "When a spawner is broken with these tools they will not drop a broken spawner"); powerSpawnerAddSpawnerCost = config.get(sectionSpawner.name, "powerSpawnerAddSpawnerCost", powerSpawnerAddSpawnerCost, "The number of levels it costs to add a broken spawner").getInt(powerSpawnerAddSpawnerCost); nutrientFoodBoostDelay = config.get(sectionFluid.name, "nutrientFluidFoodBoostDelay", nutrientFoodBoostDelay, "The delay in ticks between when nutrient distillation boosts your food value.").getInt((int) nutrientFoodBoostDelay); killerJoeNutrientUsePerAttackMb = config.get(sectionKiller.name, "killerJoeNutrientUsePerAttackMb", killerJoeNutrientUsePerAttackMb, "The number of millibuckets of nutrient fluid used per attack.").getInt(killerJoeNutrientUsePerAttackMb); killerJoeAttackHeight = config.get(sectionKiller.name, "killerJoeAttackHeight", killerJoeAttackHeight, "The reach of attacks above and bellow Joe.").getDouble(killerJoeAttackHeight); killerJoeAttackWidth = config.get(sectionKiller.name, "killerJoeAttackWidth", killerJoeAttackWidth, "The reach of attacks to each side of Joe.").getDouble(killerJoeAttackWidth); killerJoeAttackLength = config.get(sectionKiller.name, "killerJoeAttackLength", killerJoeAttackLength, "The reach of attacks in front of Joe.").getDouble(killerJoeAttackLength); killerJoeHooverXpLength = config.get(sectionKiller.name, "killerJoeHooverXpLength", killerJoeHooverXpLength, "The distance from which XP will be gathered to each side of Joe.").getDouble(killerJoeHooverXpLength); killerJoeHooverXpWidth = config.get(sectionKiller.name, "killerJoeHooverXpWidth", killerJoeHooverXpWidth, "The distance from which XP will be gathered in front of Joe.").getDouble(killerJoeHooverXpWidth); killerJoeMaxXpLevel = config.get(sectionMisc.name, "killerJoeMaxXpLevel", killerJoeMaxXpLevel, "Maximum level of XP the killer joe can contain.").getInt(); killerJoeMustSee = config.get(sectionKiller.name, "killerJoeMustSee", killerJoeMustSee, "Set whether the Killer Joe can attack through blocks.").getBoolean(); killerPvPoffDisablesSwing = config .get(sectionKiller.name, "killerPvPoffDisablesSwing", killerPvPoffDisablesSwing, "Set whether the Killer Joe swings even if PvP is off (that swing will do nothing unless killerPvPoffIsIgnored is enabled).") .getBoolean(); killerPvPoffIsIgnored = config .get(sectionKiller.name, "killerPvPoffIsIgnored", killerPvPoffIsIgnored, "Set whether the Killer Joe ignores PvP settings and always hits players (killerPvPoffDisablesSwing must be off for this to work).") .getBoolean(); killerMending = config .get(sectionKiller.name, "killerMending", killerMending, "If enabled, picked up XP will be used for the enchantement 'Mending' on the weapon.") .getBoolean(); // Add deprecated comment config.getString("isGasConduitEnabled", sectionItems.name, "auto", "Deprecated option. Use boolean \"gasConduitsEnabled\" below."); isGasConduitEnabled = config.getBoolean("gasConduitEnabled", sectionItems.name, isGasConduitEnabled, "If true, gas conduits will be enabled if the Mekanism Gas API is found. False to forcibly disable."); enableMEConduits = config.getBoolean("enableMEConduits", sectionItems.name, enableMEConduits, "Allows ME conduits. Only has an effect with AE2 installed."); enableOCConduits = config.getBoolean("enableOCConduits", sectionItems.name, enableOCConduits, "Allows OC conduits. Only has an effect with OpenComputers installed."); enableOCConduitsAnimatedTexture = config.getBoolean("enableOCConduitsAnimatedTexture", sectionItems.name, enableOCConduitsAnimatedTexture, "Use the animated texture for OC conduits."); soulVesselBlackList = Arrays.asList(config.getStringList("soulVesselBlackList", sectionSoulBinder.name, soulVesselBlackList.toArray(new String[0]), "Entities listed here will can not be captured in a Soul Vial")); soulVesselCapturesBosses = config.getBoolean("soulVesselCapturesBosses", sectionSoulBinder.name, soulVesselCapturesBosses, "When set to false, any mob with a 'boss bar' won't be able to be captured in the Soul Vial. Note: The Ender Dragon can not " + "be captured, even with this enabled. This is a limitation of the dragon, not the Soul Vial."); soulBinderBrokenSpawnerRF = config.get(sectionSoulBinder.name, "soulBinderBrokenSpawnerRF", soulBinderBrokenSpawnerRF, "The number of RF required to change the type of a broken spawner.").getInt(soulBinderBrokenSpawnerRF); soulBinderReanimationRF = config.get(sectionSoulBinder.name, "soulBinderReanimationRF", soulBinderReanimationRF, "The number of RF required to to re-animated a mob head.").getInt(soulBinderReanimationRF); soulBinderEnderCystalRF = config.get(sectionSoulBinder.name, "soulBinderEnderCystalRF", soulBinderEnderCystalRF, "The number of RF required to create an ender crystal.").getInt(soulBinderEnderCystalRF); soulBinderAttractorCystalRF = config.get(sectionSoulBinder.name, "soulBinderAttractorCystalRF", soulBinderAttractorCystalRF, "The number of RF required to create an attractor crystal.").getInt(soulBinderAttractorCystalRF); soulBinderEnderRailRF = config.get(sectionSoulBinder.name, "soulBinderEnderRailRF", soulBinderEnderRailRF, "The number of RF required to create an ender rail.").getInt(soulBinderEnderRailRF); soulBinderTunedPressurePlateRF = config.get(sectionSoulBinder.name, "soulBinderTunedPressurePlateRF", soulBinderTunedPressurePlateRF, "The number of RF required to tune a pressure plate.").getInt(soulBinderTunedPressurePlateRF); soulBinderAttractorCystalLevels = config.get(sectionSoulBinder.name, "soulBinderAttractorCystalLevels", soulBinderAttractorCystalLevels, "The number of levels required to create an attractor crystal.").getInt(soulBinderAttractorCystalLevels); soulBinderEnderCystalLevels = config.get(sectionSoulBinder.name, "soulBinderEnderCystalLevels", soulBinderEnderCystalLevels, "The number of levels required to create an ender crystal.").getInt(soulBinderEnderCystalLevels); soulBinderReanimationLevels = config.get(sectionSoulBinder.name, "soulBinderReanimationLevels", soulBinderReanimationLevels, "The number of levels required to re-animate a mob head.").getInt(soulBinderReanimationLevels); soulBinderBrokenSpawnerLevels = config.get(sectionSoulBinder.name, "soulBinderBrokenSpawnerLevels", soulBinderBrokenSpawnerLevels, "The number of levels required to change the type of a broken spawner.").getInt(soulBinderBrokenSpawnerLevels); soulBinderEnderRailLevels = config.get(sectionSoulBinder.name, "soulBinderEnderRailLevels", soulBinderEnderRailLevels, "The number of levels required to create an ender rail.").getInt(soulBinderEnderRailLevels); soulBinderTunedPressurePlateLevels = config.get(sectionSoulBinder.name, "soulBinderTunedPressurePlateLevels", soulBinderTunedPressurePlateLevels, "The number of levels required to tune a pressure plate.").getInt(soulBinderTunedPressurePlateLevels); soulBinderMaxXpLevel = config.get(sectionSoulBinder.name, "soulBinderMaxXPLevel", soulBinderMaxXpLevel, "Maximum level of XP the soul binder can contain.").getInt(); spawnGuardStopAllSlimesDebug = config.getBoolean("spawnGuardStopAllSlimesDebug", sectionAttractor.name, spawnGuardStopAllSlimesDebug, "When true slimes wont be allowed to spawn at all. Only added to aid testing in super flat worlds."); spawnGuardStopAllSquidSpawning = config.getBoolean("spawnGuardStopAllSquidSpawning", sectionAttractor.name, spawnGuardStopAllSquidSpawning, "When true no squid will be spawned."); weatherObeliskClearFluid = config.get(sectionWeather.name, "weatherObeliskClearFluid", weatherObeliskClearFluid, "The fluid required (in mB) to set the world to clear weather").getInt(); weatherObeliskRainFluid = config.get(sectionWeather.name, "weatherObeliskRainFluid", weatherObeliskRainFluid, "The fluid required (in mB) to set the world to rainy weather").getInt(); weatherObeliskThunderFluid = config.get(sectionWeather.name, "weatherObeliskThunderFluid", weatherObeliskThunderFluid, "The fluid required (in mB) to set the world to thundering weather").getInt(); // Loot Config lootDarkSteel = config.getBoolean("lootDarkSteel", sectionLootConfig.name, lootDarkSteel, "Adds Darksteel Ingots to loot tables"); lootItemConduitProbe = config.getBoolean("lootItemConduitProbe", sectionLootConfig.name, lootItemConduitProbe, "Adds ItemConduitProbe to loot tables"); lootQuartz = config.getBoolean("lootQuartz", sectionLootConfig.name, lootQuartz, "Adds quartz to loot tables"); lootNetherWart = config.getBoolean("lootNetherWart", sectionLootConfig.name, lootNetherWart, "Adds nether wart to loot tables"); lootEnderPearl = config.getBoolean("lootEnderPearl", sectionLootConfig.name, lootEnderPearl, "Adds ender pearls to loot tables"); lootElectricSteel = config.getBoolean("lootElectricSteel", sectionLootConfig.name, lootElectricSteel, "Adds Electric Steel Ingots to loot tables"); lootRedstoneAlloy = config.getBoolean("lootRedstoneAlloy", sectionLootConfig.name, lootRedstoneAlloy, "Adds Redstone Alloy Ingots to loot tables"); lootPhasedIron = config.getBoolean("lootPhasedIron", sectionLootConfig.name, lootPhasedIron, "Adds Phased Iron Ingots to loot tables"); lootPhasedGold = config.getBoolean("lootPhasedGold", sectionLootConfig.name, lootPhasedGold, "Adds Phased Gold Ingots to loot tables"); lootTravelStaff = config.getBoolean("lootTravelStaff", sectionLootConfig.name, lootTravelStaff, "Adds Travel Staff to loot tables"); lootTheEnder = config.getBoolean("lootTheEnder", sectionLootConfig.name, lootTheEnder, "Adds The Ender to loot tables"); lootDarkSteelBoots = config.getBoolean("lootDarkSteelBoots", sectionLootConfig.name, lootDarkSteelBoots, "Adds Darksteel Boots to loot tables"); enderRailEnabled = config.getBoolean("enderRailEnabled", sectionRailConfig.name, enderRailEnabled, "Whether Ender Rails are enabled"); enderRailPowerRequireCrossDimensions = config.get(sectionRailConfig.name, "enderRailPowerRequireCrossDimensions", enderRailPowerRequireCrossDimensions, "The amount of power required to transport a cart across dimensions").getInt(enderRailPowerRequireCrossDimensions); enderRailPowerRequiredPerBlock = config.get(sectionRailConfig.name, "enderRailPowerRequiredPerBlock", enderRailPowerRequiredPerBlock, "The amount of power required to teleport a cart per block in the same dimension").getInt(enderRailPowerRequiredPerBlock); enderRailCapSameDimensionPowerAtCrossDimensionCost = config.getBoolean("enderRailCapSameDimensionPowerAtCrossDimensionCost", sectionRailConfig.name, enderRailCapSameDimensionPowerAtCrossDimensionCost, "When set to true the RF cost of sending a cart within the same dimension will be capped to the cross dimension cost"); enderRailTicksBeforeForceSpawningLinkedCarts = config.get(sectionRailConfig.name, "enderRailTicksBeforeForceSpawningLinkedCarts", enderRailTicksBeforeForceSpawningLinkedCarts, "The number of ticks to wait for the track to clear before force spawning the next cart in a (RailCraft) linked set").getInt(enderRailTicksBeforeForceSpawningLinkedCarts); enderRailTeleportPlayers = config.getBoolean("enderRailTeleportPlayers", sectionRailConfig.name, enderRailTeleportPlayers, "If true player in minecarts will be teleported. WARN: WIP, seems to cause a memory leak."); dumpMobNames = config.getBoolean("dumpMobNames", sectionMobConfig.name, dumpMobNames, "When set to true a list of all registered mobs will be dumped to config/enderio/mobTypes.txt The names are in the format required by EIOs mob blacklists."); xpObeliskMaxXpLevel = config.get(sectionMisc.name, "xpObeliskMaxXpLevel", xpObeliskMaxXpLevel, "Maximum level of XP the xp obelisk can contain.").getInt(); xpJuiceName = config.getString("xpJuiceName", sectionMisc.name, xpJuiceName, "Id of liquid XP fluid (WARNING: only for users who know what they are doing - changing this id can break worlds) - this should match with OpenBlocks when installed"); glassConnectToTheirVariants = config.getBoolean("glassConnectToTheirVariants", sectionMisc.name, glassConnectToTheirVariants, "If true, quite clear glass and fused quartz will connect textures with their respective enlightened and darkened variants."); clearGlassConnectToFusedQuartz = config.getBoolean("clearGlassConnectToFusedQuartz", sectionMisc.name, clearGlassConnectToFusedQuartz, "If true, quite clear glass will connect textures with fused quartz."); glassConnectToTheirColorVariants = config.getBoolean("glassConnectToTheirColorVariants", sectionMisc.name, glassConnectToTheirColorVariants, "If true, quite clear glass and fused quartz of different colors will connect textures."); paintedGlowstoneRequireSilkTouch = config.getBoolean("paintedGlowstoneRequireSilkTouch", sectionMisc.name, paintedGlowstoneRequireSilkTouch, "If true, painted glowstone will drop dust unless broken with silk touch"); enchantmentSoulBoundEnabled = config.getBoolean("enchantmentSoulBoundEnabled", sectionEnchantments.name, enchantmentSoulBoundEnabled, "If false the soul bound enchantment will not be available"); String rareStr = config.get(sectionEnchantments.name, "enchantmentSoulBoundWeight", enchantmentSoulBoundWeight.toString(), "The rarity of the enchantment. COMMON, UNCOMMON, RARE, VERY_RARE ").getString(); try { enchantmentSoulBoundWeight = Rarity.valueOf(rareStr); } catch (Exception e) { Log.warn("Could not set value config entry enchantmentWitherArrowRarity Specified value " + rareStr); e.printStackTrace(); } telepadLockDimension = config.get(sectionTelepad.name, "lockDimension", telepadLockDimension, "If true, the dimension cannot be set via the GUI, the coord selector must be used.").getBoolean(); telepadLockCoords = config.get(sectionTelepad.name, "lockCoords", telepadLockCoords, "If true, the coordinates cannot be set via the GUI, the coord selector must be used.").getBoolean(); telepadPowerCoefficient = config.get(sectionTelepad.name, "powerCoefficient", telepadPowerCoefficient, "Power for a teleport is calculated by the formula:\npower = [this value] * ln(0.005*distance + 1)").getInt(); telepadPowerInterdimensional = config.get(sectionTelepad.name, "powerInterdimensional", telepadPowerInterdimensional, "The amount of RF required for an interdimensional teleport.").getInt(); inventoryPanelFree = config.getBoolean("inventoryPanelFree", sectionInventoryPanel.name, inventoryPanelFree, "If true, the inv panel will not accept fluids and will be active permanently."); inventoryPanelPowerPerMB = config.getFloat("powerPerMB", sectionInventoryPanel.name, inventoryPanelPowerPerMB, 1.0f, 10000.0f, "Internal power generated per mB. The default of 800/mB matches the RF generation of the Zombie generator. A panel tries to refill only once every second - setting this value too low slows down the scanning speed."); inventoryPanelScanCostPerSlot = config.getFloat("scanCostPerSlot", sectionInventoryPanel.name, inventoryPanelScanCostPerSlot, 0.0f, 10.0f, "Internal power used for scanning a slot"); inventoryPanelExtractCostPerItem = config.getFloat("extractCostPerItem", sectionInventoryPanel.name, inventoryPanelExtractCostPerItem, 0.0f, 10.0f, "Internal power used per item extracted (not a stack of items)"); inventoryPanelExtractCostPerOperation = config.getFloat("extractCostPerOperation", sectionInventoryPanel.name, inventoryPanelExtractCostPerOperation, 0.0f, 10000.0f, "Internal power used per extract operation (independent of stack size)"); inventoryPanelScaleText= config.getBoolean("inventoryPanelScaleText", sectionInventoryPanel.name, inventoryPanelScaleText, "If true stack sizes will be drawn at a smaller size with a little more detail."); debugUpdatePackets = config.getBoolean("debugUpdatePackets", sectionPersonal.name, debugUpdatePackets, "DEBUG: If true, TEs will flash when they recieve an update packet."); topEnabled = config.getBoolean("topEnabled", sectionTOP.name, topEnabled, "If true, 'The One Probe' by McJty will be supported"); topShowProgressByDefault = config.getBoolean("topShowProgressByDefault", sectionTOP.name, topShowProgressByDefault, "If true, the progress will be shown always, otherwise only it will only be shown on 'extended' mode (e.g. with shift pressed)"); topShowPowerByDefault = config.getBoolean("topShowPowerByDefault", sectionTOP.name, topShowPowerByDefault, "If true, the power level will be shown always, otherwise only it will only be shown on 'extended' mode (e.g. with shift pressed)"); topShowRedstoneByDefault = config.getBoolean("topShowRedstoneByDefault", sectionTOP.name, topShowRedstoneByDefault, "If true, the resdstone status will be shown always, otherwise only it will only be shown on 'extended' mode (e.g. with shift pressed)"); topShowSideConfigByDefault = config.getBoolean("topShowSideConfigByDefault", sectionTOP.name, topShowSideConfigByDefault, "If true, the side config will be shown always, otherwise only it will only be shown on 'extended' mode (e.g. with shift pressed)"); topShowRangeByDefault = config.getBoolean("topShowRangeByDefault", sectionTOP.name, topShowRangeByDefault, "If true, the range will be shown always, otherwise only it will only be shown on 'extended' mode (e.g. with shift pressed)"); topShowMobsByDefault = config.getBoolean("topShowMobsByDefault", sectionTOP.name, topShowMobsByDefault, "If true, the mob list will be shown always, otherwise only it will only be shown on 'extended' mode (e.g. with shift pressed)"); topShowTanksByDefault = config.getBoolean("topShowTanksByDefault", sectionTOP.name, topShowTanksByDefault, "If true, the tank content will be shown always, otherwise only it will only be shown on 'extended' mode (e.g. with shift pressed)"); CapacitorKey.processConfig(config); } public static void checkYetaAccess() { if(!useSneakMouseWheelYetaWrench && !useSneakRightClickYetaWrench) { Log.warn("Both useSneakMouseWheelYetaWrench and useSneakRightClickYetaWrench are set to false. Enabling right click."); useSneakRightClickYetaWrench = true; } } public static void init() { } public static void postInit() { farmHoes = new Things(); for (String hoe : hoeStrings) { farmHoes.add(hoe); } } public static ItemStack getStackForString(String s) { String[] nameAndMeta = s.split(";"); int meta = nameAndMeta.length == 1 ? 0 : Integer.parseInt(nameAndMeta[1]); String[] data = nameAndMeta[0].split(":"); Item item = Item.REGISTRY.getObject(new ResourceLocation(data[0], data[1])); if(item == null) { return null; } return new ItemStack(item, 1, meta); } private Config() { } }
Remvoed config setting that was moved to endercore ages ago
src/main/java/crazypants/enderio/config/Config.java
Remvoed config setting that was moved to endercore ages ago
<ide><path>rc/main/java/crazypants/enderio/config/Config.java <ide> <ide> public static int recipeLevel = 2; <ide> public static boolean addPeacefulRecipes = false; <del> public static boolean allowExternalTickSpeedup = true; <ide> public static boolean createSyntheticRecipes = true; <ide> <ide> public static boolean detailedPowerTrackingEnabled = false; <ide> "Automatically create alloy smelter recipes with double and tripple inputs and different slot allocations (1+1+1, 2+1, 1+2, 3 and 2) for single-input recipes.") <ide> .getBoolean(createSyntheticRecipes); <ide> <del> allowExternalTickSpeedup = config.get(sectionMisc.name, "allowExternalTickSpeedup", allowExternalTickSpeedup, <del> "Allows machines to run faster if another mod speeds up the tickrate. Running at higher tickrates is " <del> + "unsupported. Disable this if you run into any kind of problem.") <del> .getBoolean(allowExternalTickSpeedup); <del> <ide> redstoneConduitsShowState = config.get(sectionMisc.name, "redstoneConduitsShowState", redstoneConduitsShowState, <ide> "If set to false redstone conduits will look the same whether they are recieving a signal or not. This can help with performance.") <ide> .getBoolean(redstoneConduitsShowState);
JavaScript
mit
b298b9dd4307339c558e9aed38eaa23b746835f1
0
heytrav/nodepp
var moment = require('moment'); var AMQP = require('amqp-as-promised'); var Dispatcher = require('./dispatcher-es6'); var nconf = require('./utilities/config.js').getConfig(); var logger = require('./utilities/logging.js').getLogger(nconf); var processId = process.pid; var registry = nconf.get('registries')[0]; logger.debug("Environment: ", process.env); let host = nconf.get("rabbithost") || nconf.get("RABBITMQ_HOST"); let port = nconf.get("rabbitport") || nconf.get("RABBIT_PORT"); let login = nconf.get("rabbitlogin") || nconf.get("RABBITMQ_DEFAULT_USER"); let password = nconf.get("rabbitpassword") || nconf.get("RABBITMQ_DEFAULT_PASS"); let vhost = nconf.get("vhost") || nconf.get("RABBITMQ_DEFAULT_VHOST"); let rabbitConnection = { host: host, port: port, login: login, password: password, vhost: vhost, noDelay: true, ssl: { enabled: false } }; logger.debug("Initialised with registry ", registry); let dispatcher = new Dispatcher(registry); dispatcher.startEpp(); var availableProcesses = {}; logger.debug("Connecting to AMQP server", rabbitConnection); var amqpConnection = new AMQP(rabbitConnection); amqpConnection.errorHandler = (error) => { logger.error("In errorHandler", error); process.exit(0); }; amqpConnection.serve('epp', registry, (incoming, headers, del) => { var msg = JSON.parse(String.fromCharCode.apply(String, incoming.data)) let {command, data} = msg; var a = moment(); return dispatcher.command(command, data).then((response) => { var b = moment(); var diff = b.diff(a, 'milliseconds'); logger.info(command + ' request elapsed time: ' + diff.toString() + ' ms'); return response; }, (error) => { logger.error("In error callback of promise", error); return error; }); }); process.on('SIGINT', () => { var logoutResponse = (data) => { logger.debug("Got reply from logout ", data); }; var data = { kill: true }; dispatcher.command('logout', data).then((response) => { logger.info('Logged out.'); return response; }, (error) => { logger.error(error); return error; }); amqpConnection.shutdown(); process.exit(0); });
lib/rabbit-epp.js
var moment = require('moment'); var AMQP = require('amqp-as-promised'); var Dispatcher = require('./dispatcher-es6'); var nconf = require('./utilities/config.js').getConfig(); var logger = require('./utilities/logging.js').getLogger(nconf); var processId = process.pid; var registry = nconf.get('registries')[0]; logger.debug("Environment: ", process.env); let host = nconf.get("rabbithost") || nconf.get("RABBITMQ_HOST"); let port = nconf.get("rabbitport") || nconf.get("RABBIT_PORT"); let login = nconf.get("rabbitlogin") || nconf.get("RABBITMQ_DEFAULT_USER"); let password = nconf.get("rabbitpassword") || nconf.get("RABBITMQ_DEFAULT_PASS"); let vhost = nconf.get("vhost") || nconf.get("RABBITMQ_DEFAULT_VHOST"); let rabbitConnection = { host: host, port: port, login: login, password: password, vhost: vhost, noDelay: true, ssl: { enabled: false } }; logger.debug("Initialised with registry ", registry); let dispatcher = new Dispatcher(registry); dispatcher.startEpp(); var availableProcesses = {}; logger.debug("Connecting to AMQP server", rabbitConnection); var amqpConnection = new AMQP(rabbitConnection); amqpConnection.errorHandler = (error) => { logger.error(error); }; amqpConnection.serve('epp', registry, (incoming, headers, del) => { var msg = JSON.parse(String.fromCharCode.apply(String, incoming.data)) let {command, data} = msg; var a = moment(); return dispatcher.command(command, data).then((response) => { var b = moment(); var diff = b.diff(a, 'milliseconds'); logger.info(command + ' request elapsed time: ' + diff.toString() + ' ms'); return response; }, (error) => { logger.error(error); return error }); }); process.on('SIGINT', () => { var logoutResponse = (data) => { logger.debug("Got reply from logout ", data); }; var data = { kill: true }; dispatcher.command('logout', data).then((response) => { logger.info('Logged out.'); return response; }, (error) => { logger.error(error); return error; }); amqpConnection.shutdown(); process.exit(0); });
Exit with an error if the amqp connection goes away
lib/rabbit-epp.js
Exit with an error if the amqp connection goes away
<ide><path>ib/rabbit-epp.js <ide> logger.debug("Connecting to AMQP server", rabbitConnection); <ide> var amqpConnection = new AMQP(rabbitConnection); <ide> amqpConnection.errorHandler = (error) => { <del> logger.error(error); <add> logger.error("In errorHandler", error); <add> process.exit(0); <ide> }; <ide> amqpConnection.serve('epp', registry, (incoming, headers, del) => { <ide> var msg = JSON.parse(String.fromCharCode.apply(String, incoming.data)) <ide> logger.info(command + ' request elapsed time: ' + diff.toString() + ' ms'); <ide> return response; <ide> }, (error) => { <del> logger.error(error); <del> return error <add> logger.error("In error callback of promise", error); <add> return error; <ide> }); <ide> }); <ide> process.on('SIGINT', () => {
JavaScript
mpl-2.0
9cae39965871a9c5b57013bedf975ecd737e7096
0
gladly-team/tab,gladly-team/tab,gladly-team/tab
/* eslint-env jest */ import React from 'react' import { shallow } from 'enzyme' import toJson from 'enzyme-to-json' import { isSearchPageEnabled } from 'js/utils/feature-flags' import { goTo, dashboardURL } from 'js/navigation/navigation' jest.mock('js/utils/feature-flags') jest.mock('js/navigation/navigation') const getMockProps = () => ({ user: { id: 'some-user-id-here' }, app: {} }) beforeEach(() => { isSearchPageEnabled.mockReturnValue(true) }) afterEach(() => { jest.clearAllMocks() }) describe('Search page component', () => { it('renders without error', () => { const SearchPageComponent = require('js/components/Search/SearchPageComponent').default const mockProps = getMockProps() shallow( <SearchPageComponent {...mockProps} /> ).dive() }) it('renders no DOM elements when the search page feature is not enabled', () => { isSearchPageEnabled.mockReturnValue(false) const SearchPageComponent = require('js/components/Search/SearchPageComponent').default const mockProps = getMockProps() const wrapper = shallow( <SearchPageComponent {...mockProps} /> ).dive() expect(toJson(wrapper)).toEqual('') }) it('redirects to the dashboard when the search page feature is not enabled', () => { isSearchPageEnabled.mockReturnValue(false) const SearchPageComponent = require('js/components/Search/SearchPageComponent').default const mockProps = getMockProps() shallow( <SearchPageComponent {...mockProps} /> ).dive() expect(goTo).toHaveBeenCalledWith(dashboardURL) }) it('renders DOM elements when the search page feature is enabled', () => { isSearchPageEnabled.mockReturnValue(true) const SearchPageComponent = require('js/components/Search/SearchPageComponent').default const mockProps = getMockProps() const wrapper = shallow( <SearchPageComponent {...mockProps} /> ).dive() expect(toJson(wrapper)).not.toEqual('') }) it('does not redirect to the dashboard when the search page feature is enabled', () => { isSearchPageEnabled.mockReturnValue(true) const SearchPageComponent = require('js/components/Search/SearchPageComponent').default const mockProps = getMockProps() shallow( <SearchPageComponent {...mockProps} /> ).dive() expect(goTo).not.toHaveBeenCalled() }) })
web/src/js/components/Search/__tests__/SearchPageComponent.test.js
/* eslint-env jest */ import React from 'react' import { shallow } from 'enzyme' import toJson from 'enzyme-to-json' import { isSearchPageEnabled } from 'js/utils/feature-flags' import { goTo, dashboardURL } from 'js/navigation/navigation' jest.mock('js/utils/feature-flags') jest.mock('js/navigation/navigation') const getMockProps = () => ({ user: { id: 'some-user-id-here' }, app: {} }) beforeEach(() => { isSearchPageEnabled.mockReturnValue(true) }) afterEach(() => { jest.clearAllMocks() }) describe('Search page component', () => { it('renders without error', () => { const SearchPageComponent = require('js/components/Search/SearchPageComponent').default const mockProps = getMockProps() shallow( <SearchPageComponent {...mockProps} /> ) }) it('renders no DOM elements when the search page feature is not enabled', () => { isSearchPageEnabled.mockReturnValue(false) const SearchPageComponent = require('js/components/Search/SearchPageComponent').default const mockProps = getMockProps() const wrapper = shallow( <SearchPageComponent {...mockProps} /> ) expect(toJson(wrapper)).toEqual('') }) it('redirects to the dashboard when the search page feature is not enabled', () => { isSearchPageEnabled.mockReturnValue(false) const SearchPageComponent = require('js/components/Search/SearchPageComponent').default const mockProps = getMockProps() shallow( <SearchPageComponent {...mockProps} /> ) expect(goTo).toHaveBeenCalledWith(dashboardURL) }) it('renders DOM elements when the search page feature is enabled', () => { isSearchPageEnabled.mockReturnValue(true) const SearchPageComponent = require('js/components/Search/SearchPageComponent').default const mockProps = getMockProps() const wrapper = shallow( <SearchPageComponent {...mockProps} /> ) expect(toJson(wrapper)).not.toEqual('') }) it('does not redirect to the dashboard when the search page feature is enabled', () => { isSearchPageEnabled.mockReturnValue(true) const SearchPageComponent = require('js/components/Search/SearchPageComponent').default const mockProps = getMockProps() shallow( <SearchPageComponent {...mockProps} /> ) expect(goTo).not.toHaveBeenCalled() }) })
Fix tests when using withStyles HOC
web/src/js/components/Search/__tests__/SearchPageComponent.test.js
Fix tests when using withStyles HOC
<ide><path>eb/src/js/components/Search/__tests__/SearchPageComponent.test.js <ide> const mockProps = getMockProps() <ide> shallow( <ide> <SearchPageComponent {...mockProps} /> <del> ) <add> ).dive() <ide> }) <ide> <ide> it('renders no DOM elements when the search page feature is not enabled', () => { <ide> const mockProps = getMockProps() <ide> const wrapper = shallow( <ide> <SearchPageComponent {...mockProps} /> <del> ) <add> ).dive() <ide> expect(toJson(wrapper)).toEqual('') <ide> }) <ide> <ide> const mockProps = getMockProps() <ide> shallow( <ide> <SearchPageComponent {...mockProps} /> <del> ) <add> ).dive() <ide> expect(goTo).toHaveBeenCalledWith(dashboardURL) <ide> }) <ide> <ide> const mockProps = getMockProps() <ide> const wrapper = shallow( <ide> <SearchPageComponent {...mockProps} /> <del> ) <add> ).dive() <ide> expect(toJson(wrapper)).not.toEqual('') <ide> }) <ide> <ide> const mockProps = getMockProps() <ide> shallow( <ide> <SearchPageComponent {...mockProps} /> <del> ) <add> ).dive() <ide> expect(goTo).not.toHaveBeenCalled() <ide> }) <ide> })
Java
apache-2.0
f6eabce3992662273c75eec0fe0f3e2896b347fa
0
lstephen/esms-ai,lstephen/esms-ai
package com.ljs.ifootballmanager.ai.selection; import com.google.common.base.Function; import com.google.common.collect.Ordering; import com.ljs.ifootballmanager.ai.formation.Formation; import com.ljs.ifootballmanager.ai.player.Player; import com.ljs.ifootballmanager.ai.player.Squad; import com.ljs.ifootballmanager.ai.report.Report; import java.io.PrintWriter; import java.util.Optional; public final class RestPlan implements Report { private final Squad squad; private final Formation formation; private final Bench bench; private RestPlan(Squad s, Formation f, Bench b) { this.squad = s; this.formation = f; this.bench = b; } private Optional<Player> getPlayerToBeRested() { Player lowestFitness = Ordering.natural() .onResultOf((Player p) -> squad.findPlayer(p.getName()).getFitness()) .min(formation.players()); return squad.findPlayer(lowestFitness.getName()).isFullFitness() ? Optional.empty() : Optional.of(lowestFitness); } private Player getSubstituteFor(Player p) { return bench.findSubstitute(formation.findRole(p)); } public void print(PrintWriter w) { getPlayerToBeRested() .ifPresent( out -> { Player in = getSubstituteFor(out); w.format( "SUB %s %s %s IF SCORE <= -3%n", out.getName(), in.getName(), formation.findRole(out)); w.format( "SUB %s %s %s IF SCORE >= 3%n", out.getName(), in.getName(), formation.findRole(out)); }); } public void print(PrintWriter w, Function<Player, Integer> playerIdx) { getPlayerToBeRested() .ifPresent( out -> { Player in = getSubstituteFor(out); w.format( "SUB %s %s %s IF SCORE <= -3%n", playerIdx.apply(out), playerIdx.apply(in), formation.findRole(out)); w.format( "SUB %s %s %s IF SCORE >= 3%n", playerIdx.apply(out), playerIdx.apply(in), formation.findRole(out)); }); } public static RestPlan create(Squad s, Formation f, Bench b) { return new RestPlan(s, f, b); } }
src/main/java/com/ljs/ifootballmanager/ai/selection/RestPlan.java
package com.ljs.ifootballmanager.ai.selection; import com.google.common.base.Function; import com.google.common.collect.Ordering; import com.ljs.ifootballmanager.ai.formation.Formation; import com.ljs.ifootballmanager.ai.player.Player; import com.ljs.ifootballmanager.ai.player.Squad; import com.ljs.ifootballmanager.ai.report.Report; import java.io.PrintWriter; import java.util.Optional; public final class RestPlan implements Report { private final Squad squad; private final Formation formation; private final Bench bench; private RestPlan(Squad s, Formation f, Bench b) { this.squad = s; this.formation = f; this.bench = b; } private Optional<Player> getPlayerToBeRested() { Player lowestFitness = Ordering.natural() .onResultOf((Player p) -> squad.findPlayer(p.getName()).getFitness()) .min(formation.players()); return squad.findPlayer(lowestFitness.getName()).isFullFitness() ? Optional.empty() : Optional.of(lowestFitness); } private Player getSubstituteFor(Player p) { return bench.findSubstitute(formation.findRole(p)); } public void print(PrintWriter w) { getPlayerToBeRested() .ifPresent( out -> { Player in = getSubstituteFor(out); w.format( "SUB %s %s %s IF SCORE <= 3%n", out.getName(), in.getName(), formation.findRole(out)); w.format( "SUB %s %s %s IF SCORE >= 3%n", out.getName(), in.getName(), formation.findRole(out)); }); } public void print(PrintWriter w, Function<Player, Integer> playerIdx) { getPlayerToBeRested() .ifPresent( out -> { Player in = getSubstituteFor(out); w.format( "SUB %s %s %s IF SCORE <= -3%n", playerIdx.apply(out), playerIdx.apply(in), formation.findRole(out)); w.format( "SUB %s %s %s IF SCORE >= 3%n", playerIdx.apply(out), playerIdx.apply(in), formation.findRole(out)); }); } public static RestPlan create(Squad s, Formation f, Bench b) { return new RestPlan(s, f, b); } }
Correct bug in reset plan
src/main/java/com/ljs/ifootballmanager/ai/selection/RestPlan.java
Correct bug in reset plan
<ide><path>rc/main/java/com/ljs/ifootballmanager/ai/selection/RestPlan.java <ide> out -> { <ide> Player in = getSubstituteFor(out); <ide> w.format( <del> "SUB %s %s %s IF SCORE <= 3%n", <add> "SUB %s %s %s IF SCORE <= -3%n", <ide> out.getName(), in.getName(), formation.findRole(out)); <ide> w.format( <ide> "SUB %s %s %s IF SCORE >= 3%n",
Java
epl-1.0
552d2b182ae798174179404a52686cfa5d2b8c8b
0
debrief/debrief,debrief/debrief,alastrina123/debrief,pecko/debrief,pecko/debrief,theanuradha/debrief,pecko/debrief,alastrina123/debrief,pecko/debrief,theanuradha/debrief,alastrina123/debrief,alastrina123/debrief,debrief/debrief,theanuradha/debrief,theanuradha/debrief,theanuradha/debrief,pecko/debrief,alastrina123/debrief,pecko/debrief,alastrina123/debrief,debrief/debrief,pecko/debrief,alastrina123/debrief,debrief/debrief,debrief/debrief,theanuradha/debrief,theanuradha/debrief
/** * */ package org.mwc.debrief.core.creators.shapes; import java.awt.Color; import Debrief.Wrappers.LabelWrapper; import MWC.GUI.*; import MWC.GUI.Shapes.PlainShape; import MWC.GenericData.*; /** * @author ian.mayo */ public class InsertLabel extends CoreInsertShape { /** get a plottable object * * @param centre * @param theChart * @return */ protected Plottable getPlottable(PlainChart theChart) { // right, what's the area we're looking at WorldArea wa = theChart.getDataArea(); // get centre of area (at zero depth) WorldLocation centre = wa.getCentreAtSurface(); // and now wrap the shape LabelWrapper theWrapper = new LabelWrapper("Blank label", centre, Color.red); return theWrapper; } @Override protected PlainShape getShape(WorldLocation centre) { // don't bother, we're not generating shapes this way... return null; } @Override protected String getShapeName() { // don't bother, we're not generating shapes this way... return null; } }
trunk/org.mwc.debrief.core/src/org/mwc/debrief/core/creators/shapes/InsertLabel.java
/** * */ package org.mwc.debrief.core.creators.shapes; import java.awt.Color; import org.mwc.cmap.core.CorePlugin; import org.mwc.cmap.core.operations.DebriefActionWrapper; import org.mwc.cmap.plotViewer.actions.CoreEditorAction; import Debrief.Tools.Palette.CreateLabel; import Debrief.Wrappers.LabelWrapper; import MWC.GUI.*; import MWC.GUI.Tools.Action; import MWC.GenericData.*; /** * @author ian.mayo */ public class InsertLabel extends CoreEditorAction { public static ToolParent _theParent = null; /** * ok, store who the parent is for the operation * * @param theParent */ public static void init(ToolParent theParent) { _theParent = theParent; } /** * and execute.. */ protected void execute() { final PlainChart theChart = getChart(); Action res = getData(theChart); // ok, now wrap the action DebriefActionWrapper daw = new DebriefActionWrapper(res); // and add it to our buffer (which will execute it anyway) CorePlugin.run(daw); // res.execute(); } public final Action getData(PlainChart theChart) { Action res = null; WorldArea wa = theChart.getDataArea(); // see if we have an area defined if (wa != null) { // get centre of area (at zero depth) WorldLocation centre = wa.getCentreAtSurface(); // and now wrap the shape LabelWrapper theWrapper = new LabelWrapper("Blank label", centre, Color.red); // lastly, get the data Layers theData = theChart.getLayers(); // aah, and the misc layer, in which we will store the shape Layer theLayer = theData.findLayer("Misc"); // did we find it? if (theLayer == null) { // nope, better create it. theLayer = new BaseLayer(); theLayer.setName("Misc"); theData.addThisLayer(theLayer); } // and put it into an action (so we can undo it) res = new CreateLabel.CreateLabelAction(null, theLayer, theWrapper, theChart.getLayers()); } else { // we haven't got an area, inform the user CorePlugin.showMessage("Create Feature", "Sorry, we can't create a label until the area is defined. Try adding a coastline first"); } return res; } }
Refactor, so that user can select target layer git-svn-id: d2601f1668e3cd2de409f5c059006a6eeada0abf@1439 cb33b658-6c9e-41a7-9690-cba343611204
trunk/org.mwc.debrief.core/src/org/mwc/debrief/core/creators/shapes/InsertLabel.java
Refactor, so that user can select target layer
<ide><path>runk/org.mwc.debrief.core/src/org/mwc/debrief/core/creators/shapes/InsertLabel.java <ide> <ide> import java.awt.Color; <ide> <del>import org.mwc.cmap.core.CorePlugin; <del>import org.mwc.cmap.core.operations.DebriefActionWrapper; <del>import org.mwc.cmap.plotViewer.actions.CoreEditorAction; <del> <del>import Debrief.Tools.Palette.CreateLabel; <ide> import Debrief.Wrappers.LabelWrapper; <ide> import MWC.GUI.*; <del>import MWC.GUI.Tools.Action; <add>import MWC.GUI.Shapes.PlainShape; <ide> import MWC.GenericData.*; <ide> <ide> /** <ide> * @author ian.mayo <ide> */ <del>public class InsertLabel extends CoreEditorAction <add>public class InsertLabel extends CoreInsertShape <ide> { <del> public static ToolParent _theParent = null; <ide> <del> /** <del> * ok, store who the parent is for the operation <add> /** get a plottable object <ide> * <del> * @param theParent <add> * @param centre <add> * @param theChart <add> * @return <ide> */ <del> public static void init(ToolParent theParent) <add> protected Plottable getPlottable(PlainChart theChart) <ide> { <del> _theParent = theParent; <del> } <add> <add> // right, what's the area we're looking at <add> WorldArea wa = theChart.getDataArea(); <add> <add> // get centre of area (at zero depth) <add> WorldLocation centre = wa.getCentreAtSurface(); <ide> <del> /** <del> * and execute.. <del> */ <del> protected void execute() <del> { <del> final PlainChart theChart = getChart(); <del> <del> Action res = getData(theChart); <add> // and now wrap the shape <add> LabelWrapper theWrapper = new LabelWrapper("Blank label", centre, <add> Color.red); <ide> <del> // ok, now wrap the action <del> DebriefActionWrapper daw = new DebriefActionWrapper(res); <del> <del> // and add it to our buffer (which will execute it anyway) <del> CorePlugin.run(daw); <del> <del> // res.execute(); <del> <del> <add> return theWrapper; <ide> <ide> } <ide> <del> public final Action getData(PlainChart theChart) <add> @Override <add> protected PlainShape getShape(WorldLocation centre) <ide> { <del> Action res = null; <del> WorldArea wa = theChart.getDataArea(); <del> <del> // see if we have an area defined <del> if (wa != null) <del> { <del> <del> // get centre of area (at zero depth) <del> WorldLocation centre = wa.getCentreAtSurface(); <del> <del> // and now wrap the shape <del> LabelWrapper theWrapper = new LabelWrapper("Blank label", centre, <del> Color.red); <del> <del> // lastly, get the data <del> Layers theData = theChart.getLayers(); <del> <del> // aah, and the misc layer, in which we will store the shape <del> Layer theLayer = theData.findLayer("Misc"); <del> <del> // did we find it? <del> if (theLayer == null) <del> { <del> // nope, better create it. <del> theLayer = new BaseLayer(); <del> theLayer.setName("Misc"); <del> theData.addThisLayer(theLayer); <del> } <del> <del> // and put it into an action (so we can undo it) <del> res = new CreateLabel.CreateLabelAction(null, theLayer, theWrapper, <del> theChart.getLayers()); <del> } <del> else <del> { <del> // we haven't got an area, inform the user <del> CorePlugin.showMessage("Create Feature", <del> "Sorry, we can't create a label until the area is defined. Try adding a coastline first"); <del> } <del> <del> return res; <add> // don't bother, we're not generating shapes this way... <add> return null; <ide> } <ide> <add> @Override <add> protected String getShapeName() <add> { <add> // don't bother, we're not generating shapes this way... <add> return null; <add> } <ide> }
Java
apache-2.0
b453df53d107d981ff7da9cc513849dbd3975459
0
treasure-data/td-jdbc
package com.treasure_data.jdbc; import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.net.URL; import java.sql.Array; import java.sql.Blob; import java.sql.Clob; import java.sql.Date; import java.sql.NClob; import java.sql.Ref; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.RowId; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.SQLXML; import java.sql.Statement; import java.sql.Time; import java.sql.Timestamp; import java.util.Calendar; import java.util.List; import java.util.Map; import org.msgpack.type.BooleanValue; import org.msgpack.type.NumberValue; import org.msgpack.type.Value; /** * Data independed base class which implements the common part of all * resultsets. */ public abstract class TDResultSetBase implements ResultSet { protected SQLWarning warningChain = null; protected boolean wasNull = false; protected List<Object> row; protected List<String> columnNames; protected List<String> columnTypes; public boolean absolute(int row) throws SQLException { throw new SQLException("Method not supported"); } public void afterLast() throws SQLException { throw new SQLException("Method not supported"); } public void beforeFirst() throws SQLException { throw new SQLException("Method not supported"); } public void cancelRowUpdates() throws SQLException { throw new SQLException("Method not supported"); } public void deleteRow() throws SQLException { throw new SQLException("Method not supported"); } public int findColumn(String columnName) throws SQLException { int columnIndex = columnNames.indexOf(columnName); if (columnIndex == -1) { throw new SQLException(); } else { return ++columnIndex; } } public boolean first() throws SQLException { throw new SQLException("Method not supported"); } public Array getArray(int i) throws SQLException { throw new SQLException("Method not supported"); } public Array getArray(String colName) throws SQLException { throw new SQLException("Method not supported"); } public InputStream getAsciiStream(int columnIndex) throws SQLException { throw new SQLException("Method not supported"); } public InputStream getAsciiStream(String columnName) throws SQLException { throw new SQLException("Method not supported"); } public BigDecimal getBigDecimal(int columnIndex) throws SQLException { throw new SQLException("Method not supported"); } public BigDecimal getBigDecimal(String columnName) throws SQLException { throw new SQLException("Method not supported"); } public BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException { throw new SQLException("Method not supported"); } public BigDecimal getBigDecimal(String columnName, int scale) throws SQLException { throw new SQLException("Method not supported"); } public InputStream getBinaryStream(int columnIndex) throws SQLException { throw new SQLException("Method not supported"); } public InputStream getBinaryStream(String columnName) throws SQLException { throw new SQLException("Method not supported"); } public Blob getBlob(int i) throws SQLException { throw new SQLException("Method not supported"); } public Blob getBlob(String colName) throws SQLException { throw new SQLException("Method not supported"); } public boolean getBoolean(int index) throws SQLException { try { Object obj = getObject(index); return obj == null ? false : ((BooleanValue) obj).getBoolean(); } catch (Exception e) { String msg = String.format( "Cannot convert column %d to boolean: %s", index, e.toString()); throw new SQLException(msg); } } public boolean getBoolean(String name) throws SQLException { return getBoolean(findColumn(name)); } public byte getByte(int index) throws SQLException { try { Object obj = getObject(index); return obj == null ? 0 : ((NumberValue) obj).byteValue(); } catch (Exception e) { String msg = String.format( "Cannot convert column %d to byte: %s", index, e.toString()); throw new SQLException(msg); } } public byte getByte(String name) throws SQLException { return getByte(findColumn(name)); } public byte[] getBytes(int columnIndex) throws SQLException { throw new SQLException("Method not supported"); // TODO } public byte[] getBytes(String columnName) throws SQLException { throw new SQLException("Method not supported"); // TODO } public Reader getCharacterStream(int columnIndex) throws SQLException { throw new SQLException("Method not supported"); } public Reader getCharacterStream(String columnName) throws SQLException { throw new SQLException("Method not supported"); } public Clob getClob(int i) throws SQLException { throw new SQLException("Method not supported"); } public Clob getClob(String colName) throws SQLException { throw new SQLException("Method not supported"); } public int getConcurrency() throws SQLException { return ResultSet.CONCUR_READ_ONLY; } public String getCursorName() throws SQLException { throw new SQLException("Method not supported"); } public Date getDate(int index) throws SQLException { // TODO Object obj = getObject(index); if (obj == null) { return null; } try { Value v = (Value) obj; return Date.valueOf(v.asRawValue().getString()); } catch (Exception e) { String msg = String.format( "Cannot convert column %d to date: %s", index, e.toString()); throw new SQLException(msg); } } public Date getDate(String columnName) throws SQLException { // TODO return getDate(findColumn(columnName)); } public Date getDate(int columnIndex, Calendar cal) throws SQLException { // TODO throw new SQLException("Method not supported"); } public Date getDate(String columnName, Calendar cal) throws SQLException { // TODO throw new SQLException("Method not supported"); } public double getDouble(int index) throws SQLException { try { Object obj = getObject(index); return obj == null ? 0.0 : ((NumberValue) obj).doubleValue(); } catch (Exception e) { String msg = String.format( "Cannot convert column %d to double: %s", index, e.toString()); throw new SQLException(msg); } } public double getDouble(String name) throws SQLException { return getDouble(findColumn(name)); } public int getFetchDirection() throws SQLException { return ResultSet.FETCH_FORWARD; } public int getFetchSize() throws SQLException { throw new SQLException("Method not supported"); } public float getFloat(int index) throws SQLException { try { Object obj = getObject(index); return obj == null ? (float) 0.0 : ((NumberValue) obj).floatValue(); } catch (Exception e) { String msg = String.format( "Cannot convert column %d to float: %s", index, e.toString()); throw new SQLException(msg); } } public float getFloat(String name) throws SQLException { return getFloat(findColumn(name)); } public int getHoldability() throws SQLException { throw new SQLException("Method not supported"); } public int getInt(int index) throws SQLException { try { Object obj = getObject(index); return obj == null ? 0 : ((NumberValue) obj).intValue(); } catch (Exception e) { String msg = String.format( "Cannot convert column %d to integer: %s", index, e.toString()); throw new SQLException(msg); } } public int getInt(String name) throws SQLException { return getInt(findColumn(name)); } public long getLong(int index) throws SQLException { try { Object obj = getObject(index); return obj == null ? 0 : ((NumberValue) obj).longValue(); } catch (Exception e) { String msg = String.format( "Cannot convert column %d to long", index); throw new SQLException(msg); } } public long getLong(String name) throws SQLException { return getLong(findColumn(name)); } public ResultSetMetaData getMetaData() throws SQLException { return new TDResultSetMetaData(columnNames, columnTypes); } public Reader getNCharacterStream(int arg0) throws SQLException { throw new SQLException("Method not supported"); } public Reader getNCharacterStream(String arg0) throws SQLException { throw new SQLException("Method not supported"); } public NClob getNClob(int arg0) throws SQLException { throw new SQLException("Method not supported"); } public NClob getNClob(String columnLabel) throws SQLException { throw new SQLException("Method not supported"); } public String getNString(int columnIndex) throws SQLException { throw new SQLException("Method not supported"); } public String getNString(String columnLabel) throws SQLException { throw new SQLException("Method not supported"); } public Object getObject(int columnIndex) throws SQLException { if (row == null) { throw new SQLException("No row found."); } if (columnIndex > row.size()) { throw new SQLException("Invalid columnIndex: " + columnIndex); } try { wasNull = false; if (row.get(columnIndex - 1) == null) { wasNull = true; } return row.get(columnIndex - 1); } catch (Exception e) { throw new SQLException(e.toString()); } } public Object getObject(String columnName) throws SQLException { return getObject(findColumn(columnName)); } public Object getObject(int i, Map<String, Class<?>> map) throws SQLException { throw new SQLException("Method not supported"); } public Object getObject(String colName, Map<String, Class<?>> map) throws SQLException { throw new SQLException("Method not supported"); } public Ref getRef(int i) throws SQLException { throw new SQLException("Method not supported"); } public Ref getRef(String colName) throws SQLException { throw new SQLException("Method not supported"); } public int getRow() throws SQLException { throw new SQLException("Method not supported"); } public RowId getRowId(int columnIndex) throws SQLException { throw new SQLException("Method not supported"); } public RowId getRowId(String columnLabel) throws SQLException { throw new SQLException("Method not supported"); } public SQLXML getSQLXML(int columnIndex) throws SQLException { throw new SQLException("Method not supported"); } public SQLXML getSQLXML(String columnLabel) throws SQLException { throw new SQLException("Method not supported"); } public short getShort(int index) throws SQLException { try { Object obj = getObject(index); return obj == null ? 0 : ((NumberValue) obj).shortValue(); } catch (Exception e) { String msg = String.format( "Cannot convert column %d to short: %s", index, e.toString()); throw new SQLException(msg); } } public short getShort(String name) throws SQLException { return getShort(findColumn(name)); } public Statement getStatement() throws SQLException { throw new SQLException("Method not supported"); } /** * @param index * - the first column is 1, the second is 2, ... * @see java.sql.ResultSet#getString(int) */ public String getString(int index) throws SQLException { // Column index starts from 1, not 0. Object obj = getObject(index); if (obj == null) { return null; } try { Value v = (Value) obj; return v.asRawValue().getString(); } catch (Exception e) { String msg = String.format("Cannot convert column %d to string: %s", index, e.toString()); throw new SQLException(msg); } } public String getString(String name) throws SQLException { return getString(findColumn(name)); } public Time getTime(int columnIndex) throws SQLException { throw new SQLException("Method not supported"); } public Time getTime(String columnName) throws SQLException { throw new SQLException("Method not supported"); } public Time getTime(int columnIndex, Calendar cal) throws SQLException { throw new SQLException("Method not supported"); } public Time getTime(String columnName, Calendar cal) throws SQLException { throw new SQLException("Method not supported"); } public Timestamp getTimestamp(int columnIndex) throws SQLException { throw new SQLException("Method not supported"); } public Timestamp getTimestamp(String columnName) throws SQLException { throw new SQLException("Method not supported"); } public Timestamp getTimestamp(int columnIndex, Calendar cal) throws SQLException { throw new SQLException("Method not supported"); } public Timestamp getTimestamp(String columnName, Calendar cal) throws SQLException { throw new SQLException("Method not supported"); } public int getType() throws SQLException { return ResultSet.TYPE_FORWARD_ONLY; } public URL getURL(int columnIndex) throws SQLException { throw new SQLException("Method not supported"); } public URL getURL(String columnName) throws SQLException { throw new SQLException("Method not supported"); } public InputStream getUnicodeStream(int columnIndex) throws SQLException { throw new SQLException("Method not supported"); } public InputStream getUnicodeStream(String columnName) throws SQLException { throw new SQLException("Method not supported"); } public void insertRow() throws SQLException { throw new SQLException("Method not supported"); } public boolean isAfterLast() throws SQLException { throw new SQLException("Method not supported"); } public boolean isBeforeFirst() throws SQLException { throw new SQLException("Method not supported"); } public boolean isClosed() throws SQLException { throw new SQLException("Method not supported"); } public boolean isFirst() throws SQLException { throw new SQLException("Method not supported"); } public boolean isLast() throws SQLException { throw new SQLException("Method not supported"); } public boolean last() throws SQLException { throw new SQLException("Method not supported"); } public void moveToCurrentRow() throws SQLException { throw new SQLException("Method not supported"); } public void moveToInsertRow() throws SQLException { throw new SQLException("Method not supported"); } public boolean previous() throws SQLException { throw new SQLException("Method not supported"); } public void refreshRow() throws SQLException { throw new SQLException("Method not supported"); } public boolean relative(int rows) throws SQLException { throw new SQLException("Method not supported"); } public boolean rowDeleted() throws SQLException { throw new SQLException("Method not supported"); } public boolean rowInserted() throws SQLException { throw new SQLException("Method not supported"); } public boolean rowUpdated() throws SQLException { throw new SQLException("Method not supported"); } public void setFetchDirection(int direction) throws SQLException { throw new SQLException("Method not supported"); } public void setFetchSize(int rows) throws SQLException { throw new SQLException("Method not supported"); } public void updateArray(int columnIndex, Array x) throws SQLException { throw new SQLException("Method not supported"); } public void updateArray(String columnName, Array x) throws SQLException { throw new SQLException("Method not supported"); } public void updateAsciiStream(int columnIndex, InputStream x) throws SQLException { throw new SQLException("Method not supported"); } public void updateAsciiStream(String columnLabel, InputStream x) throws SQLException { throw new SQLException("Method not supported"); } public void updateAsciiStream(int columnIndex, InputStream x, int length) throws SQLException { throw new SQLException("Method not supported"); } public void updateAsciiStream(String columnName, InputStream x, int length) throws SQLException { throw new SQLException("Method not supported"); } public void updateAsciiStream(int columnIndex, InputStream x, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateAsciiStream(String columnLabel, InputStream x, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateBigDecimal(int columnIndex, BigDecimal x) throws SQLException { throw new SQLException("Method not supported"); } public void updateBigDecimal(String columnName, BigDecimal x) throws SQLException { throw new SQLException("Method not supported"); } public void updateBinaryStream(int columnIndex, InputStream x) throws SQLException { throw new SQLException("Method not supported"); } public void updateBinaryStream(String columnLabel, InputStream x) throws SQLException { throw new SQLException("Method not supported"); } public void updateBinaryStream(int columnIndex, InputStream x, int length) throws SQLException { throw new SQLException("Method not supported"); } public void updateBinaryStream(String columnName, InputStream x, int length) throws SQLException { throw new SQLException("Method not supported"); } public void updateBinaryStream(int columnIndex, InputStream x, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateBinaryStream(String columnLabel, InputStream x, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateBlob(int columnIndex, Blob x) throws SQLException { throw new SQLException("Method not supported"); } public void updateBlob(String columnName, Blob x) throws SQLException { throw new SQLException("Method not supported"); } public void updateBlob(int columnIndex, InputStream inputStream) throws SQLException { throw new SQLException("Method not supported"); } public void updateBlob(String columnLabel, InputStream inputStream) throws SQLException { throw new SQLException("Method not supported"); } public void updateBlob(int columnIndex, InputStream inputStream, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateBlob(String columnLabel, InputStream inputStream, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateBoolean(int columnIndex, boolean x) throws SQLException { throw new SQLException("Method not supported"); } public void updateBoolean(String columnName, boolean x) throws SQLException { throw new SQLException("Method not supported"); } public void updateByte(int columnIndex, byte x) throws SQLException { throw new SQLException("Method not supported"); } public void updateByte(String columnName, byte x) throws SQLException { throw new SQLException("Method not supported"); } public void updateBytes(int columnIndex, byte[] x) throws SQLException { throw new SQLException("Method not supported"); } public void updateBytes(String columnName, byte[] x) throws SQLException { throw new SQLException("Method not supported"); } public void updateCharacterStream(int columnIndex, Reader x) throws SQLException { throw new SQLException("Method not supported"); } public void updateCharacterStream(String columnLabel, Reader reader) throws SQLException { throw new SQLException("Method not supported"); } public void updateCharacterStream(int columnIndex, Reader x, int length) throws SQLException { throw new SQLException("Method not supported"); } public void updateCharacterStream(String columnName, Reader reader, int length) throws SQLException { throw new SQLException("Method not supported"); } public void updateCharacterStream(int columnIndex, Reader x, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateCharacterStream(String columnLabel, Reader reader, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateClob(int columnIndex, Clob x) throws SQLException { throw new SQLException("Method not supported"); } public void updateClob(String columnName, Clob x) throws SQLException { throw new SQLException("Method not supported"); } public void updateClob(int columnIndex, Reader reader) throws SQLException { throw new SQLException("Method not supported"); } public void updateClob(String columnLabel, Reader reader) throws SQLException { throw new SQLException("Method not supported"); } public void updateClob(int columnIndex, Reader reader, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateClob(String columnLabel, Reader reader, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateDate(int columnIndex, Date x) throws SQLException { throw new SQLException("Method not supported"); } public void updateDate(String columnName, Date x) throws SQLException { throw new SQLException("Method not supported"); } public void updateDouble(int columnIndex, double x) throws SQLException { throw new SQLException("Method not supported"); } public void updateDouble(String columnName, double x) throws SQLException { throw new SQLException("Method not supported"); } public void updateFloat(int columnIndex, float x) throws SQLException { throw new SQLException("Method not supported"); } public void updateFloat(String columnName, float x) throws SQLException { throw new SQLException("Method not supported"); } public void updateInt(int columnIndex, int x) throws SQLException { throw new SQLException("Method not supported"); } public void updateInt(String columnName, int x) throws SQLException { throw new SQLException("Method not supported"); } public void updateLong(int columnIndex, long x) throws SQLException { throw new SQLException("Method not supported"); } public void updateLong(String columnName, long x) throws SQLException { throw new SQLException("Method not supported"); } public void updateNCharacterStream(int columnIndex, Reader x) throws SQLException { throw new SQLException("Method not supported"); } public void updateNCharacterStream(String columnLabel, Reader reader) throws SQLException { throw new SQLException("Method not supported"); } public void updateNCharacterStream(int columnIndex, Reader x, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateNCharacterStream(String columnLabel, Reader reader, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateNClob(int columnIndex, NClob clob) throws SQLException { throw new SQLException("Method not supported"); } public void updateNClob(String columnLabel, NClob clob) throws SQLException { throw new SQLException("Method not supported"); } public void updateNClob(int columnIndex, Reader reader) throws SQLException { throw new SQLException("Method not supported"); } public void updateNClob(String columnLabel, Reader reader) throws SQLException { throw new SQLException("Method not supported"); } public void updateNClob(int columnIndex, Reader reader, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateNClob(String columnLabel, Reader reader, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateNString(int columnIndex, String string) throws SQLException { throw new SQLException("Method not supported"); } public void updateNString(String columnLabel, String string) throws SQLException { throw new SQLException("Method not supported"); } public void updateNull(int columnIndex) throws SQLException { throw new SQLException("Method not supported"); } public void updateNull(String columnName) throws SQLException { throw new SQLException("Method not supported"); } public void updateObject(int columnIndex, Object x) throws SQLException { throw new SQLException("Method not supported"); } public void updateObject(String columnName, Object x) throws SQLException { throw new SQLException("Method not supported"); } public void updateObject(int columnIndex, Object x, int scale) throws SQLException { throw new SQLException("Method not supported"); } public void updateObject(String columnName, Object x, int scale) throws SQLException { throw new SQLException("Method not supported"); } public void updateRef(int columnIndex, Ref x) throws SQLException { throw new SQLException("Method not supported"); } public void updateRef(String columnName, Ref x) throws SQLException { throw new SQLException("Method not supported"); } public void updateRow() throws SQLException { throw new SQLException("Method not supported"); } public void updateRowId(int columnIndex, RowId x) throws SQLException { throw new SQLException("Method not supported"); } public void updateRowId(String columnLabel, RowId x) throws SQLException { throw new SQLException("Method not supported"); } public void updateSQLXML(int columnIndex, SQLXML xmlObject) throws SQLException { throw new SQLException("Method not supported"); } public void updateSQLXML(String columnLabel, SQLXML xmlObject) throws SQLException { throw new SQLException("Method not supported"); } public void updateShort(int columnIndex, short x) throws SQLException { throw new SQLException("Method not supported"); } public void updateShort(String columnName, short x) throws SQLException { throw new SQLException("Method not supported"); } public void updateString(int columnIndex, String x) throws SQLException { throw new SQLException("Method not supported"); } public void updateString(String columnName, String x) throws SQLException { throw new SQLException("Method not supported"); } public void updateTime(int columnIndex, Time x) throws SQLException { throw new SQLException("Method not supported"); } public void updateTime(String columnName, Time x) throws SQLException { throw new SQLException("Method not supported"); } public void updateTimestamp(int columnIndex, Timestamp x) throws SQLException { throw new SQLException("Method not supported"); } public void updateTimestamp(String columnName, Timestamp x) throws SQLException { throw new SQLException("Method not supported"); } public SQLWarning getWarnings() throws SQLException { return warningChain; } public void clearWarnings() throws SQLException { warningChain = null; } public void close() throws SQLException { throw new SQLException("Method not supported"); } public boolean wasNull() throws SQLException { return wasNull; } public boolean isWrapperFor(Class<?> iface) throws SQLException { throw new SQLException("Method not supported"); } public <T> T unwrap(Class<T> iface) throws SQLException { throw new SQLException("Method not supported"); } }
src/main/java/com/treasure_data/jdbc/TDResultSetBase.java
package com.treasure_data.jdbc; import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.net.URL; import java.sql.Array; import java.sql.Blob; import java.sql.Clob; import java.sql.Date; import java.sql.NClob; import java.sql.Ref; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.RowId; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.SQLXML; import java.sql.Statement; import java.sql.Time; import java.sql.Timestamp; import java.util.Calendar; import java.util.List; import java.util.Map; import org.msgpack.type.Value; /** * Data independed base class which implements the common part of all * resultsets. */ public abstract class TDResultSetBase implements ResultSet { protected SQLWarning warningChain = null; protected boolean wasNull = false; protected List<Object> row; protected List<String> columnNames; protected List<String> columnTypes; public boolean absolute(int row) throws SQLException { throw new SQLException("Method not supported"); } public void afterLast() throws SQLException { throw new SQLException("Method not supported"); } public void beforeFirst() throws SQLException { throw new SQLException("Method not supported"); } public void cancelRowUpdates() throws SQLException { throw new SQLException("Method not supported"); } public void deleteRow() throws SQLException { throw new SQLException("Method not supported"); } public int findColumn(String columnName) throws SQLException { int columnIndex = columnNames.indexOf(columnName); if (columnIndex == -1) { throw new SQLException(); } else { return ++columnIndex; } } public boolean first() throws SQLException { throw new SQLException("Method not supported"); } public Array getArray(int i) throws SQLException { throw new SQLException("Method not supported"); } public Array getArray(String colName) throws SQLException { throw new SQLException("Method not supported"); } public InputStream getAsciiStream(int columnIndex) throws SQLException { throw new SQLException("Method not supported"); } public InputStream getAsciiStream(String columnName) throws SQLException { throw new SQLException("Method not supported"); } public BigDecimal getBigDecimal(int columnIndex) throws SQLException { throw new SQLException("Method not supported"); } public BigDecimal getBigDecimal(String columnName) throws SQLException { throw new SQLException("Method not supported"); } public BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException { throw new SQLException("Method not supported"); } public BigDecimal getBigDecimal(String columnName, int scale) throws SQLException { throw new SQLException("Method not supported"); } public InputStream getBinaryStream(int columnIndex) throws SQLException { throw new SQLException("Method not supported"); } public InputStream getBinaryStream(String columnName) throws SQLException { throw new SQLException("Method not supported"); } public Blob getBlob(int i) throws SQLException { throw new SQLException("Method not supported"); } public Blob getBlob(String colName) throws SQLException { throw new SQLException("Method not supported"); } public boolean getBoolean(int columnIndex) throws SQLException { try { Object obj = getObject(columnIndex); Value v = (Value) obj; return v.asBooleanValue().getBoolean(); } catch (Exception e) { throw new SQLException("Cannot convert column " + columnIndex + " to boolean"); } } public boolean getBoolean(String columnName) throws SQLException { return getBoolean(findColumn(columnName)); } public byte getByte(int columnIndex) throws SQLException { try { Object obj = getObject(columnIndex); Value v = (Value) obj; return v.asIntegerValue().getByte(); } catch (Exception e) { throw new SQLException("Cannot convert column " + columnIndex + " to byte"); } } public byte getByte(String columnName) throws SQLException { return getByte(findColumn(columnName)); } public byte[] getBytes(int columnIndex) throws SQLException { throw new SQLException("Method not supported"); } public byte[] getBytes(String columnName) throws SQLException { throw new SQLException("Method not supported"); } public Reader getCharacterStream(int columnIndex) throws SQLException { throw new SQLException("Method not supported"); } public Reader getCharacterStream(String columnName) throws SQLException { throw new SQLException("Method not supported"); } public Clob getClob(int i) throws SQLException { throw new SQLException("Method not supported"); } public Clob getClob(String colName) throws SQLException { throw new SQLException("Method not supported"); } public int getConcurrency() throws SQLException { return ResultSet.CONCUR_READ_ONLY; } public String getCursorName() throws SQLException { throw new SQLException("Method not supported"); } public Date getDate(int columnIndex) throws SQLException { Object obj = getObject(columnIndex); if (obj == null) { return null; } try { Value v = (Value) obj; return Date.valueOf(v.asRawValue().getString()); } catch (Exception e) { throw new SQLException("Cannot convert column " + columnIndex + " to date: " + e.toString()); } } public Date getDate(String columnName) throws SQLException { return getDate(findColumn(columnName)); } public Date getDate(int columnIndex, Calendar cal) throws SQLException { throw new SQLException("Method not supported"); } public Date getDate(String columnName, Calendar cal) throws SQLException { throw new SQLException("Method not supported"); } public double getDouble(int columnIndex) throws SQLException { try { Object obj = getObject(columnIndex); Value v = (Value) obj; return v.asFloatValue().getDouble(); } catch (Exception e) { throw new SQLException("Cannot convert column " + columnIndex + " to double: " + e.toString()); } } public double getDouble(String columnName) throws SQLException { return getDouble(findColumn(columnName)); } public int getFetchDirection() throws SQLException { return ResultSet.FETCH_FORWARD; } public int getFetchSize() throws SQLException { throw new SQLException("Method not supported"); } public float getFloat(int columnIndex) throws SQLException { try { Object obj = getObject(columnIndex); Value v = (Value) obj; return v.asFloatValue().getFloat(); } catch (Exception e) { throw new SQLException("Cannot convert column " + columnIndex + " to float: " + e.toString()); } } public float getFloat(String columnName) throws SQLException { return getFloat(findColumn(columnName)); } public int getHoldability() throws SQLException { throw new SQLException("Method not supported"); } public int getInt(int columnIndex) throws SQLException { try { Object obj = getObject(columnIndex); Value v = (Value) obj; return v.asIntegerValue().getInt(); } catch (Exception e) { throw new SQLException("Cannot convert column " + columnIndex + " to integer " + e.toString()); } } public int getInt(String columnName) throws SQLException { return getInt(findColumn(columnName)); } public long getLong(int columnIndex) throws SQLException { try { Object obj = getObject(columnIndex); Value v = (Value) obj; return v.asIntegerValue().getLong(); } catch (Exception e) { throw new SQLException("Cannot convert column " + columnIndex + " to long: " + e.toString()); } } public long getLong(String columnName) throws SQLException { return getLong(findColumn(columnName)); } public ResultSetMetaData getMetaData() throws SQLException { return new TDResultSetMetaData(columnNames, columnTypes); } public Reader getNCharacterStream(int arg0) throws SQLException { throw new SQLException("Method not supported"); } public Reader getNCharacterStream(String arg0) throws SQLException { throw new SQLException("Method not supported"); } public NClob getNClob(int arg0) throws SQLException { throw new SQLException("Method not supported"); } public NClob getNClob(String columnLabel) throws SQLException { throw new SQLException("Method not supported"); } public String getNString(int columnIndex) throws SQLException { throw new SQLException("Method not supported"); } public String getNString(String columnLabel) throws SQLException { throw new SQLException("Method not supported"); } public Object getObject(int columnIndex) throws SQLException { if (row == null) { throw new SQLException("No row found."); } if (columnIndex > row.size()) { throw new SQLException("Invalid columnIndex: " + columnIndex); } try { wasNull = false; if (row.get(columnIndex - 1) == null) { wasNull = true; } return row.get(columnIndex - 1); } catch (Exception e) { throw new SQLException(e.toString()); } } public Object getObject(String columnName) throws SQLException { return getObject(findColumn(columnName)); } public Object getObject(int i, Map<String, Class<?>> map) throws SQLException { throw new SQLException("Method not supported"); } public Object getObject(String colName, Map<String, Class<?>> map) throws SQLException { throw new SQLException("Method not supported"); } public Ref getRef(int i) throws SQLException { throw new SQLException("Method not supported"); } public Ref getRef(String colName) throws SQLException { throw new SQLException("Method not supported"); } public int getRow() throws SQLException { throw new SQLException("Method not supported"); } public RowId getRowId(int columnIndex) throws SQLException { throw new SQLException("Method not supported"); } public RowId getRowId(String columnLabel) throws SQLException { throw new SQLException("Method not supported"); } public SQLXML getSQLXML(int columnIndex) throws SQLException { throw new SQLException("Method not supported"); } public SQLXML getSQLXML(String columnLabel) throws SQLException { throw new SQLException("Method not supported"); } public short getShort(int columnIndex) throws SQLException { try { Object obj = getObject(columnIndex); Value v = (Value) obj; return v.asIntegerValue().getShort(); } catch (Exception e) { throw new SQLException("Cannot convert column " + columnIndex + " to short: " + e.toString()); } } public short getShort(String columnName) throws SQLException { return getShort(findColumn(columnName)); } public Statement getStatement() throws SQLException { throw new SQLException("Method not supported"); } /** * @param columnIndex * - the first column is 1, the second is 2, ... * @see java.sql.ResultSet#getString(int) */ public String getString(int columnIndex) throws SQLException { // Column index starts from 1, not 0. Object obj = getObject(columnIndex); if (obj == null) { return null; } try { Value v = (Value) obj; return v.asRawValue().getString(); } catch (Exception e) { throw new SQLException("Cannot convert column " + columnIndex + " to string: " + e.toString()); } } public String getString(String columnName) throws SQLException { return getString(findColumn(columnName)); } public Time getTime(int columnIndex) throws SQLException { throw new SQLException("Method not supported"); } public Time getTime(String columnName) throws SQLException { throw new SQLException("Method not supported"); } public Time getTime(int columnIndex, Calendar cal) throws SQLException { throw new SQLException("Method not supported"); } public Time getTime(String columnName, Calendar cal) throws SQLException { throw new SQLException("Method not supported"); } public Timestamp getTimestamp(int columnIndex) throws SQLException { throw new SQLException("Method not supported"); } public Timestamp getTimestamp(String columnName) throws SQLException { throw new SQLException("Method not supported"); } public Timestamp getTimestamp(int columnIndex, Calendar cal) throws SQLException { throw new SQLException("Method not supported"); } public Timestamp getTimestamp(String columnName, Calendar cal) throws SQLException { throw new SQLException("Method not supported"); } public int getType() throws SQLException { return ResultSet.TYPE_FORWARD_ONLY; } public URL getURL(int columnIndex) throws SQLException { throw new SQLException("Method not supported"); } public URL getURL(String columnName) throws SQLException { throw new SQLException("Method not supported"); } public InputStream getUnicodeStream(int columnIndex) throws SQLException { throw new SQLException("Method not supported"); } public InputStream getUnicodeStream(String columnName) throws SQLException { throw new SQLException("Method not supported"); } public void insertRow() throws SQLException { throw new SQLException("Method not supported"); } public boolean isAfterLast() throws SQLException { throw new SQLException("Method not supported"); } public boolean isBeforeFirst() throws SQLException { throw new SQLException("Method not supported"); } public boolean isClosed() throws SQLException { throw new SQLException("Method not supported"); } public boolean isFirst() throws SQLException { throw new SQLException("Method not supported"); } public boolean isLast() throws SQLException { throw new SQLException("Method not supported"); } public boolean last() throws SQLException { throw new SQLException("Method not supported"); } public void moveToCurrentRow() throws SQLException { throw new SQLException("Method not supported"); } public void moveToInsertRow() throws SQLException { throw new SQLException("Method not supported"); } public boolean previous() throws SQLException { throw new SQLException("Method not supported"); } public void refreshRow() throws SQLException { throw new SQLException("Method not supported"); } public boolean relative(int rows) throws SQLException { throw new SQLException("Method not supported"); } public boolean rowDeleted() throws SQLException { throw new SQLException("Method not supported"); } public boolean rowInserted() throws SQLException { throw new SQLException("Method not supported"); } public boolean rowUpdated() throws SQLException { throw new SQLException("Method not supported"); } public void setFetchDirection(int direction) throws SQLException { throw new SQLException("Method not supported"); } public void setFetchSize(int rows) throws SQLException { throw new SQLException("Method not supported"); } public void updateArray(int columnIndex, Array x) throws SQLException { throw new SQLException("Method not supported"); } public void updateArray(String columnName, Array x) throws SQLException { throw new SQLException("Method not supported"); } public void updateAsciiStream(int columnIndex, InputStream x) throws SQLException { throw new SQLException("Method not supported"); } public void updateAsciiStream(String columnLabel, InputStream x) throws SQLException { throw new SQLException("Method not supported"); } public void updateAsciiStream(int columnIndex, InputStream x, int length) throws SQLException { throw new SQLException("Method not supported"); } public void updateAsciiStream(String columnName, InputStream x, int length) throws SQLException { throw new SQLException("Method not supported"); } public void updateAsciiStream(int columnIndex, InputStream x, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateAsciiStream(String columnLabel, InputStream x, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateBigDecimal(int columnIndex, BigDecimal x) throws SQLException { throw new SQLException("Method not supported"); } public void updateBigDecimal(String columnName, BigDecimal x) throws SQLException { throw new SQLException("Method not supported"); } public void updateBinaryStream(int columnIndex, InputStream x) throws SQLException { throw new SQLException("Method not supported"); } public void updateBinaryStream(String columnLabel, InputStream x) throws SQLException { throw new SQLException("Method not supported"); } public void updateBinaryStream(int columnIndex, InputStream x, int length) throws SQLException { throw new SQLException("Method not supported"); } public void updateBinaryStream(String columnName, InputStream x, int length) throws SQLException { throw new SQLException("Method not supported"); } public void updateBinaryStream(int columnIndex, InputStream x, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateBinaryStream(String columnLabel, InputStream x, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateBlob(int columnIndex, Blob x) throws SQLException { throw new SQLException("Method not supported"); } public void updateBlob(String columnName, Blob x) throws SQLException { throw new SQLException("Method not supported"); } public void updateBlob(int columnIndex, InputStream inputStream) throws SQLException { throw new SQLException("Method not supported"); } public void updateBlob(String columnLabel, InputStream inputStream) throws SQLException { throw new SQLException("Method not supported"); } public void updateBlob(int columnIndex, InputStream inputStream, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateBlob(String columnLabel, InputStream inputStream, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateBoolean(int columnIndex, boolean x) throws SQLException { throw new SQLException("Method not supported"); } public void updateBoolean(String columnName, boolean x) throws SQLException { throw new SQLException("Method not supported"); } public void updateByte(int columnIndex, byte x) throws SQLException { throw new SQLException("Method not supported"); } public void updateByte(String columnName, byte x) throws SQLException { throw new SQLException("Method not supported"); } public void updateBytes(int columnIndex, byte[] x) throws SQLException { throw new SQLException("Method not supported"); } public void updateBytes(String columnName, byte[] x) throws SQLException { throw new SQLException("Method not supported"); } public void updateCharacterStream(int columnIndex, Reader x) throws SQLException { throw new SQLException("Method not supported"); } public void updateCharacterStream(String columnLabel, Reader reader) throws SQLException { throw new SQLException("Method not supported"); } public void updateCharacterStream(int columnIndex, Reader x, int length) throws SQLException { throw new SQLException("Method not supported"); } public void updateCharacterStream(String columnName, Reader reader, int length) throws SQLException { throw new SQLException("Method not supported"); } public void updateCharacterStream(int columnIndex, Reader x, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateCharacterStream(String columnLabel, Reader reader, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateClob(int columnIndex, Clob x) throws SQLException { throw new SQLException("Method not supported"); } public void updateClob(String columnName, Clob x) throws SQLException { throw new SQLException("Method not supported"); } public void updateClob(int columnIndex, Reader reader) throws SQLException { throw new SQLException("Method not supported"); } public void updateClob(String columnLabel, Reader reader) throws SQLException { throw new SQLException("Method not supported"); } public void updateClob(int columnIndex, Reader reader, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateClob(String columnLabel, Reader reader, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateDate(int columnIndex, Date x) throws SQLException { throw new SQLException("Method not supported"); } public void updateDate(String columnName, Date x) throws SQLException { throw new SQLException("Method not supported"); } public void updateDouble(int columnIndex, double x) throws SQLException { throw new SQLException("Method not supported"); } public void updateDouble(String columnName, double x) throws SQLException { throw new SQLException("Method not supported"); } public void updateFloat(int columnIndex, float x) throws SQLException { throw new SQLException("Method not supported"); } public void updateFloat(String columnName, float x) throws SQLException { throw new SQLException("Method not supported"); } public void updateInt(int columnIndex, int x) throws SQLException { throw new SQLException("Method not supported"); } public void updateInt(String columnName, int x) throws SQLException { throw new SQLException("Method not supported"); } public void updateLong(int columnIndex, long x) throws SQLException { throw new SQLException("Method not supported"); } public void updateLong(String columnName, long x) throws SQLException { throw new SQLException("Method not supported"); } public void updateNCharacterStream(int columnIndex, Reader x) throws SQLException { throw new SQLException("Method not supported"); } public void updateNCharacterStream(String columnLabel, Reader reader) throws SQLException { throw new SQLException("Method not supported"); } public void updateNCharacterStream(int columnIndex, Reader x, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateNCharacterStream(String columnLabel, Reader reader, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateNClob(int columnIndex, NClob clob) throws SQLException { throw new SQLException("Method not supported"); } public void updateNClob(String columnLabel, NClob clob) throws SQLException { throw new SQLException("Method not supported"); } public void updateNClob(int columnIndex, Reader reader) throws SQLException { throw new SQLException("Method not supported"); } public void updateNClob(String columnLabel, Reader reader) throws SQLException { throw new SQLException("Method not supported"); } public void updateNClob(int columnIndex, Reader reader, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateNClob(String columnLabel, Reader reader, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateNString(int columnIndex, String string) throws SQLException { throw new SQLException("Method not supported"); } public void updateNString(String columnLabel, String string) throws SQLException { throw new SQLException("Method not supported"); } public void updateNull(int columnIndex) throws SQLException { throw new SQLException("Method not supported"); } public void updateNull(String columnName) throws SQLException { throw new SQLException("Method not supported"); } public void updateObject(int columnIndex, Object x) throws SQLException { throw new SQLException("Method not supported"); } public void updateObject(String columnName, Object x) throws SQLException { throw new SQLException("Method not supported"); } public void updateObject(int columnIndex, Object x, int scale) throws SQLException { throw new SQLException("Method not supported"); } public void updateObject(String columnName, Object x, int scale) throws SQLException { throw new SQLException("Method not supported"); } public void updateRef(int columnIndex, Ref x) throws SQLException { throw new SQLException("Method not supported"); } public void updateRef(String columnName, Ref x) throws SQLException { throw new SQLException("Method not supported"); } public void updateRow() throws SQLException { throw new SQLException("Method not supported"); } public void updateRowId(int columnIndex, RowId x) throws SQLException { throw new SQLException("Method not supported"); } public void updateRowId(String columnLabel, RowId x) throws SQLException { throw new SQLException("Method not supported"); } public void updateSQLXML(int columnIndex, SQLXML xmlObject) throws SQLException { throw new SQLException("Method not supported"); } public void updateSQLXML(String columnLabel, SQLXML xmlObject) throws SQLException { throw new SQLException("Method not supported"); } public void updateShort(int columnIndex, short x) throws SQLException { throw new SQLException("Method not supported"); } public void updateShort(String columnName, short x) throws SQLException { throw new SQLException("Method not supported"); } public void updateString(int columnIndex, String x) throws SQLException { throw new SQLException("Method not supported"); } public void updateString(String columnName, String x) throws SQLException { throw new SQLException("Method not supported"); } public void updateTime(int columnIndex, Time x) throws SQLException { throw new SQLException("Method not supported"); } public void updateTime(String columnName, Time x) throws SQLException { throw new SQLException("Method not supported"); } public void updateTimestamp(int columnIndex, Timestamp x) throws SQLException { throw new SQLException("Method not supported"); } public void updateTimestamp(String columnName, Timestamp x) throws SQLException { throw new SQLException("Method not supported"); } public SQLWarning getWarnings() throws SQLException { return warningChain; } public void clearWarnings() throws SQLException { warningChain = null; } public void close() throws SQLException { throw new SQLException("Method not supported"); } public boolean wasNull() throws SQLException { return wasNull; } public boolean isWrapperFor(Class<?> iface) throws SQLException { throw new SQLException("Method not supported"); } public <T> T unwrap(Class<T> iface) throws SQLException { throw new SQLException("Method not supported"); } }
fixed a bug: RJDBC doesn't work because MTM exception occurs
src/main/java/com/treasure_data/jdbc/TDResultSetBase.java
fixed a bug: RJDBC doesn't work because MTM exception occurs
<ide><path>rc/main/java/com/treasure_data/jdbc/TDResultSetBase.java <ide> import java.util.List; <ide> import java.util.Map; <ide> <add>import org.msgpack.type.BooleanValue; <add>import org.msgpack.type.NumberValue; <ide> import org.msgpack.type.Value; <ide> <ide> /** <ide> throw new SQLException("Method not supported"); <ide> } <ide> <del> public boolean getBoolean(int columnIndex) throws SQLException { <add> public boolean getBoolean(int index) throws SQLException { <ide> try { <del> Object obj = getObject(columnIndex); <del> Value v = (Value) obj; <del> return v.asBooleanValue().getBoolean(); <add> Object obj = getObject(index); <add> return obj == null ? false : <add> ((BooleanValue) obj).getBoolean(); <ide> } catch (Exception e) { <del> throw new SQLException("Cannot convert column " + columnIndex <del> + " to boolean"); <del> } <del> } <del> <del> public boolean getBoolean(String columnName) throws SQLException { <del> return getBoolean(findColumn(columnName)); <del> } <del> <del> public byte getByte(int columnIndex) throws SQLException { <add> String msg = String.format( <add> "Cannot convert column %d to boolean: %s", <add> index, e.toString()); <add> throw new SQLException(msg); <add> } <add> } <add> <add> public boolean getBoolean(String name) throws SQLException { <add> return getBoolean(findColumn(name)); <add> } <add> <add> public byte getByte(int index) throws SQLException { <ide> try { <del> Object obj = getObject(columnIndex); <del> Value v = (Value) obj; <del> return v.asIntegerValue().getByte(); <add> Object obj = getObject(index); <add> return obj == null ? 0 : <add> ((NumberValue) obj).byteValue(); <ide> } catch (Exception e) { <del> throw new SQLException("Cannot convert column " + columnIndex <del> + " to byte"); <del> } <del> } <del> <del> public byte getByte(String columnName) throws SQLException { <del> return getByte(findColumn(columnName)); <add> String msg = String.format( <add> "Cannot convert column %d to byte: %s", <add> index, e.toString()); <add> throw new SQLException(msg); <add> } <add> } <add> <add> public byte getByte(String name) throws SQLException { <add> return getByte(findColumn(name)); <ide> } <ide> <ide> public byte[] getBytes(int columnIndex) throws SQLException { <del> throw new SQLException("Method not supported"); <add> throw new SQLException("Method not supported"); // TODO <ide> } <ide> <ide> public byte[] getBytes(String columnName) throws SQLException { <del> throw new SQLException("Method not supported"); <add> throw new SQLException("Method not supported"); // TODO <ide> } <ide> <ide> public Reader getCharacterStream(int columnIndex) throws SQLException { <ide> throw new SQLException("Method not supported"); <ide> } <ide> <del> public Date getDate(int columnIndex) throws SQLException { <del> Object obj = getObject(columnIndex); <add> public Date getDate(int index) throws SQLException { // TODO <add> Object obj = getObject(index); <ide> if (obj == null) { <ide> return null; <ide> } <ide> Value v = (Value) obj; <ide> return Date.valueOf(v.asRawValue().getString()); <ide> } catch (Exception e) { <del> throw new SQLException("Cannot convert column " + columnIndex <del> + " to date: " + e.toString()); <del> } <del> } <del> <del> public Date getDate(String columnName) throws SQLException { <add> String msg = String.format( <add> "Cannot convert column %d to date: %s", <add> index, e.toString()); <add> throw new SQLException(msg); <add> } <add> } <add> <add> public Date getDate(String columnName) throws SQLException { // TODO <ide> return getDate(findColumn(columnName)); <ide> } <ide> <del> public Date getDate(int columnIndex, Calendar cal) throws SQLException { <del> throw new SQLException("Method not supported"); <del> } <del> <del> public Date getDate(String columnName, Calendar cal) throws SQLException { <del> throw new SQLException("Method not supported"); <del> } <del> <del> public double getDouble(int columnIndex) throws SQLException { <add> public Date getDate(int columnIndex, Calendar cal) <add> throws SQLException { // TODO <add> throw new SQLException("Method not supported"); <add> } <add> <add> public Date getDate(String columnName, Calendar cal) <add> throws SQLException { // TODO <add> throw new SQLException("Method not supported"); <add> } <add> <add> public double getDouble(int index) throws SQLException { <ide> try { <del> Object obj = getObject(columnIndex); <del> Value v = (Value) obj; <del> return v.asFloatValue().getDouble(); <add> Object obj = getObject(index); <add> return obj == null ? 0.0 : <add> ((NumberValue) obj).doubleValue(); <ide> } catch (Exception e) { <del> throw new SQLException("Cannot convert column " + columnIndex <del> + " to double: " + e.toString()); <del> } <del> } <del> <del> public double getDouble(String columnName) throws SQLException { <del> return getDouble(findColumn(columnName)); <add> String msg = String.format( <add> "Cannot convert column %d to double: %s", <add> index, e.toString()); <add> throw new SQLException(msg); <add> } <add> } <add> <add> public double getDouble(String name) throws SQLException { <add> return getDouble(findColumn(name)); <ide> } <ide> <ide> public int getFetchDirection() throws SQLException { <ide> throw new SQLException("Method not supported"); <ide> } <ide> <del> public float getFloat(int columnIndex) throws SQLException { <add> public float getFloat(int index) throws SQLException { <ide> try { <del> Object obj = getObject(columnIndex); <del> Value v = (Value) obj; <del> return v.asFloatValue().getFloat(); <add> Object obj = getObject(index); <add> return obj == null ? (float) 0.0 : <add> ((NumberValue) obj).floatValue(); <ide> } catch (Exception e) { <del> throw new SQLException("Cannot convert column " + columnIndex <del> + " to float: " + e.toString()); <del> } <del> } <del> <del> public float getFloat(String columnName) throws SQLException { <del> return getFloat(findColumn(columnName)); <add> String msg = String.format( <add> "Cannot convert column %d to float: %s", <add> index, e.toString()); <add> throw new SQLException(msg); <add> } <add> } <add> <add> public float getFloat(String name) throws SQLException { <add> return getFloat(findColumn(name)); <ide> } <ide> <ide> public int getHoldability() throws SQLException { <ide> throw new SQLException("Method not supported"); <ide> } <ide> <del> public int getInt(int columnIndex) throws SQLException { <add> public int getInt(int index) throws SQLException { <ide> try { <del> Object obj = getObject(columnIndex); <del> Value v = (Value) obj; <del> return v.asIntegerValue().getInt(); <add> Object obj = getObject(index); <add> return obj == null ? 0 : <add> ((NumberValue) obj).intValue(); <ide> } catch (Exception e) { <del> throw new SQLException("Cannot convert column " + columnIndex <del> + " to integer " + e.toString()); <del> } <del> } <del> <del> public int getInt(String columnName) throws SQLException { <del> return getInt(findColumn(columnName)); <del> } <del> <del> public long getLong(int columnIndex) throws SQLException { <add> String msg = String.format( <add> "Cannot convert column %d to integer: %s", <add> index, e.toString()); <add> throw new SQLException(msg); <add> } <add> } <add> <add> public int getInt(String name) throws SQLException { <add> return getInt(findColumn(name)); <add> } <add> <add> public long getLong(int index) throws SQLException { <ide> try { <del> Object obj = getObject(columnIndex); <del> Value v = (Value) obj; <del> return v.asIntegerValue().getLong(); <add> Object obj = getObject(index); <add> return obj == null ? 0 : <add> ((NumberValue) obj).longValue(); <ide> } catch (Exception e) { <del> throw new SQLException("Cannot convert column " + columnIndex <del> + " to long: " + e.toString()); <del> } <del> } <del> <del> public long getLong(String columnName) throws SQLException { <del> return getLong(findColumn(columnName)); <add> String msg = String.format( <add> "Cannot convert column %d to long", index); <add> throw new SQLException(msg); <add> } <add> } <add> <add> public long getLong(String name) throws SQLException { <add> return getLong(findColumn(name)); <ide> } <ide> <ide> public ResultSetMetaData getMetaData() throws SQLException { <ide> throw new SQLException("Method not supported"); <ide> } <ide> <del> public short getShort(int columnIndex) throws SQLException { <add> public short getShort(int index) throws SQLException { <ide> try { <del> Object obj = getObject(columnIndex); <del> Value v = (Value) obj; <del> return v.asIntegerValue().getShort(); <add> Object obj = getObject(index); <add> return obj == null ? 0 : <add> ((NumberValue) obj).shortValue(); <ide> } catch (Exception e) { <del> throw new SQLException("Cannot convert column " + columnIndex <del> + " to short: " + e.toString()); <del> } <del> } <del> <del> public short getShort(String columnName) throws SQLException { <del> return getShort(findColumn(columnName)); <add> String msg = String.format( <add> "Cannot convert column %d to short: %s", <add> index, e.toString()); <add> throw new SQLException(msg); <add> } <add> } <add> <add> public short getShort(String name) throws SQLException { <add> return getShort(findColumn(name)); <ide> } <ide> <ide> public Statement getStatement() throws SQLException { <ide> } <ide> <ide> /** <del> * @param columnIndex <add> * @param index <ide> * - the first column is 1, the second is 2, ... <ide> * @see java.sql.ResultSet#getString(int) <ide> */ <ide> <del> public String getString(int columnIndex) throws SQLException { <add> public String getString(int index) throws SQLException { <ide> // Column index starts from 1, not 0. <del> Object obj = getObject(columnIndex); <add> Object obj = getObject(index); <ide> if (obj == null) { <ide> return null; <ide> } <ide> Value v = (Value) obj; <ide> return v.asRawValue().getString(); <ide> } catch (Exception e) { <del> throw new SQLException("Cannot convert column " + columnIndex <del> + " to string: " + e.toString()); <del> } <del> } <del> <del> public String getString(String columnName) throws SQLException { <del> return getString(findColumn(columnName)); <add> String msg = String.format("Cannot convert column %d to string: %s", <add> index, e.toString()); <add> throw new SQLException(msg); <add> } <add> } <add> <add> public String getString(String name) throws SQLException { <add> return getString(findColumn(name)); <ide> } <ide> <ide> public Time getTime(int columnIndex) throws SQLException {
Java
apache-2.0
fc3eefad503a2cca4796703ff7debf9d2055682b
0
sankarh/hive,b-slim/hive,sankarh/hive,alanfgates/hive,b-slim/hive,nishantmonu51/hive,lirui-apache/hive,anishek/hive,anishek/hive,alanfgates/hive,b-slim/hive,sankarh/hive,b-slim/hive,anishek/hive,b-slim/hive,jcamachor/hive,nishantmonu51/hive,nishantmonu51/hive,jcamachor/hive,nishantmonu51/hive,sankarh/hive,vineetgarg02/hive,jcamachor/hive,b-slim/hive,nishantmonu51/hive,jcamachor/hive,lirui-apache/hive,lirui-apache/hive,nishantmonu51/hive,jcamachor/hive,anishek/hive,b-slim/hive,jcamachor/hive,sankarh/hive,vineetgarg02/hive,lirui-apache/hive,anishek/hive,vineetgarg02/hive,nishantmonu51/hive,lirui-apache/hive,vineetgarg02/hive,anishek/hive,nishantmonu51/hive,vineetgarg02/hive,alanfgates/hive,sankarh/hive,lirui-apache/hive,b-slim/hive,nishantmonu51/hive,vineetgarg02/hive,sankarh/hive,alanfgates/hive,alanfgates/hive,jcamachor/hive,alanfgates/hive,alanfgates/hive,jcamachor/hive,sankarh/hive,lirui-apache/hive,anishek/hive,sankarh/hive,anishek/hive,anishek/hive,vineetgarg02/hive,lirui-apache/hive,jcamachor/hive,lirui-apache/hive,alanfgates/hive,b-slim/hive,vineetgarg02/hive,alanfgates/hive,vineetgarg02/hive
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.ql.stats.fs; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import com.google.common.util.concurrent.ThreadFactoryBuilder; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.PathFilter; import org.apache.hadoop.hive.common.StatsSetupConst; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.ql.exec.SerializationUtilities; import org.apache.hadoop.hive.ql.exec.Utilities; import org.apache.hadoop.hive.ql.stats.StatsAggregator; import org.apache.hadoop.hive.ql.stats.StatsCollectionContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.Input; public class FSStatsAggregator implements StatsAggregator { private final Logger LOG = LoggerFactory.getLogger(this.getClass().getName()); private List<Map<String,Map<String,String>>> statsList; private FileSystem fs; @Override public boolean connect(StatsCollectionContext scc) { List<String> statsDirs = scc.getStatsTmpDirs(); assert statsDirs.size() == 1 : "Found multiple stats dirs: " + statsDirs; Path statsDir = new Path(statsDirs.get(0)); Utilities.FILE_OP_LOGGER.trace("About to read stats from {}", statsDir); int poolSize = HiveConf.getIntVar(scc.getHiveConf(), HiveConf.ConfVars.HIVE_MOVE_FILES_THREAD_COUNT); // In case thread count is set to 0, use single thread. poolSize = Math.max(poolSize, 1); final ExecutorService pool = Executors.newFixedThreadPool(poolSize, new ThreadFactoryBuilder().setDaemon(true) .setNameFormat("stats-updater-thread-%d") .build());; final List<Future<Map<String, Map<String,String>>>> futureList = new LinkedList<>(); try { fs = statsDir.getFileSystem(scc.getHiveConf()); statsList = new ArrayList<>(); FileStatus[] status = fs.listStatus(statsDir, new PathFilter() { @Override public boolean accept(Path file) { return file.getName().startsWith(StatsSetupConst.STATS_FILE_PREFIX); } }); Map<String, Map<String,String>> statsMap = new HashMap<>(); for (final FileStatus file : status) { futureList.add(pool.submit(() -> { Kryo kryo = null; try (Input in = new Input(fs.open(file.getPath()))) { kryo = SerializationUtilities.borrowKryo(); Map<String, Map<String,String>> stats = kryo.readObject(in, statsMap.getClass()); Utilities.FILE_OP_LOGGER.trace("Read stats {}", stats); return stats; } finally { SerializationUtilities.releaseKryo(kryo); } })); } for(Future<Map<String, Map<String,String>>> future : futureList) { Map<String, Map<String,String>> stats = future.get(); if (stats != null) { statsList.add(stats); } } return true; } catch (IOException | ExecutionException e) { Utilities.FILE_OP_LOGGER.error("Failed to read stats from filesystem ", e); cancelRunningTasks(futureList); return false; } catch (InterruptedException e) { cancelRunningTasks(futureList); //reset interrupt state Thread.currentThread().interrupt(); } finally { pool.shutdownNow(); } return false; } private void cancelRunningTasks(List<Future<Map<String, Map<String,String>>>> tasks) { for(Future<Map<String, Map<String,String>>> task: tasks) { task.cancel(true); } } @Override public String aggregateStats(String partID, String statType) { long counter = 0; Utilities.FILE_OP_LOGGER.debug("Part ID: {}, {}", partID, statType); for (Map<String,Map<String,String>> statsMap : statsList) { Map<String,String> partStat = statsMap.get(partID); if (null == partStat) { // not all partitions are scanned in all mappers, so this could be null. continue; } String statVal = partStat.get(statType); if (null == statVal) { // partition was found, but was empty. continue; } counter += Long.parseLong(statVal); } Utilities.FILE_OP_LOGGER.info("Read stats for {}, {}, {}: ", partID, statType, counter); return String.valueOf(counter); } @Override public boolean closeConnection(StatsCollectionContext scc) { List<String> statsDirs = scc.getStatsTmpDirs(); assert statsDirs.size() == 1 : "Found multiple stats dirs: " + statsDirs; Path statsDir = new Path(statsDirs.get(0)); LOG.debug("About to delete stats tmp dir :" + statsDir); try { fs.delete(statsDir,true); return true; } catch (IOException e) { LOG.error("Failed to delete stats dir", e); return true; } } }
ql/src/java/org/apache/hadoop/hive/ql/stats/fs/FSStatsAggregator.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.ql.stats.fs; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.PathFilter; import org.apache.hadoop.hive.common.StatsSetupConst; import org.apache.hadoop.hive.ql.exec.SerializationUtilities; import org.apache.hadoop.hive.ql.exec.Utilities; import org.apache.hadoop.hive.ql.stats.StatsAggregator; import org.apache.hadoop.hive.ql.stats.StatsCollectionContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.Input; public class FSStatsAggregator implements StatsAggregator { private final Logger LOG = LoggerFactory.getLogger(this.getClass().getName()); private List<Map<String,Map<String,String>>> statsList; private Map<String, Map<String,String>> statsMap; private FileSystem fs; @Override public boolean connect(StatsCollectionContext scc) { List<String> statsDirs = scc.getStatsTmpDirs(); assert statsDirs.size() == 1 : "Found multiple stats dirs: " + statsDirs; Path statsDir = new Path(statsDirs.get(0)); Utilities.FILE_OP_LOGGER.trace("About to read stats from {}", statsDir); statsMap = new HashMap<String, Map<String,String>>(); try { fs = statsDir.getFileSystem(scc.getHiveConf()); statsList = new ArrayList<Map<String,Map<String,String>>>(); FileStatus[] status = fs.listStatus(statsDir, new PathFilter() { @Override public boolean accept(Path file) { return file.getName().startsWith(StatsSetupConst.STATS_FILE_PREFIX); } }); for (FileStatus file : status) { Utilities.FILE_OP_LOGGER.trace("About to read stats file {} ", file.getPath()); Input in = new Input(fs.open(file.getPath())); Kryo kryo = SerializationUtilities.borrowKryo(); try { statsMap = kryo.readObject(in, statsMap.getClass()); } finally { SerializationUtilities.releaseKryo(kryo); } Utilities.FILE_OP_LOGGER.trace("Read : {}", statsMap); statsList.add(statsMap); in.close(); } return true; } catch (IOException e) { Utilities.FILE_OP_LOGGER.error("Failed to read stats from filesystem ", e); return false; } } @Override public String aggregateStats(String partID, String statType) { long counter = 0; Utilities.FILE_OP_LOGGER.debug("Part ID: {}, {}", partID, statType); for (Map<String,Map<String,String>> statsMap : statsList) { Map<String,String> partStat = statsMap.get(partID); if (null == partStat) { // not all partitions are scanned in all mappers, so this could be null. continue; } String statVal = partStat.get(statType); if (null == statVal) { // partition was found, but was empty. continue; } counter += Long.parseLong(statVal); } Utilities.FILE_OP_LOGGER.info("Read stats for {}, {}, {}: ", partID, statType, counter); return String.valueOf(counter); } @Override public boolean closeConnection(StatsCollectionContext scc) { List<String> statsDirs = scc.getStatsTmpDirs(); assert statsDirs.size() == 1 : "Found multiple stats dirs: " + statsDirs; Path statsDir = new Path(statsDirs.get(0)); LOG.debug("About to delete stats tmp dir :" + statsDir); try { fs.delete(statsDir,true); return true; } catch (IOException e) { LOG.error("Failed to delete stats dir", e); return true; } } }
HIVE-21312: FSStatsAggregator::connect is slow (Rajesh Balamohan, reviewed by Zoltan Haindrich)
ql/src/java/org/apache/hadoop/hive/ql/stats/fs/FSStatsAggregator.java
HIVE-21312: FSStatsAggregator::connect is slow (Rajesh Balamohan, reviewed by Zoltan Haindrich)
<ide><path>l/src/java/org/apache/hadoop/hive/ql/stats/fs/FSStatsAggregator.java <ide> import java.io.IOException; <ide> import java.util.ArrayList; <ide> import java.util.HashMap; <add>import java.util.LinkedList; <ide> import java.util.List; <ide> import java.util.Map; <add>import java.util.concurrent.ExecutionException; <add>import java.util.concurrent.ExecutorService; <add>import java.util.concurrent.Executors; <add>import java.util.concurrent.Future; <ide> <add>import com.google.common.util.concurrent.ThreadFactoryBuilder; <ide> import org.apache.hadoop.fs.FileStatus; <ide> import org.apache.hadoop.fs.FileSystem; <ide> import org.apache.hadoop.fs.Path; <ide> import org.apache.hadoop.fs.PathFilter; <ide> import org.apache.hadoop.hive.common.StatsSetupConst; <add>import org.apache.hadoop.hive.conf.HiveConf; <ide> import org.apache.hadoop.hive.ql.exec.SerializationUtilities; <ide> import org.apache.hadoop.hive.ql.exec.Utilities; <ide> import org.apache.hadoop.hive.ql.stats.StatsAggregator; <ide> public class FSStatsAggregator implements StatsAggregator { <ide> private final Logger LOG = LoggerFactory.getLogger(this.getClass().getName()); <ide> private List<Map<String,Map<String,String>>> statsList; <del> private Map<String, Map<String,String>> statsMap; <ide> private FileSystem fs; <ide> <ide> @Override <ide> assert statsDirs.size() == 1 : "Found multiple stats dirs: " + statsDirs; <ide> Path statsDir = new Path(statsDirs.get(0)); <ide> Utilities.FILE_OP_LOGGER.trace("About to read stats from {}", statsDir); <del> statsMap = new HashMap<String, Map<String,String>>(); <add> int poolSize = HiveConf.getIntVar(scc.getHiveConf(), HiveConf.ConfVars.HIVE_MOVE_FILES_THREAD_COUNT); <add> // In case thread count is set to 0, use single thread. <add> poolSize = Math.max(poolSize, 1); <add> final ExecutorService pool = Executors.newFixedThreadPool(poolSize, <add> new ThreadFactoryBuilder().setDaemon(true) <add> .setNameFormat("stats-updater-thread-%d") <add> .build());; <add> <add> final List<Future<Map<String, Map<String,String>>>> futureList = new LinkedList<>(); <ide> <ide> try { <ide> fs = statsDir.getFileSystem(scc.getHiveConf()); <del> statsList = new ArrayList<Map<String,Map<String,String>>>(); <add> statsList = new ArrayList<>(); <ide> FileStatus[] status = fs.listStatus(statsDir, new PathFilter() { <ide> @Override <ide> public boolean accept(Path file) { <ide> return file.getName().startsWith(StatsSetupConst.STATS_FILE_PREFIX); <ide> } <ide> }); <del> for (FileStatus file : status) { <del> Utilities.FILE_OP_LOGGER.trace("About to read stats file {} ", file.getPath()); <del> Input in = new Input(fs.open(file.getPath())); <del> Kryo kryo = SerializationUtilities.borrowKryo(); <del> try { <del> statsMap = kryo.readObject(in, statsMap.getClass()); <del> } finally { <del> SerializationUtilities.releaseKryo(kryo); <add> Map<String, Map<String,String>> statsMap = new HashMap<>(); <add> for (final FileStatus file : status) { <add> futureList.add(pool.submit(() -> { <add> Kryo kryo = null; <add> try (Input in = new Input(fs.open(file.getPath()))) { <add> kryo = SerializationUtilities.borrowKryo(); <add> Map<String, Map<String,String>> stats = kryo.readObject(in, statsMap.getClass()); <add> Utilities.FILE_OP_LOGGER.trace("Read stats {}", stats); <add> return stats; <add> } finally { <add> SerializationUtilities.releaseKryo(kryo); <add> } <add> })); <add> } <add> for(Future<Map<String, Map<String,String>>> future : futureList) { <add> Map<String, Map<String,String>> stats = future.get(); <add> if (stats != null) { <add> statsList.add(stats); <ide> } <del> Utilities.FILE_OP_LOGGER.trace("Read : {}", statsMap); <del> statsList.add(statsMap); <del> in.close(); <ide> } <ide> return true; <del> } catch (IOException e) { <add> } catch (IOException | ExecutionException e) { <ide> Utilities.FILE_OP_LOGGER.error("Failed to read stats from filesystem ", e); <add> cancelRunningTasks(futureList); <ide> return false; <add> } catch (InterruptedException e) { <add> cancelRunningTasks(futureList); <add> //reset interrupt state <add> Thread.currentThread().interrupt(); <add> } finally { <add> pool.shutdownNow(); <add> } <add> return false; <add> } <add> <add> private void cancelRunningTasks(List<Future<Map<String, Map<String,String>>>> tasks) { <add> for(Future<Map<String, Map<String,String>>> task: tasks) { <add> task.cancel(true); <ide> } <ide> } <ide>
Java
bsd-3-clause
22cd5b0e30b10bde610c8a977c7b925bca8973e1
0
evestera/dhis2-android-sdk,Kolbeinsvik/dhis2-android-sdk,arthurgwatidzo/dhis2-android-sdk,dhis2/dhis2-android-sdk,dhis2/dhis2-android-sdk,dhis2/dhis2-android-sdk
/* * Copyright (c) 2015, University of Oslo * * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.sdk.utils.services; import org.apache.commons.jexl2.JexlException; import org.hisp.dhis.android.sdk.controllers.metadata.MetaDataController; import org.hisp.dhis.android.sdk.controllers.tracker.TrackerController; import org.hisp.dhis.android.sdk.persistence.models.Constant; import org.hisp.dhis.android.sdk.persistence.models.DataElement; import org.hisp.dhis.android.sdk.persistence.models.DataValue; import org.hisp.dhis.android.sdk.persistence.models.Enrollment; import org.hisp.dhis.android.sdk.persistence.models.Event; import org.hisp.dhis.android.sdk.persistence.models.ProgramIndicator; import org.hisp.dhis.android.sdk.persistence.models.ProgramStage; import org.hisp.dhis.android.sdk.persistence.models.ProgramStageDataElement; import org.hisp.dhis.android.sdk.persistence.models.TrackedEntityAttribute; import org.hisp.dhis.android.sdk.persistence.models.TrackedEntityAttributeValue; import org.hisp.dhis.android.sdk.utils.support.DateUtils; import org.hisp.dhis.android.sdk.utils.support.ExpressionUtils; import org.hisp.dhis.android.sdk.utils.support.MathUtils; import org.hisp.dhis.android.sdk.utils.support.TextUtils; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; /** * @author Chau Thu Tran */ /** * Handles logic related to ProgramIndicators such as calculating values based on expressions. * This class has been copied from the dhis 2 core repository and been stripped down. */ public class ProgramIndicatorService { public static final String CLASS_TAG = ProgramIndicatorService.class.getSimpleName(); /** * Calculate an program indicator value based on program instance and an * indicator defined for a TrackedEntityInstance * * @param programInstance ProgramInstance * @param programIndicator ProgramIndicator * @return Indicator value */ public static String getProgramIndicatorValue(Enrollment programInstance, ProgramIndicator programIndicator) { if(programIndicator == null) { return null; } Double value = getValue(programInstance, null, programIndicator); if (value != null && !Double.isNaN(value)) { value = MathUtils.getRounded(value, 2); return String.valueOf(value); } return null; } /** * Calculate an program indicator value based on a single event * * @param event Event * @param programIndicator ProgramIndicator * @return Indicator value */ public static String getProgramIndicatorValue(Event event, ProgramIndicator programIndicator) { if(programIndicator == null) { return null; } Double value = getValue(null, event, programIndicator); if (value != null && !Double.isNaN(value)) { value = MathUtils.getRounded(value, 2); return String.valueOf(value); } return null; } /** * Get indicator values of all program indicators defined for a TrackedEntityInstance * * @param programInstance ProgramInstance * @return Map<Indicator name, Indicator value> */ public static Map<String, String> getProgramIndicatorValues(Enrollment programInstance) { Map<String, String> result = new HashMap<>(); Collection<ProgramIndicator> programIndicators = new HashSet(programInstance.getProgram().getProgramIndicators()); for (ProgramIndicator programIndicator : programIndicators) { String value = getProgramIndicatorValue(programInstance, programIndicator); if (value != null) { result.put(programIndicator.getDisplayName(), getProgramIndicatorValue(programInstance, programIndicator)); } } return result; } /** * Get description of an indicator expression * * @param expression A expression string * @return The description */ public static String getExpressionDescription(String expression) { StringBuffer description = new StringBuffer(); Matcher matcher = ProgramIndicator.EXPRESSION_PATTERN.matcher(expression); while (matcher.find()) { String key = matcher.group(1); String uid = matcher.group(2); if (ProgramIndicator.KEY_DATAELEMENT.equals(key)) { String de = matcher.group(3); ProgramStage programStage = MetaDataController.getProgramStage(uid); DataElement dataElement = MetaDataController.getDataElement(de); if (programStage != null && dataElement != null) { String programStageName = programStage.getDisplayName(); String dataelementName = dataElement.getDisplayName(); matcher.appendReplacement(description, programStageName + ProgramIndicator.SEPARATOR_ID + dataelementName); } } else if (ProgramIndicator.KEY_ATTRIBUTE.equals(key)) { TrackedEntityAttribute attribute = MetaDataController.getTrackedEntityAttribute(uid); if (attribute != null) { matcher.appendReplacement(description, attribute.getDisplayName()); } } else if (ProgramIndicator.KEY_CONSTANT.equals(key)) { Constant constant = MetaDataController.getConstant(uid); if (constant != null) { matcher.appendReplacement(description, constant.getDisplayName()); } } else if (ProgramIndicator.KEY_PROGRAM_VARIABLE.equals(key)) { if (ProgramIndicator.CURRENT_DATE.equals(uid)) { matcher.appendReplacement(description, "Current date"); } else if (ProgramIndicator.ENROLLMENT_DATE.equals(uid)) { matcher.appendReplacement(description, "Enrollment date"); } else if (ProgramIndicator.INCIDENT_DATE.equals(uid)) { matcher.appendReplacement(description, "Incident date"); } else if (ProgramIndicator.VALUE_COUNT.equals(uid)) { matcher.appendReplacement(description, "Value count"); } } } matcher.appendTail(description); return description.toString(); } /** * Get description of an indicator expression * * @param expression A expression string * @return The expression is valid or not */ public static String expressionIsValid(String expression) { StringBuffer description = new StringBuffer(); Matcher matcher = ProgramIndicator.EXPRESSION_PATTERN.matcher(expression); while (matcher.find()) { String key = matcher.group(1); String uid = matcher.group(2); if (ProgramIndicator.KEY_DATAELEMENT.equals(key)) { String de = matcher.group(3); ProgramStage programStage = MetaDataController.getProgramStage(uid); DataElement dataElement = MetaDataController.getDataElement(de); if (programStage != null && dataElement != null) { matcher.appendReplacement(description, String.valueOf(1)); } else { return ProgramIndicator.EXPRESSION_NOT_WELL_FORMED; } } else if (ProgramIndicator.KEY_ATTRIBUTE.equals(key)) { TrackedEntityAttribute attribute = MetaDataController.getTrackedEntityAttribute(uid); if (attribute != null) { matcher.appendReplacement(description, String.valueOf(1)); } else { return ProgramIndicator.EXPRESSION_NOT_WELL_FORMED; } } else if (ProgramIndicator.KEY_CONSTANT.equals(key)) { Constant constant = MetaDataController.getConstant(uid); if (constant != null) { matcher.appendReplacement(description, String.valueOf(constant.getValue())); } else { return ProgramIndicator.EXPRESSION_NOT_WELL_FORMED; } } else if (ProgramIndicator.KEY_PROGRAM_VARIABLE.equals(key)) { matcher.appendReplacement(description, String.valueOf(0)); } } matcher.appendTail(description); // --------------------------------------------------------------------- // Well-formed expression // --------------------------------------------------------------------- if (MathUtils.expressionHasErrors(description.toString())) { return ProgramIndicator.EXPRESSION_NOT_WELL_FORMED; } return ProgramIndicator.VALID; } /** * Get all {@link org.hisp.dhis.android.sdk.persistence.models.ProgramStageDataElement} part of the expression of the * given indicator. * * @param indicator the ProgramIndicator. * @return a set of ProgramStageDataElements. */ public static Set<ProgramStageDataElement> getProgramStageDataElementsInExpression(ProgramIndicator indicator) { Set<ProgramStageDataElement> elements = new HashSet<>(); Matcher matcher = ProgramIndicator.DATAELEMENT_PATTERN.matcher(indicator.getExpression()); while (matcher.find()) { String ps = matcher.group(1); String de = matcher.group(2); ProgramStage programStage = MetaDataController.getProgramStage(ps); DataElement dataElement = MetaDataController.getDataElement(de); if (programStage != null && dataElement != null) { elements.add(programStage.getProgramStageDataElement(dataElement.getUid())); } } return elements; } public static List<String> getDataElementsInExpression(ProgramIndicator indicator) { List<String> elements = new ArrayList<>(); Matcher matcher = ProgramIndicator.DATAELEMENT_PATTERN.matcher(indicator.getExpression()); while (matcher.find()) { String ps = matcher.group(1); String de = matcher.group(2); elements.add(de); } return elements; } /** * Get all {@link org.hisp.dhis.android.sdk.persistence.models.TrackedEntityAttribute} part of the expression of the * given indicator. * * @param indicator the ProgramIndicator. * @return a set of TrackedEntityAttributes. */ public static Set<TrackedEntityAttribute> getAttributesInExpression(ProgramIndicator indicator) { Set<TrackedEntityAttribute> attributes = new HashSet<>(); Matcher matcher = ProgramIndicator.ATTRIBUTE_PATTERN.matcher(indicator.getExpression()); while (matcher.find()) { String at = matcher.group(1); TrackedEntityAttribute attribute = MetaDataController.getTrackedEntityAttribute(at); if (attribute != null) { attributes.add(attribute); } } return attributes; } // ------------------------------------------------------------------------- // Supportive methods // ------------------------------------------------------------------------- /** * @param programInstance can be null if event is not null in case single event without reg * @param event can be null if programInstance is not null * @param indicator * @return */ private static Double getValue(Enrollment programInstance, Event event, ProgramIndicator indicator) { StringBuffer buffer = new StringBuffer(); String expression = indicator.getExpression(); Matcher matcher = ProgramIndicator.EXPRESSION_PATTERN.matcher(expression); int valueCount = 0; int zeroPosValueCount = 0; Event programStageInstance = null; Map<String, DataValue> dataElementToDataValues = new HashMap<>(); while (matcher.find()) { String key = matcher.group(1); String uid = matcher.group(2); if (ProgramIndicator.KEY_DATAELEMENT.equals(key)) { String de = matcher.group(3); String programStageUid = uid; if (programStageUid != null && de != null) { if (programInstance == null) { //in case single event without reg if(programStageInstance == null) { programStageInstance = event; if (programStageInstance.getDataValues() != null) { for (DataValue dataValue : programStageInstance.getDataValues()) { dataElementToDataValues.put(dataValue.getDataElement(), dataValue); } } } } else { if (programStageInstance == null || !programStageInstance.getUid().equals(programStageUid)) { programStageInstance = TrackerController.getEvent(programInstance.getLocalId(), programStageUid); dataElementToDataValues.clear(); if (programStageInstance.getDataValues() != null) { for(DataValue dataValue: programStageInstance.getDataValues()) { dataElementToDataValues.put(dataValue.getDataElement(), dataValue); } } } } DataValue dataValue; if (programStageInstance.getDataValues() == null) { continue; } dataValue = dataElementToDataValues.get(de); String value; if (dataValue == null || dataValue.getValue() == null || dataValue.getValue().isEmpty()) { if (indicator.getMissingValueReplacement() == null) { value = String.valueOf(0); } else { value = String.valueOf(indicator.getMissingValueReplacement()); } } else { value = dataValue.getValue(); valueCount++; zeroPosValueCount = isZeroOrPositive(value) ? (zeroPosValueCount + 1) : zeroPosValueCount; } matcher.appendReplacement(buffer, value); } else { continue; } } else if (ProgramIndicator.KEY_ATTRIBUTE.equals(key)) { if (programInstance != null) { //in case single event without reg if (uid != null) { TrackedEntityAttributeValue attributeValue = TrackerController.getTrackedEntityAttributeValue( uid, programInstance.getLocalTrackedEntityInstanceId()); String value; if (attributeValue == null || attributeValue.getValue() == null || attributeValue.getValue().isEmpty()) { if (indicator.getMissingValueReplacement() == null) { value = String.valueOf(0); } else { value = String.valueOf(indicator.getMissingValueReplacement()); } } else { value = attributeValue.getValue(); valueCount++; zeroPosValueCount = isZeroOrPositive(value) ? (zeroPosValueCount + 1) : zeroPosValueCount; } matcher.appendReplacement(buffer, value); } else { continue; } } } else if (ProgramIndicator.KEY_CONSTANT.equals(key)) { Constant constant = MetaDataController.getConstant(uid); if (constant != null) { matcher.appendReplacement(buffer, String.valueOf(constant.getValue())); } else { continue; } } else if (ProgramIndicator.KEY_PROGRAM_VARIABLE.equals(key)) { if (programInstance != null) { //in case of single event without reg Date currentDate = new Date(); Date date = null; if (ProgramIndicator.ENROLLMENT_DATE.equals(uid)) { date = DateUtils.getMediumDate(programInstance.getDateOfEnrollment()); } else if (ProgramIndicator.INCIDENT_DATE.equals(uid)) { date = DateUtils.getMediumDate(programInstance.getDateOfIncident()); } else if (ProgramIndicator.CURRENT_DATE.equals(uid)) { date = currentDate; } if (date != null) { matcher.appendReplacement(buffer, DateUtils.daysBetween(currentDate, date) + ""); } } } } if(valueCount <= 0) { //returning null in case there are now values in the expression. return null; } expression = TextUtils.appendTail(matcher, buffer); // --------------------------------------------------------------------- // Value count variable // --------------------------------------------------------------------- buffer = new StringBuffer(); matcher = ProgramIndicator.VALUECOUNT_PATTERN.matcher(expression); while (matcher.find()) { String var = matcher.group(1); if (ProgramIndicator.VAR_VALUE_COUNT.equals(var)) { matcher.appendReplacement(buffer, String.valueOf(valueCount)); } else if (ProgramIndicator.VAR_ZERO_POS_VALUE_COUNT.equals(var)) { matcher.appendReplacement(buffer, String.valueOf(zeroPosValueCount)); } } expression = TextUtils.appendTail(matcher, buffer); Double value; try { value = ExpressionUtils.evaluateToDouble(expression, null); } catch (JexlException e) { e.printStackTrace(); value = new Double(0); } return value; } private static boolean isZeroOrPositive(String value) { return MathUtils.isNumeric(value) && Double.valueOf(value) >= 0d; } }
app/src/main/java/org/hisp/dhis/android/sdk/utils/services/ProgramIndicatorService.java
/* * Copyright (c) 2015, University of Oslo * * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.sdk.utils.services; import org.apache.commons.jexl2.JexlException; import org.hisp.dhis.android.sdk.controllers.metadata.MetaDataController; import org.hisp.dhis.android.sdk.controllers.tracker.TrackerController; import org.hisp.dhis.android.sdk.persistence.models.Constant; import org.hisp.dhis.android.sdk.persistence.models.DataElement; import org.hisp.dhis.android.sdk.persistence.models.DataValue; import org.hisp.dhis.android.sdk.persistence.models.Enrollment; import org.hisp.dhis.android.sdk.persistence.models.Event; import org.hisp.dhis.android.sdk.persistence.models.ProgramIndicator; import org.hisp.dhis.android.sdk.persistence.models.ProgramStage; import org.hisp.dhis.android.sdk.persistence.models.ProgramStageDataElement; import org.hisp.dhis.android.sdk.persistence.models.TrackedEntityAttribute; import org.hisp.dhis.android.sdk.persistence.models.TrackedEntityAttributeValue; import org.hisp.dhis.android.sdk.utils.support.DateUtils; import org.hisp.dhis.android.sdk.utils.support.ExpressionUtils; import org.hisp.dhis.android.sdk.utils.support.MathUtils; import org.hisp.dhis.android.sdk.utils.support.TextUtils; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; /** * @author Chau Thu Tran */ /** * Handles logic related to ProgramIndicators such as calculating values based on expressions. * This class has been copied from the dhis 2 core repository and been stripped down. */ public class ProgramIndicatorService { public static final String CLASS_TAG = ProgramIndicatorService.class.getSimpleName(); /** * Calculate an program indicator value based on program instance and an * indicator defined for a TrackedEntityInstance * * @param programInstance ProgramInstance * @param programIndicator ProgramIndicator * @return Indicator value */ public static String getProgramIndicatorValue(Enrollment programInstance, ProgramIndicator programIndicator) { if(programIndicator == null) { return null; } Double value = getValue(programInstance, null, programIndicator); if (value != null && !Double.isNaN(value)) { value = MathUtils.getRounded(value, 2); if (ProgramIndicator.VALUE_TYPE_DATE.equals(programIndicator.getValueType())) { Date baseDate = new Date(); if (ProgramIndicator.INCIDENT_DATE.equals(programIndicator.getRootDate())) { baseDate = DateUtils.getMediumDate(programInstance.getDateOfIncident()); } else if (ProgramIndicator.ENROLLMENT_DATE.equals(programIndicator.getRootDate())) { baseDate = DateUtils.getMediumDate(programInstance.getDateOfEnrollment()); } Date date = DateUtils.getDateAfterAddition(baseDate, value.intValue()); return DateUtils.getMediumDateString(date); } return String.valueOf(Math.floor(value)); } return null; } /** * Calculate an program indicator value based on a single event * * @param event Event * @param programIndicator ProgramIndicator * @return Indicator value */ public static String getProgramIndicatorValue(Event event, ProgramIndicator programIndicator) { if(programIndicator == null) { return null; } Double value = getValue(null, event, programIndicator); if (value != null && !Double.isNaN(value)) { value = MathUtils.getRounded(value, 2); if (ProgramIndicator.VALUE_TYPE_DATE.equals(programIndicator.getValueType())) { Date baseDate = new Date(); if (ProgramIndicator.INCIDENT_DATE.equals(programIndicator.getRootDate())) { //todo: ignoring in case of single event event without registration //baseDate = DateUtils.getMediumDate(programInstance.dateOfIncident); } else if (ProgramIndicator.ENROLLMENT_DATE.equals(programIndicator.getRootDate())) { //baseDate = DateUtils.getMediumDate(programInstance.dateOfEnrollment); } Date date = DateUtils.getDateAfterAddition(baseDate, value.intValue()); return DateUtils.getMediumDateString(date); } return String.valueOf(value); } return null; } /** * Get indicator values of all program indicators defined for a TrackedEntityInstance * * @param programInstance ProgramInstance * @return Map<Indicator name, Indicator value> */ public static Map<String, String> getProgramIndicatorValues(Enrollment programInstance) { Map<String, String> result = new HashMap<>(); Collection<ProgramIndicator> programIndicators = new HashSet(programInstance.getProgram().getProgramIndicators()); for (ProgramIndicator programIndicator : programIndicators) { String value = getProgramIndicatorValue(programInstance, programIndicator); if (value != null) { result.put(programIndicator.getDisplayName(), getProgramIndicatorValue(programInstance, programIndicator)); } } return result; } /** * Get description of an indicator expression * * @param expression A expression string * @return The description */ public static String getExpressionDescription(String expression) { StringBuffer description = new StringBuffer(); Matcher matcher = ProgramIndicator.EXPRESSION_PATTERN.matcher(expression); while (matcher.find()) { String key = matcher.group(1); String uid = matcher.group(2); if (ProgramIndicator.KEY_DATAELEMENT.equals(key)) { String de = matcher.group(3); ProgramStage programStage = MetaDataController.getProgramStage(uid); DataElement dataElement = MetaDataController.getDataElement(de); if (programStage != null && dataElement != null) { String programStageName = programStage.getDisplayName(); String dataelementName = dataElement.getDisplayName(); matcher.appendReplacement(description, programStageName + ProgramIndicator.SEPARATOR_ID + dataelementName); } } else if (ProgramIndicator.KEY_ATTRIBUTE.equals(key)) { TrackedEntityAttribute attribute = MetaDataController.getTrackedEntityAttribute(uid); if (attribute != null) { matcher.appendReplacement(description, attribute.getDisplayName()); } } else if (ProgramIndicator.KEY_CONSTANT.equals(key)) { Constant constant = MetaDataController.getConstant(uid); if (constant != null) { matcher.appendReplacement(description, constant.getDisplayName()); } } else if (ProgramIndicator.KEY_PROGRAM_VARIABLE.equals(key)) { if (ProgramIndicator.CURRENT_DATE.equals(uid)) { matcher.appendReplacement(description, "Current date"); } else if (ProgramIndicator.ENROLLMENT_DATE.equals(uid)) { matcher.appendReplacement(description, "Enrollment date"); } else if (ProgramIndicator.INCIDENT_DATE.equals(uid)) { matcher.appendReplacement(description, "Incident date"); } else if (ProgramIndicator.VALUE_COUNT.equals(uid)) { matcher.appendReplacement(description, "Value count"); } } } matcher.appendTail(description); return description.toString(); } /** * Get description of an indicator expression * * @param expression A expression string * @return The expression is valid or not */ public static String expressionIsValid(String expression) { StringBuffer description = new StringBuffer(); Matcher matcher = ProgramIndicator.EXPRESSION_PATTERN.matcher(expression); while (matcher.find()) { String key = matcher.group(1); String uid = matcher.group(2); if (ProgramIndicator.KEY_DATAELEMENT.equals(key)) { String de = matcher.group(3); ProgramStage programStage = MetaDataController.getProgramStage(uid); DataElement dataElement = MetaDataController.getDataElement(de); if (programStage != null && dataElement != null) { matcher.appendReplacement(description, String.valueOf(1)); } else { return ProgramIndicator.EXPRESSION_NOT_WELL_FORMED; } } else if (ProgramIndicator.KEY_ATTRIBUTE.equals(key)) { TrackedEntityAttribute attribute = MetaDataController.getTrackedEntityAttribute(uid); if (attribute != null) { matcher.appendReplacement(description, String.valueOf(1)); } else { return ProgramIndicator.EXPRESSION_NOT_WELL_FORMED; } } else if (ProgramIndicator.KEY_CONSTANT.equals(key)) { Constant constant = MetaDataController.getConstant(uid); if (constant != null) { matcher.appendReplacement(description, String.valueOf(constant.getValue())); } else { return ProgramIndicator.EXPRESSION_NOT_WELL_FORMED; } } else if (ProgramIndicator.KEY_PROGRAM_VARIABLE.equals(key)) { matcher.appendReplacement(description, String.valueOf(0)); } } matcher.appendTail(description); // --------------------------------------------------------------------- // Well-formed expression // --------------------------------------------------------------------- if (MathUtils.expressionHasErrors(description.toString())) { return ProgramIndicator.EXPRESSION_NOT_WELL_FORMED; } return ProgramIndicator.VALID; } /** * Get all {@link org.hisp.dhis.android.sdk.persistence.models.ProgramStageDataElement} part of the expression of the * given indicator. * * @param indicator the ProgramIndicator. * @return a set of ProgramStageDataElements. */ public static Set<ProgramStageDataElement> getProgramStageDataElementsInExpression(ProgramIndicator indicator) { Set<ProgramStageDataElement> elements = new HashSet<>(); Matcher matcher = ProgramIndicator.DATAELEMENT_PATTERN.matcher(indicator.getExpression()); while (matcher.find()) { String ps = matcher.group(1); String de = matcher.group(2); ProgramStage programStage = MetaDataController.getProgramStage(ps); DataElement dataElement = MetaDataController.getDataElement(de); if (programStage != null && dataElement != null) { elements.add(programStage.getProgramStageDataElement(dataElement.getUid())); } } return elements; } public static List<String> getDataElementsInExpression(ProgramIndicator indicator) { List<String> elements = new ArrayList<>(); Matcher matcher = ProgramIndicator.DATAELEMENT_PATTERN.matcher(indicator.getExpression()); while (matcher.find()) { String ps = matcher.group(1); String de = matcher.group(2); elements.add(de); } return elements; } /** * Get all {@link org.hisp.dhis.android.sdk.persistence.models.TrackedEntityAttribute} part of the expression of the * given indicator. * * @param indicator the ProgramIndicator. * @return a set of TrackedEntityAttributes. */ public static Set<TrackedEntityAttribute> getAttributesInExpression(ProgramIndicator indicator) { Set<TrackedEntityAttribute> attributes = new HashSet<>(); Matcher matcher = ProgramIndicator.ATTRIBUTE_PATTERN.matcher(indicator.getExpression()); while (matcher.find()) { String at = matcher.group(1); TrackedEntityAttribute attribute = MetaDataController.getTrackedEntityAttribute(at); if (attribute != null) { attributes.add(attribute); } } return attributes; } // ------------------------------------------------------------------------- // Supportive methods // ------------------------------------------------------------------------- /** * @param programInstance can be null if event is not null in case single event without reg * @param event can be null if programInstance is not null * @param indicator * @return */ private static Double getValue(Enrollment programInstance, Event event, ProgramIndicator indicator) { StringBuffer buffer = new StringBuffer(); String expression = indicator.getExpression(); Matcher matcher = ProgramIndicator.EXPRESSION_PATTERN.matcher(expression); int valueCount = 0; int zeroPosValueCount = 0; Event programStageInstance = null; Map<String, DataValue> dataElementToDataValues = new HashMap<>(); while (matcher.find()) { String key = matcher.group(1); String uid = matcher.group(2); if (ProgramIndicator.KEY_DATAELEMENT.equals(key)) { String de = matcher.group(3); String programStageUid = uid; if (programStageUid != null && de != null) { if (programInstance == null) { //in case single event without reg if(programStageInstance == null) { programStageInstance = event; if (programStageInstance.getDataValues() != null) { for (DataValue dataValue : programStageInstance.getDataValues()) { dataElementToDataValues.put(dataValue.getDataElement(), dataValue); } } } } else { if (programStageInstance == null || !programStageInstance.getUid().equals(programStageUid)) { programStageInstance = TrackerController.getEvent(programInstance.getLocalId(), programStageUid); dataElementToDataValues.clear(); if (programStageInstance.getDataValues() != null) { for(DataValue dataValue: programStageInstance.getDataValues()) { dataElementToDataValues.put(dataValue.getDataElement(), dataValue); } } } } DataValue dataValue; if (programStageInstance.getDataValues() == null) { continue; } dataValue = dataElementToDataValues.get(de); String value; if (dataValue == null || dataValue.getValue() == null || dataValue.getValue().isEmpty()) { if (indicator.getMissingValueReplacement() == null) { value = String.valueOf(0); } else { value = String.valueOf(indicator.getMissingValueReplacement()); } } else { value = dataValue.getValue(); valueCount++; zeroPosValueCount = isZeroOrPositive(value) ? (zeroPosValueCount + 1) : zeroPosValueCount; } matcher.appendReplacement(buffer, value); } else { continue; } } else if (ProgramIndicator.KEY_ATTRIBUTE.equals(key)) { if (programInstance != null) { //in case single event without reg if (uid != null) { TrackedEntityAttributeValue attributeValue = TrackerController.getTrackedEntityAttributeValue( uid, programInstance.getLocalTrackedEntityInstanceId()); String value; if (attributeValue == null || attributeValue.getValue() == null || attributeValue.getValue().isEmpty()) { if (indicator.getMissingValueReplacement() == null) { value = String.valueOf(0); } else { value = String.valueOf(indicator.getMissingValueReplacement()); } } else { value = attributeValue.getValue(); valueCount++; zeroPosValueCount = isZeroOrPositive(value) ? (zeroPosValueCount + 1) : zeroPosValueCount; } matcher.appendReplacement(buffer, value); } else { continue; } } } else if (ProgramIndicator.KEY_CONSTANT.equals(key)) { Constant constant = MetaDataController.getConstant(uid); if (constant != null) { matcher.appendReplacement(buffer, String.valueOf(constant.getValue())); } else { continue; } } else if (ProgramIndicator.KEY_PROGRAM_VARIABLE.equals(key)) { if (programInstance != null) { //in case of single event without reg Date currentDate = new Date(); Date date = null; if (ProgramIndicator.ENROLLMENT_DATE.equals(uid)) { date = DateUtils.getMediumDate(programInstance.getDateOfEnrollment()); } else if (ProgramIndicator.INCIDENT_DATE.equals(uid)) { date = DateUtils.getMediumDate(programInstance.getDateOfIncident()); } else if (ProgramIndicator.CURRENT_DATE.equals(uid)) { date = currentDate; } if (date != null) { matcher.appendReplacement(buffer, DateUtils.daysBetween(currentDate, date) + ""); } } } } if(valueCount <= 0) { //returning null in case there are now values in the expression. return null; } expression = TextUtils.appendTail(matcher, buffer); // --------------------------------------------------------------------- // Value count variable // --------------------------------------------------------------------- buffer = new StringBuffer(); matcher = ProgramIndicator.VALUECOUNT_PATTERN.matcher(expression); while (matcher.find()) { String var = matcher.group(1); if (ProgramIndicator.VAR_VALUE_COUNT.equals(var)) { matcher.appendReplacement(buffer, String.valueOf(valueCount)); } else if (ProgramIndicator.VAR_ZERO_POS_VALUE_COUNT.equals(var)) { matcher.appendReplacement(buffer, String.valueOf(zeroPosValueCount)); } } expression = TextUtils.appendTail(matcher, buffer); Double value; try { value = ExpressionUtils.evaluateToDouble(expression, null); } catch (JexlException e) { e.printStackTrace(); value = new Double(0); } return value; } private static boolean isZeroOrPositive(String value) { return MathUtils.isNumeric(value) && Double.valueOf(value) >= 0d; } }
Removed dead code
app/src/main/java/org/hisp/dhis/android/sdk/utils/services/ProgramIndicatorService.java
Removed dead code
<ide><path>pp/src/main/java/org/hisp/dhis/android/sdk/utils/services/ProgramIndicatorService.java <ide> if(programIndicator == null) { <ide> return null; <ide> } <add> <ide> Double value = getValue(programInstance, null, programIndicator); <ide> <ide> if (value != null && !Double.isNaN(value)) { <ide> value = MathUtils.getRounded(value, 2); <del> <del> if (ProgramIndicator.VALUE_TYPE_DATE.equals(programIndicator.getValueType())) { <del> Date baseDate = new Date(); <del> <del> if (ProgramIndicator.INCIDENT_DATE.equals(programIndicator.getRootDate())) { <del> baseDate = DateUtils.getMediumDate(programInstance.getDateOfIncident()); <del> } else if (ProgramIndicator.ENROLLMENT_DATE.equals(programIndicator.getRootDate())) { <del> baseDate = DateUtils.getMediumDate(programInstance.getDateOfEnrollment()); <del> } <del> <del> Date date = DateUtils.getDateAfterAddition(baseDate, value.intValue()); <del> <del> return DateUtils.getMediumDateString(date); <del> } <del> <del> return String.valueOf(Math.floor(value)); <add> return String.valueOf(value); <ide> } <ide> <ide> return null; <ide> if(programIndicator == null) { <ide> return null; <ide> } <add> <ide> Double value = getValue(null, event, programIndicator); <ide> <ide> if (value != null && !Double.isNaN(value)) { <ide> value = MathUtils.getRounded(value, 2); <del> <del> if (ProgramIndicator.VALUE_TYPE_DATE.equals(programIndicator.getValueType())) { <del> Date baseDate = new Date(); <del> <del> if (ProgramIndicator.INCIDENT_DATE.equals(programIndicator.getRootDate())) { //todo: ignoring in case of single event event without registration <del> //baseDate = DateUtils.getMediumDate(programInstance.dateOfIncident); <del> } else if (ProgramIndicator.ENROLLMENT_DATE.equals(programIndicator.getRootDate())) { <del> //baseDate = DateUtils.getMediumDate(programInstance.dateOfEnrollment); <del> } <del> <del> Date date = DateUtils.getDateAfterAddition(baseDate, value.intValue()); <del> <del> return DateUtils.getMediumDateString(date); <del> } <ide> return String.valueOf(value); <ide> } <ide>
Java
apache-2.0
9266549b26662bcc8121f49e89581844f5e408d1
0
google/dagger,dushmis/dagger,cgruber/dagger,cgruber/dagger,google/dagger,ze-pequeno/dagger,dushmis/dagger,google/dagger,ze-pequeno/dagger,google/dagger,ze-pequeno/dagger,ze-pequeno/dagger,cgruber/dagger
/* * Copyright (C) 2015 The Dagger 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 dagger.internal.codegen; import static com.google.common.base.Preconditions.checkNotNull; import static dagger.internal.codegen.BindingType.PROVISION; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import dagger.internal.codegen.FrameworkFieldInitializer.FrameworkInstanceCreationExpression; import dagger.model.RequestKind; import dagger.producers.Producer; import java.util.Optional; /** An {@link Producer} creation expression for provision bindings. */ final class ProducerFromProviderCreationExpression implements FrameworkInstanceCreationExpression { private final ContributionBinding binding; private final GeneratedComponentModel generatedComponentModel; private final ComponentBindingExpressions componentBindingExpressions; ProducerFromProviderCreationExpression( ContributionBinding binding, GeneratedComponentModel generatedComponentModel, ComponentBindingExpressions componentBindingExpressions) { this.binding = checkNotNull(binding); this.generatedComponentModel = checkNotNull(generatedComponentModel); this.componentBindingExpressions = checkNotNull(componentBindingExpressions); } @Override public CodeBlock creationExpression() { return FrameworkType.PROVIDER.to( RequestKind.PRODUCER, componentBindingExpressions .getDependencyExpression( FrameworkDependency.create(binding.key(), PROVISION), generatedComponentModel.name()) .codeBlock()); } @Override public Optional<ClassName> alternativeFrameworkClass() { return Optional.of(TypeNames.PRODUCER); } // TODO(ronshapiro): should this have a simple factory if the delegate expression is simple? }
java/dagger/internal/codegen/ProducerFromProviderCreationExpression.java
/* * Copyright (C) 2015 The Dagger 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 dagger.internal.codegen; import static com.google.common.base.Preconditions.checkNotNull; import static dagger.internal.codegen.BindingType.PROVISION; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import dagger.internal.codegen.FrameworkFieldInitializer.FrameworkInstanceCreationExpression; import dagger.model.RequestKind; import dagger.producers.Producer; import java.util.Optional; /** An {@link Producer} creation expression for provision bindings. */ final class ProducerFromProviderCreationExpression implements FrameworkInstanceCreationExpression { private final ContributionBinding binding; private final GeneratedComponentModel generatedComponentModel; private final ComponentBindingExpressions componentBindingExpressions; ProducerFromProviderCreationExpression( ContributionBinding binding, GeneratedComponentModel generatedComponentModel, ComponentBindingExpressions componentBindingExpressions) { this.binding = checkNotNull(binding); this.generatedComponentModel = checkNotNull(generatedComponentModel); this.componentBindingExpressions = checkNotNull(componentBindingExpressions); } @Override public CodeBlock creationExpression() { return FrameworkType.PROVIDER.to( RequestKind.PRODUCER, componentBindingExpressions .getDependencyExpression( FrameworkDependency.create(binding.key(), PROVISION), generatedComponentModel.name()) .codeBlock()); } @Override public Optional<ClassName> alternativeFrameworkClass() { return Optional.of(ClassName.get(Producer.class)); } // TODO(ronshapiro): should this have a simple factory if the delegate expression is simple? }
Use TypeNames.PRODUCER instead of ClassName.get(Producer.class). RELNOTES=n/a ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=195251609
java/dagger/internal/codegen/ProducerFromProviderCreationExpression.java
Use TypeNames.PRODUCER instead of ClassName.get(Producer.class).
<ide><path>ava/dagger/internal/codegen/ProducerFromProviderCreationExpression.java <ide> <ide> @Override <ide> public Optional<ClassName> alternativeFrameworkClass() { <del> return Optional.of(ClassName.get(Producer.class)); <add> return Optional.of(TypeNames.PRODUCER); <ide> } <ide> <ide> // TODO(ronshapiro): should this have a simple factory if the delegate expression is simple?
Java
apache-2.0
58f1a70d28a3255ec19506b5970d0358de3d0826
0
Silvermedia/unitils
unitils-io/src/main/java/org/unitils/io/IoModule.java
/* * Copyright 2011, Unitils.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.unitils.io; import org.unitils.core.Module; import org.unitils.core.TestListener; import java.util.Properties; /** * Will listen for the @FileContent annotation in tests. The content of the file * specified in the annotation will be loaded in the property. A property * annotation with {@link @FileContent} should always be a String * <br> * Example: * <p/> * <pre> * &#064;FileContent(location = &quot;be/smals/file.txt&quot;) * private String fileContent; * </pre> * * @author Jeroen Horema * @author Thomas De Rycke * @author Tim Ducheyne * @since 3.3 */ public class IoModule implements Module { private FileContentTestListener testListener; public TestListener getTestListener() { return testListener; } public void init(Properties properties) { testListener = initFileContentListener(properties); } private FileContentTestListener initFileContentListener(Properties properties) { return FileContentTestListenerFactory.createFileContentTestListener(properties); } public void afterInit() { } }
Renaming IoModule to IOModule
unitils-io/src/main/java/org/unitils/io/IoModule.java
Renaming IoModule to IOModule
<ide><path>nitils-io/src/main/java/org/unitils/io/IoModule.java <del>/* <del> * Copyright 2011, Unitils.org <del> * <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 <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del> <del>package org.unitils.io; <del> <del>import org.unitils.core.Module; <del>import org.unitils.core.TestListener; <del> <del>import java.util.Properties; <del> <del>/** <del> * Will listen for the @FileContent annotation in tests. The content of the file <del> * specified in the annotation will be loaded in the property. A property <del> * annotation with {@link @FileContent} should always be a String <del> * <br> <del> * Example: <del> * <p/> <del> * <pre> <del> * &#064;FileContent(location = &quot;be/smals/file.txt&quot;) <del> * private String fileContent; <del> * </pre> <del> * <del> * @author Jeroen Horema <del> * @author Thomas De Rycke <del> * @author Tim Ducheyne <del> * @since 3.3 <del> */ <del>public class IoModule implements Module { <del> <del> private FileContentTestListener testListener; <del> <del> public TestListener getTestListener() { <del> return testListener; <del> } <del> <del> public void init(Properties properties) { <del> testListener = initFileContentListener(properties); <del> } <del> <del> private FileContentTestListener initFileContentListener(Properties properties) { <del> return FileContentTestListenerFactory.createFileContentTestListener(properties); <del> } <del> <del> public void afterInit() { <del> } <del> <del>}
Java
apache-2.0
78bb3ca304bfc5eb8e3166afdc7a87c61967a1f9
0
torquebox/torquebox-release,torquebox/torquebox,torquebox/torquebox-release,ksw2599/torquebox,vaskoz/torquebox,mje113/torquebox,samwgoldman/torquebox,mje113/torquebox,vaskoz/torquebox,mje113/torquebox,mje113/torquebox,torquebox/torquebox-release,torquebox/torquebox,samwgoldman/torquebox,vaskoz/torquebox,ksw2599/torquebox,samwgoldman/torquebox,torquebox/torquebox-release,ksw2599/torquebox,torquebox/torquebox,torquebox/torquebox,vaskoz/torquebox,samwgoldman/torquebox,ksw2599/torquebox
/* * Copyright 2008-2011 Red Hat, Inc, and individual contributors. * * 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.torquebox.interp.core; import java.io.File; import java.io.PrintStream; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import org.jboss.kernel.Kernel; import org.jboss.logging.Logger; import org.jboss.vfs.TempFileProvider; import org.jboss.vfs.VFS; import org.jboss.vfs.VirtualFile; import org.jruby.CompatVersion; import org.jruby.Ruby; import org.jruby.RubyInstanceConfig; import org.jruby.RubyInstanceConfig.CompileMode; import org.jruby.RubyModule; import org.jruby.ast.executable.Script; import org.jruby.javasupport.JavaEmbedUtils; import org.jruby.util.ClassCache; import org.torquebox.interp.spi.RubyRuntimeFactory; import org.torquebox.interp.spi.RuntimeInitializer; /** * Default Ruby runtime interpreter factory implementation. * * @author Bob McWhirter <[email protected]> */ public class RubyRuntimeFactoryImpl implements RubyRuntimeFactory { private static final Logger log = Logger.getLogger( RubyRuntimeFactoryImpl.class ); /** MC Kernel. */ private Kernel kernel; /** Re-usable initializer. */ private RuntimeInitializer initializer; /** ClassLoader for interpreter. */ private ClassLoader classLoader; /** Shared interpreter class cache. */ private ClassCache<Script> classCache; /** Application name. */ private String applicationName; /** Load paths for the interpreter. */ private List<String> loadPaths; /** Output stream for the interpreter. */ private PrintStream outputStream = System.out; /** Error stream for the interpreter. */ private PrintStream errorStream = System.err; /** JRUBY_HOME. */ private String jrubyHome; /** GEM_PATH. */ private String gemPath; /** Should environment $JRUBY_HOME be considered? */ private boolean useJRubyHomeEnvVar = true; /** Additional application environment variables. */ private Map<String, String> applicationEnvironment; /** Undisposed runtimes created by this factory. */ private Set<Ruby> undisposed = new HashSet<Ruby>(); /** Ruby compatibility version. */ private CompatVersion rubyVersion; /** JRuby compile mode. */ private CompileMode compileMode; /** * Construct. */ public RubyRuntimeFactoryImpl() { this( null ); } /** * Construct with an initializer. * * @param initializer * The initializer (or null) to use for each created runtime. */ public RubyRuntimeFactoryImpl(RuntimeInitializer initializer) { this.initializer = initializer; } public void setApplicationName(String applicationName) { this.applicationName = applicationName; } public String getApplicationName() { return this.applicationName; } public void setGemPath(String gemPath) { this.gemPath = gemPath; } public String getGemPath() { return this.gemPath; } public void setJRubyHome(String jrubyHome) { this.jrubyHome = jrubyHome; } public String getJRubyHome() { return this.jrubyHome; } public void setUseJRubyHomeEnvVar(boolean useJRubyEnvVar) { this.useJRubyHomeEnvVar = useJRubyEnvVar; } public boolean useJRubyHomeEnvVar() { return this.useJRubyHomeEnvVar; } /** * Inject the Microcontainer kernel. * * @param kernel * The microcontainer kernel. */ public void setKernel(Kernel kernel) { this.kernel = kernel; } /** * Retrieve the Microcontainer kernel. * * @return The microcontainer kernel. */ public Kernel getKernel() { return this.kernel; } /** * Set the interpreter classloader. * * @param classLoader * The classloader. */ public void setClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } /** * Retrieve the interpreter classloader. * * @return The classloader. */ public ClassLoader getClassLoader() { if (this.classLoader != null) { return this.classLoader; } ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl != null) { return cl; } return getClass().getClassLoader(); } /** * Set the Ruby compatibility version. * * @param rubyVersion * The version. */ public void setRubyVersion(CompatVersion rubyVersion) { this.rubyVersion = rubyVersion; } /** * Retrieve the Ruby compatibility version. * * @return The version. */ public CompatVersion getRubyVersion() { return this.rubyVersion; } /** * Set the compile mode. * * @param compileMode * The mode. */ public void setCompileMode(CompileMode compileMode) { this.compileMode = compileMode; } /** * Retrieve the compile mode. * * @return The mode. */ public CompileMode getCompileMode() { return this.compileMode; } /** * Set the application-specific environment additions. * * @param applicationEnvironment * The environment. */ public void setApplicationEnvironment(Map<String, String> applicationEnvironment) { this.applicationEnvironment = applicationEnvironment; } /** * Retrieve the application-specific environment additions. * * @return The environment. */ public Map<String, String> getApplicationEnvironment() { return this.applicationEnvironment; } /** * Create a new instance of a fully-initialized runtime. */ public synchronized Ruby createInstance(String contextInfo) throws Exception { RubyInstanceConfig config = new TorqueBoxRubyInstanceConfig(); config.setClassCache( getClassCache() ); config.setLoadServiceCreator( new VFSLoadServiceCreator() ); if (this.rubyVersion != null) { config.setCompatVersion( this.rubyVersion ); } if (this.compileMode != null) { config.setCompileMode( this.compileMode ); } String jrubyHome = this.jrubyHome; if (jrubyHome == null) { jrubyHome = System.getProperty( "jruby.home" ); if (jrubyHome == null && this.useJRubyHomeEnvVar && !"true".equals( System.getProperty( "jruby_home.env.ignore" ) )) { jrubyHome = System.getenv( "JRUBY_HOME" ); if (jrubyHome != null) { if (!new File( jrubyHome ).exists()) { jrubyHome = null; } } } if (jrubyHome == null) { String jbossHome = System.getProperty( "jboss.home" ); if (jbossHome != null) { File candidatePath = new File( jbossHome, "../jruby" ); if (candidatePath.exists() && candidatePath.isDirectory()) { jrubyHome = candidatePath.getAbsolutePath(); } } } } if (jrubyHome == null) { jrubyHome = RubyInstanceConfig.class.getResource( "/META-INF/jruby.home" ).toURI().getSchemeSpecificPart(); if (jrubyHome.startsWith( "file:" ) && jrubyHome.contains( "!/" )) { int slashLoc = jrubyHome.indexOf( '/' ); int bangLoc = jrubyHome.indexOf( '!' ); String jarPath = jrubyHome.substring( slashLoc, bangLoc ); String extraPath = jrubyHome.substring( bangLoc + 1 ); VirtualFile vfsJar = VFS.getChild( jarPath ); if (vfsJar.exists()) { if (!vfsJar.isDirectory()) { ScheduledExecutorService executor = Executors.newScheduledThreadPool( 1 ); TempFileProvider tempFileProvider = TempFileProvider.create( "jruby.home", executor ); VFS.mountZip( vfsJar, vfsJar, tempFileProvider ); } if (vfsJar.isDirectory()) { VirtualFile vfsJrubyHome = vfsJar.getChild( extraPath ); if (vfsJrubyHome.exists()) { jrubyHome = vfsJrubyHome.toURL().toExternalForm(); } } } } } if (jrubyHome != null) { config.setJRubyHome( jrubyHome ); } config.setEnvironment( createEnvironment() ); config.setOutput( getOutput() ); config.setError( getError() ); List<String> loadPath = new ArrayList<String>(); if (this.loadPaths != null) { loadPath.addAll( this.loadPaths ); } config.setLoadPaths( loadPath ); long startTime = logRuntimeCreationStart( config, contextInfo ); Ruby runtime = null; try { runtime = Ruby.newInstance( config ); runtime.getLoadService().require( "java" ); prepareRuntime( runtime ); if (this.initializer != null) { this.initializer.initialize( runtime ); } else { log.warn( "No initializer set for runtime" ); } performRuntimeInitialization( runtime ); } catch (Exception ex) { log.error( "Failed to initialize runtime: ", ex ); } finally { if (runtime != null) { this.undisposed.add( runtime ); } logRuntimeCreationComplete( config, contextInfo, startTime ); } return runtime; } private long logRuntimeCreationStart(RubyInstanceConfig config, String contextInfo) { log.info( "Creating ruby runtime (ruby_version: " + config.getCompatVersion() + ", compile_mode: " + config.getCompileMode() + getFullContext( contextInfo ) + ")" ); return System.currentTimeMillis(); } private void logRuntimeCreationComplete(RubyInstanceConfig config, String contextInfo, long startTime) { long elapsedMillis = System.currentTimeMillis() - startTime; double elapsedSeconds = Math.floor( (elapsedMillis * 1.0) / 10.0 ) / 100; log.info( "Created ruby runtime (ruby_version: " + config.getCompatVersion() + ", compile_mode: " + config.getCompileMode() + getFullContext( contextInfo ) + ") in " + elapsedSeconds + "s" ); } protected String getFullContext(String contextInfo) { String fullContext = null; if ( this.applicationName != null ) { fullContext = "app: " + this.applicationName; } if ( contextInfo != null ) { if ( fullContext != null ) { fullContext += ", "; } else { fullContext = ""; } fullContext += "context: " + contextInfo; } if ( fullContext == null ) { fullContext = ""; } else { fullContext = ", " + fullContext; } return fullContext; } @Override public synchronized void destroyInstance(Ruby instance) { if (undisposed.remove( instance )) { instance.tearDown( false ); } } private void performRuntimeInitialization(Ruby runtime) { runtime.evalScriptlet( "require %q(org/torquebox/interp/core/runtime_initialization)\n" ); defineVersions( runtime ); setApplicationName( runtime ); } private void defineVersions(Ruby runtime) { RubyModule torqueBoxModule = runtime.getClassFromPath( "TorqueBox" ); JavaEmbedUtils.invokeMethod( runtime, torqueBoxModule, "define_versions", new Object[] { log }, void.class ); } private void setApplicationName(Ruby runtime) { RubyModule torqueBoxModule = runtime.getClassFromPath( "TorqueBox" ); JavaEmbedUtils.invokeMethod( runtime, torqueBoxModule, "application_name=", new Object[] { applicationName }, void.class ); } private void prepareRuntime(Ruby runtime) { runtime.getLoadService().require( "rubygems" ); runtime.evalScriptlet( "require %q(torquebox-vfs)" ); runtime.evalScriptlet( "require %q(torquebox-base)" ); injectKernel( runtime ); } private void injectKernel(Ruby runtime) { runtime.evalScriptlet( "require %q(torquebox/kernel)" ); RubyModule torqueBoxKernelModule = runtime.getClassFromPath( "TorqueBox::Kernel" ); JavaEmbedUtils.invokeMethod( runtime, torqueBoxKernelModule, "kernel=", new Object[] { this.kernel }, void.class ); } protected Map<String, String> createEnvironment() { Map<String, String> env = new HashMap<String, String>(); env.putAll( System.getenv() ); String path = (String) env.get( "PATH" ); if (path == null) { env.put( "PATH", "" ); } String gemPath = System.getProperty( "gem.path" ); if (gemPath == null) { gemPath = this.gemPath; } if ("default".equals( gemPath )) { env.remove( "GEM_PATH" ); env.remove( "GEM_HOME" ); gemPath = null; } if (gemPath != null) { env.put( "GEM_PATH", gemPath ); env.put( "GEM_HOME", gemPath ); } if (this.applicationEnvironment != null) { env.putAll( this.applicationEnvironment ); } return env; } /** * Set the interpreter output stream. * * @param outputStream * The output stream. */ public void setOutput(PrintStream outputStream) { this.outputStream = outputStream; } /** * Retrieve the interpreter output stream. * * @return The output stream. */ public PrintStream getOutput() { return this.outputStream; } /** * Set the interpreter error stream. * * @param errorStream * The error stream. */ public void setError(PrintStream errorStream) { this.errorStream = errorStream; } /** * Retrieve the interpreter error stream. * * @return The error stream. */ public PrintStream getError() { return this.errorStream; } /** * Set the interpreter load paths. * * <p> * Load paths may be either real filesystem paths or VFS URLs * </p> * * @param loadPaths * The list of load paths. */ public void setLoadPaths(List<String> loadPaths) { this.loadPaths = loadPaths; } /** * Retrieve the interpreter load paths. * * @return The list of load paths. */ public List<String> getLoadPaths() { return this.loadPaths; } public void create() { this.classCache = new ClassCache<Script>( getClassLoader() ); } public synchronized void destroy() { Set<Ruby> toDispose = new HashSet<Ruby>(); toDispose.addAll( this.undisposed ); for (Ruby ruby : toDispose ) { destroyInstance( ruby ); } this.undisposed.clear(); } public ClassCache getClassCache() { return this.classCache; } }
components/base/base-core/src/main/java/org/torquebox/interp/core/RubyRuntimeFactoryImpl.java
/* * Copyright 2008-2011 Red Hat, Inc, and individual contributors. * * 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.torquebox.interp.core; import java.io.File; import java.io.PrintStream; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import org.jboss.kernel.Kernel; import org.jboss.logging.Logger; import org.jboss.vfs.TempFileProvider; import org.jboss.vfs.VFS; import org.jboss.vfs.VirtualFile; import org.jruby.CompatVersion; import org.jruby.Ruby; import org.jruby.RubyInstanceConfig; import org.jruby.RubyInstanceConfig.CompileMode; import org.jruby.RubyModule; import org.jruby.ast.executable.Script; import org.jruby.javasupport.JavaEmbedUtils; import org.jruby.util.ClassCache; import org.torquebox.interp.spi.RubyRuntimeFactory; import org.torquebox.interp.spi.RuntimeInitializer; /** * Default Ruby runtime interpreter factory implementation. * * @author Bob McWhirter <[email protected]> */ public class RubyRuntimeFactoryImpl implements RubyRuntimeFactory { private static final Logger log = Logger.getLogger( RubyRuntimeFactoryImpl.class ); /** MC Kernel. */ private Kernel kernel; /** Re-usable initializer. */ private RuntimeInitializer initializer; /** ClassLoader for interpreter. */ private ClassLoader classLoader; /** Shared interpreter class cache. */ private ClassCache<Script> classCache; /** Application name. */ private String applicationName; /** Load paths for the interpreter. */ private List<String> loadPaths; /** Output stream for the interpreter. */ private PrintStream outputStream = System.out; /** Error stream for the interpreter. */ private PrintStream errorStream = System.err; /** JRUBY_HOME. */ private String jrubyHome; /** GEM_PATH. */ private String gemPath; /** Should environment $JRUBY_HOME be considered? */ private boolean useJRubyHomeEnvVar = true; /** Additional application environment variables. */ private Map<String, String> applicationEnvironment; /** Undisposed runtimes created by this factory. */ private Set<Ruby> undisposed = new HashSet<Ruby>(); /** Ruby compatibility version. */ private CompatVersion rubyVersion; /** JRuby compile mode. */ private CompileMode compileMode; /** * Construct. */ public RubyRuntimeFactoryImpl() { this( null ); } /** * Construct with an initializer. * * @param initializer * The initializer (or null) to use for each created runtime. */ public RubyRuntimeFactoryImpl(RuntimeInitializer initializer) { this.initializer = initializer; } public void setApplicationName(String applicationName) { this.applicationName = applicationName; } public String getApplicationName() { return this.applicationName; } public void setGemPath(String gemPath) { this.gemPath = gemPath; } public String getGemPath() { return this.gemPath; } public void setJRubyHome(String jrubyHome) { this.jrubyHome = jrubyHome; } public String getJRubyHome() { return this.jrubyHome; } public void setUseJRubyHomeEnvVar(boolean useJRubyEnvVar) { this.useJRubyHomeEnvVar = useJRubyEnvVar; } public boolean useJRubyHomeEnvVar() { return this.useJRubyHomeEnvVar; } /** * Inject the Microcontainer kernel. * * @param kernel * The microcontainer kernel. */ public void setKernel(Kernel kernel) { this.kernel = kernel; } /** * Retrieve the Microcontainer kernel. * * @return The microcontainer kernel. */ public Kernel getKernel() { return this.kernel; } /** * Set the interpreter classloader. * * @param classLoader * The classloader. */ public void setClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } /** * Retrieve the interpreter classloader. * * @return The classloader. */ public ClassLoader getClassLoader() { if (this.classLoader != null) { return this.classLoader; } ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl != null) { return cl; } return getClass().getClassLoader(); } /** * Set the Ruby compatibility version. * * @param rubyVersion * The version. */ public void setRubyVersion(CompatVersion rubyVersion) { this.rubyVersion = rubyVersion; } /** * Retrieve the Ruby compatibility version. * * @return The version. */ public CompatVersion getRubyVersion() { return this.rubyVersion; } /** * Set the compile mode. * * @param compileMode * The mode. */ public void setCompileMode(CompileMode compileMode) { this.compileMode = compileMode; } /** * Retrieve the compile mode. * * @return The mode. */ public CompileMode getCompileMode() { return this.compileMode; } /** * Set the application-specific environment additions. * * @param applicationEnvironment * The environment. */ public void setApplicationEnvironment(Map<String, String> applicationEnvironment) { this.applicationEnvironment = applicationEnvironment; } /** * Retrieve the application-specific environment additions. * * @return The environment. */ public Map<String, String> getApplicationEnvironment() { return this.applicationEnvironment; } /** * Create a new instance of a fully-initialized runtime. */ public synchronized Ruby createInstance(String contextInfo) throws Exception { RubyInstanceConfig config = new TorqueBoxRubyInstanceConfig(); config.setClassCache( getClassCache() ); config.setLoadServiceCreator( new VFSLoadServiceCreator() ); if (this.rubyVersion != null) { config.setCompatVersion( this.rubyVersion ); } if (this.compileMode != null) { config.setCompileMode( this.compileMode ); } String jrubyHome = this.jrubyHome; if (jrubyHome == null) { jrubyHome = System.getProperty( "jruby.home" ); if (jrubyHome == null && this.useJRubyHomeEnvVar && !"true".equals( System.getProperty( "jruby_home.env.ignore" ) )) { jrubyHome = System.getenv( "JRUBY_HOME" ); if (jrubyHome != null) { if (!new File( jrubyHome ).exists()) { jrubyHome = null; } } } if (jrubyHome == null) { String jbossHome = System.getProperty( "jboss.home" ); if (jbossHome != null) { File candidatePath = new File( jbossHome, "../jruby" ); if (candidatePath.exists() && candidatePath.isDirectory()) { jrubyHome = candidatePath.getAbsolutePath(); } } } } if (jrubyHome == null) { jrubyHome = RubyInstanceConfig.class.getResource( "/META-INF/jruby.home" ).toURI().getSchemeSpecificPart(); if (jrubyHome.startsWith( "file:" ) && jrubyHome.contains( "!/" )) { int slashLoc = jrubyHome.indexOf( '/' ); int bangLoc = jrubyHome.indexOf( '!' ); String jarPath = jrubyHome.substring( slashLoc, bangLoc ); String extraPath = jrubyHome.substring( bangLoc + 1 ); VirtualFile vfsJar = VFS.getChild( jarPath ); if (vfsJar.exists()) { if (!vfsJar.isDirectory()) { ScheduledExecutorService executor = Executors.newScheduledThreadPool( 1 ); TempFileProvider tempFileProvider = TempFileProvider.create( "jruby.home", executor ); VFS.mountZip( vfsJar, vfsJar, tempFileProvider ); } if (vfsJar.isDirectory()) { VirtualFile vfsJrubyHome = vfsJar.getChild( extraPath ); if (vfsJrubyHome.exists()) { jrubyHome = vfsJrubyHome.toURL().toExternalForm(); } } } } } if (jrubyHome != null) { config.setJRubyHome( jrubyHome ); } config.setEnvironment( createEnvironment() ); config.setOutput( getOutput() ); config.setError( getError() ); List<String> loadPath = new ArrayList<String>(); if (this.loadPaths != null) { loadPath.addAll( this.loadPaths ); } config.setLoadPaths( loadPath ); long startTime = logRuntimeCreationStart( config, contextInfo ); Ruby runtime = null; try { runtime = Ruby.newInstance( config ); runtime.getLoadService().require( "java" ); prepareRuntime( runtime ); if (this.initializer != null) { this.initializer.initialize( runtime ); } else { log.warn( "No initializer set for runtime" ); } performRuntimeInitialization( runtime ); return runtime; } finally { if (runtime != null) { this.undisposed.add( runtime ); } logRuntimeCreationComplete( config, contextInfo, startTime ); } } private long logRuntimeCreationStart(RubyInstanceConfig config, String contextInfo) { log.info( "Creating ruby runtime (ruby_version: " + config.getCompatVersion() + ", compile_mode: " + config.getCompileMode() + getFullContext( contextInfo ) + ")" ); return System.currentTimeMillis(); } private void logRuntimeCreationComplete(RubyInstanceConfig config, String contextInfo, long startTime) { long elapsedMillis = System.currentTimeMillis() - startTime; double elapsedSeconds = Math.floor( (elapsedMillis * 1.0) / 10.0 ) / 100; log.info( "Created ruby runtime (ruby_version: " + config.getCompatVersion() + ", compile_mode: " + config.getCompileMode() + getFullContext( contextInfo ) + ") in " + elapsedSeconds + "s" ); } protected String getFullContext(String contextInfo) { String fullContext = null; if ( this.applicationName != null ) { fullContext = "app: " + this.applicationName; } if ( contextInfo != null ) { if ( fullContext != null ) { fullContext += ", "; } else { fullContext = ""; } fullContext += "context: " + contextInfo; } if ( fullContext == null ) { fullContext = ""; } else { fullContext = ", " + fullContext; } return fullContext; } @Override public synchronized void destroyInstance(Ruby instance) { if (undisposed.remove( instance )) { instance.tearDown( false ); } } private void performRuntimeInitialization(Ruby runtime) { runtime.evalScriptlet( "require %q(org/torquebox/interp/core/runtime_initialization)\n" ); defineVersions( runtime ); setApplicationName( runtime ); } private void defineVersions(Ruby runtime) { RubyModule torqueBoxModule = runtime.getClassFromPath( "TorqueBox" ); JavaEmbedUtils.invokeMethod( runtime, torqueBoxModule, "define_versions", new Object[] { log }, void.class ); } private void setApplicationName(Ruby runtime) { RubyModule torqueBoxModule = runtime.getClassFromPath( "TorqueBox" ); JavaEmbedUtils.invokeMethod( runtime, torqueBoxModule, "application_name=", new Object[] { applicationName }, void.class ); } private void prepareRuntime(Ruby runtime) { runtime.getLoadService().require( "rubygems" ); runtime.evalScriptlet( "require %q(torquebox-vfs)" ); runtime.evalScriptlet( "require %q(torquebox-base)" ); injectKernel( runtime ); } private void injectKernel(Ruby runtime) { runtime.evalScriptlet( "require %q(torquebox/kernel)" ); RubyModule torqueBoxKernelModule = runtime.getClassFromPath( "TorqueBox::Kernel" ); JavaEmbedUtils.invokeMethod( runtime, torqueBoxKernelModule, "kernel=", new Object[] { this.kernel }, void.class ); } protected Map<String, String> createEnvironment() { Map<String, String> env = new HashMap<String, String>(); env.putAll( System.getenv() ); String path = (String) env.get( "PATH" ); if (path == null) { env.put( "PATH", "" ); } String gemPath = System.getProperty( "gem.path" ); if (gemPath == null) { gemPath = this.gemPath; } if ("default".equals( gemPath )) { env.remove( "GEM_PATH" ); env.remove( "GEM_HOME" ); gemPath = null; } if (gemPath != null) { env.put( "GEM_PATH", gemPath ); env.put( "GEM_HOME", gemPath ); } if (this.applicationEnvironment != null) { env.putAll( this.applicationEnvironment ); } return env; } /** * Set the interpreter output stream. * * @param outputStream * The output stream. */ public void setOutput(PrintStream outputStream) { this.outputStream = outputStream; } /** * Retrieve the interpreter output stream. * * @return The output stream. */ public PrintStream getOutput() { return this.outputStream; } /** * Set the interpreter error stream. * * @param errorStream * The error stream. */ public void setError(PrintStream errorStream) { this.errorStream = errorStream; } /** * Retrieve the interpreter error stream. * * @return The error stream. */ public PrintStream getError() { return this.errorStream; } /** * Set the interpreter load paths. * * <p> * Load paths may be either real filesystem paths or VFS URLs * </p> * * @param loadPaths * The list of load paths. */ public void setLoadPaths(List<String> loadPaths) { this.loadPaths = loadPaths; } /** * Retrieve the interpreter load paths. * * @return The list of load paths. */ public List<String> getLoadPaths() { return this.loadPaths; } public void create() { this.classCache = new ClassCache<Script>( getClassLoader() ); } public synchronized void destroy() { Set<Ruby> toDispose = new HashSet<Ruby>(); toDispose.addAll( this.undisposed ); for (Ruby ruby : toDispose ) { destroyInstance( ruby ); } this.undisposed.clear(); } public ClassCache getClassCache() { return this.classCache; } }
Catch errors on runtime initialization to prevent PoolManager#waitForMinimumFill() from looping forever [TORQUE-371]
components/base/base-core/src/main/java/org/torquebox/interp/core/RubyRuntimeFactoryImpl.java
Catch errors on runtime initialization to prevent PoolManager#waitForMinimumFill() from looping forever [TORQUE-371]
<ide><path>omponents/base/base-core/src/main/java/org/torquebox/interp/core/RubyRuntimeFactoryImpl.java <ide> } <ide> <ide> performRuntimeInitialization( runtime ); <del> return runtime; <add> } catch (Exception ex) { <add> log.error( "Failed to initialize runtime: ", ex ); <ide> } finally { <ide> if (runtime != null) { <ide> this.undisposed.add( runtime ); <ide> <ide> logRuntimeCreationComplete( config, contextInfo, startTime ); <ide> } <add> <add> return runtime; <ide> } <ide> <ide> private long logRuntimeCreationStart(RubyInstanceConfig config, String contextInfo) {
JavaScript
mpl-2.0
d5e0d6965ea68e998f6fca35964ea6cbef50c98c
0
pmkary/braver,diasdavid/browser-laptop,darkdh/browser-laptop,pmkary/braver,jonathansampson/browser-laptop,Sh1d0w/browser-laptop,pmkary/braver,willy-b/browser-laptop,manninglucas/browser-laptop,Sh1d0w/browser-laptop,timborden/browser-laptop,dcposch/browser-laptop,manninglucas/browser-laptop,manninglucas/browser-laptop,darkdh/browser-laptop,manninglucas/browser-laptop,luixxiul/browser-laptop,MKuenzi/browser-laptop,pmkary/braver,willy-b/browser-laptop,darkdh/browser-laptop,diasdavid/browser-laptop,luixxiul/browser-laptop,jonathansampson/browser-laptop,MKuenzi/browser-laptop,darkdh/browser-laptop,MKuenzi/browser-laptop,diasdavid/browser-laptop,jonathansampson/browser-laptop,dcposch/browser-laptop,diasdavid/browser-laptop,dcposch/browser-laptop,dcposch/browser-laptop,willy-b/browser-laptop,luixxiul/browser-laptop,Sh1d0w/browser-laptop,timborden/browser-laptop,MKuenzi/browser-laptop,timborden/browser-laptop,Sh1d0w/browser-laptop,luixxiul/browser-laptop,timborden/browser-laptop,willy-b/browser-laptop,jonathansampson/browser-laptop
var VersionInfo = require('./lib/versionInfo') var execute = require('./lib/execute') const isWindows = process.platform === 'win32' const isDarwin = process.platform === 'darwin' const arch = 'x64' const buildDir = 'Brave-' + process.platform + '-' + arch var appIcon if (isWindows) { appIcon = 'res/app.ico' } else if (isDarwin) { appIcon = 'res/app.icns' } else { appIcon = 'res/app.png' } var env = { NODE_ENV: 'production' } var cmds = ['echo cleaning up target...'] if (isWindows) { cmds = cmds.concat([ '(if exist ' + buildDir + ' rmdir /s /q ' + buildDir + ')', '(if exist dist rmdir /s /q dist)', ]) } else { cmds = cmds.concat([ 'rm -rf ' + buildDir, 'rm -f dist/*.dmg dist/*.nupkg dist/*.exe dist/*.msi dist/RELEASES dist/*.zip' ]) } cmds = cmds.concat([ 'echo done', 'echo starting build...' ]) console.log('Building version ' + VersionInfo.braveVersion + ' in ' + buildDir + ' with Electron ' + VersionInfo.electronVersion) cmds = cmds.concat([ '"./node_modules/.bin/webpack"', 'npm run checks', 'node ./node_modules/electron-packager/cli.js . Brave' + ' --overwrite' + ' --ignore="electron-download|electron-rebuild|electron-packager|electron-builder|electron-prebuilt|electron-rebuild|babel$|babel-(?!polyfill|regenerator-runtime)"' + ' --platform=' + process.platform + ' --arch=' + arch + ' --version=' + VersionInfo.electronVersion + ' --icon=' + appIcon + ' --asar=true' + ' --app-version=' + VersionInfo.braveVersion + ' --build-version=' + VersionInfo.electronVersion + ' --protocol="http" --protocol-name="HTTP Handler"' + ' --protocol="https" --protocol-name="HTTPS Handler"' + ' --version-string.CompanyName=\"Brave Inc.\"' + ' --version-string.ProductName=\"Brave\"' + ' --version-string.Copyright=\"Copyright 2016, Brave Inc.\"' + ' --version-string.FileDescription=\"Brave\"' ]) execute(cmds, env, console.log.bind(null, 'done'))
tools/buildPackage.js
var VersionInfo = require('./lib/versionInfo') var execute = require('./lib/execute') const isWindows = process.platform === 'win32' const isDarwin = process.platform === 'darwin' const arch = 'x64' const buildDir = 'Brave-' + process.platform + '-' + arch var appIcon if (isWindows) { appIcon = 'res/app.ico' } else if (isDarwin) { appIcon = 'res/app.icns' } else { appIcon = 'res/app.png' } var env = { NODE_ENV: 'production' } var cmds = ['echo cleaning up target...'] if (isWindows) { cmds = cmds.concat([ '(if exist ' + buildDir + ' rmdir /s /q ' + buildDir + ')', '(if exist dist\*.dmg del /q dist\*.dmg)', '(if exist dist\*.nupkg del /q dist\*.nupkg)', '(if exist dist\*.exe del /q dist\*.exe)', '(if exist dist\*.msi del /q dist\*.msi)', '(if exist dist\RELEASES del /q dist\RELEASES)', '(if exist dist\*.zip del /q dist\*.zip)' ]) } else { cmds = cmds.concat([ 'rm -rf ' + buildDir, 'rm -f dist/*.dmg dist/*.nupkg dist/*.exe dist/*.msi dist/RELEASES dist/*.zip' ]) } cmds = cmds.concat([ 'echo done', 'echo starting build...' ]) console.log('Building version ' + VersionInfo.braveVersion + ' in ' + buildDir + ' with Electron ' + VersionInfo.electronVersion) cmds = cmds.concat([ '"./node_modules/.bin/webpack"', 'npm run checks', 'node ./node_modules/electron-packager/cli.js . Brave' + ' --overwrite' + ' --ignore="electron-download|electron-rebuild|electron-packager|electron-builder|electron-prebuilt|electron-rebuild|babel$|babel-(?!polyfill|regenerator-runtime)"' + ' --platform=' + process.platform + ' --arch=' + arch + ' --version=' + VersionInfo.electronVersion + ' --icon=' + appIcon + ' --asar=true' + ' --app-version=' + VersionInfo.braveVersion + ' --build-version=' + VersionInfo.electronVersion + ' --protocol="http" --protocol-name="HTTP Handler"' + ' --protocol="https" --protocol-name="HTTPS Handler"' + ' --version-string.CompanyName=\"Brave Inc.\"' + ' --version-string.ProductName=\"Brave\"' + ' --version-string.Copyright=\"Copyright 2016, Brave Inc.\"' + ' --version-string.FileDescription=\"Brave\"' ]) execute(cmds, env, console.log.bind(null, 'done'))
Fix Windows including dist inside of it Auditors: da39a3ee5e6b4b0d3255bfef95601890afd80709@aekeus
tools/buildPackage.js
Fix Windows including dist inside of it
<ide><path>ools/buildPackage.js <ide> if (isWindows) { <ide> cmds = cmds.concat([ <ide> '(if exist ' + buildDir + ' rmdir /s /q ' + buildDir + ')', <del> '(if exist dist\*.dmg del /q dist\*.dmg)', <del> '(if exist dist\*.nupkg del /q dist\*.nupkg)', <del> '(if exist dist\*.exe del /q dist\*.exe)', <del> '(if exist dist\*.msi del /q dist\*.msi)', <del> '(if exist dist\RELEASES del /q dist\RELEASES)', <del> '(if exist dist\*.zip del /q dist\*.zip)' <add> '(if exist dist rmdir /s /q dist)', <ide> ]) <ide> } else { <ide> cmds = cmds.concat([
Java
apache-2.0
4f351ff8f7b065d5875bfcee8e02b76c06b1e274
0
rkboyce/DomeoClient,rkboyce/DomeoClient,rkboyce/DomeoClient
package org.mindinformatics.gwt.domeo.plugins.annotation.persistence.service; import org.mindinformatics.gwt.domeo.model.persistence.ontologies.IDomeoOntology; import org.mindinformatics.gwt.domeo.plugins.annotation.persistence.model.JsAnnotationSetSummary; import org.mindinformatics.gwt.domeo.plugins.annotation.persistence.model.JsDocumentAnnotationSummary; import org.mindinformatics.gwt.domeo.plugins.persistence.json.marshalling.JsoAnnotationSetSummary; import org.mindinformatics.gwt.domeo.plugins.persistence.json.model.JsAnnotationSet; import com.google.gwt.core.client.JsArray; import com.google.gwt.i18n.client.DateTimeFormat; /** * @author Paolo Ciccarese <[email protected]> */ public class AnnotationPersistenceServiceFacade { public static final String ALLOW_MINE = "Only my annotation"; public static final String ALLOW_GROUPS = "Annotation from my groups"; public static final String ALLOW_PUBLIC = "Public annotation"; DateTimeFormat fmt = DateTimeFormat.getFormat("yyyy.MM.dd HH:mm:ss Z"); private final native JsArray<JsAnnotationSetSummary> asArrayOfAnnotationSetSummaries(String json) /*-{ return eval(json); }-*/; private final native JsArray<JsAnnotationSet> asArrayOfAnnotationSets(String json) /*-{ return JSON.parse(json); }-*/; private final native JsArray<JsoAnnotationSetSummary> asArrayOfAnnotationSetSummaries2(String json) /*-{ return JSON.parse(json); }-*/; private final native JsArray<JsDocumentAnnotationSummary> asArrayOfDocumentAnnotationSummaries(String json) /*-{ return eval(json); }-*/; /** * Given a specific url, it returns all the available accessible * annotation for the given user * @param url Url of the document of interest * @param username User requesting the annotation */ public JsArray<JsAnnotationSetSummary> retrieveAnnotationByDocumentUrl(String url, String allowed, String username) { return retrieveAnnotationByDocumentUrl(url, allowed, false, username); } /* public JsArray<JsoAnnotationSetSummary> retrieveAnnotationSets(String url) { String json = "{}"; JsArray<JsoAnnotationSetSummary> sets = asArrayOfAnnotationSetSummaries2("[" + json+ "]"); return sets; } */ public JsArray<JsoAnnotationSetSummary> retrieveBibliographyByDocumentUrl(String url) { String json = "{}"; json = "{" + "\"@type\": \"" + IDomeoOntology.annotationSet + "\"," + "\"@id\": \"urn:domeoclient:uuid:20FEAAC7-9A44-41F6-8EF4-FC18EBCC35DE\","+ "\"rdfs:label\": \"Bibliography\"," + "\"dct:description\": \"Bibliographic Set\"," + "\"pav:lineageUri\": \"\"," + "\"domeo_localId\": \"2\", " + "\"ao:annotatesResource\": \"http://www.ncbi.nlm.nih.gov/pubmed/10679938\"," + "\"pav:versionNumber\": \"\"," + "\"pav:previousVersion\": \"\"," + "\"pav:createdOn\": \"2012-09-25 16:32:15 -0400\"," + "\"pav:createdBy\": \"http://localhost:8080/Domeo/user/8a7036ee39fe0e590139fe0e98550000\"," + "\"pav:lastUpdatedOn\": \"\"," + "\"domeo_isLocked\": \"false\"," + "\"ao:item\": [" + "{" + "\"@type\": \"ao:Reference\"," + "\"@id\": \"urn:domeoclient:uuid:3043285E-EFD3-4445-BA43-B6A4AF1BEBF3\"," + "\"rdfs:label\": \"Reference\"," + "\"domeo:uuid\": \"3043285E-EFD3-4445-BA43-B6A4AF1BEBF3\"," + "\"domeo_localId\": \"0\"," + "\"domeo_saveAsNewVersion\": \"false\"," + "\"pav:versionNumber\": \"\"," + "\"pav:previousVersion\": \"\"," + "\"pav:createdOn\": \"09/25/12 4:32PM\"," + "\"ao:context\": [" + "\"http://www.ncbi.nlm.nih.gov/pubmed/10679938\""+ "],"+ "\"domeo:content\": {" + "\"@type\": \"org.mindinformatics.gwt.framework.model.references.MPublicationArticleReference\"," + "\"@id\": \"10.1002/(SICI)1098-1004(200003)15:3<228::AID-HUMU3>3.0.CO;2-9\"," + "\"title\": \"An update of the mutation spectrum of the survival motor neuron gene (SMN1) in autosomal recessive spinal muscular atrophy (SMA).\"," + "\"authorNames\": \"Wirth B\"," + "\"doi\": \"10.1002/(SICI)1098-1004(200003)15:3<228::AID-HUMU3>3.0.CO;2-9\"," + "\"pmid\": \"10679938\"," + "\"pmcid\": \"<unknown>\"," + "\"publicationInfo\": \"Human mutation. 2000 ;Vol 15 Issue 3 :228-37\"," + "\"creationDate\": \"<unknown>\"," + "\"publisher\": \"<unknown>\"" + "}" + "}" + "]" + "}"; JsArray<JsoAnnotationSetSummary> sets = asArrayOfAnnotationSetSummaries2("[" + json+ "]"); return sets; } public JsArray<JsoAnnotationSetSummary> retrieveAnnotationByDocumentUrl(String url) { String json = ""; if(true) { //url.equals("http://www.ncbi.nlm.nih.gov/pubmed/10679938")) { // json = // "{" + // "\"pav:versionNumber\": \"1\"," + // "\"domeo_number_items\": 1," + // "\"pav:lineageUri\": \"urn:domeoserver:uuid:06DF988C-33C0-453C-8BFC-D23E383CFE88\"," + // "\"pav:createdOn\": \"2012-09-25 11:34:26 -0400\"," + // "\"rdfs:label\": \"Default Set\"," + // "\"pav:createdBy\": { " + // "\"screenname\": \"Dr. John Doe\"," + // "\"foaf_first_name\": \"John\"," + // "\"foaf_last_name\": \"Doe\"" + // "}," + // "\"pav:lastSavedOn\": \"2012-09-25 11:34:27 -0400\"," + // "\"@id\": \"urn:domeoclient:uuid:07895920-4A47-42DE-9F0A-9A79AAA33CC7\"," + // "\"dct:description\": \"The default set is created automatically by Domeo when no other set is existing.\"" + // "}"; json = "[{\"rdfs:label\":\"EuroPMC \",\"domeo:mongoUuid\":\"uNUDohDhR7KMorsRSLR2GQ\",\"@type\":\"domeo:DiscussionSet\",\"ao:numberItems\":3,\"pav:createdBy\":{\"screenname\":\"Dr. John Doe\",\"foaf_first_name\":\"John\",\"uri\":\"4028808d4185489401418548e3ca0000\",\"foaf_last_name\":\"Doe\"},\"pav:versionNumber\":\"2\",\"pav:lastSavedOn\":\"2013-10-04 17:05:15 -0400\",\"pav:lineageUri\":\"urn:domeoserver:annotationset:8B90099D-4C8C-45F5-ADBA-83D5999F5FD8\",\"pav:previousVersion\":\"urn:domeoclient:uuid:166EDE94-E8A4-4DDF-AA61-CF584F4721ED\",\"dct:description\":\"asdfsdfa\",\"permissions:accessType\":\"urn:domeo:access:public\",\"@id\":\"urn:domeoserver:annotationset:76B1FE2E-5663-4C77-9A17-5A5BDCC08407\",\"pav:createdOn\":\"2013-10-04 17:04:59 -0400\"},{\"rdfs:label\":\"Default Set\",\"domeo:mongoUuid\":\"GSQFXihqRpeY7-QbihmzGw\",\"@type\":\"ao:AnnotationSet\",\"ao:numberItems\":3,\"pav:createdBy\":{\"screenname\":\"Dr. John Doe\",\"foaf_first_name\":\"John\",\"uri\":\"4028808d4185489401418548e3ca0000\",\"foaf_last_name\":\"Doe\"},\"pav:versionNumber\":\"2\",\"pav:lastSavedOn\":\"2013-10-04 17:04:41 -0400\",\"pav:lineageUri\":\"urn:domeoserver:annotationset:DF0ED7B2-7594-4F9E-AF16-0C0DD8DE7935\",\"pav:previousVersion\":\"urn:domeoclient:uuid:580BCB7B-3A2F-410A-B106-A64B7589C7A7\",\"dct:description\":\"The default set is created automatically by Domeo when no other set is existing.\",\"permissions:accessType\":\"urn:domeo:access:public\",\"@id\":\"urn:domeoserver:annotationset:386FCC96-3486-46EF-A06E-2472084610C1\",\"pav:createdOn\":\"2013-10-04 17:04:32 -0400\"}, " + "{\"rdfs:label\":\"EuroPMC \",\"domeo:mongoUuid\":\"uNUDohDhR7KMorsRSLR2GQ\",\"@type\":\"domeo:DiscussionSet\",\"ao:numberItems\":3,\"pav:createdBy\":{\"screenname\":\"Dr. John Doe\",\"foaf_first_name\":\"John\",\"uri\":\"4028808d4185489401418548e3ca0002\",\"foaf_last_name\":\"Doe\"},\"pav:versionNumber\":\"2\",\"pav:lastSavedOn\":\"2013-10-04 17:05:15 -0400\",\"pav:lineageUri\":\"urn:domeoserver:annotationset:8B90099D-4C8C-45F5-ADBA-83D5999F5FD8\",\"pav:previousVersion\":\"urn:domeoclient:uuid:166EDE94-E8A4-4DDF-AA61-CF584F4721ED\",\"dct:description\":\"asdfsdfa\",\"permissions:accessType\":\"urn:domeo:access:public\",\"@id\":\"urn:domeoserver:annotationset:76B1FE2E-5663-4C77-9A17-5A5BDCC08408\",\"pav:createdOn\":\"2013-10-04 17:04:59 -0400\"},{\"rdfs:label\":\"Default Set\",\"domeo:mongoUuid\":\"GSQFXihqRpeY7-QbihmzGw\",\"@type\":\"ao:AnnotationSet\",\"ao:numberItems\":3,\"pav:createdBy\":{\"screenname\":\"Dr. John Doe\",\"foaf_first_name\":\"John\",\"uri\":\"4028808d4185489401418548e3ca0000\",\"foaf_last_name\":\"Doe\"},\"pav:versionNumber\":\"2\",\"pav:lastSavedOn\":\"2013-10-04 17:04:41 -0400\",\"pav:lineageUri\":\"urn:domeoserver:annotationset:DF0ED7B2-7594-4F9E-AF16-0C0DD8DE7935\",\"pav:previousVersion\":\"urn:domeoclient:uuid:580BCB7B-3A2F-410A-B106-A64B7589C7A7\",\"dct:description\":\"The default set is created automatically by Domeo when no other set is existing.\",\"permissions:accessType\":\"urn:domeo:access:public\",\"@id\":\"urn:domeoserver:annotationset:386FCC96-3486-46EF-A06E-2472084610C2\",\"pav:createdOn\":\"2013-10-04 17:04:32 -0400\"}]"; } JsArray<JsoAnnotationSetSummary> sets = asArrayOfAnnotationSetSummaries2(json); return sets; } /** * Given a specific url, it returns all the available accessible * annotation for the given user. This call also allows to extend * the request to documents with other urls that however match * some of the available document identifiers. * @param url Url of the document of interest * @param extend If true, the method will extend the request to * other documents that share an id with the requested one * @param username User requesting the annotation */ JsArray<JsAnnotationSetSummary> retrieveAnnotationByDocumentUrl(String url, String allowed, boolean extend, String username) { String json = "{}"; if(allowed.equals(AnnotationPersistenceServiceFacade.ALLOW_MINE)) { json = "{"+ "\"uuid\": \"ABC1\"," + "\"versionNumber\": \"1\"," + "\"label\": \"Set di prova\","+ "\"description\": \"My description\","+ "\"createdOn\": \"1996.07.10 15:08:56 -0500\","+ "\"createdBy\": \" Dr. Paolo Ciccarese\","+ "\"createdByUrl\": \" http://www.paolociccarese.info \","+ "\"lastSavedOn\": \"1996.07.10 15:08:56 -0500\","+ "\"isLocked\": true,"+ "\"numberOfAnnotationItems\": 4"+ "},"+ "{"+ "\"uuid\": \"ABC2\"," + "\"versionNumber\": \"2\"," + "\"previousVersion\": \"ABC3\"," + "\"label\": \"Set di prova 2\","+ "\"description\": \"My description 2\","+ "\"createdOn\": \"1998.07.10 15:08:56 -0500\","+ "\"createdBy\": \" Dr. Paolo Ciccarese\","+ "\"createdByUrl\": \" http://www.paolociccarese.info \","+ "\"lastSavedOn\": \"1998.07.10 15:08:56 -0500\","+ "\"isLocked\": false,"+ "\"numberOfAnnotationItems\": 4"+ "},"; } else if(allowed.equals(AnnotationPersistenceServiceFacade.ALLOW_GROUPS)) { json = "{"+ "\"uuid\": \"ABC1\"," + "\"versionNumber\": \"1\"," + "\"label\": \"Set di prova\","+ "\"description\": \"My description\","+ "\"createdOn\": \"1996.07.10 15:08:56 -0500\","+ "\"createdBy\": \" John Doe\","+ "\"createdByUrl\": \" http://www.example.com \","+ "\"lastSavedOn\": \"1996.07.10 15:08:56 -0500\","+ "\"isLocked\": true,"+ "\"numberOfAnnotationItems\": 3"+ "},"+ "{"+ "\"uuid\": \"ABC1\"," + "\"versionNumber\": \"1\"," + "\"label\": \"Set di prova\","+ "\"description\": \"My description\","+ "\"createdOn\": \"1996.07.10 15:08:56 -0500\","+ "\"createdBy\": \" Jenny Doe\","+ "\"createdByUrl\": \" http://www.example.com \","+ "\"lastSavedOn\": \"1996.07.10 15:08:56 -0500\","+ "\"isLocked\": true,"+ "\"numberOfAnnotationItems\": 4"+ "},"+ "{"+ "\"uuid\": \"ABC2\"," + "\"versionNumber\": \"2\"," + "\"previousVersion\": \"ABC3\"," + "\"label\": \"Set di prova 2\","+ "\"description\": \"My description 2\","+ "\"createdOn\": \"1998.07.10 15:08:56 -0500\","+ "\"createdBy\": \" John Doe\","+ "\"createdByUrl\": \" http://www.example.com \","+ "\"lastSavedOn\": \"1998.07.10 15:08:56 -0500\","+ "\"isLocked\": false,"+ "\"numberOfAnnotationItems\": 10"+ "},"; } else if(allowed.equals(AnnotationPersistenceServiceFacade.ALLOW_PUBLIC)) { json = "{"+ "\"uuid\": \"ABC1\"," + "\"versionNumber\": \"1\"," + "\"label\": \"Euro PMC\","+ "\"description\": \"My description\","+ "\"createdOn\": \"1996.07.10 15:08:56 -0500\","+ "\"createdBy\": \" Euro PMC\","+ "\"createdByUrl\": \" http://www.example.com \","+ "\"lastSavedOn\": \"1996.07.10 15:08:56 -0500\","+ "\"isLocked\": true,"+ "\"numberOfAnnotationItems\": 1"+ "},"+ "{"+ "\"uuid\": \"ABC2\"," + "\"versionNumber\": \"2\"," + "\"previousVersion\": \"ABC3\"," + "\"label\": \"Set di prova 2\","+ "\"description\": \"My description 2\","+ "\"createdOn\": \"1998.07.10 15:08:56 -0500\","+ "\"createdBy\": \" Johnny Deep\","+ "\"createdByUrl\": \" http://www.example.com \","+ "\"lastSavedOn\": \"1998.07.10 15:08:56 -0500\","+ "\"isLocked\": false,"+ "\"numberOfAnnotationItems\": 8"+ "},"+ "{"+ "\"uuid\": \"ABC1\"," + "\"versionNumber\": \"1\"," + "\"label\": \"Set di prova\","+ "\"description\": \"My description\","+ "\"createdOn\": \"1996.07.10 15:08:56 -0500\","+ "\"createdBy\": \" Johnny Smith\","+ "\"createdByUrl\": \" http://www.example.com \","+ "\"lastSavedOn\": \"1996.07.10 15:08:56 -0500\","+ "\"isLocked\": true,"+ "\"numberOfAnnotationItems\": 2"+ "},"+ "{"+ "\"uuid\": \"ABC2\"," + "\"versionNumber\": \"2\"," + "\"previousVersion\": \"ABC3\"," + "\"label\": \"Set di prova 2\","+ "\"description\": \"My description 2\","+ "\"createdOn\": \"1998.07.10 15:08:56 -0500\","+ "\"createdBy\": \" Johnny Smith\","+ "\"createdByUrl\": \" http://www.example.com \","+ "\"lastSavedOn\": \"1998.07.10 15:08:56 -0500\","+ "\"isLocked\": false,"+ "\"numberOfAnnotationItems\": 8"+ "},"+ "{"+ "\"uuid\": \"ABC1\"," + "\"versionNumber\": \"1\"," + "\"label\": \"Set di prova\","+ "\"description\": \"My description\","+ "\"createdOn\": \"1996.07.10 15:08:56 -0500\","+ "\"createdBy\": \" Johnny Deep\","+ "\"createdByUrl\": \" http://www.example.com \","+ "\"lastSavedOn\": \"1996.07.10 15:08:56 -0500\","+ "\"isLocked\": true,"+ "\"numberOfAnnotationItems\": 2"+ "},"+ "{"+ "\"uuid\": \"ABC2\"," + "\"versionNumber\": \"2\"," + "\"previousVersion\": \"ABC3\"," + "\"label\": \"Set di prova 2\","+ "\"description\": \"My description 2\","+ "\"createdOn\": \"1998.07.10 15:08:56 -0500\","+ "\"createdBy\": \" Johnny Deep\","+ "\"createdByUrl\": \" http://www.example.com \","+ "\"lastSavedOn\": \"1998.07.10 15:08:56 -0500\","+ "\"isLocked\": false,"+ "\"numberOfAnnotationItems\": 8"+ "},"+ "{"+ "\"uuid\": \"ABC1\"," + "\"versionNumber\": \"1\"," + "\"label\": \"Set di prova\","+ "\"description\": \"My description\","+ "\"createdOn\": \"1996.07.10 15:08:56 -0500\","+ "\"createdBy\": \" Johnny Smith\","+ "\"createdByUrl\": \" http://www.example.com \","+ "\"lastSavedOn\": \"1996.07.10 15:08:56 -0500\","+ "\"isLocked\": true,"+ "\"numberOfAnnotationItems\": 2"+ "},"+ "{"+ "\"uuid\": \"ABC2\"," + "\"versionNumber\": \"2\"," + "\"previousVersion\": \"ABC3\"," + "\"label\": \"Set di prova 2\","+ "\"description\": \"My description 2\","+ "\"createdOn\": \"1998.07.10 15:08:56 -0500\","+ "\"createdBy\": \" Johnny Smith\","+ "\"createdByUrl\": \" http://www.example.com \","+ "\"lastSavedOn\": \"1998.07.10 15:08:56 -0500\","+ "\"isLocked\": false,"+ "\"numberOfAnnotationItems\": 8"+ "},"; } JsArray<JsAnnotationSetSummary> sets = asArrayOfAnnotationSetSummaries("[" + json+ "]"); //for(int i=0; i<sets.length(); i++) { // Window.alert(""+fmt.format(sets.get(i).getCreatedOn())); //} return sets; } /** * Given a specific id, it returns all the available accessible * annotation for the given user. * @param id * @param idType * @param username */ public JsArray<JsAnnotationSet> retrieveAnnotationById(String id, String idType, String allowed, String username) { return retrieveAnnotationById(id, idType, allowed, false, username); } /** * Given a specific id, it returns all the available accessible * annotation for the given user. * @param id The id of the document * @param idType The type of id (Pubmed, Pmc....) * @param extend If true, the method will extend the request to * other documents that share an id with the requested one * @param username */ JsArray<JsAnnotationSet> retrieveAnnotationById(String id, String idType, String allowed, boolean extend, String username) { //String json = "[{\"pav:createdWith\": \"urn:domeo:software:id:Domeo-2.0alpha-040\",\"ao:item\": [{\"pav:createdWith\": \"urn:domeo:software:id:Domeo-2.0alpha-040\",\"rdfs:label\": \"Highlight\", \"pav:previousVersion\": \"\", \"@type\": \"ao:Qualifier\",\"domeo:belongsToSet\": \"urn:domeoclient:uuid:E7779F6D-4FFD-428C-82CF-42ED72740B06\",\"pav:createdBy\": \"urn:person:uuid:4028808d42d966140142d9666ece0000\", \"pav:lastSavedOn\": \"2013-12-12 14:43:49 -0500\",\"pav:versionNumber\": \"1\", \"@id\": \"urn:domeoclient:uuid:76CC060A-193D-45DF-B3EC-A5F10B159282\", \"ao:context\": [ { \"ao:hasSource\": \"http://en.wikipedia.org/wiki/Amyloid_precursor_protein\", \"@type\": \"ao:SpecificResource\", \"@id\": \"urn:domeoclient:uuid:3AF2A533-58BA-4A9C-88B2-83AF57B8E85E\",\"domeo_temp_localId\": \"1\", \"ao:hasSelector\": { \"ao:prefix\": \"An important but largely unmet challenge in understanding the mechanisms that govern the \",\"@type\": \"ao:PrefixSuffixTextSelector\", \"@id\": \"urn:domeoclient:uuid:3AF2A533-58BA-4A9C-88B2-83AF57B8E85E\",\"domeo_temp_localId\": \"1\", \"pav:createdOn\": \"2013-12-12 14:43:40 -0500\",\"ao:exact\": \"formation\", \"ao:suffix\": \" of specific organs is to decipher the complex and dynamic genetic programs exhibited by the diversity of cell types within the tissue of interest. \", \"domeo:uuid\": \"3AF2A533-58BA-4A9C-88B2-83AF57B8E85E\" } } ], \"ao:hasTopic\": [{ \"@id\": \"http://www.ebi.ac.uk/QuickGO/GTerm?id=GO:0009058\",\"rdfs:label\": \"biosynthetic process\", \"dct:description\": \"\", \"dct:source\": { \"@id\": \"http://www.ebi.ac.uk/QuickGO/\",\"rdfs:label\": \"Biological Process\" } } ], \"pav:createdOn\": \"2013-12-12 14:43:40 -0500\", \"pav:lineageUri\": \"urn:domeoserver:annotation:75EAD458-85A3-4879-887E-FD034E5FD52A\"} ], \"rdfs:label\": \"Default Set\",\"domeo:deleted\": \"false\", \"ao:annotatesResource\": \"http://www.ncbi.nlm.nih.gov/pmc/articles/PMC1366495/?report=classic\", \"domeo:resources\": [ { \"label\": \"An Integrated Strategy for Analyzing the Unique Developmental Programs of Different Myoblast Subtypes\", \"url\": \"http://www.ncbi.nlm.nih.gov/pmc/articles/PMC1366495/?report=classic\" }], \"@type\": \"ao:AnnotationSet\", \"pav:createdBy\": \"urn:person:uuid:4028808d42d966140142d9666ece0000\", \"pav:lastSavedOn\": \"2013-12-12 14:43:48 -0500\", \"pav:versionNumber\": \"1\",\"permissions:permissions\": {\"permissions:isLocked\": \"false\",\"permissions:accessType\": \"urn:domeo:access:public\" }, \"pav:lineageUri\": \"urn:domeoserver:annotationset:43A7C6D5-3884-4729-9E18-759752463598\", \"domeo:agents\": [{\"rdfs:label\": \"EuroPMC\", \"foafx:middlename\": \"\", \"foafx:lastname\": \"Doe\", \"@type\": \"foafx:Person\", \"foafx:homepage\": \"\",\"foafx:picture\": \"http://www.hcklab.org/images/me/paolo%20ciccarese-boston.jpg\",\"foafx:email\": \"[email protected]\",\"foafx:firstname\": \"John\",\"foafx:title\": \"\",\"@id\": \"urn:person:uuid:4028808d42d966140142d9666ece0000\", \"foafx:name\": \"Euro PMC\" },{ \"foafx:build\": \"040\" ,\"rdfs:label\": \"Domeo Annotation Toolkit\", \"@type\": \"foafx:Software\", \"foafx:homepage\": \"\",\"@id\": \"urn:domeo:software:id:Domeo-2.0alpha-040\",\"foafx:name\": \"Domeo Annotation Toolkit\",\"foafx:version\": \"2.0alpha\" } ],\"pav:previousVersion\": \"\", \"dct:description\": \"The default set is created automatically by Domeo when no other set is existing.\", \"@id\": \"urn:domeoclient:uuid:E7779F6D-4FFD-428C-82CF-42ED72740B06\", \"pav:createdOn\": \"2013-12-12 14:43:40 -0500\" } ]"; //String json = "[{\"pav:createdWith\":\"urn:domeo:software:id:Domeo-2.0alpha-040\",\"ao:item\":[{\"pav:createdWith\":\"urn:domeo:software:id:Domeo-2.0alpha-040\",\"rdfs:label\":\"SPL Annotation\",\"@type\":\"ao:SPLAnnotation\",\"domeo:belongsToSet\":\"urn:domeoclient:uuid:B2CBE747-9368-48D3-8AB8-0ECDA72850D1\",\"pav:createdBy\":\"urn:person:uuid:080e1430434f70e501434f711b6e0000\",\"pav:versionNumber\":\"1\",\"pav:lastSavedOn\":\"2014-01-22 17:35:57 -0500\",\"ao:context\":[{\"ao:hasSource\":\"http://127.0.0.1:8888/tests/SPL-annotation/Warfarin-ab047628-67d0-4a64-8d77-36b054969b44.html\",\"@type\":\"ao:SpecificResource\",\"@id\":\"urn:domeoclient:uuid:54CDC1E5-65E1-480A-A1C4-957BD32F7308\",\"domeo_temp_localId\":\"1\",\"ao:hasSelector\":{\"ao:prefix\":\"These highlights do not include all the information needed to use\",\"@type\":\"ao:PrefixSuffixTextSelector\",\"@id\":\"urn:domeoclient:uuid:54CDC1E5-65E1-480A-A1C4-957BD32F7308\",\"domeo_temp_localId\":\"1\",\"pav:createdOn\":\"2014-01-22 17:35:52 -0500\",\"ao:exact\":\" warfarin sodium safely and effectively. See full \",\"ao:suffix\":\"prescribing information for warfarin sodium.\",\"domeo:uuid\":\"54CDC1E5-65E1-480A-A1C4-957BD32F7308\"}}],\"ao:body\":[{\"sio:SIO_000563\":\"poc:PharmacokineticImpact\",\"@type\":\"poc:PharmacogenomicsStatement\",\"@id\":\"urn:linkedspls:uuid:38ACB655-54F2-43F3-8463-7AA1833725B5\",\"poc:PharmacokineticImpact\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#distribution-increase\"}],\"pav:lineageUri\":\"urn:domeoserver:annotation:A3653D48-231D-44CE-A309-B2C2F4311404\",\"pav:previousVersion\":\"\",\"@id\":\"urn:domeoclient:uuid:8E11483E-4C21-4188-AC79-B5BADA60ECE9\",\"pav:createdOn\":\"2014-01-22 17:35:52 -0500\"}],\"rdfs:label\":\"Default Set\",\"ao:annotatesResource\":\"http://127.0.0.1:8888/tests/SPL-annotation/Warfarin-ab047628-67d0-4a64-8d77-36b054969b44.html\",\"domeo:resources\":[{\"label\":\"WARFARIN SODIUM TABLET [AMERICAN HEALTH PACKAGING]\",\"url\":\"http://127.0.0.1:8888/tests/SPL-annotation/Warfarin-ab047628-67d0-4a64-8d77-36b054969b44.html\"}],\"@type\":\"ao:AnnotationSet\",\"pav:createdBy\":\"urn:person:uuid:080e1430434f70e501434f711b6e0000\",\"pav:lastSavedOn\":\"2014-01-22 17:35:57 -0500\",\"pav:versionNumber\":\"1\",\"permissions:permissions\":{\"permissions:isLocked\":\"false\",\"permissions:accessType\":\"urn:domeo:access:public\"},\"pav:lineageUri\":\"urn:domeoserver:annotationset:65B8CECA-8AFA-47C2-B14C-60ECB6FEC4F2\",\"domeo:agents\":[{\"rdfs:label\":\"boycer\",\"foafx:middlename\":\"\",\"foafx:lastname\":\"Boyce\",\"@type\":\"foafx:Person\",\"foafx:homepage\":\"\",\"foafx:picture\":\" http://www.hcklab.org/images/me/paolo%20ciccarese-boston.jpg\",\"foafx:email\":\"[email protected]\",\"foafx:firstname\":\"Richard\",\"foafx:title\":\"\",\"@id\":\"urn:person:uuid:080e1430434f70e501434f711b6e0000\",\"foafx:name\":\"boycer\"},{\"foafx:build\":\"040\",\"rdfs:label\":\"Domeo Annotation Toolkit\",\"@type\":\"foafx:Software\",\"foafx:homepage\":\"\",\"@id\":\"urn:domeo:software:id:Domeo-2.0alpha-040\",\"foafx:name\":\"Domeo Annotation Toolkit\",\"foafx:version\":\"2.0alpha\"}],\"pav:previousVersion\":\"\",\"dct:description\":\"The default set is created automatically by Domeo when no other set is existing.\",\"@id\":\"urn:domeoclient:uuid:B2CBE747-9368-48D3-8AB8-0ECDA72850D1\",\"pav:createdOn\":\"2014-01-22 17:35:44 -0500\"}]"; /* String json = "[{\"pav:createdWith\":\"urn:domeo:software:id:Domeo-2.0alpha-040\",\"ao:item\":[{\"pav:createdWith\":\"urn:domeo:software:id:Domeo-2.0alpha-040\",\"rdfs:label\":\"SPL Annotation\",\"@type\":\"ao:SPLAnnotation\",\"domeo:belongsToSet\":\"urn:domeoclient:uuid:B2CBE747-9368-48D3-8AB8-0ECDA72850D1\",\"pav:createdBy\":\"urn:person:uuid:080e1430434f70e501434f711b6e0000\",\"pav:versionNumber\":\"1\",\"pav:lastSavedOn\":\"2014-01-22 17:35:57 -0500\",\"ao:context\":[{\"ao:hasSource\":\"http://127.0.0.1:8888/tests/SPL-annotation/Warfarin-ab047628-67d0-4a64-8d77-36b054969b44.html\",\"@type\":\"ao:SpecificResource\",\"@id\":\"urn:domeoclient:uuid:54CDC1E5-65E1-480A-A1C4-957BD32F7308\",\"domeo_temp_localId\":\"1\",\"ao:hasSelector\":{\"ao:prefix\":\"These highlights do not include all the information needed to use\",\"@type\":\"ao:PrefixSuffixTextSelector\",\"@id\":\"urn:domeoclient:uuid:54CDC1E5-65E1-480A-A1C4-957BD32F7308\",\"domeo_temp_localId\":\"1\",\"pav:createdOn\":\"2014-01-22 17:35:52 -0500\",\"ao:exact\":\" warfarin sodium safely and effectively. See full \",\"ao:suffix\":\"prescribing information for warfarin sodium.\",\"domeo:uuid\":\"54CDC1E5-65E1-480A-A1C4-957BD32F7308\"}}],\"ao:body\":" + "[{\"@id\":\"urn:linkedspls:uuid:098EA66F-195E-4295-A394-AF04C5C075BC\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000628\":\"dailymed:pharmgxDrug\", \"dailymed:pharmgxDrug\":\"http://www.drugbank.ca/drugs/DB01238\", \"rdfs:label\":\"Aripiprazole\", \"dct:description\":\"The drug of interest.\"}," + "{\"@id\":\"urn:linkedspls:uuid:1ACE6E1C-1971-4EB1-A317-5F0BA90C915F\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000628\":\"dailymed:pharmgxBiomarker\", \"dailymed:pharmgxBiomarker1\":\"http://purl.obolibrary.org/obo/PR_000012621\", \"dailymed:pharmgxBiomarker2\":\"http://purl.obolibrary.org/obo/PR_000007204\", \"dailymed:pharmgxBiomarker\":\"http://purl.obolibrary.org/obo/PR_000007205\", \"rdfs:label\":\"ER and PgR_receptor\", \"dct:description\":\"The selected biomarker.\"}]" + ",\"pav:lineageUri\":\"urn:domeoserver:annotation:A3653D48-231D-44CE-A309-B2C2F4311404\",\"pav:previousVersion\":\"\",\"@id\":\"urn:domeoclient:uuid:8E11483E-4C21-4188-AC79-B5BADA60ECE9\",\"pav:createdOn\":\"2014-01-22 17:35:52 -0500\"}],\"rdfs:label\":\"Default Set\",\"ao:annotatesResource\":\"http://127.0.0.1:8888/tests/SPL-annotation/Warfarin-ab047628-67d0-4a64-8d77-36b054969b44.html\",\"domeo:resources\":[{\"label\":\"WARFARIN SODIUM TABLET [AMERICAN HEALTH PACKAGING]\",\"url\":\"http://127.0.0.1:8888/tests/SPL-annotation/Warfarin-ab047628-67d0-4a64-8d77-36b054969b44.html\"}],\"@type\":\"ao:AnnotationSet\",\"pav:createdBy\":\"urn:person:uuid:080e1430434f70e501434f711b6e0000\",\"pav:lastSavedOn\":\"2014-01-22 17:35:57 -0500\",\"pav:versionNumber\":\"1\",\"permissions:permissions\":{\"permissions:isLocked\":\"false\",\"permissions:accessType\":\"urn:domeo:access:public\"},\"pav:lineageUri\":\"urn:domeoserver:annotationset:65B8CECA-8AFA-47C2-B14C-60ECB6FEC4F2\",\"domeo:agents\":[{\"rdfs:label\":\"boycer\",\"foafx:middlename\":\"\",\"foafx:lastname\":\"Boyce\",\"@type\":\"foafx:Person\",\"foafx:homepage\":\"\",\"foafx:picture\":\" http://www.hcklab.org/images/me/paolo%20ciccarese-boston.jpg\",\"foafx:email\":\"[email protected]\",\"foafx:firstname\":\"Richard\",\"foafx:title\":\"\",\"@id\":\"urn:person:uuid:080e1430434f70e501434f711b6e0000\",\"foafx:name\":\"boycer\"},{\"foafx:build\":\"040\",\"rdfs:label\":\"Domeo Annotation Toolkit\",\"@type\":\"foafx:Software\",\"foafx:homepage\":\"\",\"@id\":\"urn:domeo:software:id:Domeo-2.0alpha-040\",\"foafx:name\":\"Domeo Annotation Toolkit\",\"foafx:version\":\"2.0alpha\"}],\"pav:previousVersion\":\"\",\"dct:description\":\"The default set is created automatically by Domeo when no other set is existing.\",\"@id\":\"urn:domeoclient:uuid:B2CBE747-9368-48D3-8AB8-0ECDA72850D1\",\"pav:createdOn\":\"2014-01-22 17:35:44 -0500\"}]"; */ String json = "[{\"pav:createdWith\":\"urn:domeo:software:id:Domeo-2.0alpha-040\",\"ao:item\":[{\"pav:createdWith\":\"urn:domeo:software:id:Domeo-2.0alpha-040\",\"rdfs:label\":\"SPL Annotation\",\"@type\":\"ao:SPLAnnotation\",\"domeo:belongsToSet\":\"urn:domeoclient:uuid:B2CBE747-9368-48D3-8AB8-0ECDA72850D1\",\"pav:createdBy\":\"urn:person:uuid:080e1430434f70e501434f711b6e0000\",\"pav:versionNumber\":\"1\",\"pav:lastSavedOn\":\"2014-01-22 17:35:57 -0500\",\"ao:context\":[{\"ao:hasSource\":\"http://127.0.0.1:8888/tests/SPL-annotation/Warfarin-ab047628-67d0-4a64-8d77-36b054969b44.html\",\"@type\":\"ao:SpecificResource\",\"@id\":\"urn:domeoclient:uuid:54CDC1E5-65E1-480A-A1C4-957BD32F7308\",\"domeo_temp_localId\":\"1\",\"ao:hasSelector\":{\"ao:prefix\":\"These highlights do not include all the information needed to use\",\"@type\":\"ao:PrefixSuffixTextSelector\",\"@id\":\"urn:domeoclient:uuid:54CDC1E5-65E1-480A-A1C4-957BD32F7308\",\"domeo_temp_localId\":\"1\",\"pav:createdOn\":\"2014-01-22 17:35:52 -0500\",\"ao:exact\":\" warfarin sodium safely and effectively. See full \",\"ao:suffix\":\"prescribing information for warfarin sodium.\",\"domeo:uuid\":\"54CDC1E5-65E1-480A-A1C4-957BD32F7308\"}}],\"ao:body\":" + "[{\"@id\":\"urn:linkedspls:uuid:542ADED5-899D-46AC-966A-F35B9BDA0723\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000628\":\"dailymed:HGNCGeneSymbol\", \"dailymed:HGNCGeneSymbol\":\"http://bio2rdf.org/hgnc:11929\", \"rdfs:label\":\"BAFF/TNFSF13B\", \"dct:description\":\"The selected HGNCGeneSymbol.\"}," + "{\"@id\":\"urn:linkedspls:uuid:51BF9FB2-0876-4618-953D-3E4279563F5A\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000628\":\"dailymed:ConcomitantMedicationOfConcern\", \"dailymed:ConcomitantMedicationOfConcern\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#concomitant-medication-concern\", \"rdfs:label\":\"Concomitant medication concern\", \"dct:description\":\"A concomitant medication of concern is mentioned.\"}," + "{\"@id\":\"urn:linkedspls:uuid:E20B7EDA-2D14-402B-BE68-8B6F35E262A5\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000563\":\"poc:VariantFrequency\", \"poc:VariantFrequency\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#population-frequency-mentioned\", \"rdfs:label\":\"Variant Frequency\", \"dct:description\":\"The frequency or proportion at which a variant occurs in a specific population is mentioned.\"}," + "{\"@id\":\"urn:linkedspls:uuid:AC117431-47DD-4A0A-B5A6-0AEA9D425094\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000628\":\"dailymed:ActiveMoiety\", \"dailymed:ActiveMoiety\":\"http://dbmi-icode-01.dbmi.pitt.edu/linkedSPLs/vocab/resource/ingredient-active\", \"rdfs:label\":\"Active ingredient\", \"dct:description\":\"the ingredient is active\"}," + "{\"@id\":\"urn:linkedspls:uuid:124D795F-C313-47D3-B601-D230D256BAFE\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000111\":\"BOXED WARNING (34066-1)\", \"poc:productLabelSection\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#BOXED WARNING (34066-1)\", \"rdfs:label\":\"SPL Section \", \"dct:description\":\"The section of the label where pharmacists identify clinical pharmgx statements\"}," + "{\"@id\":\"urn:linkedspls:uuid:8A6D2C77-41B6-40C1-8D9B-392E637480BB\", \"@type\":\"poc:PharmacogenomicsStatement\", \"poc:Comment\":\"It's a good annotation\", \"rdfs:label\":\"Comment\"}," + "{\"@id\":\"urn:linkedspls:uuid:9961B2F2-5DF2-48EF-972C-1534384C5CA2\", \"@type\":\"poc:PharmacogenomicsStatement\", \"ncit:Alleles\":\"test alleles\", \"rdfs:label\":\"Alleles\"}," + "{\"@id\":\"urn:linkedspls:uuid:72C0C502-9AFF-4425-A9DC-2361F1DABF3D\", \"@type\":\"poc:PharmacogenomicsStatement\", \"poc:MedicalCondition\":\"test medical conditions\", \"rdfs:label\":\"MedicalCondition\"}," + "{\"@id\":\"urn:linkedspls:uuid:72B35C27-DEA2-4379-B909-63169841CC4E\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000628\":\"poc:Variant\", \"poc:Variant\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#\", \"rdfs:label\":\"intermediate-metabolizer\", \"dct:description\":\"A specific variant of a gene, including the wild-type allele, or a patient phenotype\"}," + "{\"@id\":\"urn:linkedspls:uuid:377C76E3-6129-479F-8D92-CD000415943E\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000338\":\"poc:TestResult\", \"poc:TestResult\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#gene-expression-level-high\", \"rdfs:label\":\"gene-expression-level-high\", \"dct:description\":\"A test result that is somehow related to the biomarker.\"}," + "{\"@id\":\"urn:linkedspls:uuid:FFC8415C-1E46-4AC4-88AB-DD61F5C9CB58\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000563\":\"poc:MonitoringRecommendation\", \"poc:MonitoringRecommendation\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#change-monitoring-strategy\", \"rdfs:label\":\"Change monitoring strategy\", \"dct:description\":\"A strategy changed monitoring recommendation is related to the pharmacogenomic biomarker.\"}," + "{\"@id\":\"urn:linkedspls:uuid:C1898D67-D43C-48C0-B884-6394D658F386\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000563\":\"poc:TestRecommendation\", \"poc:TestRecommendation\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#take-note-that-tests-are-avaliable\", \"rdfs:label\":\"Take note that tests are avaliable\", \"dct:description\":\"Testing related to the pharmacogenomic biomarker is avaliable.\"}," + "{\"@id\":\"urn:linkedspls:uuid:1041808D-00AE-4B84-9B71-16FD1336DD16\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000563\":\"poc:PharmacokineticImpact\", \"poc:PharmacokineticImpact\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#absorption-increase\", \"rdfs:label\":\"Absorption Increase\", \"dct:description\":\"The pharmacogenomic biomarker is associated with a increase in absorption of the drug.\"}," + "{\"@id\":\"urn:linkedspls:uuid:66FB7E34-DCD6-4B2B-8C85-D6983C10ABBC\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000563\":\"poc:PharmacodynamicImpact\", \"poc:PharmacodynamicImpact\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#drug-toxicity-risk-increased\", \"rdfs:label\":\"Increased Toxicity Risk\", \"dct:description\":\"The pharmacogenomic biomarker is associated with an increased risk of toxicity.\"}," + "{\"@id\":\"urn:linkedspls:uuid:B37E7F17-F662-4FA4-8F42-82B275708A37\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000563\":\"poc:DrugSelectionRecommendation\", \"poc:DrugSelectionRecommendation\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#change-in-route-of-admin\", \"rdfs:label\":\"Change in route of administration\", \"dct:description\":\"The pharmacogenomic biomarker is related to a recommendation to add change the route of administration for the drug.\"}," + "{\"@id\":\"urn:linkedspls:uuid:BEA29BD8-8E44-4C7F-87DB-A3C0377E422A\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000563\":\"poc:DoseSelectionRecommendation\", \"poc:DoseSelectionRecommendation\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#increase-from-recommended-baseline\", \"rdfs:label\":\"Increase from baseline\", \"dct:description\":\"The pharmacogenomic biomarker is related to a recommendation to increase the dose of the drug from the recommended baseline.\"},"+ "{\"@id\":\"urn:linkedspls:uuid:098EA66F-195E-4295-A394-AF04C5C075BC\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000628\":\"dailymed:pharmgxDrug\", \"dailymed:pharmgxDrug\":\"http://www.drugbank.ca/drugs/DB01238\", \"rdfs:label\":\"Aripiprazole\", \"dct:description\":\"The drug of interest.\"}," + "{\"@id\":\"urn:linkedspls:uuid:1ACE6E1C-1971-4EB1-A317-5F0BA90C915F\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000628\":\"dailymed:pharmgxBiomarker\", \"dailymed:pharmgxBiomarker1\":\"http://purl.obolibrary.org/obo/PR_000012621\", \"dailymed:pharmgxBiomarker2\":\"http://purl.obolibrary.org/obo/PR_000007204\", \"dailymed:pharmgxBiomarker\":\"http://purl.obolibrary.org/obo/PR_000007205\", \"rdfs:label\":\"ER and PgR_receptor\", \"dct:description\":\"The selected biomarker.\"}]" + ",\"pav:lineageUri\":\"urn:domeoserver:annotation:A3653D48-231D-44CE-A309-B2C2F4311404\",\"pav:previousVersion\":\"\",\"@id\":\"urn:domeoclient:uuid:8E11483E-4C21-4188-AC79-B5BADA60ECE9\",\"pav:createdOn\":\"2014-01-22 17:35:52 -0500\"}],\"rdfs:label\":\"Default Set\",\"ao:annotatesResource\":\"http://127.0.0.1:8888/tests/SPL-annotation/Warfarin-ab047628-67d0-4a64-8d77-36b054969b44.html\",\"domeo:resources\":[{\"label\":\"WARFARIN SODIUM TABLET [AMERICAN HEALTH PACKAGING]\",\"url\":\"http://127.0.0.1:8888/tests/SPL-annotation/Warfarin-ab047628-67d0-4a64-8d77-36b054969b44.html\"}],\"@type\":\"ao:AnnotationSet\",\"pav:createdBy\":\"urn:person:uuid:080e1430434f70e501434f711b6e0000\",\"pav:lastSavedOn\":\"2014-01-22 17:35:57 -0500\",\"pav:versionNumber\":\"1\",\"permissions:permissions\":{\"permissions:isLocked\":\"false\",\"permissions:accessType\":\"urn:domeo:access:public\"},\"pav:lineageUri\":\"urn:domeoserver:annotationset:65B8CECA-8AFA-47C2-B14C-60ECB6FEC4F2\",\"domeo:agents\":[{\"rdfs:label\":\"boycer\",\"foafx:middlename\":\"\",\"foafx:lastname\":\"Boyce\",\"@type\":\"foafx:Person\",\"foafx:homepage\":\"\",\"foafx:picture\":\" http://www.hcklab.org/images/me/paolo%20ciccarese-boston.jpg\",\"foafx:email\":\"[email protected]\",\"foafx:firstname\":\"Richard\",\"foafx:title\":\"\",\"@id\":\"urn:person:uuid:080e1430434f70e501434f711b6e0000\",\"foafx:name\":\"boycer\"},{\"foafx:build\":\"040\",\"rdfs:label\":\"Domeo Annotation Toolkit\",\"@type\":\"foafx:Software\",\"foafx:homepage\":\"\",\"@id\":\"urn:domeo:software:id:Domeo-2.0alpha-040\",\"foafx:name\":\"Domeo Annotation Toolkit\",\"foafx:version\":\"2.0alpha\"}],\"pav:previousVersion\":\"\",\"dct:description\":\"The default set is created automatically by Domeo when no other set is existing.\",\"@id\":\"urn:domeoclient:uuid:B2CBE747-9368-48D3-8AB8-0ECDA72850D1\",\"pav:createdOn\":\"2014-01-22 17:35:44 -0500\"}]"; /* String json = "[{\"pav:createdWith\":\"urn:domeo:software:id:Domeo-2.0alpha-040\",\"ao:item\":[{\"pav:createdWith\":\"urn:domeo:software:id:Domeo-2.0alpha-040\",\"rdfs:label\":\"SPL Annotation\",\"@type\":\"ao:SPLAnnotation\",\"domeo:belongsToSet\":\"urn:domeoclient:uuid:B2CBE747-9368-48D3-8AB8-0ECDA72850D1\",\"pav:createdBy\":\"urn:person:uuid:080e1430434f70e501434f711b6e0000\",\"pav:versionNumber\":\"1\",\"pav:lastSavedOn\":\"2014-01-22 17:35:57 -0500\",\"ao:context\":[{\"ao:hasSource\":\"http://127.0.0.1:8888/tests/SPL-annotation/Warfarin-ab047628-67d0-4a64-8d77-36b054969b44.html\",\"@type\":\"ao:SpecificResource\",\"@id\":\"urn:domeoclient:uuid:54CDC1E5-65E1-480A-A1C4-957BD32F7308\",\"domeo_temp_localId\":\"1\",\"ao:hasSelector\":{\"ao:prefix\":\"These highlights do not include all the information needed to use\",\"@type\":\"ao:PrefixSuffixTextSelector\",\"@id\":\"urn:domeoclient:uuid:54CDC1E5-65E1-480A-A1C4-957BD32F7308\",\"domeo_temp_localId\":\"1\",\"pav:createdOn\":\"2014-01-22 17:35:52 -0500\",\"ao:exact\":\" warfarin sodium safely and effectively. See full \",\"ao:suffix\":\"prescribing information for warfarin sodium.\",\"domeo:uuid\":\"54CDC1E5-65E1-480A-A1C4-957BD32F7308\"}}],\"ao:body\":" + "[{\"@id\":\"urn:linkedspls:uuid:0E2BA97B-A180-4547-B775-3F0110E97284\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000338\":\"poc:productLabelSelection\", \"poc:productLabelSelection\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#\", \"rdfs:label\":\"CLINICAL PHARMACOLOGY (34090-1)\", \"dct:description\":\"what section of the label Pharmacists identify clinical pharmgx statements\"}," + "{\"@id\":\"urn:linkedspls:uuid:07EAA91F-B199-4565-8B13-543830A2CE25\", \"@type\":\"poc:PharmacogenomicsStatement\", \"poc:Comment\":\"test comment\", \"rdfs:label\":\"Comment\"}," + "{\"@id\":\"urn:linkedspls:uuid:7FD1AF25-ABBD-4909-B648-3D549517095E\", \"@type\":\"poc:PharmacogenomicsStatement\", \"poc:MedicalCondition\":\"test medical condition\", \"rdfs:label\":\"MedicalCondition\"}," + "{\"@id\":\"urn:linkedspls:uuid:5EF4FA92-8518-4532-ABA8-DB71FF9D2ADC\", \"@type\":\"poc:PharmacogenomicsStatement\", \"ncit:Alleles\":\"test alleles\", \"rdfs:label\":\"Alleles\"}," + "{\"@id\":\"urn:linkedspls:uuid:1055B4FD-6AC5-4718-B670-70A66B47D73D\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000628\":\"dailymed:ConcomitantMedicationOfConcern\", \"dailymed:ConcomitantMedicationOfConcern\":\"http://dbmi-icode-01.dbmi.pitt.edu/linkedSPLs/vocab/resource/concomitant-medication-concern\", \"rdfs:label\":\"Concomitant medication concern\", \"dct:description\":\"A concomitant medication of concern is mentioned.\"}," + "{\"@id\":\"urn:linkedspls:uuid:DE05922C-5327-4B28-BEBD-A6EE3CEF35B2\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000628\":\"dailymed:ActiveMoiety\", \"dailymed:ActiveMoiety\":\"http://dbmi-icode-01.dbmi.pitt.edu/linkedSPLs/vocab/resource/ingredient-active\", \"rdfs:label\":\"Active ingredient\", \"dct:description\":\"the ingredient is active\"}," + "{\"@id\":\"urn:linkedspls:uuid:A229674C-9899-474B-96D3-C37E8759C341\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000563\":\"poc:VariantFrequency\", \"poc:VariantFrequency\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#population-frequency-mentioned\", \"rdfs:label\":\"Variant Frequency\", \"dct:description\":\"The frequency or proportion at which a variant occurs in a specific population is mentioned.\"}," + "{\"@id\":\"urn:linkedspls:uuid:3F5EFB36-7B8B-4A3F-BFBA-725C36A1D74F\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000628\":\"dailymed:pharmgxDrug\", \"dailymed:pharmgxDrug\":\"http://fakeuri.org/Atomoxetine\", \"rdfs:label\":\"Arsenic_Trioxide\", \"dct:description\":\"The drug of interest.\"}," + "{\"@id\":\"urn:linkedspls:uuid:F2224CEF-E0DB-418F-ACF3-D3988D26775B\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000628\":\"dailymed:pharmgxBiomarker\", \"dailymed:pharmgxBiomarker\":\"http://fakeuri.org/CD25\", \"rdfs:label\":\"CD20_antigen\", \"dct:description\":\"The selected biomarker.\"}, " + "{\"@id\":\"urn:linkedspls:uuid:1AA7F9B3-F775-4397-BD31-F570BFAA582F\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000338\":\"poc:TestResult\", \"poc:TestResult\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#gene-SNP-positive\", \"rdfs:label\":\"gene-SNP-positive\", \"dct:description\":\"A test result that is somehow related to the biomarker.\"}," + "{\"@id\":\"urn:linkedspls:uuid:F12CFED5-0FB6-4715-85C0-280731AD2389\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000628\":\"poc:Variant\", \"poc:Variant\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#intermediate-metabolizer\", \"rdfs:label\":\"intermediate-metabolizer\", \"dct:description\":\"A specific variant of a gene, including the wild-type allele, or a patient phenotype\"}," + "{\"@id\":\"urn:linkedspls:uuid:CCB5DD68-8EBF-4B2A-BDA8-7AEE0076F6F2\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000563\":\"poc:MonitoringRecommendation\", \"poc:MonitoringRecommendation\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#recommended\", \"rdfs:label\":\"Recommended\", \"dct:description\":\"A recommended monitoring recommendation is related to the pharmacogenomic biomarker.\"}," + "{\"@id\":\"urn:linkedspls:uuid:02D1951E-D2F7-4564-8BED-C9B61C47AC69\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000563\":\"poc:TestRecommendation\", \"poc:TestRecommendation\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#required\", \"rdfs:label\":\"Required\", \"dct:description\":\"A required test is related to the biomarker.\"}," + "{\"@id\":\"urn:linkedspls:uuid:110D5162-B9B5-4F3F-B01A-506756CDEE5F\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000563\":\"poc:DoseSelectionRecommendation\", \"poc:DoseSelectionRecommendation\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#increase-from-recommended-baseline\", \"rdfs:label\":\"Increase from baseline\", \"dct:description\":\"The pharmacogenomic biomarker is related to a recommendation to increase the dose of the drug from the recommended baseline.\"}," + "{\"@id\":\"urn:linkedspls:uuid:03B92CE6-A8F5-4AF9-8A68-10F48D1542EB\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000563\":\"poc:DrugSelectionRecommendation\", \"poc:DrugSelectionRecommendation\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#alternative-recommended\", \"rdfs:label\":\"Alternative Recommended\", \"dct:description\":\"The pharmacogenomic biomarker is related to a recommendation to use an alternative drug.\"}," + "{\"@id\":\"urn:linkedspls:uuid:14FC9A6F-F105-4BF7-B270-D4CB3A9FD966\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000563\":\"poc:PharmacokineticImpact\", \"poc:PharmacokineticImpact\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#absorption-increase\", \"rdfs:label\":\"Absorption Increase\", \"dct:description\":\"The pharmacogenomic biomarker is associated with a increase in absorption of the drug.\"}," + "{\"@id\":\"urn:linkedspls:uuid:47B1922D-DAF0-430C-84E9-4EAB3766AF76\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000563\":\"poc:PharmacodynamicImpact\", \"poc:PharmacodynamicImpact\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#drug-efficacy-increased-from-baseline\", \"rdfs:label\":\"Increased Efficacy\", \"dct:description\":\"The pharmacogenomic biomarker is associated with an increase in the efficacy of the drug. \"}]" + ",\"pav:lineageUri\":\"urn:domeoserver:annotation:A3653D48-231D-44CE-A309-B2C2F4311404\",\"pav:previousVersion\":\"\",\"@id\":\"urn:domeoclient:uuid:8E11483E-4C21-4188-AC79-B5BADA60ECE9\",\"pav:createdOn\":\"2014-01-22 17:35:52 -0500\"}],\"rdfs:label\":\"Default Set\",\"ao:annotatesResource\":\"http://127.0.0.1:8888/tests/SPL-annotation/Warfarin-ab047628-67d0-4a64-8d77-36b054969b44.html\",\"domeo:resources\":[{\"label\":\"WARFARIN SODIUM TABLET [AMERICAN HEALTH PACKAGING]\",\"url\":\"http://127.0.0.1:8888/tests/SPL-annotation/Warfarin-ab047628-67d0-4a64-8d77-36b054969b44.html\"}],\"@type\":\"ao:AnnotationSet\",\"pav:createdBy\":\"urn:person:uuid:080e1430434f70e501434f711b6e0000\",\"pav:lastSavedOn\":\"2014-01-22 17:35:57 -0500\",\"pav:versionNumber\":\"1\",\"permissions:permissions\":{\"permissions:isLocked\":\"false\",\"permissions:accessType\":\"urn:domeo:access:public\"},\"pav:lineageUri\":\"urn:domeoserver:annotationset:65B8CECA-8AFA-47C2-B14C-60ECB6FEC4F2\",\"domeo:agents\":[{\"rdfs:label\":\"boycer\",\"foafx:middlename\":\"\",\"foafx:lastname\":\"Boyce\",\"@type\":\"foafx:Person\",\"foafx:homepage\":\"\",\"foafx:picture\":\" http://www.hcklab.org/images/me/paolo%20ciccarese-boston.jpg\",\"foafx:email\":\"[email protected]\",\"foafx:firstname\":\"Richard\",\"foafx:title\":\"\",\"@id\":\"urn:person:uuid:080e1430434f70e501434f711b6e0000\",\"foafx:name\":\"boycer\"},{\"foafx:build\":\"040\",\"rdfs:label\":\"Domeo Annotation Toolkit\",\"@type\":\"foafx:Software\",\"foafx:homepage\":\"\",\"@id\":\"urn:domeo:software:id:Domeo-2.0alpha-040\",\"foafx:name\":\"Domeo Annotation Toolkit\",\"foafx:version\":\"2.0alpha\"}],\"pav:previousVersion\":\"\",\"dct:description\":\"The default set is created automatically by Domeo when no other set is existing.\",\"@id\":\"urn:domeoclient:uuid:B2CBE747-9368-48D3-8AB8-0ECDA72850D1\",\"pav:createdOn\":\"2014-01-22 17:35:44 -0500\"}]"; */ JsArray<JsAnnotationSet> sets = asArrayOfAnnotationSets(json); return sets; } }
src/org/mindinformatics/gwt/domeo/plugins/annotation/persistence/service/AnnotationPersistenceServiceFacade.java
package org.mindinformatics.gwt.domeo.plugins.annotation.persistence.service; import org.mindinformatics.gwt.domeo.model.persistence.ontologies.IDomeoOntology; import org.mindinformatics.gwt.domeo.plugins.annotation.persistence.model.JsAnnotationSetSummary; import org.mindinformatics.gwt.domeo.plugins.annotation.persistence.model.JsDocumentAnnotationSummary; import org.mindinformatics.gwt.domeo.plugins.persistence.json.marshalling.JsoAnnotationSetSummary; import org.mindinformatics.gwt.domeo.plugins.persistence.json.model.JsAnnotationSet; import com.google.gwt.core.client.JsArray; import com.google.gwt.i18n.client.DateTimeFormat; /** * @author Paolo Ciccarese <[email protected]> */ public class AnnotationPersistenceServiceFacade { public static final String ALLOW_MINE = "Only my annotation"; public static final String ALLOW_GROUPS = "Annotation from my groups"; public static final String ALLOW_PUBLIC = "Public annotation"; DateTimeFormat fmt = DateTimeFormat.getFormat("yyyy.MM.dd HH:mm:ss Z"); private final native JsArray<JsAnnotationSetSummary> asArrayOfAnnotationSetSummaries(String json) /*-{ return eval(json); }-*/; private final native JsArray<JsAnnotationSet> asArrayOfAnnotationSets(String json) /*-{ return JSON.parse(json); }-*/; private final native JsArray<JsoAnnotationSetSummary> asArrayOfAnnotationSetSummaries2(String json) /*-{ return JSON.parse(json); }-*/; private final native JsArray<JsDocumentAnnotationSummary> asArrayOfDocumentAnnotationSummaries(String json) /*-{ return eval(json); }-*/; /** * Given a specific url, it returns all the available accessible * annotation for the given user * @param url Url of the document of interest * @param username User requesting the annotation */ public JsArray<JsAnnotationSetSummary> retrieveAnnotationByDocumentUrl(String url, String allowed, String username) { return retrieveAnnotationByDocumentUrl(url, allowed, false, username); } /* public JsArray<JsoAnnotationSetSummary> retrieveAnnotationSets(String url) { String json = "{}"; JsArray<JsoAnnotationSetSummary> sets = asArrayOfAnnotationSetSummaries2("[" + json+ "]"); return sets; } */ public JsArray<JsoAnnotationSetSummary> retrieveBibliographyByDocumentUrl(String url) { String json = "{}"; json = "{" + "\"@type\": \"" + IDomeoOntology.annotationSet + "\"," + "\"@id\": \"urn:domeoclient:uuid:20FEAAC7-9A44-41F6-8EF4-FC18EBCC35DE\","+ "\"rdfs:label\": \"Bibliography\"," + "\"dct:description\": \"Bibliographic Set\"," + "\"pav:lineageUri\": \"\"," + "\"domeo_localId\": \"2\", " + "\"ao:annotatesResource\": \"http://www.ncbi.nlm.nih.gov/pubmed/10679938\"," + "\"pav:versionNumber\": \"\"," + "\"pav:previousVersion\": \"\"," + "\"pav:createdOn\": \"2012-09-25 16:32:15 -0400\"," + "\"pav:createdBy\": \"http://localhost:8080/Domeo/user/8a7036ee39fe0e590139fe0e98550000\"," + "\"pav:lastUpdatedOn\": \"\"," + "\"domeo_isLocked\": \"false\"," + "\"ao:item\": [" + "{" + "\"@type\": \"ao:Reference\"," + "\"@id\": \"urn:domeoclient:uuid:3043285E-EFD3-4445-BA43-B6A4AF1BEBF3\"," + "\"rdfs:label\": \"Reference\"," + "\"domeo:uuid\": \"3043285E-EFD3-4445-BA43-B6A4AF1BEBF3\"," + "\"domeo_localId\": \"0\"," + "\"domeo_saveAsNewVersion\": \"false\"," + "\"pav:versionNumber\": \"\"," + "\"pav:previousVersion\": \"\"," + "\"pav:createdOn\": \"09/25/12 4:32PM\"," + "\"ao:context\": [" + "\"http://www.ncbi.nlm.nih.gov/pubmed/10679938\""+ "],"+ "\"domeo:content\": {" + "\"@type\": \"org.mindinformatics.gwt.framework.model.references.MPublicationArticleReference\"," + "\"@id\": \"10.1002/(SICI)1098-1004(200003)15:3<228::AID-HUMU3>3.0.CO;2-9\"," + "\"title\": \"An update of the mutation spectrum of the survival motor neuron gene (SMN1) in autosomal recessive spinal muscular atrophy (SMA).\"," + "\"authorNames\": \"Wirth B\"," + "\"doi\": \"10.1002/(SICI)1098-1004(200003)15:3<228::AID-HUMU3>3.0.CO;2-9\"," + "\"pmid\": \"10679938\"," + "\"pmcid\": \"<unknown>\"," + "\"publicationInfo\": \"Human mutation. 2000 ;Vol 15 Issue 3 :228-37\"," + "\"creationDate\": \"<unknown>\"," + "\"publisher\": \"<unknown>\"" + "}" + "}" + "]" + "}"; JsArray<JsoAnnotationSetSummary> sets = asArrayOfAnnotationSetSummaries2("[" + json+ "]"); return sets; } public JsArray<JsoAnnotationSetSummary> retrieveAnnotationByDocumentUrl(String url) { String json = ""; if(true) { //url.equals("http://www.ncbi.nlm.nih.gov/pubmed/10679938")) { // json = // "{" + // "\"pav:versionNumber\": \"1\"," + // "\"domeo_number_items\": 1," + // "\"pav:lineageUri\": \"urn:domeoserver:uuid:06DF988C-33C0-453C-8BFC-D23E383CFE88\"," + // "\"pav:createdOn\": \"2012-09-25 11:34:26 -0400\"," + // "\"rdfs:label\": \"Default Set\"," + // "\"pav:createdBy\": { " + // "\"screenname\": \"Dr. John Doe\"," + // "\"foaf_first_name\": \"John\"," + // "\"foaf_last_name\": \"Doe\"" + // "}," + // "\"pav:lastSavedOn\": \"2012-09-25 11:34:27 -0400\"," + // "\"@id\": \"urn:domeoclient:uuid:07895920-4A47-42DE-9F0A-9A79AAA33CC7\"," + // "\"dct:description\": \"The default set is created automatically by Domeo when no other set is existing.\"" + // "}"; json = "[{\"rdfs:label\":\"EuroPMC \",\"domeo:mongoUuid\":\"uNUDohDhR7KMorsRSLR2GQ\",\"@type\":\"domeo:DiscussionSet\",\"ao:numberItems\":3,\"pav:createdBy\":{\"screenname\":\"Dr. John Doe\",\"foaf_first_name\":\"John\",\"uri\":\"4028808d4185489401418548e3ca0000\",\"foaf_last_name\":\"Doe\"},\"pav:versionNumber\":\"2\",\"pav:lastSavedOn\":\"2013-10-04 17:05:15 -0400\",\"pav:lineageUri\":\"urn:domeoserver:annotationset:8B90099D-4C8C-45F5-ADBA-83D5999F5FD8\",\"pav:previousVersion\":\"urn:domeoclient:uuid:166EDE94-E8A4-4DDF-AA61-CF584F4721ED\",\"dct:description\":\"asdfsdfa\",\"permissions:accessType\":\"urn:domeo:access:public\",\"@id\":\"urn:domeoserver:annotationset:76B1FE2E-5663-4C77-9A17-5A5BDCC08407\",\"pav:createdOn\":\"2013-10-04 17:04:59 -0400\"},{\"rdfs:label\":\"Default Set\",\"domeo:mongoUuid\":\"GSQFXihqRpeY7-QbihmzGw\",\"@type\":\"ao:AnnotationSet\",\"ao:numberItems\":3,\"pav:createdBy\":{\"screenname\":\"Dr. John Doe\",\"foaf_first_name\":\"John\",\"uri\":\"4028808d4185489401418548e3ca0000\",\"foaf_last_name\":\"Doe\"},\"pav:versionNumber\":\"2\",\"pav:lastSavedOn\":\"2013-10-04 17:04:41 -0400\",\"pav:lineageUri\":\"urn:domeoserver:annotationset:DF0ED7B2-7594-4F9E-AF16-0C0DD8DE7935\",\"pav:previousVersion\":\"urn:domeoclient:uuid:580BCB7B-3A2F-410A-B106-A64B7589C7A7\",\"dct:description\":\"The default set is created automatically by Domeo when no other set is existing.\",\"permissions:accessType\":\"urn:domeo:access:public\",\"@id\":\"urn:domeoserver:annotationset:386FCC96-3486-46EF-A06E-2472084610C1\",\"pav:createdOn\":\"2013-10-04 17:04:32 -0400\"}, " + "{\"rdfs:label\":\"EuroPMC \",\"domeo:mongoUuid\":\"uNUDohDhR7KMorsRSLR2GQ\",\"@type\":\"domeo:DiscussionSet\",\"ao:numberItems\":3,\"pav:createdBy\":{\"screenname\":\"Dr. John Doe\",\"foaf_first_name\":\"John\",\"uri\":\"4028808d4185489401418548e3ca0002\",\"foaf_last_name\":\"Doe\"},\"pav:versionNumber\":\"2\",\"pav:lastSavedOn\":\"2013-10-04 17:05:15 -0400\",\"pav:lineageUri\":\"urn:domeoserver:annotationset:8B90099D-4C8C-45F5-ADBA-83D5999F5FD8\",\"pav:previousVersion\":\"urn:domeoclient:uuid:166EDE94-E8A4-4DDF-AA61-CF584F4721ED\",\"dct:description\":\"asdfsdfa\",\"permissions:accessType\":\"urn:domeo:access:public\",\"@id\":\"urn:domeoserver:annotationset:76B1FE2E-5663-4C77-9A17-5A5BDCC08408\",\"pav:createdOn\":\"2013-10-04 17:04:59 -0400\"},{\"rdfs:label\":\"Default Set\",\"domeo:mongoUuid\":\"GSQFXihqRpeY7-QbihmzGw\",\"@type\":\"ao:AnnotationSet\",\"ao:numberItems\":3,\"pav:createdBy\":{\"screenname\":\"Dr. John Doe\",\"foaf_first_name\":\"John\",\"uri\":\"4028808d4185489401418548e3ca0000\",\"foaf_last_name\":\"Doe\"},\"pav:versionNumber\":\"2\",\"pav:lastSavedOn\":\"2013-10-04 17:04:41 -0400\",\"pav:lineageUri\":\"urn:domeoserver:annotationset:DF0ED7B2-7594-4F9E-AF16-0C0DD8DE7935\",\"pav:previousVersion\":\"urn:domeoclient:uuid:580BCB7B-3A2F-410A-B106-A64B7589C7A7\",\"dct:description\":\"The default set is created automatically by Domeo when no other set is existing.\",\"permissions:accessType\":\"urn:domeo:access:public\",\"@id\":\"urn:domeoserver:annotationset:386FCC96-3486-46EF-A06E-2472084610C2\",\"pav:createdOn\":\"2013-10-04 17:04:32 -0400\"}]"; } JsArray<JsoAnnotationSetSummary> sets = asArrayOfAnnotationSetSummaries2(json); return sets; } /** * Given a specific url, it returns all the available accessible * annotation for the given user. This call also allows to extend * the request to documents with other urls that however match * some of the available document identifiers. * @param url Url of the document of interest * @param extend If true, the method will extend the request to * other documents that share an id with the requested one * @param username User requesting the annotation */ JsArray<JsAnnotationSetSummary> retrieveAnnotationByDocumentUrl(String url, String allowed, boolean extend, String username) { String json = "{}"; if(allowed.equals(AnnotationPersistenceServiceFacade.ALLOW_MINE)) { json = "{"+ "\"uuid\": \"ABC1\"," + "\"versionNumber\": \"1\"," + "\"label\": \"Set di prova\","+ "\"description\": \"My description\","+ "\"createdOn\": \"1996.07.10 15:08:56 -0500\","+ "\"createdBy\": \" Dr. Paolo Ciccarese\","+ "\"createdByUrl\": \" http://www.paolociccarese.info \","+ "\"lastSavedOn\": \"1996.07.10 15:08:56 -0500\","+ "\"isLocked\": true,"+ "\"numberOfAnnotationItems\": 4"+ "},"+ "{"+ "\"uuid\": \"ABC2\"," + "\"versionNumber\": \"2\"," + "\"previousVersion\": \"ABC3\"," + "\"label\": \"Set di prova 2\","+ "\"description\": \"My description 2\","+ "\"createdOn\": \"1998.07.10 15:08:56 -0500\","+ "\"createdBy\": \" Dr. Paolo Ciccarese\","+ "\"createdByUrl\": \" http://www.paolociccarese.info \","+ "\"lastSavedOn\": \"1998.07.10 15:08:56 -0500\","+ "\"isLocked\": false,"+ "\"numberOfAnnotationItems\": 4"+ "},"; } else if(allowed.equals(AnnotationPersistenceServiceFacade.ALLOW_GROUPS)) { json = "{"+ "\"uuid\": \"ABC1\"," + "\"versionNumber\": \"1\"," + "\"label\": \"Set di prova\","+ "\"description\": \"My description\","+ "\"createdOn\": \"1996.07.10 15:08:56 -0500\","+ "\"createdBy\": \" John Doe\","+ "\"createdByUrl\": \" http://www.example.com \","+ "\"lastSavedOn\": \"1996.07.10 15:08:56 -0500\","+ "\"isLocked\": true,"+ "\"numberOfAnnotationItems\": 3"+ "},"+ "{"+ "\"uuid\": \"ABC1\"," + "\"versionNumber\": \"1\"," + "\"label\": \"Set di prova\","+ "\"description\": \"My description\","+ "\"createdOn\": \"1996.07.10 15:08:56 -0500\","+ "\"createdBy\": \" Jenny Doe\","+ "\"createdByUrl\": \" http://www.example.com \","+ "\"lastSavedOn\": \"1996.07.10 15:08:56 -0500\","+ "\"isLocked\": true,"+ "\"numberOfAnnotationItems\": 4"+ "},"+ "{"+ "\"uuid\": \"ABC2\"," + "\"versionNumber\": \"2\"," + "\"previousVersion\": \"ABC3\"," + "\"label\": \"Set di prova 2\","+ "\"description\": \"My description 2\","+ "\"createdOn\": \"1998.07.10 15:08:56 -0500\","+ "\"createdBy\": \" John Doe\","+ "\"createdByUrl\": \" http://www.example.com \","+ "\"lastSavedOn\": \"1998.07.10 15:08:56 -0500\","+ "\"isLocked\": false,"+ "\"numberOfAnnotationItems\": 10"+ "},"; } else if(allowed.equals(AnnotationPersistenceServiceFacade.ALLOW_PUBLIC)) { json = "{"+ "\"uuid\": \"ABC1\"," + "\"versionNumber\": \"1\"," + "\"label\": \"Euro PMC\","+ "\"description\": \"My description\","+ "\"createdOn\": \"1996.07.10 15:08:56 -0500\","+ "\"createdBy\": \" Euro PMC\","+ "\"createdByUrl\": \" http://www.example.com \","+ "\"lastSavedOn\": \"1996.07.10 15:08:56 -0500\","+ "\"isLocked\": true,"+ "\"numberOfAnnotationItems\": 1"+ "},"+ "{"+ "\"uuid\": \"ABC2\"," + "\"versionNumber\": \"2\"," + "\"previousVersion\": \"ABC3\"," + "\"label\": \"Set di prova 2\","+ "\"description\": \"My description 2\","+ "\"createdOn\": \"1998.07.10 15:08:56 -0500\","+ "\"createdBy\": \" Johnny Deep\","+ "\"createdByUrl\": \" http://www.example.com \","+ "\"lastSavedOn\": \"1998.07.10 15:08:56 -0500\","+ "\"isLocked\": false,"+ "\"numberOfAnnotationItems\": 8"+ "},"+ "{"+ "\"uuid\": \"ABC1\"," + "\"versionNumber\": \"1\"," + "\"label\": \"Set di prova\","+ "\"description\": \"My description\","+ "\"createdOn\": \"1996.07.10 15:08:56 -0500\","+ "\"createdBy\": \" Johnny Smith\","+ "\"createdByUrl\": \" http://www.example.com \","+ "\"lastSavedOn\": \"1996.07.10 15:08:56 -0500\","+ "\"isLocked\": true,"+ "\"numberOfAnnotationItems\": 2"+ "},"+ "{"+ "\"uuid\": \"ABC2\"," + "\"versionNumber\": \"2\"," + "\"previousVersion\": \"ABC3\"," + "\"label\": \"Set di prova 2\","+ "\"description\": \"My description 2\","+ "\"createdOn\": \"1998.07.10 15:08:56 -0500\","+ "\"createdBy\": \" Johnny Smith\","+ "\"createdByUrl\": \" http://www.example.com \","+ "\"lastSavedOn\": \"1998.07.10 15:08:56 -0500\","+ "\"isLocked\": false,"+ "\"numberOfAnnotationItems\": 8"+ "},"+ "{"+ "\"uuid\": \"ABC1\"," + "\"versionNumber\": \"1\"," + "\"label\": \"Set di prova\","+ "\"description\": \"My description\","+ "\"createdOn\": \"1996.07.10 15:08:56 -0500\","+ "\"createdBy\": \" Johnny Deep\","+ "\"createdByUrl\": \" http://www.example.com \","+ "\"lastSavedOn\": \"1996.07.10 15:08:56 -0500\","+ "\"isLocked\": true,"+ "\"numberOfAnnotationItems\": 2"+ "},"+ "{"+ "\"uuid\": \"ABC2\"," + "\"versionNumber\": \"2\"," + "\"previousVersion\": \"ABC3\"," + "\"label\": \"Set di prova 2\","+ "\"description\": \"My description 2\","+ "\"createdOn\": \"1998.07.10 15:08:56 -0500\","+ "\"createdBy\": \" Johnny Deep\","+ "\"createdByUrl\": \" http://www.example.com \","+ "\"lastSavedOn\": \"1998.07.10 15:08:56 -0500\","+ "\"isLocked\": false,"+ "\"numberOfAnnotationItems\": 8"+ "},"+ "{"+ "\"uuid\": \"ABC1\"," + "\"versionNumber\": \"1\"," + "\"label\": \"Set di prova\","+ "\"description\": \"My description\","+ "\"createdOn\": \"1996.07.10 15:08:56 -0500\","+ "\"createdBy\": \" Johnny Smith\","+ "\"createdByUrl\": \" http://www.example.com \","+ "\"lastSavedOn\": \"1996.07.10 15:08:56 -0500\","+ "\"isLocked\": true,"+ "\"numberOfAnnotationItems\": 2"+ "},"+ "{"+ "\"uuid\": \"ABC2\"," + "\"versionNumber\": \"2\"," + "\"previousVersion\": \"ABC3\"," + "\"label\": \"Set di prova 2\","+ "\"description\": \"My description 2\","+ "\"createdOn\": \"1998.07.10 15:08:56 -0500\","+ "\"createdBy\": \" Johnny Smith\","+ "\"createdByUrl\": \" http://www.example.com \","+ "\"lastSavedOn\": \"1998.07.10 15:08:56 -0500\","+ "\"isLocked\": false,"+ "\"numberOfAnnotationItems\": 8"+ "},"; } JsArray<JsAnnotationSetSummary> sets = asArrayOfAnnotationSetSummaries("[" + json+ "]"); //for(int i=0; i<sets.length(); i++) { // Window.alert(""+fmt.format(sets.get(i).getCreatedOn())); //} return sets; } /** * Given a specific id, it returns all the available accessible * annotation for the given user. * @param id * @param idType * @param username */ public JsArray<JsAnnotationSet> retrieveAnnotationById(String id, String idType, String allowed, String username) { return retrieveAnnotationById(id, idType, allowed, false, username); } /** * Given a specific id, it returns all the available accessible * annotation for the given user. * @param id The id of the document * @param idType The type of id (Pubmed, Pmc....) * @param extend If true, the method will extend the request to * other documents that share an id with the requested one * @param username */ JsArray<JsAnnotationSet> retrieveAnnotationById(String id, String idType, String allowed, boolean extend, String username) { //String json = "[{\"pav:createdWith\": \"urn:domeo:software:id:Domeo-2.0alpha-040\",\"ao:item\": [{\"pav:createdWith\": \"urn:domeo:software:id:Domeo-2.0alpha-040\",\"rdfs:label\": \"Highlight\", \"pav:previousVersion\": \"\", \"@type\": \"ao:Qualifier\",\"domeo:belongsToSet\": \"urn:domeoclient:uuid:E7779F6D-4FFD-428C-82CF-42ED72740B06\",\"pav:createdBy\": \"urn:person:uuid:4028808d42d966140142d9666ece0000\", \"pav:lastSavedOn\": \"2013-12-12 14:43:49 -0500\",\"pav:versionNumber\": \"1\", \"@id\": \"urn:domeoclient:uuid:76CC060A-193D-45DF-B3EC-A5F10B159282\", \"ao:context\": [ { \"ao:hasSource\": \"http://en.wikipedia.org/wiki/Amyloid_precursor_protein\", \"@type\": \"ao:SpecificResource\", \"@id\": \"urn:domeoclient:uuid:3AF2A533-58BA-4A9C-88B2-83AF57B8E85E\",\"domeo_temp_localId\": \"1\", \"ao:hasSelector\": { \"ao:prefix\": \"An important but largely unmet challenge in understanding the mechanisms that govern the \",\"@type\": \"ao:PrefixSuffixTextSelector\", \"@id\": \"urn:domeoclient:uuid:3AF2A533-58BA-4A9C-88B2-83AF57B8E85E\",\"domeo_temp_localId\": \"1\", \"pav:createdOn\": \"2013-12-12 14:43:40 -0500\",\"ao:exact\": \"formation\", \"ao:suffix\": \" of specific organs is to decipher the complex and dynamic genetic programs exhibited by the diversity of cell types within the tissue of interest. \", \"domeo:uuid\": \"3AF2A533-58BA-4A9C-88B2-83AF57B8E85E\" } } ], \"ao:hasTopic\": [{ \"@id\": \"http://www.ebi.ac.uk/QuickGO/GTerm?id=GO:0009058\",\"rdfs:label\": \"biosynthetic process\", \"dct:description\": \"\", \"dct:source\": { \"@id\": \"http://www.ebi.ac.uk/QuickGO/\",\"rdfs:label\": \"Biological Process\" } } ], \"pav:createdOn\": \"2013-12-12 14:43:40 -0500\", \"pav:lineageUri\": \"urn:domeoserver:annotation:75EAD458-85A3-4879-887E-FD034E5FD52A\"} ], \"rdfs:label\": \"Default Set\",\"domeo:deleted\": \"false\", \"ao:annotatesResource\": \"http://www.ncbi.nlm.nih.gov/pmc/articles/PMC1366495/?report=classic\", \"domeo:resources\": [ { \"label\": \"An Integrated Strategy for Analyzing the Unique Developmental Programs of Different Myoblast Subtypes\", \"url\": \"http://www.ncbi.nlm.nih.gov/pmc/articles/PMC1366495/?report=classic\" }], \"@type\": \"ao:AnnotationSet\", \"pav:createdBy\": \"urn:person:uuid:4028808d42d966140142d9666ece0000\", \"pav:lastSavedOn\": \"2013-12-12 14:43:48 -0500\", \"pav:versionNumber\": \"1\",\"permissions:permissions\": {\"permissions:isLocked\": \"false\",\"permissions:accessType\": \"urn:domeo:access:public\" }, \"pav:lineageUri\": \"urn:domeoserver:annotationset:43A7C6D5-3884-4729-9E18-759752463598\", \"domeo:agents\": [{\"rdfs:label\": \"EuroPMC\", \"foafx:middlename\": \"\", \"foafx:lastname\": \"Doe\", \"@type\": \"foafx:Person\", \"foafx:homepage\": \"\",\"foafx:picture\": \"http://www.hcklab.org/images/me/paolo%20ciccarese-boston.jpg\",\"foafx:email\": \"[email protected]\",\"foafx:firstname\": \"John\",\"foafx:title\": \"\",\"@id\": \"urn:person:uuid:4028808d42d966140142d9666ece0000\", \"foafx:name\": \"Euro PMC\" },{ \"foafx:build\": \"040\" ,\"rdfs:label\": \"Domeo Annotation Toolkit\", \"@type\": \"foafx:Software\", \"foafx:homepage\": \"\",\"@id\": \"urn:domeo:software:id:Domeo-2.0alpha-040\",\"foafx:name\": \"Domeo Annotation Toolkit\",\"foafx:version\": \"2.0alpha\" } ],\"pav:previousVersion\": \"\", \"dct:description\": \"The default set is created automatically by Domeo when no other set is existing.\", \"@id\": \"urn:domeoclient:uuid:E7779F6D-4FFD-428C-82CF-42ED72740B06\", \"pav:createdOn\": \"2013-12-12 14:43:40 -0500\" } ]"; //String json = "[{\"pav:createdWith\":\"urn:domeo:software:id:Domeo-2.0alpha-040\",\"ao:item\":[{\"pav:createdWith\":\"urn:domeo:software:id:Domeo-2.0alpha-040\",\"rdfs:label\":\"SPL Annotation\",\"@type\":\"ao:SPLAnnotation\",\"domeo:belongsToSet\":\"urn:domeoclient:uuid:B2CBE747-9368-48D3-8AB8-0ECDA72850D1\",\"pav:createdBy\":\"urn:person:uuid:080e1430434f70e501434f711b6e0000\",\"pav:versionNumber\":\"1\",\"pav:lastSavedOn\":\"2014-01-22 17:35:57 -0500\",\"ao:context\":[{\"ao:hasSource\":\"http://127.0.0.1:8888/tests/SPL-annotation/Warfarin-ab047628-67d0-4a64-8d77-36b054969b44.html\",\"@type\":\"ao:SpecificResource\",\"@id\":\"urn:domeoclient:uuid:54CDC1E5-65E1-480A-A1C4-957BD32F7308\",\"domeo_temp_localId\":\"1\",\"ao:hasSelector\":{\"ao:prefix\":\"These highlights do not include all the information needed to use\",\"@type\":\"ao:PrefixSuffixTextSelector\",\"@id\":\"urn:domeoclient:uuid:54CDC1E5-65E1-480A-A1C4-957BD32F7308\",\"domeo_temp_localId\":\"1\",\"pav:createdOn\":\"2014-01-22 17:35:52 -0500\",\"ao:exact\":\" warfarin sodium safely and effectively. See full \",\"ao:suffix\":\"prescribing information for warfarin sodium.\",\"domeo:uuid\":\"54CDC1E5-65E1-480A-A1C4-957BD32F7308\"}}],\"ao:body\":[{\"sio:SIO_000563\":\"poc:PharmacokineticImpact\",\"@type\":\"poc:PharmacogenomicsStatement\",\"@id\":\"urn:linkedspls:uuid:38ACB655-54F2-43F3-8463-7AA1833725B5\",\"poc:PharmacokineticImpact\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#distribution-increase\"}],\"pav:lineageUri\":\"urn:domeoserver:annotation:A3653D48-231D-44CE-A309-B2C2F4311404\",\"pav:previousVersion\":\"\",\"@id\":\"urn:domeoclient:uuid:8E11483E-4C21-4188-AC79-B5BADA60ECE9\",\"pav:createdOn\":\"2014-01-22 17:35:52 -0500\"}],\"rdfs:label\":\"Default Set\",\"ao:annotatesResource\":\"http://127.0.0.1:8888/tests/SPL-annotation/Warfarin-ab047628-67d0-4a64-8d77-36b054969b44.html\",\"domeo:resources\":[{\"label\":\"WARFARIN SODIUM TABLET [AMERICAN HEALTH PACKAGING]\",\"url\":\"http://127.0.0.1:8888/tests/SPL-annotation/Warfarin-ab047628-67d0-4a64-8d77-36b054969b44.html\"}],\"@type\":\"ao:AnnotationSet\",\"pav:createdBy\":\"urn:person:uuid:080e1430434f70e501434f711b6e0000\",\"pav:lastSavedOn\":\"2014-01-22 17:35:57 -0500\",\"pav:versionNumber\":\"1\",\"permissions:permissions\":{\"permissions:isLocked\":\"false\",\"permissions:accessType\":\"urn:domeo:access:public\"},\"pav:lineageUri\":\"urn:domeoserver:annotationset:65B8CECA-8AFA-47C2-B14C-60ECB6FEC4F2\",\"domeo:agents\":[{\"rdfs:label\":\"boycer\",\"foafx:middlename\":\"\",\"foafx:lastname\":\"Boyce\",\"@type\":\"foafx:Person\",\"foafx:homepage\":\"\",\"foafx:picture\":\" http://www.hcklab.org/images/me/paolo%20ciccarese-boston.jpg\",\"foafx:email\":\"[email protected]\",\"foafx:firstname\":\"Richard\",\"foafx:title\":\"\",\"@id\":\"urn:person:uuid:080e1430434f70e501434f711b6e0000\",\"foafx:name\":\"boycer\"},{\"foafx:build\":\"040\",\"rdfs:label\":\"Domeo Annotation Toolkit\",\"@type\":\"foafx:Software\",\"foafx:homepage\":\"\",\"@id\":\"urn:domeo:software:id:Domeo-2.0alpha-040\",\"foafx:name\":\"Domeo Annotation Toolkit\",\"foafx:version\":\"2.0alpha\"}],\"pav:previousVersion\":\"\",\"dct:description\":\"The default set is created automatically by Domeo when no other set is existing.\",\"@id\":\"urn:domeoclient:uuid:B2CBE747-9368-48D3-8AB8-0ECDA72850D1\",\"pav:createdOn\":\"2014-01-22 17:35:44 -0500\"}]"; /* String json = "[{\"pav:createdWith\":\"urn:domeo:software:id:Domeo-2.0alpha-040\",\"ao:item\":[{\"pav:createdWith\":\"urn:domeo:software:id:Domeo-2.0alpha-040\",\"rdfs:label\":\"SPL Annotation\",\"@type\":\"ao:SPLAnnotation\",\"domeo:belongsToSet\":\"urn:domeoclient:uuid:B2CBE747-9368-48D3-8AB8-0ECDA72850D1\",\"pav:createdBy\":\"urn:person:uuid:080e1430434f70e501434f711b6e0000\",\"pav:versionNumber\":\"1\",\"pav:lastSavedOn\":\"2014-01-22 17:35:57 -0500\",\"ao:context\":[{\"ao:hasSource\":\"http://127.0.0.1:8888/tests/SPL-annotation/Warfarin-ab047628-67d0-4a64-8d77-36b054969b44.html\",\"@type\":\"ao:SpecificResource\",\"@id\":\"urn:domeoclient:uuid:54CDC1E5-65E1-480A-A1C4-957BD32F7308\",\"domeo_temp_localId\":\"1\",\"ao:hasSelector\":{\"ao:prefix\":\"These highlights do not include all the information needed to use\",\"@type\":\"ao:PrefixSuffixTextSelector\",\"@id\":\"urn:domeoclient:uuid:54CDC1E5-65E1-480A-A1C4-957BD32F7308\",\"domeo_temp_localId\":\"1\",\"pav:createdOn\":\"2014-01-22 17:35:52 -0500\",\"ao:exact\":\" warfarin sodium safely and effectively. See full \",\"ao:suffix\":\"prescribing information for warfarin sodium.\",\"domeo:uuid\":\"54CDC1E5-65E1-480A-A1C4-957BD32F7308\"}}],\"ao:body\":" + "[{\"@id\":\"urn:linkedspls:uuid:098EA66F-195E-4295-A394-AF04C5C075BC\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000628\":\"dailymed:pharmgxDrug\", \"dailymed:pharmgxDrug\":\"http://www.drugbank.ca/drugs/DB01238\", \"rdfs:label\":\"Aripiprazole\", \"dct:description\":\"The drug of interest.\"}," + "{\"@id\":\"urn:linkedspls:uuid:1ACE6E1C-1971-4EB1-A317-5F0BA90C915F\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000628\":\"dailymed:pharmgxBiomarker\", \"dailymed:pharmgxBiomarker1\":\"http://purl.obolibrary.org/obo/PR_000012621\", \"dailymed:pharmgxBiomarker2\":\"http://purl.obolibrary.org/obo/PR_000007204\", \"dailymed:pharmgxBiomarker\":\"http://purl.obolibrary.org/obo/PR_000007205\", \"rdfs:label\":\"ER and PgR_receptor\", \"dct:description\":\"The selected biomarker.\"}]" + ",\"pav:lineageUri\":\"urn:domeoserver:annotation:A3653D48-231D-44CE-A309-B2C2F4311404\",\"pav:previousVersion\":\"\",\"@id\":\"urn:domeoclient:uuid:8E11483E-4C21-4188-AC79-B5BADA60ECE9\",\"pav:createdOn\":\"2014-01-22 17:35:52 -0500\"}],\"rdfs:label\":\"Default Set\",\"ao:annotatesResource\":\"http://127.0.0.1:8888/tests/SPL-annotation/Warfarin-ab047628-67d0-4a64-8d77-36b054969b44.html\",\"domeo:resources\":[{\"label\":\"WARFARIN SODIUM TABLET [AMERICAN HEALTH PACKAGING]\",\"url\":\"http://127.0.0.1:8888/tests/SPL-annotation/Warfarin-ab047628-67d0-4a64-8d77-36b054969b44.html\"}],\"@type\":\"ao:AnnotationSet\",\"pav:createdBy\":\"urn:person:uuid:080e1430434f70e501434f711b6e0000\",\"pav:lastSavedOn\":\"2014-01-22 17:35:57 -0500\",\"pav:versionNumber\":\"1\",\"permissions:permissions\":{\"permissions:isLocked\":\"false\",\"permissions:accessType\":\"urn:domeo:access:public\"},\"pav:lineageUri\":\"urn:domeoserver:annotationset:65B8CECA-8AFA-47C2-B14C-60ECB6FEC4F2\",\"domeo:agents\":[{\"rdfs:label\":\"boycer\",\"foafx:middlename\":\"\",\"foafx:lastname\":\"Boyce\",\"@type\":\"foafx:Person\",\"foafx:homepage\":\"\",\"foafx:picture\":\" http://www.hcklab.org/images/me/paolo%20ciccarese-boston.jpg\",\"foafx:email\":\"[email protected]\",\"foafx:firstname\":\"Richard\",\"foafx:title\":\"\",\"@id\":\"urn:person:uuid:080e1430434f70e501434f711b6e0000\",\"foafx:name\":\"boycer\"},{\"foafx:build\":\"040\",\"rdfs:label\":\"Domeo Annotation Toolkit\",\"@type\":\"foafx:Software\",\"foafx:homepage\":\"\",\"@id\":\"urn:domeo:software:id:Domeo-2.0alpha-040\",\"foafx:name\":\"Domeo Annotation Toolkit\",\"foafx:version\":\"2.0alpha\"}],\"pav:previousVersion\":\"\",\"dct:description\":\"The default set is created automatically by Domeo when no other set is existing.\",\"@id\":\"urn:domeoclient:uuid:B2CBE747-9368-48D3-8AB8-0ECDA72850D1\",\"pav:createdOn\":\"2014-01-22 17:35:44 -0500\"}]"; */ String json = "[{\"pav:createdWith\":\"urn:domeo:software:id:Domeo-2.0alpha-040\",\"ao:item\":[{\"pav:createdWith\":\"urn:domeo:software:id:Domeo-2.0alpha-040\",\"rdfs:label\":\"SPL Annotation\",\"@type\":\"ao:SPLAnnotation\",\"domeo:belongsToSet\":\"urn:domeoclient:uuid:B2CBE747-9368-48D3-8AB8-0ECDA72850D1\",\"pav:createdBy\":\"urn:person:uuid:080e1430434f70e501434f711b6e0000\",\"pav:versionNumber\":\"1\",\"pav:lastSavedOn\":\"2014-01-22 17:35:57 -0500\",\"ao:context\":[{\"ao:hasSource\":\"http://127.0.0.1:8888/tests/SPL-annotation/Warfarin-ab047628-67d0-4a64-8d77-36b054969b44.html\",\"@type\":\"ao:SpecificResource\",\"@id\":\"urn:domeoclient:uuid:54CDC1E5-65E1-480A-A1C4-957BD32F7308\",\"domeo_temp_localId\":\"1\",\"ao:hasSelector\":{\"ao:prefix\":\"These highlights do not include all the information needed to use\",\"@type\":\"ao:PrefixSuffixTextSelector\",\"@id\":\"urn:domeoclient:uuid:54CDC1E5-65E1-480A-A1C4-957BD32F7308\",\"domeo_temp_localId\":\"1\",\"pav:createdOn\":\"2014-01-22 17:35:52 -0500\",\"ao:exact\":\" warfarin sodium safely and effectively. See full \",\"ao:suffix\":\"prescribing information for warfarin sodium.\",\"domeo:uuid\":\"54CDC1E5-65E1-480A-A1C4-957BD32F7308\"}}],\"ao:body\":" + "[{\"@id\":\"urn:linkedspls:uuid:51BF9FB2-0876-4618-953D-3E4279563F5A\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000628\":\"dailymed:ConcomitantMedicationOfConcern\", \"dailymed:ConcomitantMedicationOfConcern\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#concomitant-medication-concern\", \"rdfs:label\":\"Concomitant medication concern\", \"dct:description\":\"A concomitant medication of concern is mentioned.\"}," + "{\"@id\":\"urn:linkedspls:uuid:E20B7EDA-2D14-402B-BE68-8B6F35E262A5\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000563\":\"poc:VariantFrequency\", \"poc:VariantFrequency\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#population-frequency-mentioned\", \"rdfs:label\":\"Variant Frequency\", \"dct:description\":\"The frequency or proportion at which a variant occurs in a specific population is mentioned.\"}," + "{\"@id\":\"urn:linkedspls:uuid:AC117431-47DD-4A0A-B5A6-0AEA9D425094\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000628\":\"dailymed:ActiveMoiety\", \"dailymed:ActiveMoiety\":\"http://dbmi-icode-01.dbmi.pitt.edu/linkedSPLs/vocab/resource/ingredient-active\", \"rdfs:label\":\"Active ingredient\", \"dct:description\":\"the ingredient is active\"}," + "{\"@id\":\"urn:linkedspls:uuid:124D795F-C313-47D3-B601-D230D256BAFE\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000111\":\"BOXED WARNING (34066-1)\", \"poc:productLabelSection\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#BOXED WARNING (34066-1)\", \"rdfs:label\":\"SPL Section \", \"dct:description\":\"The section of the label where pharmacists identify clinical pharmgx statements\"}," + "{\"@id\":\"urn:linkedspls:uuid:8A6D2C77-41B6-40C1-8D9B-392E637480BB\", \"@type\":\"poc:PharmacogenomicsStatement\", \"poc:Comment\":\"It's a good annotation\", \"rdfs:label\":\"Comment\"}," + "{\"@id\":\"urn:linkedspls:uuid:9961B2F2-5DF2-48EF-972C-1534384C5CA2\", \"@type\":\"poc:PharmacogenomicsStatement\", \"ncit:Alleles\":\"test alleles\", \"rdfs:label\":\"Alleles\"}," + "{\"@id\":\"urn:linkedspls:uuid:72C0C502-9AFF-4425-A9DC-2361F1DABF3D\", \"@type\":\"poc:PharmacogenomicsStatement\", \"poc:MedicalCondition\":\"test medical conditions\", \"rdfs:label\":\"MedicalCondition\"}," + "{\"@id\":\"urn:linkedspls:uuid:72B35C27-DEA2-4379-B909-63169841CC4E\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000628\":\"poc:Variant\", \"poc:Variant\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#\", \"rdfs:label\":\"intermediate-metabolizer\", \"dct:description\":\"A specific variant of a gene, including the wild-type allele, or a patient phenotype\"}," + "{\"@id\":\"urn:linkedspls:uuid:377C76E3-6129-479F-8D92-CD000415943E\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000338\":\"poc:TestResult\", \"poc:TestResult\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#gene-expression-level-high\", \"rdfs:label\":\"gene-expression-level-high\", \"dct:description\":\"A test result that is somehow related to the biomarker.\"}," + "{\"@id\":\"urn:linkedspls:uuid:FFC8415C-1E46-4AC4-88AB-DD61F5C9CB58\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000563\":\"poc:MonitoringRecommendation\", \"poc:MonitoringRecommendation\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#change-monitoring-strategy\", \"rdfs:label\":\"Change monitoring strategy\", \"dct:description\":\"A strategy changed monitoring recommendation is related to the pharmacogenomic biomarker.\"}," + "{\"@id\":\"urn:linkedspls:uuid:C1898D67-D43C-48C0-B884-6394D658F386\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000563\":\"poc:TestRecommendation\", \"poc:TestRecommendation\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#take-note-that-tests-are-avaliable\", \"rdfs:label\":\"Take note that tests are avaliable\", \"dct:description\":\"Testing related to the pharmacogenomic biomarker is avaliable.\"}," + "{\"@id\":\"urn:linkedspls:uuid:1041808D-00AE-4B84-9B71-16FD1336DD16\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000563\":\"poc:PharmacokineticImpact\", \"poc:PharmacokineticImpact\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#absorption-increase\", \"rdfs:label\":\"Absorption Increase\", \"dct:description\":\"The pharmacogenomic biomarker is associated with a increase in absorption of the drug.\"}," + "{\"@id\":\"urn:linkedspls:uuid:66FB7E34-DCD6-4B2B-8C85-D6983C10ABBC\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000563\":\"poc:PharmacodynamicImpact\", \"poc:PharmacodynamicImpact\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#drug-toxicity-risk-increased\", \"rdfs:label\":\"Increased Toxicity Risk\", \"dct:description\":\"The pharmacogenomic biomarker is associated with an increased risk of toxicity.\"}," + "{\"@id\":\"urn:linkedspls:uuid:B37E7F17-F662-4FA4-8F42-82B275708A37\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000563\":\"poc:DrugSelectionRecommendation\", \"poc:DrugSelectionRecommendation\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#change-in-route-of-admin\", \"rdfs:label\":\"Change in route of administration\", \"dct:description\":\"The pharmacogenomic biomarker is related to a recommendation to add change the route of administration for the drug.\"}," + "{\"@id\":\"urn:linkedspls:uuid:BEA29BD8-8E44-4C7F-87DB-A3C0377E422A\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000563\":\"poc:DoseSelectionRecommendation\", \"poc:DoseSelectionRecommendation\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#increase-from-recommended-baseline\", \"rdfs:label\":\"Increase from baseline\", \"dct:description\":\"The pharmacogenomic biomarker is related to a recommendation to increase the dose of the drug from the recommended baseline.\"},"+ "{\"@id\":\"urn:linkedspls:uuid:098EA66F-195E-4295-A394-AF04C5C075BC\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000628\":\"dailymed:pharmgxDrug\", \"dailymed:pharmgxDrug\":\"http://www.drugbank.ca/drugs/DB01238\", \"rdfs:label\":\"Aripiprazole\", \"dct:description\":\"The drug of interest.\"}," + "{\"@id\":\"urn:linkedspls:uuid:1ACE6E1C-1971-4EB1-A317-5F0BA90C915F\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000628\":\"dailymed:pharmgxBiomarker\", \"dailymed:pharmgxBiomarker1\":\"http://purl.obolibrary.org/obo/PR_000012621\", \"dailymed:pharmgxBiomarker2\":\"http://purl.obolibrary.org/obo/PR_000007204\", \"dailymed:pharmgxBiomarker\":\"http://purl.obolibrary.org/obo/PR_000007205\", \"rdfs:label\":\"ER and PgR_receptor\", \"dct:description\":\"The selected biomarker.\"}]" + ",\"pav:lineageUri\":\"urn:domeoserver:annotation:A3653D48-231D-44CE-A309-B2C2F4311404\",\"pav:previousVersion\":\"\",\"@id\":\"urn:domeoclient:uuid:8E11483E-4C21-4188-AC79-B5BADA60ECE9\",\"pav:createdOn\":\"2014-01-22 17:35:52 -0500\"}],\"rdfs:label\":\"Default Set\",\"ao:annotatesResource\":\"http://127.0.0.1:8888/tests/SPL-annotation/Warfarin-ab047628-67d0-4a64-8d77-36b054969b44.html\",\"domeo:resources\":[{\"label\":\"WARFARIN SODIUM TABLET [AMERICAN HEALTH PACKAGING]\",\"url\":\"http://127.0.0.1:8888/tests/SPL-annotation/Warfarin-ab047628-67d0-4a64-8d77-36b054969b44.html\"}],\"@type\":\"ao:AnnotationSet\",\"pav:createdBy\":\"urn:person:uuid:080e1430434f70e501434f711b6e0000\",\"pav:lastSavedOn\":\"2014-01-22 17:35:57 -0500\",\"pav:versionNumber\":\"1\",\"permissions:permissions\":{\"permissions:isLocked\":\"false\",\"permissions:accessType\":\"urn:domeo:access:public\"},\"pav:lineageUri\":\"urn:domeoserver:annotationset:65B8CECA-8AFA-47C2-B14C-60ECB6FEC4F2\",\"domeo:agents\":[{\"rdfs:label\":\"boycer\",\"foafx:middlename\":\"\",\"foafx:lastname\":\"Boyce\",\"@type\":\"foafx:Person\",\"foafx:homepage\":\"\",\"foafx:picture\":\" http://www.hcklab.org/images/me/paolo%20ciccarese-boston.jpg\",\"foafx:email\":\"[email protected]\",\"foafx:firstname\":\"Richard\",\"foafx:title\":\"\",\"@id\":\"urn:person:uuid:080e1430434f70e501434f711b6e0000\",\"foafx:name\":\"boycer\"},{\"foafx:build\":\"040\",\"rdfs:label\":\"Domeo Annotation Toolkit\",\"@type\":\"foafx:Software\",\"foafx:homepage\":\"\",\"@id\":\"urn:domeo:software:id:Domeo-2.0alpha-040\",\"foafx:name\":\"Domeo Annotation Toolkit\",\"foafx:version\":\"2.0alpha\"}],\"pav:previousVersion\":\"\",\"dct:description\":\"The default set is created automatically by Domeo when no other set is existing.\",\"@id\":\"urn:domeoclient:uuid:B2CBE747-9368-48D3-8AB8-0ECDA72850D1\",\"pav:createdOn\":\"2014-01-22 17:35:44 -0500\"}]"; /* String json = "[{\"pav:createdWith\":\"urn:domeo:software:id:Domeo-2.0alpha-040\",\"ao:item\":[{\"pav:createdWith\":\"urn:domeo:software:id:Domeo-2.0alpha-040\",\"rdfs:label\":\"SPL Annotation\",\"@type\":\"ao:SPLAnnotation\",\"domeo:belongsToSet\":\"urn:domeoclient:uuid:B2CBE747-9368-48D3-8AB8-0ECDA72850D1\",\"pav:createdBy\":\"urn:person:uuid:080e1430434f70e501434f711b6e0000\",\"pav:versionNumber\":\"1\",\"pav:lastSavedOn\":\"2014-01-22 17:35:57 -0500\",\"ao:context\":[{\"ao:hasSource\":\"http://127.0.0.1:8888/tests/SPL-annotation/Warfarin-ab047628-67d0-4a64-8d77-36b054969b44.html\",\"@type\":\"ao:SpecificResource\",\"@id\":\"urn:domeoclient:uuid:54CDC1E5-65E1-480A-A1C4-957BD32F7308\",\"domeo_temp_localId\":\"1\",\"ao:hasSelector\":{\"ao:prefix\":\"These highlights do not include all the information needed to use\",\"@type\":\"ao:PrefixSuffixTextSelector\",\"@id\":\"urn:domeoclient:uuid:54CDC1E5-65E1-480A-A1C4-957BD32F7308\",\"domeo_temp_localId\":\"1\",\"pav:createdOn\":\"2014-01-22 17:35:52 -0500\",\"ao:exact\":\" warfarin sodium safely and effectively. See full \",\"ao:suffix\":\"prescribing information for warfarin sodium.\",\"domeo:uuid\":\"54CDC1E5-65E1-480A-A1C4-957BD32F7308\"}}],\"ao:body\":" + "[{\"@id\":\"urn:linkedspls:uuid:0E2BA97B-A180-4547-B775-3F0110E97284\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000338\":\"poc:productLabelSelection\", \"poc:productLabelSelection\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#\", \"rdfs:label\":\"CLINICAL PHARMACOLOGY (34090-1)\", \"dct:description\":\"what section of the label Pharmacists identify clinical pharmgx statements\"}," + "{\"@id\":\"urn:linkedspls:uuid:07EAA91F-B199-4565-8B13-543830A2CE25\", \"@type\":\"poc:PharmacogenomicsStatement\", \"poc:Comment\":\"test comment\", \"rdfs:label\":\"Comment\"}," + "{\"@id\":\"urn:linkedspls:uuid:7FD1AF25-ABBD-4909-B648-3D549517095E\", \"@type\":\"poc:PharmacogenomicsStatement\", \"poc:MedicalCondition\":\"test medical condition\", \"rdfs:label\":\"MedicalCondition\"}," + "{\"@id\":\"urn:linkedspls:uuid:5EF4FA92-8518-4532-ABA8-DB71FF9D2ADC\", \"@type\":\"poc:PharmacogenomicsStatement\", \"ncit:Alleles\":\"test alleles\", \"rdfs:label\":\"Alleles\"}," + "{\"@id\":\"urn:linkedspls:uuid:1055B4FD-6AC5-4718-B670-70A66B47D73D\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000628\":\"dailymed:ConcomitantMedicationOfConcern\", \"dailymed:ConcomitantMedicationOfConcern\":\"http://dbmi-icode-01.dbmi.pitt.edu/linkedSPLs/vocab/resource/concomitant-medication-concern\", \"rdfs:label\":\"Concomitant medication concern\", \"dct:description\":\"A concomitant medication of concern is mentioned.\"}," + "{\"@id\":\"urn:linkedspls:uuid:DE05922C-5327-4B28-BEBD-A6EE3CEF35B2\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000628\":\"dailymed:ActiveMoiety\", \"dailymed:ActiveMoiety\":\"http://dbmi-icode-01.dbmi.pitt.edu/linkedSPLs/vocab/resource/ingredient-active\", \"rdfs:label\":\"Active ingredient\", \"dct:description\":\"the ingredient is active\"}," + "{\"@id\":\"urn:linkedspls:uuid:A229674C-9899-474B-96D3-C37E8759C341\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000563\":\"poc:VariantFrequency\", \"poc:VariantFrequency\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#population-frequency-mentioned\", \"rdfs:label\":\"Variant Frequency\", \"dct:description\":\"The frequency or proportion at which a variant occurs in a specific population is mentioned.\"}," + "{\"@id\":\"urn:linkedspls:uuid:3F5EFB36-7B8B-4A3F-BFBA-725C36A1D74F\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000628\":\"dailymed:pharmgxDrug\", \"dailymed:pharmgxDrug\":\"http://fakeuri.org/Atomoxetine\", \"rdfs:label\":\"Arsenic_Trioxide\", \"dct:description\":\"The drug of interest.\"}," + "{\"@id\":\"urn:linkedspls:uuid:F2224CEF-E0DB-418F-ACF3-D3988D26775B\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000628\":\"dailymed:pharmgxBiomarker\", \"dailymed:pharmgxBiomarker\":\"http://fakeuri.org/CD25\", \"rdfs:label\":\"CD20_antigen\", \"dct:description\":\"The selected biomarker.\"}, " + "{\"@id\":\"urn:linkedspls:uuid:1AA7F9B3-F775-4397-BD31-F570BFAA582F\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000338\":\"poc:TestResult\", \"poc:TestResult\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#gene-SNP-positive\", \"rdfs:label\":\"gene-SNP-positive\", \"dct:description\":\"A test result that is somehow related to the biomarker.\"}," + "{\"@id\":\"urn:linkedspls:uuid:F12CFED5-0FB6-4715-85C0-280731AD2389\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000628\":\"poc:Variant\", \"poc:Variant\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#intermediate-metabolizer\", \"rdfs:label\":\"intermediate-metabolizer\", \"dct:description\":\"A specific variant of a gene, including the wild-type allele, or a patient phenotype\"}," + "{\"@id\":\"urn:linkedspls:uuid:CCB5DD68-8EBF-4B2A-BDA8-7AEE0076F6F2\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000563\":\"poc:MonitoringRecommendation\", \"poc:MonitoringRecommendation\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#recommended\", \"rdfs:label\":\"Recommended\", \"dct:description\":\"A recommended monitoring recommendation is related to the pharmacogenomic biomarker.\"}," + "{\"@id\":\"urn:linkedspls:uuid:02D1951E-D2F7-4564-8BED-C9B61C47AC69\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000563\":\"poc:TestRecommendation\", \"poc:TestRecommendation\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#required\", \"rdfs:label\":\"Required\", \"dct:description\":\"A required test is related to the biomarker.\"}," + "{\"@id\":\"urn:linkedspls:uuid:110D5162-B9B5-4F3F-B01A-506756CDEE5F\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000563\":\"poc:DoseSelectionRecommendation\", \"poc:DoseSelectionRecommendation\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#increase-from-recommended-baseline\", \"rdfs:label\":\"Increase from baseline\", \"dct:description\":\"The pharmacogenomic biomarker is related to a recommendation to increase the dose of the drug from the recommended baseline.\"}," + "{\"@id\":\"urn:linkedspls:uuid:03B92CE6-A8F5-4AF9-8A68-10F48D1542EB\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000563\":\"poc:DrugSelectionRecommendation\", \"poc:DrugSelectionRecommendation\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#alternative-recommended\", \"rdfs:label\":\"Alternative Recommended\", \"dct:description\":\"The pharmacogenomic biomarker is related to a recommendation to use an alternative drug.\"}," + "{\"@id\":\"urn:linkedspls:uuid:14FC9A6F-F105-4BF7-B270-D4CB3A9FD966\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000563\":\"poc:PharmacokineticImpact\", \"poc:PharmacokineticImpact\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#absorption-increase\", \"rdfs:label\":\"Absorption Increase\", \"dct:description\":\"The pharmacogenomic biomarker is associated with a increase in absorption of the drug.\"}," + "{\"@id\":\"urn:linkedspls:uuid:47B1922D-DAF0-430C-84E9-4EAB3766AF76\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000563\":\"poc:PharmacodynamicImpact\", \"poc:PharmacodynamicImpact\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#drug-efficacy-increased-from-baseline\", \"rdfs:label\":\"Increased Efficacy\", \"dct:description\":\"The pharmacogenomic biomarker is associated with an increase in the efficacy of the drug. \"}]" + ",\"pav:lineageUri\":\"urn:domeoserver:annotation:A3653D48-231D-44CE-A309-B2C2F4311404\",\"pav:previousVersion\":\"\",\"@id\":\"urn:domeoclient:uuid:8E11483E-4C21-4188-AC79-B5BADA60ECE9\",\"pav:createdOn\":\"2014-01-22 17:35:52 -0500\"}],\"rdfs:label\":\"Default Set\",\"ao:annotatesResource\":\"http://127.0.0.1:8888/tests/SPL-annotation/Warfarin-ab047628-67d0-4a64-8d77-36b054969b44.html\",\"domeo:resources\":[{\"label\":\"WARFARIN SODIUM TABLET [AMERICAN HEALTH PACKAGING]\",\"url\":\"http://127.0.0.1:8888/tests/SPL-annotation/Warfarin-ab047628-67d0-4a64-8d77-36b054969b44.html\"}],\"@type\":\"ao:AnnotationSet\",\"pav:createdBy\":\"urn:person:uuid:080e1430434f70e501434f711b6e0000\",\"pav:lastSavedOn\":\"2014-01-22 17:35:57 -0500\",\"pav:versionNumber\":\"1\",\"permissions:permissions\":{\"permissions:isLocked\":\"false\",\"permissions:accessType\":\"urn:domeo:access:public\"},\"pav:lineageUri\":\"urn:domeoserver:annotationset:65B8CECA-8AFA-47C2-B14C-60ECB6FEC4F2\",\"domeo:agents\":[{\"rdfs:label\":\"boycer\",\"foafx:middlename\":\"\",\"foafx:lastname\":\"Boyce\",\"@type\":\"foafx:Person\",\"foafx:homepage\":\"\",\"foafx:picture\":\" http://www.hcklab.org/images/me/paolo%20ciccarese-boston.jpg\",\"foafx:email\":\"[email protected]\",\"foafx:firstname\":\"Richard\",\"foafx:title\":\"\",\"@id\":\"urn:person:uuid:080e1430434f70e501434f711b6e0000\",\"foafx:name\":\"boycer\"},{\"foafx:build\":\"040\",\"rdfs:label\":\"Domeo Annotation Toolkit\",\"@type\":\"foafx:Software\",\"foafx:homepage\":\"\",\"@id\":\"urn:domeo:software:id:Domeo-2.0alpha-040\",\"foafx:name\":\"Domeo Annotation Toolkit\",\"foafx:version\":\"2.0alpha\"}],\"pav:previousVersion\":\"\",\"dct:description\":\"The default set is created automatically by Domeo when no other set is existing.\",\"@id\":\"urn:domeoclient:uuid:B2CBE747-9368-48D3-8AB8-0ECDA72850D1\",\"pav:createdOn\":\"2014-01-22 17:35:44 -0500\"}]"; */ JsArray<JsAnnotationSet> sets = asArrayOfAnnotationSets(json); return sets; } }
test function for new json string with new field HGNCGene
src/org/mindinformatics/gwt/domeo/plugins/annotation/persistence/service/AnnotationPersistenceServiceFacade.java
test function for new json string with new field HGNCGene
<ide><path>rc/org/mindinformatics/gwt/domeo/plugins/annotation/persistence/service/AnnotationPersistenceServiceFacade.java <ide> <ide> <ide> String json = "[{\"pav:createdWith\":\"urn:domeo:software:id:Domeo-2.0alpha-040\",\"ao:item\":[{\"pav:createdWith\":\"urn:domeo:software:id:Domeo-2.0alpha-040\",\"rdfs:label\":\"SPL Annotation\",\"@type\":\"ao:SPLAnnotation\",\"domeo:belongsToSet\":\"urn:domeoclient:uuid:B2CBE747-9368-48D3-8AB8-0ECDA72850D1\",\"pav:createdBy\":\"urn:person:uuid:080e1430434f70e501434f711b6e0000\",\"pav:versionNumber\":\"1\",\"pav:lastSavedOn\":\"2014-01-22 17:35:57 -0500\",\"ao:context\":[{\"ao:hasSource\":\"http://127.0.0.1:8888/tests/SPL-annotation/Warfarin-ab047628-67d0-4a64-8d77-36b054969b44.html\",\"@type\":\"ao:SpecificResource\",\"@id\":\"urn:domeoclient:uuid:54CDC1E5-65E1-480A-A1C4-957BD32F7308\",\"domeo_temp_localId\":\"1\",\"ao:hasSelector\":{\"ao:prefix\":\"These highlights do not include all the information needed to use\",\"@type\":\"ao:PrefixSuffixTextSelector\",\"@id\":\"urn:domeoclient:uuid:54CDC1E5-65E1-480A-A1C4-957BD32F7308\",\"domeo_temp_localId\":\"1\",\"pav:createdOn\":\"2014-01-22 17:35:52 -0500\",\"ao:exact\":\" warfarin sodium safely and effectively. See full \",\"ao:suffix\":\"prescribing information for warfarin sodium.\",\"domeo:uuid\":\"54CDC1E5-65E1-480A-A1C4-957BD32F7308\"}}],\"ao:body\":" + <del> "[{\"@id\":\"urn:linkedspls:uuid:51BF9FB2-0876-4618-953D-3E4279563F5A\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000628\":\"dailymed:ConcomitantMedicationOfConcern\", \"dailymed:ConcomitantMedicationOfConcern\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#concomitant-medication-concern\", \"rdfs:label\":\"Concomitant medication concern\", \"dct:description\":\"A concomitant medication of concern is mentioned.\"}," + <add> "[{\"@id\":\"urn:linkedspls:uuid:542ADED5-899D-46AC-966A-F35B9BDA0723\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000628\":\"dailymed:HGNCGeneSymbol\", \"dailymed:HGNCGeneSymbol\":\"http://bio2rdf.org/hgnc:11929\", \"rdfs:label\":\"BAFF/TNFSF13B\", \"dct:description\":\"The selected HGNCGeneSymbol.\"}," + <add> "{\"@id\":\"urn:linkedspls:uuid:51BF9FB2-0876-4618-953D-3E4279563F5A\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000628\":\"dailymed:ConcomitantMedicationOfConcern\", \"dailymed:ConcomitantMedicationOfConcern\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#concomitant-medication-concern\", \"rdfs:label\":\"Concomitant medication concern\", \"dct:description\":\"A concomitant medication of concern is mentioned.\"}," + <ide> "{\"@id\":\"urn:linkedspls:uuid:E20B7EDA-2D14-402B-BE68-8B6F35E262A5\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000563\":\"poc:VariantFrequency\", \"poc:VariantFrequency\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#population-frequency-mentioned\", \"rdfs:label\":\"Variant Frequency\", \"dct:description\":\"The frequency or proportion at which a variant occurs in a specific population is mentioned.\"}," + <ide> "{\"@id\":\"urn:linkedspls:uuid:AC117431-47DD-4A0A-B5A6-0AEA9D425094\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000628\":\"dailymed:ActiveMoiety\", \"dailymed:ActiveMoiety\":\"http://dbmi-icode-01.dbmi.pitt.edu/linkedSPLs/vocab/resource/ingredient-active\", \"rdfs:label\":\"Active ingredient\", \"dct:description\":\"the ingredient is active\"}," + <ide> "{\"@id\":\"urn:linkedspls:uuid:124D795F-C313-47D3-B601-D230D256BAFE\", \"@type\":\"poc:PharmacogenomicsStatement\", \"sio:SIO_000111\":\"BOXED WARNING (34066-1)\", \"poc:productLabelSection\":\"http://purl.org/net/nlprepository/spl-pharmgx-annotation-poc#BOXED WARNING (34066-1)\", \"rdfs:label\":\"SPL Section \", \"dct:description\":\"The section of the label where pharmacists identify clinical pharmgx statements\"}," +
JavaScript
mit
3bec1670a60f048eb203eb7c776859a6b86cc98b
0
wancharle/winston,pantheon-systems/winston,megastef/winston,unlucio/winston,whismat/winston,alinex/winston,tobli/winston,get-trucked/winston,jjmleiro/winston,z-10/winston,aquavitae/winston,psquickitjayant/winston,winstonjs/winston,thaliproject/winston,modulexcite/winston,paulhroth/winston,uber/winston,SmartNode-es/winston,winstonjs/winston,dustinblackman/winston,s-panferov/winston,rakesh-mohanta/winston,beni55/winston,auth0/winston,alphagov/winston,DenisGorbachev/winston,nikolas/winston,harriha/winston,apiaryio/winston,dbmikus/winston
var assert = require('assert'), winston = require('../../lib/winston'), helpers = require('../helpers'); module.exports = function (transport, options) { var logger = transport instanceof winston.Logger ? transport : new winston.Logger({ transports: [ new transport(options) ] }); var transport = logger.transports[logger._names[0]]; var out = { 'topic': logger, 'when passed valid options': { 'should have the proper methods defined': function () { switch (transport.name) { case 'console': helpers.assertConsole(transport); break; case 'file': helpers.assertFile(transport); break; case 'webhook': helpers.assertWebhook(transport); break; case 'couchdb': helpers.assertCouchdb(transport); break; } assert.isFunction(transport.log); } }, 'the log() method': helpers.testNpmLevels(transport, 'should respond with true', function (ign, err, logged) { assert.isNull(err); assert.isNotNull(logged); } ), 'the query() method': { 'using basic querying': { 'topic': function (logger) { if (!transport.query) return; var cb = this.callback; logger.log('info', 'hello world', {}, function () { logger.query({}, cb); }); }, 'should return matching results': function (err, results) { if (!transport.query) return; results = results[transport.name]; while (!Array.isArray(results)) { results = results[Object.keys(results).pop()]; } var log = results.pop(); assert.ok(log.message.indexOf('hello world') === 0 || log.message.indexOf('test message') === 0); } }, 'using the rows option': { 'topic': function (logger) { if (!transport.query) return; var cb = this.callback; logger.log('info', 'hello world', {}, function () { logger.query({ rows: 1 }, cb); }); }, 'should return one result': function (err, results) { if (!transport.query) return; results = results[transport.name]; while (!Array.isArray(results)) { results = results[Object.keys(results).pop()]; } //assert.equal(results.length, 1); } }, 'using fields and order option': { 'topic': function (logger) { if (!transport.query) return; var cb = this.callback; logger.log('info', 'hello world', {}, function () { logger.query({ order: 'asc', fields: ['timestamp'] }, cb); }); }, 'should return matching results': function (err, results) { if (!transport.query) return; results = results[transport.name]; while (!Array.isArray(results)) { results = results[Object.keys(results).pop()]; } //assert.equal(Object.keys(results[0]).length, 1); //assert.ok(new Date(results.shift().timestamp) // < new Date(results.pop().timestamp)); } } }, 'the stream() method': { 'topic': function () { if (!transport.stream) return; logger.log('info', 'hello world', {}); var cb = this.callback, j = 10, i = 10, results = [], stream = logger.stream({}); stream.on('log', function (log) { results.push(log); results.stream = stream; if (!--j) cb(null, results); }); stream.on('error', function () {}); while (i--) logger.log('info', 'hello world ' + i, {}); }, 'should stream logs': function (err, results) { if (!transport.stream) return; results.forEach(function (log) { assert.ok(log.message.indexOf('hello world') === 0 || log.message.indexOf('test message') === 0); }); results.stream.destroy(); } } }; // TODO: add couch and redis to .travis.yml if (process.env.CI && process.env.TRAVIS) { delete out['the query() method']; delete out['the stream() method']; } return out; };
test/transports/transport.js
var assert = require('assert'), winston = require('../../lib/winston'), helpers = require('../helpers'); module.exports = function (transport, options) { var logger = transport instanceof winston.Logger ? transport : new winston.Logger({ transports: [ new transport(options) ] }); var transport = logger.transports[logger._names[0]]; var out = { 'topic': logger, 'when passed valid options': { 'should have the proper methods defined': function () { switch (transport.name) { case 'console': helpers.assertConsole(transport); break; case 'file': helpers.assertFile(transport); break; case 'webhook': helpers.assertWebhook(transport); break; case 'couchdb': helpers.assertCouchdb(transport); break; } assert.isFunction(transport.log); } }, 'the log() method': helpers.testNpmLevels(transport, 'should respond with true', function (ign, err, logged) { assert.isNull(err); assert.isNotNull(logged); } ), 'the query() method': { 'topic': function (logger) { if (!transport.query) return; var cb = this.callback; logger.log('info', 'hello world', {}, function () { logger.query({}, cb); }); }, 'should return matching results': function (err, results) { if (!transport.query) return; results = results[transport.name]; while (!Array.isArray(results)) { results = results[Object.keys(results).pop()]; } var log = results.pop(); assert.ok(log.message.indexOf('hello world') === 0 || log.message.indexOf('test message') === 0); } }, 'the stream() method': { 'topic': function () { if (!transport.stream) return; logger.log('info', 'hello world', {}); var cb = this.callback, j = 10, i = 10, results = [], stream = logger.stream({}); stream.on('log', function (log) { results.push(log); results.stream = stream; if (!--j) cb(null, results); }); stream.on('error', function () {}); while (i--) logger.log('info', 'hello world ' + i, {}); }, 'should stream logs': function (err, results) { if (!transport.stream) return; results.forEach(function (log) { assert.ok(log.message.indexOf('hello world') === 0 || log.message.indexOf('test message') === 0); }); results.stream.destroy(); } } }; // TODO: add couch and redis to .travis.yml if (process.env.CI && process.env.TRAVIS) { delete out['the query() method']; delete out['the stream() method']; } return out; };
[test] more transport query tests.
test/transports/transport.js
[test] more transport query tests.
<ide><path>est/transports/transport.js <ide> } <ide> ), <ide> 'the query() method': { <del> 'topic': function (logger) { <del> if (!transport.query) return; <del> var cb = this.callback; <del> logger.log('info', 'hello world', {}, function () { <del> logger.query({}, cb); <del> }); <add> 'using basic querying': { <add> 'topic': function (logger) { <add> if (!transport.query) return; <add> var cb = this.callback; <add> logger.log('info', 'hello world', {}, function () { <add> logger.query({}, cb); <add> }); <add> }, <add> 'should return matching results': function (err, results) { <add> if (!transport.query) return; <add> results = results[transport.name]; <add> while (!Array.isArray(results)) { <add> results = results[Object.keys(results).pop()]; <add> } <add> var log = results.pop(); <add> assert.ok(log.message.indexOf('hello world') === 0 <add> || log.message.indexOf('test message') === 0); <add> } <ide> }, <del> 'should return matching results': function (err, results) { <del> if (!transport.query) return; <del> results = results[transport.name]; <del> while (!Array.isArray(results)) { <del> results = results[Object.keys(results).pop()]; <add> 'using the rows option': { <add> 'topic': function (logger) { <add> if (!transport.query) return; <add> var cb = this.callback; <add> logger.log('info', 'hello world', {}, function () { <add> logger.query({ rows: 1 }, cb); <add> }); <add> }, <add> 'should return one result': function (err, results) { <add> if (!transport.query) return; <add> results = results[transport.name]; <add> while (!Array.isArray(results)) { <add> results = results[Object.keys(results).pop()]; <add> } <add> //assert.equal(results.length, 1); <ide> } <del> var log = results.pop(); <del> assert.ok(log.message.indexOf('hello world') === 0 <del> || log.message.indexOf('test message') === 0); <add> }, <add> 'using fields and order option': { <add> 'topic': function (logger) { <add> if (!transport.query) return; <add> var cb = this.callback; <add> logger.log('info', 'hello world', {}, function () { <add> logger.query({ order: 'asc', fields: ['timestamp'] }, cb); <add> }); <add> }, <add> 'should return matching results': function (err, results) { <add> if (!transport.query) return; <add> results = results[transport.name]; <add> while (!Array.isArray(results)) { <add> results = results[Object.keys(results).pop()]; <add> } <add> //assert.equal(Object.keys(results[0]).length, 1); <add> //assert.ok(new Date(results.shift().timestamp) <add> // < new Date(results.pop().timestamp)); <add> } <ide> } <ide> }, <ide> 'the stream() method': {
Java
apache-2.0
1f7fc3482396893e0c2b3c85f6c63fd6183defdc
0
ontop/ontop,ontop/ontop,ontop/ontop,ontop/ontop,ontop/ontop
package it.unibz.inf.ontop.spec.mapping.transformer.impl; /* * #%L * ontop-reformulation-core * %% * Copyright (C) 2009 - 2014 Free University of Bozen-Bolzano * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import it.unibz.inf.ontop.datalog.CQIE; import it.unibz.inf.ontop.dbschema.*; import it.unibz.inf.ontop.exception.OntopInternalBugException; import it.unibz.inf.ontop.model.term.impl.FunctionalTermImpl; import it.unibz.inf.ontop.model.term.functionsymbol.BNodePredicate; import it.unibz.inf.ontop.model.term.functionsymbol.Predicate; import it.unibz.inf.ontop.model.term.functionsymbol.URITemplatePredicate; import it.unibz.inf.ontop.model.term.*; import it.unibz.inf.ontop.model.type.TermType; import it.unibz.inf.ontop.model.type.impl.TermTypeInferenceTools; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.stream.IntStream; import static it.unibz.inf.ontop.model.OntopModelSingletons.TERM_FACTORY; public class MappingDataTypeCompletion { private final DBMetadata metadata; private static final Logger log = LoggerFactory.getLogger(MappingDataTypeCompletion.class); /** * Constructs a new mapping data type resolution. * If no datatype is defined, then we use database metadata for obtaining the table column definition as the * default data-type. * //TODO: rewrite in a Datalog-free fashion * * @param metadata The database metadata. */ public MappingDataTypeCompletion(DBMetadata metadata) { this.metadata = metadata; } public void insertDataTyping(CQIE rule) { Function atom = rule.getHead(); Predicate predicate = atom.getFunctionSymbol(); if (predicate.getArity() == 2) { // we check both for data and object property Term term = atom.getTerm(1); // the second argument only Map<String, List<IndexedPosition>> termOccurenceIndex = createIndex(rule.getBody()); // Infer variable datatypes insertVariableDataTyping(term, atom, 1, termOccurenceIndex); // Infer operation datatypes from variable datatypes insertOperationDatatyping(term, atom, 1); } } /** * This method wraps the variable that holds data property values with a data type predicate. * It will replace the variable with a new function symbol and update the rule atom. * However, if the users already defined the data-type in the mapping, this method simply accepts the function symbol. */ private void insertVariableDataTyping(Term term, Function atom, int position, Map<String, List<IndexedPosition>> termOccurenceIndex) { Predicate predicate = atom.getFunctionSymbol(); if (term instanceof Function) { Function function = (Function) term; Predicate functionSymbol = function.getFunctionSymbol(); if (function.isDataTypeFunction() || (functionSymbol instanceof URITemplatePredicate) || (functionSymbol instanceof BNodePredicate)) { // NO-OP for already assigned datatypes, or object properties, or bnodes } else if (function.isOperation()) { for (int i = 0; i < function.getArity(); i++) { insertVariableDataTyping(function.getTerm(i), function, i, termOccurenceIndex); } } else { throw new IllegalArgumentException("Unsupported subtype of: " + Function.class.getSimpleName()); } } else if (term instanceof Variable) { Variable variable = (Variable) term; Term newTerm; Predicate.COL_TYPE type = getDataType(termOccurenceIndex, variable); newTerm = TERM_FACTORY.getTypedTerm(variable, type); log.info("Datatype "+type+" for the value " + variable + " of the property " + predicate + " has been " + "inferred " + "from the database"); atom.setTerm(position, newTerm); } else if (term instanceof ValueConstant) { Term newTerm = TERM_FACTORY.getTypedTerm(term, ((ValueConstant) term).getType()); atom.setTerm(position, newTerm); } else { throw new IllegalArgumentException("Unsupported subtype of: " + Term.class.getSimpleName()); } } /** * Infers inductively the datatypes of (evaluated) operations, from their operands. * After execution, only the outermost operation is assigned a type. */ private void insertOperationDatatyping(Term term, Function atom, int position) { if (term instanceof Function) { Function castTerm = (Function) term; if (castTerm.isOperation()) { Optional<TermType> inferredType = TermTypeInferenceTools.inferType(castTerm); if(inferredType.isPresent()){ // delete explicit datatypes of the operands deleteExplicitTypes(term, atom, position); // insert the datatype of the evaluated operation atom.setTerm( position, TERM_FACTORY.getTypedTerm( term, inferredType.get().getColType() )); }else { throw new IllegalStateException("A type should be inferred for operation " + castTerm); } } } } private void deleteExplicitTypes(Term term, Function atom, int position) { if(term instanceof Function){ Function castTerm = (Function) term; IntStream.range(0, castTerm.getArity()) .forEach(i -> deleteExplicitTypes( castTerm.getTerm(i), castTerm, i )); if(castTerm.isDataTypeFunction()){ atom.setTerm(position, castTerm.getTerm(0)); } } } /** * returns COL_TYPE for one of the datatype ids * * @param termOccurenceIndex * @param variable * @return */ private Predicate.COL_TYPE getDataType(Map<String, List<IndexedPosition>> termOccurenceIndex, Variable variable) { List<IndexedPosition> list = termOccurenceIndex.get(variable.getName()); if (list == null) throw new UnboundTargetVariableException(variable); // ROMAN (10 Oct 2015): this assumes the first occurrence is a database relation! // AND THAT THERE ARE NO CONSTANTS IN ARGUMENTS! IndexedPosition ip = list.get(0); RelationID tableId = Relation2Predicate.createRelationFromPredicateName(metadata.getQuotedIDFactory(), ip.atom .getFunctionSymbol()); RelationDefinition td = metadata.getRelation(tableId); Attribute attribute = td.getAttribute(ip.pos); return metadata.getColType(attribute) // Default datatype : XSD_STRING .orElse(Predicate.COL_TYPE.STRING); } private static class IndexedPosition { final Function atom; final int pos; IndexedPosition(Function atom, int pos) { this.atom = atom; this.pos = pos; } } private static Map<String, List<IndexedPosition>> createIndex(List<Function> body) { Map<String, List<IndexedPosition>> termOccurenceIndex = new HashMap<>(); for (Function a : body) { List<Term> terms = a.getTerms(); int i = 1; // position index for (Term t : terms) { if (t instanceof Variable) { Variable var = (Variable) t; List<IndexedPosition> aux = termOccurenceIndex.get(var.getName()); if (aux == null) aux = new LinkedList<>(); aux.add(new IndexedPosition(a, i)); termOccurenceIndex.put(var.getName(), aux); } else if (t instanceof FunctionalTermImpl) { // NO-OP } else if (t instanceof ValueConstant) { // NO-OP } else if (t instanceof URIConstant) { // NO-OP } // fabad (4 Oct 2017) Quick fix if there are constants in arguments. // Increase i in all cases. If there are terms that are not variables // and i is not incremented then indexedPosition.pos contains a wrong // index that may points to terms that are not variables. i++; // increase the position index for the next variable } } return termOccurenceIndex; } /** * Should have been detected earlier! */ private static class UnboundTargetVariableException extends OntopInternalBugException { protected UnboundTargetVariableException(Variable variable) { super("Unknown variable in the head of a mapping:" + variable + ". Should have been detected earlier !"); } } }
mapping/core/src/main/java/it/unibz/inf/ontop/spec/mapping/transformer/impl/MappingDataTypeCompletion.java
package it.unibz.inf.ontop.spec.mapping.transformer.impl; /* * #%L * ontop-reformulation-core * %% * Copyright (C) 2009 - 2014 Free University of Bozen-Bolzano * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import it.unibz.inf.ontop.datalog.CQIE; import it.unibz.inf.ontop.dbschema.*; import it.unibz.inf.ontop.exception.OntopInternalBugException; import it.unibz.inf.ontop.model.term.impl.FunctionalTermImpl; import it.unibz.inf.ontop.model.term.functionsymbol.BNodePredicate; import it.unibz.inf.ontop.model.term.functionsymbol.Predicate; import it.unibz.inf.ontop.model.term.functionsymbol.URITemplatePredicate; import it.unibz.inf.ontop.model.term.*; import it.unibz.inf.ontop.model.type.TermType; import it.unibz.inf.ontop.model.type.impl.TermTypeInferenceTools; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.stream.IntStream; import static it.unibz.inf.ontop.model.OntopModelSingletons.TERM_FACTORY; public class MappingDataTypeCompletion { private final DBMetadata metadata; private static final Logger log = LoggerFactory.getLogger(MappingDataTypeCompletion.class); /** * Constructs a new mapping data type resolution. * If no datatype is defined, then we use database metadata for obtaining the table column definition as the * default data-type. * //TODO: rewrite in a Datalog-free fashion * * @param metadata The database metadata. */ public MappingDataTypeCompletion(DBMetadata metadata) { this.metadata = metadata; } public void insertDataTyping(CQIE rule) { Function atom = rule.getHead(); Predicate predicate = atom.getFunctionSymbol(); if (predicate.getArity() == 2) { // we check both for data and object property Term term = atom.getTerm(1); // the second argument only Map<String, List<IndexedPosition>> termOccurenceIndex = createIndex(rule.getBody()); // Infer variable datatypes insertVariableDataTyping(term, atom, 1, termOccurenceIndex); // Infer operation datatypes from variable datatypes insertOperationDatatyping(term, atom, 1); } } /** * This method wraps the variable that holds data property values with a data type predicate. * It will replace the variable with a new function symbol and update the rule atom. * However, if the users already defined the data-type in the mapping, this method simply accepts the function symbol. */ private void insertVariableDataTyping(Term term, Function atom, int position, Map<String, List<IndexedPosition>> termOccurenceIndex) { Predicate predicate = atom.getFunctionSymbol(); if (term instanceof Function) { Function function = (Function) term; Predicate functionSymbol = function.getFunctionSymbol(); if (function.isDataTypeFunction() || (functionSymbol instanceof URITemplatePredicate) || (functionSymbol instanceof BNodePredicate)) { // NO-OP for already assigned datatypes, or object properties, or bnodes } else if (function.isOperation()) { for (int i = 0; i < function.getArity(); i++) { insertVariableDataTyping(function.getTerm(i), function, i, termOccurenceIndex); } } else { throw new IllegalArgumentException("Unsupported subtype of: " + Function.class.getSimpleName()); } } else if (term instanceof Variable) { Variable variable = (Variable) term; Term newTerm; Predicate.COL_TYPE type = getDataType(termOccurenceIndex, variable); newTerm = TERM_FACTORY.getTypedTerm(variable, type); log.info("Datatype "+type+" for the value " + variable + " of the property " + predicate + " has been " + "inferred " + "from the database"); atom.setTerm(position, newTerm); } else if (term instanceof ValueConstant) { Term newTerm = TERM_FACTORY.getTypedTerm(term, ((ValueConstant) term).getType()); atom.setTerm(position, newTerm); } else { throw new IllegalArgumentException("Unsupported subtype of: " + Term.class.getSimpleName()); } } /** * Infers inductively the datatypes of (evaluated) operations, from their operands. * After execution, only the outermost operation is assigned a type. */ private void insertOperationDatatyping(Term term, Function atom, int position) { if (term instanceof Function) { Function castTerm = (Function) term; if (castTerm.isOperation()) { Optional<TermType> inferredType = TermTypeInferenceTools.inferType(castTerm); if(inferredType.isPresent()){ // delete explicit datatypes of the operands deleteExplicitTypes(term, atom, position); // insert the datatype of the evaluated operation atom.setTerm( position, TERM_FACTORY.getTypedTerm( term, inferredType.get().getColType() )); }else { throw new IllegalStateException("A type should be inferred for operation " + castTerm); } } } } private void deleteExplicitTypes(Term term, Function atom, int position) { if(term instanceof Function){ Function castTerm = (Function) term; IntStream.range(0, castTerm.getArity()) .forEach(i -> deleteExplicitTypes( castTerm.getTerm(i), castTerm, i )); if(castTerm.isDataTypeFunction()){ atom.setTerm(position, castTerm.getTerm(0)); } } } /** * returns COL_TYPE for one of the datatype ids * * @param termOccurenceIndex * @param variable * @return */ private Predicate.COL_TYPE getDataType(Map<String, List<IndexedPosition>> termOccurenceIndex, Variable variable) { List<IndexedPosition> list = termOccurenceIndex.get(variable.getName()); if (list == null) throw new UnboundTargetVariableException(variable); // ROMAN (10 Oct 2015): this assumes the first occurrence is a database relation! // AND THAT THERE ARE NO CONSTANTS IN ARGUMENTS! IndexedPosition ip = list.get(0); RelationID tableId = Relation2Predicate.createRelationFromPredicateName(metadata.getQuotedIDFactory(), ip.atom .getFunctionSymbol()); RelationDefinition td = metadata.getRelation(tableId); // fabad (4 Oct 2017) Quick fix if there are constants in arguments. // Calculate the attribute position taking account on how many constants // are before the attribute in the list. int attributePos = this.getAttributePos(ip, variable); Attribute attribute = td.getAttribute(attributePos); return metadata.getColType(attribute) // Default datatype : XSD_STRING .orElse(Predicate.COL_TYPE.STRING); } private int getAttributePos(IndexedPosition ip, Variable variable) { int constBeforeAttribute = 0; for(Term term : ip.atom.getTerms()){ if(term.equals(variable)){ break; } if(term instanceof ValueConstant){ constBeforeAttribute++; } } return ip.pos + constBeforeAttribute; } private static class IndexedPosition { final Function atom; final int pos; IndexedPosition(Function atom, int pos) { this.atom = atom; this.pos = pos; } } private static Map<String, List<IndexedPosition>> createIndex(List<Function> body) { Map<String, List<IndexedPosition>> termOccurenceIndex = new HashMap<>(); for (Function a : body) { List<Term> terms = a.getTerms(); int i = 1; // position index for (Term t : terms) { if (t instanceof Variable) { Variable var = (Variable) t; List<IndexedPosition> aux = termOccurenceIndex.get(var.getName()); if (aux == null) aux = new LinkedList<>(); aux.add(new IndexedPosition(a, i)); termOccurenceIndex.put(var.getName(), aux); i++; // increase the position index for the next variable } else if (t instanceof FunctionalTermImpl) { // NO-OP } else if (t instanceof ValueConstant) { // NO-OP } else if (t instanceof URIConstant) { // NO-OP } } } return termOccurenceIndex; } /** * Should have been detected earlier! */ private static class UnboundTargetVariableException extends OntopInternalBugException { protected UnboundTargetVariableException(Variable variable) { super("Unknown variable in the head of a mapping:" + variable + ". Should have been detected earlier !"); } } }
Update MappingDataTypeCompletion.java Better solution by incrementing counter.
mapping/core/src/main/java/it/unibz/inf/ontop/spec/mapping/transformer/impl/MappingDataTypeCompletion.java
Update MappingDataTypeCompletion.java
<ide><path>apping/core/src/main/java/it/unibz/inf/ontop/spec/mapping/transformer/impl/MappingDataTypeCompletion.java <ide> .getFunctionSymbol()); <ide> RelationDefinition td = metadata.getRelation(tableId); <ide> <del> // fabad (4 Oct 2017) Quick fix if there are constants in arguments. <del> // Calculate the attribute position taking account on how many constants <del> // are before the attribute in the list. <del> int attributePos = this.getAttributePos(ip, variable); <del> Attribute attribute = td.getAttribute(attributePos); <add> <add> Attribute attribute = td.getAttribute(ip.pos); <ide> <ide> return metadata.getColType(attribute) <ide> // Default datatype : XSD_STRING <ide> .orElse(Predicate.COL_TYPE.STRING); <ide> } <del> <del> private int getAttributePos(IndexedPosition ip, Variable variable) { <del> int constBeforeAttribute = 0; <del> for(Term term : ip.atom.getTerms()){ <del> if(term.equals(variable)){ <del> break; <del> } <del> <del> if(term instanceof ValueConstant){ <del> constBeforeAttribute++; <del> } <del> } <del> <del> <del> return ip.pos + constBeforeAttribute; <del> } <ide> <ide> private static class IndexedPosition { <ide> final Function atom; <ide> aux = new LinkedList<>(); <ide> aux.add(new IndexedPosition(a, i)); <ide> termOccurenceIndex.put(var.getName(), aux); <del> i++; // increase the position index for the next variable <add> <ide> } else if (t instanceof FunctionalTermImpl) { <ide> // NO-OP <ide> } else if (t instanceof ValueConstant) { <ide> } else if (t instanceof URIConstant) { <ide> // NO-OP <ide> } <add> // fabad (4 Oct 2017) Quick fix if there are constants in arguments. <add> // Increase i in all cases. If there are terms that are not variables <add> // and i is not incremented then indexedPosition.pos contains a wrong <add> // index that may points to terms that are not variables. <add> i++; // increase the position index for the next variable <ide> } <ide> } <ide> return termOccurenceIndex; <ide> <ide> } <ide> <del>
Java
epl-1.0
56f21aed305af2a5c0deb010916722d79349df18
0
Charling-Huang/birt,sguan-actuate/birt,Charling-Huang/birt,rrimmana/birt-1,Charling-Huang/birt,rrimmana/birt-1,sguan-actuate/birt,sguan-actuate/birt,sguan-actuate/birt,rrimmana/birt-1,Charling-Huang/birt,sguan-actuate/birt,rrimmana/birt-1,Charling-Huang/birt,rrimmana/birt-1
/*********************************************************************** * Copyright (c) 2009 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.engine.nLayout.area.impl; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.report.engine.content.IContent; import org.eclipse.birt.report.engine.content.IForeignContent; import org.eclipse.birt.report.engine.nLayout.LayoutContext; import org.eclipse.birt.report.engine.nLayout.LayoutEngine; import org.eclipse.birt.report.engine.nLayout.area.ILayout; public class ForeignHTMLRegionLayout implements ILayout { private ContainerArea parent; private IForeignContent content; private LayoutContext context; public ForeignHTMLRegionLayout( ContainerArea parent, LayoutContext context, IForeignContent foreign ) { this.parent = parent; this.content = foreign; this.context = context; } public void layout( ) throws BirtException { LayoutContext regionLayoutContext = new LayoutContext( ); regionLayoutContext.setFormat( "pdf" ); regionLayoutContext.setFixedLayout( true ); regionLayoutContext.setLocale( context.getLocale( ) ); regionLayoutContext.setHtmlLayoutContext( context .getHtmlLayoutContext( ) ); regionLayoutContext.setMaxBP( Integer.MAX_VALUE ); regionLayoutContext.setMaxHeight( Integer.MAX_VALUE ); regionLayoutContext.setReport( context.getReport( ) ); ForeignHtmlRegionArea region = new ForeignHtmlRegionArea( content, regionLayoutContext ); region.setParent( parent ); ForeignHTMLRegionLayoutEngine regionLayoutEngine = new ForeignHTMLRegionLayoutEngine( region, regionLayoutContext ); regionLayoutEngine.layout( content ); if ( parent != null ) { parent.add( region ); if ( !parent.isInInlineStacking && context.isAutoPageBreak( ) ) { int aHeight = region.getAllocatedHeight( ); if ( aHeight + parent.getAbsoluteBP( ) > context.getMaxBP( ) ) { parent.autoPageBreak( ); // The RootArea's autoPageBreak() will update the children. // So return to avoid updating current area into RootArea // twice. if ( parent instanceof RootArea ) { return; } } } parent.update( region ); } } class ForeignHTMLRegionLayoutEngine extends LayoutEngine { protected ContainerArea root; public ForeignHTMLRegionLayoutEngine( ContainerArea container, LayoutContext context ) { super( context ); current = container; root = container; if ( parent != null ) { current.setMaxAvaWidth( parent.getMaxAvaWidth( ) ); } } public void layout( IContent content ) throws BirtException { current.initialize( ); //if width is specified. set MAX width if (current.specifiedWidth > 0) { current.setMaxAvaWidth(current.specifiedWidth); } if ( current.getSpecifiedHeight( ) <= 0 ) { visitChildren( content, this ); } while (current != root) { current.close(); current = current.getParent(); } current.close( ); } } }
engine/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/nLayout/area/impl/ForeignHTMLRegionLayout.java
/*********************************************************************** * Copyright (c) 2009 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.engine.nLayout.area.impl; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.report.engine.content.IContent; import org.eclipse.birt.report.engine.content.IForeignContent; import org.eclipse.birt.report.engine.nLayout.LayoutContext; import org.eclipse.birt.report.engine.nLayout.LayoutEngine; import org.eclipse.birt.report.engine.nLayout.area.ILayout; public class ForeignHTMLRegionLayout implements ILayout { private ContainerArea parent; private IForeignContent content; private LayoutContext context; public ForeignHTMLRegionLayout( ContainerArea parent, LayoutContext context, IForeignContent foreign ) { this.parent = parent; this.content = foreign; this.context = context; } public void layout( ) throws BirtException { LayoutContext regionLayoutContext = new LayoutContext( ); regionLayoutContext.setFormat( "pdf" ); regionLayoutContext.setFixedLayout( true ); regionLayoutContext.setLocale( context.getLocale( ) ); regionLayoutContext.setHtmlLayoutContext( context .getHtmlLayoutContext( ) ); regionLayoutContext.setMaxBP( Integer.MAX_VALUE ); regionLayoutContext.setMaxHeight( Integer.MAX_VALUE ); regionLayoutContext.setReport( context.getReport( ) ); ForeignHtmlRegionArea region = new ForeignHtmlRegionArea( content, regionLayoutContext ); region.setParent( parent ); ForeignHTMLRegionLayoutEngine regionLayoutEngine = new ForeignHTMLRegionLayoutEngine( region, regionLayoutContext ); regionLayoutEngine.layout( content ); if ( parent != null ) { parent.add( region ); if ( !parent.isInInlineStacking && context.isAutoPageBreak( ) ) { int aHeight = region.getAllocatedHeight( ); if ( aHeight + parent.getAbsoluteBP( ) > context.getMaxBP( ) ) { parent.autoPageBreak( ); } } parent.update( region ); } } class ForeignHTMLRegionLayoutEngine extends LayoutEngine { protected ContainerArea root; public ForeignHTMLRegionLayoutEngine( ContainerArea container, LayoutContext context ) { super( context ); current = container; root = container; if ( parent != null ) { current.setMaxAvaWidth( parent.getMaxAvaWidth( ) ); } } public void layout( IContent content ) throws BirtException { current.initialize( ); //if width is specified. set MAX width if (current.specifiedWidth > 0) { current.setMaxAvaWidth(current.specifiedWidth); } if ( current.getSpecifiedHeight( ) <= 0 ) { visitChildren( content, this ); } while (current != root) { current.close(); current = current.getParent(); } current.close( ); } } }
Fixed One more empty page shows for attached report 63143
engine/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/nLayout/area/impl/ForeignHTMLRegionLayout.java
Fixed One more empty page shows for attached report 63143
<ide><path>ngine/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/nLayout/area/impl/ForeignHTMLRegionLayout.java <ide> if ( aHeight + parent.getAbsoluteBP( ) > context.getMaxBP( ) ) <ide> { <ide> parent.autoPageBreak( ); <add> // The RootArea's autoPageBreak() will update the children. <add> // So return to avoid updating current area into RootArea <add> // twice. <add> if ( parent instanceof RootArea ) <add> { <add> return; <add> } <ide> } <ide> } <ide> parent.update( region );
Java
apache-2.0
67a9006153330c8169c2269276b011fe5a72f00f
0
jiman94/BroadleafCommerce-BroadleafCommerce2014,jiman94/BroadleafCommerce-BroadleafCommerce2014,arshadalisoomro/BroadleafCommerce,wenmangbo/BroadleafCommerce,liqianggao/BroadleafCommerce,gengzhengtao/BroadleafCommerce,lgscofield/BroadleafCommerce,passion1014/metaworks_framework,caosg/BroadleafCommerce,caosg/BroadleafCommerce,cogitoboy/BroadleafCommerce,sitexa/BroadleafCommerce,gengzhengtao/BroadleafCommerce,bijukunjummen/BroadleafCommerce,macielbombonato/BroadleafCommerce,alextiannus/BroadleafCommerce,trombka/blc-tmp,udayinfy/BroadleafCommerce,cloudbearings/BroadleafCommerce,cloudbearings/BroadleafCommerce,zhaorui1/BroadleafCommerce,passion1014/metaworks_framework,trombka/blc-tmp,alextiannus/BroadleafCommerce,trombka/blc-tmp,sitexa/BroadleafCommerce,liqianggao/BroadleafCommerce,lgscofield/BroadleafCommerce,sanlingdd/broadleaf,shopizer/BroadleafCommerce,daniellavoie/BroadleafCommerce,zhaorui1/BroadleafCommerce,bijukunjummen/BroadleafCommerce,cloudbearings/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,rawbenny/BroadleafCommerce,gengzhengtao/BroadleafCommerce,arshadalisoomro/BroadleafCommerce,wenmangbo/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,passion1014/metaworks_framework,ljshj/BroadleafCommerce,sitexa/BroadleafCommerce,TouK/BroadleafCommerce,bijukunjummen/BroadleafCommerce,arshadalisoomro/BroadleafCommerce,cengizhanozcan/BroadleafCommerce,cengizhanozcan/BroadleafCommerce,daniellavoie/BroadleafCommerce,udayinfy/BroadleafCommerce,daniellavoie/BroadleafCommerce,cogitoboy/BroadleafCommerce,TouK/BroadleafCommerce,liqianggao/BroadleafCommerce,shopizer/BroadleafCommerce,wenmangbo/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,macielbombonato/BroadleafCommerce,ljshj/BroadleafCommerce,cengizhanozcan/BroadleafCommerce,cogitoboy/BroadleafCommerce,shopizer/BroadleafCommerce,lgscofield/BroadleafCommerce,zhaorui1/BroadleafCommerce,caosg/BroadleafCommerce,rawbenny/BroadleafCommerce,ljshj/BroadleafCommerce,sanlingdd/broadleaf,TouK/BroadleafCommerce,udayinfy/BroadleafCommerce,alextiannus/BroadleafCommerce,macielbombonato/BroadleafCommerce,rawbenny/BroadleafCommerce
/* * #%L * BroadleafCommerce Framework * %% * Copyright (C) 2009 - 2013 Broadleaf Commerce * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package org.broadleafcommerce.core.payment.service; import org.broadleafcommerce.common.money.Money; import org.broadleafcommerce.common.payment.PaymentType; import org.broadleafcommerce.common.payment.dto.PaymentRequestDTO; import org.broadleafcommerce.core.order.domain.FulfillmentGroup; import org.broadleafcommerce.core.order.domain.Order; import org.broadleafcommerce.core.payment.domain.OrderPayment; import org.broadleafcommerce.core.payment.domain.PaymentTransaction; import org.broadleafcommerce.profile.core.domain.Address; import org.broadleafcommerce.profile.core.domain.Customer; import org.broadleafcommerce.profile.core.domain.CustomerPhone; import org.springframework.stereotype.Service; import java.io.Serializable; import java.util.List; import java.util.Map; /** * @author Elbert Bautista (elbertbautista) */ @Service("blOrderToPaymentRequestDTOService") public class OrderToPaymentRequestDTOServiceImpl implements OrderToPaymentRequestDTOService { public static final String ZERO_TOTAL = "0"; @Override public PaymentRequestDTO translateOrder(Order order) { if (order != null) { PaymentRequestDTO requestDTO = new PaymentRequestDTO() .orderId(order.getId().toString()) .orderCurrencyCode(order.getCurrency().getCurrencyCode()); populateCustomerInfo(order, requestDTO); populateShipTo(order, requestDTO); populateBillTo(order, requestDTO); populateTotals(order, requestDTO); populateDefaultLineItemsAndSubtotal(order, requestDTO); return requestDTO; } return null; } @Override public PaymentRequestDTO translatePaymentTransaction(Money transactionAmount, PaymentTransaction paymentTransaction) { //Will set the full amount to be charged on the transaction total/subtotal and not worry about shipping/tax breakdown PaymentRequestDTO requestDTO = new PaymentRequestDTO() .transactionTotal(transactionAmount.getAmount().toPlainString()) .orderSubtotal(transactionAmount.getAmount().toPlainString()) .shippingTotal(ZERO_TOTAL) .taxTotal(ZERO_TOTAL) .orderCurrencyCode(paymentTransaction.getOrderPayment().getCurrency().getCurrencyCode()) .orderId(paymentTransaction.getOrderPayment().getOrder().getId().toString()); //Copy Additional Fields from PaymentTransaction into the Request DTO. //This will contain any gateway specific information needed to perform actions on this transaction Map<String, String> additionalFields = paymentTransaction.getAdditionalFields(); for (String key : additionalFields.keySet()) { requestDTO.additionalField(key, additionalFields.get(key)); } return requestDTO; } protected void populateTotals(Order order, PaymentRequestDTO requestDTO) { String total = ZERO_TOTAL; String shippingTotal = ZERO_TOTAL; String taxTotal = ZERO_TOTAL; if (order.getTotalAfterAppliedPayments() != null) { total = order.getTotalAfterAppliedPayments().toString(); } if (order.getTotalShipping() != null) { shippingTotal = order.getTotalShipping().toString(); } if (order.getTotalTax() != null) { taxTotal = order.getTotalTax().toString(); } requestDTO.transactionTotal(total) .shippingTotal(shippingTotal) .taxTotal(taxTotal) .orderCurrencyCode(order.getCurrency().getCurrencyCode()); } protected void populateCustomerInfo(Order order, PaymentRequestDTO requestDTO) { Customer customer = order.getCustomer(); String phoneNumber = null; if (customer.getCustomerPhones() != null && !customer.getCustomerPhones().isEmpty()) { for (CustomerPhone phone : customer.getCustomerPhones()) { if (phone.getPhone().isDefault()) { phoneNumber = phone.getPhone().getPhoneNumber(); } } } String orderEmail = (customer.getEmailAddress() == null)? order.getEmailAddress() : customer.getEmailAddress(); requestDTO.customer() .customerId(customer.getId().toString()) .firstName(customer.getFirstName()) .lastName(customer.getLastName()) .email(orderEmail) .phone(phoneNumber); } protected void populateShipTo(Order order, PaymentRequestDTO requestDTO) { List<FulfillmentGroup> fgs = order.getFulfillmentGroups(); if (fgs != null && fgs.size() > 0) { // TODO: Absolutely cannot assume this FulfillmentGroup defaultFg = fgs.get(0); if (defaultFg.getAddress() != null) { Address fgAddress = defaultFg.getAddress(); String stateAbbr = null; String countryAbbr = null; String phone = null; if (fgAddress.getState() != null) { stateAbbr = fgAddress.getState().getAbbreviation(); } if (fgAddress.getCountry() != null) { countryAbbr = fgAddress.getCountry().getAbbreviation(); } if (fgAddress.getPhonePrimary() != null) { phone = fgAddress.getPhonePrimary().getPhoneNumber(); } requestDTO.shipTo() .addressFirstName(fgAddress.getFirstName()) .addressLastName(fgAddress.getLastName()) .addressCompanyName(fgAddress.getCompanyName()) .addressLine1(fgAddress.getAddressLine1()) .addressLine2(fgAddress.getAddressLine2()) .addressCityLocality(fgAddress.getCity()) .addressStateRegion(stateAbbr) .addressPostalCode(fgAddress.getPostalCode()) .addressCountryCode(countryAbbr) .addressPhone(phone) .addressEmail(fgAddress.getEmailAddress()); } } } protected void populateBillTo(Order order, PaymentRequestDTO requestDTO) { List<OrderPayment> payments = order.getPayments(); for (OrderPayment payment : payments) { if (PaymentType.CREDIT_CARD.equals(payment.getType())) { Address billAddress = payment.getBillingAddress(); String stateAbbr = null; String countryAbbr = null; String phone = null; if (billAddress.getState() != null) { stateAbbr = billAddress.getState().getAbbreviation(); } if (billAddress.getCountry() != null) { countryAbbr = billAddress.getCountry().getAbbreviation(); } if (billAddress.getPhonePrimary() != null) { phone = billAddress.getPhonePrimary().getPhoneNumber(); } requestDTO.billTo() .addressFirstName(billAddress.getFirstName()) .addressLastName(billAddress.getLastName()) .addressCompanyName(billAddress.getCompanyName()) .addressLine1(billAddress.getAddressLine1()) .addressLine2(billAddress.getAddressLine2()) .addressCityLocality(billAddress.getCity()) .addressStateRegion(stateAbbr) .addressPostalCode(billAddress.getPostalCode()) .addressCountryCode(countryAbbr) .addressPhone(phone) .addressEmail(billAddress.getEmailAddress()); } } } /** * IMPORTANT: * <p>If you would like to pass Line Item information to a payment gateway * so that it shows up on the hosted site, you will need to override this method and * construct line items to conform to the requirements of that particular gateway:</p> * * <p>For Example: The Paypal Express Checkout NVP API validates that the order subtotal that you pass in, * add up to the amount of the line items that you pass in. So, * In that case you will need to take into account any additional fees, promotions, * credits, gift cards, etc... that are applied to the payment and add them * as additional line items with a negative amount when necessary.</p> * * <p>Each gateway that accepts line item information may require you to construct * this differently. Please consult the module documentation on how it should * be properly constructed.</p> * * <p>In this default implementation, just the subtotal is set, without any line item details.</p> * * @param order * @param requestDTO */ protected void populateDefaultLineItemsAndSubtotal(Order order, PaymentRequestDTO requestDTO) { requestDTO.orderSubtotal(order.getSubTotal().toString()); } }
core/broadleaf-framework/src/main/java/org/broadleafcommerce/core/payment/service/OrderToPaymentRequestDTOServiceImpl.java
/* * #%L * BroadleafCommerce Framework * %% * Copyright (C) 2009 - 2013 Broadleaf Commerce * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package org.broadleafcommerce.core.payment.service; import org.broadleafcommerce.common.money.Money; import org.broadleafcommerce.common.payment.PaymentType; import org.broadleafcommerce.common.payment.dto.PaymentRequestDTO; import org.broadleafcommerce.core.order.domain.FulfillmentGroup; import org.broadleafcommerce.core.order.domain.Order; import org.broadleafcommerce.core.payment.domain.OrderPayment; import org.broadleafcommerce.core.payment.domain.PaymentTransaction; import org.broadleafcommerce.profile.core.domain.Address; import org.broadleafcommerce.profile.core.domain.Customer; import org.broadleafcommerce.profile.core.domain.CustomerPhone; import org.springframework.stereotype.Service; import java.io.Serializable; import java.util.List; import java.util.Map; /** * @author Elbert Bautista (elbertbautista) */ @Service("blOrderToPaymentRequestDTOService") public class OrderToPaymentRequestDTOServiceImpl implements OrderToPaymentRequestDTOService { public static final String ZERO_TOTAL = "0"; @Override public PaymentRequestDTO translateOrder(Order order) { if (order != null) { PaymentRequestDTO requestDTO = new PaymentRequestDTO() .orderId(order.getId().toString()) .orderCurrencyCode(order.getCurrency().getCurrencyCode()); populateCustomerInfo(order, requestDTO); populateShipTo(order, requestDTO); populateBillTo(order, requestDTO); populateTotals(order, requestDTO); populateDefaultLineItemsAndSubtotal(order, requestDTO); return requestDTO; } return null; } @Override public PaymentRequestDTO translatePaymentTransaction(Money transactionAmount, PaymentTransaction paymentTransaction) { //Will set the full amount to be charged on the transaction total/subtotal and not worry about shipping/tax breakdown PaymentRequestDTO requestDTO = new PaymentRequestDTO() .transactionTotal(transactionAmount.getAmount().toPlainString()) .orderSubtotal(transactionAmount.getAmount().toPlainString()) .shippingTotal(ZERO_TOTAL) .taxTotal(ZERO_TOTAL) .orderCurrencyCode(paymentTransaction.getOrderPayment().getCurrency().getCurrencyCode()) .orderId(paymentTransaction.getOrderPayment().getOrder().getId().toString()); //Copy Additional Fields from PaymentTransaction into the Request DTO. //This will contain any gateway specific information needed to perform actions on this transaction Map<String, String> additionalFields = paymentTransaction.getAdditionalFields(); for (String key : additionalFields.keySet()) { requestDTO.additionalField(key, additionalFields.get(key)); } return requestDTO; } protected void populateTotals(Order order, PaymentRequestDTO requestDTO) { String total = ZERO_TOTAL; String shippingTotal = ZERO_TOTAL; String taxTotal = ZERO_TOTAL; if (order.getTotalAfterAppliedPayments() != null) { total = order.getTotalAfterAppliedPayments().toString(); } if (order.getTotalShipping() != null) { shippingTotal = order.getTotalShipping().toString(); } if (order.getTotalTax() != null) { taxTotal = order.getTotalTax().toString(); } requestDTO.transactionTotal(total) .shippingTotal(shippingTotal) .taxTotal(taxTotal) .orderCurrencyCode(order.getCurrency().getCurrencyCode()); } protected void populateCustomerInfo(Order order, PaymentRequestDTO requestDTO) { Customer customer = order.getCustomer(); String phoneNumber = null; if (customer.getCustomerPhones() != null && !customer.getCustomerPhones().isEmpty()) { for (CustomerPhone phone : customer.getCustomerPhones()) { if (phone.getPhone().isDefault()) { phoneNumber = phone.getPhone().getPhoneNumber(); } } } requestDTO.customer() .customerId(customer.getId().toString()) .firstName(customer.getFirstName()) .lastName(customer.getLastName()) .email(customer.getEmailAddress()) .phone(phoneNumber); } protected void populateShipTo(Order order, PaymentRequestDTO requestDTO) { List<FulfillmentGroup> fgs = order.getFulfillmentGroups(); if (fgs != null && fgs.size() > 0) { // TODO: Absolutely cannot assume this FulfillmentGroup defaultFg = fgs.get(0); if (defaultFg.getAddress() != null) { Address fgAddress = defaultFg.getAddress(); String stateAbbr = null; String countryAbbr = null; String phone = null; if (fgAddress.getState() != null) { stateAbbr = fgAddress.getState().getAbbreviation(); } if (fgAddress.getCountry() != null) { countryAbbr = fgAddress.getCountry().getAbbreviation(); } if (fgAddress.getPhonePrimary() != null) { phone = fgAddress.getPhonePrimary().getPhoneNumber(); } requestDTO.shipTo() .addressFirstName(fgAddress.getFirstName()) .addressLastName(fgAddress.getLastName()) .addressCompanyName(fgAddress.getCompanyName()) .addressLine1(fgAddress.getAddressLine1()) .addressLine2(fgAddress.getAddressLine2()) .addressCityLocality(fgAddress.getCity()) .addressStateRegion(stateAbbr) .addressPostalCode(fgAddress.getPostalCode()) .addressCountryCode(countryAbbr) .addressPhone(phone) .addressEmail(fgAddress.getEmailAddress()); } } } protected void populateBillTo(Order order, PaymentRequestDTO requestDTO) { List<OrderPayment> payments = order.getPayments(); for (OrderPayment payment : payments) { if (PaymentType.CREDIT_CARD.equals(payment.getType())) { Address billAddress = payment.getBillingAddress(); String stateAbbr = null; String countryAbbr = null; String phone = null; if (billAddress.getState() != null) { stateAbbr = billAddress.getState().getAbbreviation(); } if (billAddress.getCountry() != null) { countryAbbr = billAddress.getCountry().getAbbreviation(); } if (billAddress.getPhonePrimary() != null) { phone = billAddress.getPhonePrimary().getPhoneNumber(); } requestDTO.billTo() .addressFirstName(billAddress.getFirstName()) .addressLastName(billAddress.getLastName()) .addressCompanyName(billAddress.getCompanyName()) .addressLine1(billAddress.getAddressLine1()) .addressLine2(billAddress.getAddressLine2()) .addressCityLocality(billAddress.getCity()) .addressStateRegion(stateAbbr) .addressPostalCode(billAddress.getPostalCode()) .addressCountryCode(countryAbbr) .addressPhone(phone) .addressEmail(billAddress.getEmailAddress()); } } } /** * IMPORTANT: * <p>If you would like to pass Line Item information to a payment gateway * so that it shows up on the hosted site, you will need to override this method and * construct line items to conform to the requirements of that particular gateway:</p> * * <p>For Example: The Paypal Express Checkout NVP API validates that the order subtotal that you pass in, * add up to the amount of the line items that you pass in. So, * In that case you will need to take into account any additional fees, promotions, * credits, gift cards, etc... that are applied to the payment and add them * as additional line items with a negative amount when necessary.</p> * * <p>Each gateway that accepts line item information may require you to construct * this differently. Please consult the module documentation on how it should * be properly constructed.</p> * * <p>In this default implementation, just the subtotal is set, without any line item details.</p> * * @param order * @param requestDTO */ protected void populateDefaultLineItemsAndSubtotal(Order order, PaymentRequestDTO requestDTO) { requestDTO.orderSubtotal(order.getSubTotal().toString()); } }
BroadleafCommerce/BroadleafCommerce#485 - need to add email address to Customer on RequestDTO for anonymous users for Cybesource integration
core/broadleaf-framework/src/main/java/org/broadleafcommerce/core/payment/service/OrderToPaymentRequestDTOServiceImpl.java
BroadleafCommerce/BroadleafCommerce#485 - need to add email address to Customer on RequestDTO for anonymous users for Cybesource integration
<ide><path>ore/broadleaf-framework/src/main/java/org/broadleafcommerce/core/payment/service/OrderToPaymentRequestDTOServiceImpl.java <ide> } <ide> } <ide> <add> String orderEmail = (customer.getEmailAddress() == null)? order.getEmailAddress() : customer.getEmailAddress(); <add> <ide> requestDTO.customer() <ide> .customerId(customer.getId().toString()) <ide> .firstName(customer.getFirstName()) <ide> .lastName(customer.getLastName()) <del> .email(customer.getEmailAddress()) <add> .email(orderEmail) <ide> .phone(phoneNumber); <ide> <ide> }
JavaScript
mit
a70641463ad7ec035bf10560da39bc85d27208bb
0
synzen/Discord.RSS,synzen/Discord.RSS
const mongoose = require('mongoose') const Version = require('./common/Version.js') const schema = new mongoose.Schema({ _id: String, value: mongoose.Schema.Types.Mixed }, { minimize: false }) schema.add(Version) exports.schema = schema /** @type {import('mongoose').Model} */ exports.Model = null
src/models/KeyValue.js
const mongoose = require('mongoose') const Version = require('./common/Version.js') const schema = new mongoose.Schema({ _id: String, value: mongoose.Schema.Types.Mixed }) schema.add(Version) exports.schema = schema /** @type {import('mongoose').Model} */ exports.Model = null
Fix incomplete keyvalues stored
src/models/KeyValue.js
Fix incomplete keyvalues stored
<ide><path>rc/models/KeyValue.js <ide> const schema = new mongoose.Schema({ <ide> _id: String, <ide> value: mongoose.Schema.Types.Mixed <add>}, { <add> minimize: false <ide> }) <ide> <ide> schema.add(Version)
JavaScript
mit
2a7db09a4db669f9344220d01d1a24e956ce4503
0
fk/gatsby,ChristopherBiscardi/gatsby,gatsbyjs/gatsby,fk/gatsby,gatsbyjs/gatsby,mingaldrichgan/gatsby,gatsbyjs/gatsby,0x80/gatsby,fk/gatsby,ChristopherBiscardi/gatsby,mingaldrichgan/gatsby,gatsbyjs/gatsby,mingaldrichgan/gatsby,0x80/gatsby,gatsbyjs/gatsby,ChristopherBiscardi/gatsby,ChristopherBiscardi/gatsby,0x80/gatsby,gatsbyjs/gatsby
require(`v8-compile-cache`) const fs = require(`fs`) const path = require(`path`) const dotenv = require(`dotenv`) const FriendlyErrorsWebpackPlugin = require(`friendly-errors-webpack-plugin`) const { store } = require(`../redux`) const { actions } = require(`../redux/actions`) const debug = require(`debug`)(`gatsby:webpack-config`) const report = require(`gatsby-cli/lib/reporter`) const { withBasePath } = require(`./path`) const apiRunnerNode = require(`./api-runner-node`) const createUtils = require(`./webpack-utils`) const hasLocalEslint = require(`./local-eslint-config-finder`) // Four stages or modes: // 1) develop: for `gatsby develop` command, hot reload and CSS injection into page // 2) develop-html: same as develop without react-hmre in the babel config for html renderer // 3) build-javascript: Build JS and CSS chunks for production // 4) build-html: build all HTML files module.exports = async ( program, directory, suppliedStage, webpackPort = 1500 ) => { const directoryPath = withBasePath(directory) // We combine develop & develop-html stages for purposes of generating the // webpack config. const stage = suppliedStage const { rules, loaders, plugins } = await createUtils({ stage, program }) function processEnv(stage, defaultNodeEnv) { debug(`Building env for "${stage}"`) const env = process.env.NODE_ENV ? process.env.NODE_ENV : `${defaultNodeEnv}` const envFile = path.join(process.cwd(), `./.env.${env}`) let parsed = {} try { parsed = dotenv.parse(fs.readFileSync(envFile, { encoding: `utf8` })) } catch (err) { if (err.code !== `ENOENT`) { report.error(`There was a problem processing the .env file`, err) } } const envObject = Object.keys(parsed).reduce((acc, key) => { acc[key] = JSON.stringify(parsed[key]) return acc }, {}) const gatsbyVarObject = Object.keys(process.env).reduce((acc, key) => { if (key.match(/^GATSBY_/)) { acc[key] = JSON.stringify(process.env[key]) } return acc }, {}) // Don't allow overwriting of NODE_ENV, PUBLIC_DIR as to not break gatsby things envObject.NODE_ENV = JSON.stringify(env) envObject.PUBLIC_DIR = JSON.stringify(`${process.cwd()}/public`) return Object.assign(envObject, gatsbyVarObject) } function getHmrPath() { let hmrBasePath = `${program.ssl ? `https` : `http`}://${ program.host }:${webpackPort}/` const hmrSuffix = `__webpack_hmr&reload=true&overlay=false` if (process.env.GATSBY_WEBPACK_PUBLICPATH) { const pubPath = process.env.GATSBY_WEBPACK_PUBLICPATH if (pubPath.substr(-1) === `/`) { hmrBasePath = pubPath } else { hmrBasePath = `${pubPath}/` } } return hmrBasePath + hmrSuffix } debug(`Loading webpack config for stage "${stage}"`) function getOutput() { switch (stage) { case `develop`: return { path: directory, filename: `[name].js`, // Add /* filename */ comments to generated require()s in the output. pathinfo: true, // Point sourcemap entries to original disk location (format as URL on Windows) publicPath: process.env.GATSBY_WEBPACK_PUBLICPATH || `${program.ssl ? `https` : `http`}://${ program.host }:${webpackPort}/`, devtoolModuleFilenameTemplate: info => path.resolve(info.absoluteResourcePath).replace(/\\/g, `/`), } case `build-html`: case `develop-html`: // A temp file required by static-site-generator-plugin. See plugins() below. // Deleted by build-html.js, since it's not needed for production. return { path: directoryPath(`public`), filename: `render-page.js`, libraryTarget: `umd`, library: `lib`, umdNamedDefine: true, globalObject: `this`, publicPath: program.prefixPaths ? `${store.getState().config.pathPrefix}/` : `/`, } case `build-javascript`: return { filename: `[name]-[chunkhash].js`, chunkFilename: `[name]-[chunkhash].js`, path: directoryPath(`public`), publicPath: program.prefixPaths ? `${store.getState().config.pathPrefix}/` : `/`, } default: throw new Error(`The state requested ${stage} doesn't exist.`) } } function getEntry() { switch (stage) { case `develop`: return { commons: [ require.resolve(`react-hot-loader/patch`), `${require.resolve( `webpack-hot-middleware/client` )}?path=${getHmrPath()}`, directoryPath(`.cache/app`), ], } case `develop-html`: return { main: directoryPath(`.cache/develop-static-entry`), } case `build-html`: return { main: directoryPath(`.cache/static-entry`), } case `build-javascript`: return { app: directoryPath(`.cache/production-app`), } default: throw new Error(`The state requested ${stage} doesn't exist.`) } } function getPlugins() { let configPlugins = [ plugins.moment(), // Add a few global variables. Set NODE_ENV to production (enables // optimizations for React) and what the link prefix is (__PATH_PREFIX__). plugins.define({ "process.env": processEnv(stage, `development`), __PATH_PREFIX__: JSON.stringify( program.prefixPaths ? store.getState().config.pathPrefix : `` ), }), ] switch (stage) { case `develop`: configPlugins = configPlugins.concat([ plugins.hotModuleReplacement(), plugins.noEmitOnErrors(), new FriendlyErrorsWebpackPlugin({ clearConsole: false, compilationSuccessInfo: { messages: [ `You can now view your site in the browser running at ${program.ssl ? `https` : `http`}://${ program.host }:${program.port}`, `Your graphql debugger is running at ${program.ssl ? `https` : `http`}://${program.host}:${ program.port }/___graphql`, ], }, }), ]) break case `build-javascript`: { configPlugins = configPlugins.concat([ plugins.extractText(), // Minify Javascript. plugins.uglify({ uglifyOptions: { compress: { drop_console: false, }, }, }), // Write out stats object mapping named dynamic imports (aka page // components) to all their async chunks. { apply: function(compiler) { compiler.hooks.done.tapAsync( `gatsby-webpack-stats-extractor`, (stats, done) => { let assets = {} for (let chunkGroup of stats.compilation.chunkGroups) { if (chunkGroup.name) { let files = [] for (let chunk of chunkGroup.chunks) { files.push(...chunk.files) } assets[chunkGroup.name] = files.filter( f => f.slice(-4) !== `.map` ) } } const webpackStats = { ...stats.toJson({ all: false, chunkGroups: true }), assetsByChunkName: assets, } fs.writeFile( path.join(`public`, `webpack.stats.json`), JSON.stringify(webpackStats), done ) } ) }, }, ]) break } } return configPlugins } function getDevtool() { switch (stage) { case `develop`: return `eval` // use a normal `source-map` for the html phases since // it gives better line and column numbers case `develop-html`: case `build-html`: case `build-javascript`: return `source-map` default: return false } } function getMode() { switch (stage) { case `build-javascript`: return `production` case `develop`: case `develop-html`: case `build-html`: return `development` // So we don't uglify the html bundle default: return `production` } } function getModule(config) { // Common config for every env. // prettier-ignore let configRules = [ rules.js(), rules.yaml(), rules.fonts(), rules.images(), rules.audioVideo(), ] switch (stage) { case `develop`: { // get schema to pass to eslint config and program for directory const { schema, program } = store.getState() // if no local eslint config, then add gatsby config if (!hasLocalEslint(program.directory)) { configRules = configRules.concat([rules.eslint(schema)]) } configRules = configRules.concat([ { oneOf: [rules.cssModules(), rules.css()], }, ]) break } case `build-html`: case `develop-html`: // We don't deal with CSS at all when building the HTML. // The 'null' loader is used to prevent 'module not found' errors. // On the other hand CSS modules loaders are necessary. // prettier-ignore configRules = configRules.concat([ { oneOf: [ rules.cssModules(), { ...rules.css(), use: [loaders.null()], }, ], }, ]) break case `build-javascript`: // We don't deal with CSS at all when building JavaScript but we still // need to process the CSS so offline-plugin knows about the various // assets referenced in your CSS. // // It's also necessary to process CSS Modules so your JS knows the // classNames to use. configRules = configRules.concat([ { oneOf: [rules.cssModules(), rules.css()], }, // Remove manually unused React Router modules. Try removing these // rules whenever they get around to making a new release with their // tree shaking fixes. { test: /HashHistory/, use: `null-loader` }, { test: /MemoryHistory/, use: `null-loader` }, { test: /StaticRouter/, use: `null-loader` }, { test: /MemoryRouter/, use: `null-loader` }, { test: /HashRouter/, use: `null-loader` }, ]) break } return { rules: configRules } } function getResolve() { const { program } = store.getState() return { // Use the program's extension list (generated via the // 'resolvableExtensions' API hook). extensions: [...program.extensions], // Default to using the site's node_modules directory to look for // modules. But also make it possible to install modules within the src // directory if you need to install a specific version of a module for a // part of your site. modules: [ directoryPath(path.join(`src`, `node_modules`)), `node_modules`, ], alias: { gatsby$: directoryPath(path.join(`.cache`, `gatsby-browser-entry.js`)), }, } } function getResolveLoader() { const root = [path.resolve(directory, `node_modules`)] const userLoaderDirectoryPath = path.resolve(directory, `loaders`) try { if (fs.statSync(userLoaderDirectoryPath).isDirectory()) { root.push(userLoaderDirectoryPath) } } catch (err) { debug(`Error resolving user loaders directory`, err) } return { modules: [...root, path.join(__dirname, `../loaders`), `node_modules`], } } const config = { // Context is the base directory for resolving the entry option. context: directory, entry: getEntry(), output: getOutput(), module: getModule(), plugins: getPlugins(), // Certain "isomorphic" packages have different entry points for browser // and server (see // https://github.com/defunctzombie/package-browser-field-spec); setting // the target tells webpack which file to include, ie. browser vs main. target: stage === `build-html` || stage === `develop-html` ? `node` : `web`, profile: stage === `production`, devtool: getDevtool(), // Turn off performance hints as we (for now) don't want to show the normal // webpack output anywhere. performance: { hints: false, }, mode: getMode(), resolveLoader: getResolveLoader(), resolve: getResolve(), node: { __filename: true, }, } if (stage === `build-javascript`) { config.optimization = { runtimeChunk: { name: `webpack-runtime`, }, splitChunks: { name: false, }, } } store.dispatch(actions.replaceWebpackConfig(config)) const getConfig = () => store.getState().webpack await apiRunnerNode(`onCreateWebpackConfig`, { getConfig, stage, rules, loaders, plugins, }) return getConfig() }
packages/gatsby/src/utils/webpack.config.js
require(`v8-compile-cache`) const fs = require(`fs`) const path = require(`path`) const dotenv = require(`dotenv`) const FriendlyErrorsWebpackPlugin = require(`friendly-errors-webpack-plugin`) const { store } = require(`../redux`) const { actions } = require(`../redux/actions`) const debug = require(`debug`)(`gatsby:webpack-config`) const report = require(`gatsby-cli/lib/reporter`) const { withBasePath } = require(`./path`) const apiRunnerNode = require(`./api-runner-node`) const createUtils = require(`./webpack-utils`) const hasLocalEslint = require(`./local-eslint-config-finder`) // Four stages or modes: // 1) develop: for `gatsby develop` command, hot reload and CSS injection into page // 2) develop-html: same as develop without react-hmre in the babel config for html renderer // 3) build-javascript: Build JS and CSS chunks for production // 4) build-html: build all HTML files module.exports = async ( program, directory, suppliedStage, webpackPort = 1500 ) => { const directoryPath = withBasePath(directory) // We combine develop & develop-html stages for purposes of generating the // webpack config. const stage = suppliedStage const { rules, loaders, plugins } = await createUtils({ stage, program }) function processEnv(stage, defaultNodeEnv) { debug(`Building env for "${stage}"`) const env = process.env.NODE_ENV ? process.env.NODE_ENV : `${defaultNodeEnv}` const envFile = path.join(process.cwd(), `./.env.${env}`) let parsed = {} try { parsed = dotenv.parse(fs.readFileSync(envFile, { encoding: `utf8` })) } catch (err) { if (err.code !== `ENOENT`) { report.error(`There was a problem processing the .env file`, err) } } const envObject = Object.keys(parsed).reduce((acc, key) => { acc[key] = JSON.stringify(parsed[key]) return acc }, {}) const gatsbyVarObject = Object.keys(process.env).reduce((acc, key) => { if (key.match(/^GATSBY_/)) { acc[key] = JSON.stringify(process.env[key]) } return acc }, {}) // Don't allow overwriting of NODE_ENV, PUBLIC_DIR as to not break gatsby things envObject.NODE_ENV = JSON.stringify(env) envObject.PUBLIC_DIR = JSON.stringify(`${process.cwd()}/public`) return Object.assign(envObject, gatsbyVarObject) } function getHmrPath() { let hmrBasePath = `${program.ssl ? `https` : `http`}://${ program.host }:${webpackPort}/` const hmrSuffix = `__webpack_hmr&reload=true&overlay=false` if (process.env.GATSBY_WEBPACK_PUBLICPATH) { const pubPath = process.env.GATSBY_WEBPACK_PUBLICPATH if (pubPath.substr(-1) === `/`) { hmrBasePath = pubPath } else { hmrBasePath = `${pubPath}/` } } return hmrBasePath + hmrSuffix } debug(`Loading webpack config for stage "${stage}"`) function getOutput() { switch (stage) { case `develop`: return { path: directory, filename: `[name].js`, // Add /* filename */ comments to generated require()s in the output. pathinfo: true, // Point sourcemap entries to original disk location (format as URL on Windows) publicPath: process.env.GATSBY_WEBPACK_PUBLICPATH || `${program.ssl ? `https` : `http`}://${ program.host }:${webpackPort}/`, devtoolModuleFilenameTemplate: info => path.resolve(info.absoluteResourcePath).replace(/\\/g, `/`), } case `build-html`: case `develop-html`: // A temp file required by static-site-generator-plugin. See plugins() below. // Deleted by build-html.js, since it's not needed for production. return { path: directoryPath(`public`), filename: `render-page.js`, libraryTarget: `umd`, library: `lib`, umdNamedDefine: true, globalObject: `this`, publicPath: program.prefixPaths ? `${store.getState().config.pathPrefix}/` : `/`, } case `build-javascript`: return { filename: `[name]-[chunkhash].js`, chunkFilename: `[name]-[chunkhash].js`, path: directoryPath(`public`), publicPath: program.prefixPaths ? `${store.getState().config.pathPrefix}/` : `/`, } default: throw new Error(`The state requested ${stage} doesn't exist.`) } } function getEntry() { switch (stage) { case `develop`: return { commons: [ require.resolve(`react-hot-loader/patch`), `${require.resolve( `webpack-hot-middleware/client` )}?path=${getHmrPath()}`, directoryPath(`.cache/app`), ], } case `develop-html`: return { main: directoryPath(`.cache/develop-static-entry`), } case `build-html`: return { main: directoryPath(`.cache/static-entry`), } case `build-javascript`: return { app: directoryPath(`.cache/production-app`), } default: throw new Error(`The state requested ${stage} doesn't exist.`) } } function getPlugins() { let configPlugins = [ plugins.moment(), // Add a few global variables. Set NODE_ENV to production (enables // optimizations for React) and what the link prefix is (__PATH_PREFIX__). plugins.define({ "process.env": processEnv(stage, `development`), __PATH_PREFIX__: JSON.stringify( program.prefixPaths ? store.getState().config.pathPrefix : `` ), }), ] switch (stage) { case `develop`: configPlugins = configPlugins.concat([ plugins.hotModuleReplacement(), plugins.noEmitOnErrors(), new FriendlyErrorsWebpackPlugin({ clearConsole: false, compilationSuccessInfo: { messages: [ `You can now view your site in the browser running at http://${ program.host }:${program.port}`, `Your graphql debugger is running at http://${program.host}:${ program.port }/___graphql`, ], }, }), ]) break case `build-javascript`: { configPlugins = configPlugins.concat([ plugins.extractText(), // Minify Javascript. plugins.uglify({ uglifyOptions: { compress: { drop_console: false, }, }, }), // Write out stats object mapping named dynamic imports (aka page // components) to all their async chunks. { apply: function(compiler) { compiler.hooks.done.tapAsync( `gatsby-webpack-stats-extractor`, (stats, done) => { let assets = {} for (let chunkGroup of stats.compilation.chunkGroups) { if (chunkGroup.name) { let files = [] for (let chunk of chunkGroup.chunks) { files.push(...chunk.files) } assets[chunkGroup.name] = files.filter( f => f.slice(-4) !== `.map` ) } } const webpackStats = { ...stats.toJson({ all: false, chunkGroups: true }), assetsByChunkName: assets, } fs.writeFile( path.join(`public`, `webpack.stats.json`), JSON.stringify(webpackStats), done ) } ) }, }, ]) break } } return configPlugins } function getDevtool() { switch (stage) { case `develop`: return `eval` // use a normal `source-map` for the html phases since // it gives better line and column numbers case `develop-html`: case `build-html`: case `build-javascript`: return `source-map` default: return false } } function getMode() { switch (stage) { case `build-javascript`: return `production` case `develop`: case `develop-html`: case `build-html`: return `development` // So we don't uglify the html bundle default: return `production` } } function getModule(config) { // Common config for every env. // prettier-ignore let configRules = [ rules.js(), rules.yaml(), rules.fonts(), rules.images(), rules.audioVideo(), ] switch (stage) { case `develop`: { // get schema to pass to eslint config and program for directory const { schema, program } = store.getState() // if no local eslint config, then add gatsby config if (!hasLocalEslint(program.directory)) { configRules = configRules.concat([rules.eslint(schema)]) } configRules = configRules.concat([ { oneOf: [rules.cssModules(), rules.css()], }, ]) break } case `build-html`: case `develop-html`: // We don't deal with CSS at all when building the HTML. // The 'null' loader is used to prevent 'module not found' errors. // On the other hand CSS modules loaders are necessary. // prettier-ignore configRules = configRules.concat([ { oneOf: [ rules.cssModules(), { ...rules.css(), use: [loaders.null()], }, ], }, ]) break case `build-javascript`: // We don't deal with CSS at all when building JavaScript but we still // need to process the CSS so offline-plugin knows about the various // assets referenced in your CSS. // // It's also necessary to process CSS Modules so your JS knows the // classNames to use. configRules = configRules.concat([ { oneOf: [rules.cssModules(), rules.css()], }, // Remove manually unused React Router modules. Try removing these // rules whenever they get around to making a new release with their // tree shaking fixes. { test: /HashHistory/, use: `null-loader` }, { test: /MemoryHistory/, use: `null-loader` }, { test: /StaticRouter/, use: `null-loader` }, { test: /MemoryRouter/, use: `null-loader` }, { test: /HashRouter/, use: `null-loader` }, ]) break } return { rules: configRules } } function getResolve() { const { program } = store.getState() return { // Use the program's extension list (generated via the // 'resolvableExtensions' API hook). extensions: [...program.extensions], // Default to using the site's node_modules directory to look for // modules. But also make it possible to install modules within the src // directory if you need to install a specific version of a module for a // part of your site. modules: [ directoryPath(path.join(`src`, `node_modules`)), `node_modules`, ], alias: { gatsby$: directoryPath(path.join(`.cache`, `gatsby-browser-entry.js`)), }, } } function getResolveLoader() { const root = [path.resolve(directory, `node_modules`)] const userLoaderDirectoryPath = path.resolve(directory, `loaders`) try { if (fs.statSync(userLoaderDirectoryPath).isDirectory()) { root.push(userLoaderDirectoryPath) } } catch (err) { debug(`Error resolving user loaders directory`, err) } return { modules: [...root, path.join(__dirname, `../loaders`), `node_modules`], } } const config = { // Context is the base directory for resolving the entry option. context: directory, entry: getEntry(), output: getOutput(), module: getModule(), plugins: getPlugins(), // Certain "isomorphic" packages have different entry points for browser // and server (see // https://github.com/defunctzombie/package-browser-field-spec); setting // the target tells webpack which file to include, ie. browser vs main. target: stage === `build-html` || stage === `develop-html` ? `node` : `web`, profile: stage === `production`, devtool: getDevtool(), // Turn off performance hints as we (for now) don't want to show the normal // webpack output anywhere. performance: { hints: false, }, mode: getMode(), resolveLoader: getResolveLoader(), resolve: getResolve(), node: { __filename: true, }, } if (stage === `build-javascript`) { config.optimization = { runtimeChunk: { name: `webpack-runtime`, }, splitChunks: { name: false, }, } } store.dispatch(actions.replaceWebpackConfig(config)) const getConfig = () => store.getState().webpack await apiRunnerNode(`onCreateWebpackConfig`, { getConfig, stage, rules, loaders, plugins, }) return getConfig() }
Update SSL for FriendlyErrorsWebpackPlugin (#6066)
packages/gatsby/src/utils/webpack.config.js
Update SSL for FriendlyErrorsWebpackPlugin (#6066)
<ide><path>ackages/gatsby/src/utils/webpack.config.js <ide> clearConsole: false, <ide> compilationSuccessInfo: { <ide> messages: [ <del> `You can now view your site in the browser running at http://${ <add> `You can now view your site in the browser running at ${program.ssl ? `https` : `http`}://${ <ide> program.host <ide> }:${program.port}`, <del> `Your graphql debugger is running at http://${program.host}:${ <add> `Your graphql debugger is running at ${program.ssl ? `https` : `http`}://${program.host}:${ <ide> program.port <ide> }/___graphql`, <ide> ],
Java
apache-2.0
4fa0aa261b6c54826c2d5e9837240431e2af0b87
0
slipstream/SlipStreamServer,slipstream/SlipStreamServer,slipstream/SlipStreamServer,slipstream/SlipStreamServer
package com.sixsq.slipstream.run; /* * +=================================================================+ * SlipStream Server (WAR) * ===== * Copyright (C) 2013 SixSq Sarl (sixsq.com) * ===== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -=================================================================- */ import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import org.apache.commons.lang.StringUtils; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.Delete; import org.restlet.resource.Get; import org.restlet.resource.Post; import org.restlet.resource.ResourceException; import com.sixsq.slipstream.configuration.Configuration; import com.sixsq.slipstream.exceptions.AbortException; import com.sixsq.slipstream.exceptions.NotFoundException; import com.sixsq.slipstream.exceptions.SlipStreamClientException; import com.sixsq.slipstream.exceptions.SlipStreamException; import com.sixsq.slipstream.exceptions.ValidationException; import com.sixsq.slipstream.factory.DeploymentFactory; import com.sixsq.slipstream.persistence.DeploymentModule; import com.sixsq.slipstream.persistence.Node; import com.sixsq.slipstream.persistence.NodeParameter; import com.sixsq.slipstream.persistence.PersistenceUtil; import com.sixsq.slipstream.persistence.Run; import com.sixsq.slipstream.persistence.RunParameter; import com.sixsq.slipstream.persistence.RuntimeParameter; import com.sixsq.slipstream.persistence.User; import com.sixsq.slipstream.persistence.Vm; import com.sixsq.slipstream.statemachine.StateMachine; import com.sixsq.slipstream.statemachine.States; public class RunNodeResource extends RunBaseResource { private final static String NUMBER_INSTANCES_ADD_FORM_PARAM = "n"; private final static String NUMBER_INSTANCES_ADD_DEFAULT = "1"; private final static String INSTANCE_IDS_REMOVE_FORM_PARAM = "ids"; private final static List<Method> IGNORE_ABORT_HTTP_METHODS = new ArrayList<Method>( Arrays.asList(Method.GET)); private String nodename; private String nodeMultiplicityRunParam; private String nodeMultiplicityRuntimeParam; private String nodeIndicesRuntimeParam; @Override public void initializeSubResource() throws ResourceException { parseRequest(); raiseConflictIfAbortIsSet(); initNodeParameters(); } private void parseRequest() { extractAndSetIgnoreAbort(); nodename = getAttribute("node"); } private void initNodeParameters() { nodeMultiplicityRunParam = DeploymentFactory.constructParamName(nodename, RuntimeParameter.MULTIPLICITY_PARAMETER_NAME); nodeMultiplicityRuntimeParam = DeploymentFactory.constructParamName(nodename, RuntimeParameter.MULTIPLICITY_PARAMETER_NAME); nodeIndicesRuntimeParam = DeploymentFactory.constructParamName(nodename, RuntimeParameter.IDS_PARAMETER_NAME); } @Get public Representation represent(Representation entity) { Run run = Run.loadFromUuid(getUuid()); List<String> instanceNames = run.getNodeInstanceNames(nodename); return new StringRepresentation(StringUtils.join(instanceNames, ","), MediaType.TEXT_PLAIN); } @Post public Representation addNodeInstances(Representation entity) throws ResourceException { Representation result = null; try { result = addNodeInstancesInTransaction(entity); } catch (ResourceException e) { throw e; } catch (SlipStreamClientException e) { throwClientConflicError(e.getMessage(), e); } catch (SlipStreamException e) { throwServerError(e.getMessage(), e); } catch (Exception e) { throwServerError(e.getMessage(), e); } return result; } private Representation addNodeInstancesInTransaction(Representation entity) throws Exception { EntityManager em = PersistenceUtil.createEntityManager(); EntityTransaction transaction = em.getTransaction(); Run run = Run.loadFromUuid(getUuid(), em); List<String> instanceNames = new ArrayList<String>(); try { validateRun(run); transaction.begin(); int noOfInst = getNumberOfInstancesToAdd(entity); Node node = getNode(run, nodename); for (int i = 0; i < noOfInst; i++) { instanceNames.add(createNodeInstanceOnRun(run, node)); } incrementNodeMultiplicityOnRun(noOfInst, run); StateMachine.createStateMachine(run).tryAdvanceToProvisionning(); if (Configuration.isQuotaEnabled()) { User user = User.loadByName(run.getUser()); Quota.validate(user, run.getCloudServiceUsage(), Vm.usage(user.getName())); } transaction.commit(); } catch (Exception ex) { if (transaction.isActive()) { transaction.rollback(); } throw ex; } finally { em.close(); } getResponse().setStatus(Status.SUCCESS_CREATED); return new StringRepresentation(StringUtils.join(instanceNames, ","), MediaType.TEXT_PLAIN); } @Delete public void deleteNodeInstances(Representation entity) throws Exception { try { deleteNodeInstancesInTransaction(entity); } catch (ResourceException e) { throw e; } catch (SlipStreamClientException e) { throwClientConflicError(e.getMessage(), e); } catch (SlipStreamException e) { throwServerError(e.getMessage(), e); } catch (Exception e) { throwServerError(e.getMessage(), e); } } private void deleteNodeInstancesInTransaction(Representation entity) throws Exception { EntityManager em = PersistenceUtil.createEntityManager(); EntityTransaction transaction = em.getTransaction(); Run run = Run.loadFromUuid(getUuid(), em); try { validateRun(run); transaction.begin(); Form form = new Form(entity); String ids = form.getFirstValue(INSTANCE_IDS_REMOVE_FORM_PARAM, ""); if (ids.isEmpty()) { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Provide list of node instance IDs to be removed from the Run."); } else { String cloudServiceName = ""; try{ cloudServiceName = run.getCloudServiceNameForNode(nodename); } catch (NullPointerException ex) { throwClientBadRequest("Invalid nodename: " + nodename); } List<String> instanceIds = Arrays.asList(ids.split("\\s*,\\s*")); for (String _id : instanceIds) { String instanceName = ""; try { instanceName = getNodeInstanceName(Integer.parseInt(_id)); } catch (NumberFormatException ex) { throwClientBadRequest("Invalid instance name: " + _id); } setRemovingNodeInstance(run, instanceName); run.removeNodeInstanceName(instanceName, cloudServiceName); } // update instance ids removeNodeInstanceIndices(run, instanceIds); decrementNodeMultiplicityOnRun(instanceIds.size(), run); } StateMachine.createStateMachine(run).tryAdvanceToProvisionning(); transaction.commit(); } catch (Exception ex) { if (transaction.isActive()) { transaction.rollback(); } throw ex; } finally { em.close(); } getResponse().setStatus(Status.SUCCESS_NO_CONTENT); } private void raiseConflictIfAbortIsSet() { // Let certain methods to succeed if 'ignore abort' is set. if (!isIgnoreAbort() && isAbortSet()) { throw (new ResourceException(Status.CLIENT_ERROR_CONFLICT, "Abort flag raised!")); } } private boolean isIgnoreAbort() { Method httpMethod = getMethod(); if (getIgnoreAbort() && IGNORE_ABORT_HTTP_METHODS.contains(httpMethod)) { return true; } else { return false; } } private int getNumberOfInstancesToAdd(Representation entity) { Form form = new Form(entity); try { return Integer.parseInt(form.getFirstValue(NUMBER_INSTANCES_ADD_FORM_PARAM, NUMBER_INSTANCES_ADD_DEFAULT)); } catch (NumberFormatException e) { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Number of instances to add should be an integer."); } } private String createNodeInstanceOnRun(Run run, Node node) throws NotFoundException, AbortException, ValidationException { int newId = addNodeInstanceIndex(run, node); createNodeInstanceRuntimeParameters(run, node, newId); String instanceName = getNodeInstanceName(newId); return instanceName; } private void createNodeInstanceRuntimeParameters(Run run, Node node, int newId) throws ValidationException, NotFoundException { DeploymentFactory.initNodeInstanceRuntimeParameters(run, node, newId); //TODO: LS: check this part // add mapping parameters for (NodeParameter param : node.getParameterMappings().values()) { if (!param.isStringValue()) { DeploymentFactory.addParameterMapping(run, param, newId); } } } private Node getNode(Run run, String nodename) { DeploymentModule deployment = (DeploymentModule) run.getModule(); Node node = deployment.getNode(nodename); if (node != null) { return node; } else { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Node " + nodename + " doesn't exist."); } } private void removeNodeInstanceIndices(Run run, List<String> ids) throws NotFoundException, AbortException, ValidationException { List<String> nodeIds = new ArrayList<String>( Arrays.asList(getNodeInstanceIndices(run).split("\\s*,\\s*"))); nodeIds.removeAll(ids); String newNodeIds = StringUtils.join(nodeIds, ","); setNodeInstanceIndices(run, newNodeIds); } private void validateRun(Run run) { if (!run.isMutable()) { throw new ResourceException(Status.CLIENT_ERROR_CONFLICT, "Can't add/remove instances. Run is not mutable."); } States currentState = run.getState(); if (currentState != States.Ready) { throw new ResourceException(Status.CLIENT_ERROR_CONFLICT, "Can't add/remove instances. Incompatible state " + currentState.toString() + ". This can only be performed on state " + States.Ready.toString()); } } private int addNodeInstanceIndex(Run run, Node node) throws NotFoundException, AbortException, ValidationException { String ids = getNodeInstanceIndices(run); String key = DeploymentFactory.constructNodeParamName(node, RunParameter.NODE_INCREMENT_KEY); RunParameter nodeInscrement = run.getParameter(key); int newId = Integer.parseInt(nodeInscrement.getValue("0")); nodeInscrement.setValue(String.valueOf(newId + 1)); if (!ids.isEmpty()) { ids += ","; } ids += newId; setNodeInstanceIndices(run, ids); return newId; } private void setRemovingNodeInstance(Run run, String instanceName) throws NotFoundException, ValidationException { setScaleActionOnNodeInstance(run, instanceName, "removing"); } private void setScaleActionOnNodeInstance(Run run, String instanceName, String action) throws NotFoundException, ValidationException { run.updateRuntimeParameter(RuntimeParameter.constructParamName( instanceName, RuntimeParameter.SCALE_STATE_KEY), action); } private String getNodeInstanceIndices(Run run) throws NotFoundException, AbortException { return run.getRuntimeParameterValue(nodeIndicesRuntimeParam); } private void setNodeInstanceIndices(Run run, String indices) throws ValidationException, NotFoundException { run.updateRuntimeParameter(nodeIndicesRuntimeParam, indices); } private String getNodeInstanceName(int index) { return RuntimeParameter.constructNodeInstanceName(nodename, index); } private void decrementNodeMultiplicityOnRun(int decrement, Run run) throws ValidationException, NotFoundException { incrementNodeMultiplicityOnRun(-1 * decrement, run); } private void incrementNodeMultiplicityOnRun(int inc, Run run) throws ValidationException, NotFoundException { // node_name--multiplicity - Run Parameter int newMultiplicity = getNodeGroupMulptilicity(run) + inc; if (newMultiplicity < 0) { newMultiplicity = 0; } // node_name:multiplicity - Runtime Parameter run.updateRuntimeParameter(nodeMultiplicityRuntimeParam, Integer.toString(newMultiplicity)); } private int getNodeGroupMulptilicity(Run run) throws NumberFormatException, NotFoundException { return Integer.parseInt(run.getRuntimeParameterValueIgnoreAbort(nodeMultiplicityRunParam)); } }
jar-service/src/main/java/com/sixsq/slipstream/run/RunNodeResource.java
package com.sixsq.slipstream.run; /* * +=================================================================+ * SlipStream Server (WAR) * ===== * Copyright (C) 2013 SixSq Sarl (sixsq.com) * ===== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -=================================================================- */ import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import org.apache.commons.lang.StringUtils; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.Delete; import org.restlet.resource.Get; import org.restlet.resource.Post; import org.restlet.resource.ResourceException; import com.sixsq.slipstream.configuration.Configuration; import com.sixsq.slipstream.exceptions.AbortException; import com.sixsq.slipstream.exceptions.NotFoundException; import com.sixsq.slipstream.exceptions.SlipStreamClientException; import com.sixsq.slipstream.exceptions.SlipStreamException; import com.sixsq.slipstream.exceptions.ValidationException; import com.sixsq.slipstream.factory.DeploymentFactory; import com.sixsq.slipstream.persistence.DeploymentModule; import com.sixsq.slipstream.persistence.Node; import com.sixsq.slipstream.persistence.NodeParameter; import com.sixsq.slipstream.persistence.PersistenceUtil; import com.sixsq.slipstream.persistence.Run; import com.sixsq.slipstream.persistence.RunParameter; import com.sixsq.slipstream.persistence.RuntimeParameter; import com.sixsq.slipstream.persistence.User; import com.sixsq.slipstream.persistence.Vm; import com.sixsq.slipstream.statemachine.StateMachine; import com.sixsq.slipstream.statemachine.States; public class RunNodeResource extends RunBaseResource { private final static String NUMBER_INSTANCES_ADD_FORM_PARAM = "n"; private final static String NUMBER_INSTANCES_ADD_DEFAULT = "1"; private final static String INSTANCE_IDS_REMOVE_FORM_PARAM = "ids"; private final static List<Method> IGNORE_ABORT_HTTP_METHODS = new ArrayList<Method>( Arrays.asList(Method.GET)); private String nodename; private String nodeMultiplicityRunParam; private String nodeMultiplicityRuntimeParam; private String nodeIndicesRuntimeParam; @Override public void initializeSubResource() throws ResourceException { parseRequest(); raiseConflictIfAbortIsSet(); initNodeParameters(); } private void parseRequest() { extractAndSetIgnoreAbort(); nodename = getAttribute("node"); } private void initNodeParameters() { nodeMultiplicityRunParam = DeploymentFactory.constructParamName(nodename, RuntimeParameter.MULTIPLICITY_PARAMETER_NAME); nodeMultiplicityRuntimeParam = DeploymentFactory.constructParamName(nodename, RuntimeParameter.MULTIPLICITY_PARAMETER_NAME); nodeIndicesRuntimeParam = DeploymentFactory.constructParamName(nodename, RuntimeParameter.IDS_PARAMETER_NAME); } @Get public Representation represent(Representation entity) { Run run = Run.loadFromUuid(getUuid()); List<String> instanceNames = run.getNodeInstanceNames(nodename); return new StringRepresentation(StringUtils.join(instanceNames, ","), MediaType.TEXT_PLAIN); } @Post public Representation addNodeInstances(Representation entity) throws ResourceException { Representation result = null; try { result = addNodeInstancesInTransaction(entity); } catch (ResourceException e) { throw e; } catch (SlipStreamClientException e) { throwClientConflicError(e.getMessage(), e); } catch (SlipStreamException e) { throwServerError(e.getMessage(), e); } catch (Exception e) { throwServerError(e.getMessage(), e); } return result; } private Representation addNodeInstancesInTransaction(Representation entity) throws Exception { EntityManager em = PersistenceUtil.createEntityManager(); EntityTransaction transaction = em.getTransaction(); Run run = Run.loadFromUuid(getUuid(), em); List<String> instanceNames = new ArrayList<String>(); try { validateRun(run); transaction.begin(); int noOfInst = getNumberOfInstancesToAdd(entity); Node node = getNode(run, nodename); for (int i = 0; i < noOfInst; i++) { instanceNames.add(createNodeInstanceOnRun(run, node)); } incrementNodeMultiplicityOnRun(noOfInst, run); StateMachine.createStateMachine(run).tryAdvanceToProvisionning(); if (Configuration.isQuotaEnabled()) { User user = User.loadByName(run.getUser()); Quota.validate(user, run.getCloudServiceUsage(), Vm.usage(user.getName())); } transaction.commit(); } catch (Exception ex) { if (transaction.isActive()) { transaction.rollback(); } throw ex; } finally { em.close(); } getResponse().setStatus(Status.SUCCESS_CREATED); return new StringRepresentation(StringUtils.join(instanceNames, ","), MediaType.TEXT_PLAIN); } @Delete public void deleteNodeInstances(Representation entity) throws Exception { try { deleteNodeInstancesInTransaction(entity); } catch (ResourceException e) { throw e; } catch (SlipStreamClientException e) { throwClientConflicError(e.getMessage(), e); } catch (SlipStreamException e) { throwServerError(e.getMessage(), e); } catch (Exception e) { throwServerError(e.getMessage(), e); } } private void deleteNodeInstancesInTransaction(Representation entity) throws Exception { EntityManager em = PersistenceUtil.createEntityManager(); EntityTransaction transaction = em.getTransaction(); Run run = Run.loadFromUuid(getUuid(), em); try { validateRun(run); transaction.begin(); Form form = new Form(entity); String ids = form.getFirstValue(INSTANCE_IDS_REMOVE_FORM_PARAM, ""); if (ids.isEmpty()) { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Provide list of node instance IDs to be removed from the Run."); } else { String cloudServiceName = run.getCloudServiceNameForNode(nodename); List<String> instanceIds = Arrays.asList(ids.split("\\s*,\\s*")); for (String _id : instanceIds) { String instanceName = getNodeInstanceName(Integer.parseInt(_id)); setRemovingNodeInstance(run, instanceName); run.removeNodeInstanceName(instanceName, cloudServiceName); } // update instance ids removeNodeInstanceIndices(run, instanceIds); decrementNodeMultiplicityOnRun(instanceIds.size(), run); } StateMachine.createStateMachine(run).tryAdvanceToProvisionning(); transaction.commit(); } catch (Exception ex) { if (transaction.isActive()) { transaction.rollback(); } throw ex; } finally { em.close(); } getResponse().setStatus(Status.SUCCESS_NO_CONTENT); } private void raiseConflictIfAbortIsSet() { // Let certain methods to succeed if 'ignore abort' is set. if (!isIgnoreAbort() && isAbortSet()) { throw (new ResourceException(Status.CLIENT_ERROR_CONFLICT, "Abort flag raised!")); } } private boolean isIgnoreAbort() { Method httpMethod = getMethod(); if (getIgnoreAbort() && IGNORE_ABORT_HTTP_METHODS.contains(httpMethod)) { return true; } else { return false; } } private int getNumberOfInstancesToAdd(Representation entity) { Form form = new Form(entity); try { return Integer.parseInt(form.getFirstValue(NUMBER_INSTANCES_ADD_FORM_PARAM, NUMBER_INSTANCES_ADD_DEFAULT)); } catch (NumberFormatException e) { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Number of instances to add should be an integer."); } } private String createNodeInstanceOnRun(Run run, Node node) throws NotFoundException, AbortException, ValidationException { int newId = addNodeInstanceIndex(run, node); createNodeInstanceRuntimeParameters(run, node, newId); String instanceName = getNodeInstanceName(newId); return instanceName; } private void createNodeInstanceRuntimeParameters(Run run, Node node, int newId) throws ValidationException, NotFoundException { DeploymentFactory.initNodeInstanceRuntimeParameters(run, node, newId); //TODO: LS: check this part // add mapping parameters for (NodeParameter param : node.getParameterMappings().values()) { if (!param.isStringValue()) { DeploymentFactory.addParameterMapping(run, param, newId); } } } private Node getNode(Run run, String nodename) { DeploymentModule deployment = (DeploymentModule) run.getModule(); Node node = deployment.getNode(nodename); if (node != null) { return node; } else { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Node " + nodename + " doesn't exist."); } } private void removeNodeInstanceIndices(Run run, List<String> ids) throws NotFoundException, AbortException, ValidationException { List<String> nodeIds = new ArrayList<String>( Arrays.asList(getNodeInstanceIndices(run).split("\\s*,\\s*"))); nodeIds.removeAll(ids); String newNodeIds = StringUtils.join(nodeIds, ","); setNodeInstanceIndices(run, newNodeIds); } private void validateRun(Run run) { if (!run.isMutable()) { throw new ResourceException(Status.CLIENT_ERROR_CONFLICT, "Can't add/remove instances. Run is not mutable."); } States currentState = run.getState(); if (currentState != States.Ready) { throw new ResourceException(Status.CLIENT_ERROR_CONFLICT, "Can't add/remove instances. Incompatible state " + currentState.toString() + ". Allowed state " + States.Ready.toString()); } } private int addNodeInstanceIndex(Run run, Node node) throws NotFoundException, AbortException, ValidationException { String ids = getNodeInstanceIndices(run); String key = DeploymentFactory.constructNodeParamName(node, RunParameter.NODE_INCREMENT_KEY); RunParameter nodeInscrement = run.getParameter(key); int newId = Integer.parseInt(nodeInscrement.getValue("0")); nodeInscrement.setValue(String.valueOf(newId + 1)); if (!ids.isEmpty()) { ids += ","; } ids += newId; setNodeInstanceIndices(run, ids); return newId; } private void setRemovingNodeInstance(Run run, String instanceName) throws NotFoundException, ValidationException { setScaleActionOnNodeInstance(run, instanceName, "removing"); } private void setScaleActionOnNodeInstance(Run run, String instanceName, String action) throws NotFoundException, ValidationException { run.updateRuntimeParameter(RuntimeParameter.constructParamName( instanceName, RuntimeParameter.SCALE_STATE_KEY), action); } private String getNodeInstanceIndices(Run run) throws NotFoundException, AbortException { return run.getRuntimeParameterValue(nodeIndicesRuntimeParam); } private void setNodeInstanceIndices(Run run, String indices) throws ValidationException, NotFoundException { run.updateRuntimeParameter(nodeIndicesRuntimeParam, indices); } private String getNodeInstanceName(int index) { return RuntimeParameter.constructNodeInstanceName(nodename, index); } private void decrementNodeMultiplicityOnRun(int decrement, Run run) throws ValidationException, NotFoundException { incrementNodeMultiplicityOnRun(-1 * decrement, run); } private void incrementNodeMultiplicityOnRun(int inc, Run run) throws ValidationException, NotFoundException { // node_name--multiplicity - Run Parameter int newMultiplicity = getNodeGroupMulptilicity(run) + inc; if (newMultiplicity < 0) { newMultiplicity = 0; } // node_name:multiplicity - Runtime Parameter run.updateRuntimeParameter(nodeMultiplicityRuntimeParam, Integer.toString(newMultiplicity)); } private int getNodeGroupMulptilicity(Run run) throws NumberFormatException, NotFoundException { return Integer.parseInt(run.getRuntimeParameterValueIgnoreAbort(nodeMultiplicityRunParam)); } }
Improved error handling
jar-service/src/main/java/com/sixsq/slipstream/run/RunNodeResource.java
Improved error handling
<ide><path>ar-service/src/main/java/com/sixsq/slipstream/run/RunNodeResource.java <ide> private void deleteNodeInstancesInTransaction(Representation entity) throws Exception { <ide> EntityManager em = PersistenceUtil.createEntityManager(); <ide> EntityTransaction transaction = em.getTransaction(); <add> <ide> Run run = Run.loadFromUuid(getUuid(), em); <ide> try { <ide> validateRun(run); <ide> throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, <ide> "Provide list of node instance IDs to be removed from the Run."); <ide> } else { <del> String cloudServiceName = run.getCloudServiceNameForNode(nodename); <add> String cloudServiceName = ""; <add> try{ <add> cloudServiceName = run.getCloudServiceNameForNode(nodename); <add> } catch (NullPointerException ex) { <add> throwClientBadRequest("Invalid nodename: " + nodename); <add> } <ide> List<String> instanceIds = Arrays.asList(ids.split("\\s*,\\s*")); <ide> for (String _id : instanceIds) { <del> String instanceName = getNodeInstanceName(Integer.parseInt(_id)); <add> String instanceName = ""; <add> try { <add> instanceName = getNodeInstanceName(Integer.parseInt(_id)); <add> } catch (NumberFormatException ex) { <add> throwClientBadRequest("Invalid instance name: " + _id); <add> } <ide> setRemovingNodeInstance(run, instanceName); <ide> run.removeNodeInstanceName(instanceName, cloudServiceName); <ide> } <ide> if (currentState != States.Ready) { <ide> throw new ResourceException(Status.CLIENT_ERROR_CONFLICT, <ide> "Can't add/remove instances. Incompatible state " <del> + currentState.toString() + ". Allowed state " <add> + currentState.toString() + ". This can only be performed on state " <ide> + States.Ready.toString()); <ide> } <ide> }
Java
apache-2.0
b8a53172fd70875c9e52bd3e47bcaadb882dac22
0
kermitt2/grobid,kermitt2/grobid,kermitt2/grobid,kermitt2/grobid,kermitt2/grobid,kermitt2/grobid
package org.grobid.core.visualization; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import com.google.common.collect.Multimap; import net.sf.saxon.trans.XPathException; import org.apache.commons.lang3.StringUtils; import org.apache.pdfbox.cos.COSArray; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDPageDestination; import org.apache.pdfbox.pdmodel.PDPageContentStream; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.apache.pdfbox.pdmodel.graphics.color.PDColor; import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB; import org.apache.pdfbox.pdmodel.interactive.action.PDActionGoTo; import org.apache.pdfbox.pdmodel.interactive.action.PDActionURI; import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationLink; import org.apache.pdfbox.pdmodel.interactive.annotation.PDBorderStyleDictionary; import org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDPageFitWidthDestination; import org.grobid.core.data.BibDataSet; import org.grobid.core.data.BibDataSetContext; import org.grobid.core.data.BiblioItem; import org.grobid.core.data.Person; import org.grobid.core.document.Document; import org.grobid.core.layout.BoundingBox; import org.grobid.core.layout.Page; import org.grobid.core.utilities.BibDataSetContextExtractor; import org.grobid.core.utilities.LayoutTokensUtil; import org.grobid.core.utilities.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.StringWriter; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Utilities for visualizing citation markers and biblographical references, wither directly * in the PDF using the PDF annotation layer or as annotations in JSON for supporting * web based rendering (e.g. with PDF.js) and interactive HTML layer. * See the web console/demo for actual examples of usage. */ public class CitationsVisualizer { private static final Logger LOGGER = LoggerFactory.getLogger(CitationsVisualizer.class); private static final JsonFactory jFactory = new JsonFactory(); /** * Augment a PDF with bibliographical annotation, for bib. ref. and bib markers. * The PDF annotation layer is used with "GoTo" and "URI" action links. * The annotations of the bibliographical references can be associated to an URL in order * to have clickable references direclty in the PDF. * The Apache PDFBox library is used. * * @param document PDDocument object resulting from the PDF parsing with PDFBox * @param teiDoc the Document object resulting from the full document structuring * @param resolvedBibRefUrl the list of URL to be added to the bibliographical reference * annotations, if null the bib. ref. annotations are not associated to external URL. */ public static PDDocument annotatePdfWithCitations(PDDocument document, Document teiDoc, List<String> resolvedBibRefUrl) throws IOException, XPathException { String tei = teiDoc.getTei(); //System.out.println(tei); int totalBib = 0; int totalMarkers1 = 0; int totalMarkers2 = 0; Multimap<String, BibDataSetContext> contexts = BibDataSetContextExtractor.getCitationReferences(tei); Map<String, Pair<Integer, Integer>> dictionary = new HashMap<>(); int indexBib = 0; for (BibDataSet cit : teiDoc.getBibDataSets()) { String teiId = cit.getResBib().getTeiId(); totalBib++; String theUrl = null; if ( (resolvedBibRefUrl != null) && (resolvedBibRefUrl.size() > indexBib) && (resolvedBibRefUrl.get(indexBib) != null) ) theUrl = resolvedBibRefUrl.get(indexBib); else { // by default we put the existing url, doi or arXiv link BiblioItem biblio = cit.getResBib(); if (!StringUtils.isEmpty(biblio.getDOI())) { theUrl = "https://dx.doi.org/" + biblio.getDOI(); } else if (!StringUtils.isEmpty(biblio.getArXivId())) { theUrl = "https://arxiv.org/" + biblio.getArXivId(); } else if (!StringUtils.isEmpty(biblio.getWeb())) { theUrl = biblio.getWeb(); } } if (cit.getResBib().getCoordinates() != null) { for (BoundingBox b : cit.getResBib().getCoordinates()) { annotatePage(document, b.toString(), teiId, theUrl, 1.5f, false, dictionary); } } //annotating reference markers for (BibDataSetContext c : contexts.get(teiId)) { //System.out.println(c.getContext()); String mrect = c.getDocumentCoords(); if ((mrect != null) && (mrect.trim().length()>0)) { for (String coords : mrect.split(";")) { if (coords.trim().length() == 0) continue; annotatePage(document, coords, teiId, null, 1.0f, true, dictionary); totalMarkers1++; } } } indexBib++; } for (BibDataSetContext c : contexts.get("")) { String mrect = c.getDocumentCoords(); if ((mrect != null) && (mrect.trim().length()>0)) { for (String coords : mrect.split(";")) { if (coords.trim().length() == 0) continue; annotatePage(document, coords, null, null, 1.0f, true, dictionary); totalMarkers2++; } } } if (teiDoc.getResHeader() != null && teiDoc.getResHeader().getFullAuthors() != null) { for (Person p : teiDoc.getResHeader().getFullAuthors()) { if (p.getLayoutTokens() != null) { String coordsString = LayoutTokensUtil.getCoordsString(p.getLayoutTokens()); for (String coords : coordsString.split(";")) { annotatePage(document, coords, "123", null, // p.getLastName() == null ? 1 : p.getLastName().hashCode(), 1.0f, true, dictionary); } } } } LOGGER.debug("totalBib: " + totalBib); LOGGER.debug("totalMarkers1: " + totalMarkers1); LOGGER.debug("totalMarkers2: " + totalMarkers2); return document; } private static void annotatePage(PDDocument document, String coords, String teiId, String uri, float lineWidth, boolean isMarker, Map<String, Pair<Integer, Integer>> dictionary) throws IOException { //System.out.println("Annotating for coordinates: " + coords); /*long seed = 0L; if (teiId != null) seed = teiId.hashCode();*/ if (StringUtils.isEmpty(coords)) { return; } String[] split = coords.split(","); Long pageNum = Long.valueOf(split[0], 10) - 1; PDPage page = document.getDocumentCatalog().getPages().get(pageNum.intValue()); PDRectangle mediaBox = page.getMediaBox(); if (mediaBox == null) { mediaBox = page.getMediaBox(); // this will look for the main media box of the page up in the PDF element hierarchy if (mediaBox == null) { // we tried our best given PDFBox LOGGER.warn("Media box for page " + pageNum.intValue() + " not found."); return; } } float height = mediaBox.getHeight(); float lowerX = mediaBox.getLowerLeftX(); float lowerY = mediaBox.getLowerLeftY(); float x = Float.parseFloat(split[1]); float y = Float.parseFloat(split[2]); float w = Float.parseFloat(split[3]); float h = Float.parseFloat(split[4]); float annX = x + lowerX; float annY = (height - (y + h)) + lowerY; float annRightX = x + w + lowerX; float annTopY = height - y + lowerY; PDRectangle rect = new PDRectangle(); rect.setLowerLeftX(annX); rect.setLowerLeftY(annY); rect.setUpperRightX(annRightX); rect.setUpperRightY(annTopY); PDBorderStyleDictionary borderULine = new PDBorderStyleDictionary(); borderULine.setStyle(PDBorderStyleDictionary.STYLE_BEVELED); // so that a border is not visible at all borderULine.setWidth(0); PDAnnotationLink txtLink = new PDAnnotationLink(); txtLink.setBorderStyle(borderULine); //white rectangle border color (ideally, should be transparent) COSArray white = new COSArray(); white.setFloatArray(new float[]{1f, 1f, 1f}); txtLink.setColor(new PDColor(white, PDDeviceRGB.INSTANCE)); txtLink.setReadOnly(true); txtLink.setHighlightMode(PDAnnotationLink.HIGHLIGHT_MODE_PUSH); if (isMarker && (teiId != null)) { Pair<Integer, Integer> thePlace = dictionary.get(teiId); if (thePlace != null) { PDPageFitWidthDestination destination = new PDPageFitWidthDestination(); PDPage pdpage = document.getPage(thePlace.getA()); destination.setPage(pdpage); //destination.setPageNumber(thePlace.getA()); destination.setTop(thePlace.getB()); PDActionGoTo action = new PDActionGoTo(); action.setDestination(destination); txtLink.setAction(action); } } else { if (teiId != null) { // register the object in the dictionary if (dictionary.get(teiId) == null) { Pair<Integer, Integer> thePlace = new Pair<>(pageNum.intValue(), Math.round(annTopY + h)); dictionary.put(teiId, thePlace); } } if (uri != null) { PDActionURI action = new PDActionURI(); if (uri.endsWith("fulltext/original")) uri = uri.replace("fulltext/original", "fulltext/pdf"); action.setURI(uri); txtLink.setAction(action); } else return; } txtLink.setRectangle(rect); // adding link to the reference page.getAnnotations().add(txtLink); //draw a line PDBorderStyleDictionary borderThick = new PDBorderStyleDictionary(); borderThick.setWidth(1); // 12th inch // adding line to the reference PDPageContentStream stream = new PDPageContentStream(document, page, true, false, true); //Random r = new Random(seed + 1); // stream.setStrokingColor(85, 177, 245); //stream.setStrokingColor(r.nextInt(255), r.nextInt(255), r.nextInt(255)); stream.setStrokingColor(0, 0, 255); if (isMarker || (uri != null)) stream.setLineWidth(lineWidth); else stream.setLineWidth(0f); stream.drawLine(annX, annY, annRightX, annY); stream.close(); } /** * Produce JSON annotations with PDF coordinates for web based PDF rendering. Annotations * are given for bib. ref. and bib markers separately, together with the dimension of the * different pages for client resizing. * The annotations of the bibliographical references can be associated to an URL in * order to support "clickable" bib. ref. annotations. * * @param teiDoc the Document object resulting from the full document structuring * @param resolvedBibRefUrl the list of URL to be added to the bibliographical reference * annotations, if null the bib. ref. annotations are not associated to external URL. */ public static String getJsonAnnotations(Document teiDoc, List<String> resolvedBibRefUrl) throws IOException, XPathException { StringWriter refW = new StringWriter(); JsonGenerator jsonRef = jFactory.createGenerator(refW); //jsonRef.useDefaultPrettyPrinter(); jsonRef.writeStartObject(); // page height and width List<Page> pages = teiDoc.getPages(); int pageNumber = 1; jsonRef.writeArrayFieldStart("pages"); for(Page page : pages) { jsonRef.writeStartObject(); jsonRef.writeNumberField("page_height", page.getHeight()); jsonRef.writeNumberField("page_width", page.getWidth()); jsonRef.writeEndObject(); pageNumber++; } jsonRef.writeEndArray(); StringWriter markW = new StringWriter(); JsonGenerator jsonMark = jFactory.createGenerator(markW); jsonMark.writeStartArray(); int totalMarkers1 = 0; int totalMarkers2 = 0; int totalBib = 0; jsonRef.writeArrayFieldStart("refBibs"); String tei = teiDoc.getTei(); Multimap<String, BibDataSetContext> contexts = BibDataSetContextExtractor.getCitationReferences(tei); int bibIndex = 0; for (BibDataSet cit : teiDoc.getBibDataSets()) { String teiId = cit.getResBib().getTeiId(); totalBib++; jsonRef.writeStartObject(); jsonRef.writeStringField("id", teiId); // url if any - they are passed via the resolvedBibRefUrl vector provided as argument if ( (resolvedBibRefUrl != null) && (resolvedBibRefUrl.size()>bibIndex) && (resolvedBibRefUrl.get(bibIndex) != null) ) { jsonRef.writeStringField("url", resolvedBibRefUrl.get(bibIndex)); } else { // by default we put the existing url, doi or arXiv link BiblioItem biblio = cit.getResBib(); String theUrl = null; if (!StringUtils.isEmpty(biblio.getOAURL())) { theUrl = biblio.getOAURL(); } else if (!StringUtils.isEmpty(biblio.getDOI())) { theUrl = "https://dx.doi.org/" + biblio.getDOI(); } else if (!StringUtils.isEmpty(biblio.getArXivId())) { theUrl = "https://arxiv.org/" + biblio.getArXivId(); } else if (!StringUtils.isEmpty(biblio.getWeb())) { theUrl = biblio.getWeb(); } if (theUrl != null) jsonRef.writeStringField("url", theUrl); } jsonRef.writeArrayFieldStart("pos"); if (cit.getResBib().getCoordinates() != null) { for (BoundingBox b : cit.getResBib().getCoordinates()) { // reference string jsonRef.writeStartObject(); b.writeJsonProps(jsonRef); jsonRef.writeEndObject(); } } jsonRef.writeEndArray(); // pos jsonRef.writeEndObject(); // refBibs element // reference markers for this reference for (BibDataSetContext c : contexts.get(teiId)) { //System.out.println(c.getContext()); String mrect = c.getDocumentCoords(); if ((mrect != null) && (mrect.trim().length()>0)) { for (String coords : mrect.split(";")) { if ((coords == null) || (coords.length() == 0)) continue; //annotatePage(document, coords, teiId.hashCode(), 1.0f); jsonMark.writeStartObject(); jsonMark.writeStringField("id", teiId); BoundingBox b2 = BoundingBox.fromString(coords); b2.writeJsonProps(jsonMark); jsonMark.writeEndObject(); totalMarkers1++; } } } bibIndex++; } jsonRef.writeEndArray(); // refBibs for (BibDataSetContext c : contexts.get("")) { String mrect = c.getDocumentCoords(); if ((mrect != null) && (mrect.trim().length()>0)) { for (String coords : mrect.split(";")) { if (coords.trim().length() == 0) continue; //annotatePage(document, coords, 0, 1.0f); BoundingBox b = BoundingBox.fromString(coords); jsonMark.writeStartObject(); b.writeJsonProps(jsonMark); jsonMark.writeEndObject(); totalMarkers2++; } } } jsonMark.writeEndArray(); jsonMark.close(); LOGGER.debug("totalBib: " + totalBib); LOGGER.debug("totalMarkers1: " + totalMarkers1); LOGGER.debug("totalMarkers2: " + totalMarkers2); jsonRef.writeFieldName("refMarkers"); jsonRef.writeRawValue(markW.toString()); jsonRef.writeEndObject(); jsonRef.close(); return refW.toString(); } /* * A variant where annotations are provided page per page */ public static String getJsonAnnotationsPerPage(Document teiDoc, List<String> resolvedBibRefUrl) throws IOException, XPathException { StringBuilder jsonRef = new StringBuilder(); jsonRef.append("{\"pages\" : ["); int totalMarkers1 = 0; int totalMarkers2 = 0; int totalBib = 0; List<Page> pages = teiDoc.getPages(); int pageNumber = 1; for(Page page : pages) { if (pageNumber > 1) jsonRef.append(", "); // page height and width jsonRef.append("{\"page_height\":" + page.getHeight()); jsonRef.append(", \"page_width\":" + page.getWidth()); boolean refBibOutput = false; StringBuilder jsonMark = new StringBuilder(); boolean refMarkOutput = false; String tei = teiDoc.getTei(); Multimap<String, BibDataSetContext> contexts = BibDataSetContextExtractor.getCitationReferences(tei); boolean beginMark = true; boolean begin = true; for (BibDataSet cit : teiDoc.getBibDataSets()) { String teiId = cit.getResBib().getTeiId(); boolean idOutput = false; boolean begin2 = true; if (cit.getResBib().getCoordinates() != null) { for (BoundingBox b : cit.getResBib().getCoordinates()) { if (b.getPage() == pageNumber) { if (!refBibOutput) { jsonRef.append(", \"refBibs\": [ "); refBibOutput = true; } if (!idOutput) { if (begin) begin = false; else jsonRef.append(", "); jsonRef.append("{\"id\":\"").append(teiId).append("\", "); jsonRef.append("\"pos\":["); idOutput = true; } // reference string if (begin2) begin2 = false; else jsonRef.append(", "); jsonRef.append("{").append(b.toJson()).append("}"); totalBib++; } //annotatePage(document, b.toString(), teiId.hashCode(), contexts.containsKey(teiId) ? 1.5f : 0.5f); } } // reference markers for this reference for (BibDataSetContext c : contexts.get(teiId)) { //System.out.println(c.getContext()); String mrect = c.getDocumentCoords(); if ( (mrect != null) && (mrect.trim().length()>0) ) { for (String coords : mrect.split(";")) { if (coords.trim().length() == 0) continue; //annotatePage(document, coords, teiId.hashCode(), 1.0f); BoundingBox b2 = BoundingBox.fromString(coords); if (b2.getPage() == pageNumber) { if (!refMarkOutput) { jsonMark.append(", \"refMarkers\": ["); refMarkOutput = true; } else jsonMark.append(", "); jsonMark.append("{ \"id\":\"").append(teiId).append("\", "); jsonMark.append(b2.toJson()).append(" }"); totalMarkers1++; } } } } if (idOutput) { jsonRef.append("] }"); } } for (BibDataSetContext c : contexts.get("")) { String mrect = c.getDocumentCoords(); if ( (mrect != null) && (mrect.trim().length()>0) ) { for (String coords : mrect.split(";")) { if (coords.trim().length() == 0) continue; BoundingBox b = BoundingBox.fromString(coords); if (b.getPage() == pageNumber) { if (!refMarkOutput) { jsonMark.append(", \"refMarkers\": ["); refMarkOutput = true; } else jsonMark.append(", "); jsonMark.append("{").append(b.toJson()).append("}"); totalMarkers2++; } } } } pageNumber++; if (refBibOutput) { jsonRef.append("]"); } if (refMarkOutput) { jsonRef.append(jsonMark.toString()).append("]"); } jsonRef.append("}"); } LOGGER.debug("totalBib: " + totalBib); LOGGER.debug("totalMarkers1: " + totalMarkers1); LOGGER.debug("totalMarkers2: " + totalMarkers2); jsonRef.append("]}"); return jsonRef.toString(); } }
grobid-core/src/main/java/org/grobid/core/visualization/CitationsVisualizer.java
package org.grobid.core.visualization; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import com.google.common.collect.Multimap; import net.sf.saxon.trans.XPathException; import org.apache.commons.lang3.StringUtils; import org.apache.pdfbox.cos.COSArray; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDPageDestination; import org.apache.pdfbox.pdmodel.PDPageContentStream; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.apache.pdfbox.pdmodel.graphics.color.PDColor; import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB; import org.apache.pdfbox.pdmodel.interactive.action.PDActionGoTo; import org.apache.pdfbox.pdmodel.interactive.action.PDActionURI; import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationLink; import org.apache.pdfbox.pdmodel.interactive.annotation.PDBorderStyleDictionary; import org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDPageFitWidthDestination; import org.grobid.core.data.BibDataSet; import org.grobid.core.data.BibDataSetContext; import org.grobid.core.data.BiblioItem; import org.grobid.core.data.Person; import org.grobid.core.document.Document; import org.grobid.core.layout.BoundingBox; import org.grobid.core.layout.Page; import org.grobid.core.utilities.BibDataSetContextExtractor; import org.grobid.core.utilities.LayoutTokensUtil; import org.grobid.core.utilities.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.StringWriter; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Utilities for visualizing citation markers and biblographical references, wither directly * in the PDF using the PDF annotation layer or as annotations in JSON for supporting * web based rendering (e.g. with PDF.js) and interactive HTML layer. * See the web console/demo for actual examples of usage. */ public class CitationsVisualizer { private static final Logger LOGGER = LoggerFactory.getLogger(CitationsVisualizer.class); private static final JsonFactory jFactory = new JsonFactory(); /** * Augment a PDF with bibliographical annotation, for bib. ref. and bib markers. * The PDF annotation layer is used with "GoTo" and "URI" action links. * The annotations of the bibliographical references can be associated to an URL in order * to have clickable references direclty in the PDF. * The Apache PDFBox library is used. * * @param document PDDocument object resulting from the PDF parsing with PDFBox * @param teiDoc the Document object resulting from the full document structuring * @param resolvedBibRefUrl the list of URL to be added to the bibliographical reference * annotations, if null the bib. ref. annotations are not associated to external URL. */ public static PDDocument annotatePdfWithCitations(PDDocument document, Document teiDoc, List<String> resolvedBibRefUrl) throws IOException, XPathException { String tei = teiDoc.getTei(); //System.out.println(tei); int totalBib = 0; int totalMarkers1 = 0; int totalMarkers2 = 0; Multimap<String, BibDataSetContext> contexts = BibDataSetContextExtractor.getCitationReferences(tei); Map<String, Pair<Integer, Integer>> dictionary = new HashMap<>(); int indexBib = 0; for (BibDataSet cit : teiDoc.getBibDataSets()) { String teiId = cit.getResBib().getTeiId(); totalBib++; String theUrl = null; if ( (resolvedBibRefUrl != null) && (resolvedBibRefUrl.size() > indexBib) && (resolvedBibRefUrl.get(indexBib) != null) ) theUrl = resolvedBibRefUrl.get(indexBib); else { // by default we put the existing url, doi or arXiv link BiblioItem biblio = cit.getResBib(); if (!StringUtils.isEmpty(biblio.getDOI())) { theUrl = "http://dx.doi.org/" + biblio.getDOI(); } else if (!StringUtils.isEmpty(biblio.getArXivId())) { theUrl = "http://arxiv.org/" + biblio.getArXivId(); } else if (!StringUtils.isEmpty(biblio.getWeb())) { theUrl = biblio.getWeb(); } } if (cit.getResBib().getCoordinates() != null) { for (BoundingBox b : cit.getResBib().getCoordinates()) { annotatePage(document, b.toString(), teiId, theUrl, 1.5f, false, dictionary); } } //annotating reference markers for (BibDataSetContext c : contexts.get(teiId)) { //System.out.println(c.getContext()); String mrect = c.getDocumentCoords(); if ((mrect != null) && (mrect.trim().length()>0)) { for (String coords : mrect.split(";")) { if (coords.trim().length() == 0) continue; annotatePage(document, coords, teiId, null, 1.0f, true, dictionary); totalMarkers1++; } } } indexBib++; } for (BibDataSetContext c : contexts.get("")) { String mrect = c.getDocumentCoords(); if ((mrect != null) && (mrect.trim().length()>0)) { for (String coords : mrect.split(";")) { if (coords.trim().length() == 0) continue; annotatePage(document, coords, null, null, 1.0f, true, dictionary); totalMarkers2++; } } } if (teiDoc.getResHeader() != null && teiDoc.getResHeader().getFullAuthors() != null) { for (Person p : teiDoc.getResHeader().getFullAuthors()) { if (p.getLayoutTokens() != null) { String coordsString = LayoutTokensUtil.getCoordsString(p.getLayoutTokens()); for (String coords : coordsString.split(";")) { annotatePage(document, coords, "123", null, // p.getLastName() == null ? 1 : p.getLastName().hashCode(), 1.0f, true, dictionary); } } } } LOGGER.debug("totalBib: " + totalBib); LOGGER.debug("totalMarkers1: " + totalMarkers1); LOGGER.debug("totalMarkers2: " + totalMarkers2); return document; } private static void annotatePage(PDDocument document, String coords, String teiId, String uri, float lineWidth, boolean isMarker, Map<String, Pair<Integer, Integer>> dictionary) throws IOException { //System.out.println("Annotating for coordinates: " + coords); /*long seed = 0L; if (teiId != null) seed = teiId.hashCode();*/ if (StringUtils.isEmpty(coords)) { return; } String[] split = coords.split(","); Long pageNum = Long.valueOf(split[0], 10) - 1; PDPage page = document.getDocumentCatalog().getPages().get(pageNum.intValue()); PDRectangle mediaBox = page.getMediaBox(); if (mediaBox == null) { mediaBox = page.getMediaBox(); // this will look for the main media box of the page up in the PDF element hierarchy if (mediaBox == null) { // we tried our best given PDFBox LOGGER.warn("Media box for page " + pageNum.intValue() + " not found."); return; } } float height = mediaBox.getHeight(); float lowerX = mediaBox.getLowerLeftX(); float lowerY = mediaBox.getLowerLeftY(); float x = Float.parseFloat(split[1]); float y = Float.parseFloat(split[2]); float w = Float.parseFloat(split[3]); float h = Float.parseFloat(split[4]); float annX = x + lowerX; float annY = (height - (y + h)) + lowerY; float annRightX = x + w + lowerX; float annTopY = height - y + lowerY; PDRectangle rect = new PDRectangle(); rect.setLowerLeftX(annX); rect.setLowerLeftY(annY); rect.setUpperRightX(annRightX); rect.setUpperRightY(annTopY); PDBorderStyleDictionary borderULine = new PDBorderStyleDictionary(); borderULine.setStyle(PDBorderStyleDictionary.STYLE_BEVELED); // so that a border is not visible at all borderULine.setWidth(0); PDAnnotationLink txtLink = new PDAnnotationLink(); txtLink.setBorderStyle(borderULine); //white rectangle border color (ideally, should be transparent) COSArray white = new COSArray(); white.setFloatArray(new float[]{1f, 1f, 1f}); txtLink.setColor(new PDColor(white, PDDeviceRGB.INSTANCE)); txtLink.setReadOnly(true); txtLink.setHighlightMode(PDAnnotationLink.HIGHLIGHT_MODE_PUSH); if (isMarker && (teiId != null)) { Pair<Integer, Integer> thePlace = dictionary.get(teiId); if (thePlace != null) { PDPageFitWidthDestination destination = new PDPageFitWidthDestination(); PDPage pdpage = document.getPage(thePlace.getA()); destination.setPage(pdpage); //destination.setPageNumber(thePlace.getA()); destination.setTop(thePlace.getB()); PDActionGoTo action = new PDActionGoTo(); action.setDestination(destination); txtLink.setAction(action); } } else { if (teiId != null) { // register the object in the dictionary if (dictionary.get(teiId) == null) { Pair<Integer, Integer> thePlace = new Pair<>(pageNum.intValue(), Math.round(annTopY + h)); dictionary.put(teiId, thePlace); } } if (uri != null) { PDActionURI action = new PDActionURI(); if (uri.endsWith("fulltext/original")) uri = uri.replace("fulltext/original", "fulltext/pdf"); action.setURI(uri); txtLink.setAction(action); } else return; } txtLink.setRectangle(rect); // adding link to the reference page.getAnnotations().add(txtLink); //draw a line PDBorderStyleDictionary borderThick = new PDBorderStyleDictionary(); borderThick.setWidth(1); // 12th inch // adding line to the reference PDPageContentStream stream = new PDPageContentStream(document, page, true, false, true); //Random r = new Random(seed + 1); // stream.setStrokingColor(85, 177, 245); //stream.setStrokingColor(r.nextInt(255), r.nextInt(255), r.nextInt(255)); stream.setStrokingColor(0, 0, 255); if (isMarker || (uri != null)) stream.setLineWidth(lineWidth); else stream.setLineWidth(0f); stream.drawLine(annX, annY, annRightX, annY); stream.close(); } /** * Produce JSON annotations with PDF coordinates for web based PDF rendering. Annotations * are given for bib. ref. and bib markers separately, together with the dimension of the * different pages for client resizing. * The annotations of the bibliographical references can be associated to an URL in * order to support "clickable" bib. ref. annotations. * * @param teiDoc the Document object resulting from the full document structuring * @param resolvedBibRefUrl the list of URL to be added to the bibliographical reference * annotations, if null the bib. ref. annotations are not associated to external URL. */ public static String getJsonAnnotations(Document teiDoc, List<String> resolvedBibRefUrl) throws IOException, XPathException { StringWriter refW = new StringWriter(); JsonGenerator jsonRef = jFactory.createGenerator(refW); //jsonRef.useDefaultPrettyPrinter(); jsonRef.writeStartObject(); // page height and width List<Page> pages = teiDoc.getPages(); int pageNumber = 1; jsonRef.writeArrayFieldStart("pages"); for(Page page : pages) { jsonRef.writeStartObject(); jsonRef.writeNumberField("page_height", page.getHeight()); jsonRef.writeNumberField("page_width", page.getWidth()); jsonRef.writeEndObject(); pageNumber++; } jsonRef.writeEndArray(); StringWriter markW = new StringWriter(); JsonGenerator jsonMark = jFactory.createGenerator(markW); jsonMark.writeStartArray(); int totalMarkers1 = 0; int totalMarkers2 = 0; int totalBib = 0; jsonRef.writeArrayFieldStart("refBibs"); String tei = teiDoc.getTei(); Multimap<String, BibDataSetContext> contexts = BibDataSetContextExtractor.getCitationReferences(tei); int bibIndex = 0; for (BibDataSet cit : teiDoc.getBibDataSets()) { String teiId = cit.getResBib().getTeiId(); totalBib++; jsonRef.writeStartObject(); jsonRef.writeStringField("id", teiId); // url if any - they are passed via the resolvedBibRefUrl vector provided as argument if ( (resolvedBibRefUrl != null) && (resolvedBibRefUrl.size()>bibIndex) && (resolvedBibRefUrl.get(bibIndex) != null) ) { jsonRef.writeStringField("url", resolvedBibRefUrl.get(bibIndex)); } else { // by default we put the existing url, doi or arXiv link BiblioItem biblio = cit.getResBib(); String theUrl = null; if (!StringUtils.isEmpty(biblio.getOAURL())) { theUrl = biblio.getOAURL(); } else if (!StringUtils.isEmpty(biblio.getDOI())) { theUrl = "http://dx.doi.org/" + biblio.getDOI(); } else if (!StringUtils.isEmpty(biblio.getArXivId())) { theUrl = "http://arxiv.org/" + biblio.getArXivId(); } else if (!StringUtils.isEmpty(biblio.getWeb())) { theUrl = biblio.getWeb(); } if (theUrl != null) jsonRef.writeStringField("url", theUrl); } jsonRef.writeArrayFieldStart("pos"); if (cit.getResBib().getCoordinates() != null) { for (BoundingBox b : cit.getResBib().getCoordinates()) { // reference string jsonRef.writeStartObject(); b.writeJsonProps(jsonRef); jsonRef.writeEndObject(); } } jsonRef.writeEndArray(); // pos jsonRef.writeEndObject(); // refBibs element // reference markers for this reference for (BibDataSetContext c : contexts.get(teiId)) { //System.out.println(c.getContext()); String mrect = c.getDocumentCoords(); if ((mrect != null) && (mrect.trim().length()>0)) { for (String coords : mrect.split(";")) { if ((coords == null) || (coords.length() == 0)) continue; //annotatePage(document, coords, teiId.hashCode(), 1.0f); jsonMark.writeStartObject(); jsonMark.writeStringField("id", teiId); BoundingBox b2 = BoundingBox.fromString(coords); b2.writeJsonProps(jsonMark); jsonMark.writeEndObject(); totalMarkers1++; } } } bibIndex++; } jsonRef.writeEndArray(); // refBibs for (BibDataSetContext c : contexts.get("")) { String mrect = c.getDocumentCoords(); if ((mrect != null) && (mrect.trim().length()>0)) { for (String coords : mrect.split(";")) { if (coords.trim().length() == 0) continue; //annotatePage(document, coords, 0, 1.0f); BoundingBox b = BoundingBox.fromString(coords); jsonMark.writeStartObject(); b.writeJsonProps(jsonMark); jsonMark.writeEndObject(); totalMarkers2++; } } } jsonMark.writeEndArray(); jsonMark.close(); LOGGER.debug("totalBib: " + totalBib); LOGGER.debug("totalMarkers1: " + totalMarkers1); LOGGER.debug("totalMarkers2: " + totalMarkers2); jsonRef.writeFieldName("refMarkers"); jsonRef.writeRawValue(markW.toString()); jsonRef.writeEndObject(); jsonRef.close(); return refW.toString(); } /* * A variant where annotations are provided page per page */ public static String getJsonAnnotationsPerPage(Document teiDoc, List<String> resolvedBibRefUrl) throws IOException, XPathException { StringBuilder jsonRef = new StringBuilder(); jsonRef.append("{\"pages\" : ["); int totalMarkers1 = 0; int totalMarkers2 = 0; int totalBib = 0; List<Page> pages = teiDoc.getPages(); int pageNumber = 1; for(Page page : pages) { if (pageNumber > 1) jsonRef.append(", "); // page height and width jsonRef.append("{\"page_height\":" + page.getHeight()); jsonRef.append(", \"page_width\":" + page.getWidth()); boolean refBibOutput = false; StringBuilder jsonMark = new StringBuilder(); boolean refMarkOutput = false; String tei = teiDoc.getTei(); Multimap<String, BibDataSetContext> contexts = BibDataSetContextExtractor.getCitationReferences(tei); boolean beginMark = true; boolean begin = true; for (BibDataSet cit : teiDoc.getBibDataSets()) { String teiId = cit.getResBib().getTeiId(); boolean idOutput = false; boolean begin2 = true; if (cit.getResBib().getCoordinates() != null) { for (BoundingBox b : cit.getResBib().getCoordinates()) { if (b.getPage() == pageNumber) { if (!refBibOutput) { jsonRef.append(", \"refBibs\": [ "); refBibOutput = true; } if (!idOutput) { if (begin) begin = false; else jsonRef.append(", "); jsonRef.append("{\"id\":\"").append(teiId).append("\", "); jsonRef.append("\"pos\":["); idOutput = true; } // reference string if (begin2) begin2 = false; else jsonRef.append(", "); jsonRef.append("{").append(b.toJson()).append("}"); totalBib++; } //annotatePage(document, b.toString(), teiId.hashCode(), contexts.containsKey(teiId) ? 1.5f : 0.5f); } } // reference markers for this reference for (BibDataSetContext c : contexts.get(teiId)) { //System.out.println(c.getContext()); String mrect = c.getDocumentCoords(); if ( (mrect != null) && (mrect.trim().length()>0) ) { for (String coords : mrect.split(";")) { if (coords.trim().length() == 0) continue; //annotatePage(document, coords, teiId.hashCode(), 1.0f); BoundingBox b2 = BoundingBox.fromString(coords); if (b2.getPage() == pageNumber) { if (!refMarkOutput) { jsonMark.append(", \"refMarkers\": ["); refMarkOutput = true; } else jsonMark.append(", "); jsonMark.append("{ \"id\":\"").append(teiId).append("\", "); jsonMark.append(b2.toJson()).append(" }"); totalMarkers1++; } } } } if (idOutput) { jsonRef.append("] }"); } } for (BibDataSetContext c : contexts.get("")) { String mrect = c.getDocumentCoords(); if ( (mrect != null) && (mrect.trim().length()>0) ) { for (String coords : mrect.split(";")) { if (coords.trim().length() == 0) continue; BoundingBox b = BoundingBox.fromString(coords); if (b.getPage() == pageNumber) { if (!refMarkOutput) { jsonMark.append(", \"refMarkers\": ["); refMarkOutput = true; } else jsonMark.append(", "); jsonMark.append("{").append(b.toJson()).append("}"); totalMarkers2++; } } } } pageNumber++; if (refBibOutput) { jsonRef.append("]"); } if (refMarkOutput) { jsonRef.append(jsonMark.toString()).append("]"); } jsonRef.append("}"); } LOGGER.debug("totalBib: " + totalBib); LOGGER.debug("totalMarkers1: " + totalMarkers1); LOGGER.debug("totalMarkers2: " + totalMarkers2); jsonRef.append("]}"); return jsonRef.toString(); } }
use https:// in links (not http://) Former-commit-id: 6a0dd1cc182ef81b1505eb83096b5ae110dbdc06
grobid-core/src/main/java/org/grobid/core/visualization/CitationsVisualizer.java
use https:// in links (not http://)
<ide><path>robid-core/src/main/java/org/grobid/core/visualization/CitationsVisualizer.java <ide> // by default we put the existing url, doi or arXiv link <ide> BiblioItem biblio = cit.getResBib(); <ide> if (!StringUtils.isEmpty(biblio.getDOI())) { <del> theUrl = "http://dx.doi.org/" + biblio.getDOI(); <add> theUrl = "https://dx.doi.org/" + biblio.getDOI(); <ide> } else if (!StringUtils.isEmpty(biblio.getArXivId())) { <del> theUrl = "http://arxiv.org/" + biblio.getArXivId(); <add> theUrl = "https://arxiv.org/" + biblio.getArXivId(); <ide> } else if (!StringUtils.isEmpty(biblio.getWeb())) { <ide> theUrl = biblio.getWeb(); <ide> } <ide> if (!StringUtils.isEmpty(biblio.getOAURL())) { <ide> theUrl = biblio.getOAURL(); <ide> } else if (!StringUtils.isEmpty(biblio.getDOI())) { <del> theUrl = "http://dx.doi.org/" + biblio.getDOI(); <add> theUrl = "https://dx.doi.org/" + biblio.getDOI(); <ide> } else if (!StringUtils.isEmpty(biblio.getArXivId())) { <del> theUrl = "http://arxiv.org/" + biblio.getArXivId(); <add> theUrl = "https://arxiv.org/" + biblio.getArXivId(); <ide> } else if (!StringUtils.isEmpty(biblio.getWeb())) { <ide> theUrl = biblio.getWeb(); <ide> }
Java
mit
2eb766de22af4f4e7d65c0f317225f5e3995ceaf
0
honorem/spring-session-cassandra
/* * The MIT License * * Copyright 2016 honorem. * * 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.honorem.spring.session.cassandra; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Base64; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.UUID; import org.springframework.cassandra.core.PrimaryKeyType; import org.springframework.data.cassandra.mapping.PrimaryKeyColumn; import org.springframework.data.cassandra.mapping.Table; import org.springframework.session.ExpiringSession; /** * * @author Marc Honoré <[email protected]> */ @Table public class CassandraSession implements ExpiringSession { public static final String DEFAULT_TABLE_NAME = "cassandra_sessions"; //The default validity of a session (in s) public static final int SESSION_DEFAULT_VALIDITY = 1800; //The validity of this session protected static int SESSION_VALIDITY = SESSION_DEFAULT_VALIDITY; //the id of the session used as a primary key @PrimaryKeyColumn(name = "id", ordinal = 0, type = PrimaryKeyType.PARTITIONED) private String id; //the interval beetwen which the session is valid private int interval; //the time of creation of the session private long created; //the last time the session has been accessed private long accessed; //the data in the session private Map<String, String> data; //update default session validity public static void setSessionValidity(int validity) { SESSION_VALIDITY = validity; } //constructor used by cassandra session repository public CassandraSession() { this(SESSION_DEFAULT_VALIDITY); } //constructor used to delete a session public CassandraSession(String id) { this.id = id; } //constructor used by cassandra session repository public CassandraSession(int interval) { this(UUID.randomUUID().toString(), interval); } //constructor used by cassandra session repository public CassandraSession(String _id, int interval) { this.id = _id; this.interval = interval; this.accessed = System.currentTimeMillis(); this.data = new HashMap<>(); } @Override public long getCreationTime() { return this.created; } @Override public void setLastAccessedTime(long lastAccessedTime) { this.accessed = lastAccessedTime; } @Override public long getLastAccessedTime() { return this.accessed; } @Override public void setMaxInactiveIntervalInSeconds(int interval) { this.interval = interval; } @Override public int getMaxInactiveIntervalInSeconds() { return this.interval; } @Override public boolean isExpired() { return System.currentTimeMillis() > (this.accessed + 1000 * this.interval); } @Override public String getId() { return this.id; } @Override public <T> T getAttribute(String attributeName) { if (this.data == null || !this.data.containsKey(attributeName)) { return null; } String o = this.data.get(attributeName); return (T) deserialize(o); } @Override public Set<String> getAttributeNames() { return this.data.keySet(); } @Override public void setAttribute(String attributeName, Object attributeValue) { if(this.data.getClass().getSimpleName().equals("UnmodifiableMap")){ Map<String, String> map = new HashMap<>(); this.data.keySet().stream().forEach((key) -> { map.put(key, this.data.get(key)); }); this.data = map; } this.data.put(attributeName, serialize(attributeValue)); } @Override public void removeAttribute(String attributeName) { if(this.data.getClass().getSimpleName().equals("UnmodifiableMap")){ Map<String, String> map = new HashMap<>(); this.data.keySet().stream().forEach((key) -> { map.put(key, this.data.get(key)); }); this.data = map; } this.data.remove(attributeName); } /** * Serialize object as base64 encoded String * * @param _object The object to serialize * @return The serialized object */ private String serialize(Object _object) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(_object); oos.close(); return Base64.getEncoder().encodeToString(baos.toByteArray()); } catch (Exception ex) { throw new RuntimeException(ex); } } /** * Deserialize base64 encoded object * * @param _serialized The object serialized * @return The deserialized object */ private Object deserialize(String _serialized) { if (_serialized == null) { return null; } try { return new ObjectInputStream( new ByteArrayInputStream( Base64.getDecoder().decode(_serialized) ) ).readObject(); } catch (Exception ex) { throw new RuntimeException(ex); } } public Map<String, String> getMetadata(){ return data; } }
src/main/java/com/github/honorem/spring/session/cassandra/CassandraSession.java
/* * The MIT License * * Copyright 2016 honorem. * * 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.honorem.spring.session.cassandra; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Base64; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.UUID; import org.springframework.cassandra.core.PrimaryKeyType; import org.springframework.data.cassandra.mapping.PrimaryKeyColumn; import org.springframework.data.cassandra.mapping.Table; import org.springframework.session.ExpiringSession; /** * * @author Marc Honoré <[email protected]> */ @Table public class CassandraSession implements ExpiringSession { public static final String DEFAULT_TABLE_NAME = "cassandra_sessions"; //The default validity of a session (in s) public static final int SESSION_DEFAULT_VALIDITY = 1800; //The validity of this session protected static int SESSION_VALIDITY = SESSION_DEFAULT_VALIDITY; //the id of the session used as a primary key @PrimaryKeyColumn(name = "id", ordinal = 0, type = PrimaryKeyType.PARTITIONED) private String id; //the interval beetwen which the session is valid private int interval; //the time of creation of the session private long created; //the last time the session has been accessed private long accessed; //the data in the session private Map<String, String> data; //update default session validity public static void setSessionValidity(int validity) { SESSION_VALIDITY = validity; } //constructor used by cassandra session repository public CassandraSession() { this(SESSION_DEFAULT_VALIDITY); } //constructor used to delete a session public CassandraSession(String id) { this.id = id; } //constructor used by cassandra session repository public CassandraSession(int interval) { this(UUID.randomUUID().toString(), interval); } //constructor used by cassandra session repository public CassandraSession(String _id, int interval) { this.id = _id; this.interval = interval; this.accessed = System.currentTimeMillis(); this.data = new HashMap<>(); } @Override public long getCreationTime() { return this.created; } @Override public void setLastAccessedTime(long lastAccessedTime) { this.accessed = lastAccessedTime; } @Override public long getLastAccessedTime() { return this.accessed; } @Override public void setMaxInactiveIntervalInSeconds(int interval) { this.interval = interval; } @Override public int getMaxInactiveIntervalInSeconds() { return this.interval; } @Override public boolean isExpired() { return System.currentTimeMillis() > (this.accessed + 1000 * this.interval); } @Override public String getId() { return this.id; } @Override public <T> T getAttribute(String attributeName) { if (!this.data.containsKey(attributeName)) { return null; } String o = this.data.get(attributeName); return (T) deserialize(o); } @Override public Set<String> getAttributeNames() { return this.data.keySet(); } @Override public void setAttribute(String attributeName, Object attributeValue) { if(this.data.getClass().getSimpleName().equals("UnmodifiableMap")){ Map<String, String> map = new HashMap<>(); this.data.keySet().stream().forEach((key) -> { map.put(key, this.data.get(key)); }); this.data = map; } this.data.put(attributeName, serialize(attributeValue)); } @Override public void removeAttribute(String attributeName) { if(this.data.getClass().getSimpleName().equals("UnmodifiableMap")){ Map<String, String> map = new HashMap<>(); this.data.keySet().stream().forEach((key) -> { map.put(key, this.data.get(key)); }); this.data = map; } this.data.remove(attributeName); } /** * Serialize object as base64 encoded String * * @param _object The object to serialize * @return The serialized object */ private String serialize(Object _object) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(_object); oos.close(); return Base64.getEncoder().encodeToString(baos.toByteArray()); } catch (Exception ex) { throw new RuntimeException(ex); } } /** * Deserialize base64 encoded object * * @param _serialized The object serialized * @return The deserialized object */ private Object deserialize(String _serialized) { if (_serialized == null) { return null; } try { return new ObjectInputStream( new ByteArrayInputStream( Base64.getDecoder().decode(_serialized) ) ).readObject(); } catch (Exception ex) { throw new RuntimeException(ex); } } public Map<String, String> getMetadata(){ return data; } }
fix nullpointer on getAttribute
src/main/java/com/github/honorem/spring/session/cassandra/CassandraSession.java
fix nullpointer on getAttribute
<ide><path>rc/main/java/com/github/honorem/spring/session/cassandra/CassandraSession.java <ide> <ide> @Override <ide> public <T> T getAttribute(String attributeName) { <del> if (!this.data.containsKey(attributeName)) { <add> if (this.data == null || !this.data.containsKey(attributeName)) { <ide> return null; <ide> } <ide> String o = this.data.get(attributeName);
Java
mit
error: pathspec 'app/src/main/java/com/nestedworld/nestedworld/Fragment/Base/BaseFragment.java' did not match any file(s) known to git
3c5a6b13de1df7ceccc8bf2367339e63bee23e21
1
NestedWorld/NestedWorld-Android
package com.nestedworld.nestedworld.Fragment.Base; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import butterknife.ButterKnife; public abstract class BaseFragment extends Fragment { protected String TAG = getClass().getSimpleName(); protected abstract int getLayoutResource(); protected abstract void initVariable(Bundle savedInstanceState); protected abstract void initData(Bundle savedInstanceState); public String toString() { return TAG; } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(getLayoutResource(), container, false); ButterKnife.bind(this, rootView); initVariable(savedInstanceState); initData(savedInstanceState); return rootView; } @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.unbind(this); } }
app/src/main/java/com/nestedworld/nestedworld/Fragment/Base/BaseFragment.java
add baseFragment
app/src/main/java/com/nestedworld/nestedworld/Fragment/Base/BaseFragment.java
add baseFragment
<ide><path>pp/src/main/java/com/nestedworld/nestedworld/Fragment/Base/BaseFragment.java <add>package com.nestedworld.nestedworld.Fragment.Base; <add> <add>import android.os.Bundle; <add>import android.support.annotation.Nullable; <add>import android.support.v4.app.Fragment; <add>import android.view.LayoutInflater; <add>import android.view.View; <add>import android.view.ViewGroup; <add> <add>import butterknife.ButterKnife; <add> <add>public abstract class BaseFragment extends Fragment { <add> <add> protected String TAG = getClass().getSimpleName(); <add> <add> protected abstract int getLayoutResource(); <add> <add> protected abstract void initVariable(Bundle savedInstanceState); <add> <add> protected abstract void initData(Bundle savedInstanceState); <add> <add> public String toString() { <add> return TAG; <add> } <add> <add> @Nullable <add> @Override <add> public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { <add> View rootView = inflater.inflate(getLayoutResource(), container, false); <add> ButterKnife.bind(this, rootView); <add> initVariable(savedInstanceState); <add> initData(savedInstanceState); <add> return rootView; <add> } <add> <add> @Override <add> public void onDestroyView() { <add> super.onDestroyView(); <add> ButterKnife.unbind(this); <add> } <add>}
JavaScript
agpl-3.0
bbd8a306d7363d913981ae6e4c837f11b39e26cd
0
sociam/indx,sociam/indx,sociam/indx
/* jshint undef: true, strict:false, trailing:false, unused:false */ /* global Backbone, angular, jQuery, _, chrome, console */ (function() { var server; var DEFAULT_URL = 'https://indx.local:8211'; var GEO_ENABLE = false; localStorage.indx_url = localStorage.indx_url || DEFAULT_URL; var setErrorBadge = function(errtext) { chrome.browserAction.setBadgeText({text:'x'}); // chrome.browserAction.setBadgeText({text:''+errtext}); chrome.browserAction.setBadgeBackgroundColor({color:'#ff0000'}); }; var clearBadge = function() { chrome.browserAction.setBadgeText({text:''}); }; var setOKBadge = function(s) { chrome.browserAction.setBadgeText({text:s.toString()}); chrome.browserAction.setBadgeBackgroundColor({color:'#00ffff'}); }; var duration_secs = function(d) { return (d.peek('tend') && d.peek('tend').valueOf() - d.peek('tstart') && d.peek('tstart').valueOf()) / 1000.0; }; var getBoxName = function() { return localStorage.indx_box || 'lifelog'; }; var get_watcher = function() { return chrome.extension.getBackgroundPage().watcher_instance; }; var get_store = function() { var w = get_watcher(); if (w) { return w.get('store'); } }; var make_store = function(client,utils) { var server_url = localStorage.indx_url; if (server === undefined) { server = new client.Store({server_host:server_url}); } if (server.get('server_host') !== server_url) { server.set('server_host', server_url); } return server; }; // declare modules -----------------| var app = angular.module('webjournal', ['indx']) .config(function($compileProvider){ $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|data|mailto|file|chrome-extension|chrome|chrome\-extension):/); }).config(function($sceProvider) { // Completely disable SCE - options iframe interference $sceProvider.enabled(false); }).factory('pluginUtils', function() { return { setErrorBadge:setErrorBadge, setOKBadge:setOKBadge, getBoxName:getBoxName, duration_secs:duration_secs, clearBadge:clearBadge }; }).controller('popup', function($scope, watcher, utils) { window.$s = $scope; var records = []; var guid = utils.guid(); // scope methods for rendering things nicely. $scope.date = function(d) { return new Date().toLocaleTimeString().slice(0,-3); }; $scope.duration = function(d) { var secs = duration_secs(d); if (secs < 60) { return secs.toFixed(2) + 's'; } return (secs/60.0).toFixed(2) + 'm'; }; var thumbs = []; $scope.thumb = function(d) { var what = d && d.peek('what'); return what.peek('thumbnail'); }; $scope.label = function(d) { var maxlen = 150; var what = d && d.peek('what'); if (!what) { return ''; } if (what.peek('title') && what.peek('title').length && what.peek('title').trim().length > 0) { return what.peek('title').slice(0,maxlen); } var url = what.id; if (!url) { return ''; } var noprot = url.slice(url.indexOf('//')+2); if (noprot.indexOf('www.') === 0) { noprot = noprot.slice(4); } return noprot.slice(0,maxlen); }; var update_history = function(history) { // console.log('update history >> ', history, history.length ); if (history) { window.hh = utils.dict(history.map(function(h) { return [h.peek('what').id, h.peek('what').peek('thumbnail')]; })); } utils.safeApply($scope, function() { $scope.data = history.concat(); }); }; get_watcher().on('updated-history', function(history) { update_history(history); }, guid); update_history(get_watcher()._get_history()); window.onunload=function() { get_watcher().off(undefined, undefined, guid); }; }).controller('options', function($scope, client, utils) { // options screen only ------------------------------------------- var watcher = get_watcher(), guid = utils.guid(), old_store = get_store(); var sa = function(f) { utils.safeApply($scope, f); }; var logged_dudes = []; $scope.durations = []; window.$s = $scope; var load_stats = function(store) { console.log('getting boxlist -- ', store); store.getBoxList().then(function(boxes) { console.log('getting boxes >> ', boxes); sa(function() { $scope.boxes = boxes; }); }).fail(function(bail) { console.log('fail getting boxes ' ); sa(function() { delete $scope.boxes; }); }); store.checkLogin().then(function(x) { sa(function() { $scope.user = x; }); }); if (watcher.get_box()) { var b = watcher.get_box(); var date = function(vd) { return new Date(vd['@value']); }; b.query({activity:'browse'}, ['tstart', 'tend', 'what']).then(function(x) { console.log('browse result >>', x); $scope.durations = _(x.data).map(function(activity,id) { if (!activity.tend || !activity.tstart) { return 0; } var tstart = date(activity.tstart[0]).valueOf(); return [tstart, date(activity.tend[0]).valueOf() - tstart]; }); $scope.durations.sort(function(a,b){ return b[0] - a[0]; }); console.log('durations >> ', $scope.durations); sa(function() { $scope.base_browse_count = _(x.data).size(); $scope.browse_count = $scope.base_browse_count + logged_dudes.length; }); }); b.off(undefined,undefined,guid); b.on('obj-add', function(obj) { sa(function() { $scope.memuse = b.getCacheSize(); }, guid); }); b.on('new-token', function() { sa(function() { $scope.token = b._getCachedToken() || b._getStoredToken(); }); }); } sa(function() { $scope.token = b._getCachedToken() || b._getStoredToken(); $scope.memuse = b.getCacheSize(); }); }, update_history = function() { sa(function() { $scope.history = watcher._get_history().concat(); $scope.thumbs = _(chrome.extension.getBackgroundPage().tt).clone(); }); }; // clean up window.onunload=function() { get_watcher().off(undefined, undefined, guid); var b = get_watcher().get_box(); if (b) { b.off(undefined, undefined, guid); } }; $scope.server_url = localStorage.indx_url; $scope.set_server = function(url) { console.log('setting server ... ', url); if (watcher.get_box()) { watcher.get_box().off(undefined, undefined, guid); } sa(function() { delete $scope.browse_count; logged_dudes = []; }); localStorage.indx_url = $scope.server_url; var store = make_store(client,utils); get_watcher().set_store(store); load_stats(store); }; $scope.box_selection = localStorage.indx_box; $scope.$watch('box_selection', function() { var boxid = $scope.box_selection; if (boxid && boxid !== localStorage.indx_box) { console.log('setting box ', boxid); localStorage.indx_box = boxid; get_watcher()._load_box(); } }); watcher.on('change:box', function(b) { console.info('change box ... ', b.id); load_stats(make_store(client,utils)); },guid); watcher.on('updated-history', update_history); watcher.on('new-record', function(record) { sa(function() { if (logged_dudes.indexOf(record) < 0) { logged_dudes.push(record); } $scope.browse_count = $scope.base_browse_count + logged_dudes.length; }); }); update_history(); load_stats(make_store(client,utils)); window.watcher = get_watcher(); window.$s = $scope; }).controller('background', function($scope, watcher, geowatcher, client, utils, entities) { // main --------------> // background page window.utils = utils; var winstance = watcher.init(), n_logged = 0, geoinstance = GEO_ENABLE && geowatcher.init(); var store = make_store(client,utils); // var displayFail = function(reason) { setErrorBadge('x' , reason); winstance.setError(reason); }; winstance.on('new-entries', function(entries) { n_logged += entries.length; setOKBadge(''+n_logged); }); winstance.on('connection-error', function() { setErrorBadge('Error'); }); winstance.on('connection-ok', function() { setOKBadge(':)'); }); window.watcher_instance = winstance; winstance.set_store(store); window.store = store; }); }());
plugins/chrome-webjournal/js/background.js
/* jshint undef: true, strict:false, trailing:false, unused:false */ /* global Backbone, angular, jQuery, _, chrome, console */ (function() { var server; var DEFAULT_URL = 'https://indx.local:8211'; var GEO_ENABLE = false; localStorage.indx_url = localStorage.indx_url || DEFAULT_URL; var setErrorBadge = function(errtext) { chrome.browserAction.setBadgeText({text:'x'}); // chrome.browserAction.setBadgeText({text:''+errtext}); chrome.browserAction.setBadgeBackgroundColor({color:'#ff0000'}); }; var clearBadge = function() { chrome.browserAction.setBadgeText({text:''}); }; var setOKBadge = function(s) { chrome.browserAction.setBadgeText({text:s.toString()}); chrome.browserAction.setBadgeBackgroundColor({color:'#00ffff'}); }; var duration_secs = function(d) { return (d.peek('tend') && d.peek('tend').valueOf() - d.peek('tstart') && d.peek('tstart').valueOf()) / 1000.0; }; var getBoxName = function() { return localStorage.indx_box || 'lifelog'; }; var get_watcher = function() { return chrome.extension.getBackgroundPage().watcher_instance; }; var get_store = function() { var w = get_watcher(); if (w) { return w.get('store'); } }; var make_store = function(client,utils) { var server_url = localStorage.indx_url; if (server === undefined) { server = new client.Store({server_host:server_url}); } if (server.get('server_host') !== server_url) { server.set('server_host', server_url); } return server; }; // declare modules -----------------| var app = angular.module('webjournal', ['indx']) .config(function($compileProvider){ $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|data|mailto|file|chrome-extension|chrome|chrome\-extension):/); }).config(function($sceProvider) { // Completely disable SCE - options iframe interference $sceProvider.enabled(false); }).factory('pluginUtils', function() { return { setErrorBadge:setErrorBadge, setOKBadge:setOKBadge, getBoxName:getBoxName, duration_secs:duration_secs, clearBadge:clearBadge }; }).controller('popup', function($scope, watcher, utils) { window.$s = $scope; var records = []; var guid = utils.guid(); // scope methods for rendering things nicely. $scope.date = function(d) { return new Date().toLocaleTimeString().slice(0,-3); }; $scope.duration = function(d) { var secs = duration_secs(d); if (secs < 60) { return secs.toFixed(2) + 's'; } return (secs/60.0).toFixed(2) + 'm'; }; var thumbs = []; $scope.thumb = function(d) { var what = d && d.peek('what'); return what.peek('thumbnail'); }; $scope.label = function(d) { var maxlen = 150; var what = d && d.peek('what'); if (!what) { return ''; } if (what.peek('title') && what.peek('title').length && what.peek('title').trim().length > 0) { return what.peek('title').slice(0,maxlen); } var url = what.id; if (!url) { return ''; } var noprot = url.slice(url.indexOf('//')+2); if (noprot.indexOf('www.') === 0) { noprot = noprot.slice(4); } return noprot.slice(0,maxlen); }; var update_history = function(history) { // console.log('update history >> ', history, history.length ); if (history) { window.hh = utils.dict(history.map(function(h) { return [h.peek('what').id, h.peek('what').peek('thumbnail')]; })); } utils.safeApply($scope, function() { $scope.data = history.concat(); }); }; get_watcher().on('updated-history', function(history) { update_history(history); }, guid); update_history(get_watcher()._get_history()); window.onunload=function() { get_watcher().off(undefined, undefined, guid); }; }).controller('options', function($scope, client, utils) { // options screen only ------------------------------------------- var watcher = get_watcher(), guid = utils.guid(), old_store = get_store(); var sa = function(f) { utils.safeApply($scope, f); }; var logged_dudes = []; window.$s = $scope; var load_stats = function(store) { console.log('getting boxlist -- ', store); store.getBoxList().then(function(boxes) { console.log('getting boxes >> ', boxes); sa(function() { $scope.boxes = boxes; }); }).fail(function(bail) { console.log('fail getting boxes ' ); sa(function() { delete $scope.boxes; }); }); store.checkLogin().then(function(x) { sa(function() { $scope.user = x; }); }); if (watcher.get_box()) { var b = watcher.get_box(); b.countQuery({activity:'browse'}).then(function(x) { console.log('got a countquery response ', x); sa(function() { $scope.base_browse_count = x; $scope.browse_count = $scope.base_browse_count + logged_dudes.length; }); }); b.off(undefined,undefined,guid); b.on('obj-add', function(obj) { sa(function() { $scope.token = b._getCachedToken() || b._getStoredToken(); $scope.memuse = b.getCacheSize(); }); }); } }, update_history = function() { sa(function() { $scope.history = watcher._get_history().concat(); $scope.thumbs = _(chrome.extension.getBackgroundPage().tt).clone(); }); }; // clean up window.onunload=function() { get_watcher().off(undefined, undefined, guid); }; $scope.server_url = localStorage.indx_url; $scope.set_server = function(url) { console.log('setting server ... ', url); if (watcher.get_box()) { watcher.get_box().off(undefined, undefined, guid); } sa(function() { delete $scope.browse_count; logged_dudes = []; }); localStorage.indx_url = $scope.server_url; var store = make_store(client,utils); get_watcher().set_store(store); load_stats(store); }; $scope.box_selection = localStorage.indx_box; $scope.$watch('box_selection', function() { var boxid = $scope.box_selection; if (boxid && boxid !== localStorage.indx_box) { console.log('setting box ', boxid); localStorage.indx_box = boxid; get_watcher()._load_box(); } }); watcher.on('change:box', function(b) { console.info('change box ... ', b.id); load_stats(make_store(client,utils)); },guid); watcher.on('updated-history', update_history); watcher.on('new-record', function(record) { sa(function() { if (logged_dudes.indexOf(record) < 0) { logged_dudes.push(record); } $scope.browse_count = $scope.base_browse_count + logged_dudes.length; }); }); update_history(); load_stats(make_store(client,utils)); window.watcher = get_watcher(); $s = $scope; }).controller('background', function($scope, watcher, geowatcher, client, utils, entities) { // main --------------> // background page window.utils = utils; var winstance = watcher.init(), n_logged = 0, geoinstance = GEO_ENABLE && geowatcher.init(); var store = make_store(client,utils); // var displayFail = function(reason) { setErrorBadge('x' , reason); winstance.setError(reason); }; winstance.on('new-entries', function(entries) { n_logged += entries.length; setOKBadge(''+n_logged); }); winstance.on('connection-error', function() { setErrorBadge('Error'); }); winstance.on('connection-ok', function() { setOKBadge(':)'); }); window.watcher_instance = winstance; winstance.set_store(store); window.store = store; }); }());
watcher yo
plugins/chrome-webjournal/js/background.js
watcher yo
<ide><path>lugins/chrome-webjournal/js/background.js <ide> var watcher = get_watcher(), guid = utils.guid(), old_store = get_store(); <ide> var sa = function(f) { utils.safeApply($scope, f); }; <ide> var logged_dudes = []; <add> $scope.durations = []; <ide> window.$s = $scope; <ide> var load_stats = function(store) { <ide> console.log('getting boxlist -- ', store); <ide> console.log('fail getting boxes ' ); <ide> sa(function() { delete $scope.boxes; }); <ide> }); <del> store.checkLogin().then(function(x) { <del> sa(function() { $scope.user = x; }); <del> }); <add> store.checkLogin().then(function(x) { sa(function() { $scope.user = x; }); }); <ide> if (watcher.get_box()) { <ide> var b = watcher.get_box(); <del> b.countQuery({activity:'browse'}).then(function(x) { <del> console.log('got a countquery response ', x); <add> var date = function(vd) { return new Date(vd['@value']); }; <add> b.query({activity:'browse'}, ['tstart', 'tend', 'what']).then(function(x) { <add> console.log('browse result >>', x); <add> $scope.durations = _(x.data).map(function(activity,id) { <add> if (!activity.tend || !activity.tstart) { return 0; } <add> var tstart = date(activity.tstart[0]).valueOf(); <add> return [tstart, date(activity.tend[0]).valueOf() - tstart]; <add> }); <add> $scope.durations.sort(function(a,b){ return b[0] - a[0]; }); <add> console.log('durations >> ', $scope.durations); <ide> sa(function() { <del> $scope.base_browse_count = x; <add> $scope.base_browse_count = _(x.data).size(); <ide> $scope.browse_count = $scope.base_browse_count + logged_dudes.length; <ide> }); <ide> }); <ide> b.off(undefined,undefined,guid); <del> b.on('obj-add', function(obj) { <del> sa(function() { <del> $scope.token = b._getCachedToken() || b._getStoredToken(); <del> $scope.memuse = b.getCacheSize(); <del> }); <del> }); <add> b.on('obj-add', function(obj) { sa(function() { $scope.memuse = b.getCacheSize(); }, guid); }); <add> b.on('new-token', function() { sa(function() { $scope.token = b._getCachedToken() || b._getStoredToken(); }); }); <ide> } <del> <add> sa(function() { <add> $scope.token = b._getCachedToken() || b._getStoredToken(); <add> $scope.memuse = b.getCacheSize(); <add> }); <ide> }, update_history = function() { <ide> sa(function() { <ide> $scope.history = watcher._get_history().concat(); <ide> }); <ide> }; <ide> // clean up <del> window.onunload=function() { get_watcher().off(undefined, undefined, guid); }; <add> window.onunload=function() { <add> get_watcher().off(undefined, undefined, guid); <add> var b = get_watcher().get_box(); <add> if (b) { b.off(undefined, undefined, guid); } <add> }; <ide> $scope.server_url = localStorage.indx_url; <ide> $scope.set_server = function(url) { <ide> console.log('setting server ... ', url); <ide> update_history(); <ide> load_stats(make_store(client,utils)); <ide> window.watcher = get_watcher(); <del> $s = $scope; <add> window.$s = $scope; <ide> }).controller('background', function($scope, watcher, geowatcher, client, utils, entities) { <ide> // main --------------> <ide> // background page
JavaScript
mit
c3ed74ddd25f5b43577b33d2955bdb199d5435f7
0
misterfifths/jutil,misterfifths/jutil
#!/usr/bin/env node ;(function() { "use strict"; var defaultConfig = { // All files with a .js extension in these directories will be loaded // before evaulating the input. moduleDirectories: ['~/.jutil/modules'], // Controls spacing in pretty-printed output (when using the default // prettyPrinter function). Can be a character (like '\t') or an // integer, in which case it represents a number of spaces to use. prettyPrintIndent: 4, // The function used to serialize an object into a human-readable // JSON string. The function takes two arguments: // config: the current application configuration, as specified in // the configuration file // obj: the object to format // Return the formatted JSON string. prettyPrinter: function(config, obj) { return JSON.stringify(obj, null, config.prettyPrintIndent) + '\n'; }, // The function used to deserialize a JSON string into an object. // The function takes two arguments: // config: the current application configuration, as specified in // the configuration file // json: the JSON string to parse. // Return the deserialized object, or throw an exception if the // given string is not valid JSON. jsonParser: function(config, json) { return JSON.parse(json); }, // Always pretty-print the output. Not recommend (as it's a waste of // cycles) if you do a lot of piping of output. alwaysPrettyPrint: false, // By default, if stdout is a terminal, the output will be pretty-printed // and, if it is larger than your window, piped into your pager (the PAGER // environment variable or 'less', by default). Setting this to true // disables that behavior. disableSmartOutput: false, // Always sort keys in the output. Useful for automated testing or // doing diffs against the results. alwaysSort: false, // For commands that take a script to execute, don't wrap that script // inside "with(this) { ... }", which is the default behavior. The clause // makes for less typing (you can reference properties of the input data // without "this." before them), but can cause issues if the data has a // property with a name that hides some useful variable or function. disableWithClause: false, // Always attempt to extract a useful property of the incoming JSON. // This passes the incoming data through the autoUnwrapper function // before running the script against it. alwaysAutoUnwrap: false, // A list of property names to be extracted when using the default // autoUnwrapper function. autoUnwrapProperties: [], // The function used to attempt to extract a useful property of the // incoming JSON. The function takes 2 arguments: // config: the current application configuration, as specified in // the configuration file // obj: the object parsed from the incoming JSON // It should return a "useful" property from obj (or obj itself if // appropriate). "Useful" can mean many things, but really this is // intended to handle JSON APIs that returned arrays wrapped in // objects, to work around the issue discussed here: http://bit.ly/m3el. // The default function does the following: // If obj is an object that only has one property, and the value of // that property is an object or an array, return that value. // Otherwise if obj has a property named the same as one in the // autoUnwrapProperties array, the value of the first matching // property is returned. autoUnwrapper: function(config, obj) { if(typeof obj != 'object' || Array.isArray(obj)) return obj; var propName, onlyPropName, foundOne = false, val, i; for(propName in obj) { if(obj.hasOwnProperty(propName)) { foundOne = true; if(onlyPropName) { onlyPropName = undefined; break; } onlyPropName = propName; } } if(!foundOne) { // This object has no properties; nothing we can do return obj; } if(onlyPropName) { val = obj[onlyPropName]; if(typeof val == 'object' && val !== null) return val; } // More than one property. Cross-reference with autoUnwrapProperties for(i = 0; i < config.autoUnwrapProperties.length; i++) { propName = config.autoUnwrapProperties[i]; if(obj.hasOwnProperty(propName)) return obj[propName]; } // No luck; pass through original object return obj; } }; // For now (?) we do nothing if imported elsewhere via require if(require.main == module) { parseCommandLine({ script: { help: 'Run a script against the loaded data. Its return value will be printed as JSON.', options: { script: { position: 1, help: 'Script to run against the loaded JSON; may also be loaded from a file via the -i option.' }, scriptPath: { abbr: 'i', full: 'script', metavar: 'FILE', help: 'Load the script to run from the given file instead of the first positional argument.', type: 'string' } }, outputsJSON: true, needsSandbox: true, hasWithClauseOpt: true, handler: scriptCommandHandler }, where: { help: 'Iterate over the input, returning only objects that match the given predicate.', options: { predicate: { position: 1, required: true, help: 'Predicate to evaluate for each object in the loaded JSON. (Required)' } }, outputsJSON: true, needsSandbox: true, hasWithClauseOpt: true, handler: whereCommandHandler }, first: { help: 'Iterate over the input, returning the first object that matches the given predicate.', options: { predicate: { position: 1, help: 'Predicate to evaluate for each object in the loaded JSON. If omitted, the first object from the input will be returned.' } }, outputsJSON: true, needsSandbox: true, hasWithClauseOpt: true, handler: firstCommandHandler }, count: { help: 'Iterate over the input, counting the objects that match the given predicate.', options: { predicate: { position: 1, help: 'Predicate to evaluate for each object in the loaded JSON. If omitted, all objects will be counted.' } }, outputsJSON: false, needsSandbox: true, hasWithClauseOpt: true, handler: countCommandHandler }, select: { help: 'Iterate over the input, accumulating the result of the given expression for each object.', options: { shaper: { position: 1, required: true, help: 'Expression to evaluate for each object in the loaded JSON. (Required)' } }, outputsJSON: true, needsSandbox: true, hasWithClauseOpt: true, handler: selectCommandHandler }, props: { help: 'Iterate over the input, returning only the given properties of each object.', options: { propMappings: { position: 1, list: true, required: true, help: 'Names of properties to extract from each object in the loaded JSON. These are of the form [[key.]*key=][key.]*key, to follow subobjects and optionally rename them in the output. (At least one is required)' } }, outputsJSON: true, needsSandbox: false, hasWithClauseOpt: false, handler: propsCommandHandler }, format: { help: 'Iterate over the input, printing the result of the given format string for each object.', options: { format: { position: 1, required: true, help: 'The format string to use. Tokens are of the form %property or %{expression}. (Required)' }, header: { abbr: 'H', metavar: 'FORMAT', help: 'A header to print before the main output; same token syntax as the format string and is evaluated against the data as a whole.', type: 'string' }, footer: { abbr: 'F', metavar: 'FORMAT', help: 'A footer to print after the main output; same token syntax as the format string and is evaluated against the data as a whole.', type: 'string' } }, outputsJSON: false, needsSandbox: true, hasWithClauseOpt: true, handler: formatCommandHandler } }); } // Basic script command function scriptCommandHandler(runtimeSettings, config, opts) { var fs = require('fs'), vm = require('vm'), scriptPath, rawScript, script; if(opts.script && opts.scriptPath) { console.error('Error: You cannot specify both a script file (-i/--script) and an inline script.'); process.exit(1); } if(opts.script) rawScript = opts.script; else if(opts.scriptPath) { try { scriptPath = resolvePath(opts.scriptPath); rawScript = fs.readFileSync(scriptPath, 'utf8'); } catch(exc) { console.error('Error: Unable to load script file "' + scriptPath + '": ' + exc); process.exit(1); } } if(rawScript) { script = '(function() { '; if(runtimeSettings.withClause) script += 'with(this) { '; script += rawScript + ';'; if(runtimeSettings.withClause) script += ' }'; script += ' }).apply($data);'; try { return vm.runInContext(script, runtimeSettings.sandbox, runtimeSettings.scriptPath); } catch(exc) { console.error('Error running script: ' + exc); process.exit(1); } } // No script to run; just pass through the input return runtimeSettings.data; } /// Predicate-based commands (where, first, count) function whereCommandHandler(runtimeSettings, config, opts) { var res = []; runPredicate(runtimeSettings, opts, function(match) { res.push(match); return true; }); return res; } function firstCommandHandler(runtimeSettings, config, opts) { var res; if(!opts.predicate) opts.predicate = 'true'; runPredicate(runtimeSettings, opts, function(match) { res = match; return false; }); return res; } function countCommandHandler(runtimeSettings, config, opts) { var res = 0; if(!opts.predicate) opts.predicate = 'true'; runPredicate(runtimeSettings, opts, function(match) { res++; return true; }); process.stdout.write(res.toString() + '\n'); } function mapOverInput(expr, runtimeSettings, handleOne) { function applyToValue(valueStr) { // TODO: if the array contains undefined or null, this gets funky. // Function.apply() with one of those turns 'this' into the global // object, which is not what was intended, certainly. var script = '(function() { '; if(runtimeSettings.withClause) script += 'with(this) { '; script += 'return (' + expr + ');'; if(runtimeSettings.withClause) script += ' }'; script += ' }).apply(' + valueStr + ');'; return vm.runInContext(script, runtimeSettings.sandbox); } var vm = require('vm'), data = runtimeSettings.data, i; // TODO: there's probably a better way to do this, all inside the sandbox, // rather than a bunch of calls into it. But eh, will it make that much // of a difference, speed-wise? if(Array.isArray(data)) { for(i = 0; i < data.length; i++) { if(!handleOne(data[i], applyToValue('$data[' + i + ']'))) return; } } else handleOne(data, applyToValue('$data')); } function runPredicate(runtimeSettings, opts, handleMatch) { var expr = '!!(' + opts.predicate + ')'; mapOverInput(expr, runtimeSettings, function(raw, matched) { if(matched) return handleMatch(raw); return true; }); } //// Shaping commands (select, props, format) function selectCommandHandler(runtimeSettings, config, opts) { // TODO: maybe an option to omit falsy results var res = []; mapOverInput(opts.shaper, runtimeSettings, function(raw, shaped) { res.push(shaped); return true; }); return res; } function propsCommandHandler(runtimeSettings, config, opts) { function getKeyPath(obj, path) { var dotIdx, pathComponent, arrayMap; // We're done; obj is the value we want if(path === undefined) return { value: obj }; // Can't go any further; we didn't succeed if(obj === null || obj === undefined) return undefined; // Traverse arrays by mapping the key path getter over every element if(Array.isArray(obj)) { arrayMap = obj.map(function(o) { var res = getKeyPath(o, path); if(res) return res.value; return {}; }); return { value: arrayMap }; } dotIdx = path.indexOf('.'); if(dotIdx == -1) { pathComponent = path; path = undefined; } else { pathComponent = path.substring(0, dotIdx); path = path.substring(dotIdx + 1); } if(!obj.hasOwnProperty(pathComponent)) return undefined; return getKeyPath(obj[pathComponent], path); } function setKeyPath(obj, path, value) { var i = 0, pathComponent; path = path.split('.'); while(i < path.length - 1) { pathComponent = path[i]; if(!obj.hasOwnProperty(pathComponent)) obj[pathComponent] = {}; obj = obj[pathComponent]; i++; } obj[path[i]] = value; } function shapeObj(obj) { var i, mapping, res = {}, val; for(i = 0; i < propMappings.length; i++) { mapping = propMappings[i]; val = getKeyPath(obj, mapping.from); if(val) setKeyPath(res, mapping.to, val.value); } return res; } var res = [], data = runtimeSettings.data, propMappings = [], i, s, from, to; for(i = 0; i < opts.propMappings.length; i++) { s = opts.propMappings[i].split('='); if(s.length == 1 && s[0].length > 0) from = to = s[0]; else if(s.length == 2 && s[0].length > 0 && s[1].length > 0) { to = s[0]; from = s[1]; } else { console.error('Invalid property mapping: ' + opts.propMappings[i]); process.exit(1); } propMappings.push({ from: from, to: to }); } if(Array.isArray(data)) return data.map(shapeObj); return shapeObj(data); } function formatCommandHandler(runtimeSettings, config, opts) { function replacerFactory(data, dataString) { return function(match, unbracketed, bracketed) { // Short-circuit this case; this can only be a property name // of the object if(unbracketed) return data[unbracketed]; // Otherwise, evaluate the expression // TODO: slight modifications on this are used in a few places; // would be good to make this a function. var script = '(function() { '; if(runtimeSettings.withClause) script += 'with(this) { '; script += 'return (' + bracketed + ').toString();'; if(runtimeSettings.withClause) script += ' }'; script += ' }).apply(' + dataString + ');'; return vm.runInContext(script, runtimeSettings.sandbox); }; } /* bracketed: /%\{(?=[^}]*\})([^}]*)\}/ unbracketed: /%([\w$]+)/ */ var vm = require('vm'), format = opts.format, re = /%([\w%]+)|%\{(?=[^}]*\})([^}]*)\}/g, data = runtimeSettings.data, i, replacer; if(!Array.isArray(data)) data = [data]; // TODO: might be nice to provide autopaging here, like for the commands // that output JSON. if(opts.header) { replacer = replacerFactory(data, '$data'); if(opts.header) process.stdout.write(opts.header.replace(re, replacer) + '\n'); } for(i = 0; i < data.length; i++) { replacer = replacerFactory(data[i], '$data[' + i + ']'); // TODO: $data[0] is invalid if data was a single object! process.stdout.write(format.replace(re, replacer) + '\n'); } if(opts.footer) { replacer = replacerFactory(data, '$data'); if(opts.footer) process.stdout.write(opts.footer.replace(re, replacer) + '\n'); } } //// Guts function runCommand(commandDesc, opts) { var config = loadConfig(defaultConfig, opts.configPath), runtimeSettings = makeRuntimeSettings(commandDesc, config, opts), res = commandDesc.handler(runtimeSettings, config, opts); if(commandDesc.outputsJSON) outputJSON(res, runtimeSettings, config); } // Merges config and command line options down into a friendly object, which // includes searching module directories for .js files and loading them into // a sandbox, as well as loading and parsing the input file (or stdin). function makeRuntimeSettings(commandDesc, config, opts) { var fs = require('fs'), vm = require('vm'), isatty = require('tty').isatty(process.stdout.fd), settings = {}, dirs; if(commandDesc.outputsJSON) { if(opts.disableSmartOutput) settings.smartOutput = false; else settings.smartOutput = opts.disableSmartOutput === false || !config.disableSmartOutput; if(opts.prettyPrint === false) {} // --no-pretty-print else if(opts.prettyPrint || config.alwaysPrettyPrint || (settings.smartOutput && isatty)) settings.prettyPrinter = config.prettyPrinter; if(opts.sort === false) {} // --no-sort else if(opts.sort || config.alwaysSort) settings.sort = true; } if(commandDesc.hasWithClauseOpt) { if(opts.disableWithClause) settings.withClause = false; else settings.withClause = opts.disableWithClause === false || !config.disableWithClause; } if(opts.autoUnwrap === false) { } // --no-auto-unwrap else if(opts.autoUnwrap || config.alwaysAutoUnwrap) settings.unwrapper = config.autoUnwrapper; if(opts.unwrapProperty) settings.unwrapper = function(config, obj) { return obj[opts.unwrapProperty]; }; settings.verbose = opts.verbose; if(opts.file) settings.file = opts.file; else settings.file = '/dev/stdin'; try { settings.json = fs.readFileSync(settings.file, 'utf8'); } catch(exc) { console.error('Error: Unable to load JSON file "' + settings.file + '": ' + exc); process.exit(1); } settings.jsonParser = config.jsonParser; try { settings.data = settings.jsonParser(config, settings.json); } catch(exc) { console.error('Error parsing JSON: ' + exc + '.\nInput:\n' + settings.json); process.exit(1); } if(settings.unwrapper) settings.data = settings.unwrapper(config, settings.data); // Find modules and load them into a sandbox if the command needs it, // and throw the data in there too as $data if(commandDesc.needsSandbox) { if(opts.moduleDirectories && opts.moduleDirectories[0] === false) // nomnom turns --no-<list option> into [false] settings.modulePaths = []; else if(opts.moduleDirectories) { dirs = opts.moduleDirectories; dirs.push.apply(dirs, config.moduleDirectories); settings.modulePaths = findModules(dirs); } else settings.modulePaths = findModules(config.moduleDirectories); if(opts.modulePaths && opts.modulePaths[0] !== false) settings.modulePaths.push.apply(settings.modulePaths, opts.modulePaths); settings.sandbox = vm.createContext({ $config: config, $data: settings.data, console: console, out: console.log, process: process, require: require }); loadModules(settings.modulePaths, settings.sandbox); } return settings; } function loadModules(modulePaths, sandbox) { var fs = require('fs'), vm = require('vm'), i, modulePath, moduleContents; for(i = 0; i < modulePaths.length; i++) { modulePath = modulePaths[i]; try { moduleContents = fs.readFileSync(modulePath, 'utf8'); vm.runInContext(moduleContents, sandbox, modulePath); } catch(exc) { console.warn('Warning: error loading module "' + modulePath + '": ' + exc); } } } function outputJSON(obj, runtimeSettings, config) { var buffer, lineCount, pagerCmd, pager; if(obj === undefined) return; if(runtimeSettings.sort) obj = sortObject(obj); try { if(runtimeSettings.prettyPrinter) obj = runtimeSettings.prettyPrinter(config, obj); else obj = JSON.stringify(obj); } catch(exc) { console.error('Error converting result to JSON: ' + exc); process.exit(1); } if(typeof obj != 'string') { // JSON.stringify will return undefined if the top-level object is // a function or an XML object, neither of which should ever happen, // so we're just ignoring this for now. return; } if(runtimeSettings.smartOutput && require('tty').isatty(process.stdout.fd)) { lineCount = obj.length - obj.replace(new RegExp('\n', 'g'), '').length; if(lineCount > process.stdout.getWindowSize()[1]) { // Autopage pagerCmd = process.env.PAGER || 'less'; pager = require('child_process') .spawn(pagerCmd, [], { customFds: [-1, process.stdout.fd, -1] }); pager.stderr.setEncoding('utf8'); pager.stderr.on('data', function(data) { console.error('Error running pager command ("' + pagerCmd + '"): ' + data); process.exit(1); }); pager.stdin.end(obj); pager.stdin.on('error', function(exc) { // Silence EPIPE; just means that they closed the pager before // we finished writing (or the pager never started, in which // case the stderr output will be sufficient). if(exc.code != 'EPIPE') throw exc; }); return; } } // process.stdout.write seems like the obvious choice here, but // it causes an exception if we pipe a big result to something // and close the whole shebang before it can finish writing. // Should probably file a node bug... buffer = new Buffer(obj); require('fs').write(process.stdout.fd, buffer, 0, buffer.length); } //// Command line parsing function parseCommandLine(commands) { var args = process.argv.slice(2), // remove 'node' and script name defaultCommand = 'script', scriptName = require('path').basename(process.argv[1], '.js'), firstArg = args[0], parser = require('nomnom'), globalOpts, jsonOutputOpts, sandboxOpts, withClauseOpt, commandName, commandDesc, commandObj; globalOpts = { unwrapProperty: { abbr: 'u', metavar: 'KEY', full: 'unwrap-prop', type: 'string', help: 'Operate only against the given property of the loaded JSON.' }, autoUnwrap: { abbr: 'a', full: 'auto-unwrap', flag: true, help: 'Attempt to intelligently extract a useful property of the loaded JSON to run against.' }, file: { abbr: 'f', metavar: 'FILE', help: 'Load JSON from the given file instead of reading from stdin.', type: 'string' }, configPath: { abbr: 'c', full: 'config', metavar: 'FILE', help: 'Load the given config file. The default is ~/.jutil/config; specify --no-config to use the default configuration.', type: 'string', 'default': '~/.jutil/config' }, verbose: { abbr: 'v', flag: true, help: 'Be verbose about things (e.g. module loading).' } }; jsonOutputOpts = { prettyPrint: { abbr: 'p', full: 'pretty-print', flag: true, help: 'Pretty-print the output.' }, sort: { abbr: 's', full: 'sort-keys', flag: true, help: 'Sort keys in the output.' }, disableSmartOutput: { abbr: 'S', full: 'disable-smart', flag: true, help: 'Don\'t pretty-print or autopage if stdout is a terminal.' } }; sandboxOpts = { moduleDirectories: { abbr: 'M', full: 'module-dir', metavar: 'DIR', list: true, type: 'string', help: 'Add the given directory as a module path. Any .js files in the directory will be loaded before executing. Specify --no-module-dir to disable module directory loading.' }, modulePaths: { abbr: 'm', full: 'module', metavar: 'FILE', list: true, type: 'string', help: 'Load the given JavaScript file before executing.' } }; withClauseOpt = { abbr: 'W', full: 'disable-with', flag: true, help: 'Don\'t wrap the script to execute in a "with" clause.' }; // If we weren't invoked as 'jutil', we were called 'j<command name>', // which we massage into the first argument. if(scriptName != 'jutil') args.unshift(scriptName.substr(1)); else if(!firstArg || (firstArg != '-h' && firstArg != '--help' && !commands.hasOwnProperty(firstArg))) { // Otherwise, add in the default command 'script', if appropriate: // --help/-h -> no default // no first arg -> default // first arg is not a command name -> default args.unshift(defaultCommand); } parser.script('jutil'); parser .nocommand() .help('Run jutil <command> --help to see command-specific options.\nIf no command is specified, the default is "' + defaultCommand + '".'); for(commandName in commands) { if(commands.hasOwnProperty(commandName)) { commandDesc = commands[commandName]; commandObj = parser.command(commandName); commandObj.help(commandDesc.help); // nomnom seems to freak out if we call options() more than once // on a command object, wo we're gathering all the options in one // place to just make one call. shallowCopy(globalOpts, commandDesc.options); if(commandDesc.outputsJSON) shallowCopy(jsonOutputOpts, commandDesc.options); if(commandDesc.needsSandbox) shallowCopy(sandboxOpts, commandDesc.options); if(commandDesc.hasWithClauseOpt) commandDesc.options.disableWithClause = withClauseOpt; commandObj.options(commandDesc.options); // Go go gadget JS scoping rules!!! (function(commandDesc) { commandObj.callback(function(opts) { runCommand(commandDesc, opts); }); })(commandDesc); } } return parser.parse(args); } //// Configuration file handling function loadConfig(defaultConfig, configPath) { var fs = require('fs'), vm = require('vm'), config = {}, realConfigPath, configFile, configSandbox, propName, defaultConfigProperties, userConfig; shallowCopy(defaultConfig, config); if(!configPath) return config; try { realConfigPath = resolvePath(configPath); configFile = fs.readFileSync(realConfigPath, 'utf8'); configSandbox = vm.createContext({ console: console, out: console.log, process: process, require: require }); vm.runInContext(configFile, configSandbox, realConfigPath); userConfig = configSandbox.config; } catch(exc) { // It's fine if we didn't find a config file; we'll use the defaults if(exc.code == 'ENOENT') return config; else { console.error('Error loading configuration file: ' + exc); process.exit(1); } } if(userConfig) { // Validate config file and merge it with the defaults. copyStringArraySetting(userConfig, config, 'moduleDirectories'); copyFunctionSetting(userConfig, config, 'prettyPrinter', 2); copyFunctionSetting(userConfig, config, 'jsonParser', 3); copyBooleanSetting(userConfig, config, 'alwaysSort'); copyBooleanSetting(userConfig, config, 'alwaysPrettyPrint'); copyBooleanSetting(userConfig, config, 'alwaysAutoUnwrap'); copyStringArraySetting(userConfig, config, 'autoUnwrapProperties'); copyFunctionSetting(userConfig, config, 'autoUnwrapper', 2); copyBooleanSetting(userConfig, config, 'disableWithClause'); copyBooleanSetting(userConfig, config, 'disableSmartOutput'); if(userConfig.hasOwnProperty('prettyPrintIndent')) { switch(typeof userConfig.prettyPrintIndent) { case 'string': case 'number': config.prettyPrintIndent = userConfig.prettyPrintIndent; break; default: console.warn('Warning: prettyPrintIndent property in config file must be a number or string; ignoring the setting'); } } // Copy over any other properties from the config file for(propName in userConfig) { if(userConfig.hasOwnProperty(propName) && !defaultConfig.hasOwnProperty(propName)) { config[propName] = userConfig[propName]; } } } else console.warn('Warning: config file must assign to the global "config" var; ignoring the file'); return config; } function copyStringArraySetting(userConfig, config, name) { var val, i; if(userConfig.hasOwnProperty(name)) { val = userConfig[name]; if(Array.isArray(val)) { for(i = 0; i < val.length; i++) { if(typeof val[i] != 'string') { console.warn('Warning: ' + name + ' property in config file must contain only string elements; ignoring the setting'); return; } } config[name] = val; } else console.warn('Warning: ' + name + ' property in config file must be an array; ignoring the setting'); } } function copyFunctionSetting(userConfig, config, name, arity) { if(userConfig.hasOwnProperty(name)) { var val = userConfig[name]; if(typeof val == 'function') { if(val.length == arity) config[name] = val; else console.warn('Warning: ' + name + ' function in config file must take exactly ' + arity + ' arguments; ignoring the setting'); } else console.warn('Warning: ' + name + ' property in config file must be a function; ignoring the setting'); } } function copyBooleanSetting(userConfig, config, name) { if(userConfig.hasOwnProperty(name)) { if(typeof userConfig[name] == 'boolean') config[name] = userConfig[name]; else console.warn('Warning: ' + name + ' property in config file must be a boolean; ignoring the setting'); } } //// Helpers function resolvePath(p) { var path = require('path'); switch(p.charAt(0)) { case '~': return path.join(process.env.HOME, p.substr(1)); case '/': return p; default: return path.join(process.cwd(), p); } } function shallowCopy(source, dest) { var keys = Object.keys(source), i, key; for(i = 0; i < keys.length; i++) { key = keys[i]; dest[key] = source[key]; } } function findModules(dirs) { var fs = require('fs'), path = require('path'), paths = [], moduleDir, allFiles, i, j, file; for(i = 0; i < dirs.length; i++) { moduleDir = resolvePath(dirs[i]); allFiles = []; try { allFiles = fs.readdirSync(moduleDir); } catch(exc) { // No warning if module directory is nonexistent if(exc.code != 'ENOENT') console.warn('Warning: error reading module directory "' + moduleDir + '": ' + exc); } for(j = 0; j < allFiles.length; j++) { file = allFiles[j]; if(path.extname(file).toLowerCase() == '.js') paths.push(path.join(moduleDir, file)); } } return paths; } function sortObject(obj) { // This relies on the JavaScript interpreter placing some importance // on the order in which keys were added to an object. Luckily V8 // does that, at least for now... var sortedKeys, sortedObj, i, key; if(typeof obj != 'object' || obj === null) return obj; if(Array.isArray(obj)) return obj.map(sortObject); sortedKeys = Object.keys(obj).sort(); sortedObj = {}; for(i = 0; i < sortedKeys.length; i++) { key = sortedKeys[i]; sortedObj[key] = sortObject(obj[key]); } return sortedObj; } })();
jutil.js
#!/usr/bin/env node ;(function() { "use strict"; var defaultConfig = { // All files with a .js extension in these directories will be loaded // before evaulating the input. moduleDirectories: ['~/.jutil/modules'], // Controls spacing in pretty-printed output (when using the default // prettyPrinter function). Can be a character (like '\t') or an // integer, in which case it represents a number of spaces to use. prettyPrintIndent: 4, // The function used to serialize an object into a human-readable // JSON string. The function takes two arguments: // config: the current application configuration, as specified in // the configuration file // obj: the object to format // Return the formatted JSON string. prettyPrinter: function(config, obj) { return JSON.stringify(obj, null, config.prettyPrintIndent) + '\n'; }, // The function used to deserialize a JSON string into an object. // The function takes two arguments: // config: the current application configuration, as specified in // the configuration file // json: the JSON string to parse. // Return the deserialized object, or throw an exception if the // given string is not valid JSON. jsonParser: function(config, json) { return JSON.parse(json); }, // Always pretty-print the output. Not recommend (as it's a waste of // cycles) if you do a lot of piping of output. alwaysPrettyPrint: false, // By default, if stdout is a terminal, the output will be pretty-printed // and, if it is larger than your window, piped into your pager (the PAGER // environment variable or 'less', by default). Setting this to true // disables that behavior. disableSmartOutput: false, // Always sort keys in the output. Useful for automated testing or // doing diffs against the results. alwaysSort: false, // For commands that take a script to execute, don't wrap that script // inside "with(this) { ... }", which is the default behavior. The clause // makes for less typing (you can reference properties of the input data // without "this." before them), but can cause issues if the data has a // property with a name that hides some useful variable or function. disableWithClause: false, // Always attempt to extract a useful property of the incoming JSON. // This passes the incoming data through the autoUnwrapper function // before running the script against it. alwaysAutoUnwrap: false, // A list of property names to be extracted when using the default // autoUnwrapper function. autoUnwrapProperties: [], // The function used to attempt to extract a useful property of the // incoming JSON. The function takes 2 arguments: // config: the current application configuration, as specified in // the configuration file // obj: the object parsed from the incoming JSON // It should return a "useful" property from obj (or obj itself if // appropriate). "Useful" can mean many things, but really this is // intended to handle JSON APIs that returned arrays wrapped in // objects, to work around the issue discussed here: http://bit.ly/m3el. // The default function does the following: // If obj is an object that only has one property, and the value of // that property is an object or an array, return that value. // Otherwise if obj has a property named the same as one in the // autoUnwrapProperties array, the value of the first matching // property is returned. autoUnwrapper: function(config, obj) { if(typeof obj != 'object' || Array.isArray(obj)) return obj; var propName, onlyPropName, foundOne = false, val, i; for(propName in obj) { if(obj.hasOwnProperty(propName)) { foundOne = true; if(onlyPropName) { onlyPropName = undefined; break; } onlyPropName = propName; } } if(!foundOne) { // This object has no properties; nothing we can do return obj; } if(onlyPropName) { val = obj[onlyPropName]; if(typeof val == 'object' && val !== null) return val; } // More than one property. Cross-reference with autoUnwrapProperties for(i = 0; i < config.autoUnwrapProperties.length; i++) { propName = config.autoUnwrapProperties[i]; if(obj.hasOwnProperty(propName)) return obj[propName]; } // No luck; pass through original object return obj; } }; // For now (?) we do nothing if imported elsewhere via require if(require.main == module) { parseCommandLine({ script: { help: 'Run a script against the loaded data. Its return value will be printed as JSON.', options: { script: { position: 1, help: 'Script to run against the loaded JSON; may also be loaded from a file via the -i option.' }, scriptPath: { abbr: 'i', full: 'script', metavar: 'FILE', help: 'Load the script to run from the given file instead of the first positional argument.', type: 'string' } }, outputsJSON: true, needsSandbox: true, hasWithClauseOpt: true, handler: scriptCommandHandler }, where: { help: 'Iterate over the input, returning only objects that match the given predicate.', options: { predicate: { position: 1, required: true, help: 'Predicate to evaluate for each object in the loaded JSON. (Required)' } }, outputsJSON: true, needsSandbox: true, hasWithClauseOpt: true, handler: whereCommandHandler }, first: { help: 'Iterate over the input, returning the first object that matches the given predicate.', options: { predicate: { position: 1, help: 'Predicate to evaluate for each object in the loaded JSON. If omitted, the first object from the input will be returned.' } }, outputsJSON: true, needsSandbox: true, hasWithClauseOpt: true, handler: firstCommandHandler }, count: { help: 'Iterate over the input, counting the objects that match the given predicate.', options: { predicate: { position: 1, help: 'Predicate to evaluate for each object in the loaded JSON. If omitted, all objects will be counted.' } }, outputsJSON: false, needsSandbox: true, hasWithClauseOpt: true, handler: countCommandHandler }, select: { help: 'Iterate over the input, accumulating the result of the given expression for each object.', options: { shaper: { position: 1, required: true, help: 'Expression to evaluate for each object in the loaded JSON. (Required)' } }, outputsJSON: true, needsSandbox: true, hasWithClauseOpt: true, handler: selectCommandHandler }, props: { help: 'Iterate over the input, returning only the given properties of each object.', options: { propMappings: { position: 1, list: true, required: true, help: 'Names of properties to extract from each object in the loaded JSON. These are of the form [[key.]*key=][key.]*key, to follow subobjects and optionally rename them in the output. (At least one is required)' } }, outputsJSON: true, needsSandbox: false, hasWithClauseOpt: false, handler: propsCommandHandler }, format: { help: 'Iterate over the input, printing the result of the given format string for each object.', options: { format: { position: 1, required: true, help: 'The format string to use. Tokens are of the form %property or %{expression}. (Required)' } }, outputsJSON: false, needsSandbox: true, hasWithClauseOpt: true, handler: formatCommandHandler } }); } // Basic script command function scriptCommandHandler(runtimeSettings, config, opts) { var fs = require('fs'), vm = require('vm'), scriptPath, rawScript, script; if(opts.script && opts.scriptPath) { console.error('Error: You cannot specify both a script file (-i/--script) and an inline script.'); process.exit(1); } if(opts.script) rawScript = opts.script; else if(opts.scriptPath) { try { scriptPath = resolvePath(opts.scriptPath); rawScript = fs.readFileSync(scriptPath, 'utf8'); } catch(exc) { console.error('Error: Unable to load script file "' + scriptPath + '": ' + exc); process.exit(1); } } if(rawScript) { script = '(function() { '; if(runtimeSettings.withClause) script += 'with(this) { '; script += rawScript + ';'; if(runtimeSettings.withClause) script += ' }'; script += ' }).apply($data);'; try { return vm.runInContext(script, runtimeSettings.sandbox, runtimeSettings.scriptPath); } catch(exc) { console.error('Error running script: ' + exc); process.exit(1); } } // No script to run; just pass through the input return runtimeSettings.data; } /// Predicate-based commands (where, first, count) function whereCommandHandler(runtimeSettings, config, opts) { var res = []; runPredicate(runtimeSettings, opts, function(match) { res.push(match); return true; }); return res; } function firstCommandHandler(runtimeSettings, config, opts) { var res; if(!opts.predicate) opts.predicate = 'true'; runPredicate(runtimeSettings, opts, function(match) { res = match; return false; }); return res; } function countCommandHandler(runtimeSettings, config, opts) { var res = 0; if(!opts.predicate) opts.predicate = 'true'; runPredicate(runtimeSettings, opts, function(match) { res++; return true; }); process.stdout.write(res.toString() + '\n'); } function mapOverInput(expr, runtimeSettings, handleOne) { function applyToValue(valueStr) { // TODO: if the array contains undefined or null, this gets funky. // Function.apply() with one of those turns 'this' into the global // object, which is not what was intended, certainly. var script = '(function() { '; if(runtimeSettings.withClause) script += 'with(this) { '; script += 'return (' + expr + ');'; if(runtimeSettings.withClause) script += ' }'; script += ' }).apply(' + valueStr + ');'; return vm.runInContext(script, runtimeSettings.sandbox); } var vm = require('vm'), data = runtimeSettings.data, i; // TODO: there's probably a better way to do this, all inside the sandbox, // rather than a bunch of calls into it. But eh, will it make that much // of a difference, speed-wise? if(Array.isArray(data)) { for(i = 0; i < data.length; i++) { if(!handleOne(data[i], applyToValue('$data[' + i + ']'))) return; } } else handleOne(data, applyToValue('$data')); } function runPredicate(runtimeSettings, opts, handleMatch) { var expr = '!!(' + opts.predicate + ')'; mapOverInput(expr, runtimeSettings, function(raw, matched) { if(matched) return handleMatch(raw); return true; }); } //// Shaping commands (select, props, format) function selectCommandHandler(runtimeSettings, config, opts) { // TODO: maybe an option to omit falsy results var res = []; mapOverInput(opts.shaper, runtimeSettings, function(raw, shaped) { res.push(shaped); return true; }); return res; } function propsCommandHandler(runtimeSettings, config, opts) { function getKeyPath(obj, path) { var dotIdx, pathComponent, arrayMap; // We're done; obj is the value we want if(path === undefined) return { value: obj }; // Can't go any further; we didn't succeed if(obj === null || obj === undefined) return undefined; // Traverse arrays by mapping the key path getter over every element if(Array.isArray(obj)) { arrayMap = obj.map(function(o) { var res = getKeyPath(o, path); if(res) return res.value; return {}; }); return { value: arrayMap }; } dotIdx = path.indexOf('.'); if(dotIdx == -1) { pathComponent = path; path = undefined; } else { pathComponent = path.substring(0, dotIdx); path = path.substring(dotIdx + 1); } if(!obj.hasOwnProperty(pathComponent)) return undefined; return getKeyPath(obj[pathComponent], path); } function setKeyPath(obj, path, value) { var i = 0, pathComponent; path = path.split('.'); while(i < path.length - 1) { pathComponent = path[i]; if(!obj.hasOwnProperty(pathComponent)) obj[pathComponent] = {}; obj = obj[pathComponent]; i++; } obj[path[i]] = value; } function shapeObj(obj) { var i, mapping, res = {}, val; for(i = 0; i < propMappings.length; i++) { mapping = propMappings[i]; val = getKeyPath(obj, mapping.from); if(val) setKeyPath(res, mapping.to, val.value); } return res; } var res = [], data = runtimeSettings.data, propMappings = [], i, s, from, to; for(i = 0; i < opts.propMappings.length; i++) { s = opts.propMappings[i].split('='); if(s.length == 1 && s[0].length > 0) from = to = s[0]; else if(s.length == 2 && s[0].length > 0 && s[1].length > 0) { to = s[0]; from = s[1]; } else { console.error('Invalid property mapping: ' + opts.propMappings[i]); process.exit(1); } propMappings.push({ from: from, to: to }); } if(Array.isArray(data)) return data.map(shapeObj); return shapeObj(data); } function formatCommandHandler(runtimeSettings, config, opts) { function replacerFactory(data, dataIdx) { return function(match, unbracketed, bracketed) { // Short-circuit this case; this can only be a property name // of the object if(unbracketed) return data[dataIdx][unbracketed]; // Otherwise, evaluate the expression // TODO: slight modifications on this are used in a few places; // would be good to make this a function. var script = '(function() { '; if(runtimeSettings.withClause) script += 'with(this) { '; script += 'return (' + bracketed + ').toString();'; if(runtimeSettings.withClause) script += ' }'; script += ' }).apply($data[' + dataIdx + ']);'; return vm.runInContext(script, runtimeSettings.sandbox); }; } /* bracketed: /%\{(?=[^}]*\})([^}]*)\}/ unbracketed: /%([\w$]+)/ */ var vm = require('vm'), format = opts.format, re = /%([\w%]+)|%\{(?=[^}]*\})([^}]*)\}/g, data = runtimeSettings.data, i, replacer; if(!Array.isArray(data)) data = [data]; // TODO: might be nice to provide autopaging here, like for the commands // that output JSON. for(i = 0; i < data.length; i++) { replacer = replacerFactory(data, i); process.stdout.write(format.replace(re, replacer) + '\n'); } } //// Guts function runCommand(commandDesc, opts) { var config = loadConfig(defaultConfig, opts.configPath), runtimeSettings = makeRuntimeSettings(commandDesc, config, opts), res = commandDesc.handler(runtimeSettings, config, opts); if(commandDesc.outputsJSON) outputJSON(res, runtimeSettings, config); } // Merges config and command line options down into a friendly object, which // includes searching module directories for .js files and loading them into // a sandbox, as well as loading and parsing the input file (or stdin). function makeRuntimeSettings(commandDesc, config, opts) { var fs = require('fs'), vm = require('vm'), isatty = require('tty').isatty(process.stdout.fd), settings = {}, dirs; if(commandDesc.outputsJSON) { if(opts.disableSmartOutput) settings.smartOutput = false; else settings.smartOutput = opts.disableSmartOutput === false || !config.disableSmartOutput; if(opts.prettyPrint === false) {} // --no-pretty-print else if(opts.prettyPrint || config.alwaysPrettyPrint || (settings.smartOutput && isatty)) settings.prettyPrinter = config.prettyPrinter; if(opts.sort === false) {} // --no-sort else if(opts.sort || config.alwaysSort) settings.sort = true; } if(commandDesc.hasWithClauseOpt) { if(opts.disableWithClause) settings.withClause = false; else settings.withClause = opts.disableWithClause === false || !config.disableWithClause; } if(opts.autoUnwrap === false) { } // --no-auto-unwrap else if(opts.autoUnwrap || config.alwaysAutoUnwrap) settings.unwrapper = config.autoUnwrapper; if(opts.unwrapProperty) settings.unwrapper = function(config, obj) { return obj[opts.unwrapProperty]; }; settings.verbose = opts.verbose; if(opts.file) settings.file = opts.file; else settings.file = '/dev/stdin'; try { settings.json = fs.readFileSync(settings.file, 'utf8'); } catch(exc) { console.error('Error: Unable to load JSON file "' + settings.file + '": ' + exc); process.exit(1); } settings.jsonParser = config.jsonParser; try { settings.data = settings.jsonParser(config, settings.json); } catch(exc) { console.error('Error parsing JSON: ' + exc + '.\nInput:\n' + settings.json); process.exit(1); } if(settings.unwrapper) settings.data = settings.unwrapper(config, settings.data); // Find modules and load them into a sandbox if the command needs it, // and throw the data in there too as $data if(commandDesc.needsSandbox) { if(opts.moduleDirectories && opts.moduleDirectories[0] === false) // nomnom turns --no-<list option> into [false] settings.modulePaths = []; else if(opts.moduleDirectories) { dirs = opts.moduleDirectories; dirs.push.apply(dirs, config.moduleDirectories); settings.modulePaths = findModules(dirs); } else settings.modulePaths = findModules(config.moduleDirectories); if(opts.modulePaths && opts.modulePaths[0] !== false) settings.modulePaths.push.apply(settings.modulePaths, opts.modulePaths); settings.sandbox = vm.createContext({ $config: config, $data: settings.data, console: console, out: console.log, process: process, require: require }); loadModules(settings.modulePaths, settings.sandbox); } return settings; } function loadModules(modulePaths, sandbox) { var fs = require('fs'), vm = require('vm'), i, modulePath, moduleContents; for(i = 0; i < modulePaths.length; i++) { modulePath = modulePaths[i]; try { moduleContents = fs.readFileSync(modulePath, 'utf8'); vm.runInContext(moduleContents, sandbox, modulePath); } catch(exc) { console.warn('Warning: error loading module "' + modulePath + '": ' + exc); } } } function outputJSON(obj, runtimeSettings, config) { var buffer, lineCount, pagerCmd, pager; if(obj === undefined) return; if(runtimeSettings.sort) obj = sortObject(obj); try { if(runtimeSettings.prettyPrinter) obj = runtimeSettings.prettyPrinter(config, obj); else obj = JSON.stringify(obj); } catch(exc) { console.error('Error converting result to JSON: ' + exc); process.exit(1); } if(typeof obj != 'string') { // JSON.stringify will return undefined if the top-level object is // a function or an XML object, neither of which should ever happen, // so we're just ignoring this for now. return; } if(runtimeSettings.smartOutput && require('tty').isatty(process.stdout.fd)) { lineCount = obj.length - obj.replace(new RegExp('\n', 'g'), '').length; if(lineCount > process.stdout.getWindowSize()[1]) { // Autopage pagerCmd = process.env.PAGER || 'less'; pager = require('child_process') .spawn(pagerCmd, [], { customFds: [-1, process.stdout.fd, -1] }); pager.stderr.setEncoding('utf8'); pager.stderr.on('data', function(data) { console.error('Error running pager command ("' + pagerCmd + '"): ' + data); process.exit(1); }); pager.stdin.end(obj); pager.stdin.on('error', function(exc) { // Silence EPIPE; just means that they closed the pager before // we finished writing (or the pager never started, in which // case the stderr output will be sufficient). if(exc.code != 'EPIPE') throw exc; }); return; } } // process.stdout.write seems like the obvious choice here, but // it causes an exception if we pipe a big result to something // and close the whole shebang before it can finish writing. // Should probably file a node bug... buffer = new Buffer(obj); require('fs').write(process.stdout.fd, buffer, 0, buffer.length); } //// Command line parsing function parseCommandLine(commands) { var args = process.argv.slice(2), // remove 'node' and script name defaultCommand = 'script', scriptName = require('path').basename(process.argv[1], '.js'), firstArg = args[0], parser = require('nomnom'), globalOpts, jsonOutputOpts, sandboxOpts, withClauseOpt, commandName, commandDesc, commandObj; globalOpts = { unwrapProperty: { abbr: 'u', metavar: 'KEY', full: 'unwrap-prop', type: 'string', help: 'Operate only against the given property of the loaded JSON.' }, autoUnwrap: { abbr: 'a', full: 'auto-unwrap', flag: true, help: 'Attempt to intelligently extract a useful property of the loaded JSON to run against.' }, file: { abbr: 'f', metavar: 'FILE', help: 'Load JSON from the given file instead of reading from stdin.', type: 'string' }, configPath: { abbr: 'c', full: 'config', metavar: 'FILE', help: 'Load the given config file. The default is ~/.jutil/config; specify --no-config to use the default configuration.', type: 'string', 'default': '~/.jutil/config' }, verbose: { abbr: 'v', flag: true, help: 'Be verbose about things (e.g. module loading).' } }; jsonOutputOpts = { prettyPrint: { abbr: 'p', full: 'pretty-print', flag: true, help: 'Pretty-print the output.' }, sort: { abbr: 's', full: 'sort-keys', flag: true, help: 'Sort keys in the output.' }, disableSmartOutput: { abbr: 'S', full: 'disable-smart', flag: true, help: 'Don\'t pretty-print or autopage if stdout is a terminal.' } }; sandboxOpts = { moduleDirectories: { abbr: 'M', full: 'module-dir', metavar: 'DIR', list: true, type: 'string', help: 'Add the given directory as a module path. Any .js files in the directory will be loaded before executing. Specify --no-module-dir to disable module directory loading.' }, modulePaths: { abbr: 'm', full: 'module', metavar: 'FILE', list: true, type: 'string', help: 'Load the given JavaScript file before executing.' } }; withClauseOpt = { abbr: 'W', full: 'disable-with', flag: true, help: 'Don\'t wrap the script to execute in a "with" clause.' }; // If we weren't invoked as 'jutil', we were called 'j<command name>', // which we massage into the first argument. if(scriptName != 'jutil') args.unshift(scriptName.substr(1)); else if(!firstArg || (firstArg != '-h' && firstArg != '--help' && !commands.hasOwnProperty(firstArg))) { // Otherwise, add in the default command 'script', if appropriate: // --help/-h -> no default // no first arg -> default // first arg is not a command name -> default args.unshift(defaultCommand); } parser.script('jutil'); parser .nocommand() .help('Run jutil <command> --help to see command-specific options.\nIf no command is specified, the default is "' + defaultCommand + '".'); for(commandName in commands) { if(commands.hasOwnProperty(commandName)) { commandDesc = commands[commandName]; commandObj = parser.command(commandName); commandObj.help(commandDesc.help); // nomnom seems to freak out if we call options() more than once // on a command object, wo we're gathering all the options in one // place to just make one call. shallowCopy(globalOpts, commandDesc.options); if(commandDesc.outputsJSON) shallowCopy(jsonOutputOpts, commandDesc.options); if(commandDesc.needsSandbox) shallowCopy(sandboxOpts, commandDesc.options); if(commandDesc.hasWithClauseOpt) commandDesc.options.disableWithClause = withClauseOpt; commandObj.options(commandDesc.options); // Go go gadget JS scoping rules!!! (function(commandDesc) { commandObj.callback(function(opts) { runCommand(commandDesc, opts); }); })(commandDesc); } } return parser.parse(args); } //// Configuration file handling function loadConfig(defaultConfig, configPath) { var fs = require('fs'), vm = require('vm'), config = {}, realConfigPath, configFile, configSandbox, propName, defaultConfigProperties, userConfig; shallowCopy(defaultConfig, config); if(!configPath) return config; try { realConfigPath = resolvePath(configPath); configFile = fs.readFileSync(realConfigPath, 'utf8'); configSandbox = vm.createContext({ console: console, out: console.log, process: process, require: require }); vm.runInContext(configFile, configSandbox, realConfigPath); userConfig = configSandbox.config; } catch(exc) { // It's fine if we didn't find a config file; we'll use the defaults if(exc.code == 'ENOENT') return config; else { console.error('Error loading configuration file: ' + exc); process.exit(1); } } if(userConfig) { // Validate config file and merge it with the defaults. copyStringArraySetting(userConfig, config, 'moduleDirectories'); copyFunctionSetting(userConfig, config, 'prettyPrinter', 2); copyFunctionSetting(userConfig, config, 'jsonParser', 3); copyBooleanSetting(userConfig, config, 'alwaysSort'); copyBooleanSetting(userConfig, config, 'alwaysPrettyPrint'); copyBooleanSetting(userConfig, config, 'alwaysAutoUnwrap'); copyStringArraySetting(userConfig, config, 'autoUnwrapProperties'); copyFunctionSetting(userConfig, config, 'autoUnwrapper', 2); copyBooleanSetting(userConfig, config, 'disableWithClause'); copyBooleanSetting(userConfig, config, 'disableSmartOutput'); if(userConfig.hasOwnProperty('prettyPrintIndent')) { switch(typeof userConfig.prettyPrintIndent) { case 'string': case 'number': config.prettyPrintIndent = userConfig.prettyPrintIndent; break; default: console.warn('Warning: prettyPrintIndent property in config file must be a number or string; ignoring the setting'); } } // Copy over any other properties from the config file for(propName in userConfig) { if(userConfig.hasOwnProperty(propName) && !defaultConfig.hasOwnProperty(propName)) { config[propName] = userConfig[propName]; } } } else console.warn('Warning: config file must assign to the global "config" var; ignoring the file'); return config; } function copyStringArraySetting(userConfig, config, name) { var val, i; if(userConfig.hasOwnProperty(name)) { val = userConfig[name]; if(Array.isArray(val)) { for(i = 0; i < val.length; i++) { if(typeof val[i] != 'string') { console.warn('Warning: ' + name + ' property in config file must contain only string elements; ignoring the setting'); return; } } config[name] = val; } else console.warn('Warning: ' + name + ' property in config file must be an array; ignoring the setting'); } } function copyFunctionSetting(userConfig, config, name, arity) { if(userConfig.hasOwnProperty(name)) { var val = userConfig[name]; if(typeof val == 'function') { if(val.length == arity) config[name] = val; else console.warn('Warning: ' + name + ' function in config file must take exactly ' + arity + ' arguments; ignoring the setting'); } else console.warn('Warning: ' + name + ' property in config file must be a function; ignoring the setting'); } } function copyBooleanSetting(userConfig, config, name) { if(userConfig.hasOwnProperty(name)) { if(typeof userConfig[name] == 'boolean') config[name] = userConfig[name]; else console.warn('Warning: ' + name + ' property in config file must be a boolean; ignoring the setting'); } } //// Helpers function resolvePath(p) { var path = require('path'); switch(p.charAt(0)) { case '~': return path.join(process.env.HOME, p.substr(1)); case '/': return p; default: return path.join(process.cwd(), p); } } function shallowCopy(source, dest) { var keys = Object.keys(source), i, key; for(i = 0; i < keys.length; i++) { key = keys[i]; dest[key] = source[key]; } } function findModules(dirs) { var fs = require('fs'), path = require('path'), paths = [], moduleDir, allFiles, i, j, file; for(i = 0; i < dirs.length; i++) { moduleDir = resolvePath(dirs[i]); allFiles = []; try { allFiles = fs.readdirSync(moduleDir); } catch(exc) { // No warning if module directory is nonexistent if(exc.code != 'ENOENT') console.warn('Warning: error reading module directory "' + moduleDir + '": ' + exc); } for(j = 0; j < allFiles.length; j++) { file = allFiles[j]; if(path.extname(file).toLowerCase() == '.js') paths.push(path.join(moduleDir, file)); } } return paths; } function sortObject(obj) { // This relies on the JavaScript interpreter placing some importance // on the order in which keys were added to an object. Luckily V8 // does that, at least for now... var sortedKeys, sortedObj, i, key; if(typeof obj != 'object' || obj === null) return obj; if(Array.isArray(obj)) return obj.map(sortObject); sortedKeys = Object.keys(obj).sort(); sortedObj = {}; for(i = 0; i < sortedKeys.length; i++) { key = sortedKeys[i]; sortedObj[key] = sortObject(obj[key]); } return sortedObj; } })();
Add header and footer options to jformat
jutil.js
Add header and footer options to jformat
<ide><path>util.js <ide> position: 1, <ide> required: true, <ide> help: 'The format string to use. Tokens are of the form %property or %{expression}. (Required)' <add> }, <add> header: { <add> abbr: 'H', <add> metavar: 'FORMAT', <add> help: 'A header to print before the main output; same token syntax as the format string and is evaluated against the data as a whole.', <add> type: 'string' <add> }, <add> footer: { <add> abbr: 'F', <add> metavar: 'FORMAT', <add> help: 'A footer to print after the main output; same token syntax as the format string and is evaluated against the data as a whole.', <add> type: 'string' <ide> } <ide> }, <ide> outputsJSON: false, <ide> <ide> function formatCommandHandler(runtimeSettings, config, opts) <ide> { <del> function replacerFactory(data, dataIdx) { <add> function replacerFactory(data, dataString) { <ide> return function(match, unbracketed, bracketed) { <ide> // Short-circuit this case; this can only be a property name <ide> // of the object <ide> if(unbracketed) <del> return data[dataIdx][unbracketed]; <add> return data[unbracketed]; <ide> <ide> // Otherwise, evaluate the expression <ide> // TODO: slight modifications on this are used in a few places; <ide> if(runtimeSettings.withClause) script += 'with(this) { '; <ide> script += 'return (' + bracketed + ').toString();'; <ide> if(runtimeSettings.withClause) script += ' }'; <del> script += ' }).apply($data[' + dataIdx + ']);'; <add> script += ' }).apply(' + dataString + ');'; <ide> <ide> return vm.runInContext(script, runtimeSettings.sandbox); <ide> }; <ide> <ide> // TODO: might be nice to provide autopaging here, like for the commands <ide> // that output JSON. <add> <add> if(opts.header) { <add> replacer = replacerFactory(data, '$data'); <add> <add> if(opts.header) <add> process.stdout.write(opts.header.replace(re, replacer) + '\n'); <add> } <add> <ide> for(i = 0; i < data.length; i++) { <del> replacer = replacerFactory(data, i); <add> replacer = replacerFactory(data[i], '$data[' + i + ']'); // TODO: $data[0] is invalid if data was a single object! <ide> process.stdout.write(format.replace(re, replacer) + '\n'); <add> } <add> <add> if(opts.footer) { <add> replacer = replacerFactory(data, '$data'); <add> <add> if(opts.footer) <add> process.stdout.write(opts.footer.replace(re, replacer) + '\n'); <ide> } <ide> } <ide>
Java
apache-2.0
d1833f3a6108f64e2e06ddd4de0fa565156d1b46
0
spennihana/h2o-3,michalkurka/h2o-3,kyoren/https-github.com-h2oai-h2o-3,jangorecki/h2o-3,spennihana/h2o-3,spennihana/h2o-3,jangorecki/h2o-3,h2oai/h2o-dev,jangorecki/h2o-3,kyoren/https-github.com-h2oai-h2o-3,h2oai/h2o-3,madmax983/h2o-3,pchmieli/h2o-3,h2oai/h2o-3,kyoren/https-github.com-h2oai-h2o-3,kyoren/https-github.com-h2oai-h2o-3,pchmieli/h2o-3,mathemage/h2o-3,michalkurka/h2o-3,madmax983/h2o-3,h2oai/h2o-3,pchmieli/h2o-3,kyoren/https-github.com-h2oai-h2o-3,h2oai/h2o-3,h2oai/h2o-dev,spennihana/h2o-3,madmax983/h2o-3,mathemage/h2o-3,mathemage/h2o-3,spennihana/h2o-3,spennihana/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,h2oai/h2o-dev,madmax983/h2o-3,h2oai/h2o-3,mathemage/h2o-3,madmax983/h2o-3,h2oai/h2o-3,kyoren/https-github.com-h2oai-h2o-3,jangorecki/h2o-3,pchmieli/h2o-3,YzPaul3/h2o-3,YzPaul3/h2o-3,h2oai/h2o-dev,spennihana/h2o-3,mathemage/h2o-3,YzPaul3/h2o-3,YzPaul3/h2o-3,michalkurka/h2o-3,jangorecki/h2o-3,mathemage/h2o-3,michalkurka/h2o-3,h2oai/h2o-dev,pchmieli/h2o-3,h2oai/h2o-3,pchmieli/h2o-3,madmax983/h2o-3,h2oai/h2o-dev,YzPaul3/h2o-3,jangorecki/h2o-3,jangorecki/h2o-3,madmax983/h2o-3,YzPaul3/h2o-3,pchmieli/h2o-3,YzPaul3/h2o-3,h2oai/h2o-3,h2oai/h2o-dev,michalkurka/h2o-3,kyoren/https-github.com-h2oai-h2o-3,mathemage/h2o-3
package hex.deeplearning; import hex.*; import hex.quantile.Quantile; import hex.quantile.QuantileModel; import hex.schemas.DeepLearningModelV3; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import water.*; import water.api.ModelSchema; import water.exceptions.H2OIllegalArgumentException; import water.fvec.Chunk; import water.fvec.Frame; import water.fvec.NewChunk; import water.fvec.Vec; import water.util.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static hex.ModelMetrics.calcVarImp; import static hex.deeplearning.DeepLearning.makeDataInfo; import static water.H2O.technote; /** * The Deep Learning model * It contains a DeepLearningModelInfo with the most up-to-date model, * a scoring history, as well as some helpers to indicate the progress */ public class DeepLearningModel extends Model<DeepLearningModel,DeepLearningParameters,DeepLearningModel.DeepLearningModelOutput> implements Model.DeepFeatures { /** * The Deep Learning model output contains a few extra fields in addition to the metrics in Model.Output * 1) Scoring history (raw data) * 2) weights/biases (raw data) * 3) variable importances (TwoDimTable) */ public static class DeepLearningModelOutput extends Model.Output { public DeepLearningModelOutput() { super(); autoencoder = false;} public DeepLearningModelOutput(DeepLearning b) { super(b); autoencoder = b._parms._autoencoder; assert b.isSupervised() == !autoencoder; } final boolean autoencoder; DeepLearningScoring errors; Key[] weights; Key[] biases; double[] normmul; double[] normsub; double[] normrespmul; double[] normrespsub; int[] catoffsets; public TwoDimTable _variable_importances; @Override public ModelCategory getModelCategory() { return autoencoder ? ModelCategory.AutoEncoder : super.getModelCategory(); } @Override public boolean isSupervised() { return !autoencoder; } } /** * Deviance of given distribution function at predicted value f * @param w observation weight * @param y (actual) response * @param f (predicted) response in original response space * @return value of gradient */ @Override public double deviance(double w, double y, double f) { // Note: Must use sanitized parameters via get_params() as this._params can still have defaults AUTO, etc.) assert(get_params()._distribution != Distribution.Family.AUTO); return new Distribution(get_params()._distribution, get_params()._tweedie_power).deviance(w,y,f); } // Default publicly visible Schema is V2 public ModelSchema schema() { return new DeepLearningModelV3(); } void set_model_info(DeepLearningModelInfo mi) { assert(mi != null); model_info = mi; } final public DeepLearningModelInfo model_info() { return model_info; } final public VarImp varImp() { return _output.errors.variable_importances; } private volatile DeepLearningModelInfo model_info; public long run_time; private long start_time; public long actual_train_samples_per_iteration; public long tspiGuess; public double time_for_communication_us; //helper for auto-tuning: time in microseconds for collective bcast/reduce of the model public double epoch_counter; public boolean stopped_early; public long training_rows; public long validation_rows; private DeepLearningScoring[] errors; public DeepLearningScoring[] scoring_history() { return errors; } // Keep the best model so far, based on a single criterion (overall class. error or MSE) private float _bestError = Float.POSITIVE_INFINITY; public Key actual_best_model_key; public Key model_info_key; // return the most up-to-date model metrics DeepLearningScoring last_scored() { return errors == null ? null : errors[errors.length-1]; } /** * Get the parameters actually used for model building, not the user-given ones (_parms) * They might differ since some defaults are filled in, and some invalid combinations are auto-disabled in modifyParams * @return actually used parameters */ public final DeepLearningParameters get_params() { return model_info.get_params(); } // Lower is better public float error() { return (float) (_output.isClassifier() ? classification_error() : deviance()); } @Override public ModelMetrics.MetricBuilder makeMetricBuilder(String[] domain) { switch(_output.getModelCategory()) { case Binomial: return new ModelMetricsBinomial.MetricBuilderBinomial(domain); case Multinomial: return new ModelMetricsMultinomial.MetricBuilderMultinomial(_output.nclasses(),domain); case Regression: return new ModelMetricsRegression.MetricBuilderRegression(); case AutoEncoder: return new ModelMetricsAutoEncoder.MetricBuilderAutoEncoder(_output.nfeatures()); default: throw H2O.unimpl("Invalid ModelCategory " + _output.getModelCategory()); } } public int compareTo(DeepLearningModel o) { if (o._output.isClassifier() != _output.isClassifier()) throw new UnsupportedOperationException("Cannot compare classifier against regressor."); if (o._output.nclasses() != _output.nclasses()) throw new UnsupportedOperationException("Cannot compare models with different number of classes."); return (error() < o.error() ? -1 : error() > o.error() ? 1 : 0); } public static class DeepLearningScoring extends Iced { public double epoch_counter; public double training_samples; public long training_time_ms; boolean validation; public long score_training_samples; public long score_validation_samples; public boolean classification; VarImp variable_importances; ScoreKeeper scored_train = new ScoreKeeper(); ScoreKeeper scored_valid = new ScoreKeeper(); public AUC2 training_AUC; public AUC2 validation_AUC; public long scoring_time; DeepLearningScoring deep_clone() { AutoBuffer ab = new AutoBuffer(); this.write(ab); ab.flipForReading(); return (DeepLearningScoring) new DeepLearningScoring().read(ab); } } public double classification_error() { if (errors == null) return Double.NaN; return last_scored().validation ? last_scored().scored_valid._classError : last_scored().scored_train._classError; } public double mse() { if (errors == null) return Double.NaN; return last_scored().validation ? last_scored().scored_valid._mse : last_scored().scored_train._mse; } public double deviance() { if (errors == null) return Double.NaN; return last_scored().validation ? last_scored().scored_valid._mean_residual_deviance : last_scored().scored_train._mean_residual_deviance; } public double logloss() { if (errors == null) return Double.NaN; return last_scored().validation ? last_scored().scored_valid._logloss : last_scored().scored_train._logloss; } private TwoDimTable createScoringHistoryTable(DeepLearningScoring[] errors) { List<String> colHeaders = new ArrayList<>(); List<String> colTypes = new ArrayList<>(); List<String> colFormat = new ArrayList<>(); colHeaders.add("Timestamp"); colTypes.add("string"); colFormat.add("%s"); colHeaders.add("Duration"); colTypes.add("string"); colFormat.add("%s"); colHeaders.add("Training Speed"); colTypes.add("string"); colFormat.add("%s"); colHeaders.add("Epochs"); colTypes.add("double"); colFormat.add("%.5f"); colHeaders.add("Samples"); colTypes.add("double"); colFormat.add("%f"); colHeaders.add("Training MSE"); colTypes.add("double"); colFormat.add("%.5f"); if (_output.getModelCategory() == ModelCategory.Regression) { colHeaders.add("Training Deviance"); colTypes.add("double"); colFormat.add("%.5f"); } if (!_output.autoencoder) { colHeaders.add("Training R^2"); colTypes.add("double"); colFormat.add("%.5f"); } if (_output.isClassifier()) { colHeaders.add("Training LogLoss"); colTypes.add("double"); colFormat.add("%.5f"); } if (_output.getModelCategory() == ModelCategory.Binomial) { colHeaders.add("Training AUC"); colTypes.add("double"); colFormat.add("%.5f"); } if (_output.getModelCategory() == ModelCategory.Binomial || _output.getModelCategory() == ModelCategory.Multinomial) { colHeaders.add("Training Classification Error"); colTypes.add("double"); colFormat.add("%.5f"); } if (get_params()._valid != null) { colHeaders.add("Validation MSE"); colTypes.add("double"); colFormat.add("%.5f"); if (_output.getModelCategory() == ModelCategory.Regression) { colHeaders.add("Validation Deviance"); colTypes.add("double"); colFormat.add("%.5f"); } if (!_output.autoencoder) { colHeaders.add("Validation R^2"); colTypes.add("double"); colFormat.add("%.5f"); } if (_output.isClassifier()) { colHeaders.add("Validation LogLoss"); colTypes.add("double"); colFormat.add("%.5f"); } if (_output.getModelCategory() == ModelCategory.Binomial) { colHeaders.add("Validation AUC"); colTypes.add("double"); colFormat.add("%.5f"); } if (_output.isClassifier()) { colHeaders.add("Validation Classification Error"); colTypes.add("double"); colFormat.add("%.5f"); } } final int rows = errors.length; String[] s = new String[0]; TwoDimTable table = new TwoDimTable( "Scoring History", null, new String[rows], colHeaders.toArray(s), colTypes.toArray(s), colFormat.toArray(s), ""); int row = 0; for (final DeepLearningScoring e : errors) { int col = 0; assert (row < table.getRowDim()); assert (col < table.getColDim()); DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); table.set(row, col++, fmt.print(start_time + e.training_time_ms)); table.set(row, col++, PrettyPrint.msecs(e.training_time_ms, true)); table.set(row, col++, e.training_time_ms == 0 ? null : (String.format("%.3f", e.training_samples / (e.training_time_ms / 1e3)) + " rows/sec")); table.set(row, col++, e.epoch_counter); table.set(row, col++, e.training_samples); table.set(row, col++, e.scored_train != null ? e.scored_train._mse : Double.NaN); if (_output.getModelCategory() == ModelCategory.Regression) { table.set(row, col++, e.scored_train != null ? e.scored_train._mean_residual_deviance : Double.NaN); } if (!_output.autoencoder) { table.set(row, col++, e.scored_train != null ? e.scored_train._r2 : Double.NaN); } if (_output.isClassifier()) { table.set(row, col++, e.scored_train != null ? e.scored_train._logloss : Double.NaN); } if (_output.getModelCategory() == ModelCategory.Binomial) { table.set(row, col++, e.training_AUC != null ? e.training_AUC._auc : Double.NaN); } if (_output.isClassifier()) { table.set(row, col++, e.scored_train != null ? e.scored_train._classError : Double.NaN); } if (get_params()._valid != null) { table.set(row, col++, e.scored_valid != null ? e.scored_valid._mse : Double.NaN); if (_output.getModelCategory() == ModelCategory.Regression) { table.set(row, col++, e.scored_valid != null ? e.scored_valid._mean_residual_deviance : Double.NaN); } if (!_output.autoencoder) { table.set(row, col++, e.scored_valid != null ? e.scored_valid._r2 : Double.NaN); } if (_output.isClassifier()) { table.set(row, col++, e.scored_valid != null ? e.scored_valid._logloss : Double.NaN); } if (_output.getModelCategory() == ModelCategory.Binomial) { table.set(row, col++, e.validation_AUC != null ? e.validation_AUC._auc : Double.NaN); } if (_output.isClassifier()) { table.set(row, col, e.scored_valid != null ? e.scored_valid._classError : Double.NaN); } } row++; } return table; } /** * Helper to allocate keys for output frames for weights and biases * @param destKey Base destination key for output frames */ private void makeWeightsBiases(Key destKey) { if (!model_info.get_params()._export_weights_and_biases) { _output.weights = null; _output.biases = null; _output.normmul = null; _output.normsub = null; _output.normrespmul = null; _output.normrespsub = null; _output.catoffsets = null; } else { _output.weights = new Key[get_params()._hidden.length + 1]; for (int i = 0; i < _output.weights.length; ++i) { _output.weights[i] = Key.makeUserHidden(Key.make(destKey + ".weights." + i)); } _output.biases = new Key[get_params()._hidden.length + 1]; for (int i = 0; i < _output.biases.length; ++i) { _output.biases[i] = Key.makeUserHidden(Key.make(destKey + ".biases." + i)); } _output.normmul = model_info.data_info._normMul; _output.normsub = model_info.data_info._normSub; _output.normrespmul = model_info.data_info._normRespMul; _output.normrespsub = model_info.data_info._normRespSub; _output.catoffsets = model_info.data_info._catOffsets; } } /** Constructor to restart from a checkpointed model * @param destKey New destination key for the model * @param parms User-given parameters for checkpoint restart * @param cp Checkpoint to restart from * @param store_best_model Store only the best model instead of the latest one */ public DeepLearningModel(final Key destKey, final DeepLearningParameters parms, final DeepLearningModel cp, final boolean store_best_model, final DataInfo dataInfo) { super(destKey, parms == null ? (DeepLearningParameters)cp._parms.clone() : parms, (DeepLearningModelOutput)cp._output.clone()); assert(_parms != cp._parms); //make sure we have a clone model_info = cp.model_info.deep_clone(); //don't want to interfere with model being built, just make a deep copy and store that if (store_best_model) { model_info.data_info = dataInfo.deep_clone(); //replace previous data_info with updated version that's passed in (contains enum for classification) } else { model_info.data_info = dataInfo; //shallow clone is ok if (parms != null) { assert (_parms == parms); assert (_parms._checkpoint == parms._checkpoint); assert (_parms._checkpoint == cp._key); } // _parms._checkpoint = cp._key; //it's only a "real" checkpoint if job != null, otherwise a best model copy } DKV.put(dataInfo); assert(get_params() != cp.model_info().get_params()); //make sure we have a clone actual_best_model_key = cp.actual_best_model_key; start_time = cp.start_time; run_time = cp.run_time; training_rows = cp.training_rows; //copy the value to display the right number on the model page before training has started validation_rows = cp.validation_rows; //copy the value to display the right number on the model page before training has started _bestError = cp._bestError; epoch_counter = cp.epoch_counter; // deep clone scoring history errors = cp.errors.clone(); for (int i=0; i<errors.length;++i) errors[i] = cp.errors[i].deep_clone(); _output.errors = last_scored(); makeWeightsBiases(destKey); _output._scoring_history = createScoringHistoryTable(errors); _output._variable_importances = calcVarImp(last_scored().variable_importances); _output._names = dataInfo._adaptedFrame.names(); _output._domains = dataInfo._adaptedFrame.domains(); // set proper timing _timeLastScoreEnter = System.currentTimeMillis(); _timeLastScoreStart = 0; _timeLastScoreEnd = 0; _timeLastPrintStart = 0; assert(Arrays.equals(_key._kb, destKey._kb)); } /** * Regular constructor (from scratch) * @param destKey destination key * @param parms DL parameters * @param output DL model output * @param train Training frame * @param valid Validation frame * @param nClasses Number of classes (1 for regression or autoencoder) */ public DeepLearningModel(final Key destKey, final DeepLearningParameters parms, final DeepLearningModelOutput output, Frame train, Frame valid, int nClasses) { super(destKey, parms, output); final DataInfo dinfo = makeDataInfo(train, valid, _parms); _output._names = train._names ; // Since changed by DataInfo, need to be reflected in the Model output as well _output._domains= train.domains(); _output._names = dinfo._adaptedFrame.names(); _output._domains = dinfo._adaptedFrame.domains(); DKV.put(dinfo); model_info = new DeepLearningModelInfo(parms, dinfo, nClasses, train, valid); model_info_key = Key.makeUserHidden(Key.make(H2O.SELF)); actual_best_model_key = Key.makeUserHidden(Key.make(H2O.SELF)); if (parms._nfolds != 0) actual_best_model_key = null; if (!parms._autoencoder) { errors = new DeepLearningScoring[1]; errors[0] = new DeepLearningScoring(); errors[0].validation = (parms._valid != null); _output.errors = last_scored(); _output._scoring_history = createScoringHistoryTable(errors); _output._variable_importances = calcVarImp(last_scored().variable_importances); } makeWeightsBiases(destKey); run_time = 0; start_time = System.currentTimeMillis(); _timeLastScoreEnter = start_time; assert _key.equals(destKey); boolean fail = false; long byte_size = 0; try { byte_size = new AutoBuffer().put(this).buf().length; } catch(Throwable t) { fail = true; } if (byte_size > Value.MAX || fail) throw new IllegalArgumentException(technote(5, "Model is too large")); } public long _timeLastScoreEnter; //not transient: needed for HTML display page transient private long _timeLastScoreStart; transient private long _timeLastScoreEnd; transient private long _timeLastPrintStart; /** * Score this DeepLearning model * @param ftrain potentially downsampled training data for scoring * @param ftest potentially downsampled validation data for scoring * @param job_key key of the owning job * @param progressKey key of the progress * @param iteration Map/Reduce iteration count * @return true if model building is ongoing */ boolean doScoring(Frame ftrain, Frame ftest, Key job_key, Key progressKey, int iteration) { final long now = System.currentTimeMillis(); epoch_counter = (double)model_info().get_processed_total()/training_rows; final double time_last_iter_millis = Math.max(5,now-_timeLastScoreEnter); run_time += time_last_iter_millis; // First update Job progress based on the number of trained samples for the last iteration // and update the progress message Job.Progress prog = DKV.getGet(progressKey); float progress = prog == null ? 0 : prog.progress(); String msg = "Map/Reduce Iteration " + String.format("%,d",iteration) + ": Training at " + String.format("%,d", model_info().get_processed_total() * 1000 / run_time) + " samples/s..." + (progress == 0 ? "" : " Estimated time left: " + PrettyPrint.msecs((long) (run_time * (1. - progress) / progress), true)); ((Job)DKV.getGet(job_key)).update(actual_train_samples_per_iteration); //mark the amount of work done for the progress bar if (progressKey != null) new Job.ProgressUpdate(msg).fork(progressKey); //update the message for the progress bar boolean keep_running; // Auto-tuning // if multi-node and auto-tuning and at least 10 ms for communication (to avoid doing thins on multi-JVM on same node), // then adjust the auto-tuning parameter 'actual_train_samples_per_iteration' such that the targeted ratio of comm to comp is achieved // Note: actual communication time is estimated by the NetworkTest's collective test. if (H2O.CLOUD.size() > 1 && get_params()._train_samples_per_iteration == -2 && iteration != 0) { Log.info("Auto-tuning train_samples_per_iteration."); if (time_for_communication_us > 1e4) { Log.info(" Time taken for communication: " + PrettyPrint.usecs((long) time_for_communication_us)); Log.info(" Time taken for Map/Reduce iteration: " + PrettyPrint.msecs((long) time_last_iter_millis, true)); final double comm_to_work_ratio = (time_for_communication_us * 1e-3) / time_last_iter_millis; Log.info(" Ratio of network communication to computation: " + String.format("%.5f", comm_to_work_ratio)); Log.info(" target_comm_to_work: " + get_params()._target_ratio_comm_to_comp); Log.info("Old value of train_samples_per_iteration: " + actual_train_samples_per_iteration); double correction = get_params()._target_ratio_comm_to_comp / comm_to_work_ratio; correction = Math.max(0.5,Math.min(2, correction)); //it's ok to train up to 2x more training rows per iteration, but not fewer than half. if (Math.abs(correction) < 0.8 || Math.abs(correction) > 1.2) { //don't correct unless it's significant (avoid slow drift) actual_train_samples_per_iteration /= correction; actual_train_samples_per_iteration = Math.max(1, actual_train_samples_per_iteration); Log.info("New value of train_samples_per_iteration: " + actual_train_samples_per_iteration); } else { Log.info("Keeping value of train_samples_per_iteration the same (would deviate too little from previous value): " + actual_train_samples_per_iteration); } } else { Log.info("Communication is faster than 10 ms. Not modifying train_samples_per_iteration: " + actual_train_samples_per_iteration); } } _timeLastScoreEnter = now; keep_running = (epoch_counter < get_params()._epochs) && !stopped_early; final long sinceLastScore = now -_timeLastScoreStart; final long sinceLastPrint = now -_timeLastPrintStart; if (!keep_running || sinceLastPrint > get_params()._score_interval * 1000) { //print this after every score_interval, not considering duty cycle _timeLastPrintStart = now; if (!get_params()._quiet_mode) { Log.info("Training time: " + PrettyPrint.msecs(run_time, true) + ". Processed " + String.format("%,d", model_info().get_processed_total()) + " samples" + " (" + String.format("%.3f", epoch_counter) + " epochs)." + " Speed: " + String.format("%,d", 1000 * model_info().get_processed_total() / run_time) + " samples/sec.\n"); Log.info(msg); } } // this is potentially slow - only do every so often if( !keep_running || (sinceLastScore > get_params()._score_interval *1000 //don't score too often &&(double)(_timeLastScoreEnd-_timeLastScoreStart)/sinceLastScore < get_params()._score_duty_cycle) ) { //duty cycle if (progressKey != null) { new Job.ProgressUpdate("Scoring on " + ftrain.numRows() + " training samples" + (ftest != null ? (", " + ftest.numRows() + " validation samples") : "") ).fork(progressKey); } final boolean printme = !get_params()._quiet_mode; _timeLastScoreStart = now; model_info().computeStats(); //might not be necessary, but is done to be certain that numbers are good DeepLearningScoring err = new DeepLearningScoring(); err.training_time_ms = run_time; err.epoch_counter = epoch_counter; err.training_samples = (double)model_info().get_processed_total(); err.validation = ftest != null; err.score_training_samples = ftrain.numRows(); err.classification = _output.isClassifier(); if (get_params()._autoencoder) { if (printme) Log.info("Scoring the auto-encoder."); // training { final Frame mse_frame = scoreAutoEncoder(ftrain, Key.make()); mse_frame.delete(); ModelMetrics mtrain = ModelMetrics.getFromDKV(this,ftrain); //updated by model.score _output._training_metrics = mtrain; err.scored_train = new ScoreKeeper(mtrain); } if (ftest != null) { final Frame mse_frame = scoreAutoEncoder(ftest, Key.make()); mse_frame.delete(); ModelMetrics mtest = ModelMetrics.getFromDKV(this,ftest); //updated by model.score _output._validation_metrics = mtest; err.scored_valid = new ScoreKeeper(mtest); } } else { if (printme) Log.info("Scoring the model."); // compute errors final String m = model_info().toString(); if (m.length() > 0) Log.info(m); final Frame trainPredict = score(ftrain); trainPredict.delete(); hex.ModelMetrics mtrain = ModelMetrics.getFromDKV(this, ftrain); _output._training_metrics = mtrain; err.scored_train = new ScoreKeeper(mtrain); hex.ModelMetrics mtest = null; hex.ModelMetricsSupervised mm1 = (ModelMetricsSupervised)ModelMetrics.getFromDKV(this,ftrain); if (mm1 instanceof ModelMetricsBinomial) { ModelMetricsBinomial mm = (ModelMetricsBinomial)(mm1); err.training_AUC = mm._auc; } if (ftrain.numRows() != training_rows) { _output._training_metrics._description = "Metrics reported on temporary training frame with " + ftrain.numRows() + " samples"; } else if (ftrain._key != null && ftrain._key.toString().contains("chunks")){ _output._training_metrics._description = "Metrics reported on temporary (load-balanced) training frame"; } else { _output._training_metrics._description = "Metrics reported on full training frame"; } if (ftest != null) { Frame validPred = score(ftest); validPred.delete(); if (ftest != null) { mtest = ModelMetrics.getFromDKV(this, ftest); _output._validation_metrics = mtest; err.scored_valid = new ScoreKeeper(mtest); } if (mtest != null) { if (mtest instanceof ModelMetricsBinomial) { ModelMetricsBinomial mm = (ModelMetricsBinomial)mtest; err.validation_AUC = mm._auc; } if (ftest.numRows() != validation_rows) { _output._validation_metrics._description = "Metrics reported on temporary validation frame with " + ftest.numRows() + " samples"; if (get_params()._score_validation_sampling == DeepLearningParameters.ClassSamplingMethod.Stratified) { _output._validation_metrics._description += " (stratified sampling)"; } } else if (ftest._key != null && ftest._key.toString().contains("chunks")){ _output._validation_metrics._description = "Metrics reported on temporary (load-balanced) validation frame"; } else { _output._validation_metrics._description = "Metrics reported on full validation frame"; } } } } if (get_params()._variable_importances) { if (!get_params()._quiet_mode) Log.info("Computing variable importances."); final float[] vi = model_info().computeVariableImportances(); err.variable_importances = new VarImp(vi, Arrays.copyOfRange(model_info().data_info().coefNames(), 0, vi.length)); } _timeLastScoreEnd = System.currentTimeMillis(); err.scoring_time = System.currentTimeMillis() - now; // enlarge the error array by one, push latest score back if (errors == null) { errors = new DeepLearningScoring[]{err}; } else { DeepLearningScoring[] err2 = new DeepLearningScoring[errors.length + 1]; System.arraycopy(errors, 0, err2, 0, errors.length); err2[err2.length - 1] = err; errors = err2; } _output.errors = last_scored(); makeWeightsBiases(_key); water.util.Timer t = new Timer(); // store weights and matrices to Frames if (_output.weights != null && _output.biases != null) { for (int i = 0; i < _output.weights.length; ++i) { model_info.get_weights(i).toFrame(_output.weights[i]); } for (int i = 0; i < _output.biases.length; ++i) { model_info.get_biases(i).toFrame(_output.biases[i]); } if (!_parms._quiet_mode) Log.info("Writing weights and biases to Frames took " + t.time()/1000. + " seconds."); } _output._scoring_history = createScoringHistoryTable(errors); _output._variable_importances = calcVarImp(last_scored().variable_importances); _output._model_summary = model_info.createSummaryTable(); if (!get_params()._autoencoder) { // always keep a copy of the best model so far (based on the following criterion) if (actual_best_model_key != null && get_params()._overwrite_with_best_model && ( // if we have a best_model in DKV, then compare against its error() (unless it's a different model as judged by the network size) (DKV.get(actual_best_model_key) != null && (error() < DKV.get(actual_best_model_key).<DeepLearningModel>get().error() || !Arrays.equals(model_info().units, DKV.get(actual_best_model_key).<DeepLearningModel>get().model_info().units))) || // otherwise, compare against our own _bestError (DKV.get(actual_best_model_key) == null && error() < _bestError) ) ) { if (!get_params()._quiet_mode) Log.info("Error reduced from " + _bestError + " to " + error() + "."); _bestError = error(); putMeAsBestModel(actual_best_model_key); } } // print the freshly scored model to ASCII if (keep_running && printme) Log.info(toString()); if (printme) Log.info("Time taken for scoring and diagnostics: " + PrettyPrint.msecs(err.scoring_time, true)); } if ( (_output.isClassifier() && last_scored().scored_train._classError <= get_params()._classification_stop) || (!_output.isClassifier() && last_scored().scored_train._mse <= get_params()._regression_stop) ) { Log.info("Achieved requested predictive accuracy on the training data. Model building completed."); stopped_early = true; keep_running = false; } update(job_key); return keep_running; } /** Make either a prediction or a reconstruction. * @param orig Test dataset * @param adaptedFr Test dataset, adapted to the model * @return A frame containing the prediction or reconstruction */ @Override protected Frame predictScoreImpl(Frame orig, Frame adaptedFr, String destination_key) { if (!get_params()._autoencoder) { return super.predictScoreImpl(orig, adaptedFr, destination_key); } else { // Reconstruction final int len = model_info().data_info().fullN(); assert(model_info().data_info()._responses == 0); String[] coefnames = model_info().data_info().coefNames(); assert(len == coefnames.length); String[] names = new String[len]; for(int i = 0; i < names.length; ++i) { names[i] = "reconstr_" + coefnames[i]; } Frame f = new MRTask() { @Override public void map( Chunk chks[], NewChunk recon[] ) { double tmp [] = new double[_output._names.length]; double preds[] = new double [len]; final Neurons[] neurons = DeepLearningTask.makeNeuronsForTesting(model_info); for( int row=0; row<chks[0]._len; row++ ) { double p[] = score_autoencoder(chks, row, tmp, preds, neurons); for( int c=0; c<len; c++ ) recon[c].addNum(p[c]); } } }.doAll(len,adaptedFr).outputFrame(); Frame of = new Frame((null == destination_key ? Key.make() : Key.make(destination_key)), names, f.vecs()); DKV.put(of); makeMetricBuilder(null).makeModelMetrics(this, orig); return of; } } @Override protected double[] score0(double[] data, double[] preds) { return score0(data, preds, 1, 0); } /** * Compute the loss function * @param myRows Mini-Batch Array of denseRow's containing numerical/categorical predictor and response data (standardized) * @return loss */ public double loss(DataInfo.Row[] myRows) { double loss = 0; Neurons[] neurons = DeepLearningTask.makeNeuronsForTraining(model_info()); for (DataInfo.Row myRow : myRows) { if (myRow == null) continue; long seed = -1; //ignored // check that all non-last layer errors/gradients are empty for (int i = 0; i<neurons.length-1;++i) { Storage.DenseVector e = neurons[i]._e; if (e==null) continue; assert(ArrayUtils.sum(e.raw()) == 0); } ((Neurons.Input)neurons[0]).setInput(seed, myRow.numVals, myRow.nBins, myRow.binIds); DeepLearningTask.step(seed, neurons, model_info(), null, false, null, myRow.offset); // check that all non-last layer errors/gradients are empty for (int i = 0; i<neurons.length-1;++i) { Storage.DenseVector e = neurons[i]._e; if (e==null) continue; assert(ArrayUtils.sum(e.raw()) == 0); } if (get_params()._loss == DeepLearningParameters.Loss.CrossEntropy) { if (_parms._balance_classes) throw H2O.unimpl(); int actual = (int) myRow.response[0]; double pred = neurons[neurons.length - 1]._a.get(actual); loss += -Math.log(Math.max(1e-15, pred)); //cross-entropy (same as log loss) } else { if (model_info.get_params()._autoencoder) throw H2O.unimpl(); //prediction and actual response in standardized response space double pred = neurons[neurons.length - 1]._a.get(0); double actual = myRow.response[0]; // FIXME: re-enable this such that the loss is computed from the de-standardized prediction/response //bring standardized prediction and actual response to real space // DataInfo di = model_info().data_info(); // if (di._normRespMul != null) { //either both are null or none // pred = (pred / di._normRespMul[0] + di._normRespSub[0]); // actual = (actual / di._normRespMul[0] + di._normRespSub[0]); // } Distribution dist = new Distribution(model_info.get_params()._distribution, model_info.get_params()._tweedie_power); pred = dist.linkInv(pred); loss += 0.5 * dist.deviance(1 /*weight*/, actual, pred); } // add L1/L2 penalty of model coefficients (weights & biases) for (int i = 0; i < _parms._hidden.length + 1; ++i) { if (neurons[i]._w == null) continue; for (int row = 0; row < neurons[i]._w.rows(); ++row) { for (int col = 0; col < neurons[i]._w.cols(); ++col) { loss += _parms._l1 * Math.abs(neurons[i]._w.get(row, col)); loss += 0.5 * _parms._l2 * Math.pow(neurons[i]._w.get(row, col), 2); } } for (int row = 0; row < neurons[i]._b.size(); ++row) { loss += _parms._l1 * Math.abs(neurons[i]._b.get(row)); loss += 0.5 * _parms._l2 * Math.pow(neurons[i]._b.get(row), 2); } } } return loss; } /** * Predict from raw double values representing the data * @param data raw array containing categorical values (horizontalized to 1,0,0,1,0,0 etc.) and numerical values (0.35,1.24,5.3234,etc), both can contain NaNs * @param preds predicted label and per-class probabilities (for classification), predicted target (regression), can contain NaNs * @return preds, can contain NaNs */ @Override public double[] score0(double[] data, double[] preds, double weight, double offset) { if (model_info().isUnstable()) { Log.err(unstable_msg); throw new UnsupportedOperationException(unstable_msg); } Neurons[] neurons = DeepLearningTask.makeNeuronsForTesting(model_info); ((Neurons.Input)neurons[0]).setInput(-1, data); DeepLearningTask.step(-1, neurons, model_info, null, false, null, offset); double[] out = neurons[neurons.length - 1]._a.raw(); if (_output.isClassifier()) { assert (preds.length == out.length + 1); for (int i = 0; i < preds.length - 1; ++i) { preds[i + 1] = out[i]; if (Double.isNaN(preds[i + 1])) throw new RuntimeException("Predicted class probability NaN!"); } // label assignment happens later - explicitly mark it as invalid here preds[0] = -1; } else { if (model_info().data_info()._normRespMul != null) //either both are null or none preds[0] = (out[0] / model_info().data_info()._normRespMul[0] + model_info().data_info()._normRespSub[0]); else preds[0] = out[0]; // transform prediction to response space preds[0] = new Distribution(model_info.get_params()._distribution, model_info.get_params()._tweedie_power).linkInv(preds[0]); if (Double.isNaN(preds[0])) throw new RuntimeException("Predicted regression target NaN!"); } return preds; } /** * Score auto-encoded reconstruction (on-the-fly, without allocating the reconstruction as done in Frame score(Frame fr)) * @param frame Original data (can contain response, will be ignored) * @return Frame containing one Vec with reconstruction error (MSE) of each reconstructed row, caller is responsible for deletion */ public Frame scoreAutoEncoder(Frame frame, Key destination_key) { if (!get_params()._autoencoder) throw new H2OIllegalArgumentException("Only for AutoEncoder Deep Learning model.", ""); final int len = _output._names.length; Frame adaptFrm = new Frame(frame); adaptTestForTrain(adaptFrm,true, false); Frame mse = new MRTask() { @Override public void map( Chunk chks[], NewChunk[] mse ) { double tmp [] = new double[len]; final Neurons[] neurons = DeepLearningTask.makeNeuronsForTesting(model_info); for( int row=0; row<chks[0]._len; row++ ) { for( int i=0; i<len; i++ ) tmp[i] = chks[i].atd(row); mse[0].addNum(score_autoencoder(tmp, null, neurons)); } } }.doAll(1,adaptFrm).outputFrame(); Frame res = new Frame(destination_key, new String[]{"Reconstruction.MSE"}, mse.vecs()); DKV.put(res); _output.addModelMetrics(new ModelMetricsAutoEncoder(this, frame, res.vecs()[0].mean() /*mean MSE*/)); return res; } /** * Score auto-encoded reconstruction (on-the-fly, and materialize the deep features of given layer * @param frame Original data (can contain response, will be ignored) * @param layer index of the hidden layer for which to extract the features * @return Frame containing the deep features (#cols = hidden[layer]) */ public Frame scoreDeepFeatures(Frame frame, final int layer) { if (layer < 0 || layer >= model_info().get_params()._hidden.length) throw new H2OIllegalArgumentException("hidden layer (index) to extract must be between " + 0 + " and " + (model_info().get_params()._hidden.length-1),""); final int len = _output.nfeatures(); Vec resp = null; if (isSupervised()) { int ridx = frame.find(_output.responseName()); if (ridx != -1) { // drop the response for scoring! frame = new Frame(frame); resp = frame.vecs()[ridx]; frame.remove(ridx); } } Frame adaptFrm = new Frame(frame); //create new features, will be dense final int features = model_info().get_params()._hidden[layer]; Vec v = adaptFrm.anyVec(); Vec[] vecs = v!=null ? v.makeZeros(features) : null; if (vecs == null) throw new IllegalArgumentException("Cannot create deep features from a frame with no columns."); Scope.enter(); adaptTestForTrain(_output._names, _output.weightsName(), _output.offsetName(), _output.foldName(), null /*don't skip response*/, _output._domains, adaptFrm, _parms.missingColumnsType(), true, true); for (int j=0; j<features; ++j) { adaptFrm.add("DF.L"+(layer+1)+".C" + (j+1), vecs[j]); } new MRTask() { @Override public void map( Chunk chks[] ) { double tmp [] = new double[len]; final Neurons[] neurons = DeepLearningTask.makeNeuronsForTesting(model_info); for( int row=0; row<chks[0]._len; row++ ) { for( int i=0; i<len; i++ ) tmp[i] = chks[i].atd(row); ((Neurons.Input)neurons[0]).setInput(-1, tmp); //FIXME: No weights yet DeepLearningTask.step(-1, neurons, model_info, null, false, null, 0 /*no offset*/); double[] out = neurons[layer+1]._a.raw(); //extract the layer-th hidden feature for( int c=0; c<features; c++ ) chks[_output._names.length+c].set(row,out[c]); } } }.doAll(adaptFrm); // Return just the output columns int x=_output._names.length, y=adaptFrm.numCols(); Frame ret = adaptFrm.extractFrame(x, y); if (resp != null) ret.prepend(_output.responseName(), resp); Scope.exit(); return ret; } // Make (potentially expanded) reconstruction private double[] score_autoencoder(Chunk[] chks, int row_in_chunk, double[] tmp, double[] preds, Neurons[] neurons) { assert(get_params()._autoencoder); assert(tmp.length == _output._names.length); for( int i=0; i<tmp.length; i++ ) tmp[i] = chks[i].atd(row_in_chunk); score_autoencoder(tmp, preds, neurons); // this fills preds, returns MSE error (ignored here) return preds; } /** * Helper to reconstruct original data into preds array and compute the reconstruction error (MSE) * @param data Original data (unexpanded) * @param preds Reconstruction (potentially expanded) * @return reconstruction error */ private double score_autoencoder(double[] data, double[] preds, Neurons[] neurons) { assert(model_info().get_params()._autoencoder); if (model_info().isUnstable()) { Log.err(unstable_msg); throw new UnsupportedOperationException(unstable_msg); } ((Neurons.Input)neurons[0]).setInput(-1, data); // FIXME - no weights yet DeepLearningTask.step(-1, neurons, model_info, null, false, null, 0 /*no offset*/); // reconstructs data in expanded space double[] in = neurons[0]._a.raw(); //input (expanded) double[] out = neurons[neurons.length - 1]._a.raw(); //output (expanded) assert(in.length == out.length); // First normalize categorical reconstructions to be probabilities // (such that they can be better compared to the input where one factor was 1 and the rest was 0) // model_info().data_info().softMaxCategoricals(out,out); //only modifies the categoricals // Compute MSE of reconstruction in expanded space (with categorical probabilities) double l2 = 0; for (int i = 0; i < in.length; ++i) l2 += Math.pow((out[i] - in[i]), 2); l2 /= in.length; if (preds!=null) { // Now scale back numerical columns to original data space (scale + shift) model_info().data_info().unScaleNumericals(out, out); //only modifies the numericals System.arraycopy(out, 0, preds, 0, out.length); //copy reconstruction into preds } return l2; } /** * Compute quantile-based threshold (in reconstruction error) to find outliers * @param mse Vector containing reconstruction errors * @param quantile Quantile for cut-off * @return Threshold in MSE value for a point to be above the quantile */ public double calcOutlierThreshold(Vec mse, double quantile) { Frame mse_frame = new Frame(Key.make(), new String[]{"Reconstruction.MSE"}, new Vec[]{mse}); DKV.put(mse_frame._key, mse_frame); QuantileModel.QuantileParameters parms = new QuantileModel.QuantileParameters(); parms._train = mse_frame._key; parms._probs = new double[]{quantile}; Job<QuantileModel> job = new Quantile(parms).trainModel(); QuantileModel kmm = job.get(); job.remove(); double q = kmm._output._quantiles[0][0]; kmm.delete(); DKV.remove(mse_frame._key); return q; } // helper to push this model to another key (for keeping good models) private void putMeAsBestModel(Key bestModelKey) { DeepLearningModel bestModel = new DeepLearningModel(bestModelKey, null, this, true, model_info().data_info()); DKV.put(bestModel._key, bestModel); if (model_info().get_params()._elastic_averaging) { DeepLearningModelInfo eamodel = DKV.getGet(model_info.elasticAverageModelInfoKey()); if (eamodel != null) DKV.put(bestModel.model_info().elasticAverageModelInfoKey(), eamodel); } assert (DKV.get(bestModelKey) != null); assert (bestModel.compareTo(this) <= 0); } @Override public void delete() { if (_output.weights != null && _output.biases != null) { for (Key k : _output.weights) { if (DKV.getGet(k) != null) ((Frame) DKV.getGet(k)).delete(); } for (Key k : _output.biases) { if (DKV.getGet(k) != null) ((Frame) DKV.getGet(k)).delete(); } } DKV.remove(model_info().data_info()._key); deleteElasticAverageModels(); super.delete(); } void deleteElasticAverageModels() { if (model_info().get_params()._elastic_averaging) { DKV.remove(model_info().elasticAverageModelInfoKey()); for (H2ONode node : H2O.CLOUD._memary) { DKV.remove(model_info().localModelInfoKey(node)); } } } private String getHeader() { assert get_params()._autoencoder; StringBuilder sb = new StringBuilder(); final int len = model_info().data_info().fullN(); String prefix = "reconstr_"; assert (model_info().data_info()._responses == 0); String[] coefnames = model_info().data_info().coefNames(); assert (len == coefnames.length); for (int c = 0; c < len; c++) { if (c>0) sb.append(","); sb.append(prefix).append(coefnames[c]); } return sb.toString(); } @Override protected SB toJavaInit(SB sb, SB fileContextSB) { sb = super.toJavaInit(sb, fileContextSB); String mname = JCodeGen.toJavaId(_key.toString()); Neurons[] neurons = DeepLearningTask.makeNeuronsForTesting(model_info()); final DeepLearningParameters p = model_info.get_params(); sb.ip("public boolean isSupervised() { return " + isSupervised() + "; }").nl(); sb.ip("public int nfeatures() { return "+_output.nfeatures()+"; }").nl(); sb.ip("public int nclasses() { return "+ (p._autoencoder ? neurons[neurons.length-1].units : _output.nclasses()) + "; }").nl(); if (model_info().data_info()._nums > 0) { JCodeGen.toStaticVar(sb, "NUMS", new double[model_info().data_info()._nums], "Workspace for storing numerical input variables."); JCodeGen.toStaticVar(sb, "NORMMUL", model_info().data_info()._normMul, "Standardization/Normalization scaling factor for numerical variables."); JCodeGen.toStaticVar(sb, "NORMSUB", model_info().data_info()._normSub, "Standardization/Normalization offset for numerical variables."); } if (model_info().data_info()._cats > 0) { JCodeGen.toStaticVar(sb, "CATS", new int[model_info().data_info()._cats], "Workspace for storing categorical input variables."); } JCodeGen.toStaticVar(sb, "CATOFFSETS", model_info().data_info()._catOffsets, "Workspace for categorical offsets."); if (model_info().data_info()._normRespMul != null) { JCodeGen.toStaticVar(sb, "NORMRESPMUL", model_info().data_info()._normRespMul, "Standardization/Normalization scaling factor for response."); JCodeGen.toStaticVar(sb, "NORMRESPSUB", model_info().data_info()._normRespSub, "Standardization/Normalization offset for response."); } if (p._hidden_dropout_ratios != null) { JCodeGen.toStaticVar(sb, "HIDDEN_DROPOUT_RATIOS", p._hidden_dropout_ratios, "Hidden layer dropout ratios."); } int[] layers = new int[neurons.length]; for (int i=0;i<neurons.length;++i) layers[i] = neurons[i].units; JCodeGen.toStaticVar(sb, "NEURONS", layers, "Number of neurons for each layer."); if (get_params()._autoencoder) { sb.i(1).p("public int getPredsSize() { return " + model_info.units[model_info.units.length-1] + "; }").nl(); sb.i(1).p("public boolean isAutoEncoder() { return true; }").nl(); sb.i(1).p("public String getHeader() { return \"" + getHeader() + "\"; }").nl(); } // activation storage sb.i(1).p("// Storage for neuron activation values.").nl(); sb.i(1).p("public static final double[][] ACTIVATION = new double[][] {").nl(); for (int i=0; i<neurons.length; i++) { String colInfoClazz = mname + "_Activation_"+i; sb.i(2).p("/* ").p(neurons[i].getClass().getSimpleName()).p(" */ "); sb.p(colInfoClazz).p(".VALUES"); if (i!=neurons.length-1) sb.p(','); sb.nl(); fileContextSB.i().p("// Neuron activation values for ").p(neurons[i].getClass().getSimpleName()).p(" layer").nl(); JCodeGen.toClassWithArray(fileContextSB, null, colInfoClazz, new double[layers[i]]); } sb.i(1).p("};").nl(); // biases sb.i(1).p("// Neuron bias values.").nl(); sb.i(1).p("public static final double[][] BIAS = new double[][] {").nl(); for (int i=0; i<neurons.length; i++) { String colInfoClazz = mname + "_Bias_"+i; sb.i(2).p("/* ").p(neurons[i].getClass().getSimpleName()).p(" */ "); sb.p(colInfoClazz).p(".VALUES"); if (i!=neurons.length-1) sb.p(','); sb.nl(); fileContextSB.i().p("// Neuron bias values for ").p(neurons[i].getClass().getSimpleName()).p(" layer").nl(); double[] bias = i == 0 ? null : new double[model_info().get_biases(i-1).size()]; if (i>0) { for (int j=0; j<bias.length; ++j) bias[j] = model_info().get_biases(i-1).get(j); } JCodeGen.toClassWithArray(fileContextSB, null, colInfoClazz, bias); } sb.i(1).p("};").nl(); // weights sb.i(1).p("// Connecting weights between neurons.").nl(); sb.i(1).p("public static final float[][] WEIGHT = new float[][] {").nl(); for (int i=0; i<neurons.length; i++) { String colInfoClazz = mname + "_Weight_"+i; sb.i(2).p("/* ").p(neurons[i].getClass().getSimpleName()).p(" */ "); sb.p(colInfoClazz).p(".VALUES"); if (i!=neurons.length-1) sb.p(','); sb.nl(); if (i > 0) { fileContextSB.i().p("// Neuron weights connecting "). p(neurons[i - 1].getClass().getSimpleName()).p(" and "). p(neurons[i].getClass().getSimpleName()). p(" layer").nl(); } float[] weights = i == 0 ? null : new float[model_info().get_weights(i-1).rows()*model_info().get_weights(i-1).cols()]; if (i>0) { final int rows = model_info().get_weights(i-1).rows(); final int cols = model_info().get_weights(i-1).cols(); for (int j=0; j<rows; ++j) for (int k=0; k<cols; ++k) weights[j*cols+k] = model_info().get_weights(i-1).get(j,k); } JCodeGen.toClassWithArray(fileContextSB, null, colInfoClazz, weights); } sb.i(1).p("};").nl(); return sb; } @Override protected boolean toJavaCheckTooBig() { return (model_info.size() > 1e6); } private SB pureMatVec(final SB bodySb) { bodySb.i(1).p("int cols = ACTIVATION[i-1].length;").nl(); bodySb.i(1).p("int rows = ACTIVATION[i].length;").nl(); bodySb.i(1).p("int extra=cols-cols%8;").nl(); bodySb.i(1).p("int multiple = (cols/8)*8-1;").nl(); bodySb.i(1).p("int idx = 0;").nl(); bodySb.i(1).p("float[] a = WEIGHT[i];").nl(); bodySb.i(1).p("double[] x = ACTIVATION[i-1];").nl(); bodySb.i(1).p("double[] y = BIAS[i];").nl(); bodySb.i(1).p("double[] res = ACTIVATION[i];").nl(); bodySb.i(1).p("for (int row=0; row<rows; ++row) {").nl(); bodySb.i(2).p("double psum0 = 0, psum1 = 0, psum2 = 0, psum3 = 0, psum4 = 0, psum5 = 0, psum6 = 0, psum7 = 0;").nl(); bodySb.i(2).p("for (int col = 0; col < multiple; col += 8) {").nl(); bodySb.i(3).p("int off = idx + col;").nl(); bodySb.i(3).p("psum0 += a[off ] * x[col ];").nl(); bodySb.i(3).p("psum1 += a[off + 1] * x[col + 1];").nl(); bodySb.i(3).p("psum2 += a[off + 2] * x[col + 2];").nl(); bodySb.i(3).p("psum3 += a[off + 3] * x[col + 3];").nl(); bodySb.i(3).p("psum4 += a[off + 4] * x[col + 4];").nl(); bodySb.i(3).p("psum5 += a[off + 5] * x[col + 5];").nl(); bodySb.i(3).p("psum6 += a[off + 6] * x[col + 6];").nl(); bodySb.i(3).p("psum7 += a[off + 7] * x[col + 7];").nl(); bodySb.i(2).p("}").nl(); bodySb.i(2).p("res[row] += psum0 + psum1 + psum2 + psum3;").nl(); bodySb.i(2).p("res[row] += psum4 + psum5 + psum6 + psum7;").nl(); bodySb.i(2).p("for (int col = extra; col < cols; col++)").nl(); bodySb.i(3).p("res[row] += a[idx + col] * x[col];").nl(); bodySb.i(2).p("res[row] += y[row];").nl(); bodySb.i(2).p("idx += cols;").nl(); bodySb.i(1).p("}").nl(); return bodySb; } @Override protected void toJavaPredictBody( final SB bodySb, final SB classCtxSb, final SB fileCtxSb) { SB model = new SB(); final DeepLearningParameters p = model_info.get_params(); bodySb.i().p("java.util.Arrays.fill(preds,0);").nl(); final int cats = model_info().data_info()._cats; final int nums = model_info().data_info()._nums; // initialize input layer if (nums > 0) bodySb.i().p("java.util.Arrays.fill(NUMS,0);").nl(); if (cats > 0) bodySb.i().p("java.util.Arrays.fill(CATS,0);").nl(); bodySb.i().p("int i = 0, ncats = 0;").nl(); if (cats > 0) { bodySb.i().p("for(; i<"+cats+"; ++i) {").nl(); bodySb.i(1).p("if (!Double.isNaN(data[i])) {").nl(); bodySb.i(2).p("int c = (int) data[i];").nl(); if (model_info().data_info()._useAllFactorLevels) bodySb.i(2).p("CATS[ncats++] = c + CATOFFSETS[i];").nl(); else bodySb.i(2).p("if (c != 0) CATS[ncats++] = c + CATOFFSETS[i] - 1;").nl(); bodySb.i(1).p("}").nl(); bodySb.i().p("}").nl(); } if (nums > 0) { bodySb.i().p("final int n = data.length;").nl(); bodySb.i().p("for(; i<n; ++i) {").nl(); bodySb.i(1).p("NUMS[i" + (cats > 0 ? "-" + cats : "") + "] = Double.isNaN(data[i]) ? 0 : "); if (model_info().data_info()._normMul != null) { bodySb.p("(data[i] - NORMSUB[i" + (cats > 0 ? "-" + cats : "") + "])*NORMMUL[i" + (cats > 0 ? "-" + cats : "") + "];").nl(); } else { bodySb.p("data[i];").nl(); } bodySb.i(0).p("}").nl(); } bodySb.i().p("java.util.Arrays.fill(ACTIVATION[0],0);").nl(); if (cats > 0) { bodySb.i().p("for (i=0; i<ncats; ++i) ACTIVATION[0][CATS[i]] = 1;").nl(); } if (nums > 0) { bodySb.i().p("for (i=0; i<NUMS.length; ++i) {").nl(); bodySb.i(1).p("ACTIVATION[0][CATOFFSETS[CATOFFSETS.length-1] + i] = Double.isNaN(NUMS[i]) ? 0 : NUMS[i];").nl(); bodySb.i().p("}").nl(); } boolean tanh=(p._activation == DeepLearningParameters.Activation.Tanh || p._activation == DeepLearningParameters.Activation.TanhWithDropout); boolean relu=(p._activation == DeepLearningParameters.Activation.Rectifier || p._activation == DeepLearningParameters.Activation.RectifierWithDropout); boolean maxout=(p._activation == DeepLearningParameters.Activation.Maxout || p._activation == DeepLearningParameters.Activation.MaxoutWithDropout); final String stopping = p._autoencoder ? "(i<=ACTIVATION.length-1)" : "(i<ACTIVATION.length-1)"; // make prediction: forward propagation bodySb.i().p("for (i=1; i<ACTIVATION.length; ++i) {").nl(); bodySb.i(1).p("java.util.Arrays.fill(ACTIVATION[i],0);").nl(); if (maxout) { bodySb.i(1).p("int _k = 2; // channels").nl(); bodySb.i(1).p("if " + stopping + " {").nl(); bodySb.i(2).p("double[] channel = new double[_k];").nl(); bodySb.i(2).p("for (int r=0; r<ACTIVATION[i].length; ++r) {").nl(); bodySb.i(3).p("final int cols = ACTIVATION[i-1].length;").nl(); bodySb.i(3).p("short maxK = 0;").nl(); bodySb.i(3).p("for (short k = 0; k < _k; ++k) {").nl(); bodySb.i(4).p("channel[k] = 0;").nl(); bodySb.i(4).p("for (int c=0; c<cols; ++c) {").nl(); bodySb.i(5).p("channel[k] += WEIGHT[i][_k*(r * cols + c) + k] * ACTIVATION[i-1][c];").nl(); bodySb.i(4).p("}").nl(); bodySb.i(4).p("channel[k] += BIAS[i][_k*r+k];").nl(); bodySb.i(4).p("if (channel[k] > channel[maxK]) maxK=k;").nl(); bodySb.i(3).p("}").nl(); bodySb.i(3).p("ACTIVATION[i][r] = channel[maxK];").nl(); } else { // optimized pureMatVec(bodySb); // Activation function bodySb.i(1).p("if " + stopping + " {").nl(); bodySb.i(2).p("for (int r=0; r<ACTIVATION[i].length; ++r) {").nl(); if (tanh) { bodySb.i(3).p("ACTIVATION[i][r] = 1 - 2 / (1 + Math.exp(2*ACTIVATION[i][r]));").nl(); } else if (relu) { bodySb.i(3).p("ACTIVATION[i][r] = Math.max(0, ACTIVATION[i][r]);").nl(); } } if (p._hidden_dropout_ratios != null) { bodySb.i(3).p("if (i<ACTIVATION.length-1) {").nl(); bodySb.i(4).p("ACTIVATION[i][r] *= HIDDEN_DROPOUT_RATIOS[i-1];").nl(); bodySb.i(3).p("}").nl(); } bodySb.i(2).p("}").nl(); bodySb.i(1).p("}").nl(); if (maxout) { bodySb.i(1).p("if (i == ACTIVATION.length-1) {").nl(); pureMatVec(bodySb); bodySb.i(1).p("}").nl(); } if (_output.isClassifier()) { bodySb.i(1).p("if (i == ACTIVATION.length-1) {").nl(); // softmax bodySb.i(2).p("double max = ACTIVATION[i][0];").nl(); bodySb.i(2).p("for (int r=1; r<ACTIVATION[i].length; r++) {").nl(); bodySb.i(3).p("if (ACTIVATION[i][r]>max) max = ACTIVATION[i][r];").nl(); bodySb.i(2).p("}").nl(); bodySb.i(2).p("double scale = 0;").nl(); bodySb.i(2).p("for (int r=0; r<ACTIVATION[i].length; r++) {").nl(); bodySb.i(3).p("ACTIVATION[i][r] = Math.exp(ACTIVATION[i][r] - max);").nl(); bodySb.i(3).p("scale += ACTIVATION[i][r];").nl(); bodySb.i(2).p("}").nl(); bodySb.i(2).p("for (int r=0; r<ACTIVATION[i].length; r++) {").nl(); bodySb.i(3).p("if (Double.isNaN(ACTIVATION[i][r]))").nl(); bodySb.i(4).p("throw new RuntimeException(\"Numerical instability, predicted NaN.\");").nl(); bodySb.i(3).p("ACTIVATION[i][r] /= scale;").nl(); bodySb.i(3).p("preds[r+1] = ACTIVATION[i][r];").nl(); bodySb.i(2).p("}").nl(); bodySb.i(1).p("}").nl(); bodySb.i().p("}").nl(); } else if (!p._autoencoder) { //Regression bodySb.i(1).p("if (i == ACTIVATION.length-1) {").nl(); // regression: set preds[1], FillPreds0 will put it into preds[0] if (model_info().data_info()._normRespMul != null) { bodySb.i(2).p("preds[1] = (ACTIVATION[i][0] / NORMRESPMUL[0] + NORMRESPSUB[0]);").nl(); } else { bodySb.i(2).p("preds[1] = ACTIVATION[i][0];").nl(); } bodySb.i(2).p("preds[1] = " + new Distribution(model_info.get_params()._distribution, model_info.get_params()._tweedie_power).linkInvString("preds[1]")+";").nl(); bodySb.i(2).p("if (Double.isNaN(preds[1])) throw new RuntimeException(\"Predicted regression target NaN!\");").nl(); bodySb.i(1).p("}").nl(); bodySb.i().p("}").nl(); } else { //AutoEncoder bodySb.i(1).p("if (i == ACTIVATION.length-1) {").nl(); bodySb.i(2).p("for (int r=0; r<ACTIVATION[i].length; r++) {").nl(); bodySb.i(3).p("if (Double.isNaN(ACTIVATION[i][r]))").nl(); bodySb.i(4).p("throw new RuntimeException(\"Numerical instability, reconstructed NaN.\");").nl(); bodySb.i(3).p("preds[r] = ACTIVATION[i][r];").nl(); bodySb.i(2).p("}").nl(); if (model_info().data_info()._nums > 0) { int ns = model_info().data_info().numStart(); bodySb.i(2).p("for (int k=" + ns + "; k<" + model_info().data_info().fullN() + "; ++k) {").nl(); bodySb.i(3).p("preds[k] = preds[k] / NORMMUL[k-" + ns + "] + NORMSUB[k-" + ns + "];").nl(); bodySb.i(2).p("}").nl(); } bodySb.i(1).p("}").nl(); bodySb.i().p("}").nl(); // DEBUGGING // bodySb.i().p("System.out.println(java.util.Arrays.toString(data));").nl(); // bodySb.i().p("System.out.println(java.util.Arrays.toString(ACTIVATION[0]));").nl(); // bodySb.i().p("System.out.println(java.util.Arrays.toString(ACTIVATION[ACTIVATION.length-1]));").nl(); // bodySb.i().p("System.out.println(java.util.Arrays.toString(preds));").nl(); // bodySb.i().p("System.out.println(\"\");").nl(); } fileCtxSb.p(model); if (_output.autoencoder) return; if (_output.isClassifier()) { if (_parms._balance_classes) bodySb.ip("hex.genmodel.GenModel.correctProbabilities(preds, PRIOR_CLASS_DISTRIB, MODEL_CLASS_DISTRIB);").nl(); bodySb.ip("preds[0] = hex.genmodel.GenModel.getPrediction(preds, PRIOR_CLASS_DISTRIB, data, " + defaultThreshold()+");").nl(); } else { bodySb.ip("preds[0] = preds[1];").nl(); } } private final String unstable_msg = technote(4, "\n\nTrying to predict with an unstable model." + "\nJob was aborted due to observed numerical instability (exponential growth)." + "\nEither the weights or the bias values are unreasonably large or lead to large activation values." + "\nTry a different initial distribution, a bounded activation function (Tanh), adding regularization" + "\n(via max_w2, l1, l2, dropout) or learning rate (either enable adaptive_rate or use a smaller learning rate or faster annealing)."); @Override protected long checksum_impl() { return super.checksum_impl() * model_info.checksum_impl(); } }
h2o-algos/src/main/java/hex/deeplearning/DeepLearningModel.java
package hex.deeplearning; import hex.*; import hex.quantile.Quantile; import hex.quantile.QuantileModel; import hex.schemas.DeepLearningModelV3; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import water.*; import water.api.ModelSchema; import water.exceptions.H2OIllegalArgumentException; import water.fvec.Chunk; import water.fvec.Frame; import water.fvec.NewChunk; import water.fvec.Vec; import water.util.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static hex.ModelMetrics.calcVarImp; import static hex.deeplearning.DeepLearning.makeDataInfo; import static water.H2O.technote; /** * The Deep Learning model * It contains a DeepLearningModelInfo with the most up-to-date model, * a scoring history, as well as some helpers to indicate the progress */ public class DeepLearningModel extends Model<DeepLearningModel,DeepLearningParameters,DeepLearningModel.DeepLearningModelOutput> implements Model.DeepFeatures { /** * The Deep Learning model output contains a few extra fields in addition to the metrics in Model.Output * 1) Scoring history (raw data) * 2) weights/biases (raw data) * 3) variable importances (TwoDimTable) */ public static class DeepLearningModelOutput extends Model.Output { /** * For autoencoder, there's no response. * Otherwise, there's 1 response at the end, and no other reserved columns in the data * @return Number of features (possible predictors) */ public DeepLearningModelOutput() { super(); autoencoder = false;} public DeepLearningModelOutput(DeepLearning b) { super(b); autoencoder = b._parms._autoencoder; assert b.isSupervised() == !autoencoder; } final boolean autoencoder; DeepLearningScoring errors; Key[] weights; Key[] biases; double[] normmul; double[] normsub; double[] normrespmul; double[] normrespsub; int[] catoffsets; public TwoDimTable _variable_importances; @Override public ModelCategory getModelCategory() { return autoencoder ? ModelCategory.AutoEncoder : super.getModelCategory(); } @Override public boolean isSupervised() { return !autoencoder; } } @Override public double deviance(double w, double y, double f) { // Note: Must use sanitized parameters via get_params() as this._params can still have defaults AUTO, etc.) assert(get_params()._distribution != Distribution.Family.AUTO); return new Distribution(get_params()._distribution, get_params()._tweedie_power).deviance(w,y,f); } // Default publicly visible Schema is V2 public ModelSchema schema() { return new DeepLearningModelV3(); } void set_model_info(DeepLearningModelInfo mi) { assert(mi != null); model_info = mi; } final public DeepLearningModelInfo model_info() { return model_info; } final public VarImp varImp() { return _output.errors.variable_importances; } private volatile DeepLearningModelInfo model_info; public long run_time; private long start_time; public long actual_train_samples_per_iteration; public long tspiGuess; public double time_for_communication_us; //helper for auto-tuning: time in microseconds for collective bcast/reduce of the model public double epoch_counter; public boolean stopped_early; public long training_rows; public long validation_rows; private DeepLearningScoring[] errors; public DeepLearningScoring[] scoring_history() { return errors; } // Keep the best model so far, based on a single criterion (overall class. error or MSE) private float _bestError = Float.POSITIVE_INFINITY; public Key actual_best_model_key; public Key model_info_key; // return the most up-to-date model metrics DeepLearningScoring last_scored() { return errors == null ? null : errors[errors.length-1]; } /** * Get the parameters actually used for model building, not the user-given ones (_parms) * They might differ since some defaults are filled in, and some invalid combinations are auto-disabled in modifyParams * @return actually used parameters */ public final DeepLearningParameters get_params() { return model_info.get_params(); } // Lower is better public float error() { return (float) (_output.isClassifier() ? classification_error() : deviance()); } @Override public ModelMetrics.MetricBuilder makeMetricBuilder(String[] domain) { switch(_output.getModelCategory()) { case Binomial: return new ModelMetricsBinomial.MetricBuilderBinomial(domain); case Multinomial: return new ModelMetricsMultinomial.MetricBuilderMultinomial(_output.nclasses(),domain); case Regression: return new ModelMetricsRegression.MetricBuilderRegression(); case AutoEncoder: return new ModelMetricsAutoEncoder.MetricBuilderAutoEncoder(_output.nfeatures()); default: throw H2O.unimpl("Invalid ModelCategory " + _output.getModelCategory()); } } public int compareTo(DeepLearningModel o) { if (o._output.isClassifier() != _output.isClassifier()) throw new UnsupportedOperationException("Cannot compare classifier against regressor."); if (o._output.nclasses() != _output.nclasses()) throw new UnsupportedOperationException("Cannot compare models with different number of classes."); return (error() < o.error() ? -1 : error() > o.error() ? 1 : 0); } public static class DeepLearningScoring extends Iced { public double epoch_counter; public double training_samples; public long training_time_ms; boolean validation; public long score_training_samples; public long score_validation_samples; public boolean classification; VarImp variable_importances; ScoreKeeper scored_train = new ScoreKeeper(); ScoreKeeper scored_valid = new ScoreKeeper(); public AUC2 training_AUC; public AUC2 validation_AUC; public long scoring_time; DeepLearningScoring deep_clone() { AutoBuffer ab = new AutoBuffer(); this.write(ab); ab.flipForReading(); return (DeepLearningScoring) new DeepLearningScoring().read(ab); } } public double classification_error() { if (errors == null) return Double.NaN; return last_scored().validation ? last_scored().scored_valid._classError : last_scored().scored_train._classError; } public double mse() { if (errors == null) return Double.NaN; return last_scored().validation ? last_scored().scored_valid._mse : last_scored().scored_train._mse; } public double deviance() { if (errors == null) return Double.NaN; return last_scored().validation ? last_scored().scored_valid._mean_residual_deviance : last_scored().scored_train._mean_residual_deviance; } public double logloss() { if (errors == null) return Double.NaN; return last_scored().validation ? last_scored().scored_valid._logloss : last_scored().scored_train._logloss; } private TwoDimTable createScoringHistoryTable(DeepLearningScoring[] errors) { List<String> colHeaders = new ArrayList<>(); List<String> colTypes = new ArrayList<>(); List<String> colFormat = new ArrayList<>(); colHeaders.add("Timestamp"); colTypes.add("string"); colFormat.add("%s"); colHeaders.add("Duration"); colTypes.add("string"); colFormat.add("%s"); colHeaders.add("Training Speed"); colTypes.add("string"); colFormat.add("%s"); colHeaders.add("Epochs"); colTypes.add("double"); colFormat.add("%.5f"); colHeaders.add("Samples"); colTypes.add("double"); colFormat.add("%f"); colHeaders.add("Training MSE"); colTypes.add("double"); colFormat.add("%.5f"); if (_output.getModelCategory() == ModelCategory.Regression) { colHeaders.add("Training Deviance"); colTypes.add("double"); colFormat.add("%.5f"); } if (!_output.autoencoder) { colHeaders.add("Training R^2"); colTypes.add("double"); colFormat.add("%.5f"); } if (_output.isClassifier()) { colHeaders.add("Training LogLoss"); colTypes.add("double"); colFormat.add("%.5f"); } if (_output.getModelCategory() == ModelCategory.Binomial) { colHeaders.add("Training AUC"); colTypes.add("double"); colFormat.add("%.5f"); } if (_output.getModelCategory() == ModelCategory.Binomial || _output.getModelCategory() == ModelCategory.Multinomial) { colHeaders.add("Training Classification Error"); colTypes.add("double"); colFormat.add("%.5f"); } if (get_params()._valid != null) { colHeaders.add("Validation MSE"); colTypes.add("double"); colFormat.add("%.5f"); if (_output.getModelCategory() == ModelCategory.Regression) { colHeaders.add("Validation Deviance"); colTypes.add("double"); colFormat.add("%.5f"); } if (!_output.autoencoder) { colHeaders.add("Validation R^2"); colTypes.add("double"); colFormat.add("%.5f"); } if (_output.isClassifier()) { colHeaders.add("Validation LogLoss"); colTypes.add("double"); colFormat.add("%.5f"); } if (_output.getModelCategory() == ModelCategory.Binomial) { colHeaders.add("Validation AUC"); colTypes.add("double"); colFormat.add("%.5f"); } if (_output.isClassifier()) { colHeaders.add("Validation Classification Error"); colTypes.add("double"); colFormat.add("%.5f"); } } else if (get_params()._nfolds > 1) { // colHeaders.add("Cross-Validation MSE"); colTypes.add("double"); colFormat.add("%.5f"); //// colHeaders.add("Validation R^2"); colTypes.add("double"); colFormat.add("%g"); // if (_output.getModelCategory() == ModelCategory.Binomial) { // colHeaders.add("Cross-Validation AUC"); // colTypes.add("double"); // colFormat.add("%.5f"); // } // if (_output.isClassifier()) { // colHeaders.add("Cross-Validation Classification Error"); // colTypes.add("double"); // colFormat.add("%.5f"); // } } final int rows = errors.length; TwoDimTable table = new TwoDimTable( "Scoring History", null, new String[rows], colHeaders.toArray(new String[0]), colTypes.toArray(new String[0]), colFormat.toArray(new String[0]), ""); int row = 0; for( int i = 0; i<errors.length ; i++ ) { final DeepLearningScoring e = errors[i]; int col = 0; assert(row < table.getRowDim()); assert(col < table.getColDim()); DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); table.set(row, col++, fmt.print(start_time + e.training_time_ms)); table.set(row, col++, PrettyPrint.msecs(e.training_time_ms, true)); table.set(row, col++, e.training_time_ms == 0 ? null : (String.format("%.3f", e.training_samples/(e.training_time_ms/1e3)) + " rows/sec")); table.set(row, col++, e.epoch_counter); table.set(row, col++, e.training_samples); table.set(row, col++, e.scored_train != null ? e.scored_train._mse : Double.NaN); if (_output.getModelCategory() == ModelCategory.Regression) { table.set(row, col++, e.scored_train != null ? e.scored_train._mean_residual_deviance : Double.NaN); } if (!_output.autoencoder) { table.set(row, col++, e.scored_train != null ? e.scored_train._r2 : Double.NaN); } if (_output.isClassifier()) { table.set(row, col++, e.scored_train != null ? e.scored_train._logloss : Double.NaN); } if (_output.getModelCategory() == ModelCategory.Binomial) { table.set(row, col++, e.training_AUC != null ? e.training_AUC._auc : Double.NaN); } if (_output.isClassifier()) { table.set(row, col++, e.scored_train != null ? e.scored_train._classError : Double.NaN); } if (get_params()._valid != null) { table.set(row, col++, e.scored_valid != null ? e.scored_valid._mse : Double.NaN); if (_output.getModelCategory() == ModelCategory.Regression) { table.set(row, col++, e.scored_valid != null ? e.scored_valid._mean_residual_deviance : Double.NaN); } if (!_output.autoencoder) { table.set(row, col++, e.scored_valid != null ? e.scored_valid._r2 : Double.NaN); } if (_output.isClassifier()) { table.set(row, col++, e.scored_valid != null ? e.scored_valid._logloss : Double.NaN); } if (_output.getModelCategory() == ModelCategory.Binomial) { table.set(row, col++, e.validation_AUC != null ? e.validation_AUC._auc : Double.NaN); } if (_output.isClassifier()) { table.set(row, col++, e.scored_valid != null ? e.scored_valid._classError : Double.NaN); } } row++; } return table; } /** * Helper to allocate keys for output frames for weights and biases * @param destKey */ private void makeWeightsBiases(Key destKey) { if (!model_info.get_params()._export_weights_and_biases) { _output.weights = null; _output.biases = null; _output.normmul = null; _output.normsub = null; _output.normrespmul = null; _output.normrespsub = null; _output.catoffsets = null; } else { _output.weights = new Key[model_info.get_params()._hidden.length + 1]; for (int i = 0; i < _output.weights.length; ++i) { _output.weights[i] = Key.makeUserHidden(Key.make(destKey + ".weights." + i)); } _output.biases = new Key[model_info.get_params()._hidden.length + 1]; for (int i = 0; i < _output.biases.length; ++i) { _output.biases[i] = Key.makeUserHidden(Key.make(destKey + ".biases." + i)); } _output.normmul = model_info.data_info._normMul; _output.normsub = model_info.data_info._normSub; _output.normrespmul = model_info.data_info._normRespMul; _output.normrespsub = model_info.data_info._normRespSub; _output.catoffsets = model_info.data_info._catOffsets; } } /** Constructor to restart from a checkpointed model * @param destKey New destination key for the model * @param parms User-given parameters for checkpoint restart * @param cp Checkpoint to restart from * @param store_best_model Store only the best model instead of the latest one */ public DeepLearningModel(final Key destKey, final DeepLearningParameters parms, final DeepLearningModel cp, final boolean store_best_model, final DataInfo dataInfo) { super(destKey, parms == null ? (DeepLearningParameters)cp._parms.clone() : parms, (DeepLearningModelOutput)cp._output.clone()); assert(_parms != cp._parms); //make sure we have a clone model_info = cp.model_info.deep_clone(); //don't want to interfere with model being built, just make a deep copy and store that if (store_best_model) { model_info.data_info = dataInfo.deep_clone(); //replace previous data_info with updated version that's passed in (contains enum for classification) } else { model_info.data_info = dataInfo; //shallow clone is ok if (parms != null) { assert (_parms == parms); assert (_parms._checkpoint == parms._checkpoint); assert (_parms._checkpoint == cp._key); } // _parms._checkpoint = cp._key; //it's only a "real" checkpoint if job != null, otherwise a best model copy } DKV.put(dataInfo); assert(model_info().get_params() != cp.model_info().get_params()); //make sure we have a clone actual_best_model_key = cp.actual_best_model_key; start_time = cp.start_time; run_time = cp.run_time; training_rows = cp.training_rows; //copy the value to display the right number on the model page before training has started validation_rows = cp.validation_rows; //copy the value to display the right number on the model page before training has started _bestError = cp._bestError; epoch_counter = cp.epoch_counter; // deep clone scoring history errors = cp.errors.clone(); for (int i=0; i<errors.length;++i) errors[i] = cp.errors[i].deep_clone(); _output.errors = last_scored(); makeWeightsBiases(destKey); _output._scoring_history = createScoringHistoryTable(errors); _output._variable_importances = calcVarImp(last_scored().variable_importances); _output._names = dataInfo._adaptedFrame.names(); _output._domains = dataInfo._adaptedFrame.domains(); // set proper timing _timeLastScoreEnter = System.currentTimeMillis(); _timeLastScoreStart = 0; _timeLastScoreEnd = 0; _timeLastPrintStart = 0; assert(Arrays.equals(_key._kb, destKey._kb)); } /** * Regular constructor (from scratch) * @param destKey * @param parms * @param output * @param train * @param valid * @param nClasses */ public DeepLearningModel(final Key destKey, final DeepLearningParameters parms, final DeepLearningModelOutput output, Frame train, Frame valid, int nClasses) { super(destKey, parms, output); final DataInfo dinfo = makeDataInfo(train, valid, _parms); _output._names = train._names ; // Since changed by DataInfo, need to be reflected in the Model output as well _output._domains= train.domains(); _output._names = dinfo._adaptedFrame.names(); _output._domains = dinfo._adaptedFrame.domains(); DKV.put(dinfo); model_info = new DeepLearningModelInfo(parms, dinfo, nClasses, train, valid); model_info_key = Key.makeUserHidden(Key.make(H2O.SELF)); actual_best_model_key = Key.makeUserHidden(Key.make(H2O.SELF)); if (parms._nfolds != 0) actual_best_model_key = null; if (!parms._autoencoder) { errors = new DeepLearningScoring[1]; errors[0] = new DeepLearningScoring(); errors[0].validation = (parms._valid != null); _output.errors = last_scored(); _output._scoring_history = createScoringHistoryTable(errors); _output._variable_importances = calcVarImp(last_scored().variable_importances); } makeWeightsBiases(destKey); run_time = 0; start_time = System.currentTimeMillis(); _timeLastScoreEnter = start_time; assert _key.equals(destKey); boolean fail = false; long byte_size = 0; try { byte_size = new AutoBuffer().put(this).buf().length; } catch(Throwable t) { fail = true; } if (byte_size > Value.MAX || fail) throw new IllegalArgumentException(technote(5, "Model is too large")); } public long _timeLastScoreEnter; //not transient: needed for HTML display page transient private long _timeLastScoreStart; transient private long _timeLastScoreEnd; transient private long _timeLastPrintStart; /** * Score this DeepLearning model * @param ftrain potentially downsampled training data for scoring * @param ftest potentially downsampled validation data for scoring * @param job_key key of the owning job * @param progressKey key of the progress * @param iteration Map/Reduce iteration count * @return true if model building is ongoing */ boolean doScoring(Frame ftrain, Frame ftest, Key job_key, Key progressKey, int iteration) { final long now = System.currentTimeMillis(); epoch_counter = (double)model_info().get_processed_total()/training_rows; final double time_last_iter_millis = Math.max(5,now-_timeLastScoreEnter); run_time += time_last_iter_millis; // First update Job progress based on the number of trained samples for the last iteration // and update the progress message Job.Progress prog = DKV.getGet(progressKey); float progress = prog == null ? 0 : prog.progress(); String msg = "Map/Reduce Iteration " + String.format("%,d",iteration) + ": Training at " + String.format("%,d", model_info().get_processed_total() * 1000 / run_time) + " samples/s..." + (progress == 0 ? "" : " Estimated time left: " + PrettyPrint.msecs((long) (run_time * (1. - progress) / progress), true)); ((Job)DKV.getGet(job_key)).update(actual_train_samples_per_iteration); //mark the amount of work done for the progress bar if (progressKey != null) new Job.ProgressUpdate(msg).fork(progressKey); //update the message for the progress bar boolean keep_running; // Auto-tuning // if multi-node and auto-tuning and at least 10 ms for communication (to avoid doing thins on multi-JVM on same node), // then adjust the auto-tuning parameter 'actual_train_samples_per_iteration' such that the targeted ratio of comm to comp is achieved // Note: actual communication time is estimated by the NetworkTest's collective test. if (H2O.CLOUD.size() > 1 && get_params()._train_samples_per_iteration == -2 && iteration != 0) { Log.info("Auto-tuning train_samples_per_iteration."); if (time_for_communication_us > 1e4) { Log.info(" Time taken for communication: " + PrettyPrint.usecs((long) time_for_communication_us)); Log.info(" Time taken for Map/Reduce iteration: " + PrettyPrint.msecs((long) time_last_iter_millis, true)); final double comm_to_work_ratio = (time_for_communication_us * 1e-3) / time_last_iter_millis; Log.info(" Ratio of network communication to computation: " + String.format("%.5f", comm_to_work_ratio)); Log.info(" target_comm_to_work: " + get_params()._target_ratio_comm_to_comp); Log.info("Old value of train_samples_per_iteration: " + actual_train_samples_per_iteration); double correction = get_params()._target_ratio_comm_to_comp / comm_to_work_ratio; correction = Math.max(0.5,Math.min(2, correction)); //it's ok to train up to 2x more training rows per iteration, but not fewer than half. if (Math.abs(correction) < 0.8 || Math.abs(correction) > 1.2) { //don't correct unless it's significant (avoid slow drift) actual_train_samples_per_iteration /= correction; actual_train_samples_per_iteration = Math.max(1, actual_train_samples_per_iteration); Log.info("New value of train_samples_per_iteration: " + actual_train_samples_per_iteration); } else { Log.info("Keeping value of train_samples_per_iteration the same (would deviate too little from previous value): " + actual_train_samples_per_iteration); } } else { Log.info("Communication is faster than 10 ms. Not modifying train_samples_per_iteration: " + actual_train_samples_per_iteration); } } _timeLastScoreEnter = now; keep_running = (epoch_counter < model_info().get_params()._epochs) && !stopped_early; final long sinceLastScore = now -_timeLastScoreStart; final long sinceLastPrint = now -_timeLastPrintStart; if (!keep_running || sinceLastPrint > get_params()._score_interval * 1000) { //print this after every score_interval, not considering duty cycle _timeLastPrintStart = now; if (!get_params()._quiet_mode) { Log.info("Training time: " + PrettyPrint.msecs(run_time, true) + ". Processed " + String.format("%,d", model_info().get_processed_total()) + " samples" + " (" + String.format("%.3f", epoch_counter) + " epochs)." + " Speed: " + String.format("%,d", 1000 * model_info().get_processed_total() / run_time) + " samples/sec.\n"); Log.info(msg); } } // this is potentially slow - only do every so often if( !keep_running || (sinceLastScore > get_params()._score_interval *1000 //don't score too often &&(double)(_timeLastScoreEnd-_timeLastScoreStart)/sinceLastScore < get_params()._score_duty_cycle) ) { //duty cycle if (progressKey != null) { new Job.ProgressUpdate("Scoring on " + ftrain.numRows() + " training samples" + (ftest != null ? (", " + ftest.numRows() + " validation samples") : "") ).fork(progressKey); } final boolean printme = !get_params()._quiet_mode; _timeLastScoreStart = now; model_info().computeStats(); //might not be necessary, but is done to be certain that numbers are good DeepLearningScoring err = new DeepLearningScoring(); err.training_time_ms = run_time; err.epoch_counter = epoch_counter; err.training_samples = (double)model_info().get_processed_total(); err.validation = ftest != null; err.score_training_samples = ftrain.numRows(); err.classification = _output.isClassifier(); if (get_params()._autoencoder) { if (printme) Log.info("Scoring the auto-encoder."); // training { final Frame mse_frame = scoreAutoEncoder(ftrain, Key.make()); mse_frame.delete(); ModelMetrics mtrain = ModelMetrics.getFromDKV(this,ftrain); //updated by model.score _output._training_metrics = mtrain; err.scored_train = new ScoreKeeper(mtrain); } if (ftest != null) { final Frame mse_frame = scoreAutoEncoder(ftest, Key.make()); mse_frame.delete(); ModelMetrics mtest = ModelMetrics.getFromDKV(this,ftest); //updated by model.score _output._validation_metrics = mtest; err.scored_valid = new ScoreKeeper(mtest); } } else { if (printme) Log.info("Scoring the model."); // compute errors final String m = model_info().toString(); if (m.length() > 0) Log.info(m); final Frame trainPredict = score(ftrain); trainPredict.delete(); hex.ModelMetrics mtrain = ModelMetrics.getFromDKV(this, ftrain); _output._training_metrics = mtrain; err.scored_train = new ScoreKeeper(mtrain); hex.ModelMetrics mtest = null; hex.ModelMetricsSupervised mm1 = (ModelMetricsSupervised)ModelMetrics.getFromDKV(this,ftrain); if (mm1 instanceof ModelMetricsBinomial) { ModelMetricsBinomial mm = (ModelMetricsBinomial)(mm1); err.training_AUC = mm._auc; } if (ftrain.numRows() != training_rows) { _output._training_metrics._description = "Metrics reported on temporary training frame with " + ftrain.numRows() + " samples"; } else if (ftrain._key != null && ftrain._key.toString().contains("chunks")){ _output._training_metrics._description = "Metrics reported on temporary (load-balanced) training frame"; } else { _output._training_metrics._description = "Metrics reported on full training frame"; } if (ftest != null) { Frame validPred = score(ftest); validPred.delete(); if (ftest != null) { mtest = ModelMetrics.getFromDKV(this, ftest); _output._validation_metrics = mtest; err.scored_valid = new ScoreKeeper(mtest); } if (mtest != null) { if (mtest instanceof ModelMetricsBinomial) { ModelMetricsBinomial mm = (ModelMetricsBinomial)mtest; err.validation_AUC = mm._auc; } if (ftest.numRows() != validation_rows) { _output._validation_metrics._description = "Metrics reported on temporary validation frame with " + ftest.numRows() + " samples"; if (get_params()._score_validation_sampling == DeepLearningParameters.ClassSamplingMethod.Stratified) { _output._validation_metrics._description += " (stratified sampling)"; } } else if (ftest._key != null && ftest._key.toString().contains("chunks")){ _output._validation_metrics._description = "Metrics reported on temporary (load-balanced) validation frame"; } else { _output._validation_metrics._description = "Metrics reported on full validation frame"; } } } } if (get_params()._variable_importances) { if (!get_params()._quiet_mode) Log.info("Computing variable importances."); final float[] vi = model_info().computeVariableImportances(); err.variable_importances = new VarImp(vi, Arrays.copyOfRange(model_info().data_info().coefNames(), 0, vi.length)); } _timeLastScoreEnd = System.currentTimeMillis(); err.scoring_time = System.currentTimeMillis() - now; // enlarge the error array by one, push latest score back if (errors == null) { errors = new DeepLearningScoring[]{err}; } else { DeepLearningScoring[] err2 = new DeepLearningScoring[errors.length + 1]; System.arraycopy(errors, 0, err2, 0, errors.length); err2[err2.length - 1] = err; errors = err2; } _output.errors = last_scored(); makeWeightsBiases(_key); water.util.Timer t = new Timer(); // store weights and matrices to Frames if (_output.weights != null && _output.biases != null) { for (int i = 0; i < _output.weights.length; ++i) { model_info.get_weights(i).toFrame(_output.weights[i]); } for (int i = 0; i < _output.biases.length; ++i) { model_info.get_biases(i).toFrame(_output.biases[i]); } if (!_parms._quiet_mode) Log.info("Writing weights and biases to Frames took " + t.time()/1000. + " seconds."); } _output._scoring_history = createScoringHistoryTable(errors); _output._variable_importances = calcVarImp(last_scored().variable_importances); _output._model_summary = model_info.createSummaryTable(); if (!get_params()._autoencoder) { // always keep a copy of the best model so far (based on the following criterion) if (actual_best_model_key != null && get_params()._overwrite_with_best_model && ( // if we have a best_model in DKV, then compare against its error() (unless it's a different model as judged by the network size) (DKV.get(actual_best_model_key) != null && (error() < DKV.get(actual_best_model_key).<DeepLearningModel>get().error() || !Arrays.equals(model_info().units, DKV.get(actual_best_model_key).<DeepLearningModel>get().model_info().units))) || // otherwise, compare against our own _bestError (DKV.get(actual_best_model_key) == null && error() < _bestError) ) ) { if (!get_params()._quiet_mode) Log.info("Error reduced from " + _bestError + " to " + error() + "."); _bestError = error(); putMeAsBestModel(actual_best_model_key); } } // print the freshly scored model to ASCII if (keep_running && printme) Log.info(toString()); if (printme) Log.info("Time taken for scoring and diagnostics: " + PrettyPrint.msecs(err.scoring_time, true)); } if ( (_output.isClassifier() && last_scored().scored_train._classError <= get_params()._classification_stop) || (!_output.isClassifier() && last_scored().scored_train._mse <= get_params()._regression_stop) ) { Log.info("Achieved requested predictive accuracy on the training data. Model building completed."); stopped_early = true; keep_running = false; } update(job_key); return keep_running; } /** Make either a prediction or a reconstruction. * @param orig Test dataset * @param adaptedFr Test dataset, adapted to the model * @return A frame containing the prediction or reconstruction */ @Override protected Frame predictScoreImpl(Frame orig, Frame adaptedFr, String destination_key) { if (!get_params()._autoencoder) { return super.predictScoreImpl(orig, adaptedFr, destination_key); } else { // Reconstruction final int len = model_info().data_info().fullN(); assert(model_info().data_info()._responses == 0); String[] coefnames = model_info().data_info().coefNames(); assert(len == coefnames.length); String[] names = new String[len]; for(int i = 0; i < names.length; ++i) { names[i] = "reconstr_" + coefnames[i]; } Frame f = new MRTask() { @Override public void map( Chunk chks[], NewChunk recon[] ) { double tmp [] = new double[_output._names.length]; double preds[] = new double [len]; final Neurons[] neurons = DeepLearningTask.makeNeuronsForTesting(model_info); for( int row=0; row<chks[0]._len; row++ ) { double p[] = score_autoencoder(chks, row, tmp, preds, neurons); for( int c=0; c<len; c++ ) recon[c].addNum(p[c]); } } }.doAll(len,adaptedFr).outputFrame(); Frame of = new Frame((null == destination_key ? Key.make() : Key.make(destination_key)), names, f.vecs()); DKV.put(of); makeMetricBuilder(null).makeModelMetrics(this, orig); return of; } } @Override protected double[] score0(double[] data, double[] preds) { return score0(data, preds, 1, 0); } /** * Compute the loss function * @param myRows Mini-Batch Array of denseRow's containing numerical/categorical predictor and response data (standardized) * @return loss */ public double loss(DataInfo.Row[] myRows) { double loss = 0; Neurons[] neurons = DeepLearningTask.makeNeuronsForTraining(model_info()); for (DataInfo.Row myRow : myRows) { if (myRow == null) continue; long seed = -1; //ignored // check that all non-last layer errors/gradients are empty for (int i = 0; i<neurons.length-1;++i) { Storage.DenseVector e = neurons[i]._e; if (e==null) continue; assert(ArrayUtils.sum(e.raw()) == 0); } ((Neurons.Input)neurons[0]).setInput(seed, myRow.numVals, myRow.nBins, myRow.binIds); DeepLearningTask.step(seed, neurons, model_info(), null, false, null, myRow.offset); // check that all non-last layer errors/gradients are empty for (int i = 0; i<neurons.length-1;++i) { Storage.DenseVector e = neurons[i]._e; if (e==null) continue; assert(ArrayUtils.sum(e.raw()) == 0); } if (model_info.get_params()._loss == DeepLearningParameters.Loss.CrossEntropy) { if (_parms._balance_classes) throw H2O.unimpl(); int actual = (int) myRow.response[0]; double pred = neurons[neurons.length - 1]._a.get(actual); loss += -Math.log(Math.max(1e-15, pred)); //cross-entropy (same as log loss) } else { if (model_info.get_params()._autoencoder) throw H2O.unimpl(); //prediction and actual response in standardized response space double pred = neurons[neurons.length - 1]._a.get(0); double actual = myRow.response[0]; // FIXME: re-enable this such that the loss is computed from the de-standardized prediction/response //bring standardized prediction and actual response to real space // DataInfo di = model_info().data_info(); // if (di._normRespMul != null) { //either both are null or none // pred = (pred / di._normRespMul[0] + di._normRespSub[0]); // actual = (actual / di._normRespMul[0] + di._normRespSub[0]); // } Distribution dist = new Distribution(model_info.get_params()._distribution, model_info.get_params()._tweedie_power); pred = dist.linkInv(pred); loss += 0.5 * dist.deviance(1 /*weight*/, actual, pred); } // add L1/L2 penalty of model coefficients (weights & biases) for (int i = 0; i < _parms._hidden.length + 1; ++i) { if (neurons[i]._w == null) continue; for (int row = 0; row < neurons[i]._w.rows(); ++row) { for (int col = 0; col < neurons[i]._w.cols(); ++col) { loss += _parms._l1 * Math.abs(neurons[i]._w.get(row, col)); loss += 0.5 * _parms._l2 * Math.pow(neurons[i]._w.get(row, col), 2); } } for (int row = 0; row < neurons[i]._w.rows(); ++row) { loss += _parms._l1 * Math.abs(neurons[i]._b.get(row)); loss += 0.5 * _parms._l2 * Math.pow(neurons[i]._b.get(row), 2); } } } return loss; } /** * Predict from raw double values representing the data * @param data raw array containing categorical values (horizontalized to 1,0,0,1,0,0 etc.) and numerical values (0.35,1.24,5.3234,etc), both can contain NaNs * @param preds predicted label and per-class probabilities (for classification), predicted target (regression), can contain NaNs * @return preds, can contain NaNs */ @Override public double[] score0(double[] data, double[] preds, double weight, double offset) { if (model_info().isUnstable()) { Log.err(unstable_msg); throw new UnsupportedOperationException(unstable_msg); } Neurons[] neurons = DeepLearningTask.makeNeuronsForTesting(model_info); ((Neurons.Input)neurons[0]).setInput(-1, data); DeepLearningTask.step(-1, neurons, model_info, null, false, null, offset); double[] out = neurons[neurons.length - 1]._a.raw(); if (_output.isClassifier()) { assert (preds.length == out.length + 1); for (int i = 0; i < preds.length - 1; ++i) { preds[i + 1] = out[i]; if (Double.isNaN(preds[i + 1])) throw new RuntimeException("Predicted class probability NaN!"); } // label assignment happens later - explicitly mark it as invalid here preds[0] = -1; } else { if (model_info().data_info()._normRespMul != null) //either both are null or none preds[0] = (out[0] / model_info().data_info()._normRespMul[0] + model_info().data_info()._normRespSub[0]); else preds[0] = out[0]; // transform prediction to response space preds[0] = new Distribution(model_info.get_params()._distribution, model_info.get_params()._tweedie_power).linkInv(preds[0]); if (Double.isNaN(preds[0])) throw new RuntimeException("Predicted regression target NaN!"); } return preds; } /** * Score auto-encoded reconstruction (on-the-fly, without allocating the reconstruction as done in Frame score(Frame fr)) * @param frame Original data (can contain response, will be ignored) * @return Frame containing one Vec with reconstruction error (MSE) of each reconstructed row, caller is responsible for deletion */ public Frame scoreAutoEncoder(Frame frame, Key destination_key) { if (!get_params()._autoencoder) throw new H2OIllegalArgumentException("Only for AutoEncoder Deep Learning model.", ""); final int len = _output._names.length; Frame adaptFrm = new Frame(frame); adaptTestForTrain(adaptFrm,true, false); Frame mse = new MRTask() { @Override public void map( Chunk chks[], NewChunk[] mse ) { double tmp [] = new double[len]; final Neurons[] neurons = DeepLearningTask.makeNeuronsForTesting(model_info); for( int row=0; row<chks[0]._len; row++ ) { for( int i=0; i<len; i++ ) tmp[i] = chks[i].atd(row); mse[0].addNum(score_autoencoder(tmp, null, neurons)); } } }.doAll(1,adaptFrm).outputFrame(); Frame res = new Frame(destination_key, new String[]{"Reconstruction.MSE"}, mse.vecs()); DKV.put(res); _output.addModelMetrics(new ModelMetricsAutoEncoder(this, frame, res.vecs()[0].mean() /*mean MSE*/)); return res; } /** * Score auto-encoded reconstruction (on-the-fly, and materialize the deep features of given layer * @param frame Original data (can contain response, will be ignored) * @param layer index of the hidden layer for which to extract the features * @return Frame containing the deep features (#cols = hidden[layer]) */ public Frame scoreDeepFeatures(Frame frame, final int layer) { if (layer < 0 || layer >= model_info().get_params()._hidden.length) throw new H2OIllegalArgumentException("hidden layer (index) to extract must be between " + 0 + " and " + (model_info().get_params()._hidden.length-1),""); final int len = _output.nfeatures(); Vec resp = null; if (isSupervised()) { int ridx = frame.find(_output.responseName()); if (ridx != -1) { // drop the response for scoring! frame = new Frame(frame); resp = frame.vecs()[ridx]; frame.remove(ridx); } } Frame adaptFrm = new Frame(frame); //create new features, will be dense final int features = model_info().get_params()._hidden[layer]; Vec[] vecs = adaptFrm.anyVec().makeZeros(features); Scope.enter(); adaptTestForTrain(_output._names, _output.weightsName(), _output.offsetName(), _output.foldName(), null /*don't skip response*/, _output._domains, adaptFrm, _parms.missingColumnsType(), true, true); for (int j=0; j<features; ++j) { adaptFrm.add("DF.L"+(layer+1)+".C" + (j+1), vecs[j]); } new MRTask() { @Override public void map( Chunk chks[] ) { double tmp [] = new double[len]; final Neurons[] neurons = DeepLearningTask.makeNeuronsForTesting(model_info); for( int row=0; row<chks[0]._len; row++ ) { for( int i=0; i<len; i++ ) tmp[i] = chks[i].atd(row); ((Neurons.Input)neurons[0]).setInput(-1, tmp); //FIXME: No weights yet DeepLearningTask.step(-1, neurons, model_info, null, false, null, 0 /*no offset*/); double[] out = neurons[layer+1]._a.raw(); //extract the layer-th hidden feature for( int c=0; c<features; c++ ) chks[_output._names.length+c].set(row,out[c]); } } }.doAll(adaptFrm); // Return just the output columns int x=_output._names.length, y=adaptFrm.numCols(); Frame ret = adaptFrm.extractFrame(x, y); if (resp != null) ret.prepend(_output.responseName(), resp); Scope.exit(); return ret; } // Make (potentially expanded) reconstruction private double[] score_autoencoder(Chunk[] chks, int row_in_chunk, double[] tmp, double[] preds, Neurons[] neurons) { assert(get_params()._autoencoder); assert(tmp.length == _output._names.length); for( int i=0; i<tmp.length; i++ ) tmp[i] = chks[i].atd(row_in_chunk); score_autoencoder(tmp, preds, neurons); // this fills preds, returns MSE error (ignored here) return preds; } /** * Helper to reconstruct original data into preds array and compute the reconstruction error (MSE) * @param data Original data (unexpanded) * @param preds Reconstruction (potentially expanded) * @return reconstruction error */ private double score_autoencoder(double[] data, double[] preds, Neurons[] neurons) { assert(model_info().get_params()._autoencoder); if (model_info().isUnstable()) { Log.err(unstable_msg); throw new UnsupportedOperationException(unstable_msg); } ((Neurons.Input)neurons[0]).setInput(-1, data); // FIXME - no weights yet DeepLearningTask.step(-1, neurons, model_info, null, false, null, 0 /*no offset*/); // reconstructs data in expanded space double[] in = neurons[0]._a.raw(); //input (expanded) double[] out = neurons[neurons.length - 1]._a.raw(); //output (expanded) assert(in.length == out.length); // First normalize categorical reconstructions to be probabilities // (such that they can be better compared to the input where one factor was 1 and the rest was 0) // model_info().data_info().softMaxCategoricals(out,out); //only modifies the categoricals // Compute MSE of reconstruction in expanded space (with categorical probabilities) double l2 = 0; for (int i = 0; i < in.length; ++i) l2 += Math.pow((out[i] - in[i]), 2); l2 /= in.length; if (preds!=null) { // Now scale back numerical columns to original data space (scale + shift) model_info().data_info().unScaleNumericals(out, out); //only modifies the numericals System.arraycopy(out, 0, preds, 0, out.length); //copy reconstruction into preds } return l2; } /** * Compute quantile-based threshold (in reconstruction error) to find outliers * @param mse Vector containing reconstruction errors * @param quantile Quantile for cut-off * @return Threshold in MSE value for a point to be above the quantile */ public double calcOutlierThreshold(Vec mse, double quantile) { Frame mse_frame = new Frame(Key.make(), new String[]{"Reconstruction.MSE"}, new Vec[]{mse}); DKV.put(mse_frame._key, mse_frame); QuantileModel.QuantileParameters parms = new QuantileModel.QuantileParameters(); parms._train = mse_frame._key; parms._probs = new double[]{quantile}; Job<QuantileModel> job = new Quantile(parms).trainModel(); QuantileModel kmm = job.get(); job.remove(); double q = kmm._output._quantiles[0][0]; kmm.delete(); DKV.remove(mse_frame._key); return q; } // helper to push this model to another key (for keeping good models) private void putMeAsBestModel(Key bestModelKey) { DeepLearningModel bestModel = new DeepLearningModel(bestModelKey, null, this, true, model_info().data_info()); DKV.put(bestModel._key, bestModel); if (model_info().get_params()._elastic_averaging) { DeepLearningModelInfo eamodel = DKV.getGet(model_info.elasticAverageModelInfoKey()); if (eamodel != null) DKV.put(bestModel.model_info().elasticAverageModelInfoKey(), eamodel); } assert (DKV.get(bestModelKey) != null); assert (bestModel.compareTo(this) <= 0); } @Override public void delete() { if (_output.weights != null && _output.biases != null) { for (Key k : _output.weights) { if (DKV.getGet(k) != null) ((Frame) DKV.getGet(k)).delete(); } for (Key k : _output.biases) { if (DKV.getGet(k) != null) ((Frame) DKV.getGet(k)).delete(); } } DKV.remove(model_info().data_info()._key); deleteElasticAverageModels(); super.delete(); } void deleteElasticAverageModels() { if (model_info().get_params()._elastic_averaging) { DKV.remove(model_info().elasticAverageModelInfoKey()); for (H2ONode node : H2O.CLOUD._memary) { DKV.remove(model_info().localModelInfoKey(node)); } } } private String getHeader() { assert get_params()._autoencoder; StringBuilder sb = new StringBuilder(); final int len = model_info().data_info().fullN(); String prefix = "reconstr_"; assert (model_info().data_info()._responses == 0); String[] coefnames = model_info().data_info().coefNames(); assert (len == coefnames.length); for (int c = 0; c < len; c++) { if (c>0) sb.append(","); sb.append(prefix + coefnames[c]); } return sb.toString(); } @Override protected SB toJavaInit(SB sb, SB fileContextSB) { sb = super.toJavaInit(sb, fileContextSB); String mname = JCodeGen.toJavaId(_key.toString()); Neurons[] neurons = DeepLearningTask.makeNeuronsForTesting(model_info()); final DeepLearningParameters p = model_info.get_params(); sb.ip("public boolean isSupervised() { return " + isSupervised() + "; }").nl(); sb.ip("public int nfeatures() { return "+_output.nfeatures()+"; }").nl(); sb.ip("public int nclasses() { return "+ (p._autoencoder ? neurons[neurons.length-1].units : _output.nclasses()) + "; }").nl(); if (model_info().data_info()._nums > 0) { JCodeGen.toStaticVar(sb, "NUMS", new double[model_info().data_info()._nums], "Workspace for storing numerical input variables."); JCodeGen.toStaticVar(sb, "NORMMUL", model_info().data_info()._normMul, "Standardization/Normalization scaling factor for numerical variables."); JCodeGen.toStaticVar(sb, "NORMSUB", model_info().data_info()._normSub, "Standardization/Normalization offset for numerical variables."); } if (model_info().data_info()._cats > 0) { JCodeGen.toStaticVar(sb, "CATS", new int[model_info().data_info()._cats], "Workspace for storing categorical input variables."); } JCodeGen.toStaticVar(sb, "CATOFFSETS", model_info().data_info()._catOffsets, "Workspace for categorical offsets."); if (model_info().data_info()._normRespMul != null) { JCodeGen.toStaticVar(sb, "NORMRESPMUL", model_info().data_info()._normRespMul, "Standardization/Normalization scaling factor for response."); JCodeGen.toStaticVar(sb, "NORMRESPSUB", model_info().data_info()._normRespSub, "Standardization/Normalization offset for response."); } if (p._hidden_dropout_ratios != null) { JCodeGen.toStaticVar(sb, "HIDDEN_DROPOUT_RATIOS", p._hidden_dropout_ratios, "Hidden layer dropout ratios."); } int[] layers = new int[neurons.length]; for (int i=0;i<neurons.length;++i) layers[i] = neurons[i].units; JCodeGen.toStaticVar(sb, "NEURONS", layers, "Number of neurons for each layer."); if (get_params()._autoencoder) { sb.i(1).p("public int getPredsSize() { return " + model_info.units[model_info.units.length-1] + "; }").nl(); sb.i(1).p("public boolean isAutoEncoder() { return true; }").nl(); sb.i(1).p("public String getHeader() { return \"" + getHeader() + "\"; }").nl(); } // activation storage sb.i(1).p("// Storage for neuron activation values.").nl(); sb.i(1).p("public static final double[][] ACTIVATION = new double[][] {").nl(); for (int i=0; i<neurons.length; i++) { String colInfoClazz = mname + "_Activation_"+i; sb.i(2).p("/* ").p(neurons[i].getClass().getSimpleName()).p(" */ "); sb.p(colInfoClazz).p(".VALUES"); if (i!=neurons.length-1) sb.p(','); sb.nl(); fileContextSB.i().p("// Neuron activation values for ").p(neurons[i].getClass().getSimpleName()).p(" layer").nl(); JCodeGen.toClassWithArray(fileContextSB, null, colInfoClazz, new double[layers[i]]); } sb.i(1).p("};").nl(); // biases sb.i(1).p("// Neuron bias values.").nl(); sb.i(1).p("public static final double[][] BIAS = new double[][] {").nl(); for (int i=0; i<neurons.length; i++) { String colInfoClazz = mname + "_Bias_"+i; sb.i(2).p("/* ").p(neurons[i].getClass().getSimpleName()).p(" */ "); sb.p(colInfoClazz).p(".VALUES"); if (i!=neurons.length-1) sb.p(','); sb.nl(); fileContextSB.i().p("// Neuron bias values for ").p(neurons[i].getClass().getSimpleName()).p(" layer").nl(); double[] bias = i == 0 ? null : new double[model_info().get_biases(i-1).size()]; if (i>0) { for (int j=0; j<bias.length; ++j) bias[j] = model_info().get_biases(i-1).get(j); } JCodeGen.toClassWithArray(fileContextSB, null, colInfoClazz, bias); } sb.i(1).p("};").nl(); // weights sb.i(1).p("// Connecting weights between neurons.").nl(); sb.i(1).p("public static final float[][] WEIGHT = new float[][] {").nl(); for (int i=0; i<neurons.length; i++) { String colInfoClazz = mname + "_Weight_"+i; sb.i(2).p("/* ").p(neurons[i].getClass().getSimpleName()).p(" */ "); sb.p(colInfoClazz).p(".VALUES"); if (i!=neurons.length-1) sb.p(','); sb.nl(); if (i > 0) { fileContextSB.i().p("// Neuron weights connecting "). p(neurons[i - 1].getClass().getSimpleName()).p(" and "). p(neurons[i].getClass().getSimpleName()). p(" layer").nl(); } float[] weights = i == 0 ? null : new float[model_info().get_weights(i-1).rows()*model_info().get_weights(i-1).cols()]; if (i>0) { final int rows = model_info().get_weights(i-1).rows(); final int cols = model_info().get_weights(i-1).cols(); for (int j=0; j<rows; ++j) for (int k=0; k<cols; ++k) weights[j*cols+k] = model_info().get_weights(i-1).get(j,k); } JCodeGen.toClassWithArray(fileContextSB, null, colInfoClazz, weights); } sb.i(1).p("};").nl(); return sb; } @Override protected boolean toJavaCheckTooBig() { return (model_info.size() > 1e6); } private SB pureMatVec(final SB bodySb) { bodySb.i(1).p("int cols = ACTIVATION[i-1].length;").nl(); bodySb.i(1).p("int rows = ACTIVATION[i].length;").nl(); bodySb.i(1).p("int extra=cols-cols%8;").nl(); bodySb.i(1).p("int multiple = (cols/8)*8-1;").nl(); bodySb.i(1).p("int idx = 0;").nl(); bodySb.i(1).p("float[] a = WEIGHT[i];").nl(); bodySb.i(1).p("double[] x = ACTIVATION[i-1];").nl(); bodySb.i(1).p("double[] y = BIAS[i];").nl(); bodySb.i(1).p("double[] res = ACTIVATION[i];").nl(); bodySb.i(1).p("for (int row=0; row<rows; ++row) {").nl(); bodySb.i(2).p("double psum0 = 0, psum1 = 0, psum2 = 0, psum3 = 0, psum4 = 0, psum5 = 0, psum6 = 0, psum7 = 0;").nl(); bodySb.i(2).p("for (int col = 0; col < multiple; col += 8) {").nl(); bodySb.i(3).p("int off = idx + col;").nl(); bodySb.i(3).p("psum0 += a[off ] * x[col ];").nl(); bodySb.i(3).p("psum1 += a[off + 1] * x[col + 1];").nl(); bodySb.i(3).p("psum2 += a[off + 2] * x[col + 2];").nl(); bodySb.i(3).p("psum3 += a[off + 3] * x[col + 3];").nl(); bodySb.i(3).p("psum4 += a[off + 4] * x[col + 4];").nl(); bodySb.i(3).p("psum5 += a[off + 5] * x[col + 5];").nl(); bodySb.i(3).p("psum6 += a[off + 6] * x[col + 6];").nl(); bodySb.i(3).p("psum7 += a[off + 7] * x[col + 7];").nl(); bodySb.i(2).p("}").nl(); bodySb.i(2).p("res[row] += psum0 + psum1 + psum2 + psum3;").nl(); bodySb.i(2).p("res[row] += psum4 + psum5 + psum6 + psum7;").nl(); bodySb.i(2).p("for (int col = extra; col < cols; col++)").nl(); bodySb.i(3).p("res[row] += a[idx + col] * x[col];").nl(); bodySb.i(2).p("res[row] += y[row];").nl(); bodySb.i(2).p("idx += cols;").nl(); bodySb.i(1).p("}").nl(); return bodySb; } @Override protected void toJavaPredictBody( final SB bodySb, final SB classCtxSb, final SB fileCtxSb) { SB model = new SB(); final DeepLearningParameters p = model_info.get_params(); bodySb.i().p("java.util.Arrays.fill(preds,0);").nl(); final int cats = model_info().data_info()._cats; final int nums = model_info().data_info()._nums; // initialize input layer if (nums > 0) bodySb.i().p("java.util.Arrays.fill(NUMS,0);").nl(); if (cats > 0) bodySb.i().p("java.util.Arrays.fill(CATS,0);").nl(); bodySb.i().p("int i = 0, ncats = 0;").nl(); if (cats > 0) { bodySb.i().p("for(; i<"+cats+"; ++i) {").nl(); bodySb.i(1).p("if (!Double.isNaN(data[i])) {").nl(); bodySb.i(2).p("int c = (int) data[i];").nl(); if (model_info().data_info()._useAllFactorLevels) bodySb.i(2).p("CATS[ncats++] = c + CATOFFSETS[i];").nl(); else bodySb.i(2).p("if (c != 0) CATS[ncats++] = c + CATOFFSETS[i] - 1;").nl(); bodySb.i(1).p("}").nl(); bodySb.i().p("}").nl(); } if (nums > 0) { bodySb.i().p("final int n = data.length;").nl(); bodySb.i().p("for(; i<n; ++i) {").nl(); bodySb.i(1).p("NUMS[i" + (cats > 0 ? "-" + cats : "") + "] = Double.isNaN(data[i]) ? 0 : "); if (model_info().data_info()._normMul != null) { bodySb.p("(data[i] - NORMSUB[i" + (cats > 0 ? "-" + cats : "") + "])*NORMMUL[i" + (cats > 0 ? "-" + cats : "") + "];").nl(); } else { bodySb.p("data[i];").nl(); } bodySb.i(0).p("}").nl(); } bodySb.i().p("java.util.Arrays.fill(ACTIVATION[0],0);").nl(); if (cats > 0) { bodySb.i().p("for (i=0; i<ncats; ++i) ACTIVATION[0][CATS[i]] = 1;").nl(); } if (nums > 0) { bodySb.i().p("for (i=0; i<NUMS.length; ++i) {").nl(); bodySb.i(1).p("ACTIVATION[0][CATOFFSETS[CATOFFSETS.length-1] + i] = Double.isNaN(NUMS[i]) ? 0 : NUMS[i];").nl(); bodySb.i().p("}").nl(); } boolean tanh=(p._activation == DeepLearningParameters.Activation.Tanh || p._activation == DeepLearningParameters.Activation.TanhWithDropout); boolean relu=(p._activation == DeepLearningParameters.Activation.Rectifier || p._activation == DeepLearningParameters.Activation.RectifierWithDropout); boolean maxout=(p._activation == DeepLearningParameters.Activation.Maxout || p._activation == DeepLearningParameters.Activation.MaxoutWithDropout); final String stopping = p._autoencoder ? "(i<=ACTIVATION.length-1)" : "(i<ACTIVATION.length-1)"; // make prediction: forward propagation bodySb.i().p("for (i=1; i<ACTIVATION.length; ++i) {").nl(); bodySb.i(1).p("java.util.Arrays.fill(ACTIVATION[i],0);").nl(); if (maxout) { bodySb.i(1).p("int _k = 2; // channels").nl(); bodySb.i(1).p("if " + stopping + " {").nl(); bodySb.i(2).p("double[] channel = new double[_k];").nl(); bodySb.i(2).p("for (int r=0; r<ACTIVATION[i].length; ++r) {").nl(); bodySb.i(3).p("final int cols = ACTIVATION[i-1].length;").nl(); bodySb.i(3).p("short maxK = 0;").nl(); bodySb.i(3).p("for (short k = 0; k < _k; ++k) {").nl(); bodySb.i(4).p("channel[k] = 0;").nl(); bodySb.i(4).p("for (int c=0; c<cols; ++c) {").nl(); bodySb.i(5).p("channel[k] += WEIGHT[i][_k*(r * cols + c) + k] * ACTIVATION[i-1][c];").nl(); bodySb.i(4).p("}").nl(); bodySb.i(4).p("channel[k] += BIAS[i][_k*r+k];").nl(); bodySb.i(4).p("if (channel[k] > channel[maxK]) maxK=k;").nl(); bodySb.i(3).p("}").nl(); bodySb.i(3).p("ACTIVATION[i][r] = channel[maxK];").nl(); } else { // optimized pureMatVec(bodySb); // Activation function bodySb.i(1).p("if " + stopping + " {").nl(); bodySb.i(2).p("for (int r=0; r<ACTIVATION[i].length; ++r) {").nl(); if (tanh) { bodySb.i(3).p("ACTIVATION[i][r] = 1 - 2 / (1 + Math.exp(2*ACTIVATION[i][r]));").nl(); } else if (relu) { bodySb.i(3).p("ACTIVATION[i][r] = Math.max(0, ACTIVATION[i][r]);").nl(); } } if (p._hidden_dropout_ratios != null) { bodySb.i(3).p("if (i<ACTIVATION.length-1) {").nl(); bodySb.i(4).p("ACTIVATION[i][r] *= HIDDEN_DROPOUT_RATIOS[i-1];").nl(); bodySb.i(3).p("}").nl(); } bodySb.i(2).p("}").nl(); bodySb.i(1).p("}").nl(); if (maxout) { bodySb.i(1).p("if (i == ACTIVATION.length-1) {").nl(); pureMatVec(bodySb); bodySb.i(1).p("}").nl(); } if (_output.isClassifier()) { bodySb.i(1).p("if (i == ACTIVATION.length-1) {").nl(); // softmax bodySb.i(2).p("double max = ACTIVATION[i][0];").nl(); bodySb.i(2).p("for (int r=1; r<ACTIVATION[i].length; r++) {").nl(); bodySb.i(3).p("if (ACTIVATION[i][r]>max) max = ACTIVATION[i][r];").nl(); bodySb.i(2).p("}").nl(); bodySb.i(2).p("double scale = 0;").nl(); bodySb.i(2).p("for (int r=0; r<ACTIVATION[i].length; r++) {").nl(); bodySb.i(3).p("ACTIVATION[i][r] = Math.exp(ACTIVATION[i][r] - max);").nl(); bodySb.i(3).p("scale += ACTIVATION[i][r];").nl(); bodySb.i(2).p("}").nl(); bodySb.i(2).p("for (int r=0; r<ACTIVATION[i].length; r++) {").nl(); bodySb.i(3).p("if (Double.isNaN(ACTIVATION[i][r]))").nl(); bodySb.i(4).p("throw new RuntimeException(\"Numerical instability, predicted NaN.\");").nl(); bodySb.i(3).p("ACTIVATION[i][r] /= scale;").nl(); bodySb.i(3).p("preds[r+1] = ACTIVATION[i][r];").nl(); bodySb.i(2).p("}").nl(); bodySb.i(1).p("}").nl(); bodySb.i().p("}").nl(); } else if (!p._autoencoder) { //Regression bodySb.i(1).p("if (i == ACTIVATION.length-1) {").nl(); // regression: set preds[1], FillPreds0 will put it into preds[0] if (model_info().data_info()._normRespMul != null) { bodySb.i(2).p("preds[1] = (ACTIVATION[i][0] / NORMRESPMUL[0] + NORMRESPSUB[0]);").nl(); } else { bodySb.i(2).p("preds[1] = ACTIVATION[i][0];").nl(); } bodySb.i(2).p("preds[1] = " + new Distribution(model_info.get_params()._distribution, model_info.get_params()._tweedie_power).linkInvString("preds[1]")+";").nl(); bodySb.i(2).p("if (Double.isNaN(preds[1])) throw new RuntimeException(\"Predicted regression target NaN!\");").nl(); bodySb.i(1).p("}").nl(); bodySb.i().p("}").nl(); } else { //AutoEncoder bodySb.i(1).p("if (i == ACTIVATION.length-1) {").nl(); bodySb.i(2).p("for (int r=0; r<ACTIVATION[i].length; r++) {").nl(); bodySb.i(3).p("if (Double.isNaN(ACTIVATION[i][r]))").nl(); bodySb.i(4).p("throw new RuntimeException(\"Numerical instability, reconstructed NaN.\");").nl(); bodySb.i(3).p("preds[r] = ACTIVATION[i][r];").nl(); bodySb.i(2).p("}").nl(); if (model_info().data_info()._nums > 0) { int ns = model_info().data_info().numStart(); bodySb.i(2).p("for (int k=" + ns + "; k<" + model_info().data_info().fullN() + "; ++k) {").nl(); bodySb.i(3).p("preds[k] = preds[k] / NORMMUL[k-" + ns + "] + NORMSUB[k-" + ns + "];").nl(); bodySb.i(2).p("}").nl(); } bodySb.i(1).p("}").nl(); bodySb.i().p("}").nl(); // DEBUGGING // bodySb.i().p("System.out.println(java.util.Arrays.toString(data));").nl(); // bodySb.i().p("System.out.println(java.util.Arrays.toString(ACTIVATION[0]));").nl(); // bodySb.i().p("System.out.println(java.util.Arrays.toString(ACTIVATION[ACTIVATION.length-1]));").nl(); // bodySb.i().p("System.out.println(java.util.Arrays.toString(preds));").nl(); // bodySb.i().p("System.out.println(\"\");").nl(); } fileCtxSb.p(model); if (_output.autoencoder) return; if (_output.isClassifier()) { if (_parms._balance_classes) bodySb.ip("hex.genmodel.GenModel.correctProbabilities(preds, PRIOR_CLASS_DISTRIB, MODEL_CLASS_DISTRIB);").nl(); bodySb.ip("preds[0] = hex.genmodel.GenModel.getPrediction(preds, PRIOR_CLASS_DISTRIB, data, " + defaultThreshold()+");").nl(); } else { bodySb.ip("preds[0] = preds[1];").nl(); } } private final String unstable_msg = technote(4, "\n\nTrying to predict with an unstable model." + "\nJob was aborted due to observed numerical instability (exponential growth)." + "\nEither the weights or the bias values are unreasonably large or lead to large activation values." + "\nTry a different initial distribution, a bounded activation function (Tanh), adding regularization" + "\n(via max_w2, l1, l2, dropout) or learning rate (either enable adaptive_rate or use a smaller learning rate or faster annealing)."); @Override protected long checksum_impl() { return super.checksum_impl() * model_info.checksum_impl(); } }
Fix IDEA warnings.
h2o-algos/src/main/java/hex/deeplearning/DeepLearningModel.java
Fix IDEA warnings.
<ide><path>2o-algos/src/main/java/hex/deeplearning/DeepLearningModel.java <ide> * 3) variable importances (TwoDimTable) <ide> */ <ide> public static class DeepLearningModelOutput extends Model.Output { <del> <del> /** <del> * For autoencoder, there's no response. <del> * Otherwise, there's 1 response at the end, and no other reserved columns in the data <del> * @return Number of features (possible predictors) <del> */ <ide> public DeepLearningModelOutput() { super(); autoencoder = false;} <ide> public DeepLearningModelOutput(DeepLearning b) { <ide> super(b); <ide> } <ide> } <ide> <add> /** <add> * Deviance of given distribution function at predicted value f <add> * @param w observation weight <add> * @param y (actual) response <add> * @param f (predicted) response in original response space <add> * @return value of gradient <add> */ <ide> @Override <ide> public double deviance(double w, double y, double f) { <ide> // Note: Must use sanitized parameters via get_params() as this._params can still have defaults AUTO, etc.) <ide> if (_output.isClassifier()) { <ide> colHeaders.add("Validation Classification Error"); colTypes.add("double"); colFormat.add("%.5f"); <ide> } <del> } else if (get_params()._nfolds > 1) { <del>// colHeaders.add("Cross-Validation MSE"); colTypes.add("double"); colFormat.add("%.5f"); <del>//// colHeaders.add("Validation R^2"); colTypes.add("double"); colFormat.add("%g"); <del>// if (_output.getModelCategory() == ModelCategory.Binomial) { <del>// colHeaders.add("Cross-Validation AUC"); <del>// colTypes.add("double"); <del>// colFormat.add("%.5f"); <del>// } <del>// if (_output.isClassifier()) { <del>// colHeaders.add("Cross-Validation Classification Error"); <del>// colTypes.add("double"); <del>// colFormat.add("%.5f"); <del>// } <ide> } <ide> <ide> final int rows = errors.length; <add> String[] s = new String[0]; <ide> TwoDimTable table = new TwoDimTable( <ide> "Scoring History", null, <ide> new String[rows], <del> colHeaders.toArray(new String[0]), <del> colTypes.toArray(new String[0]), <del> colFormat.toArray(new String[0]), <add> colHeaders.toArray(s), <add> colTypes.toArray(s), <add> colFormat.toArray(s), <ide> ""); <ide> int row = 0; <del> for( int i = 0; i<errors.length ; i++ ) { <del> final DeepLearningScoring e = errors[i]; <add> for (final DeepLearningScoring e : errors) { <ide> int col = 0; <del> assert(row < table.getRowDim()); <del> assert(col < table.getColDim()); <add> assert (row < table.getRowDim()); <add> assert (col < table.getColDim()); <ide> DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); <ide> table.set(row, col++, fmt.print(start_time + e.training_time_ms)); <ide> table.set(row, col++, PrettyPrint.msecs(e.training_time_ms, true)); <del> table.set(row, col++, e.training_time_ms == 0 ? null : (String.format("%.3f", e.training_samples/(e.training_time_ms/1e3)) + " rows/sec")); <add> table.set(row, col++, e.training_time_ms == 0 ? null : (String.format("%.3f", e.training_samples / (e.training_time_ms / 1e3)) + " rows/sec")); <ide> table.set(row, col++, e.epoch_counter); <ide> table.set(row, col++, e.training_samples); <ide> table.set(row, col++, e.scored_train != null ? e.scored_train._mse : Double.NaN); <ide> table.set(row, col++, e.validation_AUC != null ? e.validation_AUC._auc : Double.NaN); <ide> } <ide> if (_output.isClassifier()) { <del> table.set(row, col++, e.scored_valid != null ? e.scored_valid._classError : Double.NaN); <add> table.set(row, col, e.scored_valid != null ? e.scored_valid._classError : Double.NaN); <ide> } <ide> } <ide> row++; <ide> <ide> /** <ide> * Helper to allocate keys for output frames for weights and biases <del> * @param destKey <add> * @param destKey Base destination key for output frames <ide> */ <ide> private void makeWeightsBiases(Key destKey) { <ide> if (!model_info.get_params()._export_weights_and_biases) { <ide> _output.normrespsub = null; <ide> _output.catoffsets = null; <ide> } else { <del> _output.weights = new Key[model_info.get_params()._hidden.length + 1]; <add> _output.weights = new Key[get_params()._hidden.length + 1]; <ide> for (int i = 0; i < _output.weights.length; ++i) { <ide> _output.weights[i] = Key.makeUserHidden(Key.make(destKey + ".weights." + i)); <ide> } <del> _output.biases = new Key[model_info.get_params()._hidden.length + 1]; <add> _output.biases = new Key[get_params()._hidden.length + 1]; <ide> for (int i = 0; i < _output.biases.length; ++i) { <ide> _output.biases[i] = Key.makeUserHidden(Key.make(destKey + ".biases." + i)); <ide> } <ide> // _parms._checkpoint = cp._key; //it's only a "real" checkpoint if job != null, otherwise a best model copy <ide> } <ide> DKV.put(dataInfo); <del> assert(model_info().get_params() != cp.model_info().get_params()); //make sure we have a clone <add> assert(get_params() != cp.model_info().get_params()); //make sure we have a clone <ide> actual_best_model_key = cp.actual_best_model_key; <ide> start_time = cp.start_time; <ide> run_time = cp.run_time; <ide> <ide> /** <ide> * Regular constructor (from scratch) <del> * @param destKey <del> * @param parms <del> * @param output <del> * @param train <del> * @param valid <del> * @param nClasses <add> * @param destKey destination key <add> * @param parms DL parameters <add> * @param output DL model output <add> * @param train Training frame <add> * @param valid Validation frame <add> * @param nClasses Number of classes (1 for regression or autoencoder) <ide> */ <ide> public DeepLearningModel(final Key destKey, final DeepLearningParameters parms, final DeepLearningModelOutput output, Frame train, Frame valid, int nClasses) { <ide> super(destKey, parms, output); <ide> } <ide> <ide> _timeLastScoreEnter = now; <del> keep_running = (epoch_counter < model_info().get_params()._epochs) && !stopped_early; <add> keep_running = (epoch_counter < get_params()._epochs) && !stopped_early; <ide> final long sinceLastScore = now -_timeLastScoreStart; <ide> final long sinceLastPrint = now -_timeLastPrintStart; <ide> if (!keep_running || sinceLastPrint > get_params()._score_interval * 1000) { //print this after every score_interval, not considering duty cycle <ide> assert(ArrayUtils.sum(e.raw()) == 0); <ide> } <ide> <del> if (model_info.get_params()._loss == DeepLearningParameters.Loss.CrossEntropy) { <add> if (get_params()._loss == DeepLearningParameters.Loss.CrossEntropy) { <ide> if (_parms._balance_classes) throw H2O.unimpl(); <ide> int actual = (int) myRow.response[0]; <ide> double pred = neurons[neurons.length - 1]._a.get(actual); <ide> loss += 0.5 * _parms._l2 * Math.pow(neurons[i]._w.get(row, col), 2); <ide> } <ide> } <del> for (int row = 0; row < neurons[i]._w.rows(); ++row) { <add> for (int row = 0; row < neurons[i]._b.size(); ++row) { <ide> loss += _parms._l1 * Math.abs(neurons[i]._b.get(row)); <ide> loss += 0.5 * _parms._l2 * Math.pow(neurons[i]._b.get(row), 2); <ide> } <ide> Frame adaptFrm = new Frame(frame); <ide> //create new features, will be dense <ide> final int features = model_info().get_params()._hidden[layer]; <del> Vec[] vecs = adaptFrm.anyVec().makeZeros(features); <add> Vec v = adaptFrm.anyVec(); <add> Vec[] vecs = v!=null ? v.makeZeros(features) : null; <add> if (vecs == null) throw new IllegalArgumentException("Cannot create deep features from a frame with no columns."); <ide> <ide> Scope.enter(); <ide> adaptTestForTrain(_output._names, _output.weightsName(), _output.offsetName(), _output.foldName(), null /*don't skip response*/, _output._domains, adaptFrm, _parms.missingColumnsType(), true, true); <ide> assert (len == coefnames.length); <ide> for (int c = 0; c < len; c++) { <ide> if (c>0) sb.append(","); <del> sb.append(prefix + coefnames[c]); <add> sb.append(prefix).append(coefnames[c]); <ide> } <ide> return sb.toString(); <ide> }
Java
epl-1.0
cbe5801849a2443a32bbe59941b2cc464547baa2
0
OndraZizka/windup,mareknovotny/windup,Ladicek/windup,windup/windup-sample-apps,windup/windup-legacy,bradsdavis/windup,jsight/windup,Ladicek/windup,Maarc/windup,jsight/windup,lincolnthree/windup,johnsteele/windup,johnsteele/windup,Ladicek/windup,windup/windup,johnsteele/windup,d-s/windup,windup/windup,d-s/windup,Maarc/windup,sgilda/windup,johnsteele/windup,sgilda/windup,mbriskar/windup,Maarc/windup,bradsdavis/windup,OndraZizka/windup,mbriskar/windup,bradsdavis/windup,jsight/windup,windup/windup,d-s/windup,Ladicek/windup,mareknovotny/windup,windup/windup-legacy,lincolnthree/windup,Maarc/windup,sgilda/windup,OndraZizka/windup,mbriskar/windup,mareknovotny/windup,mareknovotny/windup,sgilda/windup,jsight/windup,OndraZizka/windup,d-s/windup,lincolnthree/windup,mbriskar/windup,windup/windup-legacy,lincolnthree/windup,windup/windup
package org.jboss.windup.graph; import java.io.File; import java.util.UUID; import javax.enterprise.context.ApplicationScoped; import javax.inject.Named; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Named("windup-context") @ApplicationScoped public class WindupContext { private static final Logger LOG = LoggerFactory.getLogger(WindupContext.class); private File runDirectory; private GraphContext graphContext; public GraphContext getGraphContext() { if (graphContext == null) { graphContext = new GraphContext(new File(getRunDirectory(), "windup-graph")); } return graphContext; } public File getRunDirectory() { if (runDirectory == null) { runDirectory = new File(FileUtils.getTempDirectory(), UUID.randomUUID().toString()); } return runDirectory; } }
engine/graph/api/src/main/java/org/jboss/windup/graph/WindupContext.java
package org.jboss.windup.graph; import java.io.File; import java.util.UUID; import javax.enterprise.context.ApplicationScoped; import javax.inject.Named; import org.apache.commons.io.FileUtils; import org.jboss.windup.graph.GraphContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Named("windup-context") @ApplicationScoped public class WindupContext { private static final Logger LOG = LoggerFactory.getLogger(WindupContext.class); private final File runDirectory; private final GraphContext graphContext; public WindupContext() { runDirectory = new File(FileUtils.getTempDirectory(), UUID.randomUUID().toString()); graphContext = new GraphContext(new File(runDirectory, "windup-graph")); } public GraphContext getGraphContext() { return graphContext; } public File getRunDirectory() { return runDirectory; } }
Avoid initializing directories in proxies
engine/graph/api/src/main/java/org/jboss/windup/graph/WindupContext.java
Avoid initializing directories in proxies
<ide><path>ngine/graph/api/src/main/java/org/jboss/windup/graph/WindupContext.java <ide> import javax.inject.Named; <ide> <ide> import org.apache.commons.io.FileUtils; <del>import org.jboss.windup.graph.GraphContext; <ide> import org.slf4j.Logger; <ide> import org.slf4j.LoggerFactory; <ide> <ide> @Named("windup-context") <ide> @ApplicationScoped <del>public class WindupContext { <add>public class WindupContext <add>{ <add> private static final Logger LOG = LoggerFactory.getLogger(WindupContext.class); <ide> <del> private static final Logger LOG = LoggerFactory.getLogger(WindupContext.class); <del> <del> private final File runDirectory; <del> private final GraphContext graphContext; <del> <del> public WindupContext() { <del> runDirectory = new File(FileUtils.getTempDirectory(), UUID.randomUUID().toString()); <del> graphContext = new GraphContext(new File(runDirectory, "windup-graph")); <del> } <del> <del> public GraphContext getGraphContext() { <del> return graphContext; <del> } <del> <del> public File getRunDirectory() { <del> return runDirectory; <del> } <add> private File runDirectory; <add> private GraphContext graphContext; <add> <add> public GraphContext getGraphContext() <add> { <add> if (graphContext == null) <add> { <add> graphContext = new GraphContext(new File(getRunDirectory(), "windup-graph")); <add> } <add> return graphContext; <add> } <add> <add> public File getRunDirectory() <add> { <add> if (runDirectory == null) <add> { <add> runDirectory = new File(FileUtils.getTempDirectory(), UUID.randomUUID().toString()); <add> } <add> return runDirectory; <add> } <ide> }
JavaScript
mit
85265daf0e03940d987f1d7723bfa2a90bbea2d2
0
onsetsu/bloob,onsetsu/bloob,onsetsu/bloob
module.exports = function (config) { config.set({ basePath : './', frameworks: ['jasmine'], files: [ 'lib/**/*.js', 'test/spec/*.js' ], exclude: [ 'test/karma.conf.js' ], browsers : ['PhantomJS'], reporters : ['spec', 'coverage', 'html'], preprocessors: { 'lib/**/*.js': 'coverage' }, coverageReporter: { type : 'html', dir : 'coverage/' }, htmlReporter: { outputFile: 'results/unit-tests.html' }, singleRun: true, plugins : [ 'karma-spec-reporter', 'karma-phantomjs-launcher', 'karma-jasmine', 'karma-coverage', 'karma-htmlfile-reporter' ] }); };
test/karma.conf.js
module.exports = function (config) { config.set({ basePath : './', frameworks: ['jasmine'], files: [ 'lib/*.js', 'test/spec/*.js' ], exclude: [ 'test/karma.conf.js' ], browsers : ['PhantomJS'], reporters : ['spec', 'coverage', 'html'], preprocessors: { '../src/js/**/*.js': 'coverage' }, coverageReporter: { type : 'html', dir : 'coverage/' }, htmlReporter: { outputFile: 'results/unit-tests.html' }, singleRun: true, plugins : [ 'karma-spec-reporter', 'karma-phantomjs-launcher', 'karma-jasmine', 'karma-coverage', 'karma-htmlfile-reporter' ] }); };
Corrected preprocessor path
test/karma.conf.js
Corrected preprocessor path
<ide><path>est/karma.conf.js <ide> basePath : './', <ide> frameworks: ['jasmine'], <ide> files: [ <del> 'lib/*.js', <add> 'lib/**/*.js', <ide> 'test/spec/*.js' <ide> ], <ide> exclude: [ <ide> browsers : ['PhantomJS'], <ide> reporters : ['spec', 'coverage', 'html'], <ide> preprocessors: { <del> '../src/js/**/*.js': 'coverage' <add> 'lib/**/*.js': 'coverage' <ide> }, <ide> coverageReporter: { <ide> type : 'html',
Java
epl-1.0
8e7e7d00f8b7f41c1ba9f224e2ce60fd3ad56d21
0
Charling-Huang/birt,Charling-Huang/birt,sguan-actuate/birt,sguan-actuate/birt,sguan-actuate/birt,rrimmana/birt-1,sguan-actuate/birt,Charling-Huang/birt,rrimmana/birt-1,rrimmana/birt-1,Charling-Huang/birt,rrimmana/birt-1,sguan-actuate/birt,Charling-Huang/birt,rrimmana/birt-1
/******************************************************************************* * Copyright (c) 2004 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.data.ui.dataset; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.birt.core.data.ExpressionUtil; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.data.engine.api.DataEngine; import org.eclipse.birt.data.engine.api.IQueryResults; import org.eclipse.birt.data.engine.api.IResultIterator; import org.eclipse.birt.data.engine.api.querydefn.InputParameterBinding; import org.eclipse.birt.data.engine.api.querydefn.QueryDefinition; import org.eclipse.birt.data.engine.api.querydefn.ScriptExpression; import org.eclipse.birt.data.engine.core.DataException; import org.eclipse.birt.data.engine.script.ScriptEvalUtil; import org.eclipse.birt.report.data.adapter.api.DataRequestSession; import org.eclipse.birt.report.data.adapter.api.DataSessionContext; import org.eclipse.birt.report.designer.data.ui.util.DataSetProvider; import org.eclipse.birt.report.designer.data.ui.util.DataUtil; import org.eclipse.birt.report.designer.data.ui.util.DummyEngineTask; import org.eclipse.birt.report.designer.data.ui.util.Utility; import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler; import org.eclipse.birt.report.designer.nls.Messages; import org.eclipse.birt.report.designer.ui.ReportPlugin; import org.eclipse.birt.report.designer.ui.dialogs.properties.AbstractPropertyPage; import org.eclipse.birt.report.designer.ui.preferences.DateSetPreferencePage; import org.eclipse.birt.report.engine.api.EngineConfig; import org.eclipse.birt.report.engine.api.EngineConstants; import org.eclipse.birt.report.engine.api.impl.ReportEngine; import org.eclipse.birt.report.engine.api.impl.ReportEngineFactory; import org.eclipse.birt.report.engine.api.impl.ReportEngineHelper; import org.eclipse.birt.report.model.api.DataSetHandle; import org.eclipse.birt.report.model.api.DataSetParameterHandle; import org.eclipse.birt.report.model.api.DesignElementHandle; import org.eclipse.birt.report.model.api.ModuleHandle; import org.eclipse.birt.report.model.api.OdaDataSetParameterHandle; import org.eclipse.birt.report.model.api.ParameterHandle; import org.eclipse.birt.report.model.api.PropertyHandle; import org.eclipse.birt.report.model.api.ReportDesignHandle; import org.eclipse.birt.report.model.api.ScalarParameterHandle; import org.eclipse.birt.report.model.api.activity.NotificationEvent; import org.eclipse.birt.report.model.api.activity.SemanticException; import org.eclipse.birt.report.model.api.core.Listener; import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Preferences; import org.eclipse.core.runtime.Status; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.ColumnPixelData; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.TableLayout; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; 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.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.progress.UIJob; /** * Property page to preview the resultset. * */ public class ResultSetPreviewPage extends AbstractPropertyPage implements Listener { private TableViewer resultSetTableViewer = null; private transient Table resultSetTable = null; private boolean modelChanged = true; private boolean needsUpdateUI = true; private int columnCount = -1; private List recordList = null; private DataSetViewData[] metaData; private List errorList = new ArrayList(); private String[] columnBindingNames; private int previousMaxRow = -1; private CLabel promptLabel; /** * The constructor. */ public ResultSetPreviewPage( ) { super( ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.ui.IPropertyPage#createPageControl(org.eclipse.swt.widgets.Composite) */ public Control createPageControl( Composite parent ) { Composite resultSetComposite = new Composite( parent, SWT.NONE ); GridLayout layout = new GridLayout( ); layout.verticalSpacing = 15; resultSetComposite.setLayout( layout ); resultSetComposite.setLayoutData( new GridData( GridData.FILL_BOTH ) ); resultSetTable = new Table( resultSetComposite, SWT.FULL_SELECTION | SWT.MULTI | SWT.VIRTUAL | SWT.BORDER ); resultSetTable.setHeaderVisible( true ); resultSetTable.setLinesVisible( true ); resultSetTable.setLayoutData( new GridData( GridData.FILL_BOTH ) ); ( (DataSetHandle) getContainer( ).getModel( ) ).addListener( this ); resultSetTable.addMouseListener( new MouseAdapter( ) { public void mouseUp( MouseEvent e ) { // if not mouse left button if ( e.button != 1 ) { MenuManager menuManager = new MenuManager( ); ResultSetTableAction copyAction = ResultSetTableActionFactory.createResultSetTableAction( resultSetTable, ResultSetTableActionFactory.COPY_ACTION ); ResultSetTableAction selectAllAction = ResultSetTableActionFactory.createResultSetTableAction( resultSetTable, ResultSetTableActionFactory.SELECTALL_ACTION ); menuManager.add( copyAction ); menuManager.add( selectAllAction ); menuManager.update( ); copyAction.update( ); selectAllAction.update( ); Menu contextMenu = menuManager.createContextMenu( resultSetTable ); contextMenu.setEnabled( true ); contextMenu.setVisible( true ); } } } ); createResultSetTableViewer( ); promptLabel = new CLabel( resultSetComposite, SWT.WRAP ); GridData labelData = new GridData( GridData.FILL_HORIZONTAL ); promptLabel.setLayoutData( labelData ); return resultSetComposite; } private void createResultSetTableViewer( ) { resultSetTableViewer = new TableViewer( resultSetTable ); resultSetTableViewer.setSorter( null ); resultSetTableViewer.setContentProvider( new IStructuredContentProvider( ) { public Object[] getElements( Object inputElement ) { if ( inputElement instanceof List ) { return ( (List) inputElement ).toArray( ); } return new Object[0]; } public void inputChanged( Viewer viewer, Object oldInput, Object newInput ) { } public void dispose( ) { } } ); resultSetTableViewer.setLabelProvider( new ITableLabelProvider( ) { public Image getColumnImage( Object element, int columnIndex ) { return null; } public String getColumnText( Object element, int columnIndex ) { return ( (CellValue[]) element )[columnIndex].getDisplayValue( ); } public void addListener( ILabelProviderListener listener ) { } public void dispose( ) { } public boolean isLabelProperty( Object element, String property ) { return false; } public void removeListener( ILabelProviderListener listener ) { } } ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.ui.IPropertyPage#pageActivated() */ public void pageActivated( ) { getContainer( ).setMessage( Messages.getString( "dataset.editor.preview" ),//$NON-NLS-1$ IMessageProvider.NONE ); if ( modelChanged || ( (DataSetEditor) this.getContainer( ) ).modelChanged( ) ) { modelChanged = false; new UIJob( "" ) { //$NON-NLS-1$ public IStatus runInUIThread( IProgressMonitor monitor ) { updateResultsProcess( ); return Status.OK_STATUS; } }.schedule( ); } } protected final void clearResultSetTable( ) { if ( recordList == null ) recordList = new ArrayList( ); else recordList.clear( ); // Clear the columns TableColumn[] columns = resultSetTable.getColumns( ); for ( int n = 0; n < columns.length; n++ ) { columns[n].dispose( ); } // clear everything else resultSetTable.removeAll( ); } /** * Get resultSet * * @return */ private IQueryResults executeProcess( DataRequestSession session ) { errorList = new ArrayList( ); try { metaData = ( (DataSetEditor) this.getContainer( ) ).getCurrentItemModel( ); columnCount = metaData == null ? 0 : metaData.length; // Create a new Report Query definition for retrieving the // columns QueryDefinition query = new QueryDefinition( ); query.setDataSetName( ( (DataSetEditor) getContainer( ) ).getHandle( ) .getQualifiedName( ) ); int maxRow = getMaxRowPreference( ); query.setMaxRows( maxRow ); PropertyHandle handle = ( (DataSetEditor) getContainer( ) ).getHandle( ) .getPropertyHandle( DataSetHandle.PARAMETERS_PROP ); if ( handle != null ) { Iterator paramIter = handle.iterator( ); while ( paramIter.hasNext( ) ) { String value = null; DataSetParameterHandle paramDefn = (DataSetParameterHandle) paramIter.next( ); if ( paramDefn.isInput( ) ) { if ( paramDefn instanceof OdaDataSetParameterHandle && ( (OdaDataSetParameterHandle) paramDefn ).getParamName( ) != null ) { String linkedReportParam = ( (OdaDataSetParameterHandle) paramDefn ).getParamName( ); if ( linkedReportParam != null ) { ParameterHandle ph = ( (DataSetEditor) getContainer( ) ).getHandle( ).getModuleHandle( ).findParameter( linkedReportParam ); if ( ph instanceof ScalarParameterHandle ) { if (((ScalarParameterHandle)ph).getParamType( ).equals( DesignChoiceConstants.SCALAR_PARAM_TYPE_MULTI_VALUE )) { throw new BirtException(Messages.getFormattedString( "dataset.editor.error.invalidLinkedParameter", new String[]{linkedReportParam} ), null); } } } // get the value from report parameter value = DataUtil.getParamValue( ( (DataSetEditor) getContainer( ) ).getHandle( ), (OdaDataSetParameterHandle) paramDefn ); } if ( value != null ) { InputParameterBinding binding = new InputParameterBinding( paramDefn.getName( ), new ScriptExpression( value ) ); query.addInputParamBinding( binding ); } } } } columnBindingNames = new String[columnCount]; ScriptExpression[] expressions = new ScriptExpression[columnCount]; for ( int n = 0; n < columnCount; n++ ) { columnBindingNames[n] = metaData[n].getName( ); expressions[n] = new ScriptExpression( ExpressionUtil.createJSDataSetRowExpression( metaData[n].getName( ) ) ); expressions[n].setDataType( metaData[n].getDataType( ) ); query.addResultSetExpression( columnBindingNames[n], expressions[n] ); } boolean needCache = false; if ( this.previousMaxRow != maxRow ) { this.previousMaxRow = maxRow; needCache = true; } IQueryResults resultSet = DataSetProvider.getCurrentInstance( ) .execute( ( (DataSetEditor) getContainer( ) ).getHandle( ), query, true, true, needCache, session ); return resultSet; } catch ( BirtException e ) { errorList.add( e ); return null; } } private int getMaxRowPreference( ) { int maxRow; Preferences preferences = ReportPlugin.getDefault( ) .getPluginPreferences( ); if ( preferences.contains( DateSetPreferencePage.USER_MAXROW ) ) { maxRow = preferences.getInt( DateSetPreferencePage.USER_MAXROW ); } else { maxRow = DateSetPreferencePage.DEFAULT_MAX_ROW; preferences.setValue( DateSetPreferencePage.USER_MAXROW, maxRow ); } return maxRow; } /** * Show ProgressMonitorDialog * */ private void updateResultsProcess( ) { needsUpdateUI = true; clearResultSetTable( ); IRunnableWithProgress runnable = new IRunnableWithProgress( ) { public void run( IProgressMonitor monitor ) throws InvocationTargetException, InterruptedException { monitor.beginTask( "", IProgressMonitor.UNKNOWN ); //$NON-NLS-1$ if ( resultSetTable != null && !resultSetTable.isDisposed( ) ) { // Set thread context class loader so Rhino can find POJOs // in // workspace // projects ClassLoader oldContextLoader = Thread.currentThread( ) .getContextClassLoader( ); ClassLoader parentLoader = oldContextLoader; if ( parentLoader == null ) parentLoader = this.getClass( ).getClassLoader( ); ClassLoader newContextLoader = DataSetProvider.getCustomScriptClassLoader( parentLoader, ( (DataSetEditor) getContainer( ) ).getHandle( ) .getModuleHandle( ) ); Thread.currentThread( ) .setContextClassLoader( newContextLoader ); Map dataSetBindingMap = new HashMap( ); Map dataSourceBindingMap = new HashMap( ); ModuleHandle handle; DataSetHandle dsHandle = ( (DataSetEditor) getContainer( ) ).getHandle( ); handle = dsHandle.getModuleHandle( ); try { if ( handle instanceof ReportDesignHandle ) { EngineConfig ec = new EngineConfig( ); ec.getAppContext( ) .put( EngineConstants.APPCONTEXT_CLASSLOADER_KEY, newContextLoader ); ReportEngine engine = (ReportEngine) new ReportEngineFactory( ).createReportEngine( ec ); DataSetUIUtil.clearPropertyBindingMap( dsHandle, dataSetBindingMap, dataSourceBindingMap ); DummyEngineTask engineTask = new DummyEngineTask( engine, new ReportEngineHelper( engine ).openReportDesign( (ReportDesignHandle) handle ), handle ); DataRequestSession session = engineTask.getDataSession( ); Map appContext = new HashMap( ); appContext.put( DataEngine.MEMORY_DATA_SET_CACHE, new Integer( ( (DataSetHandle) getContainer( ).getModel( ) ).getRowFetchLimit( ) ) ); engineTask.setAppContext( appContext ); engineTask.run( ); IQueryResults resultSet = executeProcess( session ); populateRecords( resultSet ); engineTask.close( ); engine.destroy( ); monitor.done( ); } else { DataSessionContext context; context = new DataSessionContext( DataSessionContext.MODE_DIRECT_PRESENTATION, ( (DataSetEditor) getContainer( ) ).getHandle( ) .getModuleHandle( ) ); DataRequestSession session = DataRequestSession.newSession( context ); Map appContext = new HashMap( ); appContext.put( DataEngine.MEMORY_DATA_SET_CACHE, new Integer( ( (DataSetHandle) getContainer( ).getModel( ) ).getRowFetchLimit( ) ) ); if ( context.getAppContext( ) != null ) { appContext.putAll( context.getAppContext( ) ); } context.setAppContext( appContext ); IQueryResults resultSet = executeProcess( session ); populateRecords( resultSet ); session.shutdown( ); } } catch ( BirtException e ) { ExceptionHandler.handle( e ); } finally { try { DataSetUIUtil.resetPropertyBinding( dsHandle, dataSetBindingMap, dataSourceBindingMap ); } catch ( SemanticException e ) { } } // Restore old thread context class loader Thread.currentThread( ) .setContextClassLoader( oldContextLoader ); } } }; try { new ProgressMonitorDialog( PlatformUI.getWorkbench( ) .getDisplay( ) .getActiveShell( ) ) { protected void cancelPressed( ) { super.cancelPressed( ); needsUpdateUI = false; } }.run( true, true, runnable ); } catch ( InvocationTargetException e ) { ExceptionHandler.handle( e ); } catch ( InterruptedException e ) { ExceptionHandler.handle( e ); } updateResultSetTableUI( ); } /** * Populate records to be retrieved when re-render resultSetTable * * @param metaData * @param query * @throws BirtException */ private void populateRecords( IQueryResults actualResultSet ) { try { if ( actualResultSet != null ) { IResultIterator iter = actualResultSet.getResultIterator( ); if ( columnCount > 0 ) { while ( iter.next( ) ) { CellValue[] record = new CellValue[columnCount]; for ( int n = 0; n < columnCount; n++ ) { CellValue cv = new CellValue( ); Object value = iter.getValue( columnBindingNames[n] ); String disp = null; if( value instanceof Number ) disp = value.toString( ); else disp = iter.getString( columnBindingNames[n] ); cv.setDisplayValue( disp ); cv.setRealValue( value ); record[n] = cv; } recordList.add( record ); } } setPromptLabelText( ); actualResultSet.close( ); } } catch ( RuntimeException e ) { errorList.add( e ); } catch ( BirtException e ) { errorList.add( e ); } } /** * Set the prompt label text * */ private void setPromptLabelText( ) { Display.getDefault( ).syncExec( new Runnable( ) { public void run( ) { String prompt = ""; prompt = Messages.getFormattedString( "dataset.resultset.preview.promptMessage.recordsNum", new Object[]{ recordList.size( ) } ); if ( recordList != null ) { if ( recordList.size( ) >= getMaxRowPreference( ) ) { prompt += " " + Messages.getString( "dataset.resultset.preview.promptMessage.MoreRecordsExist" ); } } if ( promptLabel != null ) { promptLabel.setText( prompt ); } } } ); } private void updateResultSetTableUI( ) { if ( !needsUpdateUI ) return; if ( !errorList.isEmpty( ) ) { setPromptLabelText( ); ExceptionHandler.handle( (Exception) errorList.get( 0 ) ); } else { if ( metaData != null ) createColumns( metaData ); insertRecords( ); } } private void createColumns( DataSetViewData[] rsMd ) { DataSetViewData[] columnsModel = rsMd; TableColumn column = null; TableLayout layout = new TableLayout( ); for ( int n = 0; n < rsMd.length; n++ ) { column = new TableColumn( resultSetTable, SWT.LEFT ); column.setText( getColumnDisplayName( columnsModel, n ) ); column.setResizable( true ); layout.addColumnData( new ColumnPixelData( 120, true ) ); addColumnSortListener( column, n ); column.pack( ); } resultSetTable.setLayout( layout ); resultSetTable.layout( true ); } private void insertRecords( ) { resultSetTableViewer.setInput( recordList ); } private String getColumnDisplayName( DataSetViewData[] columnsModel, int index ) { if ( columnsModel == null || columnsModel.length == 0 || index < 0 || index > columnsModel.length ) { return "";//$NON-NLS-1$ } return columnsModel[index].getDisplayName( ); } /** * Add listener to a column * * @param column * @param n */ private void addColumnSortListener( TableColumn column, final int index ) { column.addSelectionListener( new SelectionListener( ) { private boolean asc = false; public void widgetSelected( SelectionEvent e ) { sort( index, asc ); asc = !asc; } public void widgetDefaultSelected( SelectionEvent e ) { } } ); } /** * Carry out sort operation against certain column * * @param columnIndex * the column based on which the sort operation would be carried * out * @param asc * the sort direction */ private void sort( final int columnIndex, final boolean asc ) { resultSetTable.setSortColumn( resultSetTable.getColumn( columnIndex ) ); resultSetTable.setSortDirection( asc == true ? SWT.DOWN : SWT.UP ); this.resultSetTableViewer.setSorter( new ViewerSorter( ) { // @Override public int compare( Viewer viewer, Object e1, Object e2 ) { CellValue cv1 = ( (CellValue[]) e1 )[columnIndex]; CellValue cv2 = ( (CellValue[]) e2 )[columnIndex]; int result = 0; if ( cv1 == null && cv1 != cv2 ) result = -1; else if ( cv1 != null ) result = cv1.compareTo( cv2 ); if ( !asc ) return result; else return result * -1; } } ); } /* * (non-Javadoc) * * @see org.eclipse.birt.model.core.Listener#elementChanged(org.eclipse.birt.model.api.DesignElementHandle, * org.eclipse.birt.model.activity.NotificationEvent) */ public void elementChanged( DesignElementHandle focus, NotificationEvent ev ) { if ( focus.equals( getContainer( ).getModel( ) ) || ( (DataSetEditor) this.getContainer( ) ).modelChanged( ) ) { modelChanged = true; } } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.ui.dialogs.properties.IPropertyPage#performCancel() */ public boolean performCancel( ) { ( (DataSetHandle) getContainer( ).getModel( ) ).removeListener( this ); return super.performCancel( ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.ui.dialogs.properties.IPropertyPage#performOk() */ public boolean performOk( ) { ( (DataSetHandle) getContainer( ).getModel( ) ).removeListener( this ); return super.performOk( ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.ui.dialogs.properties.IPropertyPage#getToolTip() */ public String getToolTip( ) { return Messages.getString( "dataset.resultset.preview.tooltip" ); //$NON-NLS-1$ } } /** * The Action factory */ final class ResultSetTableActionFactory { public static final int COPY_ACTION = 1; public static final int SELECTALL_ACTION = 2; public static ResultSetTableAction createResultSetTableAction( Table resultSetTable, int operationID ) { assert resultSetTable != null; ResultSetTableAction rsTableAction = null; if ( operationID == COPY_ACTION ) { rsTableAction = new CopyAction( resultSetTable ); } else if ( operationID == SELECTALL_ACTION ) { rsTableAction = new SelectAllAction( resultSetTable ); } return rsTableAction; } } /** * An implementation of Action */ abstract class ResultSetTableAction extends Action { protected Table resultSetTable = null; public ResultSetTableAction( Table resultSetTable, String actionName ) { super( actionName ); this.resultSetTable = resultSetTable; } /** * This method update the state of the action. Particularly, it will disable * the action under certain circumstance. */ public abstract void update( ); } /** * Copy action. */ final class CopyAction extends ResultSetTableAction { /** * @param resultSetTable * the ResultSetTable against which the action is applied to */ public CopyAction( Table resultSetTable ) { super( resultSetTable, Messages.getString( "CopyAction.text" ) ); //$NON-NLS-1$ this.setImageDescriptor( Utility.getImageDescriptor( ISharedImages.IMG_TOOL_COPY ) ); } /* * @see org.eclipse.jface.action.IAction#run() */ public void run( ) { StringBuffer textData = new StringBuffer( ); for ( int i = 0; i < resultSetTable.getColumnCount( ); i++ ) { textData.append( resultSetTable.getColumn( i ).getText( ) + "\t" ); //$NON-NLS-1$ } textData.append( "\n" ); //$NON-NLS-1$ TableItem[] tableItems = resultSetTable.getSelection( ); for ( int i = 0; i < tableItems.length; i++ ) { for ( int j = 0; j < resultSetTable.getColumnCount( ); j++ ) { textData.append( tableItems[i].getText( j ) + "\t" ); //$NON-NLS-1$ } textData.append( "\n" ); //$NON-NLS-1$ } Clipboard clipboard = new Clipboard( resultSetTable.getDisplay( ) ); clipboard.setContents( new Object[]{ textData.toString( ) }, new Transfer[]{ TextTransfer.getInstance( ) } ); clipboard.dispose( ); } /* * @see org.eclipse.birt.report.designer.internal.ui.dialogs.ResultSetTableAction#update() */ public void update( ) { if ( resultSetTable.getItems( ).length < 1 || resultSetTable.getSelectionCount( ) < 1 ) { this.setEnabled( false ); } } } /** * Select All Action */ final class SelectAllAction extends ResultSetTableAction { /** * @param resultSetTable * the ResultSetTable against which the action is applied to */ public SelectAllAction( Table resultSetTable ) { super( resultSetTable, Messages.getString( "SelectAllAction.text" ) ); //$NON-NLS-1$ } /* * @see org.eclipse.jface.action.IAction#run() */ public void run( ) { resultSetTable.selectAll( ); } /* * @see org.eclipse.birt.report.designer.internal.ui.dialogs.ResultSetTableAction#update() */ public void update( ) { if ( resultSetTable.getItems( ).length < 1 ) { this.setEnabled( false ); } } } final class CellValue implements Comparable { private Object realValue; private String displayValue; public int compareTo( Object o ) { if ( o == null ) { return 1; } CellValue other = (CellValue) o; try { return ScriptEvalUtil.compare( this.realValue, other.realValue); } catch ( DataException e ) { // should never get here assert ( false ); return -1; } } public String toString( ) { return displayValue == null ? "" : displayValue; //$NON-NLS-1$ } public void setRealValue( Object realValue ) { this.realValue = realValue; } public void setDisplayValue( String displayValue ) { this.displayValue = displayValue; } public String getDisplayValue( ) { return displayValue; } }
UI/org.eclipse.birt.report.designer.ui.data/src/org/eclipse/birt/report/designer/data/ui/dataset/ResultSetPreviewPage.java
/******************************************************************************* * Copyright (c) 2004 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.data.ui.dataset; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.birt.core.data.ExpressionUtil; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.data.engine.api.DataEngine; import org.eclipse.birt.data.engine.api.IQueryResults; import org.eclipse.birt.data.engine.api.IResultIterator; import org.eclipse.birt.data.engine.api.querydefn.InputParameterBinding; import org.eclipse.birt.data.engine.api.querydefn.QueryDefinition; import org.eclipse.birt.data.engine.api.querydefn.ScriptExpression; import org.eclipse.birt.data.engine.core.DataException; import org.eclipse.birt.data.engine.script.ScriptEvalUtil; import org.eclipse.birt.report.data.adapter.api.DataRequestSession; import org.eclipse.birt.report.data.adapter.api.DataSessionContext; import org.eclipse.birt.report.designer.data.ui.util.DataSetProvider; import org.eclipse.birt.report.designer.data.ui.util.DataUtil; import org.eclipse.birt.report.designer.data.ui.util.DummyEngineTask; import org.eclipse.birt.report.designer.data.ui.util.Utility; import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler; import org.eclipse.birt.report.designer.nls.Messages; import org.eclipse.birt.report.designer.ui.ReportPlugin; import org.eclipse.birt.report.designer.ui.dialogs.properties.AbstractPropertyPage; import org.eclipse.birt.report.designer.ui.preferences.DateSetPreferencePage; import org.eclipse.birt.report.engine.api.EngineConfig; import org.eclipse.birt.report.engine.api.EngineConstants; import org.eclipse.birt.report.engine.api.impl.ReportEngine; import org.eclipse.birt.report.engine.api.impl.ReportEngineFactory; import org.eclipse.birt.report.engine.api.impl.ReportEngineHelper; import org.eclipse.birt.report.model.api.DataSetHandle; import org.eclipse.birt.report.model.api.DataSetParameterHandle; import org.eclipse.birt.report.model.api.DesignElementHandle; import org.eclipse.birt.report.model.api.ModuleHandle; import org.eclipse.birt.report.model.api.OdaDataSetParameterHandle; import org.eclipse.birt.report.model.api.ParameterHandle; import org.eclipse.birt.report.model.api.PropertyHandle; import org.eclipse.birt.report.model.api.ReportDesignHandle; import org.eclipse.birt.report.model.api.ScalarParameterHandle; import org.eclipse.birt.report.model.api.activity.NotificationEvent; import org.eclipse.birt.report.model.api.activity.SemanticException; import org.eclipse.birt.report.model.api.core.Listener; import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Preferences; import org.eclipse.core.runtime.Status; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.ColumnPixelData; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.TableLayout; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; 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.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.progress.UIJob; /** * Property page to preview the resultset. * */ public class ResultSetPreviewPage extends AbstractPropertyPage implements Listener { private TableViewer resultSetTableViewer = null; private transient Table resultSetTable = null; private boolean modelChanged = true; private boolean needsUpdateUI = true; private int columnCount = -1; private List recordList = null; private DataSetViewData[] metaData; private List errorList = new ArrayList(); private String[] columnBindingNames; private int previousMaxRow = -1; private CLabel promptLabel; /** * The constructor. */ public ResultSetPreviewPage( ) { super( ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.ui.IPropertyPage#createPageControl(org.eclipse.swt.widgets.Composite) */ public Control createPageControl( Composite parent ) { Composite resultSetComposite = new Composite( parent, SWT.NONE ); GridLayout layout = new GridLayout( ); layout.verticalSpacing = 15; resultSetComposite.setLayout( layout ); resultSetComposite.setLayoutData( new GridData( GridData.FILL_BOTH ) ); resultSetTable = new Table( resultSetComposite, SWT.FULL_SELECTION | SWT.MULTI | SWT.VIRTUAL | SWT.BORDER ); resultSetTable.setHeaderVisible( true ); resultSetTable.setLinesVisible( true ); resultSetTable.setLayoutData( new GridData( GridData.FILL_BOTH ) ); ( (DataSetHandle) getContainer( ).getModel( ) ).addListener( this ); resultSetTable.addMouseListener( new MouseAdapter( ) { public void mouseUp( MouseEvent e ) { // if not mouse left button if ( e.button != 1 ) { MenuManager menuManager = new MenuManager( ); ResultSetTableAction copyAction = ResultSetTableActionFactory.createResultSetTableAction( resultSetTable, ResultSetTableActionFactory.COPY_ACTION ); ResultSetTableAction selectAllAction = ResultSetTableActionFactory.createResultSetTableAction( resultSetTable, ResultSetTableActionFactory.SELECTALL_ACTION ); menuManager.add( copyAction ); menuManager.add( selectAllAction ); menuManager.update( ); copyAction.update( ); selectAllAction.update( ); Menu contextMenu = menuManager.createContextMenu( resultSetTable ); contextMenu.setEnabled( true ); contextMenu.setVisible( true ); } } } ); createResultSetTableViewer( ); promptLabel = new CLabel( resultSetComposite, SWT.WRAP ); GridData labelData = new GridData( GridData.FILL_HORIZONTAL ); promptLabel.setLayoutData( labelData ); return resultSetComposite; } private void createResultSetTableViewer( ) { resultSetTableViewer = new TableViewer( resultSetTable ); resultSetTableViewer.setSorter( null ); resultSetTableViewer.setContentProvider( new IStructuredContentProvider( ) { public Object[] getElements( Object inputElement ) { if ( inputElement instanceof List ) { return ( (List) inputElement ).toArray( ); } return new Object[0]; } public void inputChanged( Viewer viewer, Object oldInput, Object newInput ) { } public void dispose( ) { } } ); resultSetTableViewer.setLabelProvider( new ITableLabelProvider( ) { public Image getColumnImage( Object element, int columnIndex ) { return null; } public String getColumnText( Object element, int columnIndex ) { return ( (CellValue[]) element )[columnIndex].getDisplayValue( ); } public void addListener( ILabelProviderListener listener ) { } public void dispose( ) { } public boolean isLabelProperty( Object element, String property ) { return false; } public void removeListener( ILabelProviderListener listener ) { } } ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.ui.IPropertyPage#pageActivated() */ public void pageActivated( ) { getContainer( ).setMessage( Messages.getString( "dataset.editor.preview" ),//$NON-NLS-1$ IMessageProvider.NONE ); if ( modelChanged || ( (DataSetEditor) this.getContainer( ) ).modelChanged( ) ) { modelChanged = false; new UIJob( "" ) { //$NON-NLS-1$ public IStatus runInUIThread( IProgressMonitor monitor ) { updateResultsProcess( ); return Status.OK_STATUS; } }.schedule( ); } } protected final void clearResultSetTable( ) { if ( recordList == null ) recordList = new ArrayList( ); else recordList.clear( ); // Clear the columns TableColumn[] columns = resultSetTable.getColumns( ); for ( int n = 0; n < columns.length; n++ ) { columns[n].dispose( ); } // clear everything else resultSetTable.removeAll( ); } /** * Get resultSet * * @return */ private IQueryResults executeProcess( DataRequestSession session ) { errorList = new ArrayList( ); try { metaData = ( (DataSetEditor) this.getContainer( ) ).getCurrentItemModel( ); columnCount = metaData == null ? 0 : metaData.length; // Create a new Report Query definition for retrieving the // columns QueryDefinition query = new QueryDefinition( ); query.setDataSetName( ( (DataSetEditor) getContainer( ) ).getHandle( ) .getQualifiedName( ) ); int maxRow = getMaxRowPreference( ); query.setMaxRows( maxRow ); PropertyHandle handle = ( (DataSetEditor) getContainer( ) ).getHandle( ) .getPropertyHandle( DataSetHandle.PARAMETERS_PROP ); if ( handle != null ) { Iterator paramIter = handle.iterator( ); while ( paramIter.hasNext( ) ) { String value = null; DataSetParameterHandle paramDefn = (DataSetParameterHandle) paramIter.next( ); if ( paramDefn.isInput( ) ) { if ( paramDefn instanceof OdaDataSetParameterHandle && ( (OdaDataSetParameterHandle) paramDefn ).getParamName( ) != null ) { String linkedReportParam = ( (OdaDataSetParameterHandle) paramDefn ).getParamName( ); if ( linkedReportParam != null ) { ParameterHandle ph = ( (DataSetEditor) getContainer( ) ).getHandle( ).getModuleHandle( ).findParameter( linkedReportParam ); if ( ph instanceof ScalarParameterHandle ) { if (((ScalarParameterHandle)ph).getParamType( ).equals( DesignChoiceConstants.SCALAR_PARAM_TYPE_MULTI_VALUE )) { throw new BirtException(Messages.getFormattedString( "dataset.editor.error.invalidLinkedParameter", new String[]{linkedReportParam} ), null); } } } // get the value from report parameter value = DataUtil.getParamValue( ( (DataSetEditor) getContainer( ) ).getHandle( ), (OdaDataSetParameterHandle) paramDefn ); } if ( value != null ) { InputParameterBinding binding = new InputParameterBinding( paramDefn.getName( ), new ScriptExpression( value ) ); query.addInputParamBinding( binding ); } } } } columnBindingNames = new String[columnCount]; ScriptExpression[] expressions = new ScriptExpression[columnCount]; for ( int n = 0; n < columnCount; n++ ) { columnBindingNames[n] = metaData[n].getName( ); expressions[n] = new ScriptExpression( ExpressionUtil.createJSDataSetRowExpression( metaData[n].getName( ) ) ); expressions[n].setDataType( metaData[n].getDataType( ) ); query.addResultSetExpression( columnBindingNames[n], expressions[n] ); } boolean needCache = false; if ( this.previousMaxRow != maxRow ) { this.previousMaxRow = maxRow; needCache = true; } IQueryResults resultSet = DataSetProvider.getCurrentInstance( ) .execute( ( (DataSetEditor) getContainer( ) ).getHandle( ), query, true, true, needCache, session ); return resultSet; } catch ( BirtException e ) { errorList.add( e ); return null; } } private int getMaxRowPreference( ) { int maxRow; Preferences preferences = ReportPlugin.getDefault( ) .getPluginPreferences( ); if ( preferences.contains( DateSetPreferencePage.USER_MAXROW ) ) { maxRow = preferences.getInt( DateSetPreferencePage.USER_MAXROW ); } else { maxRow = DateSetPreferencePage.DEFAULT_MAX_ROW; preferences.setValue( DateSetPreferencePage.USER_MAXROW, maxRow ); } return maxRow; } /** * Show ProgressMonitorDialog * */ private void updateResultsProcess( ) { needsUpdateUI = true; clearResultSetTable( ); IRunnableWithProgress runnable = new IRunnableWithProgress( ) { public void run( IProgressMonitor monitor ) throws InvocationTargetException, InterruptedException { monitor.beginTask( "", IProgressMonitor.UNKNOWN ); //$NON-NLS-1$ if ( resultSetTable != null && !resultSetTable.isDisposed( ) ) { // Set thread context class loader so Rhino can find POJOs // in // workspace // projects ClassLoader oldContextLoader = Thread.currentThread( ) .getContextClassLoader( ); ClassLoader parentLoader = oldContextLoader; if ( parentLoader == null ) parentLoader = this.getClass( ).getClassLoader( ); ClassLoader newContextLoader = DataSetProvider.getCustomScriptClassLoader( parentLoader, ( (DataSetEditor) getContainer( ) ).getHandle( ) .getModuleHandle( ) ); Thread.currentThread( ) .setContextClassLoader( newContextLoader ); Map dataSetBindingMap = new HashMap( ); Map dataSourceBindingMap = new HashMap( ); ModuleHandle handle; DataSetHandle dsHandle = ( (DataSetEditor) getContainer( ) ).getHandle( ); handle = dsHandle.getModuleHandle( ); try { if ( handle instanceof ReportDesignHandle ) { EngineConfig ec = new EngineConfig( ); ec.getAppContext( ) .put( EngineConstants.APPCONTEXT_CLASSLOADER_KEY, newContextLoader ); ReportEngine engine = (ReportEngine) new ReportEngineFactory( ).createReportEngine( ec ); DataSetUIUtil.clearPropertyBindingMap( dsHandle, dataSetBindingMap, dataSourceBindingMap ); DummyEngineTask engineTask = new DummyEngineTask( engine, new ReportEngineHelper( engine ).openReportDesign( (ReportDesignHandle) handle ), handle ); DataRequestSession session = engineTask.getDataSession( ); Map appContext = new HashMap( ); appContext.put( DataEngine.MEMORY_DATA_SET_CACHE, new Integer( ( (DataSetHandle) getContainer( ).getModel( ) ).getRowFetchLimit( ) ) ); engineTask.setAppContext( appContext ); engineTask.run( ); IQueryResults resultSet = executeProcess( session ); populateRecords( resultSet ); engineTask.close( ); engine.destroy( ); monitor.done( ); } else { DataSessionContext context; context = new DataSessionContext( DataSessionContext.MODE_DIRECT_PRESENTATION, ( (DataSetEditor) getContainer( ) ).getHandle( ) .getModuleHandle( ) ); DataRequestSession session = DataRequestSession.newSession( context ); Map appContext = new HashMap( ); appContext.put( DataEngine.MEMORY_DATA_SET_CACHE, new Integer( ( (DataSetHandle) getContainer( ).getModel( ) ).getRowFetchLimit( ) ) ); context.setAppContext( appContext ); IQueryResults resultSet = executeProcess( session ); populateRecords( resultSet ); session.shutdown( ); } } catch ( BirtException e ) { ExceptionHandler.handle( e ); } finally { try { DataSetUIUtil.resetPropertyBinding( dsHandle, dataSetBindingMap, dataSourceBindingMap ); } catch ( SemanticException e ) { } } // Restore old thread context class loader Thread.currentThread( ) .setContextClassLoader( oldContextLoader ); } } }; try { new ProgressMonitorDialog( PlatformUI.getWorkbench( ) .getDisplay( ) .getActiveShell( ) ) { protected void cancelPressed( ) { super.cancelPressed( ); needsUpdateUI = false; } }.run( true, true, runnable ); } catch ( InvocationTargetException e ) { ExceptionHandler.handle( e ); } catch ( InterruptedException e ) { ExceptionHandler.handle( e ); } updateResultSetTableUI( ); } /** * Populate records to be retrieved when re-render resultSetTable * * @param metaData * @param query * @throws BirtException */ private void populateRecords( IQueryResults actualResultSet ) { try { if ( actualResultSet != null ) { IResultIterator iter = actualResultSet.getResultIterator( ); if ( columnCount > 0 ) { while ( iter.next( ) ) { CellValue[] record = new CellValue[columnCount]; for ( int n = 0; n < columnCount; n++ ) { CellValue cv = new CellValue( ); Object value = iter.getValue( columnBindingNames[n] ); String disp = null; if( value instanceof Number ) disp = value.toString( ); else disp = iter.getString( columnBindingNames[n] ); cv.setDisplayValue( disp ); cv.setRealValue( value ); record[n] = cv; } recordList.add( record ); } } setPromptLabelText( ); actualResultSet.close( ); } } catch ( RuntimeException e ) { errorList.add( e ); } catch ( BirtException e ) { errorList.add( e ); } } /** * Set the prompt label text * */ private void setPromptLabelText( ) { Display.getDefault( ).syncExec( new Runnable( ) { public void run( ) { String prompt = ""; prompt = Messages.getFormattedString( "dataset.resultset.preview.promptMessage.recordsNum", new Object[]{ recordList.size( ) } ); if ( recordList != null ) { if ( recordList.size( ) >= getMaxRowPreference( ) ) { prompt += " " + Messages.getString( "dataset.resultset.preview.promptMessage.MoreRecordsExist" ); } } if ( promptLabel != null ) { promptLabel.setText( prompt ); } } } ); } private void updateResultSetTableUI( ) { if ( !needsUpdateUI ) return; if ( !errorList.isEmpty( ) ) { setPromptLabelText( ); ExceptionHandler.handle( (Exception) errorList.get( 0 ) ); } else { if ( metaData != null ) createColumns( metaData ); insertRecords( ); } } private void createColumns( DataSetViewData[] rsMd ) { DataSetViewData[] columnsModel = rsMd; TableColumn column = null; TableLayout layout = new TableLayout( ); for ( int n = 0; n < rsMd.length; n++ ) { column = new TableColumn( resultSetTable, SWT.LEFT ); column.setText( getColumnDisplayName( columnsModel, n ) ); column.setResizable( true ); layout.addColumnData( new ColumnPixelData( 120, true ) ); addColumnSortListener( column, n ); column.pack( ); } resultSetTable.setLayout( layout ); resultSetTable.layout( true ); } private void insertRecords( ) { resultSetTableViewer.setInput( recordList ); } private String getColumnDisplayName( DataSetViewData[] columnsModel, int index ) { if ( columnsModel == null || columnsModel.length == 0 || index < 0 || index > columnsModel.length ) { return "";//$NON-NLS-1$ } return columnsModel[index].getDisplayName( ); } /** * Add listener to a column * * @param column * @param n */ private void addColumnSortListener( TableColumn column, final int index ) { column.addSelectionListener( new SelectionListener( ) { private boolean asc = false; public void widgetSelected( SelectionEvent e ) { sort( index, asc ); asc = !asc; } public void widgetDefaultSelected( SelectionEvent e ) { } } ); } /** * Carry out sort operation against certain column * * @param columnIndex * the column based on which the sort operation would be carried * out * @param asc * the sort direction */ private void sort( final int columnIndex, final boolean asc ) { resultSetTable.setSortColumn( resultSetTable.getColumn( columnIndex ) ); resultSetTable.setSortDirection( asc == true ? SWT.DOWN : SWT.UP ); this.resultSetTableViewer.setSorter( new ViewerSorter( ) { // @Override public int compare( Viewer viewer, Object e1, Object e2 ) { CellValue cv1 = ( (CellValue[]) e1 )[columnIndex]; CellValue cv2 = ( (CellValue[]) e2 )[columnIndex]; int result = 0; if ( cv1 == null && cv1 != cv2 ) result = -1; else if ( cv1 != null ) result = cv1.compareTo( cv2 ); if ( !asc ) return result; else return result * -1; } } ); } /* * (non-Javadoc) * * @see org.eclipse.birt.model.core.Listener#elementChanged(org.eclipse.birt.model.api.DesignElementHandle, * org.eclipse.birt.model.activity.NotificationEvent) */ public void elementChanged( DesignElementHandle focus, NotificationEvent ev ) { if ( focus.equals( getContainer( ).getModel( ) ) || ( (DataSetEditor) this.getContainer( ) ).modelChanged( ) ) { modelChanged = true; } } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.ui.dialogs.properties.IPropertyPage#performCancel() */ public boolean performCancel( ) { ( (DataSetHandle) getContainer( ).getModel( ) ).removeListener( this ); return super.performCancel( ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.ui.dialogs.properties.IPropertyPage#performOk() */ public boolean performOk( ) { ( (DataSetHandle) getContainer( ).getModel( ) ).removeListener( this ); return super.performOk( ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.ui.dialogs.properties.IPropertyPage#getToolTip() */ public String getToolTip( ) { return Messages.getString( "dataset.resultset.preview.tooltip" ); //$NON-NLS-1$ } } /** * The Action factory */ final class ResultSetTableActionFactory { public static final int COPY_ACTION = 1; public static final int SELECTALL_ACTION = 2; public static ResultSetTableAction createResultSetTableAction( Table resultSetTable, int operationID ) { assert resultSetTable != null; ResultSetTableAction rsTableAction = null; if ( operationID == COPY_ACTION ) { rsTableAction = new CopyAction( resultSetTable ); } else if ( operationID == SELECTALL_ACTION ) { rsTableAction = new SelectAllAction( resultSetTable ); } return rsTableAction; } } /** * An implementation of Action */ abstract class ResultSetTableAction extends Action { protected Table resultSetTable = null; public ResultSetTableAction( Table resultSetTable, String actionName ) { super( actionName ); this.resultSetTable = resultSetTable; } /** * This method update the state of the action. Particularly, it will disable * the action under certain circumstance. */ public abstract void update( ); } /** * Copy action. */ final class CopyAction extends ResultSetTableAction { /** * @param resultSetTable * the ResultSetTable against which the action is applied to */ public CopyAction( Table resultSetTable ) { super( resultSetTable, Messages.getString( "CopyAction.text" ) ); //$NON-NLS-1$ this.setImageDescriptor( Utility.getImageDescriptor( ISharedImages.IMG_TOOL_COPY ) ); } /* * @see org.eclipse.jface.action.IAction#run() */ public void run( ) { StringBuffer textData = new StringBuffer( ); for ( int i = 0; i < resultSetTable.getColumnCount( ); i++ ) { textData.append( resultSetTable.getColumn( i ).getText( ) + "\t" ); //$NON-NLS-1$ } textData.append( "\n" ); //$NON-NLS-1$ TableItem[] tableItems = resultSetTable.getSelection( ); for ( int i = 0; i < tableItems.length; i++ ) { for ( int j = 0; j < resultSetTable.getColumnCount( ); j++ ) { textData.append( tableItems[i].getText( j ) + "\t" ); //$NON-NLS-1$ } textData.append( "\n" ); //$NON-NLS-1$ } Clipboard clipboard = new Clipboard( resultSetTable.getDisplay( ) ); clipboard.setContents( new Object[]{ textData.toString( ) }, new Transfer[]{ TextTransfer.getInstance( ) } ); clipboard.dispose( ); } /* * @see org.eclipse.birt.report.designer.internal.ui.dialogs.ResultSetTableAction#update() */ public void update( ) { if ( resultSetTable.getItems( ).length < 1 || resultSetTable.getSelectionCount( ) < 1 ) { this.setEnabled( false ); } } } /** * Select All Action */ final class SelectAllAction extends ResultSetTableAction { /** * @param resultSetTable * the ResultSetTable against which the action is applied to */ public SelectAllAction( Table resultSetTable ) { super( resultSetTable, Messages.getString( "SelectAllAction.text" ) ); //$NON-NLS-1$ } /* * @see org.eclipse.jface.action.IAction#run() */ public void run( ) { resultSetTable.selectAll( ); } /* * @see org.eclipse.birt.report.designer.internal.ui.dialogs.ResultSetTableAction#update() */ public void update( ) { if ( resultSetTable.getItems( ).length < 1 ) { this.setEnabled( false ); } } } final class CellValue implements Comparable { private Object realValue; private String displayValue; public int compareTo( Object o ) { if ( o == null ) { return 1; } CellValue other = (CellValue) o; try { return ScriptEvalUtil.compare( this.realValue, other.realValue); } catch ( DataException e ) { // should never get here assert ( false ); return -1; } } public String toString( ) { return displayValue == null ? "" : displayValue; //$NON-NLS-1$ } public void setRealValue( Object realValue ) { this.realValue = realValue; } public void setDisplayValue( String displayValue ) { this.displayValue = displayValue; } public String getDisplayValue( ) { return displayValue; } }
CheckIn:Ted16002--Project 1119: POJO Data source failed to use relative path jar/class folder in report library
UI/org.eclipse.birt.report.designer.ui.data/src/org/eclipse/birt/report/designer/data/ui/dataset/ResultSetPreviewPage.java
CheckIn:Ted16002--Project 1119: POJO Data source failed to use relative path jar/class folder in report library
<ide><path>I/org.eclipse.birt.report.designer.ui.data/src/org/eclipse/birt/report/designer/data/ui/dataset/ResultSetPreviewPage.java <ide> Map appContext = new HashMap( ); <ide> appContext.put( DataEngine.MEMORY_DATA_SET_CACHE, <ide> new Integer( ( (DataSetHandle) getContainer( ).getModel( ) ).getRowFetchLimit( ) ) ); <del> <add> if ( context.getAppContext( ) != null ) <add> { <add> appContext.putAll( context.getAppContext( ) ); <add> } <ide> context.setAppContext( appContext ); <del> <ide> IQueryResults resultSet = executeProcess( session ); <ide> populateRecords( resultSet ); <ide> session.shutdown( );
Java
lgpl-2.1
error: pathspec 'src/polyglot/visit/ExtensionCleaner.java' did not match any file(s) known to git
ab47d3df0ea5a2d0aa633a7cc87e7ae4cd0b9067
1
liujed/polyglot-eclipse,blue-systems-group/project.maybe.polyglot,xcv58/polyglot,xcv58/polyglot,blue-systems-group/project.maybe.polyglot,xcv58/polyglot,blue-systems-group/project.maybe.polyglot,liujed/polyglot-eclipse,liujed/polyglot-eclipse,liujed/polyglot-eclipse,xcv58/polyglot,blue-systems-group/project.maybe.polyglot
package polyglot.visit; import polyglot.ast.*; import polyglot.types.*; import polyglot.frontend.ExtensionInfo; import polyglot.util.*; import polyglot.types.Package; import java.util.*; /** * This visitor overwrites all extension object refs with null, * sets delegate object refs to point back to the node, * and strips type information out. **/ public class ExtensionCleaner extends NodeVisitor { protected NodeFactory nf; protected TypeSystem ts; protected ExtensionInfo javaExt; public ExtensionCleaner(ExtensionInfo javaExt) { this.javaExt = javaExt; this.nf = javaExt.nodeFactory(); this.ts = javaExt.typeSystem(); } public Node leave(Node old, Node n, NodeVisitor v) { n = n.ext(null); n = n.del(null); n = strip(n); return n; } protected Node strip(Node n) { // FIXME: should use method dispatch for this. if (n instanceof Call) { n = ((Call) n).methodInstance(null); } if (n instanceof ClassDecl) { n = ((ClassDecl) n).type(null); } if (n instanceof ConstructorCall) { n = ((ConstructorCall) n).constructorInstance(null); } if (n instanceof Field) { n = ((Field) n).fieldInstance(null); } if (n instanceof FieldDecl) { n = ((FieldDecl) n).fieldInstance(null); n = ((FieldDecl) n).initializerInstance(null); } if (n instanceof Formal) { n = ((Formal) n).localInstance(null); } if (n instanceof Initializer) { n = ((Initializer) n).initializerInstance(null); } if (n instanceof Local) { n = ((Local) n).localInstance(null); } if (n instanceof LocalDecl) { n = ((LocalDecl) n).localInstance(null); } if (n instanceof MethodDecl) { n = ((MethodDecl) n).methodInstance(null); } if (n instanceof New) { n = ((New) n).anonType(null); n = ((New) n).constructorInstance(null); } if (n instanceof TypeNode) { n = convert((TypeNode) n); } if (n instanceof PackageNode) { n = convert((PackageNode) n); } if (n instanceof Expr) { n = ((Expr) n).type(null); } return n; } protected TypeNode convert(TypeNode n) { Type t = n.type(); if (n instanceof CanonicalTypeNode) { if (t.typeSystem() == ts) { return n; } else { throw new InternalCompilerError("Unexpected Jx type: " + t + " found in rewritten AST."); } } // Must be an AmbTypeNode if (t != null && t.isCanonical()) { if (t.typeSystem() == ts) { return nf.CanonicalTypeNode(n.position(), t); } } n = n.type(null); return n; } protected PackageNode convert(PackageNode n) { Package p = n.package_(); if (p != null && p.isCanonical()) { if (p.typeSystem() == ts) { return nf.PackageNode(n.position(), p); } } return nf.PackageNode(n.position(), ts.createPackage(n.toString())); } }
src/polyglot/visit/ExtensionCleaner.java
Visitor to strip extension-specific information from an AST. Based on the visitor in JMatch.
src/polyglot/visit/ExtensionCleaner.java
Visitor to strip extension-specific information from an AST. Based on the visitor in JMatch.
<ide><path>rc/polyglot/visit/ExtensionCleaner.java <add>package polyglot.visit; <add> <add>import polyglot.ast.*; <add>import polyglot.types.*; <add>import polyglot.frontend.ExtensionInfo; <add>import polyglot.util.*; <add>import polyglot.types.Package; <add> <add>import java.util.*; <add> <add>/** <add> * This visitor overwrites all extension object refs with null, <add> * sets delegate object refs to point back to the node, <add> * and strips type information out. <add> **/ <add>public class ExtensionCleaner extends NodeVisitor { <add> protected NodeFactory nf; <add> protected TypeSystem ts; <add> protected ExtensionInfo javaExt; <add> <add> public ExtensionCleaner(ExtensionInfo javaExt) { <add> this.javaExt = javaExt; <add> this.nf = javaExt.nodeFactory(); <add> this.ts = javaExt.typeSystem(); <add> } <add> <add> public Node leave(Node old, Node n, NodeVisitor v) { <add> n = n.ext(null); <add> n = n.del(null); <add> n = strip(n); <add> return n; <add> } <add> <add> protected Node strip(Node n) { <add> // FIXME: should use method dispatch for this. <add> if (n instanceof Call) { <add> n = ((Call) n).methodInstance(null); <add> } <add> <add> if (n instanceof ClassDecl) { <add> n = ((ClassDecl) n).type(null); <add> } <add> <add> if (n instanceof ConstructorCall) { <add> n = ((ConstructorCall) n).constructorInstance(null); <add> } <add> <add> if (n instanceof Field) { <add> n = ((Field) n).fieldInstance(null); <add> } <add> <add> if (n instanceof FieldDecl) { <add> n = ((FieldDecl) n).fieldInstance(null); <add> n = ((FieldDecl) n).initializerInstance(null); <add> } <add> <add> if (n instanceof Formal) { <add> n = ((Formal) n).localInstance(null); <add> } <add> <add> if (n instanceof Initializer) { <add> n = ((Initializer) n).initializerInstance(null); <add> } <add> <add> if (n instanceof Local) { <add> n = ((Local) n).localInstance(null); <add> } <add> <add> if (n instanceof LocalDecl) { <add> n = ((LocalDecl) n).localInstance(null); <add> } <add> <add> if (n instanceof MethodDecl) { <add> n = ((MethodDecl) n).methodInstance(null); <add> } <add> <add> if (n instanceof New) { <add> n = ((New) n).anonType(null); <add> n = ((New) n).constructorInstance(null); <add> } <add> <add> if (n instanceof TypeNode) { <add> n = convert((TypeNode) n); <add> } <add> <add> if (n instanceof PackageNode) { <add> n = convert((PackageNode) n); <add> } <add> <add> if (n instanceof Expr) { <add> n = ((Expr) n).type(null); <add> } <add> <add> return n; <add> } <add> <add> protected TypeNode convert(TypeNode n) { <add> Type t = n.type(); <add> <add> if (n instanceof CanonicalTypeNode) { <add> if (t.typeSystem() == ts) { <add> return n; <add> } <add> else { <add> throw new InternalCompilerError("Unexpected Jx type: " + t + " found in rewritten AST."); <add> } <add> } <add> <add> // Must be an AmbTypeNode <add> <add> if (t != null && t.isCanonical()) { <add> if (t.typeSystem() == ts) { <add> return nf.CanonicalTypeNode(n.position(), t); <add> } <add> } <add> <add> n = n.type(null); <add> <add> return n; <add> } <add> <add> protected PackageNode convert(PackageNode n) { <add> Package p = n.package_(); <add> <add> if (p != null && p.isCanonical()) { <add> if (p.typeSystem() == ts) { <add> return nf.PackageNode(n.position(), p); <add> } <add> } <add> <add> return nf.PackageNode(n.position(), ts.createPackage(n.toString())); <add> } <add>}
JavaScript
mit
305c38edd27a3a1e55a9a2afb8ff88842bcdee18
0
t-kelly/slate,t-kelly/slate
/** * Variant Selection scripts * ------------------------------------------------------------------------------ * * Handles change events from the variant inputs in any `cart/add` forms that may * exist. Also updates the master select and triggers updates when the variants * price or image changes. * * @namespace variants */ slate.Variants = (function() { /** * Variant constructor * * @param {object} options - Settings from `product.js` */ function Variants(options) { this.$container = options.$container; this.product = options.product; this.singleOptionSelector = options.singleOptionSelector; this.originalSelectorId = options.originalSelectorId; this.enableHistoryState = options.enableHistoryState; this.currentVariant = this._getVariantFromOptions(); $(this.singleOptionSelector, this.$container).on('change', this._onSelectChange.bind(this)); } Variants.prototype = _.assignIn({}, Variants.prototype, { /** * Get the currently selected options from add-to-cart form. Works with all * form input elements. * * @return {array} options - Values of currently selected variants */ _getCurrentOptions: function() { var currentOptions = _.map($(this.singleOptionSelector, this.$container), function(element) { var $element = $(element); var type = $element.attr('type'); if (type === 'radio' || type === 'checkbox') { if ($element[0].checked) { return $element.val(); } else { return false; } } else { return $element.val(); } }); // remove any unchecked input values if using radio buttons or checkboxes currentOptions = _.compact(currentOptions); return currentOptions; }, /** * Find variant based on selected values. * * @param {array} selectedValues - Values of variant inputs * @return {object || undefined} found - Variant object from product.variants */ _getVariantFromOptions: function() { var selectedValues = this._getCurrentOptions(); var variants = this.product.variants; var found = _.find(variants, function(variant) { return selectedValues.every(function(value) { return (variant.options.indexOf(value) !== -1); }); }); return found; }, /** * Event handler for when a variant input changes. */ _onSelectChange: function() { var variant = this._getVariantFromOptions(); this.$container.trigger({ type: 'variantChange', variant: variant }); if (!variant) { return; } this._updateMasterSelect(variant); this._updateImages(variant); this._updatePrice(variant); this.currentVariant = variant; if (this.enableHistoryState) { this._updateHistoryState(variant); } }, /** * Trigger event when variant image changes * * @param {object} variant - Currently selected variant * @return {event} variantImageChange */ _updateImages: function(variant) { var variantImage = variant.featured_image || {}; var currentVariantImage = this.currentVariant.featured_image || {}; if (!variant.featured_image || variantImage.src === currentVariantImage.src) { return; } this.$container.trigger({ type: 'variantImageChange', variant: variant }); }, /** * Trigger event when variant price changes. * * @param {object} variant - Currently selected variant * @return {event} variantPriceChange */ _updatePrice: function(variant) { if (variant.price === this.currentVariant.price && variant.compare_at_price === this.currentVariant.compare_at_price) { return; } this.$container.trigger({ type: 'variantPriceChange', variant: variant }); }, /** * Update history state for product deeplinking * * @param {variant} variant - Currently selected variant * @return {k} [description] */ _updateHistoryState: function(variant) { if (!history.replaceState || !variant) { return; } var newurl = window.location.protocol + '//' + window.location.host + window.location.pathname + '?variant=' + variant.id; window.history.replaceState({path: newurl}, '', newurl); }, /** * Update hidden master select of variant change * * @param {variant} variant - Currently selected variant */ _updateMasterSelect: function(variant) { $(this.originalSelectorId, this.$container)[0].value = variant.id; } }); return Variants; })();
src/scripts/slate/variants.js
/** * Variant Selection scripts * ------------------------------------------------------------------------------ * * Handles change events from the variant inputs in any `cart/add` forms that may * exist. Also updates the master select and triggers updates when the variants * price or image changes. * * @namespace variants */ slate.Variants = (function() { /** * Variant constructor * * @param {object} options - Settings from `product.js` */ function Variants(options) { this.$container = options.$container; this.product = options.product; this.singleOptionSelector = options.singleOptionSelector; this.originalSelectorId = options.originalSelectorId; this.enableHistoryState = options.enableHistoryState; this.currentVariant = this._getVariantFromOptions(); $(this.singleOptionSelector, this.$container).on('change', this._onSelectChange.bind(this)); } Variants.prototype = _.assignIn({}, Variants.prototype, { /** * Get the currently selected options from add-to-cart form. Works with all * form input elements. * * @return {array} options - Values of currently selected variants */ _getCurrentOptions: function() { var currentOptions = _.map($(this.singleOptionSelector, this.$container), function(element) { var $element = $(element); var type = $element.attr('type'); if (type === 'radio' || type === 'checkbox') { if ($element[0].checked) { return $element.val(); } else { return false; } } else { return $element.val(); } }); // remove any unchecked input values if using radio buttons or checkboxes currentOptions = _.compact(currentOptions); return currentOptions; }, /** * Find variant based on selected values. * * @param {array} selectedValues - Values of variant inputs * @return {object || undefined} found - Variant object from product.variants */ _getVariantFromOptions: function() { var selectedValues = this._getCurrentOptions(); var variants = this.product.variants; var found = _.find(variants, function(variant) { return selectedValues.every(function(value) { return (variant.options.indexOf(value) !== -1); }); }); return found; }, /** * Event handler for when a variant input changes. */ _onSelectChange: function() { var variant = this._getVariantFromOptions(); this.$container.trigger({ type: 'variantChange', variant: variant }); if (!variant) { return; } this._updateMasterSelect(variant); this._updateImages(variant); this._updatePrice(variant); this.currentVariant = variant; if (this.enableHistoryState) { this._updateHistoryState(variant); } }, /** * Trigger event when variant image changes * * @param {object} variant - Currently selected variant * @return {event} variantImageChange */ _updateImages: function(variant) { var variantImage = variant.featured_image || {}; var currentVariantImage = this.currentVariant.featured_image || {}; if (!variant.featured_image || variantImage.src === currentVariantImage.src) { return; } this.$container.trigger({ type: 'variantImageChange', variant: variant }); }, /** * Trigger event when variant price changes. * * @param {object} variant - Currently selected variant * @return {event} variantPriceChange */ _updatePrice: function(variant) { if (variant.price === this.currentVariant.price && variant.compare_at_price === this.currentVariant.compare_at_price) { return; } this.$container.trigger({ type: 'variantPriceChange', variant: variant }); }, /** * Update history state for product deeplinking * * @param {variant} variant - Currently selected variant * @return {k} [description] */ _updateHistoryState: function(variant) { if (!history.replaceState || !variant) { return; } var newurl = window.location.protocol + '//' + window.location.host + window.location.pathname + '?variant=' + variant.id; window.history.replaceState({path: newurl}, '', newurl); }, /** * Update hidden master select of variant change * * @param {variant} variant - Currently selected variant */ _updateMasterSelect: function(variant) { var $originalSelector = $(this.originalSelectorId, this.$container); if (!variant) { return; } $originalSelector.find('[selected]').removeAttr('selected'); $originalSelector.find('[value=' + variant.id + ']').attr('selected', 'selected'); } }); return Variants; })();
fixes master select not updating (#44)
src/scripts/slate/variants.js
fixes master select not updating (#44)
<ide><path>rc/scripts/slate/variants.js <ide> * @param {variant} variant - Currently selected variant <ide> */ <ide> _updateMasterSelect: function(variant) { <del> var $originalSelector = $(this.originalSelectorId, this.$container); <del> <del> if (!variant) { <del> return; <del> } <del> <del> $originalSelector.find('[selected]').removeAttr('selected'); <del> $originalSelector.find('[value=' + variant.id + ']').attr('selected', 'selected'); <add> $(this.originalSelectorId, this.$container)[0].value = variant.id; <ide> } <ide> }); <ide>
Java
agpl-3.0
a51b532da699adb081c6e9393e83558c05e288a7
0
smith750/kfs,ua-eas/kfs-devops-automation-fork,kuali/kfs,bhutchinson/kfs,ua-eas/kfs,ua-eas/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/kfs,UniversityOfHawaii/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/kfs,quikkian-ua-devops/will-financials,kuali/kfs,ua-eas/kfs-devops-automation-fork,kuali/kfs,kkronenb/kfs,ua-eas/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/kfs,smith750/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs-devops-automation-fork,bhutchinson/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/will-financials,kuali/kfs,kkronenb/kfs,smith750/kfs,kkronenb/kfs,bhutchinson/kfs,smith750/kfs,ua-eas/kfs-devops-automation-fork,UniversityOfHawaii/kfs,kkronenb/kfs,ua-eas/kfs,bhutchinson/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs,kuali/kfs
/* * Copyright 2007 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; import java.util.HashMap; import org.apache.commons.lang.StringUtils; import org.kuali.core.JstlConstants; import org.kuali.core.service.DataDictionaryService; import org.kuali.core.util.KualiDecimal; import org.kuali.kfs.context.SpringContext; import org.kuali.module.gl.bo.OriginEntryFull; import org.kuali.workflow.attribute.RoutingAccount; import org.kuali.workflow.attribute.OrgReviewRoutingData; import org.kuali.workflow.attribute.RoutingData; /** * This class is used to define global constants. */ public class KFSConstants extends JstlConstants implements ParameterKeyConstants { private static final long serialVersionUID = 2882277719647128949L; // special user used in the post-processor public static final String SYSTEM_USER = "KULUSER"; public static final String ENVIRONMENT_KEY = "environment"; public static final String VERSION_KEY = "version"; public static final String LOG4J_SETTINGS_FILE_KEY = "log4j.settings.file"; public static final String LOGS_DIRECTORY_KEY = "logs.directory"; public static final String LOG4J_RELOAD_MINUTES_KEY = "log4j.reload.minutes"; public static final String APPLICATION_URL_KEY = "application.url"; public static final String ATTACHMENTS_DIRECTORY_KEY = "attachments.directory"; public static final String ATTACHMENTS_PENDING_DIRECTORY_KEY = "attachments.pending.directory"; public static final String HTDOCS_LOGS_URL_KEY = "htdocs.logs.url"; public static final String HTDOCS_STAGING_URL_KEY = "htdocs.staging.url"; public static final String STAGING_DIRECTORY_KEY = "staging.directory"; public static final String TEMP_DIRECTORY_KEY = "temp.directory"; public static final String EXTERNALIZABLE_HELP_URL_KEY = "externalizable.help.url"; public static final String EXTERNALIZABLE_IMAGES_URL_KEY = "externalizable.images.url"; public static final String EXTERNALIZABLE_XML_URL_KEY = "externalizable.xml.url"; public static final String RICE_EXTERNALIZABLE_IMAGES_URL_KEY = "kr.externalizable.images.url"; public static final String REPORTS_DIRECTORY_KEY = "reports.directory"; public static final String WORKFLOW_URL_KEY = "workflow.url"; public static final String PROD_ENVIRONMENT_CODE_KEY = "production.environment.code"; public static final String MAINTAIN_USERS_LOCALLY_KEY = "maintain.users.locally"; public static final String USE_STANDALONE_WORKFLOW = "rice.use.standalone.workflow"; public static final String DATABASE_REPOSITORY_FILES_LIST_NAME = "databaseRepositoryFilePaths"; public static final String SCRIPT_CONFIGURATION_FILES_LIST_NAME = "scriptConfigurationFilePaths"; public static final String JOB_NAMES_LIST_NAME = "jobNames"; public static final String TRIGGER_NAMES_LIST_NAME = "triggerNames"; public static final String LOOKUP_RESULTS_LIMIT_URL_KEY = "RESULTS_LIMIT"; public static final String DOCHANDLER_DO_URL = "/DocHandler.do?docId="; public static final String DOCHANDLER_URL_CHUNK = "&command=displayDocSearchView"; public static final String ACCOUNT_NUMBER_PROPERTY_NAME = "accountNumber"; public static final String MODULE_ID_PROPERTY_NAME = "moduleId"; public static final String MODULE_CODE_PROPERTY_NAME = "moduleCode"; public static final String ACCOUNT_STATUS_CLOSED = "Y"; public static final String ACCOUNTING_PERIOD_STATUS_CODE_FIELD = "universityFiscalPeriodStatusCode"; public static final String ACCOUNTING_PERIOD_STATUS_CLOSED = "C"; public static final String ACCOUNTING_PERIOD_STATUS_OPEN = "O"; public static final String ACCOUNTING_STRING_SOURCE_ENTRY = "@"; public static final String ACCOUNTING_STRING_SOURCE_ACCOUNT = "#"; public static final String ACTION_FORM_UTIL_MAP_METHOD_PARM_DELIMITER = "~"; public static final String ADD_LINE_METHOD = "addLine"; public static final String ADD_PREFIX = "add"; public static final String ACTIVE_INDICATOR = "Y"; public static final String AGGREGATE_ENCUMBRANCE_BALANCE_TYPE_CODE = "EN"; public static final String AMOUNT_PROPERTY_NAME = "amount"; public static final String APPROVE_METHOD = "approve"; public static final String NON_ACTIVE_INDICATOR = "N"; public static final String BLANK_SPACE = " "; public static final String BACK_LOCATION = "backLocation"; public static final String BACKDOOR_PARAMETER = "backdoorId"; public static final String BALANCE_INQUIRY_REPORT_MENU_ACTION = "balanceInquiryReportMenu.do"; public static final String BALANCE_TYPE_PROPERTY_NAME = "balanceTypeCode"; public static final String BALANCE_TYPE_CURRENT_BUDGET = "CB"; public static final String BALANCE_TYPE_BASE_BUDGET = "BB"; public static final String BALANCE_TYPE_MONTHLY_BUDGET = "MB"; public static final String BALANCE_TYPE_EXTERNAL_ENCUMBRANCE = "EX"; public static final String BALANCE_TYPE_INTERNAL_ENCUMBRANCE = "IE"; public static final String BALANCE_TYPE_COST_SHARE_ENCUMBRANCE = "CE"; public static final String BALANCE_TYPE_ACTUAL = "AC"; public static final String BALANCE_TYPE_AUDIT_TRAIL = "NB"; public static final String BALANCE_TYPE_A21 = "A2"; public static final String BALANCE_TYPE_BUDGET_STATISTICS = "BS"; public static final String BALANCE_TYPE_PRE_ENCUMBRANCE = "PE"; public static final String BLANKET_APPROVE_METHOD = "blanketApprove"; public static final String BUSINESS_OBJECT_CLASS_ATTRIBUTE = "businessObjectClassName"; public static final String CALLING_METHOD = "caller"; public static final String CASH_MANAGEMENT_DOCUMENT_ACTION = "financialCashManagement.do"; public static final String CHANGE_JOURNAL_VOUCHER_BALANCE_TYPE_METHOD = "changeBalanceType"; public static final String CHART_OF_ACCOUNTS_CODE_PROPERTY_NAME = "chartOfAccountsCode"; public static final String CONFIRMATION_QUESTION = "confirmationQuestion"; public static final String CONSOLIDATED_SUBACCOUNT = "*ALL*"; public static final String CONVERSION_FIELDS_PARAMETER = "conversionFields"; public static final String LOOKUP_READ_ONLY_FIELDS = "readOnlyFields"; public static final String LOOKUP_AUTO_SEARCH = "autoSearch"; public static final String COST_SHARE = "CS"; public static final String CREDIT_AMOUNT_PROPERTY_NAME = "newSourceLineCredit"; public static final String DEBIT_AMOUNT_PROPERTY_NAME = "newSourceLineDebit"; public static final String DELETE_LINE_METHOD = "deleteLine"; public static final String DICTIONARY_BO_NAME = "dictionaryBusinessObjectName"; public static final String DISENCUMBRANCE = "Disencumbrance"; public static final String DISPATCH_REQUEST_PARAMETER = "methodToCall"; public static final String DOC_FORM_KEY = "docFormKey"; public static final String BALANCE_INQUIRY_REPORT_MENU_CALLER_DOC_FORM_KEY = "balanceInquiryReportMenuCallerDocFormKey"; public static final String DOCUMENT_CANCEL_QUESTION = "DocCancel"; public static final String DOCUMENT_DELETE_QUESTION = "DocDelete"; public static final String DOCUMENT_DISAPPROVE_QUESTION = "DocDisapprove"; public static final String DOCUMENT_HEADER_ID = "documentHeaderId"; public static final String DOCUMENT_HEADER_DOCUMENT_STATUS_CODE_PROPERTY_NAME = "financialDocumentStatusCode"; public static final String NOTE_TEXT_PROPERTY_NAME = "noteText"; public static final String DOCUMENT_HEADER_PROPERTY_NAME = "documentHeader"; public static final String DOCUMENT_SAVE_BEFORE_CLOSE_QUESTION = "DocSaveBeforeClose"; public static final String EMPLOYEE_ACTIVE_STATUS = "A"; public static final String EXISTING_SOURCE_ACCT_LINE_PROPERTY_NAME = "sourceAccountingLine"; public static final String EXISTING_TARGET_ACCT_LINE_PROPERTY_NAME = "targetAccountingLine"; public static final String SOURCE_ACCT_LINE_TYPE_CODE = "F"; // F = From, the label for this on most documents public static final String TARGET_ACCT_LINE_TYPE_CODE = "T"; // T = To, the label for this on most documents public static final String EXTRA_BUTTON_SOURCE = "extraButtonSource"; public static final String EXTRA_BUTTON_PARAMS = "extraButtonParams"; public static final String NEW_DOCUMENT_NOTE_PROPERTY_NAME = "newDocumentNote"; public static final String NEW_AD_HOC_ROUTE_PERSON_PROPERTY_NAME = "newAdHocRoutePerson"; public static final String NEW_AD_HOC_ROUTE_WORKGROUP_PROPERTY_NAME = "newAdHocRouteWorkgroup"; public static final String EXISTING_AD_HOC_ROUTE_PERSON_PROPERTY_NAME = "adHocRoutePerson"; public static final String EXISTING_AD_HOC_ROUTE_WORKGROUP_PROPERTY_NAME = "adHocRouteWorkgroup"; public static final String NEW_SOURCE_ACCT_LINE_PROPERTY_NAME = "newSourceLine"; public static final String NEW_TARGET_ACCT_LINES_PROPERTY_NAME = "newTargetLines"; public static final String NEW_TARGET_ACCT_LINE_PROPERTY_NAME = "newTargetLine"; public static final String DOCUMENT_PROPERTY_NAME = "document"; public static final String DOCUMENT_TYPE_NAME = "docTypeName"; public static final String EDIT_PREFIX = "edit"; public static final String DASH = "-"; public static final String EMPTY_STRING = ""; public static final String ENCUMBRANCE = "Encumbrance"; public static final String EXPENSE = "Expense"; public static final String FIELD_CONVERSION_PAIR_SEPERATOR = ":"; public static final String FIELD_CONVERSIONS_SEPERATOR = ","; public static final String REFERENCES_TO_REFRESH_SEPARATOR = ","; public static final String FIELD_CONVERSION_PREFIX_PARAMETER = "fieldConversionPrefix"; public static final String FINANCIAL_OBJECT_CODE_PROPERTY_NAME = "financialObjectCode"; public static final String FINANCIAL_OBJECT_LEVEL_CODE_PROPERTY_NAME = "financialObjectLevelCode"; public static final String FINANCIAL_SUB_OBJECT_CODE_PROPERTY_NAME = "financialSubObjectCode"; public static final String FISCAL_CHART_NAME = "fiscalChartOfAccountsCode"; public static final String FISCAL_ORG_NAME = "fiscalOrganizationCode"; public static final String FROM = "From"; public static final String GENERIC_FIELD_NAME = "Field"; public static final String GENERIC_CODE_PROPERTY_NAME = "code"; public static final String GL_BALANCE_INQUIRY_FLAG = "inquiryFlag"; public static final String GL_ACCOUNT_BALANCE_BY_CONSOLIDATION_LOOKUP_ACTION = "glAccountBalanceByConsolidationLookup.do"; public static final String GL_BALANCE_INQUIRY_ACTION = "glBalanceInquiry.do"; public static final String GL_MODIFIED_INQUIRY_ACTION = "glModifiedInquiry.do"; public static final String GL_PE_OFFSET_STRING = "TP Generated Offset"; public static final String SUB_OBJECT_CODE_PROPERTY_NAME = "subObjectCode"; public static final String UNIVERSITY_FISCAL_YEAR_PROPERTY_NAME = "universityFiscalYear"; public static final String UNIVERSITY_FISCAL_PERIOD_CODE_PROPERTY_NAME = "universityFiscalPeriodCode"; public static final String FINANCIAL_BALANCE_TYPE_CODE_PROPERTY_NAME = "financialBalanceTypeCode"; public static final String ACCOUNT_SUFFICIENT_FUNDS_CODE_PROPERTY_NAME = "accountSufficientFundsCode"; public static final String CURRENT_BUDGET_BALANCE_AMOUNT_PROPERTY_NAME = "currentBudgetBalanceAmount"; public static final String ACCOUNT_ENCUMBRANCE_AMOUNT_PROPERTY_NAME = "accountEncumbranceAmount"; public static final String TRANSACTION_DEBIT_CREDIT_CODE = "transactionDebitCreditCode"; public static final String TRANSACTION_LEDGER_ENTRY_AMOUNT = "transactionLedgerEntryAmount"; public static final String ACCOUNT_SUFFICIENT_FUNDS_FINANCIAL_OBJECT_CODE_PROPERTY_NAME = "acctSufficientFundsFinObjCd"; public static final String FINANCIAL_OBJECT_TYPE_CODE = "financialObjectTypeCode"; public static final String FINANCIAL_DOCUMENT_TYPE_CODE = "financialDocumentTypeCode"; public static final String ORGANIZATION_CODE_PROPERTY_NAME = "organizationCode"; public static final String ORIGIN_CODE_KUALI = "01"; public static final String TRANSFER_FUNDS = "TF"; public static final String[] ENCUMBRANCE_BALANCE_TYPE = new String[] { BALANCE_TYPE_EXTERNAL_ENCUMBRANCE, BALANCE_TYPE_INTERNAL_ENCUMBRANCE, BALANCE_TYPE_PRE_ENCUMBRANCE }; public static final String LABOR_DISTRIBUTION_ORIGIN_CODE = "LD"; public static final String STAND_IN_BUSINESS_OBJECT_FOR_ATTRIBUTES = "KFSAttributeReferenceDummy"; public static final String LABOR_MODIFIED_INQUIRY_ACTION = "laborModifiedInquiry.do"; public static final String LABOR_A2_BALANCE_TYPE = "A2"; public static final String EMPLOYEE_FUNDING_INQUIRY_ACTION = "employeeFundingInquiry.do"; public static final String OVERRIDE_KEYS = "overrideKeys"; public static final String[] LLCP_GROUP_FILTER_EXCEPTION = new String[] { "LLGL" }; public static final String PERCENTAGE_SIGN = "%"; /** * This value denotes that a max length has not been defined for a given lookup results field */ public static final int LOOKUP_RESULT_FIELD_MAX_LENGTH_NOT_DEFINED = -1; /** * The number of levels BusinessObjectDictionaryServiceImpl will recurse. If this number is high, it may lead to serious * performance problems */ public static final int BUSINESS_OBJECT_DICTIONARY_SERVICE_PERFORM_FORCE_UPPERCASE_RECURSION_MAX_DEPTH = 3; /** * When checkboxes are rendered on the form, a hidden field will also be rendered corresponding to each checkbox with the * checkbox's name suffixed with the value of this constant. No real fields should have names that contain this suffix, since * this may lead to undesired results. */ public static final String CHECKBOX_PRESENT_ON_FORM_ANNOTATION = "{CheckboxPresentOnFormAnnotation}"; public static class OrgReversion { public static final String VALID_PREFIX = "EXTENDED_DEFINITIONS_INCLUDE_"; public static final String INVALID_PREFIX = "EXTENDED_DEFINITIONS_EXCLUDE_"; public static final String OBJECT_CONSOL_PARAM_SUFFIX = "OBJECT_CONSOLIDATIONS_BY_ORGANIZATION_REVERSION_CATEGORY"; public static final String OBJECT_LEVEL_PARAM_SUFFIX = "OBJECT_LEVELS_BY_ORGANIZATION_REVERSION_CATEGORY"; public static final String OBJECT_TYPE_PARAM_SUFFIX = "OBJECT_TYPES_BY_ORGANIZATION_REVERSION_CATEGORY"; public static final String OBJECT_SUB_TYPE_PARAM_SUFFIX = "OBJECT_SUB_TYPES_BY_ORGANIZATION_REVERSION_CATEGORY"; public static final String IS_EXPENSE_PARAM = "EXTENDED_DEFINITIONS_EXPENSE_CATEGORIES"; } // CR doc properties public static final String NEW_CHECK_PROPERTY_NAME = "newCheck"; public static final String EXISTING_CHECK_PROPERTY_NAME = "check"; public static final int DOCUMENT_ANNOTATION_MAX_LENGTH = 2000; // TRN_LDGR_DEBIT_CRDT_CD valid values public static final String GL_DEBIT_CODE = "D"; public static final String GL_CREDIT_CODE = "C"; public static final String GL_BUDGET_CODE = " "; // TRN_ENCUM_UPDT_CD value values public static final String ENCUMB_UPDT_DOCUMENT_CD = "D"; public static final String ENCUMB_UPDT_REFERENCE_DOCUMENT_CD = "R"; public static final String ENCUMB_UPDT_NO_ENCUMBRANCE_CD = "N"; // GL Reversal Generated Entry Description Prefix public static final String GL_REVERSAL_DESCRIPTION_PREFIX = "AUTO REVERSAL-"; // Misc GL text. public static final String PLANT_INDEBTEDNESS_ENTRY_DESCRIPTION = "GENERATED TRANSFER TO NET PLANT"; // Sufficient Funds Type Codes public static final String SF_TYPE_NO_CHECKING = "N"; public static final String SF_TYPE_OBJECT = "O"; public static final String SF_TYPE_LEVEL = "L"; public static final String SF_TYPE_CONSOLIDATION = "C"; public static final String SF_TYPE_CASH_AT_ACCOUNT = "H"; public static final String SF_TYPE_ACCOUNT = "A"; public static final String BUDGET_CHECKING_OPTIONS_CD_ACTIVE = "Y"; public static final String GRANT = "Grant"; public static final String HIDE_LOOKUP_RETURN_LINK = "hideReturnLink"; public static final String SUPPRESS_ACTIONS = "suppressActions"; public static final String REFERENCES_TO_REFRESH = "referencesToRefresh"; public static final String INCOME = "Income"; public static final String INITIAL_KUALI_DOCUMENT_STATUS_CD = "?"; public static final String INSERT_SOURCE_LINE_METHOD = "insertSourceLine"; public static final String INSERT_TARGET_LINE_METHOD = "insertTargetLine"; public static final String ICR = "Receipt"; public static final String PARM_SECTION_NAME_FIELD = "FS_SCR_NM"; public static final String PARM_PARM_NAME_FIELD = "FS_PARM_NM"; public static final String PROJECT_CODE_PROPERTY_NAME = "projectCode"; public static final String INQUIRABLE_ATTRIBUTE_NAME = "kualiInquirable"; public static final String INQUIRY_ACTION = "kr/inquiry.do"; public static final String INQUIRY_IMPL_ATTRIBUTE_NAME = "inquirableImplServiceName"; public static final String JOURNAL_VOUCHER_CHANGE_BALANCE_TYPE_QUESTION = "JournalVoucherChangeBalanceTypeQuestion"; public static final String JOURNAL_VOUCHER_ROUTE_OUT_OF_BALANCE_DOCUMENT_QUESTION = "JournalVoucherRouteOutOfBalanceDocumentQuestion"; public static final String JOURNAL_VOUCHER_ENCUMBRANCE_UPDATE_CODE_BALANCE_TYPE_EXTERNAL_ENCUMBRANCE = "R"; public static final String JOURNAL_LINE_HELPER_PROPERTY_NAME = "journalLineHelper"; public static final String AUXILIARY_LINE_HELPER_PROPERTY_NAME = "auxiliaryLineHelper"; public static final String VOUCHER_LINE_HELPER_CREDIT_PROPERTY_NAME = ".credit"; public static final String VOUCHER_LINE_HELPER_DEBIT_PROPERTY_NAME = ".debit"; public static final String KUALI_WORKFLOW_APPLICATION_CODE = "kuali"; public static final String LOOKUP_ACTION = "kr/lookup.do"; public static final String LOOKUP_RESULTS_SEQUENCE_NUMBER = "lookupResultsSequenceNumber"; public static final String LOOKUP_RESULTS_BO_CLASS_NAME = "lookupResultsBOClassName"; public static final String LOOKED_UP_COLLECTION_NAME = "lookedUpCollectionName"; public static final String MULTIPLE_VALUE_LOOKUP_PREVIOUSLY_SELECTED_OBJ_IDS_PARAM = "previouslySelectedObjectIds"; public static final String MULTIPLE_VALUE_LOOKUP_OBJ_IDS_SEPARATOR = "||"; public static final String MULTIPLE_VALUE_LOOKUP_DISPLAYED_OBJ_ID_PARAM_PREFIX = "displayedObjId-"; public static final String MULTIPLE_VALUE_LOOKUP_SELECTED_OBJ_ID_PARAM_PREFIX = "selectedObjId-"; public static final String LOOKUP_ANCHOR = "lookupAnchor"; public static final String LOOKUPABLE_IMPL_ATTRIBUTE_NAME = "lookupableImplServiceName"; public static final String LOOKUP_RESULTS_SEQUENCE = "LOOKUP_RESULT_SEQUENCE_NBR_SEQ"; public static final String KUALI_LOOKUPABLE_IMPL = "kualiLookupable"; public static final String KUALI_USER_LOOKUPABLE_IMPL = "universalUserLookupable"; public static final String DOC_HANDLER_ACTION = "DocHandler.do"; public static final String DOC_HANDLER_METHOD = "docHandler"; public static final String PARAMETER_DOC_ID = "docId"; public static final String PARAMETER_COMMAND = "command"; public static final String LOOKUP_METHOD = "performLookup"; public static final String METHOD_DISPLAY_DOC_SEARCH_VIEW = "displayDocSearchView"; public static final String MAINTENANCE_ACTION = "maintenance.do"; public static final String MAINTENANCE_ADD_PREFIX = "add."; public static final String MAINTENANCE_COPY_ACTION = "Copy"; public static final String MAINTENANCE_EDIT_ACTION = "Edit"; public static final String MAINTENANCE_NEW_ACTION = "New"; public static final String MAINTENANCE_COPY_METHOD_TO_CALL = "copy"; public static final String MAINTENANCE_EDIT_METHOD_TO_CALL = "edit"; public static final String MAINTENANCE_NEW_METHOD_TO_CALL = "start"; public static final String MAINTENANCE_NEWWITHEXISTING_ACTION = "newWithExisting"; public static final String MAINTENANCE_NEW_MAINTAINABLE = "document.newMaintainableObject."; public static final String MAINTENANCE_OLD_MAINTAINABLE = "document.oldMaintainableObject."; public static final String ENCRYPTED_LIST_PREFIX = "encryptedValues"; public static final String MAPPING_BASIC = "basic"; public static final String MAPPING_CANCEL = "cancel"; public static final String MAPPING_CLOSE = "close"; public static final String MAPPING_DISAPPROVE = "disapprove"; public static final String MAPPING_DELETE = "delete"; public static final String MAPPING_ERROR = "error"; public static final String MAPPING_PORTAL = "portal"; public static final String MAPPING_MULTIPLE_VALUE_LOOKUP = "multipleValueLookup"; public static final String MAPPING_BALANCE_INQUIRY_REPORT_MENU = "balanceInquiryReportMenu"; public static final String MAPPING_DV_PER_DIEM_LINKS = "dvPerDiemLinks"; public static final String MAXLENGTH_SUFFIX = ".maxLength"; public static final String METHOD_TO_CALL_ATTRIBUTE = "methodToCallAttribute"; public static final String METHOD_TO_CALL_PATH = "methodToCallPath"; public static final String METHOD_TO_CALL_BOPARM_LEFT_DEL = "(!!"; public static final String METHOD_TO_CALL_BOPARM_RIGHT_DEL = "!!)"; public static final String METHOD_TO_CALL_PARM1_LEFT_DEL = "((("; public static final String METHOD_TO_CALL_PARM1_RIGHT_DEL = ")))"; public static final String METHOD_TO_CALL_PARM2_LEFT_DEL = "((#"; public static final String METHOD_TO_CALL_PARM2_RIGHT_DEL = "#))"; public static final String METHOD_TO_CALL_PARM3_LEFT_DEL = "((<"; public static final String METHOD_TO_CALL_PARM3_RIGHT_DEL = ">))"; public static final String METHOD_TO_CALL_PARM4_LEFT_DEL = "((["; public static final String METHOD_TO_CALL_PARM4_RIGHT_DEL = "]))"; public static final String METHOD_TO_CALL_PARM5_LEFT_DEL = "((*"; public static final String METHOD_TO_CALL_PARM5_RIGHT_DEL = "*))"; public static final String METHOD_TO_CALL_PARM6_LEFT_DEL = "((%"; public static final String METHOD_TO_CALL_PARM6_RIGHT_DEL = "%))"; public static final String METHOD_TO_CALL_PARM7_LEFT_DEL = "((^"; public static final String METHOD_TO_CALL_PARM7_RIGHT_DEL = "^))"; public static final String METHOD_TO_CALL_PARM8_LEFT_DEL = "((&"; public static final String METHOD_TO_CALL_PARM8_RIGHT_DEL = "&))"; public static final String METHOD_TO_CALL_PARM9_LEFT_DEL = "((~"; public static final String METHOD_TO_CALL_PARM9_RIGHT_DEL = "~))"; public static final String METHOD_TO_CALL_PARM10_LEFT_DEL = "((/"; public static final String METHOD_TO_CALL_PARM10_RIGHT_DEL = "/))"; public static final String METHOD_TO_CALL_PARM11_LEFT_DEL = "(:;"; public static final String METHOD_TO_CALL_PARM11_RIGHT_DEL = ";:)"; public static final String METHOD_TO_CALL_PARM12_LEFT_DEL = "(::;"; public static final String METHOD_TO_CALL_PARM12_RIGHT_DEL = ";::)"; public static final String METHOD_TO_CALL_PARM13_LEFT_DEL = "(:::;"; public static final String METHOD_TO_CALL_PARM13_RIGHT_DEL = ";:::)"; // if more strings needed, then add more colons to the PARM11 strings above, e.g. (::; (:::;, etc. public static final String ANCHOR = "anchor"; public static final String ANCHOR_TOP_OF_FORM = "topOfForm"; public static final String QUESTION_ANCHOR = "questionAnchor"; public static final String NOT_AVAILABLE_STRING = "N/A"; public static final int NEGATIVE_ONE = -1; public static final String OBJECT_CODE_STATUS_ACTIVE = "Y"; public static final String OBJECT_TYPE_CODE_PROPERTY_NAME = "objectTypeCode"; public static final String CONTEXT_PATH = "contextPath"; public static final String QUESTION_ACTION = "questionPrompt.do"; public static final String QUESTION_CLICKED_BUTTON = "buttonClicked"; public static final String QUESTION_ERROR_KEY = "questionErrorKey"; public static final String QUESTION_ERROR_PROPERTY_NAME = "questionErrorPropertyName"; public static final String QUESTION_ERROR_PARAMETER = "questionErrorParameter"; public static final String QUESTION_IMPL_ATTRIBUTE_NAME = "questionType"; public static final String QUESTION_INST_ATTRIBUTE_NAME = "questionIndex"; public static final String QUESTION_PAGE_TITLE = "Question Dialog Page"; public static final String QUESTION_REFRESH = "QuestionRefresh"; public static final String QUESTION_CONTEXT = "context"; public static final String QUESTION_TEXT_ATTRIBUTE_NAME = "questionText"; public static final String QUESTION_REASON_ATTRIBUTE_NAME = "reason"; public static final String QUESTION_SHOW_REASON_FIELD = "showReasonField"; public static final String RELOAD_METHOD_TO_CALL = "reload"; public static final String REFRESH_CALLER = "refreshCaller"; public static final String REFRESH_MAPPING_PREFIX = "/Refresh"; public static final String REQUIRED_FIELD_SYMBOL = "*"; public static final String RETURN_LOCATION_PARAMETER = "returnLocation"; public static final String RETURN_METHOD_TO_CALL = "refresh"; public static final String ROUTE_METHOD = "route"; public static final String SAVE_METHOD = "save"; public static final String START_METHOD = "start"; public static final String SEARCH_METHOD = "search"; public static final String COPY_METHOD = "copy"; public static final String ERRORCORRECT_METHOD = "correct"; public static final String SOURCE = "Source"; public static final String SQUARE_BRACKET_LEFT = "["; public static final String SQUARE_BRACKET_RIGHT = "]"; public static final String SUB_ACCOUNT_STATUS_ACTIVE = "Y"; public static final String SUB_ACCOUNT_NUMBER_PROPERTY_NAME = "subAccountNumber"; public static final String SUB_OBJECT_CODE_STATUS_ACTIVE = "Y"; public static final String TARGET = "Target"; public static final String TO = "To"; public static final String USER_SESSION_KEY = "UserSession"; public static final String VERSION_NUMBER = "versionNumber"; public static final String SEARCH_LIST_KEY_PREFIX = "searchResults"; public static final String SEARCH_LIST_REQUEST_KEY = "searchResultKey"; public static final String CORRECTION_FORM_KEY = "correctionFormKey"; public static final int CORRECTION_RECENT_GROUPS_DAY = 10; public static final String SEARCH_DATA_KEY_PREFIX = "dataSearchResults"; public static final String SEARCH_DATA_REQUEST_KEY = "searchResultDataKey"; public static final String GLOBAL_ERRORS = "GLOBAL_ERRORS"; public static final String GLOBAL_MESSAGES = "GlobalMessages"; public static final String AD_HOC_ROUTE_PERSON_ERRORS = "newAdHocRoutePerson*,adHocRoutePerson*"; public static final String AD_HOC_ROUTE_WORKGROUP_ERRORS = "newAdHocRouteWorkgroup*,adHocRouteWorkgroup*"; public static final String DOCUMENT_DOCUMENT_ERRORS = "document.document*"; public static final String DOCUMENT_EXPLANATION_ERRORS = "document.explanation*"; public static final String DOCUMENT_REVERSAL_ERRORS = "document.reversal*"; public static final String DOCUMENT_SELECTED_ERRORS = "document.selected*"; public static final String DOCUMENT_HEADER_ERRORS = "document.header*"; public static final String DOCUMENT_ERRORS_LESS_DOCUMENT = DOCUMENT_EXPLANATION_ERRORS + "," + DOCUMENT_REVERSAL_ERRORS + "," + DOCUMENT_SELECTED_ERRORS + "," + DOCUMENT_HEADER_ERRORS; public static final String DOCUMENT_ERRORS = DOCUMENT_DOCUMENT_ERRORS + "," + DOCUMENT_EXPLANATION_ERRORS + "," + DOCUMENT_REVERSAL_ERRORS + "," + DOCUMENT_SELECTED_ERRORS + "," + DOCUMENT_HEADER_ERRORS; public static final String DOCUMENT_NOTES_ERRORS = "newDocumentNote*"; public static final String BUDGET_PARAMETERS_ERRORS = "newBudgetParameters*"; public static final String BUDGET_PERMISSIONS_ERRORS = "newBudgetPermissions*"; public static final String BUDGET_SPREADSHEET_ERRORS = "newBudgetPermissions*"; public static final String BUDGET_OUTPUT_ERRORS = "newBudgetPermissions*"; public static final String BUDGET_COSTING_ERRORS = "newBudgetPermissions*"; public enum NoteTypeEnum { BUSINESS_OBJECT_NOTE_TYPE("BO", "documentBusinessObject"), DOCUMENT_HEADER_NOTE_TYPE("DH", "documentHeader"); private String noteTypeCode; private String noteTypePath; private NoteTypeEnum(String noteTypeCode, String noteTypePath) { this.noteTypeCode = noteTypeCode; this.noteTypePath = noteTypePath; } public String getCode() { return this.noteTypeCode; } public String getPath() { return this.noteTypePath; } public String getFullPath() { return KFSConstants.DOCUMENT_PROPERTY_NAME + "." + getPath(); } } public static final String EDIT_JOURNAL_VOUCHER_ERRORS = "EditJournalVoucherErrors"; public static final String EDIT_AUXILIARY_VOUCHER_ERRORS = "EditAuxiliaryVoucherErrors"; public static final String EDIT_PRE_ENCUMBRANCE_ERRORS = "EditPreEncumbranceErrors"; public static final String ACCOUNTING_LINE_ERRORS = "document.accountingLines"; public static final String SOURCE_ACCOUNTING_LINE_ERROR_PATTERN = "document.sourceAccounting*,sourceAccountingLines,newSourceLine*,journalLineHelper*,auxiliaryLineHelper*"; public static final String TARGET_ACCOUNTING_LINE_ERROR_PATTERN = "document.targetAccounting*,targetAccountingLines,newTargetLine*"; public static final String ACCOUNTING_LINE_GROUP_SUFFIX = "s"; public static final String SOURCE_ACCOUNTING_LINE_ERRORS = EXISTING_SOURCE_ACCT_LINE_PROPERTY_NAME + ACCOUNTING_LINE_GROUP_SUFFIX; public static final String TARGET_ACCOUNTING_LINE_ERRORS = EXISTING_TARGET_ACCT_LINE_PROPERTY_NAME + ACCOUNTING_LINE_GROUP_SUFFIX; public static final String ITEM_LINE_ERRORS = "newItem*,document.item*"; public static final String CREDIT_CARD_RECEIPTS_LINE_ERRORS = "newCreditCardReceipt*,document.creditCardReceipt*"; public static final String ADVANCE_DEPOSITS_LINE_ERRORS = "newAdvanceDeposit*,document.advanceDeposit*"; public static final String GENERAL_LEDGER_PENDING_ENTRIES_TAB_ERRORS = "document.generalLedgerPendingEntr*"; public static final String BUDGET_CONSTRUCTION_SALARY_SETTING_TAB_ERRORS = "document.budgetConstructionSalarySetting*"; public static final String BUDGET_CONSTRUCTION_REVENUE_TAB_ERRORS = "document.budgetConstructionRevenue*"; public static final String BUDGET_CONSTRUCTION_EXPENDITURE_TAB_ERRORS = "document.budgetConstructionExpenditure*"; public static final String BUDGET_CONSTRUCTION_MONTHLY_BUDGET_ERRORS = "document.budgetConstructionMonthlyBudget*"; public static final String CASHIER_CLOSING_DRAWER_ERRORS = "document.bursarControl*"; public static final String AND_LOGICAL_OPERATOR = "&&"; public static final String OR_LOGICAL_OPERATOR = "|"; public static final String NOT_LOGICAL_OPERATOR = "!"; // add AND operator to thest if it is uncommented below public static final String[] LOGICAL_OPERATORS = { OR_LOGICAL_OPERATOR, NOT_LOGICAL_OPERATOR }; public static final String WILDCARD_CHARACTER = "*"; public static final String[] QUERY_CHARACTERS = { WILDCARD_CHARACTER, "?", "%", ">", "<", "..", OR_LOGICAL_OPERATOR, NOT_LOGICAL_OPERATOR, "=" }; public static final String WILDCARD_NOT_ALLOWED_ON_FIELD = "error.fieldDoNotAllowWildcard"; // disbursement voucher error fields public static final String DV_PAYEE_TAB_ERRORS = "DVPayeeErrors,document.dvPayeeDetail.disbVchrPayeeIdNumber,document.dvPayeeDetail.disbVchrPayeeCityName,document.dvPayeeDetail.disbVchrPayeePersonName," + "document.dvPayeeDetail.disbVchrPayeeStateCode,document.dvPayeeDetail.disbVchrPayeeLine1Addr,document.dvPayeeDetail.disbVchrPayeeZipCode,document.dvPayeeDetail.disbVchrPayeeLine2Addr,document.dvPayeeDetail.disbVchrPayeeCountryCode,document.dvPayeeDetail.disbursementVoucherPayeeTypeCode,"; public static final String DV_PAYMENT_TAB_ERRORS = "DVPaymentErrors,document.dvPayeeDetail.disbVchrPaymentReasonCode,document.disbVchrCheckTotalAmount,document.disbursementVoucherDueDate,document.dvPayeeDetail.disbVchrAlienPaymentCode," + "document.dvPayeeDetail.disbVchrPayeeEmployeeCode,document.disbVchrAttachmentCode,document.disbVchrSpecialHandlingCode,document.disbVchrPayeeW9CompleteCode" + "document.disbVchrPaymentMethodCode,document.disbursementVoucherDocumentationLocationCode,document.disbVchrCheckStubText"; public static final String DV_NRATAX_TAB_ERRORS = "DVNRATaxErrors,document.dvNonResidentAlienTax.incomeClassCode,document.dvNonResidentAlienTax.incomeTaxTreatyExemptCode,document.dvNonResidentAlienTax.federalIncomeTaxPercent," + "document.dvNonResidentAlienTax.foreignSourceIncomeCode,document.dvNonResidentAlienTax.stateIncomeTaxPercent,document.dvNonResidentAlienTax.incomeTaxGrossUpCode,document.dvNonResidentAlienTax.postalCountryCode," + "document.dvNonResidentAlienTax.referenceFinancialDocumentNumber"; public static final String DV_FOREIGNDRAFTS_TAB_ERRORS = "DVForeignDraftErrors,document.dvWireTransfer.disbursementVoucherForeignCurrencyTypeCode,document.dvWireTransfer.disbursementVoucherForeignCurrencyTypeName"; public static final String DV_CONTACT_TAB_ERRORS = "DVContactErrors,document.disbVchrContact*"; public static final String DV_SPECHAND_TAB_ERRORS = "DVSpecialHandlingErrors,document.dvPayeeDetail.disbVchrRemitPersonName,document.dvPayeeDetail.disbVchrRemitCityName,document.dvPayeeDetail.disbVchrRemitLine1Addr,document.dvPayeeDetail.disbVchrRemitStateCode," + "document.dvPayeeDetail.disbVchrRemitLine2Addr,document.dvPayeeDetail.disbVchrRemitZipCode,document.dvPayeeDetail.disbVchrRemitCountryName"; public static final String DV_WIRETRANSFER_TAB_ERRORS = "DVWireTransfersErrors,document.dvWireTransfer.disbursementVoucherBankName,document.dvWireTransfer.disbVchrBankRoutingNumber,document.dvWireTransfer.disbVchrBankCityName,document.dvWireTransfer.disbVchrBankStateCode," + "document.dvWireTransfer.disbVchrBankCountryCode,document.dvWireTransfer.disbVchrAttentionLineText,document.dvWireTransfer.disbVchrAdditionalWireText,document.dvWireTransfer.disbVchrPayeeAccountNumber,document.dvWireTransfer.disbVchrCurrencyTypeName,document.dvWireTransfer.disbVchrCurrencyTypeCode," + "document.dvWireTransfer.disbursementVoucherWireTransferFeeWaiverIndicator,document.dvWireTransfer.disbursementVoucherPayeeAccountName,document.dvWireTransfer.disbursementVoucherPayeeAccountTypeCode,document.dvWireTransfer.disbursementVoucherAutomatedClearingHouseProfileNumber"; public static final String DV_NON_EMPL_TRAVEL_TAB_ERRORS = "DVNonEmployeeTravelErrors,newPrePaidNonEmployeeExpenseLine.*,newNonEmployeeExpenseLine.*,document.dvNonEmployeeTravel.*"; public static final String DV_PREPAID_TAB_ERRORS = "DVPrePaidTravelErrors,newPreConferenceRegistrantLine.*,document.dvPreConferenceDetail.*"; public static final String PAYEE_W9_QUESTION = "PayeeW9Question"; public static final String PAYEE_NAME_EXIST_QUESTION = "PayeeNameExistQuestion"; public static final String COPY_NEW_PAYEE_ADDRESS_LINES = "NewPayeeCopyAddressLinesQuestion"; public static final String COPY_CHANGE_PAYEE_ADDRESS_LINES = "ChangePayeeCopyAddressLinesQuestion"; public static final String DV_PAYMENT_REASON_NONEMPLOYEE = "N"; public static final String DV_PAYMENT_REASON_NONEMPLOYEE_HONORARIUM = "X"; public static final String GENERAL_PAYEE_TAB_ERRORS = "DVPayeeErrors"; public static final String GENERAL_PAYMENT_TAB_ERRORS = "DVPaymentErrors"; public static final String GENERAL_NRATAX_TAB_ERRORS = "DVNRATaxErrors"; public static final String GENERAL_FOREIGNDRAFTS_TAB_ERRORS = "DVForeignDraftErrors"; public static final String GENERAL_CONTACT_TAB_ERRORS = "DVContactErrors"; public static final String GENERAL_SPECHAND_TAB_ERRORS = "DVSpecialHandlingErrors"; public static final String GENERAL_WIRETRANSFER_TAB_ERRORS = "DVWireTransfersErrors"; public static final String GENERAL_PREPAID_TAB_ERRORS = "DVPrePaidTravelErrors"; public static final String GENERAL_NONEMPLOYEE_TAB_ERRORS = "DVNonEmployeeTravelErrors,document.dvNonEmployeeTravel.totalTravelAmount"; public static final String DV_PAYEE_ID_FIELD_NAME = "dvPayeeDetail.disbVchrPayeeIdNumber"; public static final String DV_PAYMENT_REASON_FIELD_NAME = "dvPayeeDetail.disbVchrPaymentReasonCode"; public static final String DV_CHECK_TRAVEL_TOTAL_ERROR = "document.dvNonEmployeeTravel.totalTravelAmount"; // KRA-related constant values public static final KualiDecimal CONTRACTS_AND_GRANTS_FRINGE_RATE_MAX = new KualiDecimal("100.0"); public static final KualiDecimal CONTRACTS_AND_GRANTS_COST_SHARE_MAX = new KualiDecimal("100.0"); public static final KualiDecimal GRADUATE_ASSISTANT_RATE_MAX = new KualiDecimal("9999.99"); public static final String AUDIT_ERRORS = "AuditErrors"; // Header Tab navigation constant values public static final String NAVIGATE_TO = "navigateTo."; public static final String HEADER_DISPATCH = "headerDispatch."; // country public static final String COUNTRY_CODE_UNITED_STATES = "US"; // CashManagement tab errors public static final String CASH_MANAGEMENT_DEPOSIT_ERRORS = "document.deposit*"; // Coin and Currency Amounts public static class CoinTypeAmounts { public static final KualiDecimal HUNDRED_CENT_AMOUNT = new KualiDecimal(1.0); public static final KualiDecimal FIFTY_CENT_AMOUNT = new KualiDecimal(0.5); public static final KualiDecimal TWENTY_FIVE_CENT_AMOUNT = new KualiDecimal(0.25); public static final KualiDecimal TEN_CENT_AMOUNT = new KualiDecimal(0.1); public static final KualiDecimal FIVE_CENT_AMOUNT = new KualiDecimal(0.05); public static final KualiDecimal ONE_CENT_AMOUNT = new KualiDecimal(0.01); } public static class CurrencyTypeAmounts { public static final KualiDecimal HUNDRED_DOLLAR_AMOUNT = new KualiDecimal(100.0); public static final KualiDecimal FIFTY_DOLLAR_AMOUNT = new KualiDecimal(50.0); public static final KualiDecimal TWENTY_DOLLAR_AMOUNT = new KualiDecimal(20.0); public static final KualiDecimal TEN_DOLLAR_AMOUNT = new KualiDecimal(10.0); public static final KualiDecimal FIVE_DOLLAR_AMOUNT = new KualiDecimal(5.0); public static final KualiDecimal TWO_DOLLAR_AMOUNT = new KualiDecimal(2.0); public static final KualiDecimal ONE_DOLLAR_AMOUNT = new KualiDecimal(1.0); } // Cashiering source constants public static class CurrencyCoinSources { public static final String CASH_MANAGEMENT_IN = "R"; // money coming in through cashiering activity public static final String DEPOSITS = "D"; // money going out through deposits public static final String CASH_RECEIPTS = "C"; // money coming in through cash receipts public static final String CASH_MANAGEMENT_OUT = "O"; // money going out through cashiering activity public static final String CASH_MANAGEMENT_MASTER = "M"; // an amalgamation of a cashiering transaction } // Constants for check sources // Why are these constants different from the Currency/Coin constants? // Why, I ask you in return, is the sky blue? That's right, because of // the effect of Rayleigh scattering on atmospheric particles. That's why. public static class CheckSources { public static final String CASH_RECEIPTS = "R"; public static final String CASH_MANAGEMENT = "I"; } public static final String CASHIERING_TRANSACTION_OPEN_ITEM_IN_PROCESS_PROPERTY = "document.currentTransaction.openItemInProcess"; // Tab error patterns must be at the top level; JSPs do not have access to the nested classes. public static final String EDIT_CASH_RECEIPT_CASH_RECONCILIATION_ERRORS = "document.totalCashAmount,document.totalCheckAmount,document.totalCoinAmount,document.sumTotalAmount"; public static final String EDIT_CASH_RECEIPT_CHECK_DETAIL_ERRORS = "newCheck*,document.check*"; public static final String EDIT_CASH_RECEIPT_CURRENCY_COIN_ERRORS = "document.currencyDetail.*,document.coinDetail.*"; public static final String EDIT_CASH_MANAGEMENT_CASHIERING_TRANSACTION_ERRORS = "document.currentTransaction.*"; public static final String MULTIPLE_VALUE = "multipleValues"; public static final String MULTIPLE_VALUE_LABEL = "Lookup initial values"; public static final String MULTIPLE_VALUE_NAME = "Multiple Value Name"; // Agency type codes public static final String AGENCY_TYPE_CODE_FEDERAL = "F"; // special chars that I don't know how to put into string literals in JSP expression language public static final String NEWLINE = "\n"; // Workflow constants public static final String WORKFLOW_FYI_REQUEST = "F"; public static final String WORKFLOW_APPROVE_REQUEST = "A"; // Permission codes public static final String PERMISSION_READ_CODE = "R"; public static final String PERMISSION_READ_DESCRIPTION = "READ"; public static final String PERMISSION_MOD_CODE = "M"; public static final String PERMISSION_MOD_DESCRIPTION = "MOD"; public static final String PERMISSION_MODIFY = "modify"; public static final String PERMISSION_VIEW = "view"; public static class DocumentStatusCodes { public static final String INITIATED = "?"; public static final String CANCELLED = "X"; public static final String ENROUTE = "R"; public static final String DISAPPROVED = "D"; public static final String APPROVED = "A"; public static class CashReceipt { // once a CashReceipt gets approved, its financialDocumentStatus goes to "verified" public static final String VERIFIED = "V"; // when a CashReceipt associated with a Deposit, its financialDocumentStatus changes to "interim" or "final" public static final String INTERIM = "I"; public static final String FINAL = "F"; // when the CMDoc is finalized, the CRs of its Deposits change to status "approved" } } public static class AdvanceDepositConstants { public static final String CASH_RECEIPT_ADVANCE_DEPOSIT_COLUMN_TYPE_CODE = "R"; } public static class AuxiliaryVoucher { public static final String ADJUSTMENT_DOC_TYPE = "AVAD"; public static final String ADJUSTMENT_DOC_TYPE_NAME = "Adjustment"; public static final String RECODE_DOC_TYPE = "AVRC"; public static final String RECODE_DOC_TYPE_NAME = "Recode"; public static final String ACCRUAL_DOC_TYPE = "AVAE"; public static final String ACCRUAL_DOC_TYPE_NAME = "Accrual"; public static final String ERROR_DOCUMENT_RECODE_DISTRIBUTION_OF_INCOME_AND_EXPENSE_UNSUCCESSFUL = "Unable to auto-generate Distribution of Income and Expense for document with number \"%s.\" Please contact your System Administrator for a Distribution of Income and Expense to be created manually."; public static final String ERROR_DOCUMENT_HAS_TARGET_LINES = "AV document doesn't have target accounting lines. This method should have never been entered"; public static final String RECODE_DISTRIBUTION_OF_INCOME_AND_EXPENSE_DESCRIPTION = "Auto-generated for Auxiliary Voucher"; public static final String RECODE_DISTRIBUTION_OF_INCOME_AND_EXPENSE_EXPLANATION = "Auxiliary Voucher recode document type was chosen. A Distribution of Income And Expense needs to be routed to FINAL along with it. This Document is routed by Auxiliary Voucher \"%s\"."; public static final String CHANGE_VOUCHER_TYPE = "changeVoucherType"; } public static class CashDrawerConstants { public static final String STATUS_CLOSED = "C"; public static final String STATUS_OPEN = "O"; public static final String STATUS_LOCKED = "L"; } public static class CashReceiptConstants { public static final String TEST_CASH_RECEIPT_VERIFICATION_UNIT = "HAWAII_CR_VERIFICATION_UNIT"; public static final String TEST_CASH_RECEIPT_CAMPUS_LOCATION_CODE = "HI"; public static final String DEFAULT_CASH_RECEIPT_CAMPUS_LOCATION_CODE = "??"; public static final String CASH_RECEIPT_CAMPUS_LOCATION_CODE_PROPERTY_NAME = "campusLocationCode"; public static final String CASH_RECEIPT_DOC_HEADER_STATUS_CODE_PROPERTY_NAME = KFSConstants.DOCUMENT_HEADER_PROPERTY_NAME + "." + KFSConstants.DOCUMENT_HEADER_DOCUMENT_STATUS_CODE_PROPERTY_NAME; } public static class DepositConstants { public static final String DEPOSIT_TYPE_INTERIM = "I"; public static final String DEPOSIT_TYPE_FINAL = "F"; public static final String DEPOSIT_WIZARD_CASHRECEIPT_ERROR = "cashReceiptErrors"; public static final String DEPOSIT_WIZARD_DEPOSITHEADER_ERROR = "depositHeaderErrors"; } public static class CreditCardReceiptConstants { public static final String CASH_RECEIPT_CREDIT_CARD_RECEIPT_COLUMN_TYPE_CODE = "R"; } public static class BudgetAdjustmentDocumentConstants { public static final String SOURCE_BA = "From/Decrease"; public static final String TARGET_BA = "To/Increase"; public static final String GENERATE_BENEFITS_QUESTION_ID = "GenerateBenefitsQuestion"; public static final String ADJUSTMENT_RESTRICTION_LEVEL_FUND = "F"; public static final String ADJUSTMENT_RESTRICTION_LEVEL_CHART = "C"; public static final String ADJUSTMENT_RESTRICTION_LEVEL_ORGANIZATION = "O"; public static final String ADJUSTMENT_RESTRICTION_LEVEL_ACCOUNT = "A"; public static final String ADJUSTMENT_RESTRICTION_LEVEL_SUBFUND = "S"; public static final String ADJUSTMENT_RESTRICTION_LEVEL_NONE = "N"; } public static class BudgetConstructionPositionConstants { public static final String POSITION_REGULAR_TEMPORARY_REGULAR = "R"; public static final String POSITION_REGULAR_TEMPORARY_TEMPORARY = "T"; public static final String POSITION_EFFECTIVE_STATUS_ACTIVE = "A"; public static final String POSITION_EFFECTIVE_STATUS_INACTIVE = "I"; public static final String POSITION_STATUS_APPROVED = "A"; public static final String POSITION_STATUS_DELETED = "D"; public static final String POSITION_STATUS_FROZEN = "F"; public static final String POSITION_STATUS_TEMPORARILY_INACTIVE = "T"; } public static class DisbursementVoucherDocumentConstants { public static final String CLEAR_NON_EMPLOYEE_TAB_QUESTION_ID = "ClearNonEmplTravTabQuestion"; public static final String CLEAR_WIRE_TRANSFER_TAB_QUESTION_ID = "ClearWireTransferTabQuestion"; public static final String CLEAR_FOREIGN_DRAFT_TAB_QUESTION_ID = "ClearForeignDraftTabQuestion"; } public static class CoreApcParms { // Kuali User params public static final String USER_INVALID_EMPLOYEE_STATUSES = "ACTIVE_KFS_USER_EMPLOYEE_STATUSES"; public static final String UNIVERSAL_USER_EDIT_WORKGROUP = "UNIVERSAL_USER_EDIT_GROUP"; public static final String SERVICE_BUS_ACCESS_GROUP_PARM = "SERVICE_BUS_ACCESS_GROUP"; } public static final String MAINTENANCE_ADMIN_WORKGROUP_PARM_NM = "MAINTENANCE_ADMIN_GROUP"; public static final String ACCOUNTING_LINE_IMPORT_MAX_FILE_SIZE_PARM_NM = "MAX_FILE_SIZE_ACCOUNTING_LINE_IMPORT"; public static final String ORIGIN_ENTRY_IMPORT_MAX_FILE_SIZE_PARM_NM = "MAX_FILE_SIZE_ORIGIN_ENTRY_IMPORT"; public static class ChartApcParms { public static final String FISCAL_YEAR_MAKER_REPLACE_MODE = "OVERRIDE_TARGET_YEAR_DATA_IND"; public static final String FISCAL_YEAR_MAKER_SOURCE_FISCAL_YEAR = "SOURCE_FISCAL_YEAR"; // added from parameter refactoring. public static final String APC_HRMS_ACTIVE_KEY = "USE_HRMS_ORGANIZATION_ATTRIBUTES_IND"; public final static String OBJECT_CODE_ILLEGAL_VALUES = "OBJECT_CODES"; public static final String DOCTYPE_AND_OBJ_CODE_ACTIVE = "DOCUMENT_TYPES_REQUIRING_ACTIVE_OBJECT_CODES"; public static final String INVALID_DOCUMENT_TYPES_BY_OBJECT_SUB_TYPE = "INVALID_DOCUMENT_TYPES_BY_OBJECT_SUB_TYPE"; public static final String VALID_DOCUMENT_TYPES_BY_OBJECT_SUB_TYPE = "VALID_DOCUMENT_TYPES_BY_OBJECT_SUB_TYPE"; public static final String CG_ALLOWED_SUBACCOUNT_TYPE_CODES = "SUB_ACCOUNT_TYPES"; // Account parms public static final String ACCOUNT_USER_EMP_STATUSES = "ROLE_EMPLOYEE_STATUSES"; public static final String ACCOUNT_USER_EMP_TYPES = "ROLE_EMPLOYEE_TYPES"; // Delegate parms public static final String DELEGATE_USER_EMP_STATUSES = "EMPLOYEE_STATUSES"; public static final String DELEGATE_USER_EMP_TYPES = "EMPLOYEE_TYPES"; // SubAccount parms public static final String SUBACCOUNT_CG_WORKGROUP_PARM_NAME = "CG_GROUP"; // Org parms public static final String DEFAULT_ACCOUNT_NOT_REQUIRED_ORG_TYPES = "ORGANIZATION_TYPES_NOT_REQUIRING_DEFAULT_ACCOUNT"; public static final String ORG_MUST_REPORT_TO_SELF_ORG_TYPES = "ORGANIZATION_TYPES_THAT_MUST_REPORT_TO_SELF"; public static final String ORG_PLANT_WORKGROUP_PARM_NAME = "PLANT_GROUP"; public static final String ADMINISTRATOR_WORKGROUP = "Maintenance.Admin.Workgroup"; public static final String ACCOUNT_FUND_GROUP_DENOTES_CG = "FUND_GROUP_DENOTES_CG_IND"; public static final String ACCOUNT_CG_DENOTING_VALUE = "CG_DENOTING_VALUE"; public static final String DEFAULT_USER_CHART_CODE_SOURCE_ATTRIBUTE = "DEFAULT_CHART_SOURCE_ATTRIBUTE"; public static final String DEFAULT_USER_CHART_CODE_EXTRACTION_REGEXP = "DEFAULT_CHART_EXTRACTION_REG_EXP"; public static final String DEFAULT_USER_ORGANIZATION_CODE_SOURCE_ATTRIBUTE = "DEFAULT_ORGANIZATION_SOURCE_ATTRIBUTE"; public static final String DEFAULT_USER_ORGANIZATION_CODE_EXTRACTION_REGEXP = "DEFAULT_ORGANIZATION_EXTRACTION_REG_EXP"; } public static class FinancialApcParms { // public static final String GROUP_DV_DOCUMENT = "Kuali.FinancialTransactionProcessing.DisbursementVoucherDocument"; public static final String DV_TAX_WORKGROUP = "TAX_GROUP"; public static final String DV_ADMIN_WORKGROUP = "ADMIN_GROUP"; public static final String DV_FOREIGNDRAFT_WORKGROUP = "FOREIGN_DRAFT_GROUP"; public static final String DV_WIRETRANSFER_WORKGROUP = "WIRE_TRANSFER_GROUP"; public static final String DV_TRAVEL_WORKGROUP = "TRAVEL_GROUP"; public static final String ACCOUNTING_LINE_IMPORT_HELP = "ACCOUNTING_LINE_IMPORT"; } public static class SystemGroupParameterNames { public static final String FLEXIBLE_OFFSET_ENABLED_FLAG = "USE_FLEXIBLE_OFFSET_IND"; public static final String FLEXIBLE_CLAIM_ON_CASH_BANK_ENABLED_FLAG = "USE_FLEXIBLE_CLAIM_ON_CASH_IND"; public static final String ICR_ENCUMBRANCE_ENABLED_FLAG = "USE_ICR_ENCUMBRANCE_IND"; public static final String PURGE_GL_ACCT_BALANCES_T_BEFORE_YEAR = "PRIOR_TO_YEAR"; public static final String PURGE_GL_ENCUMBRANCE_T_BEFORE_YEAR = "PRIOR_TO_YEAR"; public static final String PURGE_GL_SF_BALANCES_T_BEFORE_YEAR = "PRIOR_TO_YEAR"; public static final String PURGE_GL_BALANCE_T_BEFORE_YEAR = "PRIOR_TO_YEAR"; public static final String PURGE_GL_ENTRY_T_BEFORE_YEAR = "PRIOR_TO_YEAR"; public static final String PURGE_GL_ID_BILL_T_BEFORE_YEAR = "PRIOR_TO_YEAR"; public static final String GL_ANNUAL_CLOSING_DOC_TYPE = "ANNUAL_CLOSING_DOCUMENT_TYPE"; public static final String GL_INDIRECT_COST_RECOVERY = "INDIRECT_COST_RECOVERY_DOCUMENT_TYPE"; public static final String GL_NET_EXPENSE_OBJECT_TYPE_CODE = "NET_EXPENSE_OBJECT_TYPE_CODE"; public static final String GL_ORIGINATION_CODE = "MANUAL_FEED_ORIGINATION"; public static final String GL_SCRUBBER_VALIDATION_DAYS_OFFSET = "CG_ACCOUNT_EXPIRATION_EXTENSION_DAYS"; public static final String MULTIPLE_VALUE_LOOKUP_RESULTS_PER_PAGE = "MULTIPLE_VALUE_RESULTS_PER_PAGE"; public static final String MULTIPLE_VALUE_LOOKUP_RESULTS_EXPIRATION_AGE = "MULTIPLE_VALUE_RESULTS_EXPIRATION_SECONDS"; public static final String ACTIVE_INPUT_TYPES_PARAMETER_NAME = "ACTIVE_FILE_TYPES"; public static final String FILE_TYPE_WORKGROUP_PARAMETER_NAME = "UPLOAD_GROUP"; public static final String COLLECTOR_VALIDATOR_EMAIL_SUBJECT_PARAMETER_NAME = "VALIDATION_EMAIL_SUBJECT_LINE"; public static final String COLLECTOR_DEMERGER_EMAIL_SUBJECT_PARAMETER_NAME = "ERROR_EMAIL_SUBJECT_LINE"; public static final String COLLECTOR_EQUAL_DC_TOTAL_DOCUMENT_TYPES = "EQUAL_DEBIT_CREDIT_TOTAL_DOCUMENT_TYPES"; public static final String COLLECTOR_PERFORM_DUPLICATE_HEADER_CHECK = "PERFORM_DUPLICATE_HEADER_CHECK_IND"; public static final String BATCH_SCHEDULE_CUTOFF_TIME = "CUTOFF_TIME"; public static final String BATCH_SCHEDULE_CUTOFF_TIME_IS_NEXT_DAY = "CUTOFF_TIME_NEXT_DAY_IND"; public static final String BATCH_SCHEDULE_STATUS_CHECK_INTERVAL = "STATUS_CHECK_INTERVAL"; /** * Used by PurgePendingAttachmentsJob to compute the maximum amount of time a pending attachment is allowed to persist on * the file system before being deleted. */ public static final String PURGE_PENDING_ATTACHMENTS_STEP_MAX_AGE = "MAX_AGE"; public static final String JOB_ADMIN_WORKGROUP = "SCHEDULE_ADMIN_GROUP"; public static final String JOB_WORKGROUP_SUFFIX = "_SCHEDULE_GROUP"; } public static class GeneralLedgerApplicationParameterKeys { public static final String INCOME_OBJECT_TYPE_CODES = "INCOME_OBJECT_TYPE_CODES"; public static final String INCOME_TRANSFER_OBJECT_TYPE_CODES = "INCOME_TRANSFER_OBJECT_TYPE_CODES"; public static final String EXPENSE_OBJECT_TYPE_CODES = "EXPENSE_OBJECT_TYPE_CODES"; public static final String EXPENSE_TRANSFER_OBJECT_TYPE_CODES = "EXPENSE_TRANSFER_OBJECT_TYPE_CODES"; } public static class GeneralLedgerCorrectionProcessApplicationParameterKeys { public static final String RECORD_COUNT_FUNCTIONALITY_LIMIT = "RECORD_COUNT_FUNCTIONALITY_LIMIT"; public static final String RECORDS_PER_PAGE = "RECORDS_PER_PAGE"; } public static class EnterpriseFeederApplicationParameterKeys { public static final String TO_ADDRESS = "INVALID_FILE_TO_ADDRESSES"; } public static class ParameterValues { public static final String YES = "Y"; public static final String NO = "N"; } public static class Maintenance { public static final String AFTER_CLASS_DELIM = "!!"; public static final String AFTER_FIELDNAME_DELIM = "^^"; public static final String AFTER_VALUE_DELIM = "::"; } public static class ObjectCodeConstants { public static final String INACTIVE_OBJECT_LEVEL_QUESTION_ID = "InactiveObjectLevelQuestion"; } public static final String MONTH1 = "01"; public static final String MONTH2 = "02"; public static final String MONTH3 = "03"; public static final String MONTH4 = "04"; public static final String MONTH5 = "05"; public static final String MONTH6 = "06"; public static final String MONTH7 = "07"; public static final String MONTH8 = "08"; public static final String MONTH9 = "09"; public static final String MONTH10 = "10"; public static final String MONTH11 = "11"; public static final String MONTH12 = "12"; public static final String MONTH13 = "13"; public static final String PERIOD_CODE_ANNUAL_BALANCE = "AB"; public static final String PERIOD_CODE_BEGINNING_BALANCE = "BB"; public static final String PERIOD_CODE_CG_BEGINNING_BALANCE = "CB"; public static final String REQUEST_SEARCH_RESULTS = "reqSearchResults"; public static final String REQUEST_SEARCH_RESULTS_SIZE = "reqSearchResultsSize"; public static final String GL_COLLECTOR_STAGING_DIRECTORY = "collector.staging.directory"; public static final String DISBURSEMENT_VOUCHER_DOCUMENTATION_LOCATION_CODE_PROPERTY_NAME = "disbursementVoucherDocumentationLocationCode"; public static final String FUND_GROUP_CODE_PROPERTY_NAME = "code"; public static final String SUB_FUND_GROUP_CODE_PROPERTY_NAME = "subFundGroupCode"; public static final String ACCOUNT_TYPE_S3 = "S3"; public static final String RULE_CODE_R1 = "R1"; public static final String RULE_CODE_R2 = "R2"; public static final String RULE_CODE_N1 = "N1"; public static final String RULE_CODE_N2 = "N2"; public static final String RULE_CODE_C1 = "C1"; public static final String RULE_CODE_C2 = "C2"; public static final String RULE_CODE_A = "A"; public static final String TRANSACTION_DT = "TRANSACTION_DT"; public static final String UNALLOC_OBJECT_CD = "UNALLOC_OBJECT_CD"; public static final String BEG_BUD_CASH_OBJECT_CD = "BEG_BUD_CASH_OBJECT_CD"; public static final String FUND_BAL_OBJECT_CD = "FUND_BAL_OBJECT_CD"; public static final String UNIV_FISCAL_YR = "UNIV_FISCAL_YR"; public static final int DEFAULT_NUM_OF_COLUMNS = 1; public static final String EMPLOYEE_LOOKUP_ERRORS = "document.employeeLookups"; public static class BudgetConstructionConstants { public enum LockStatus { SUCCESS, BY_OTHER, NO_DOOR, OPTIMISTIC_EX, FLOCK_FOUND } public static final int maxLockRetry = 20; /* KFSConstants for the CSF Tracker */ public static final String ACTIVE_CSF_DELETE_CODE = "-"; /* KFSConstants for the budget construction flag names */ private static int NUMBER_OF_CTRL_FLAGS = 8; public final static String BUDGET_ADMINSTRATION_ACTIVE = "BAACTV"; public final static String BASE_BUDGET_UPDATES_OK = "BASEAD"; public final static String BUDGET_BATCH_SYNCHRONIZATION_OK = "BSSYNC"; public final static String CSF_UPDATES_OK = "CSFUPD"; public final static String BUDGET_CONSTRUCTION_ACTIVE = "BCACTV"; public final static String BUDGET_CONSTRUCTION_GENESIS_RUNNING = "BCGENE"; public final static String BUDGET_CONSTRUCTION_UPDATES_OK = "BCUPDT"; public final static String BUDGET_ON_LINE_SYNCHRONIZATION_OK = "PSSYNC"; /* state for current year budget construction flags after genesis */ private static HashMap<String, String> buildCurrentYear() { HashMap<String, String> mapSLF; mapSLF = new HashMap<String, String>(NUMBER_OF_CTRL_FLAGS, (float) 1.00); mapSLF.put(BUDGET_ADMINSTRATION_ACTIVE, ParameterValues.YES); mapSLF.put(BASE_BUDGET_UPDATES_OK, ParameterValues.YES); mapSLF.put(BUDGET_BATCH_SYNCHRONIZATION_OK, ParameterValues.NO); mapSLF.put(CSF_UPDATES_OK, ParameterValues.NO); mapSLF.put(BUDGET_CONSTRUCTION_ACTIVE, ParameterValues.NO); mapSLF.put(BUDGET_CONSTRUCTION_GENESIS_RUNNING, ParameterValues.NO); mapSLF.put(BUDGET_CONSTRUCTION_UPDATES_OK, ParameterValues.NO); mapSLF.put(BUDGET_ON_LINE_SYNCHRONIZATION_OK, ParameterValues.NO); return mapSLF; } public final static HashMap<String, String> CURRENT_FSCL_YR_CTRL_FLAGS = buildCurrentYear(); /* state for next year budget construction flags after genesis */ private static HashMap<String, String> buildNextYear() { HashMap<String, String> mapSLF; mapSLF = new HashMap<String, String>(NUMBER_OF_CTRL_FLAGS, (float) 1.00); mapSLF.put(BUDGET_ADMINSTRATION_ACTIVE, ParameterValues.NO); mapSLF.put(BASE_BUDGET_UPDATES_OK, ParameterValues.NO); mapSLF.put(BUDGET_BATCH_SYNCHRONIZATION_OK, ParameterValues.YES); mapSLF.put(CSF_UPDATES_OK, ParameterValues.YES); mapSLF.put(BUDGET_CONSTRUCTION_ACTIVE, ParameterValues.YES); mapSLF.put(BUDGET_CONSTRUCTION_GENESIS_RUNNING, ParameterValues.NO); mapSLF.put(BUDGET_CONSTRUCTION_UPDATES_OK, ParameterValues.NO); mapSLF.put(BUDGET_ON_LINE_SYNCHRONIZATION_OK, ParameterValues.YES); return mapSLF; } public final static HashMap<String, String> NEXT_FSCL_YR_CTRL_FLAGS_AFTER_GENESIS = buildNextYear(); /* appointment funding duration code for people NOT on leave */ public final static String NO_LEAVE_INDICATED = "NONE"; /* KFSConstants for the budget construction header */ public final static String DEFAULT_BUDGET_HEADER_LOCK_IDS = null; public final static Integer INITIAL_ORGANIZATION_LEVEL_CODE = new Integer(0); public final static String INITIAL_ORGANIZATION_LEVEL_CHART_OF_ACCOUNTS_CODE = null; public final static String INITIAL_ORGANIZATION_LEVEL_ORGANIZATION_CODE = null; /* Budget Construction document type */ public final static String BUDGET_CONSTRUCTION_DOCUMENT_TYPE = "BC"; public final static String BUDGET_CONSTRUCTION_DOCUMENT_NAME = "BudgetConstructionDocument"; public final static String BUDGET_CONSTRUCTION_DOCUMENT_DESCRIPTION = "Budget Construction"; public final static String BUDGET_CONSTRUCTION_DOCUMENT_INITIAL_STATUS = "$"; public final static String ORG_REVIEW_RULE_TEMPLATE = "KualiOrgReviewTemplate"; /* codes used in the Calculated Salary Foundation (CSF) */ public final static String VACANT_CSF_LINE = "V"; public final static String UNFUNDED_CSF_LINE = "U"; public final static String ACTIVE_CSF_LINE = "-"; public final static String VACANT_EMPLID = "VACANT"; /* * object code which stores amounts by which pending general ledger rows in budget construction are out of balance */ public final static String OBJECT_CODE_2PLG = "2PLG"; /* * initial sizes for hash maps used in genesis supposedly starting the map out with about the right amount of space makes * look-ups more efficient these numbers shouldn't need to be very precise */ public final static Integer ESTIMATED_PENDING_GENERAL_LEDGER_ROWS = 70000; public final static Integer AVERAGE_REPORTING_TREE_SIZE = 4; } public static class OperationType { public static final String READ = "read"; public static final String REPORT_ERROR = "with error"; public static final String INSERT = "insert"; public static final String UPDATE = "update"; public static final String DELETE = "delete"; public static final String SELECT = "select"; public static final String BYPASS = "bypassed"; } public static class PENDING_ENTRY_APPROVED_STATUS_CODE { public static final String APPROVED = "A"; public static final String PROCESSED = "X"; } public static class TableRenderConstants { public static final String SWITCH_TO_PAGE_METHOD = "switchToPage"; public static final String SORT_METHOD = "sort"; public static final String SELECT_ALL_METHOD = "selectAll"; public static final String UNSELECT_ALL_METHOD = "unselectAll"; public static final String PREVIOUSLY_SORTED_COLUMN_INDEX_PARAM = "previouslySortedColumnIndex"; public static final String VIEWED_PAGE_NUMBER = "viewedPageNumber"; } public static final String PCDO_FILE_TYPE_INDENTIFIER = "procurementCardInputFileType"; public static final String COLLECTOR_FILE_TYPE_INDENTIFIER = "collectorInputFileType"; public static final String ENTERPRISE_FEEDER_FILE_SET_TYPE_INDENTIFIER = "enterpriseFeederFileSetType"; // next 3 variables for the enterprise feeder batch upload public static final String DATA_FILE_TYPE = "DATA"; public static final String RECON_FILE_TYPE = "RECON"; public static final class WorkflowConstants { public static final String GET_GENERIC_ACCOUNTS_PREFIX = "//routingInfo/"+RoutingData.class.getName()+"/routingTypes[string='"; public static final String GET_GENERIC_ACCOUNTS_SUFFIX = "']/following-sibling::routingSet/"+ RoutingAccount.class.getName(); public static final String GET_GENERIC_ORGS_PREFIX = "//routingInfo/"+RoutingData.class.getName()+"/routingTypes[string='"; public static final String GET_GENERIC_ORGS_SUFFIX = "']/following-sibling::routingSet/"+OrgReviewRoutingData.class.getName(); public static final String GET_GENERIC_CHART= "./routingChart"; public static final String GET_GENERIC_ACCOUNT = "./routingAccount"; public static final String GET_GENERIC_OVERRIDE_CD = "./routingOverrideCode"; public static final String GET_GENERIC_ORG = "./routingOrg"; public static final String GET_GENERIC_ACCOUNT_CHART = "//routingSet/" + RoutingAccount.class.getName() + "/routingChart"; public static final String GET_GENERIC_ACCOUNT_ACCOUNT = "//routingSet/" + RoutingAccount.class.getName() + "/routingAccount"; public static final String GET_GENERIC_ORG_CHART = "//routingSet/" + OrgReviewRoutingData.class.getName() + "/routingChart"; public static final String GET_GENERIC_ORG_ORG = "//routingSet/" + OrgReviewRoutingData.class.getName() + "/routingOrg"; public static final String GET_GENERIC_ACCOUNT_REPORT_PREFIX = "<generatedContent><report_for_routing_purposes><routingSet><" + RoutingAccount.class.getName() + ">"; public static final String GET_GENERIC_ACCOUNT_REPORT_SUFFIX = "</" + RoutingAccount.class.getName() +"></routingSet></report_for_routing_purposes></generatedContent>"; public static final String GET_GENERIC_ORG_REPORT_PREFIX = "<generatedContent><report_for_routing_purposes><routingSet><" + OrgReviewRoutingData.class.getName() + ">"; public static final String GET_GENERIC_ORG_REPORT_SUFFIX = "</" + OrgReviewRoutingData.class.getName() + "></routingSet></report_for_routing_purposes></generatedContent>"; } /** * The base implementation of {@link org.kuali.module.gl.util.EnterpriseFeederStatusBase} uses strings contained within * ApplicationResources.properties to store the human-readable descriptions of each status object. The fully qualified class * name is appended to the end of this key to generate the true key. For example, * gl.EnterpriseFeeder.StatusDescriptionPrefix.org.kuali.module.gl.util.FileReconBadLoadAbortedStatus */ public static final String ENTERPRISE_FEEDER_STATUS_DESCRIPTION_PREFIX = "gl.EnterpriseFeeder.StatusDescription."; public static final String BATCH_STEP_RUNNER_JOB_NAME = "stepRunByBatchStepRunner"; // Some static method calls below that could be done in static variables instead but isn't safe to do during class loading // w/SpringContext. private static String DASH_FINANCIAL_OBJECT_CODE = null; public static String getDashFinancialObjectCode() { if (DASH_FINANCIAL_OBJECT_CODE == null) { DASH_FINANCIAL_OBJECT_CODE = StringUtils.rightPad("", SpringContext.getBean(DataDictionaryService.class).getAttributeMaxLength(OriginEntryFull.class, KFSPropertyConstants.FINANCIAL_OBJECT_CODE), '-'); } return DASH_FINANCIAL_OBJECT_CODE; } private static String DASH_FINANCIAL_SUB_OBJECT_CODE = null; public static String getDashFinancialSubObjectCode() { if (DASH_FINANCIAL_SUB_OBJECT_CODE == null) { DASH_FINANCIAL_SUB_OBJECT_CODE = StringUtils.rightPad("", SpringContext.getBean(DataDictionaryService.class).getAttributeMaxLength(OriginEntryFull.class, KFSPropertyConstants.FINANCIAL_SUB_OBJECT_CODE), '-'); } return DASH_FINANCIAL_SUB_OBJECT_CODE; } private static String DASH_SUB_ACCOUNT_NUMBER = null; public static String getDashSubAccountNumber() { if (DASH_SUB_ACCOUNT_NUMBER == null) { DASH_SUB_ACCOUNT_NUMBER = StringUtils.rightPad("", SpringContext.getBean(DataDictionaryService.class).getAttributeMaxLength(OriginEntryFull.class, KFSPropertyConstants.SUB_ACCOUNT_NUMBER), '-'); } return DASH_SUB_ACCOUNT_NUMBER; } private static String SPACE_SUB_ACCOUNT_NUMBER = null; public static String getSpaceSubAccountNumber() { if (SPACE_SUB_ACCOUNT_NUMBER == null) { SPACE_SUB_ACCOUNT_NUMBER = StringUtils.rightPad("", SpringContext.getBean(DataDictionaryService.class).getAttributeMaxLength(OriginEntryFull.class, KFSPropertyConstants.SUB_ACCOUNT_NUMBER), ' '); } return SPACE_SUB_ACCOUNT_NUMBER; } private static String DASH_PROJECT_CODE = null; public static String getDashProjectCode() { if (DASH_PROJECT_CODE == null) { DASH_PROJECT_CODE = StringUtils.rightPad("", SpringContext.getBean(DataDictionaryService.class).getAttributeMaxLength(OriginEntryFull.class, KFSPropertyConstants.PROJECT_CODE), '-'); } return DASH_PROJECT_CODE; } //AR TAB ERROR KEYS //Customer Invoice Document public static final String CUSTOMER_INVOICE_DOCUMENT_ORGANIZATION_ERRORS = "document.billByChartOfAccountCode,document.billedByOrganizationCode"; public static final String CUSTOMER_INVOICE_DOCUMENT_GENERAL_ERRORS = "document.accountsReceivableDocumentHeader.customerNumber,document.invoice*,document.billingDate,document.invoiceDueDate"; public static final String CUSTOMER_INVOICE_DOCUMENT_ADDRESS = "document.customerBillToAddressIdentifier,document.customerShipToAddressIdentifier"; public static final String CUSTOMER_INVOICE_DOCUMENT_RECEIVABLE_ACCOUNTING_LINE = "document.payment*"; public static final String CUSTOMER_INVOICE_DETAIL_ERRORS = "newCustomerInvoiceDetail*,document.sourceAccountingLine*"; //Cash Control Document public static final String CASH_CONTROL_DOCUMENT_ERRORS = "document.accountsReceivableDocumentHeader.processingChartOfAccountCode,document.referenceFinancialDocumentNumber,document.customerPaymentMediumCode,document.organizationCode"; public static final String CASH_CONTROL_DETAILS_ERRORS = "newCashControl*,document.cashControlDetail*"; public static final class ReportGeneration{ public final static String PARAMETER_NAME_SUBREPORT_DIR = "SUBREPORT_DIR"; public final static String PARAMETER_NAME_SUBREPORT_TEMPLATE_NAME = "SUBREPORT_TEMPLATE_NAMES"; public final static String DESIGN_FILE_EXTENSION = ".jrxml"; public final static String JASPER_REPORT_EXTENSION = ".jasper"; public final static String PDF_FILE_EXTENSION = ".pdf"; public final static String PDF_MIME_TYPE = "application/pdf"; } }
work/src/org/kuali/kfs/sys/KFSConstants.java
/* * Copyright 2007 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; import java.util.HashMap; import org.apache.commons.lang.StringUtils; import org.kuali.core.JstlConstants; import org.kuali.core.service.DataDictionaryService; import org.kuali.core.util.KualiDecimal; import org.kuali.kfs.context.SpringContext; import org.kuali.module.gl.bo.OriginEntryFull; import org.kuali.workflow.attribute.RoutingAccount; import org.kuali.workflow.attribute.OrgReviewRoutingData; import org.kuali.workflow.attribute.RoutingData; /** * This class is used to define global constants. */ public class KFSConstants extends JstlConstants implements ParameterKeyConstants { private static final long serialVersionUID = 2882277719647128949L; // special user used in the post-processor public static final String SYSTEM_USER = "KULUSER"; public static final String ENVIRONMENT_KEY = "environment"; public static final String VERSION_KEY = "version"; public static final String LOG4J_SETTINGS_FILE_KEY = "log4j.settings.file"; public static final String LOGS_DIRECTORY_KEY = "logs.directory"; public static final String LOG4J_RELOAD_MINUTES_KEY = "log4j.reload.minutes"; public static final String APPLICATION_URL_KEY = "application.url"; public static final String ATTACHMENTS_DIRECTORY_KEY = "attachments.directory"; public static final String ATTACHMENTS_PENDING_DIRECTORY_KEY = "attachments.pending.directory"; public static final String HTDOCS_LOGS_URL_KEY = "htdocs.logs.url"; public static final String HTDOCS_STAGING_URL_KEY = "htdocs.staging.url"; public static final String STAGING_DIRECTORY_KEY = "staging.directory"; public static final String TEMP_DIRECTORY_KEY = "temp.directory"; public static final String EXTERNALIZABLE_HELP_URL_KEY = "externalizable.help.url"; public static final String EXTERNALIZABLE_IMAGES_URL_KEY = "externalizable.images.url"; public static final String EXTERNALIZABLE_XML_URL_KEY = "externalizable.xml.url"; public static final String RICE_EXTERNALIZABLE_IMAGES_URL_KEY = "kr.externalizable.images.url"; public static final String REPORTS_DIRECTORY_KEY = "reports.directory"; public static final String WORKFLOW_URL_KEY = "workflow.url"; public static final String PROD_ENVIRONMENT_CODE_KEY = "production.environment.code"; public static final String MAINTAIN_USERS_LOCALLY_KEY = "maintain.users.locally"; public static final String USE_STANDALONE_WORKFLOW = "rice.use.standalone.workflow"; public static final String DATABASE_REPOSITORY_FILES_LIST_NAME = "databaseRepositoryFilePaths"; public static final String SCRIPT_CONFIGURATION_FILES_LIST_NAME = "scriptConfigurationFilePaths"; public static final String JOB_NAMES_LIST_NAME = "jobNames"; public static final String TRIGGER_NAMES_LIST_NAME = "triggerNames"; public static final String LOOKUP_RESULTS_LIMIT_URL_KEY = "RESULTS_LIMIT"; public static final String DOCHANDLER_DO_URL = "/DocHandler.do?docId="; public static final String DOCHANDLER_URL_CHUNK = "&command=displayDocSearchView"; public static final String ACCOUNT_NUMBER_PROPERTY_NAME = "accountNumber"; public static final String MODULE_ID_PROPERTY_NAME = "moduleId"; public static final String MODULE_CODE_PROPERTY_NAME = "moduleCode"; public static final String ACCOUNT_STATUS_CLOSED = "Y"; public static final String ACCOUNTING_PERIOD_STATUS_CODE_FIELD = "universityFiscalPeriodStatusCode"; public static final String ACCOUNTING_PERIOD_STATUS_CLOSED = "C"; public static final String ACCOUNTING_PERIOD_STATUS_OPEN = "O"; public static final String ACCOUNTING_STRING_SOURCE_ENTRY = "@"; public static final String ACCOUNTING_STRING_SOURCE_ACCOUNT = "#"; public static final String ACTION_FORM_UTIL_MAP_METHOD_PARM_DELIMITER = "~"; public static final String ADD_LINE_METHOD = "addLine"; public static final String ADD_PREFIX = "add"; public static final String ACTIVE_INDICATOR = "Y"; public static final String AGGREGATE_ENCUMBRANCE_BALANCE_TYPE_CODE = "EN"; public static final String AMOUNT_PROPERTY_NAME = "amount"; public static final String APPROVE_METHOD = "approve"; public static final String NON_ACTIVE_INDICATOR = "N"; public static final String BLANK_SPACE = " "; public static final String BACK_LOCATION = "backLocation"; public static final String BACKDOOR_PARAMETER = "backdoorId"; public static final String BALANCE_INQUIRY_REPORT_MENU_ACTION = "balanceInquiryReportMenu.do"; public static final String BALANCE_TYPE_PROPERTY_NAME = "balanceTypeCode"; public static final String BALANCE_TYPE_CURRENT_BUDGET = "CB"; public static final String BALANCE_TYPE_BASE_BUDGET = "BB"; public static final String BALANCE_TYPE_MONTHLY_BUDGET = "MB"; public static final String BALANCE_TYPE_EXTERNAL_ENCUMBRANCE = "EX"; public static final String BALANCE_TYPE_INTERNAL_ENCUMBRANCE = "IE"; public static final String BALANCE_TYPE_COST_SHARE_ENCUMBRANCE = "CE"; public static final String BALANCE_TYPE_ACTUAL = "AC"; public static final String BALANCE_TYPE_AUDIT_TRAIL = "NB"; public static final String BALANCE_TYPE_A21 = "A2"; public static final String BALANCE_TYPE_BUDGET_STATISTICS = "BS"; public static final String BALANCE_TYPE_PRE_ENCUMBRANCE = "PE"; public static final String BLANKET_APPROVE_METHOD = "blanketApprove"; public static final String BUSINESS_OBJECT_CLASS_ATTRIBUTE = "businessObjectClassName"; public static final String CALLING_METHOD = "caller"; public static final String CASH_MANAGEMENT_DOCUMENT_ACTION = "financialCashManagement.do"; public static final String CHANGE_JOURNAL_VOUCHER_BALANCE_TYPE_METHOD = "changeBalanceType"; public static final String CHART_OF_ACCOUNTS_CODE_PROPERTY_NAME = "chartOfAccountsCode"; public static final String CONFIRMATION_QUESTION = "confirmationQuestion"; public static final String CONSOLIDATED_SUBACCOUNT = "*ALL*"; public static final String CONVERSION_FIELDS_PARAMETER = "conversionFields"; public static final String LOOKUP_READ_ONLY_FIELDS = "readOnlyFields"; public static final String LOOKUP_AUTO_SEARCH = "autoSearch"; public static final String COST_SHARE = "CS"; public static final String CREDIT_AMOUNT_PROPERTY_NAME = "newSourceLineCredit"; public static final String DEBIT_AMOUNT_PROPERTY_NAME = "newSourceLineDebit"; public static final String DELETE_LINE_METHOD = "deleteLine"; public static final String DICTIONARY_BO_NAME = "dictionaryBusinessObjectName"; public static final String DISENCUMBRANCE = "Disencumbrance"; public static final String DISPATCH_REQUEST_PARAMETER = "methodToCall"; public static final String DOC_FORM_KEY = "docFormKey"; public static final String BALANCE_INQUIRY_REPORT_MENU_CALLER_DOC_FORM_KEY = "balanceInquiryReportMenuCallerDocFormKey"; public static final String DOCUMENT_CANCEL_QUESTION = "DocCancel"; public static final String DOCUMENT_DELETE_QUESTION = "DocDelete"; public static final String DOCUMENT_DISAPPROVE_QUESTION = "DocDisapprove"; public static final String DOCUMENT_HEADER_ID = "documentHeaderId"; public static final String DOCUMENT_HEADER_DOCUMENT_STATUS_CODE_PROPERTY_NAME = "financialDocumentStatusCode"; public static final String NOTE_TEXT_PROPERTY_NAME = "noteText"; public static final String DOCUMENT_HEADER_PROPERTY_NAME = "documentHeader"; public static final String DOCUMENT_SAVE_BEFORE_CLOSE_QUESTION = "DocSaveBeforeClose"; public static final String EMPLOYEE_ACTIVE_STATUS = "A"; public static final String EXISTING_SOURCE_ACCT_LINE_PROPERTY_NAME = "sourceAccountingLine"; public static final String EXISTING_TARGET_ACCT_LINE_PROPERTY_NAME = "targetAccountingLine"; public static final String SOURCE_ACCT_LINE_TYPE_CODE = "F"; // F = From, the label for this on most documents public static final String TARGET_ACCT_LINE_TYPE_CODE = "T"; // T = To, the label for this on most documents public static final String EXTRA_BUTTON_SOURCE = "extraButtonSource"; public static final String EXTRA_BUTTON_PARAMS = "extraButtonParams"; public static final String NEW_DOCUMENT_NOTE_PROPERTY_NAME = "newDocumentNote"; public static final String NEW_AD_HOC_ROUTE_PERSON_PROPERTY_NAME = "newAdHocRoutePerson"; public static final String NEW_AD_HOC_ROUTE_WORKGROUP_PROPERTY_NAME = "newAdHocRouteWorkgroup"; public static final String EXISTING_AD_HOC_ROUTE_PERSON_PROPERTY_NAME = "adHocRoutePerson"; public static final String EXISTING_AD_HOC_ROUTE_WORKGROUP_PROPERTY_NAME = "adHocRouteWorkgroup"; public static final String NEW_SOURCE_ACCT_LINE_PROPERTY_NAME = "newSourceLine"; public static final String NEW_TARGET_ACCT_LINES_PROPERTY_NAME = "newTargetLines"; public static final String NEW_TARGET_ACCT_LINE_PROPERTY_NAME = "newTargetLine"; public static final String DOCUMENT_PROPERTY_NAME = "document"; public static final String DOCUMENT_TYPE_NAME = "docTypeName"; public static final String EDIT_PREFIX = "edit"; public static final String DASH = "-"; public static final String EMPTY_STRING = ""; public static final String ENCUMBRANCE = "Encumbrance"; public static final String EXPENSE = "Expense"; public static final String FIELD_CONVERSION_PAIR_SEPERATOR = ":"; public static final String FIELD_CONVERSIONS_SEPERATOR = ","; public static final String REFERENCES_TO_REFRESH_SEPARATOR = ","; public static final String FIELD_CONVERSION_PREFIX_PARAMETER = "fieldConversionPrefix"; public static final String FINANCIAL_OBJECT_CODE_PROPERTY_NAME = "financialObjectCode"; public static final String FINANCIAL_OBJECT_LEVEL_CODE_PROPERTY_NAME = "financialObjectLevelCode"; public static final String FINANCIAL_SUB_OBJECT_CODE_PROPERTY_NAME = "financialSubObjectCode"; public static final String FISCAL_CHART_NAME = "fiscalChartOfAccountsCode"; public static final String FISCAL_ORG_NAME = "fiscalOrganizationCode"; public static final String FROM = "From"; public static final String GENERIC_FIELD_NAME = "Field"; public static final String GENERIC_CODE_PROPERTY_NAME = "code"; public static final String GL_BALANCE_INQUIRY_FLAG = "inquiryFlag"; public static final String GL_ACCOUNT_BALANCE_BY_CONSOLIDATION_LOOKUP_ACTION = "glAccountBalanceByConsolidationLookup.do"; public static final String GL_BALANCE_INQUIRY_ACTION = "glBalanceInquiry.do"; public static final String GL_MODIFIED_INQUIRY_ACTION = "glModifiedInquiry.do"; public static final String GL_PE_OFFSET_STRING = "TP Generated Offset"; public static final String SUB_OBJECT_CODE_PROPERTY_NAME = "subObjectCode"; public static final String UNIVERSITY_FISCAL_YEAR_PROPERTY_NAME = "universityFiscalYear"; public static final String UNIVERSITY_FISCAL_PERIOD_CODE_PROPERTY_NAME = "universityFiscalPeriodCode"; public static final String FINANCIAL_BALANCE_TYPE_CODE_PROPERTY_NAME = "financialBalanceTypeCode"; public static final String ACCOUNT_SUFFICIENT_FUNDS_CODE_PROPERTY_NAME = "accountSufficientFundsCode"; public static final String CURRENT_BUDGET_BALANCE_AMOUNT_PROPERTY_NAME = "currentBudgetBalanceAmount"; public static final String ACCOUNT_ENCUMBRANCE_AMOUNT_PROPERTY_NAME = "accountEncumbranceAmount"; public static final String TRANSACTION_DEBIT_CREDIT_CODE = "transactionDebitCreditCode"; public static final String TRANSACTION_LEDGER_ENTRY_AMOUNT = "transactionLedgerEntryAmount"; public static final String ACCOUNT_SUFFICIENT_FUNDS_FINANCIAL_OBJECT_CODE_PROPERTY_NAME = "acctSufficientFundsFinObjCd"; public static final String FINANCIAL_OBJECT_TYPE_CODE = "financialObjectTypeCode"; public static final String FINANCIAL_DOCUMENT_TYPE_CODE = "financialDocumentTypeCode"; public static final String ORGANIZATION_CODE_PROPERTY_NAME = "organizationCode"; public static final String ORIGIN_CODE_KUALI = "01"; public static final String TRANSFER_FUNDS = "TF"; public static final String[] ENCUMBRANCE_BALANCE_TYPE = new String[] { BALANCE_TYPE_EXTERNAL_ENCUMBRANCE, BALANCE_TYPE_INTERNAL_ENCUMBRANCE, BALANCE_TYPE_PRE_ENCUMBRANCE }; public static final String LABOR_DISTRIBUTION_ORIGIN_CODE = "LD"; public static final String STAND_IN_BUSINESS_OBJECT_FOR_ATTRIBUTES = "KFSAttributeReferenceDummy"; public static final String LABOR_MODIFIED_INQUIRY_ACTION = "laborModifiedInquiry.do"; public static final String LABOR_A2_BALANCE_TYPE = "A2"; public static final String EMPLOYEE_FUNDING_INQUIRY_ACTION = "employeeFundingInquiry.do"; public static final String OVERRIDE_KEYS = "overrideKeys"; public static final String[] LLCP_GROUP_FILTER_EXCEPTION = new String[] { "LLGL" }; public static final String PERCENTAGE_SIGN = "%"; /** * This value denotes that a max length has not been defined for a given lookup results field */ public static final int LOOKUP_RESULT_FIELD_MAX_LENGTH_NOT_DEFINED = -1; /** * The number of levels BusinessObjectDictionaryServiceImpl will recurse. If this number is high, it may lead to serious * performance problems */ public static final int BUSINESS_OBJECT_DICTIONARY_SERVICE_PERFORM_FORCE_UPPERCASE_RECURSION_MAX_DEPTH = 3; /** * When checkboxes are rendered on the form, a hidden field will also be rendered corresponding to each checkbox with the * checkbox's name suffixed with the value of this constant. No real fields should have names that contain this suffix, since * this may lead to undesired results. */ public static final String CHECKBOX_PRESENT_ON_FORM_ANNOTATION = "{CheckboxPresentOnFormAnnotation}"; public static class OrgReversion { public static final String VALID_PREFIX = "EXTENDED_DEFINITIONS_INCLUDE_"; public static final String INVALID_PREFIX = "EXTENDED_DEFINITIONS_EXCLUDE_"; public static final String OBJECT_CONSOL_PARAM_SUFFIX = "OBJECT_CONSOLIDATIONS_BY_ORGANIZATION_REVERSION_CATEGORY"; public static final String OBJECT_LEVEL_PARAM_SUFFIX = "OBJECT_LEVELS_BY_ORGANIZATION_REVERSION_CATEGORY"; public static final String OBJECT_TYPE_PARAM_SUFFIX = "OBJECT_TYPES_BY_ORGANIZATION_REVERSION_CATEGORY"; public static final String OBJECT_SUB_TYPE_PARAM_SUFFIX = "OBJECT_SUB_TYPES_BY_ORGANIZATION_REVERSION_CATEGORY"; public static final String IS_EXPENSE_PARAM = "EXTENDED_DEFINITIONS_EXPENSE_CATEGORIES"; } // CR doc properties public static final String NEW_CHECK_PROPERTY_NAME = "newCheck"; public static final String EXISTING_CHECK_PROPERTY_NAME = "check"; public static final int DOCUMENT_ANNOTATION_MAX_LENGTH = 2000; // TRN_LDGR_DEBIT_CRDT_CD valid values public static final String GL_DEBIT_CODE = "D"; public static final String GL_CREDIT_CODE = "C"; public static final String GL_BUDGET_CODE = " "; // TRN_ENCUM_UPDT_CD value values public static final String ENCUMB_UPDT_DOCUMENT_CD = "D"; public static final String ENCUMB_UPDT_REFERENCE_DOCUMENT_CD = "R"; public static final String ENCUMB_UPDT_NO_ENCUMBRANCE_CD = "N"; // GL Reversal Generated Entry Description Prefix public static final String GL_REVERSAL_DESCRIPTION_PREFIX = "AUTO REVERSAL-"; // Misc GL text. public static final String PLANT_INDEBTEDNESS_ENTRY_DESCRIPTION = "GENERATED TRANSFER TO NET PLANT"; // Sufficient Funds Type Codes public static final String SF_TYPE_NO_CHECKING = "N"; public static final String SF_TYPE_OBJECT = "O"; public static final String SF_TYPE_LEVEL = "L"; public static final String SF_TYPE_CONSOLIDATION = "C"; public static final String SF_TYPE_CASH_AT_ACCOUNT = "H"; public static final String SF_TYPE_ACCOUNT = "A"; public static final String BUDGET_CHECKING_OPTIONS_CD_ACTIVE = "Y"; public static final String GRANT = "Grant"; public static final String HIDE_LOOKUP_RETURN_LINK = "hideReturnLink"; public static final String SUPPRESS_ACTIONS = "suppressActions"; public static final String REFERENCES_TO_REFRESH = "referencesToRefresh"; public static final String INCOME = "Income"; public static final String INITIAL_KUALI_DOCUMENT_STATUS_CD = "?"; public static final String INSERT_SOURCE_LINE_METHOD = "insertSourceLine"; public static final String INSERT_TARGET_LINE_METHOD = "insertTargetLine"; public static final String ICR = "Receipt"; public static final String PARM_SECTION_NAME_FIELD = "FS_SCR_NM"; public static final String PARM_PARM_NAME_FIELD = "FS_PARM_NM"; public static final String PROJECT_CODE_PROPERTY_NAME = "projectCode"; public static final String INQUIRABLE_ATTRIBUTE_NAME = "kualiInquirable"; public static final String INQUIRY_ACTION = "kr/inquiry.do"; public static final String INQUIRY_IMPL_ATTRIBUTE_NAME = "inquirableImplServiceName"; public static final String JOURNAL_VOUCHER_CHANGE_BALANCE_TYPE_QUESTION = "JournalVoucherChangeBalanceTypeQuestion"; public static final String JOURNAL_VOUCHER_ROUTE_OUT_OF_BALANCE_DOCUMENT_QUESTION = "JournalVoucherRouteOutOfBalanceDocumentQuestion"; public static final String JOURNAL_VOUCHER_ENCUMBRANCE_UPDATE_CODE_BALANCE_TYPE_EXTERNAL_ENCUMBRANCE = "R"; public static final String JOURNAL_LINE_HELPER_PROPERTY_NAME = "journalLineHelper"; public static final String AUXILIARY_LINE_HELPER_PROPERTY_NAME = "auxiliaryLineHelper"; public static final String VOUCHER_LINE_HELPER_CREDIT_PROPERTY_NAME = ".credit"; public static final String VOUCHER_LINE_HELPER_DEBIT_PROPERTY_NAME = ".debit"; public static final String KUALI_WORKFLOW_APPLICATION_CODE = "kuali"; public static final String LOOKUP_ACTION = "kr/lookup.do"; public static final String LOOKUP_RESULTS_SEQUENCE_NUMBER = "lookupResultsSequenceNumber"; public static final String LOOKUP_RESULTS_BO_CLASS_NAME = "lookupResultsBOClassName"; public static final String LOOKED_UP_COLLECTION_NAME = "lookedUpCollectionName"; public static final String MULTIPLE_VALUE_LOOKUP_PREVIOUSLY_SELECTED_OBJ_IDS_PARAM = "previouslySelectedObjectIds"; public static final String MULTIPLE_VALUE_LOOKUP_OBJ_IDS_SEPARATOR = "||"; public static final String MULTIPLE_VALUE_LOOKUP_DISPLAYED_OBJ_ID_PARAM_PREFIX = "displayedObjId-"; public static final String MULTIPLE_VALUE_LOOKUP_SELECTED_OBJ_ID_PARAM_PREFIX = "selectedObjId-"; public static final String LOOKUP_ANCHOR = "lookupAnchor"; public static final String LOOKUPABLE_IMPL_ATTRIBUTE_NAME = "lookupableImplServiceName"; public static final String LOOKUP_RESULTS_SEQUENCE = "LOOKUP_RESULT_SEQUENCE_NBR_SEQ"; public static final String KUALI_LOOKUPABLE_IMPL = "kualiLookupable"; public static final String KUALI_USER_LOOKUPABLE_IMPL = "universalUserLookupable"; public static final String DOC_HANDLER_ACTION = "DocHandler.do"; public static final String DOC_HANDLER_METHOD = "docHandler"; public static final String PARAMETER_DOC_ID = "docId"; public static final String PARAMETER_COMMAND = "command"; public static final String LOOKUP_METHOD = "performLookup"; public static final String METHOD_DISPLAY_DOC_SEARCH_VIEW = "displayDocSearchView"; public static final String MAINTENANCE_ACTION = "maintenance.do"; public static final String MAINTENANCE_ADD_PREFIX = "add."; public static final String MAINTENANCE_COPY_ACTION = "Copy"; public static final String MAINTENANCE_EDIT_ACTION = "Edit"; public static final String MAINTENANCE_NEW_ACTION = "New"; public static final String MAINTENANCE_COPY_METHOD_TO_CALL = "copy"; public static final String MAINTENANCE_EDIT_METHOD_TO_CALL = "edit"; public static final String MAINTENANCE_NEW_METHOD_TO_CALL = "start"; public static final String MAINTENANCE_NEWWITHEXISTING_ACTION = "newWithExisting"; public static final String MAINTENANCE_NEW_MAINTAINABLE = "document.newMaintainableObject."; public static final String MAINTENANCE_OLD_MAINTAINABLE = "document.oldMaintainableObject."; public static final String ENCRYPTED_LIST_PREFIX = "encryptedValues"; public static final String MAPPING_BASIC = "basic"; public static final String MAPPING_CANCEL = "cancel"; public static final String MAPPING_CLOSE = "close"; public static final String MAPPING_DISAPPROVE = "disapprove"; public static final String MAPPING_DELETE = "delete"; public static final String MAPPING_ERROR = "error"; public static final String MAPPING_PORTAL = "portal"; public static final String MAPPING_MULTIPLE_VALUE_LOOKUP = "multipleValueLookup"; public static final String MAPPING_BALANCE_INQUIRY_REPORT_MENU = "balanceInquiryReportMenu"; public static final String MAPPING_DV_PER_DIEM_LINKS = "dvPerDiemLinks"; public static final String MAXLENGTH_SUFFIX = ".maxLength"; public static final String METHOD_TO_CALL_ATTRIBUTE = "methodToCallAttribute"; public static final String METHOD_TO_CALL_PATH = "methodToCallPath"; public static final String METHOD_TO_CALL_BOPARM_LEFT_DEL = "(!!"; public static final String METHOD_TO_CALL_BOPARM_RIGHT_DEL = "!!)"; public static final String METHOD_TO_CALL_PARM1_LEFT_DEL = "((("; public static final String METHOD_TO_CALL_PARM1_RIGHT_DEL = ")))"; public static final String METHOD_TO_CALL_PARM2_LEFT_DEL = "((#"; public static final String METHOD_TO_CALL_PARM2_RIGHT_DEL = "#))"; public static final String METHOD_TO_CALL_PARM3_LEFT_DEL = "((<"; public static final String METHOD_TO_CALL_PARM3_RIGHT_DEL = ">))"; public static final String METHOD_TO_CALL_PARM4_LEFT_DEL = "((["; public static final String METHOD_TO_CALL_PARM4_RIGHT_DEL = "]))"; public static final String METHOD_TO_CALL_PARM5_LEFT_DEL = "((*"; public static final String METHOD_TO_CALL_PARM5_RIGHT_DEL = "*))"; public static final String METHOD_TO_CALL_PARM6_LEFT_DEL = "((%"; public static final String METHOD_TO_CALL_PARM6_RIGHT_DEL = "%))"; public static final String METHOD_TO_CALL_PARM7_LEFT_DEL = "((^"; public static final String METHOD_TO_CALL_PARM7_RIGHT_DEL = "^))"; public static final String METHOD_TO_CALL_PARM8_LEFT_DEL = "((&"; public static final String METHOD_TO_CALL_PARM8_RIGHT_DEL = "&))"; public static final String METHOD_TO_CALL_PARM9_LEFT_DEL = "((~"; public static final String METHOD_TO_CALL_PARM9_RIGHT_DEL = "~))"; public static final String METHOD_TO_CALL_PARM10_LEFT_DEL = "((/"; public static final String METHOD_TO_CALL_PARM10_RIGHT_DEL = "/))"; public static final String METHOD_TO_CALL_PARM11_LEFT_DEL = "(:;"; public static final String METHOD_TO_CALL_PARM11_RIGHT_DEL = ";:)"; public static final String METHOD_TO_CALL_PARM12_LEFT_DEL = "(::;"; public static final String METHOD_TO_CALL_PARM12_RIGHT_DEL = ";::)"; public static final String METHOD_TO_CALL_PARM13_LEFT_DEL = "(:::;"; public static final String METHOD_TO_CALL_PARM13_RIGHT_DEL = ";:::)"; // if more strings needed, then add more colons to the PARM11 strings above, e.g. (::; (:::;, etc. public static final String ANCHOR = "anchor"; public static final String ANCHOR_TOP_OF_FORM = "topOfForm"; public static final String QUESTION_ANCHOR = "questionAnchor"; public static final String NOT_AVAILABLE_STRING = "N/A"; public static final int NEGATIVE_ONE = -1; public static final String OBJECT_CODE_STATUS_ACTIVE = "Y"; public static final String OBJECT_TYPE_CODE_PROPERTY_NAME = "objectTypeCode"; public static final String CONTEXT_PATH = "contextPath"; public static final String QUESTION_ACTION = "questionPrompt.do"; public static final String QUESTION_CLICKED_BUTTON = "buttonClicked"; public static final String QUESTION_ERROR_KEY = "questionErrorKey"; public static final String QUESTION_ERROR_PROPERTY_NAME = "questionErrorPropertyName"; public static final String QUESTION_ERROR_PARAMETER = "questionErrorParameter"; public static final String QUESTION_IMPL_ATTRIBUTE_NAME = "questionType"; public static final String QUESTION_INST_ATTRIBUTE_NAME = "questionIndex"; public static final String QUESTION_PAGE_TITLE = "Question Dialog Page"; public static final String QUESTION_REFRESH = "QuestionRefresh"; public static final String QUESTION_CONTEXT = "context"; public static final String QUESTION_TEXT_ATTRIBUTE_NAME = "questionText"; public static final String QUESTION_REASON_ATTRIBUTE_NAME = "reason"; public static final String QUESTION_SHOW_REASON_FIELD = "showReasonField"; public static final String RELOAD_METHOD_TO_CALL = "reload"; public static final String REFRESH_CALLER = "refreshCaller"; public static final String REFRESH_MAPPING_PREFIX = "/Refresh"; public static final String REQUIRED_FIELD_SYMBOL = "*"; public static final String RETURN_LOCATION_PARAMETER = "returnLocation"; public static final String RETURN_METHOD_TO_CALL = "refresh"; public static final String ROUTE_METHOD = "route"; public static final String SAVE_METHOD = "save"; public static final String START_METHOD = "start"; public static final String SEARCH_METHOD = "search"; public static final String COPY_METHOD = "copy"; public static final String ERRORCORRECT_METHOD = "correct"; public static final String SOURCE = "Source"; public static final String SQUARE_BRACKET_LEFT = "["; public static final String SQUARE_BRACKET_RIGHT = "]"; public static final String SUB_ACCOUNT_STATUS_ACTIVE = "Y"; public static final String SUB_ACCOUNT_NUMBER_PROPERTY_NAME = "subAccountNumber"; public static final String SUB_OBJECT_CODE_STATUS_ACTIVE = "Y"; public static final String TARGET = "Target"; public static final String TO = "To"; public static final String USER_SESSION_KEY = "UserSession"; public static final String VERSION_NUMBER = "versionNumber"; public static final String SEARCH_LIST_KEY_PREFIX = "searchResults"; public static final String SEARCH_LIST_REQUEST_KEY = "searchResultKey"; public static final String CORRECTION_FORM_KEY = "correctionFormKey"; public static final int CORRECTION_RECENT_GROUPS_DAY = 10; public static final String SEARCH_DATA_KEY_PREFIX = "dataSearchResults"; public static final String SEARCH_DATA_REQUEST_KEY = "searchResultDataKey"; public static final String GLOBAL_ERRORS = "GLOBAL_ERRORS"; public static final String GLOBAL_MESSAGES = "GlobalMessages"; public static final String AD_HOC_ROUTE_PERSON_ERRORS = "newAdHocRoutePerson*,adHocRoutePerson*"; public static final String AD_HOC_ROUTE_WORKGROUP_ERRORS = "newAdHocRouteWorkgroup*,adHocRouteWorkgroup*"; public static final String DOCUMENT_DOCUMENT_ERRORS = "document.document*"; public static final String DOCUMENT_EXPLANATION_ERRORS = "document.explanation*"; public static final String DOCUMENT_REVERSAL_ERRORS = "document.reversal*"; public static final String DOCUMENT_SELECTED_ERRORS = "document.selected*"; public static final String DOCUMENT_HEADER_ERRORS = "document.header*"; public static final String DOCUMENT_ERRORS_LESS_DOCUMENT = DOCUMENT_EXPLANATION_ERRORS + "," + DOCUMENT_REVERSAL_ERRORS + "," + DOCUMENT_SELECTED_ERRORS + "," + DOCUMENT_HEADER_ERRORS; public static final String DOCUMENT_ERRORS = DOCUMENT_DOCUMENT_ERRORS + "," + DOCUMENT_EXPLANATION_ERRORS + "," + DOCUMENT_REVERSAL_ERRORS + "," + DOCUMENT_SELECTED_ERRORS + "," + DOCUMENT_HEADER_ERRORS; public static final String DOCUMENT_NOTES_ERRORS = "newDocumentNote*"; public static final String BUDGET_PARAMETERS_ERRORS = "newBudgetParameters*"; public static final String BUDGET_PERMISSIONS_ERRORS = "newBudgetPermissions*"; public static final String BUDGET_SPREADSHEET_ERRORS = "newBudgetPermissions*"; public static final String BUDGET_OUTPUT_ERRORS = "newBudgetPermissions*"; public static final String BUDGET_COSTING_ERRORS = "newBudgetPermissions*"; public enum NoteTypeEnum { BUSINESS_OBJECT_NOTE_TYPE("BO", "documentBusinessObject"), DOCUMENT_HEADER_NOTE_TYPE("DH", "documentHeader"); private String noteTypeCode; private String noteTypePath; private NoteTypeEnum(String noteTypeCode, String noteTypePath) { this.noteTypeCode = noteTypeCode; this.noteTypePath = noteTypePath; } public String getCode() { return this.noteTypeCode; } public String getPath() { return this.noteTypePath; } public String getFullPath() { return KFSConstants.DOCUMENT_PROPERTY_NAME + "." + getPath(); } } public static final String EDIT_JOURNAL_VOUCHER_ERRORS = "EditJournalVoucherErrors"; public static final String EDIT_AUXILIARY_VOUCHER_ERRORS = "EditAuxiliaryVoucherErrors"; public static final String EDIT_PRE_ENCUMBRANCE_ERRORS = "EditPreEncumbranceErrors"; public static final String ACCOUNTING_LINE_ERRORS = "document.accountingLines"; public static final String SOURCE_ACCOUNTING_LINE_ERROR_PATTERN = "document.sourceAccounting*,sourceAccountingLines,newSourceLine*,journalLineHelper*,auxiliaryLineHelper*"; public static final String TARGET_ACCOUNTING_LINE_ERROR_PATTERN = "document.targetAccounting*,targetAccountingLines,newTargetLine*"; public static final String ACCOUNTING_LINE_GROUP_SUFFIX = "s"; public static final String SOURCE_ACCOUNTING_LINE_ERRORS = EXISTING_SOURCE_ACCT_LINE_PROPERTY_NAME + ACCOUNTING_LINE_GROUP_SUFFIX; public static final String TARGET_ACCOUNTING_LINE_ERRORS = EXISTING_TARGET_ACCT_LINE_PROPERTY_NAME + ACCOUNTING_LINE_GROUP_SUFFIX; public static final String ITEM_LINE_ERRORS = "newItem*,document.item*"; public static final String CREDIT_CARD_RECEIPTS_LINE_ERRORS = "newCreditCardReceipt*,document.creditCardReceipt*"; public static final String ADVANCE_DEPOSITS_LINE_ERRORS = "newAdvanceDeposit*,document.advanceDeposit*"; public static final String GENERAL_LEDGER_PENDING_ENTRIES_TAB_ERRORS = "document.generalLedgerPendingEntr*"; public static final String BUDGET_CONSTRUCTION_SALARY_SETTING_TAB_ERRORS = "document.budgetConstructionSalarySetting*"; public static final String BUDGET_CONSTRUCTION_REVENUE_TAB_ERRORS = "document.budgetConstructionRevenue*"; public static final String BUDGET_CONSTRUCTION_EXPENDITURE_TAB_ERRORS = "document.budgetConstructionExpenditure*"; public static final String BUDGET_CONSTRUCTION_MONTHLY_BUDGET_ERRORS = "document.budgetConstructionMonthlyBudget*"; public static final String CASHIER_CLOSING_DRAWER_ERRORS = "document.bursarControl*"; public static final String AND_LOGICAL_OPERATOR = "&&"; public static final String OR_LOGICAL_OPERATOR = "|"; public static final String NOT_LOGICAL_OPERATOR = "!"; // add AND operator to thest if it is uncommented below public static final String[] LOGICAL_OPERATORS = { OR_LOGICAL_OPERATOR, NOT_LOGICAL_OPERATOR }; public static final String WILDCARD_CHARACTER = "*"; public static final String[] QUERY_CHARACTERS = { WILDCARD_CHARACTER, "?", "%", ">", "<", "..", OR_LOGICAL_OPERATOR, NOT_LOGICAL_OPERATOR, "=" }; public static final String WILDCARD_NOT_ALLOWED_ON_FIELD = "error.fieldDoNotAllowWildcard"; // disbursement voucher error fields public static final String DV_PAYEE_TAB_ERRORS = "DVPayeeErrors,document.dvPayeeDetail.disbVchrPayeeIdNumber,document.dvPayeeDetail.disbVchrPayeeCityName,document.dvPayeeDetail.disbVchrPayeePersonName," + "document.dvPayeeDetail.disbVchrPayeeStateCode,document.dvPayeeDetail.disbVchrPayeeLine1Addr,document.dvPayeeDetail.disbVchrPayeeZipCode,document.dvPayeeDetail.disbVchrPayeeLine2Addr,document.dvPayeeDetail.disbVchrPayeeCountryCode,document.dvPayeeDetail.disbursementVoucherPayeeTypeCode,"; public static final String DV_PAYMENT_TAB_ERRORS = "DVPaymentErrors,document.dvPayeeDetail.disbVchrPaymentReasonCode,document.disbVchrCheckTotalAmount,document.disbursementVoucherDueDate,document.dvPayeeDetail.disbVchrAlienPaymentCode," + "document.dvPayeeDetail.disbVchrPayeeEmployeeCode,document.disbVchrAttachmentCode,document.disbVchrSpecialHandlingCode,document.disbVchrPayeeW9CompleteCode" + "document.disbVchrPaymentMethodCode,document.disbursementVoucherDocumentationLocationCode,document.disbVchrCheckStubText"; public static final String DV_NRATAX_TAB_ERRORS = "DVNRATaxErrors,document.dvNonResidentAlienTax.incomeClassCode,document.dvNonResidentAlienTax.incomeTaxTreatyExemptCode,document.dvNonResidentAlienTax.federalIncomeTaxPercent," + "document.dvNonResidentAlienTax.foreignSourceIncomeCode,document.dvNonResidentAlienTax.stateIncomeTaxPercent,document.dvNonResidentAlienTax.incomeTaxGrossUpCode,document.dvNonResidentAlienTax.postalCountryCode," + "document.dvNonResidentAlienTax.referenceFinancialDocumentNumber"; public static final String DV_FOREIGNDRAFTS_TAB_ERRORS = "DVForeignDraftErrors,document.dvWireTransfer.disbursementVoucherForeignCurrencyTypeCode,document.dvWireTransfer.disbursementVoucherForeignCurrencyTypeName"; public static final String DV_CONTACT_TAB_ERRORS = "DVContactErrors,document.disbVchrContact*"; public static final String DV_SPECHAND_TAB_ERRORS = "DVSpecialHandlingErrors,document.dvPayeeDetail.disbVchrRemitPersonName,document.dvPayeeDetail.disbVchrRemitCityName,document.dvPayeeDetail.disbVchrRemitLine1Addr,document.dvPayeeDetail.disbVchrRemitStateCode," + "document.dvPayeeDetail.disbVchrRemitLine2Addr,document.dvPayeeDetail.disbVchrRemitZipCode,document.dvPayeeDetail.disbVchrRemitCountryName"; public static final String DV_WIRETRANSFER_TAB_ERRORS = "DVWireTransfersErrors,document.dvWireTransfer.disbursementVoucherBankName,document.dvWireTransfer.disbVchrBankRoutingNumber,document.dvWireTransfer.disbVchrBankCityName,document.dvWireTransfer.disbVchrBankStateCode," + "document.dvWireTransfer.disbVchrBankCountryCode,document.dvWireTransfer.disbVchrAttentionLineText,document.dvWireTransfer.disbVchrAdditionalWireText,document.dvWireTransfer.disbVchrPayeeAccountNumber,document.dvWireTransfer.disbVchrCurrencyTypeName,document.dvWireTransfer.disbVchrCurrencyTypeCode," + "document.dvWireTransfer.disbursementVoucherWireTransferFeeWaiverIndicator,document.dvWireTransfer.disbursementVoucherPayeeAccountName,document.dvWireTransfer.disbursementVoucherPayeeAccountTypeCode,document.dvWireTransfer.disbursementVoucherAutomatedClearingHouseProfileNumber"; public static final String DV_NON_EMPL_TRAVEL_TAB_ERRORS = "DVNonEmployeeTravelErrors,newPrePaidNonEmployeeExpenseLine.*,newNonEmployeeExpenseLine.*,document.dvNonEmployeeTravel.*"; public static final String DV_PREPAID_TAB_ERRORS = "DVPrePaidTravelErrors,newPreConferenceRegistrantLine.*,document.dvPreConferenceDetail.*"; public static final String PAYEE_W9_QUESTION = "PayeeW9Question"; public static final String PAYEE_NAME_EXIST_QUESTION = "PayeeNameExistQuestion"; public static final String COPY_NEW_PAYEE_ADDRESS_LINES = "NewPayeeCopyAddressLinesQuestion"; public static final String COPY_CHANGE_PAYEE_ADDRESS_LINES = "ChangePayeeCopyAddressLinesQuestion"; public static final String DV_PAYMENT_REASON_NONEMPLOYEE = "N"; public static final String DV_PAYMENT_REASON_NONEMPLOYEE_HONORARIUM = "X"; public static final String GENERAL_PAYEE_TAB_ERRORS = "DVPayeeErrors"; public static final String GENERAL_PAYMENT_TAB_ERRORS = "DVPaymentErrors"; public static final String GENERAL_NRATAX_TAB_ERRORS = "DVNRATaxErrors"; public static final String GENERAL_FOREIGNDRAFTS_TAB_ERRORS = "DVForeignDraftErrors"; public static final String GENERAL_CONTACT_TAB_ERRORS = "DVContactErrors"; public static final String GENERAL_SPECHAND_TAB_ERRORS = "DVSpecialHandlingErrors"; public static final String GENERAL_WIRETRANSFER_TAB_ERRORS = "DVWireTransfersErrors"; public static final String GENERAL_PREPAID_TAB_ERRORS = "DVPrePaidTravelErrors"; public static final String GENERAL_NONEMPLOYEE_TAB_ERRORS = "DVNonEmployeeTravelErrors,document.dvNonEmployeeTravel.totalTravelAmount"; public static final String DV_PAYEE_ID_FIELD_NAME = "dvPayeeDetail.disbVchrPayeeIdNumber"; public static final String DV_PAYMENT_REASON_FIELD_NAME = "dvPayeeDetail.disbVchrPaymentReasonCode"; public static final String DV_CHECK_TRAVEL_TOTAL_ERROR = "document.dvNonEmployeeTravel.totalTravelAmount"; // KRA-related constant values public static final KualiDecimal CONTRACTS_AND_GRANTS_FRINGE_RATE_MAX = new KualiDecimal("100.0"); public static final KualiDecimal CONTRACTS_AND_GRANTS_COST_SHARE_MAX = new KualiDecimal("100.0"); public static final KualiDecimal GRADUATE_ASSISTANT_RATE_MAX = new KualiDecimal("9999.99"); public static final String AUDIT_ERRORS = "AuditErrors"; // Header Tab navigation constant values public static final String NAVIGATE_TO = "navigateTo."; public static final String HEADER_DISPATCH = "headerDispatch."; // country public static final String COUNTRY_CODE_UNITED_STATES = "US"; // CashManagement tab errors public static final String CASH_MANAGEMENT_DEPOSIT_ERRORS = "document.deposit*"; // Coin and Currency Amounts public static class CoinTypeAmounts { public static final KualiDecimal HUNDRED_CENT_AMOUNT = new KualiDecimal(1.0); public static final KualiDecimal FIFTY_CENT_AMOUNT = new KualiDecimal(0.5); public static final KualiDecimal TWENTY_FIVE_CENT_AMOUNT = new KualiDecimal(0.25); public static final KualiDecimal TEN_CENT_AMOUNT = new KualiDecimal(0.1); public static final KualiDecimal FIVE_CENT_AMOUNT = new KualiDecimal(0.05); public static final KualiDecimal ONE_CENT_AMOUNT = new KualiDecimal(0.01); } public static class CurrencyTypeAmounts { public static final KualiDecimal HUNDRED_DOLLAR_AMOUNT = new KualiDecimal(100.0); public static final KualiDecimal FIFTY_DOLLAR_AMOUNT = new KualiDecimal(50.0); public static final KualiDecimal TWENTY_DOLLAR_AMOUNT = new KualiDecimal(20.0); public static final KualiDecimal TEN_DOLLAR_AMOUNT = new KualiDecimal(10.0); public static final KualiDecimal FIVE_DOLLAR_AMOUNT = new KualiDecimal(5.0); public static final KualiDecimal TWO_DOLLAR_AMOUNT = new KualiDecimal(2.0); public static final KualiDecimal ONE_DOLLAR_AMOUNT = new KualiDecimal(1.0); } // Cashiering source constants public static class CurrencyCoinSources { public static final String CASH_MANAGEMENT_IN = "R"; // money coming in through cashiering activity public static final String DEPOSITS = "D"; // money going out through deposits public static final String CASH_RECEIPTS = "C"; // money coming in through cash receipts public static final String CASH_MANAGEMENT_OUT = "O"; // money going out through cashiering activity public static final String CASH_MANAGEMENT_MASTER = "M"; // an amalgamation of a cashiering transaction } // Constants for check sources // Why are these constants different from the Currency/Coin constants? // Why, I ask you in return, is the sky blue? That's right, because of // the effect of Rayleigh scattering on atmospheric particles. That's why. public static class CheckSources { public static final String CASH_RECEIPTS = "R"; public static final String CASH_MANAGEMENT = "I"; } public static final String CASHIERING_TRANSACTION_OPEN_ITEM_IN_PROCESS_PROPERTY = "document.currentTransaction.openItemInProcess"; // Tab error patterns must be at the top level; JSPs do not have access to the nested classes. public static final String EDIT_CASH_RECEIPT_CASH_RECONCILIATION_ERRORS = "document.totalCashAmount,document.totalCheckAmount,document.totalCoinAmount,document.sumTotalAmount"; public static final String EDIT_CASH_RECEIPT_CHECK_DETAIL_ERRORS = "newCheck*,document.check*"; public static final String EDIT_CASH_RECEIPT_CURRENCY_COIN_ERRORS = "document.currencyDetail.*,document.coinDetail.*"; public static final String EDIT_CASH_MANAGEMENT_CASHIERING_TRANSACTION_ERRORS = "document.currentTransaction.*"; public static final String MULTIPLE_VALUE = "multipleValues"; public static final String MULTIPLE_VALUE_LABEL = "Lookup initial values"; public static final String MULTIPLE_VALUE_NAME = "Multiple Value Name"; // Agency type codes public static final String AGENCY_TYPE_CODE_FEDERAL = "F"; // special chars that I don't know how to put into string literals in JSP expression language public static final String NEWLINE = "\n"; // Workflow constants public static final String WORKFLOW_FYI_REQUEST = "F"; public static final String WORKFLOW_APPROVE_REQUEST = "A"; // Permission codes public static final String PERMISSION_READ_CODE = "R"; public static final String PERMISSION_READ_DESCRIPTION = "READ"; public static final String PERMISSION_MOD_CODE = "M"; public static final String PERMISSION_MOD_DESCRIPTION = "MOD"; public static final String PERMISSION_MODIFY = "modify"; public static final String PERMISSION_VIEW = "view"; public static class DocumentStatusCodes { public static final String INITIATED = "?"; public static final String CANCELLED = "X"; public static final String ENROUTE = "R"; public static final String DISAPPROVED = "D"; public static final String APPROVED = "A"; public static class CashReceipt { // once a CashReceipt gets approved, its financialDocumentStatus goes to "verified" public static final String VERIFIED = "V"; // when a CashReceipt associated with a Deposit, its financialDocumentStatus changes to "interim" or "final" public static final String INTERIM = "I"; public static final String FINAL = "F"; // when the CMDoc is finalized, the CRs of its Deposits change to status "approved" } } public static class AdvanceDepositConstants { public static final String CASH_RECEIPT_ADVANCE_DEPOSIT_COLUMN_TYPE_CODE = "R"; } public static class AuxiliaryVoucher { public static final String ADJUSTMENT_DOC_TYPE = "AVAD"; public static final String ADJUSTMENT_DOC_TYPE_NAME = "Adjustment"; public static final String RECODE_DOC_TYPE = "AVRC"; public static final String RECODE_DOC_TYPE_NAME = "Recode"; public static final String ACCRUAL_DOC_TYPE = "AVAE"; public static final String ACCRUAL_DOC_TYPE_NAME = "Accrual"; public static final String ERROR_DOCUMENT_RECODE_DISTRIBUTION_OF_INCOME_AND_EXPENSE_UNSUCCESSFUL = "Unable to auto-generate Distribution of Income and Expense for document with number \"%s.\" Please contact your System Administrator for a Distribution of Income and Expense to be created manually."; public static final String ERROR_DOCUMENT_HAS_TARGET_LINES = "AV document doesn't have target accounting lines. This method should have never been entered"; public static final String RECODE_DISTRIBUTION_OF_INCOME_AND_EXPENSE_DESCRIPTION = "Auto-generated for Auxiliary Voucher"; public static final String RECODE_DISTRIBUTION_OF_INCOME_AND_EXPENSE_EXPLANATION = "Auxiliary Voucher recode document type was chosen. A Distribution of Income And Expense needs to be routed to FINAL along with it. This Document is routed by Auxiliary Voucher \"%s\"."; public static final String CHANGE_VOUCHER_TYPE = "changeVoucherType"; } public static class CashDrawerConstants { public static final String STATUS_CLOSED = "C"; public static final String STATUS_OPEN = "O"; public static final String STATUS_LOCKED = "L"; } public static class CashReceiptConstants { public static final String TEST_CASH_RECEIPT_VERIFICATION_UNIT = "HAWAII_CR_VERIFICATION_UNIT"; public static final String TEST_CASH_RECEIPT_CAMPUS_LOCATION_CODE = "HI"; public static final String DEFAULT_CASH_RECEIPT_CAMPUS_LOCATION_CODE = "??"; public static final String CASH_RECEIPT_CAMPUS_LOCATION_CODE_PROPERTY_NAME = "campusLocationCode"; public static final String CASH_RECEIPT_DOC_HEADER_STATUS_CODE_PROPERTY_NAME = KFSConstants.DOCUMENT_HEADER_PROPERTY_NAME + "." + KFSConstants.DOCUMENT_HEADER_DOCUMENT_STATUS_CODE_PROPERTY_NAME; } public static class DepositConstants { public static final String DEPOSIT_TYPE_INTERIM = "I"; public static final String DEPOSIT_TYPE_FINAL = "F"; public static final String DEPOSIT_WIZARD_CASHRECEIPT_ERROR = "cashReceiptErrors"; public static final String DEPOSIT_WIZARD_DEPOSITHEADER_ERROR = "depositHeaderErrors"; } public static class CreditCardReceiptConstants { public static final String CASH_RECEIPT_CREDIT_CARD_RECEIPT_COLUMN_TYPE_CODE = "R"; } public static class BudgetAdjustmentDocumentConstants { public static final String SOURCE_BA = "From/Decrease"; public static final String TARGET_BA = "To/Increase"; public static final String GENERATE_BENEFITS_QUESTION_ID = "GenerateBenefitsQuestion"; public static final String ADJUSTMENT_RESTRICTION_LEVEL_FUND = "F"; public static final String ADJUSTMENT_RESTRICTION_LEVEL_CHART = "C"; public static final String ADJUSTMENT_RESTRICTION_LEVEL_ORGANIZATION = "O"; public static final String ADJUSTMENT_RESTRICTION_LEVEL_ACCOUNT = "A"; public static final String ADJUSTMENT_RESTRICTION_LEVEL_SUBFUND = "S"; public static final String ADJUSTMENT_RESTRICTION_LEVEL_NONE = "N"; } public static class BudgetConstructionPositionConstants { public static final String POSITION_REGULAR_TEMPORARY_REGULAR = "R"; public static final String POSITION_REGULAR_TEMPORARY_TEMPORARY = "T"; public static final String POSITION_EFFECTIVE_STATUS_ACTIVE = "A"; public static final String POSITION_EFFECTIVE_STATUS_INACTIVE = "I"; public static final String POSITION_STATUS_APPROVED = "A"; public static final String POSITION_STATUS_DELETED = "D"; public static final String POSITION_STATUS_FROZEN = "F"; public static final String POSITION_STATUS_TEMPORARILY_INACTIVE = "T"; } public static class DisbursementVoucherDocumentConstants { public static final String CLEAR_NON_EMPLOYEE_TAB_QUESTION_ID = "ClearNonEmplTravTabQuestion"; public static final String CLEAR_WIRE_TRANSFER_TAB_QUESTION_ID = "ClearWireTransferTabQuestion"; public static final String CLEAR_FOREIGN_DRAFT_TAB_QUESTION_ID = "ClearForeignDraftTabQuestion"; } public static class CoreApcParms { // Kuali User params public static final String USER_INVALID_EMPLOYEE_STATUSES = "ACTIVE_KFS_USER_EMPLOYEE_STATUSES"; public static final String UNIVERSAL_USER_EDIT_WORKGROUP = "UNIVERSAL_USER_EDIT_GROUP"; public static final String SERVICE_BUS_ACCESS_GROUP_PARM = "SERVICE_BUS_ACCESS_GROUP"; } public static final String MAINTENANCE_ADMIN_WORKGROUP_PARM_NM = "MAINTENANCE_ADMIN_GROUP"; public static final String ACCOUNTING_LINE_IMPORT_MAX_FILE_SIZE_PARM_NM = "MAX_FILE_SIZE_ACCOUNTING_LINE_IMPORT"; public static final String ORIGIN_ENTRY_IMPORT_MAX_FILE_SIZE_PARM_NM = "MAX_FILE_SIZE_ORIGIN_ENTRY_IMPORT"; public static class ChartApcParms { public static final String FISCAL_YEAR_MAKER_REPLACE_MODE = "OVERRIDE_TARGET_YEAR_DATA_IND"; public static final String FISCAL_YEAR_MAKER_SOURCE_FISCAL_YEAR = "SOURCE_FISCAL_YEAR"; // added from parameter refactoring. public static final String APC_HRMS_ACTIVE_KEY = "USE_HRMS_ORGANIZATION_ATTRIBUTES_IND"; public final static String OBJECT_CODE_ILLEGAL_VALUES = "OBJECT_CODES"; public static final String DOCTYPE_AND_OBJ_CODE_ACTIVE = "DOCUMENT_TYPES_REQUIRING_ACTIVE_OBJECT_CODES"; public static final String INVALID_DOCUMENT_TYPES_BY_OBJECT_SUB_TYPE = "INVALID_DOCUMENT_TYPES_BY_OBJECT_SUB_TYPE"; public static final String VALID_DOCUMENT_TYPES_BY_OBJECT_SUB_TYPE = "VALID_DOCUMENT_TYPES_BY_OBJECT_SUB_TYPE"; public static final String CG_ALLOWED_SUBACCOUNT_TYPE_CODES = "SUB_ACCOUNT_TYPES"; // Account parms public static final String ACCOUNT_USER_EMP_STATUSES = "ROLE_EMPLOYEE_STATUSES"; public static final String ACCOUNT_USER_EMP_TYPES = "ROLE_EMPLOYEE_TYPES"; // Delegate parms public static final String DELEGATE_USER_EMP_STATUSES = "EMPLOYEE_STATUSES"; public static final String DELEGATE_USER_EMP_TYPES = "EMPLOYEE_TYPES"; // SubAccount parms public static final String SUBACCOUNT_CG_WORKGROUP_PARM_NAME = "CG_GROUP"; // Org parms public static final String DEFAULT_ACCOUNT_NOT_REQUIRED_ORG_TYPES = "ORGANIZATION_TYPES_NOT_REQUIRING_DEFAULT_ACCOUNT"; public static final String ORG_MUST_REPORT_TO_SELF_ORG_TYPES = "ORGANIZATION_TYPES_THAT_MUST_REPORT_TO_SELF"; public static final String ORG_PLANT_WORKGROUP_PARM_NAME = "PLANT_GROUP"; public static final String ADMINISTRATOR_WORKGROUP = "Maintenance.Admin.Workgroup"; public static final String ACCOUNT_FUND_GROUP_DENOTES_CG = "FUND_GROUP_DENOTES_CG_IND"; public static final String ACCOUNT_CG_DENOTING_VALUE = "CG_DENOTING_VALUE"; public static final String DEFAULT_USER_CHART_CODE_SOURCE_ATTRIBUTE = "DEFAULT_CHART_SOURCE_ATTRIBUTE"; public static final String DEFAULT_USER_CHART_CODE_EXTRACTION_REGEXP = "DEFAULT_CHART_EXTRACTION_REG_EXP"; public static final String DEFAULT_USER_ORGANIZATION_CODE_SOURCE_ATTRIBUTE = "DEFAULT_ORGANIZATION_SOURCE_ATTRIBUTE"; public static final String DEFAULT_USER_ORGANIZATION_CODE_EXTRACTION_REGEXP = "DEFAULT_ORGANIZATION_EXTRACTION_REG_EXP"; } public static class FinancialApcParms { // public static final String GROUP_DV_DOCUMENT = "Kuali.FinancialTransactionProcessing.DisbursementVoucherDocument"; public static final String DV_TAX_WORKGROUP = "TAX_GROUP"; public static final String DV_ADMIN_WORKGROUP = "ADMIN_GROUP"; public static final String DV_FOREIGNDRAFT_WORKGROUP = "FOREIGN_DRAFT_GROUP"; public static final String DV_WIRETRANSFER_WORKGROUP = "WIRE_TRANSFER_GROUP"; public static final String DV_TRAVEL_WORKGROUP = "TRAVEL_GROUP"; public static final String ACCOUNTING_LINE_IMPORT_HELP = "ACCOUNTING_LINE_IMPORT"; } public static class SystemGroupParameterNames { public static final String FLEXIBLE_OFFSET_ENABLED_FLAG = "USE_FLEXIBLE_OFFSET_IND"; public static final String FLEXIBLE_CLAIM_ON_CASH_BANK_ENABLED_FLAG = "USE_FLEXIBLE_CLAIM_ON_CASH_IND"; public static final String ICR_ENCUMBRANCE_ENABLED_FLAG = "USE_ICR_ENCUMBRANCE_IND"; public static final String PURGE_GL_ACCT_BALANCES_T_BEFORE_YEAR = "PRIOR_TO_YEAR"; public static final String PURGE_GL_ENCUMBRANCE_T_BEFORE_YEAR = "PRIOR_TO_YEAR"; public static final String PURGE_GL_SF_BALANCES_T_BEFORE_YEAR = "PRIOR_TO_YEAR"; public static final String PURGE_GL_BALANCE_T_BEFORE_YEAR = "PRIOR_TO_YEAR"; public static final String PURGE_GL_ENTRY_T_BEFORE_YEAR = "PRIOR_TO_YEAR"; public static final String PURGE_GL_ID_BILL_T_BEFORE_YEAR = "PRIOR_TO_YEAR"; public static final String GL_ANNUAL_CLOSING_DOC_TYPE = "ANNUAL_CLOSING_DOCUMENT_TYPE"; public static final String GL_INDIRECT_COST_RECOVERY = "INDIRECT_COST_RECOVERY_DOCUMENT_TYPE"; public static final String GL_NET_EXPENSE_OBJECT_TYPE_CODE = "NET_EXPENSE_OBJECT_TYPE_CODE"; public static final String GL_ORIGINATION_CODE = "MANUAL_FEED_ORIGINATION"; public static final String GL_SCRUBBER_VALIDATION_DAYS_OFFSET = "CG_ACCOUNT_EXPIRATION_EXTENSION_DAYS"; public static final String MULTIPLE_VALUE_LOOKUP_RESULTS_PER_PAGE = "MULTIPLE_VALUE_RESULTS_PER_PAGE"; public static final String MULTIPLE_VALUE_LOOKUP_RESULTS_EXPIRATION_AGE = "MULTIPLE_VALUE_RESULTS_EXPIRATION_SECONDS"; public static final String ACTIVE_INPUT_TYPES_PARAMETER_NAME = "ACTIVE_FILE_TYPES"; public static final String FILE_TYPE_WORKGROUP_PARAMETER_NAME = "UPLOAD_GROUP"; public static final String COLLECTOR_VALIDATOR_EMAIL_SUBJECT_PARAMETER_NAME = "VALIDATION_EMAIL_SUBJECT_LINE"; public static final String COLLECTOR_DEMERGER_EMAIL_SUBJECT_PARAMETER_NAME = "ERROR_EMAIL_SUBJECT_LINE"; public static final String COLLECTOR_EQUAL_DC_TOTAL_DOCUMENT_TYPES = "EQUAL_DEBIT_CREDIT_TOTAL_DOCUMENT_TYPES"; public static final String COLLECTOR_PERFORM_DUPLICATE_HEADER_CHECK = "PERFORM_DUPLICATE_HEADER_CHECK_IND"; public static final String BATCH_SCHEDULE_CUTOFF_TIME = "CUTOFF_TIME"; public static final String BATCH_SCHEDULE_CUTOFF_TIME_IS_NEXT_DAY = "CUTOFF_TIME_NEXT_DAY_IND"; public static final String BATCH_SCHEDULE_STATUS_CHECK_INTERVAL = "STATUS_CHECK_INTERVAL"; /** * Used by PurgePendingAttachmentsJob to compute the maximum amount of time a pending attachment is allowed to persist on * the file system before being deleted. */ public static final String PURGE_PENDING_ATTACHMENTS_STEP_MAX_AGE = "MAX_AGE"; public static final String JOB_ADMIN_WORKGROUP = "SCHEDULE_ADMIN_GROUP"; public static final String JOB_WORKGROUP_SUFFIX = "_SCHEDULE_GROUP"; } public static class GeneralLedgerApplicationParameterKeys { public static final String INCOME_OBJECT_TYPE_CODES = "INCOME_OBJECT_TYPE_CODES"; public static final String INCOME_TRANSFER_OBJECT_TYPE_CODES = "INCOME_TRANSFER_OBJECT_TYPE_CODES"; public static final String EXPENSE_OBJECT_TYPE_CODES = "EXPENSE_OBJECT_TYPE_CODES"; public static final String EXPENSE_TRANSFER_OBJECT_TYPE_CODES = "EXPENSE_TRANSFER_OBJECT_TYPE_CODES"; } public static class GeneralLedgerCorrectionProcessApplicationParameterKeys { public static final String RECORD_COUNT_FUNCTIONALITY_LIMIT = "RECORD_COUNT_FUNCTIONALITY_LIMIT"; public static final String RECORDS_PER_PAGE = "RECORDS_PER_PAGE"; } public static class EnterpriseFeederApplicationParameterKeys { public static final String TO_ADDRESS = "INVALID_FILE_TO_ADDRESSES"; } public static class ParameterValues { public static final String YES = "Y"; public static final String NO = "N"; } public static class Maintenance { public static final String AFTER_CLASS_DELIM = "!!"; public static final String AFTER_FIELDNAME_DELIM = "^^"; public static final String AFTER_VALUE_DELIM = "::"; } public static class ObjectCodeConstants { public static final String INACTIVE_OBJECT_LEVEL_QUESTION_ID = "InactiveObjectLevelQuestion"; } public static final String MONTH1 = "01"; public static final String MONTH2 = "02"; public static final String MONTH3 = "03"; public static final String MONTH4 = "04"; public static final String MONTH5 = "05"; public static final String MONTH6 = "06"; public static final String MONTH7 = "07"; public static final String MONTH8 = "08"; public static final String MONTH9 = "09"; public static final String MONTH10 = "10"; public static final String MONTH11 = "11"; public static final String MONTH12 = "12"; public static final String MONTH13 = "13"; public static final String PERIOD_CODE_ANNUAL_BALANCE = "AB"; public static final String PERIOD_CODE_BEGINNING_BALANCE = "BB"; public static final String PERIOD_CODE_CG_BEGINNING_BALANCE = "CB"; public static final String REQUEST_SEARCH_RESULTS = "reqSearchResults"; public static final String REQUEST_SEARCH_RESULTS_SIZE = "reqSearchResultsSize"; public static final String GL_COLLECTOR_STAGING_DIRECTORY = "collector.staging.directory"; public static final String DISBURSEMENT_VOUCHER_DOCUMENTATION_LOCATION_CODE_PROPERTY_NAME = "disbursementVoucherDocumentationLocationCode"; public static final String FUND_GROUP_CODE_PROPERTY_NAME = "code"; public static final String SUB_FUND_GROUP_CODE_PROPERTY_NAME = "subFundGroupCode"; public static final String ACCOUNT_TYPE_S3 = "S3"; public static final String RULE_CODE_R1 = "R1"; public static final String RULE_CODE_R2 = "R2"; public static final String RULE_CODE_N1 = "N1"; public static final String RULE_CODE_N2 = "N2"; public static final String RULE_CODE_C1 = "C1"; public static final String RULE_CODE_C2 = "C2"; public static final String RULE_CODE_A = "A"; public static final String TRANSACTION_DT = "TRANSACTION_DT"; public static final String UNALLOC_OBJECT_CD = "UNALLOC_OBJECT_CD"; public static final String BEG_BUD_CASH_OBJECT_CD = "BEG_BUD_CASH_OBJECT_CD"; public static final String FUND_BAL_OBJECT_CD = "FUND_BAL_OBJECT_CD"; public static final String UNIV_FISCAL_YR = "UNIV_FISCAL_YR"; public static final int DEFAULT_NUM_OF_COLUMNS = 1; public static final String EMPLOYEE_LOOKUP_ERRORS = "document.employeeLookups"; public static class BudgetConstructionConstants { public enum LockStatus { SUCCESS, BY_OTHER, NO_DOOR, OPTIMISTIC_EX, FLOCK_FOUND } public static final int maxLockRetry = 20; /* KFSConstants for the CSF Tracker */ public static final String ACTIVE_CSF_DELETE_CODE = "-"; /* KFSConstants for the budget construction flag names */ private static int NUMBER_OF_CTRL_FLAGS = 8; public final static String BUDGET_ADMINSTRATION_ACTIVE = "BAACTV"; public final static String BASE_BUDGET_UPDATES_OK = "BASEAD"; public final static String BUDGET_BATCH_SYNCHRONIZATION_OK = "BSSYNC"; public final static String CSF_UPDATES_OK = "CSFUPD"; public final static String BUDGET_CONSTRUCTION_ACTIVE = "BCACTV"; public final static String BUDGET_CONSTRUCTION_GENESIS_RUNNING = "BCGENE"; public final static String BUDGET_CONSTRUCTION_UPDATES_OK = "BCUPDT"; public final static String BUDGET_ON_LINE_SYNCHRONIZATION_OK = "PSSYNC"; /* state for current year budget construction flags after genesis */ private static HashMap<String, String> buildCurrentYear() { HashMap<String, String> mapSLF; mapSLF = new HashMap<String, String>(NUMBER_OF_CTRL_FLAGS, (float) 1.00); mapSLF.put(BUDGET_ADMINSTRATION_ACTIVE, ParameterValues.YES); mapSLF.put(BASE_BUDGET_UPDATES_OK, ParameterValues.YES); mapSLF.put(BUDGET_BATCH_SYNCHRONIZATION_OK, ParameterValues.NO); mapSLF.put(CSF_UPDATES_OK, ParameterValues.NO); mapSLF.put(BUDGET_CONSTRUCTION_ACTIVE, ParameterValues.NO); mapSLF.put(BUDGET_CONSTRUCTION_GENESIS_RUNNING, ParameterValues.NO); mapSLF.put(BUDGET_CONSTRUCTION_UPDATES_OK, ParameterValues.NO); mapSLF.put(BUDGET_ON_LINE_SYNCHRONIZATION_OK, ParameterValues.NO); return mapSLF; } public final static HashMap<String, String> CURRENT_FSCL_YR_CTRL_FLAGS = buildCurrentYear(); /* state for next year budget construction flags after genesis */ private static HashMap<String, String> buildNextYear() { HashMap<String, String> mapSLF; mapSLF = new HashMap<String, String>(NUMBER_OF_CTRL_FLAGS, (float) 1.00); mapSLF.put(BUDGET_ADMINSTRATION_ACTIVE, ParameterValues.NO); mapSLF.put(BASE_BUDGET_UPDATES_OK, ParameterValues.NO); mapSLF.put(BUDGET_BATCH_SYNCHRONIZATION_OK, ParameterValues.YES); mapSLF.put(CSF_UPDATES_OK, ParameterValues.YES); mapSLF.put(BUDGET_CONSTRUCTION_ACTIVE, ParameterValues.YES); mapSLF.put(BUDGET_CONSTRUCTION_GENESIS_RUNNING, ParameterValues.NO); mapSLF.put(BUDGET_CONSTRUCTION_UPDATES_OK, ParameterValues.NO); mapSLF.put(BUDGET_ON_LINE_SYNCHRONIZATION_OK, ParameterValues.YES); return mapSLF; } public final static HashMap<String, String> NEXT_FSCL_YR_CTRL_FLAGS_AFTER_GENESIS = buildNextYear(); /* appointment funding duration code for people NOT on leave */ public final static String NO_LEAVE_INDICATED = "NONE"; /* KFSConstants for the budget construction header */ public final static String DEFAULT_BUDGET_HEADER_LOCK_IDS = null; public final static Integer INITIAL_ORGANIZATION_LEVEL_CODE = new Integer(0); public final static String INITIAL_ORGANIZATION_LEVEL_CHART_OF_ACCOUNTS_CODE = null; public final static String INITIAL_ORGANIZATION_LEVEL_ORGANIZATION_CODE = null; /* Budget Construction document type */ public final static String BUDGET_CONSTRUCTION_DOCUMENT_TYPE = "BC"; public final static String BUDGET_CONSTRUCTION_DOCUMENT_NAME = "BudgetConstructionDocument"; public final static String BUDGET_CONSTRUCTION_DOCUMENT_DESCRIPTION = "Budget Construction"; public final static String BUDGET_CONSTRUCTION_DOCUMENT_INITIAL_STATUS = "$"; public final static String ORG_REVIEW_RULE_TEMPLATE = "KualiOrgReviewTemplate"; /* codes used in the Calculated Salary Foundation (CSF) */ public final static String VACANT_CSF_LINE = "V"; public final static String UNFUNDED_CSF_LINE = "U"; public final static String ACTIVE_CSF_LINE = "-"; public final static String VACANT_EMPLID = "VACANT"; /* * object code which stores amounts by which pending general ledger rows in budget construction are out of balance */ public final static String OBJECT_CODE_2PLG = "2PLG"; /* * initial sizes for hash maps used in genesis supposedly starting the map out with about the right amount of space makes * look-ups more efficient these numbers shouldn't need to be very precise */ public final static Integer ESTIMATED_PENDING_GENERAL_LEDGER_ROWS = 70000; public final static Integer AVERAGE_REPORTING_TREE_SIZE = 4; } public static class OperationType { public static final String READ = "read"; public static final String REPORT_ERROR = "with error"; public static final String INSERT = "insert"; public static final String UPDATE = "update"; public static final String DELETE = "delete"; public static final String SELECT = "select"; public static final String BYPASS = "bypass"; } public static class PENDING_ENTRY_APPROVED_STATUS_CODE { public static final String APPROVED = "A"; public static final String PROCESSED = "X"; } public static class TableRenderConstants { public static final String SWITCH_TO_PAGE_METHOD = "switchToPage"; public static final String SORT_METHOD = "sort"; public static final String SELECT_ALL_METHOD = "selectAll"; public static final String UNSELECT_ALL_METHOD = "unselectAll"; public static final String PREVIOUSLY_SORTED_COLUMN_INDEX_PARAM = "previouslySortedColumnIndex"; public static final String VIEWED_PAGE_NUMBER = "viewedPageNumber"; } public static final String PCDO_FILE_TYPE_INDENTIFIER = "procurementCardInputFileType"; public static final String COLLECTOR_FILE_TYPE_INDENTIFIER = "collectorInputFileType"; public static final String ENTERPRISE_FEEDER_FILE_SET_TYPE_INDENTIFIER = "enterpriseFeederFileSetType"; // next 3 variables for the enterprise feeder batch upload public static final String DATA_FILE_TYPE = "DATA"; public static final String RECON_FILE_TYPE = "RECON"; public static final class WorkflowConstants { public static final String GET_GENERIC_ACCOUNTS_PREFIX = "//routingInfo/"+RoutingData.class.getName()+"/routingTypes[string='"; public static final String GET_GENERIC_ACCOUNTS_SUFFIX = "']/following-sibling::routingSet/"+ RoutingAccount.class.getName(); public static final String GET_GENERIC_ORGS_PREFIX = "//routingInfo/"+RoutingData.class.getName()+"/routingTypes[string='"; public static final String GET_GENERIC_ORGS_SUFFIX = "']/following-sibling::routingSet/"+OrgReviewRoutingData.class.getName(); public static final String GET_GENERIC_CHART= "./routingChart"; public static final String GET_GENERIC_ACCOUNT = "./routingAccount"; public static final String GET_GENERIC_OVERRIDE_CD = "./routingOverrideCode"; public static final String GET_GENERIC_ORG = "./routingOrg"; public static final String GET_GENERIC_ACCOUNT_CHART = "//routingSet/" + RoutingAccount.class.getName() + "/routingChart"; public static final String GET_GENERIC_ACCOUNT_ACCOUNT = "//routingSet/" + RoutingAccount.class.getName() + "/routingAccount"; public static final String GET_GENERIC_ORG_CHART = "//routingSet/" + OrgReviewRoutingData.class.getName() + "/routingChart"; public static final String GET_GENERIC_ORG_ORG = "//routingSet/" + OrgReviewRoutingData.class.getName() + "/routingOrg"; public static final String GET_GENERIC_ACCOUNT_REPORT_PREFIX = "<generatedContent><report_for_routing_purposes><routingSet><" + RoutingAccount.class.getName() + ">"; public static final String GET_GENERIC_ACCOUNT_REPORT_SUFFIX = "</" + RoutingAccount.class.getName() +"></routingSet></report_for_routing_purposes></generatedContent>"; public static final String GET_GENERIC_ORG_REPORT_PREFIX = "<generatedContent><report_for_routing_purposes><routingSet><" + OrgReviewRoutingData.class.getName() + ">"; public static final String GET_GENERIC_ORG_REPORT_SUFFIX = "</" + OrgReviewRoutingData.class.getName() + "></routingSet></report_for_routing_purposes></generatedContent>"; } /** * The base implementation of {@link org.kuali.module.gl.util.EnterpriseFeederStatusBase} uses strings contained within * ApplicationResources.properties to store the human-readable descriptions of each status object. The fully qualified class * name is appended to the end of this key to generate the true key. For example, * gl.EnterpriseFeeder.StatusDescriptionPrefix.org.kuali.module.gl.util.FileReconBadLoadAbortedStatus */ public static final String ENTERPRISE_FEEDER_STATUS_DESCRIPTION_PREFIX = "gl.EnterpriseFeeder.StatusDescription."; public static final String BATCH_STEP_RUNNER_JOB_NAME = "stepRunByBatchStepRunner"; // Some static method calls below that could be done in static variables instead but isn't safe to do during class loading // w/SpringContext. private static String DASH_FINANCIAL_OBJECT_CODE = null; public static String getDashFinancialObjectCode() { if (DASH_FINANCIAL_OBJECT_CODE == null) { DASH_FINANCIAL_OBJECT_CODE = StringUtils.rightPad("", SpringContext.getBean(DataDictionaryService.class).getAttributeMaxLength(OriginEntryFull.class, KFSPropertyConstants.FINANCIAL_OBJECT_CODE), '-'); } return DASH_FINANCIAL_OBJECT_CODE; } private static String DASH_FINANCIAL_SUB_OBJECT_CODE = null; public static String getDashFinancialSubObjectCode() { if (DASH_FINANCIAL_SUB_OBJECT_CODE == null) { DASH_FINANCIAL_SUB_OBJECT_CODE = StringUtils.rightPad("", SpringContext.getBean(DataDictionaryService.class).getAttributeMaxLength(OriginEntryFull.class, KFSPropertyConstants.FINANCIAL_SUB_OBJECT_CODE), '-'); } return DASH_FINANCIAL_SUB_OBJECT_CODE; } private static String DASH_SUB_ACCOUNT_NUMBER = null; public static String getDashSubAccountNumber() { if (DASH_SUB_ACCOUNT_NUMBER == null) { DASH_SUB_ACCOUNT_NUMBER = StringUtils.rightPad("", SpringContext.getBean(DataDictionaryService.class).getAttributeMaxLength(OriginEntryFull.class, KFSPropertyConstants.SUB_ACCOUNT_NUMBER), '-'); } return DASH_SUB_ACCOUNT_NUMBER; } private static String SPACE_SUB_ACCOUNT_NUMBER = null; public static String getSpaceSubAccountNumber() { if (SPACE_SUB_ACCOUNT_NUMBER == null) { SPACE_SUB_ACCOUNT_NUMBER = StringUtils.rightPad("", SpringContext.getBean(DataDictionaryService.class).getAttributeMaxLength(OriginEntryFull.class, KFSPropertyConstants.SUB_ACCOUNT_NUMBER), ' '); } return SPACE_SUB_ACCOUNT_NUMBER; } private static String DASH_PROJECT_CODE = null; public static String getDashProjectCode() { if (DASH_PROJECT_CODE == null) { DASH_PROJECT_CODE = StringUtils.rightPad("", SpringContext.getBean(DataDictionaryService.class).getAttributeMaxLength(OriginEntryFull.class, KFSPropertyConstants.PROJECT_CODE), '-'); } return DASH_PROJECT_CODE; } //AR TAB ERROR KEYS //Customer Invoice Document public static final String CUSTOMER_INVOICE_DOCUMENT_ORGANIZATION_ERRORS = "document.billByChartOfAccountCode,document.billedByOrganizationCode"; public static final String CUSTOMER_INVOICE_DOCUMENT_GENERAL_ERRORS = "document.accountsReceivableDocumentHeader.customerNumber,document.invoice*,document.billingDate,document.invoiceDueDate"; public static final String CUSTOMER_INVOICE_DOCUMENT_ADDRESS = "document.customerBillToAddressIdentifier,document.customerShipToAddressIdentifier"; public static final String CUSTOMER_INVOICE_DOCUMENT_RECEIVABLE_ACCOUNTING_LINE = "document.payment*"; public static final String CUSTOMER_INVOICE_DETAIL_ERRORS = "newCustomerInvoiceDetail*,document.sourceAccountingLine*"; //Cash Control Document public static final String CASH_CONTROL_DOCUMENT_ERRORS = "document.accountsReceivableDocumentHeader.processingChartOfAccountCode,document.referenceFinancialDocumentNumber,document.customerPaymentMediumCode,document.organizationCode"; public static final String CASH_CONTROL_DETAILS_ERRORS = "newCashControl*,document.cashControlDetail*"; public static final class ReportGeneration{ public final static String PARAMETER_NAME_SUBREPORT_DIR = "SUBREPORT_DIR"; public final static String PARAMETER_NAME_SUBREPORT_TEMPLATE_NAME = "SUBREPORT_TEMPLATE_NAMES"; public final static String DESIGN_FILE_EXTENSION = ".jrxml"; public final static String JASPER_REPORT_EXTENSION = ".jasper"; public final static String PDF_FILE_EXTENSION = ".pdf"; public final static String PDF_MIME_TYPE = "application/pdf"; } }
change "bypass" into "bypassed"
work/src/org/kuali/kfs/sys/KFSConstants.java
change "bypass" into "bypassed"
<ide><path>ork/src/org/kuali/kfs/sys/KFSConstants.java <ide> public static final String UPDATE = "update"; <ide> public static final String DELETE = "delete"; <ide> public static final String SELECT = "select"; <del> public static final String BYPASS = "bypass"; <add> public static final String BYPASS = "bypassed"; <ide> } <ide> <ide> public static class PENDING_ENTRY_APPROVED_STATUS_CODE {
JavaScript
mit
70b5ac3917089d64235e930e1a6c5d100ab61a35
0
midler/configs
'use strict'; var gulp = require('gulp'); // var svgmin = require('gulp-svgmin'); var imgmin = require('gulp-imagemin'); // var hb = require('gulp-hb'); var less = require('gulp-less'); var pleeease = require('gulp-pleeease'); var rename = require('gulp-rename'); var plumber = require('gulp-plumber'); var browserSync = require('browser-sync'); var reload = browserSync.reload; var runSequence = require('run-sequence'); var stylus = require('gulp-stylus'); var flatten = require('gulp-flatten'); var svgconvert = require('gulp-svg2png'); /*===================Paths===================== */ //base path var bpath = { src: './src/', dest: './dest/' }; var path = { images: { src: bpath.src + 'images/', dest: bpath.dest + 'images/', srcopt: bpath.src + 'images/opt/' }, scripts: { src: bpath.src + 'js/', dest: bpath.dest + 'js/', destm: bpath.dest + 'js/min/' }, styles: { src: bpath.src + 'stylus/', dest: bpath.dest + 'css/' }, html: { src: bpath.src + 'html/', dest: bpath.dest }, fonts: { src: bpath.src + 'fonts', dest: bpath.dest + 'fonts/' } }; var pathImagesFormat = { jpeg: path.images.src + 'jpeg', png: path.images.src + 'png', svg: path.images.src + 'svg' }; /*===================Plug-In===================== */ // gulp.task('svgmin', function () { // return gulp.src(pathImagesFormat.svg) // .pipe(plumber()) // .pipe(svgmin()) // .pipe(gulp.dest(bpath.dest + 'images/')); // }); gulp.task('imgmin', ['svgconvert'], function () { return gulp.src(path.images.src + '/**/*.{jpg,jpeg,png,gif}') .pipe(plumber()) .pipe(imgmin({ progressive: true, interlaced: true, optimizationLevel: 3 })) .pipe(flatten()) .pipe(gulp.dest(path.images.dest)); }); gulp.task('svgconvert', function () { console.log(pathImagesFormat.svg + '/*.svg'); return gulp.src(pathImagesFormat.svg + '/*.svg') .pipe(plumber()) .pipe(svgconvert()) .pipe(gulp.dest(pathImagesFormat.png)); }); // gulp.task('hbs', function () { // return gulp // .src(path.hbs.src + '/*') // .pipe(plumber()) // .pipe(hb()) // .pipe(gulp.dest(bpath.dest)); // }); gulp.task('move-html', function () { return gulp.src(path.html.src + '/**/*.html') .pipe(plumber()) .pipe(gulp.dest(path.html.dest)) .pipe(reload({ stream: true })); }); gulp.task('move-fonts', function () { return gulp.src(path.fonts.src + '/**/*.*') .pipe(plumber()) .pipe(gulp.dest(path.fonts.dest)); }); gulp.task('less', function () { return gulp .src(path.styles.src + '**/*.less') .pipe(plumber()) .pipe(less()) .pipe(pleeease()) // .pipe(rename({ // suffix: '.min', // extname: '.css' // })) .pipe(gulp.dest(bpath.dest + '/css')); }); gulp.task('stylus', function () { return gulp .src(path.styles.src + '/style.styl') .pipe(plumber()) .pipe(stylus({ "include css": true })) .pipe(gulp.dest(bpath.dest + '/css')) .pipe(reload({ stream: true })); }); gulp.task('browser-sync', function () { browserSync({ server: { baseDir: bpath.dest }, logLevel: "info", open: false, // ghostMode: { // clicks: true, // location: true, // forms: true, // scroll: false // } ghostMode: false, notify: false, reloadDelay: 500 }); }); /* ===================== Main Tasks ========================== */ gulp.task('default', function () { console.log('Mida\'s building system'); }); gulp.task('server', ['imgmin', 'move-fonts', 'move-html', 'stylus', 'browser-sync'], function () { gulp.watch(path.styles.src + '/**/*.styl', ['stylus']); gulp.watch(path.html.src + "/*.html", ['move-html']); }); // gulp.task('server-nob', ['browser-sync']);
Gulpfile.js
'use strict'; var gulp = require('gulp'); // var svgmin = require('gulp-svgmin'); // var imgmin = require('gulp-imagemin'); // var hb = require('gulp-hb'); var less = require('gulp-less'); var pleeease = require('gulp-pleeease'); var rename = require('gulp-rename'); var plumber = require('gulp-plumber'); var browserSync = require('browser-sync'); var runSequence = require('run-sequence'); /*===================Paths===================== */ //base path var bpath = { src: './src/', dest: './dest/' }; var path = { images: { src: bpath.src + 'images/', dest: bpath.dest + 'images/', srcopt: bpath.src + 'images/opt/' }, scripts: { src: bpath.src + 'js/', dest: bpath.dest + 'js/', destm: bpath.dest + 'js/min/' }, styles: { src: bpath.src + 'less/', dest: bpath.dest + 'css/' }, html: { src: bpath.src + 'html/', dest: bpath.dest } }; var pathImagesFormat = { jpeg: path.images.src + 'jpeg', png: path.images.src + 'png', svg: path.images.src + 'svg' }; /*===================Plug-In===================== */ // gulp.task('svgmin', function () { // return gulp.src(pathImagesFormat.svg) // .pipe(plumber()) // .pipe(svgmin()) // .pipe(gulp.dest(bpath.dest + 'images/')); // }); // gulp.task('imgmin', function () { // return gulp.src(path.images.src) // .pipe(plumber()) // .pipe(imgmin) // .pipe(gulp.dest(path.images.srcopt)); // }); // gulp.task('hbs', function () { // return gulp // .src(path.hbs.src + '/*') // .pipe(plumber()) // .pipe(hb()) // .pipe(gulp.dest(bpath.dest)); // }); gulp.task('move-html', function () { return gulp.src(path.html.src + '/**/*.html') .pipe(plumber()) .pipe(gulp.dest(path.html.dest)); }); gulp.task('less', function () { return gulp .src(path.styles.src + '**/*.less') .pipe(plumber()) .pipe(less()) .pipe(pleeease()) .pipe(rename({ suffix: '.min', extname: '.css' })) .pipe(gulp.dest(bpath.dest + '/css')); }); gulp.task('browser-sync', function () { browserSync.init(null, { server: { baseDir: bpath.dest }, logLevel: "info", open: false, // ghostMode: { // clicks: true, // location: true, // forms: true, // scroll: false // } ghostMode: false, notify: false, reloadDelay: 500 }); }); /* ===================== Main Tasks ========================== */ gulp.task('default', function () { console.log('Mida\'s building system'); }); gulp.task('server', ['move-html', 'less', 'browser-sync'], function () { gulp.watch(path.styles.src, ['less']); }); // gulp.task('server-nob', ['browser-sync']);
Image optimization, fonts replace, stylus
Gulpfile.js
Image optimization, fonts replace, stylus
<ide><path>ulpfile.js <ide> 'use strict'; <del> <ide> var gulp = require('gulp'); <ide> // var svgmin = require('gulp-svgmin'); <del>// var imgmin = require('gulp-imagemin'); <add>var imgmin = require('gulp-imagemin'); <ide> // var hb = require('gulp-hb'); <ide> var less = require('gulp-less'); <ide> var pleeease = require('gulp-pleeease'); <ide> var rename = require('gulp-rename'); <ide> var plumber = require('gulp-plumber'); <ide> var browserSync = require('browser-sync'); <add>var reload = browserSync.reload; <ide> var runSequence = require('run-sequence'); <del> <add>var stylus = require('gulp-stylus'); <add>var flatten = require('gulp-flatten'); <add>var svgconvert = require('gulp-svg2png'); <ide> <ide> <ide> <ide> destm: bpath.dest + 'js/min/' <ide> }, <ide> styles: { <del> src: bpath.src + 'less/', <add> src: bpath.src + 'stylus/', <ide> dest: bpath.dest + 'css/' <ide> }, <ide> html: { <ide> src: bpath.src + 'html/', <ide> dest: bpath.dest <add> }, <add> fonts: { <add> src: bpath.src + 'fonts', <add> dest: bpath.dest + 'fonts/' <ide> } <ide> <ide> }; <ide> // .pipe(gulp.dest(bpath.dest + 'images/')); <ide> // }); <ide> <del>// gulp.task('imgmin', function () { <del>// return gulp.src(path.images.src) <del>// .pipe(plumber()) <del>// .pipe(imgmin) <del>// .pipe(gulp.dest(path.images.srcopt)); <del>// }); <add>gulp.task('imgmin', ['svgconvert'], <add> function () { <add> return gulp.src(path.images.src + '/**/*.{jpg,jpeg,png,gif}') <add> .pipe(plumber()) <add> .pipe(imgmin({ <add> progressive: true, <add> interlaced: true, <add> optimizationLevel: 3 <add> })) <add> .pipe(flatten()) <add> .pipe(gulp.dest(path.images.dest)); <add> }); <ide> <add> <add>gulp.task('svgconvert', function () { <add> console.log(pathImagesFormat.svg + '/*.svg'); <add> return gulp.src(pathImagesFormat.svg + '/*.svg') <add> .pipe(plumber()) <add> .pipe(svgconvert()) <add> .pipe(gulp.dest(pathImagesFormat.png)); <add>}); <ide> <ide> <ide> <ide> gulp.task('move-html', function () { <ide> return gulp.src(path.html.src + '/**/*.html') <ide> .pipe(plumber()) <del> .pipe(gulp.dest(path.html.dest)); <add> .pipe(gulp.dest(path.html.dest)) <add> .pipe(reload({ <add> stream: true <add> })); <add>}); <add> <add>gulp.task('move-fonts', function () { <add> return gulp.src(path.fonts.src + '/**/*.*') <add> .pipe(plumber()) <add> .pipe(gulp.dest(path.fonts.dest)); <ide> }); <ide> <ide> <ide> .pipe(plumber()) <ide> .pipe(less()) <ide> .pipe(pleeease()) <del> .pipe(rename({ <del> suffix: '.min', <del> extname: '.css' <del> })) <add> // .pipe(rename({ <add> // suffix: '.min', <add> // extname: '.css' <add> // })) <ide> .pipe(gulp.dest(bpath.dest + '/css')); <ide> }); <ide> <ide> <add>gulp.task('stylus', function () { <add> return gulp <add> .src(path.styles.src + '/style.styl') <add> .pipe(plumber()) <add> .pipe(stylus({ <add> "include css": true <add> })) <add> .pipe(gulp.dest(bpath.dest + '/css')) <add> .pipe(reload({ <add> stream: true <add> })); <add>}); <add> <ide> <ide> gulp.task('browser-sync', function () { <del> browserSync.init(null, { <add> browserSync({ <ide> server: { <ide> baseDir: bpath.dest <ide> }, <ide> }); <ide> <ide> <del>gulp.task('server', ['move-html', 'less', 'browser-sync'], function () { <del> gulp.watch(path.styles.src, ['less']); <add>gulp.task('server', ['imgmin', 'move-fonts', 'move-html', 'stylus', 'browser-sync'], function () { <add> gulp.watch(path.styles.src + '/**/*.styl', ['stylus']); <add> gulp.watch(path.html.src + "/*.html", ['move-html']); <ide> }); <ide> <ide>
JavaScript
agpl-3.0
84b970eb34a65591b1cc3adf1c904456513e5bb7
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
5ee6f5ae-2e65-11e5-9284-b827eb9e62be
helloWorld.js
5ee182b8-2e65-11e5-9284-b827eb9e62be
5ee6f5ae-2e65-11e5-9284-b827eb9e62be
helloWorld.js
5ee6f5ae-2e65-11e5-9284-b827eb9e62be
<ide><path>elloWorld.js <del>5ee182b8-2e65-11e5-9284-b827eb9e62be <add>5ee6f5ae-2e65-11e5-9284-b827eb9e62be
JavaScript
mit
e705c4df03c79eff9e0281bce1719e0a42306b41
0
iosonofabio/hivwholeweb,iosonofabio/hivwholeweb,iosonofabio/hivwholeweb,iosonofabio/hivwholeweb
function emptyTree(id, keepData) { var svg = d3.select('#'+id); svg.selectAll("*").remove(); if ((typeof(keepData) == "undefined") | (!keepData)) svg.datum(null); } /* * Plot phylogenetic trees with radial or rectangular representation * Author: Fabio Zanini */ // NOTE: this function is ready for callbacks, they have to set data = {chartType: <chartType>} function updateTree(id, data) { if (typeof(data)==='undefined') data = {}; var svg = d3.select('#'+id), divWidth = $('#'+id).parent().width(); // if this function is called with some useful data, bind it to the DOM if ("tree" in data) svg.datum(data) var chart = treeChart().svgWidth(0.9 * divWidth); // Figure out settings from the DOM, e.g. coloring and chart type if ($("#switchRectangular").hasClass("active")) { chart.chartType("rectangular"); chart.svgHeight(15 * getNumberTerminals(svg.datum().tree, 0)); } else chart.svgHeight(0.9 * divWidth); if ($("#switchColorLinkDate").hasClass("active")) chart.colorLinkType("date"); else if ($("#switchColorLinkSubtype").hasClass("active")) chart.colorLinkType("subtype"); else if ($("#switchColorLinkPatient").hasClass("active")) chart.colorLinkType("patient"); // Leaf labels defaults to false for minor variant trees if ((data.leafLabels === false) || ((typeof(data.leafLabels) == "undefined") && (svg.datum().region.indexOf("minor") != -1))) chart.leafLabels(false); if (data.optimizeSpace === true) chart.optimizeSpace(true); if (data.tipMuts === false) chart.tipMuts(false); svg.call(chart); function getNumberTerminals(n, number) { if (n.children) for(var i=0; i < n.children.length; i++) number += getNumberTerminals(n.children[i], 0); else number += 1; return number; } } /* tree chart closure as of Mark Bostock: http://bost.ocks.org/mike/chart/ */ function treeChart() { var svgWidth = 400, svgHeight = 400, margin = {top: 5, bottom: 5, left: 5, right: 5}, width = svgWidth - margin.left - margin.right, height = svgHeight - margin.top - margin.bottom, chartType = "radial", colorLinkType = "black", leafLabels = true, optimizeSpace = false, tipMuts = true; // TREE CHART FUNCTION function chart(selection) { selection.each(function (data) { var colors = ["#5097BA", "#60AA9E", "#75B681", "#8EBC66", "#AABD52", "#C4B945", "#D9AD3D", "#E59637", "#E67030", "#DF4327"]; var colorMap = d3.scale.linear() .interpolate(d3.interpolateRgb) .domain([0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]) .range(colors); var tree = data.tree, pname = data.pname, region = data.region; // minor haplotype trees require more margin because they have balls attached if (region.indexOf("minor") != 1) { margin.top += 5; margin.bottom += 5; height -= 10; margin.left += 5; margin.right += 5; width -= 10; } // Create outer chart (SVG) and make sure there are no other ones var svg = d3.select(this); svg.selectAll("*").remove(); // Set the outer dimensions. //svg.attr("width", width + margin.left + margin.right) // .attr("height", height + margin.top + margin.bottom) //responsive SVG needs these 2 attributes and no width and height attr svg.attr("preserveAspectRatio", "xMinYMin meet") .attr("viewBox", "0 0 " + (width + margin.left + margin.right) + " " + (height + margin.top + margin.bottom)); // calculate various properties of all nodes setDepths(tree, 0); setNTerminals(tree); setDSI(tree); setPatientInternal(tree); var depth = Math.max(1e-7, getMaxTree(tree, function(d) { return d.depthScaled; })), dsiMax = getMaxTree(tree, function(d) { return d.DSI; }); // set link coloring function if (colorLinkType == "date") var colorLinkFunc = function(d) { var dsi = d.target.DSI; if (dsi != "undefined") return colorMap(dsi / dsiMax); else return "grey"; } else if (colorLinkType == "subtype") var colorLinkFunc = function(d) { var n = d.target; // NOTE: colors from colorbrewer dark2 if (n.subtype === 'B') return "#7570b3"; else if (n.subtype === 'C') return "#d95f02"; else if (n.subtype === 'AE') return "#1b9e77" else return "grey"; } else if (colorLinkType == "patient") var colorLinkFunc = function(d) { var cscale = d3.scale.category20() .domain(['p1','p2','p3','p4','p5','p6','p7','p8','p9','p10','p11']); if (d.target.patient != "undefined") return cscale(d.target.patient); else if (d.target.name != "undefined") return "black"; else return "grey"; } else var colorLinkFunc = function(d) { return "black"; } // tooltip var tip = d3.tip() .attr('class', 'd3-tip') .html(tooltipFunc); // prepare cluster representation var cluster = d3.layout.cluster() .sort(null) .value(function(d) { return d.branch_length; }) .separation(function(a, b) { return 1; }); // plot the chart if (chartType == "radial") makeRadial(); else makeRectangular(); // RADIAL CHART function makeRadial() { // Create inner chart, centered in the center of the circle var maxAngle = 360, r = width / 2, treeCenter = {'cx': r, 'cy': r}; // if the leaf labels are not shown, center the tree differently var rInternal = r; if (leafLabels === true) rInternal -= 170; // adjust the bar to calibration var treeScale = 0.9 * rInternal / depth; // set up the d3 cluster cluster.size([maxAngle, 1]); var nodes = cluster.nodes(tree); // add position attributes to the tree: // - angle // - radius from the coordinate center (treeCenter) // - x coordinate from the treeCenter // - y coordinate from the treeCenter nodes.map(function(n) { n.radius = n.depthScaled * treeScale; n.angle = n.x; setProjectRadial(n); }); // if requested, optimize space by resetting the viewbox if (optimizeSpace === true) { // get max and min x and y var xMax = d3.max(nodes, function(d){ return d.x; }), xMin = d3.min(nodes, function(d){ return d.x; }), yMax = d3.max(nodes, function(d){ return d.y; }), yMin = d3.min(nodes, function(d){ return d.y; }); svg.attr("viewBox", ((r + xMin - 20) + " " + (r + yMin - 20) + " " + (xMax - xMin + 40 + margin.left + margin.right) + " " + (yMax - yMin + 40 + margin.top + margin.bottom)) ); } // SVG group to render tree in var vis = svg.append("g") .attr("transform", ("translate(" + (margin.left + treeCenter.cx) + "," + (margin.top + treeCenter.cy) + ")") ); //// Test dot in the treeCenter //svg.append("circle") // .attr("cx", margin.left + r) // .attr("cy", margin.top + r) // .attr("r", 10) // .style("fill", "red"); //svg.append("rect") // .attr("x", margin.left) // .attr("y", margin.top) // .attr("width", 2 * r) // .attr("height", 2 * r) // .attr("fill", "none") // .attr("stroke", "red") // .attr("stroke-width", 3); // activate tip on visualized svg vis.call(tip); // links var link = vis.selectAll("path.link") .data(cluster.links(nodes)) .enter() .append("path") .attr("class", "link") .attr("d", stepRadial) .attr("stroke", colorLinkFunc) .on("mouseover", moverLinksRadial) .on("mouseout", moutLinksRadial); // balls proportional to frequency for minor variants if (region.indexOf("minor") != -1) { link.filter(function(d) { return d.target.frequency != "undefined" }) .each(plotBallsRadial); } var treetips = vis.selectAll("treetip") .data(cluster.links(nodes)) .enter() .append("circle") .attr("class", "treetip") .attr("cx", function (d) {return d.target.x;}) .attr("cy", function (d) {return d.target.y;}) .attr("r", 5) .attr("stroke", colorLinkFunc) .on("mouseover", moverLinksRadial) .on("mouseout", moutLinksRadial); // line connecting the leaves to their labels if (leafLabels === true) { var label = vis.selectAll(".anno") .data(nodes.filter(function(d) { return d.x !== undefined && !d.children; })) .enter() .append("g") .attr("class", "anno"); label.append("path") .attr("class", "annoline") .attr("d", function(d) { return stepAnnoRadial(d, rInternal); }); // leaf labels label.append("text") .attr("dy", ".31em") .attr("class", "annotext") .attr("text-anchor", function(d) { return d.angle < 180 ? "start" : "end"; }) .attr("transform", function(d) { return ("rotate(" + (d.angle - 90) + ")translate(" + (r - 170 + 8) + ")rotate(" + (d.angle < 180 ? 0 : 180) + ")"); }) .text(leafLabelFunc) .on("mouseover", moverRadial) .on("mouseout", moutRadial); } // scale bar if ((leafLabels === true) & (depth > 1e-6)) { var barLengthData = (30.0 / treeScale).toPrecision(1), barLength = treeScale * barLengthData, barLengthText = String(barLengthData); var bar = vis.append("g") .attr("class", "lengthbar") .attr("transform", "translate(" + (r - 50) + "," + (r - 20) + ")"); bar.selectAll(".lengthbar") .data([[-barLength, 0, 0, 0], [-barLength, -barLength, -7, 7], [0, 0, -7, 7]]) .enter() .append("svg:line") .attr("x1", function(d) { return d[0]; }) .attr("x2", function(d) { return d[1]; }) .attr("y1", function(d) { return d[2]; }) .attr("y2", function(d) { return d[3]; }); bar.append("text") .attr("class", "lengthbartext") .attr("x", -barLength / 2) .attr("y", 25) .text(barLengthText) .attr("text-anchor", "middle"); } function moverLinksRadial(d) { moverRadial(d.target); } function moutLinksRadial(d) { moutRadial(d.target); } function moverRadial(d) { var t = projectRadial(d); vis.append("circle") .attr("class", "highlight") .attr("cx", t.x) .attr("cy", t.y) .attr("r", 8) tip.show(d); } function moutRadial(d) { tip.hide(d); vis.selectAll(".highlight") .remove(); } function projectRadial(d) { var r = d.radius, a = (d.angle - 90) / 180 * Math.PI; return {'x': r * Math.cos(a), 'y': r * Math.sin(a)}; } function setProjectRadial(d) { var pr = projectRadial(d); d.x = pr.x; d.y = pr.y; } function stepRadial(d) { var s = d.source, m = projectRadial({angle: d.target.angle, radius: d.source.radius}), t = d.target, r = d.source.radius, sweep = d.target.angle > d.source.angle ? 1 : 0; return ( "M" + s.x + "," + s.y + "A" + r + "," + r + " 0 0," + sweep + " " + m.x + "," + m.y + "L" + t.x + "," + t.y); } function stepAnnoRadial(d, r) { var s = projectRadial({angle: d.angle, radius: d.radius + 5}), t = projectRadial({angle: d.angle, radius: r}); return ( "M" + s.x + "," + s.y + "L" + t.x + "," + t.y); } function plotBallsRadial(d, i) { var freq = d.target.frequency, r = 2 + (18 - 5) * ((Math.log(freq) / Math.LN10) + 2.0) / 2.0; vis.append("circle") .datum(d.target) .attr("class", "leaf") .attr("r", r) .attr("cx", d.target.x) .attr("cy", d.target.y) .attr("fill", colorLinkFunc(d, i)) .attr("stroke", d3.rgb(colorLinkFunc(d, i)).darker()) .attr("fill-opacity", 0.7) .on("mouseover", moverRadial) .on("mouseout", moutRadial); } } // RECTANGULAR CHART function makeRectangular() { var vis = svg.append("g") .attr("transform", "translate(" + (margin.left) + "," + (margin.top) + ")"); // activate tip on visualized svg vis.call(tip); // set up d3 cluster // note: at present, x and y are swapped to keep consistency with the radial layout var treeHeight = height, treeWidth = 0.93 * width; cluster.size([treeHeight, treeWidth]); // adjust the bar to calibration var treeScale = cluster.size()[1] / depth; if ((leafLabels === true) & (depth > 1e-6)) { var barLengthData = (30.0 / treeScale).toPrecision(1), barLength = treeScale * barLengthData; // set the bar text, should be the same as the data except in degenerate trees var barLengthText = String(barLengthData); // scale bar var bar = vis.append("g") .attr("transform", "translate(" + 50 + "," + (height - 20) + ")"); bar.selectAll(".lengthbar") .data([[-barLength, 0, 0, 0], [-barLength, -barLength, -7, 7], [0, 0, -7, 7]]) .enter() .append("svg:line") .attr("class","lengthbar") .attr("x1", function(d) { return d[0]; }) .attr("x2", function(d) { return d[1]; }) .attr("y1", function(d) { return d[2]; }) .attr("y2", function(d) { return d[3]; }); bar.append("text") .attr("x", -barLength / 2) .attr("y", 25) .text(barLengthText) .attr("text-anchor", "middle"); } var nodes = cluster.nodes(tree); // add scaled depths (in pixels) to the tree nodes.map(function(n) {n.y = n.depthScaled * treeScale; }); // links var link = vis.selectAll("path.link") .data(cluster.links(nodes)) .enter() .append("path") .attr("class", "link") .attr("d", stepRectangular) // .attr("fill", "none") .attr("stroke", colorLinkFunc) .on("mouseover", moverLinksRectangular) .on("mouseout", moutLinksRectangular); // balls proportional to frequency for minor variants if (region.indexOf("minor") != -1) { link.filter(function(d) { return d.target.frequency != "undefined" }) .each(plotBallsRect); } var treetips = vis.selectAll("treetip") .data(cluster.links(nodes)) .enter() .append("circle") .attr("class", "treetip") .attr("cx", function (d) {return d.target.y;}) .attr("cy", function (d) {return d.target.x;}) .attr("r", 5) .attr("stroke", colorLinkFunc) .on("mouseover", moverLinksRectangular) .on("mouseout", moutLinksRectangular); // line connecting the leaves to their labels if (leafLabels === true) { var label = vis.selectAll(".anno") .data(nodes.filter(function(d) { return d.x !== undefined && !d.children; })) .enter() .append("g") .attr("class", "anno"); label.append("path") .attr("class", "annoline") .attr("d", function(d) { return stepAnnoRectangular(d); }) // leaf labels label.append("text") .attr("class", "annotext") .attr("dy", ".31em") .attr("text-anchor", "end") .attr("transform", function(d) { return "translate(" + width + "," + d.x + ")"; }) .text(leafLabelFunc) .on("mouseover", moverRectangular) .on("mouseout", moutRectangular); } function moverLinksRectangular(d) { moverRectangular(d.target); } function moutLinksRectangular(d) { moutRectangular(d.target); } function moverRectangular(d) { vis.append("circle") .attr("class", "highlight") .attr("cx", d.y) .attr("cy", d.x) .attr("r", 8) .transition() .duration(400) tip.show(d); } function moutRectangular(d) { tip.hide(d); vis.selectAll(".highlight") .remove(); } function stepRectangular(d) { return ( "M" + d.source.y + "," + d.source.x + "V" + d.target.x + "H" + d.target.y ); } function stepAnnoRectangular(d) { // FIXME: the depth is a trick, we should allocate space // for the labels and subtract, but that depends on fontsize return ( "M" + d.y + "," + d.x + "H" + (10 + depth * treeScale) ); } function plotBallsRect(d, i) { var freq = d.target.frequency, r = 2 + (18 - 5) * ((Math.log(freq) / Math.LN10) + 2.0) / 2.0; vis.append("circle") .attr("class", "leaf") .attr("r", r) .attr("cx", d.target.y) .attr("cy", d.target.x) .attr("fill", colorLinkFunc(d, i)) .attr("stroke", d3.rgb(colorLinkFunc(d, i)).darker()) .on("mouseover", function() { return moverLinksRectangular(d)}) .on("mouseout", function() { return moutLinksRectangular(d)}); } } function leafLabelFunc(d) { if (String(region).indexOf('minor') != -1) { var freqLabel = String((d.frequency * 100).toFixed(0)) + "%", timeLabel = String(Math.floor(d.DSI / 30.5)) + " m", label = freqLabel + ", " + timeLabel; return label; } else { var name = String(d.name); return name.split('_').join(" "); } } }); // NOTE: node.depth is a d3 construct to get the integer depth, we use depthScaled function setDepths(n, parentDepth) { n.depthScaled = parentDepth + n.branch_length; if (n.children) for (var i=0; i < n.children.length; i++) setDepths(n.children[i], n.depthScaled); } function getMaxTree(n, accessor) { if (n.children) return d3.max(n.children, function (d) { return getMaxTree(d, accessor); }); else return accessor(n); } function setNTerminals(n) { if (n.children) { n.children.map(setNTerminals); n.nTerminals = d3.sum(n.children, function(d) { return d.nTerminals; }); } else n.nTerminals = 1; } // Get weighted mean of DSIs of terminal nodes function setDSI(n) { if (n.children) { n.children.map(setDSI); var dsicum = d3.sum(n.children, function (d) { var dsi = d.DSI; if (dsi == "undefined") return 0; return dsi * d.nTerminals; }); var childrencum = d3.sum(n.children, function(d) { if (d.DSI == "undefined") return 0; return d.nTerminals; }); if (childrencum == 0) n.DSI = "undefined"; else n.DSI = dsicum / childrencum; } } // Set the patient designation of internal nodes to that of its children // iff all agree. otherwise, set to undefined function setPatientInternal(n) { if (n.children) { n.children.map(setPatientInternal); var patient = n.children.map(function (d) {return d.patient}); if (patient.every(function (d){return d==patient[0]})){ n.patient=patient[0]; }else{ n.patient="undefined"; } } } // Tooltip function, used for both edges and nodes function tooltipFunc(d) { // get the child node anyway if (d.hasOwnProperty('target')) d = d.target; var msg = ""; if (!(d.children)) { var pname = String(d.name).split('_')[0]; if (pname[0] == "p") msg = msg + "Patient: " + pname + "</br>"; else if (pname != "undefined") { if (pname == "LAI-III") msg = msg + "Name: " + pname + " (HXB2)</br>"; else msg = msg + "Name: " + pname + "</br>"; } if (isNumeric(d.CD4)) msg = msg + "CD4+ cell count [cells/ml]: " + d.CD4 + "</br>"; if (isNumeric(d.VL)) msg = msg + "Viral load [virions/ml]: " + d.VL + "</br>"; } if ((typeof(d.subtype) != "undefined") && (d.subtype !== "undefined")) { msg = msg + "Subtype: " + d.subtype + "</br>"; } if (isNumeric(d.DSI)) msg = msg + "Day since infection: " + d.DSI.toFixed(0) + "</br>"; if (isNumeric(d.frequency)) msg = msg + "Frequency: " + (100 * d.frequency).toFixed(0) + "%</br>"; if (isNumeric(d.count)) msg = msg + "N. reads: " + d.count.toFixed(0) + "</br>"; if ((tipMuts) && (typeof(d.muts) != "undefined") && (d.muts !== "undefined")){ msg = msg + "Mutations on this branch: "; if (d.muts.length > 0) { var muts = d.muts.split(" "), nMuts = muts.length, nMutsPerLine = 10, nMutLines = Math.ceil(nMuts / nMutsPerLine); if (nMutLines == 1) msg = msg + d.muts; else { msg = msg + "</br>"; for(var i=0; i < nMutLines - 1; i++) msg = msg + muts.slice(i * nMutsPerLine, (i+1) * nMutsPerLine).join(" ") + "</br>"; msg = msg + muts.slice((nMutLines - 1) * nMutsPerLine, nMuts).join(" "); } } else msg = msg + "(none)"; } return msg; } } chart.margin = function (_) { if (!arguments.length) return margin; margin = _; width = svgWidth - margin.left - margin.right; height = svgHeight - margin.top - margin.bottom; return chart; }; chart.svgWidth = function (_) { if (!arguments.length) return width; svgWidth = _; width = svgWidth - margin.left - margin.right; return chart; }; chart.svgHeight = function (_) { if (!arguments.length) return height; svgHeight = _; height = svgHeight - margin.top - margin.bottom; return chart; }; chart.chartType = function (_) { if (!arguments.length) return chartType; chartType = _; return chart; }; chart.colorLinkType = function (_) { if (!arguments.length) return colorLinkType; colorLinkType = _; return chart; }; chart.leafLabels = function (_) { if (!arguments.length) return leafLabels; leafLabels = _; return chart; }; chart.optimizeSpace = function (_) { if (!arguments.length) return optimizeSpace; optimizeSpace = _; return chart; }; chart.tipMuts = function (_) { if (!arguments.length) return tipMuts; tipMuts = _; return chart; }; return chart; }
app/hiv/static/js/trees.js
function emptyTree(id, keepData) { var svg = d3.select('#'+id); svg.selectAll("*").remove(); if ((typeof(keepData) == "undefined") | (!keepData)) svg.datum(null); } /* * Plot phylogenetic trees with radial or rectangular representation * Author: Fabio Zanini */ // NOTE: this function is ready for callbacks, they have to set data = {chartType: <chartType>} function updateTree(id, data) { if (typeof(data)==='undefined') data = {}; var svg = d3.select('#'+id), divWidth = $('#'+id).parent().width(); // if this function is called with some useful data, bind it to the DOM if ("tree" in data) svg.datum(data) var chart = treeChart().svgWidth(0.9 * divWidth); // Figure out settings from the DOM, e.g. coloring and chart type if ($("#switchRectangular").hasClass("active")) { chart.chartType("rectangular"); chart.svgHeight(15 * getNumberTerminals(svg.datum().tree, 0)); } else chart.svgHeight(0.9 * divWidth); if ($("#switchColorLinkDate").hasClass("active")) chart.colorLinkType("date"); else if ($("#switchColorLinkSubtype").hasClass("active")) chart.colorLinkType("subtype"); else if ($("#switchColorLinkPatient").hasClass("active")) chart.colorLinkType("patient"); // Leaf labels defaults to false for minor variant trees if ((data.leafLabels === false) || ((typeof(data.leafLabels) == "undefined") && (svg.datum().region.indexOf("minor") != -1))) chart.leafLabels(false); if (data.optimizeSpace === true) chart.optimizeSpace(true); if (data.tipMuts === false) chart.tipMuts(false); svg.call(chart); function getNumberTerminals(n, number) { if (n.children) for(var i=0; i < n.children.length; i++) number += getNumberTerminals(n.children[i], 0); else number += 1; return number; } } /* tree chart closure as of Mark Bostock: http://bost.ocks.org/mike/chart/ */ function treeChart() { var svgWidth = 400, svgHeight = 400, margin = {top: 5, bottom: 5, left: 5, right: 5}, width = svgWidth - margin.left - margin.right, height = svgHeight - margin.top - margin.bottom, chartType = "radial", colorLinkType = "black", leafLabels = true, optimizeSpace = false, tipMuts = true; // TREE CHART FUNCTION function chart(selection) { selection.each(function (data) { var colors = ["#5097BA", "#60AA9E", "#75B681", "#8EBC66", "#AABD52", "#C4B945", "#D9AD3D", "#E59637", "#E67030", "#DF4327"]; var colorMap = d3.scale.linear() .interpolate(d3.interpolateRgb) .domain([0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]) .range(colors); var tree = data.tree, pname = data.pname, region = data.region; // minor haplotype trees require more margin because they have balls attached if (region.indexOf("minor") != 1) { margin.top += 5; margin.bottom += 5; height -= 10; margin.left += 5; margin.right += 5; width -= 10; } // Create outer chart (SVG) and make sure there are no other ones var svg = d3.select(this); svg.selectAll("*").remove(); // Set the outer dimensions. //svg.attr("width", width + margin.left + margin.right) // .attr("height", height + margin.top + margin.bottom) //responsive SVG needs these 2 attributes and no width and height attr svg.attr("preserveAspectRatio", "xMinYMin meet") .attr("viewBox", "0 0 " + (width + margin.left + margin.right) + " " + (height + margin.top + margin.bottom)); // calculate various properties of all nodes setDepths(tree, 0); setNTerminals(tree); setDSI(tree); setPatientInternal(tree); var depth = Math.max(1e-7, getMaxTree(tree, function(d) { return d.depthScaled; })), dsiMax = getMaxTree(tree, function(d) { return d.DSI; }); // set link coloring function if (colorLinkType == "date") var colorLinkFunc = function(d) { var dsi = d.target.DSI; if (dsi != "undefined") return colorMap(dsi / dsiMax); else return "grey"; } else if (colorLinkType == "subtype") var colorLinkFunc = function(d) { var n = d.target; // NOTE: colors from colorbrewer dark2 if (n.subtype === 'B') return "#7570b3"; else if (n.subtype === 'C') return "#d95f02"; else if (n.subtype === 'AE') return "#1b9e77" else return "grey"; } else if (colorLinkType == "patient") var colorLinkFunc = function(d) { var cscale = d3.scale.category20() .domain(['p1','p2','p3','p4','p5','p6','p7','p8','p9','p10','p11']); if (d.target.patient != "undefined") return cscale(d.target.patient); else if (d.target.name != "undefined") return "black"; else return "grey"; } else var colorLinkFunc = function(d) { return "black"; } // tooltip var tip = d3.tip() .attr('class', 'd3-tip') .html(tooltipFunc); // prepare cluster representation var cluster = d3.layout.cluster() .sort(null) .value(function(d) { return d.branch_length; }) .separation(function(a, b) { return 1; }); // plot the chart if (chartType == "radial") makeRadial(); else makeRectangular(); // RADIAL CHART function makeRadial() { // Create inner chart, centered in the center of the circle var maxAngle = 360, r = width / 2, treeCenter = {'cx': r, 'cy': r}; // if the leaf labels are not shown, center the tree differently var rInternal = r; if (leafLabels === true) rInternal -= 170; // adjust the bar to calibration var treeScale = 0.9 * rInternal / depth; // set up the d3 cluster cluster.size([maxAngle, 1]); var nodes = cluster.nodes(tree); // add position attributes to the tree: // - angle // - radius from the coordinate center (treeCenter) // - x coordinate from the treeCenter // - y coordinate from the treeCenter nodes.map(function(n) { n.radius = n.depthScaled * treeScale; n.angle = n.x; setProjectRadial(n); }); // if requested, optimize space by resetting the viewbox if (optimizeSpace === true) { // get max and min x and y var xMax = d3.max(nodes, function(d){ return d.x; }), xMin = d3.min(nodes, function(d){ return d.x; }), yMax = d3.max(nodes, function(d){ return d.y; }), yMin = d3.min(nodes, function(d){ return d.y; }); svg.attr("viewBox", ((r + xMin - 20) + " " + (r + yMin - 20) + " " + (xMax - xMin + 40 + margin.left + margin.right) + " " + (yMax - yMin + 40 + margin.top + margin.bottom)) ); } // SVG group to render tree in var vis = svg.append("g") .attr("transform", ("translate(" + (margin.left + treeCenter.cx) + "," + (margin.top + treeCenter.cy) + ")") ); //// Test dot in the treeCenter //svg.append("circle") // .attr("cx", margin.left + r) // .attr("cy", margin.top + r) // .attr("r", 10) // .style("fill", "red"); //svg.append("rect") // .attr("x", margin.left) // .attr("y", margin.top) // .attr("width", 2 * r) // .attr("height", 2 * r) // .attr("fill", "none") // .attr("stroke", "red") // .attr("stroke-width", 3); // activate tip on visualized svg vis.call(tip); // links var link = vis.selectAll("path.link") .data(cluster.links(nodes)) .enter() .append("path") .attr("class", "link") .attr("d", stepRadial) .attr("stroke", colorLinkFunc) .on("mouseover", moverLinksRadial) .on("mouseout", moutLinksRadial); // balls proportional to frequency for minor variants if (region.indexOf("minor") != -1) { link.filter(function(d) { return d.target.frequency != "undefined" }) .each(plotBallsRadial); } var treetips = vis.selectAll("treetip") .data(cluster.links(nodes)) .enter() .append("circle") .attr("class", "treetip") .attr("cx", function (d) {return d.target.x;}) .attr("cy", function (d) {return d.target.y;}) .attr("r", 5) .attr("stroke", colorLinkFunc) .on("mouseover", moverLinksRadial) .on("mouseout", moutLinksRadial); // line connecting the leaves to their labels if (leafLabels === true) { var label = vis.selectAll(".anno") .data(nodes.filter(function(d) { return d.x !== undefined && !d.children; })) .enter() .append("g") .attr("class", "anno"); label.append("path") .attr("class", "annoline") .attr("d", function(d) { return stepAnnoRadial(d, rInternal); }); // leaf labels label.append("text") .attr("dy", ".31em") .attr("class", "annotext") .attr("text-anchor", function(d) { return d.angle < 180 ? "start" : "end"; }) .attr("transform", function(d) { return ("rotate(" + (d.angle - 90) + ")translate(" + (r - 170 + 8) + ")rotate(" + (d.angle < 180 ? 0 : 180) + ")"); }) .text(leafLabelFunc) .on("mouseover", moverRadial) .on("mouseout", moutRadial); } // scale bar if ((leafLabels === true) & (depth > 1e-6)) { var barLengthData = (30.0 / treeScale).toPrecision(1), barLength = treeScale * barLengthData, barLengthText = String(barLengthData); var bar = vis.append("g") .attr("class", "lengthbar") .attr("transform", "translate(" + (r - 50) + "," + (r - 20) + ")"); bar.selectAll(".lengthbar") .data([[-barLength, 0, 0, 0], [-barLength, -barLength, -7, 7], [0, 0, -7, 7]]) .enter() .append("svg:line") .attr("x1", function(d) { return d[0]; }) .attr("x2", function(d) { return d[1]; }) .attr("y1", function(d) { return d[2]; }) .attr("y2", function(d) { return d[3]; }); bar.append("text") .attr("class", "lengthbartext") .attr("x", -barLength / 2) .attr("y", 25) .text(barLengthText) .attr("text-anchor", "middle"); } function moverLinksRadial(d) { moverRadial(d.target); } function moutLinksRadial(d) { moutRadial(d.target); } function moverRadial(d) { var t = projectRadial(d); vis.append("circle") .attr("class", "highlight") .attr("cx", t.x) .attr("cy", t.y) .attr("r", 8) .transition() .duration(400); tip.show(d); } function moutRadial(d) { tip.hide(d); vis.selectAll(".highlight") .remove(); } function projectRadial(d) { var r = d.radius, a = (d.angle - 90) / 180 * Math.PI; return {'x': r * Math.cos(a), 'y': r * Math.sin(a)}; } function setProjectRadial(d) { var pr = projectRadial(d); d.x = pr.x; d.y = pr.y; } function stepRadial(d) { var s = d.source, m = projectRadial({angle: d.target.angle, radius: d.source.radius}), t = d.target, r = d.source.radius, sweep = d.target.angle > d.source.angle ? 1 : 0; return ( "M" + s.x + "," + s.y + "A" + r + "," + r + " 0 0," + sweep + " " + m.x + "," + m.y + "L" + t.x + "," + t.y); } function stepAnnoRadial(d, r) { var s = projectRadial({angle: d.angle, radius: d.radius + 5}), t = projectRadial({angle: d.angle, radius: r}); return ( "M" + s.x + "," + s.y + "L" + t.x + "," + t.y); } function plotBallsRadial(d, i) { var freq = d.target.frequency, r = 2 + (18 - 5) * ((Math.log(freq) / Math.LN10) + 2.0) / 2.0; vis.append("circle") .datum(d.target) .attr("class", "leaf") .attr("r", r) .attr("cx", d.target.x) .attr("cy", d.target.y) .attr("fill", colorLinkFunc(d, i)) .attr("stroke", d3.rgb(colorLinkFunc(d, i)).darker()) .attr("fill-opacity", 0.7) .on("mouseover", moverRadial) .on("mouseout", moutRadial); } } // RECTANGULAR CHART function makeRectangular() { var vis = svg.append("g") .attr("transform", "translate(" + (margin.left) + "," + (margin.top) + ")"); // activate tip on visualized svg vis.call(tip); // set up d3 cluster // note: at present, x and y are swapped to keep consistency with the radial layout var treeHeight = height, treeWidth = 0.93 * width; cluster.size([treeHeight, treeWidth]); // adjust the bar to calibration var treeScale = cluster.size()[1] / depth; if ((leafLabels === true) & (depth > 1e-6)) { var barLengthData = (30.0 / treeScale).toPrecision(1), barLength = treeScale * barLengthData; // set the bar text, should be the same as the data except in degenerate trees var barLengthText = String(barLengthData); // scale bar var bar = vis.append("g") .attr("transform", "translate(" + 50 + "," + (height - 20) + ")"); bar.selectAll(".lengthbar") .data([[-barLength, 0, 0, 0], [-barLength, -barLength, -7, 7], [0, 0, -7, 7]]) .enter() .append("svg:line") .attr("class","lengthbar") .attr("x1", function(d) { return d[0]; }) .attr("x2", function(d) { return d[1]; }) .attr("y1", function(d) { return d[2]; }) .attr("y2", function(d) { return d[3]; }); bar.append("text") .attr("x", -barLength / 2) .attr("y", 25) .text(barLengthText) .attr("text-anchor", "middle"); } var nodes = cluster.nodes(tree); // add scaled depths (in pixels) to the tree nodes.map(function(n) {n.y = n.depthScaled * treeScale; }); // links var link = vis.selectAll("path.link") .data(cluster.links(nodes)) .enter() .append("path") .attr("class", "link") .attr("d", stepRectangular) // .attr("fill", "none") .attr("stroke", colorLinkFunc) .on("mouseover", moverLinksRectangular) .on("mouseout", moutLinksRectangular); // balls proportional to frequency for minor variants if (region.indexOf("minor") != -1) { link.filter(function(d) { return d.target.frequency != "undefined" }) .each(plotBallsRect); } var treetips = vis.selectAll("treetip") .data(cluster.links(nodes)) .enter() .append("circle") .attr("class", "treetip") .attr("cx", function (d) {return d.target.y;}) .attr("cy", function (d) {return d.target.x;}) .attr("r", 5) .attr("stroke", colorLinkFunc) .on("mouseover", moverLinksRectangular) .on("mouseout", moutLinksRectangular); // line connecting the leaves to their labels if (leafLabels === true) { var label = vis.selectAll(".anno") .data(nodes.filter(function(d) { return d.x !== undefined && !d.children; })) .enter() .append("g") .attr("class", "anno"); label.append("path") .attr("class", "annoline") .attr("d", function(d) { return stepAnnoRectangular(d); }) // leaf labels label.append("text") .attr("class", "annotext") .attr("dy", ".31em") .attr("text-anchor", "end") .attr("transform", function(d) { return "translate(" + width + "," + d.x + ")"; }) .text(leafLabelFunc) .on("mouseover", moverRectangular) .on("mouseout", moutRectangular); } function moverLinksRectangular(d) { moverRectangular(d.target); } function moutLinksRectangular(d) { moutRectangular(d.target); } function moverRectangular(d) { vis.append("circle") .attr("class", "highlight") .attr("cx", d.y) .attr("cy", d.x) .attr("r", 8) .transition() .duration(400) tip.show(d); } function moutRectangular(d) { tip.hide(d); vis.selectAll(".highlight") .remove(); } function stepRectangular(d) { return ( "M" + d.source.y + "," + d.source.x + "V" + d.target.x + "H" + d.target.y ); } function stepAnnoRectangular(d) { // FIXME: the depth is a trick, we should allocate space // for the labels and subtract, but that depends on fontsize return ( "M" + d.y + "," + d.x + "H" + (10 + depth * treeScale) ); } function plotBallsRect(d, i) { var freq = d.target.frequency, r = 2 + (18 - 5) * ((Math.log(freq) / Math.LN10) + 2.0) / 2.0; vis.append("circle") .attr("class", "leaf") .attr("r", r) .attr("cx", d.target.y) .attr("cy", d.target.x) .attr("fill", colorLinkFunc(d, i)) .attr("stroke", d3.rgb(colorLinkFunc(d, i)).darker()) .on("mouseover", function() { return moverLinksRectangular(d)}) .on("mouseout", function() { return moutLinksRectangular(d)}); } } function leafLabelFunc(d) { if (String(region).indexOf('minor') != -1) { var freqLabel = String((d.frequency * 100).toFixed(0)) + "%", timeLabel = String(Math.floor(d.DSI / 30.5)) + " m", label = freqLabel + ", " + timeLabel; return label; } else { var name = String(d.name); return name.split('_').join(" "); } } }); // NOTE: node.depth is a d3 construct to get the integer depth, we use depthScaled function setDepths(n, parentDepth) { n.depthScaled = parentDepth + n.branch_length; if (n.children) for (var i=0; i < n.children.length; i++) setDepths(n.children[i], n.depthScaled); } function getMaxTree(n, accessor) { if (n.children) return d3.max(n.children, function (d) { return getMaxTree(d, accessor); }); else return accessor(n); } function setNTerminals(n) { if (n.children) { n.children.map(setNTerminals); n.nTerminals = d3.sum(n.children, function(d) { return d.nTerminals; }); } else n.nTerminals = 1; } // Get weighted mean of DSIs of terminal nodes function setDSI(n) { if (n.children) { n.children.map(setDSI); var dsicum = d3.sum(n.children, function (d) { var dsi = d.DSI; if (dsi == "undefined") return 0; return dsi * d.nTerminals; }); var childrencum = d3.sum(n.children, function(d) { if (d.DSI == "undefined") return 0; return d.nTerminals; }); if (childrencum == 0) n.DSI = "undefined"; else n.DSI = dsicum / childrencum; } } // Set the patient designation of internal nodes to that of its children // iff all agree. otherwise, set to undefined function setPatientInternal(n) { if (n.children) { n.children.map(setPatientInternal); var patient = n.children.map(function (d) {return d.patient}); if (patient.every(function (d){return d==patient[0]})){ n.patient=patient[0]; }else{ n.patient="undefined"; } } } // Tooltip function, used for both edges and nodes function tooltipFunc(d) { // get the child node anyway if (d.hasOwnProperty('target')) d = d.target; var msg = ""; if (!(d.children)) { var pname = String(d.name).split('_')[0]; if (pname[0] == "p") msg = msg + "Patient: " + pname + "</br>"; else if (pname != "undefined") { if (pname == "LAI-III") msg = msg + "Name: " + pname + " (HXB2)</br>"; else msg = msg + "Name: " + pname + "</br>"; } if (isNumeric(d.CD4)) msg = msg + "CD4+ cell count [cells/ml]: " + d.CD4 + "</br>"; if (isNumeric(d.VL)) msg = msg + "Viral load [virions/ml]: " + d.VL + "</br>"; } if ((typeof(d.subtype) != "undefined") && (d.subtype !== "undefined")) { msg = msg + "Subtype: " + d.subtype + "</br>"; } if (isNumeric(d.DSI)) msg = msg + "Day since infection: " + d.DSI.toFixed(0) + "</br>"; if (isNumeric(d.frequency)) msg = msg + "Frequency: " + (100 * d.frequency).toFixed(0) + "%</br>"; if (isNumeric(d.count)) msg = msg + "N. reads: " + d.count.toFixed(0) + "</br>"; if ((tipMuts) && (typeof(d.muts) != "undefined") && (d.muts !== "undefined")){ msg = msg + "Mutations on this branch: "; if (d.muts.length > 0) { var muts = d.muts.split(" "), nMuts = muts.length, nMutsPerLine = 10, nMutLines = Math.ceil(nMuts / nMutsPerLine); if (nMutLines == 1) msg = msg + d.muts; else { msg = msg + "</br>"; for(var i=0; i < nMutLines - 1; i++) msg = msg + muts.slice(i * nMutsPerLine, (i+1) * nMutsPerLine).join(" ") + "</br>"; msg = msg + muts.slice((nMutLines - 1) * nMutsPerLine, nMuts).join(" "); } } else msg = msg + "(none)"; } return msg; } } chart.margin = function (_) { if (!arguments.length) return margin; margin = _; width = svgWidth - margin.left - margin.right; height = svgHeight - margin.top - margin.bottom; return chart; }; chart.svgWidth = function (_) { if (!arguments.length) return width; svgWidth = _; width = svgWidth - margin.left - margin.right; return chart; }; chart.svgHeight = function (_) { if (!arguments.length) return height; svgHeight = _; height = svgHeight - margin.top - margin.bottom; return chart; }; chart.chartType = function (_) { if (!arguments.length) return chartType; chartType = _; return chart; }; chart.colorLinkType = function (_) { if (!arguments.length) return colorLinkType; colorLinkType = _; return chart; }; chart.leafLabels = function (_) { if (!arguments.length) return leafLabels; leafLabels = _; return chart; }; chart.optimizeSpace = function (_) { if (!arguments.length) return optimizeSpace; optimizeSpace = _; return chart; }; chart.tipMuts = function (_) { if (!arguments.length) return tipMuts; tipMuts = _; return chart; }; return chart; }
Bugfix in transition in tree.js
app/hiv/static/js/trees.js
Bugfix in transition in tree.js
<ide><path>pp/hiv/static/js/trees.js <ide> .attr("cx", t.x) <ide> .attr("cy", t.y) <ide> .attr("r", 8) <del> .transition() <del> .duration(400); <ide> tip.show(d); <ide> } <ide>
Java
bsd-3-clause
4c82f710ca94af11d71c9cb74141a628e908be2f
0
frc4343/max2014
/* * FRC Team 4343 * Visit us at www.4343.ca */ package ca._4343.max3.commandGroups.autonomous.hot; import ca._4343.RobotConstants; import ca._4343.max3.commands.camera.WaitForHot; import ca._4343.max3.commands.drivetrain.DriveForward; import ca._4343.max3.commands.drivetrain.TurnLeft; import ca._4343.max3.commands.drivetrain.TurnRight; import ca._4343.max3.commandGroups.FireAndReloadSequence; import ca._4343.max3.commands.pickup.ExtendArm; import ca._4343.max3.commands.pickup.LoadBall; import ca._4343.max3.commands.pickup.RetractArm; import edu.wpi.first.wpilibj.command.CommandGroup; /** * * @author Brian Ho <www.4343.ca> * @author Tedi Papajorgji <www.4343.ca> */ public class DoubleBallRightSequence extends CommandGroup { boolean isHot = false; public DoubleBallRightSequence() { setTimeout(RobotConstants.AUTONOMOUS_DOUBLE_BALL_HOT_GOAL_TIMEOUT); addSequential(new WaitForHot(), RobotConstants.AUTONOMOUS_DOUBLE_BALL_HOT_GOAL_TIMEOUT); isHot = !isTimedOut(); if (isHot) { addSequential(new FireAndReloadSequence()); addSequential(new LoadBall()); addSequential(new TurnLeft(), RobotConstants.AUTONOMOUS_TURN_DURATION); addSequential(new FireAndReloadSequence()); addSequential(new DriveForward(), RobotConstants.AUTONOMOUS_DRIVE_DURATION); } else { addSequential(new TurnLeft(), RobotConstants.AUTONOMOUS_TURN_DURATION); addSequential(new FireAndReloadSequence()); addSequential(new RetractArm()); addSequential(new TurnRight(), RobotConstants.AUTONOMOUS_TURN_DURATION); addParallel(new ExtendArm()); addParallel(new LoadBall()); addSequential(new FireAndReloadSequence()); addSequential(new DriveForward(), RobotConstants.AUTONOMOUS_DRIVE_DURATION); } } }
src/ca/_4343/max3/commandGroups/autonomous/hot/DoubleBallRightSequence.java
/* * FRC Team 4343 * Visit us at www.4343.ca */ package ca._4343.max3.commandGroups.autonomous.hot; import ca._4343.RobotConstants; import ca._4343.max3.commands.camera.WaitForHot; import ca._4343.max3.commands.drivetrain.DriveForward; import ca._4343.max3.commands.drivetrain.TurnLeft; import ca._4343.max3.commands.drivetrain.TurnRight; import ca._4343.max3.commandGroups.FireAndReloadSequence; import ca._4343.max3.commands.pickup.ExtendArm; import ca._4343.max3.commands.pickup.LoadBall; import ca._4343.max3.commands.pickup.RetractArm; import edu.wpi.first.wpilibj.command.CommandGroup; /** * * @author Brian Ho <www.4343.ca> * @author Tedi Papajorgji <www.4343.ca> */ public class DoubleBallRightSequence extends CommandGroup { boolean isHot = false; public DoubleBallRightSequence() { setTimeout(RobotConstants.AUTONOMOUS_DOUBLE_BALL_HOT_GOAL_TIMEOUT); addSequential(new WaitForHot(), RobotConstants.AUTONOMOUS_DOUBLE_BALL_HOT_GOAL_TIMEOUT); isHot = !isTimedOut(); if (isHot) { addSequential(new FireAndReloadSequence()); addSequential(new LoadBall()); addSequential(new TurnLeft(), RobotConstants.AUTONOMOUS_TURN_DURATION); addSequential(new FireAndReloadSequence()); addSequential(new DriveForward(), RobotConstants.AUTONOMOUS_DRIVE_DURATION); } else { addSequential(new TurnLeft(), RobotConstants.AUTONOMOUS_TURN_DURATION); addSequential(new FireAndReloadSequence()); addSequential(new RetractArm()); addSequential(new TurnRight(), RobotConstants.AUTONOMOUS_TURN_DURATION); addSequential(new ExtendArm()); addSequential(new LoadBall()); addSequential(new FireAndReloadSequence()); addSequential(new DriveForward(), RobotConstants.AUTONOMOUS_DRIVE_DURATION); } } }
Forgot a addparallel for autonomous
src/ca/_4343/max3/commandGroups/autonomous/hot/DoubleBallRightSequence.java
Forgot a addparallel for autonomous
<ide><path>rc/ca/_4343/max3/commandGroups/autonomous/hot/DoubleBallRightSequence.java <ide> addSequential(new FireAndReloadSequence()); <ide> addSequential(new RetractArm()); <ide> addSequential(new TurnRight(), RobotConstants.AUTONOMOUS_TURN_DURATION); <del> addSequential(new ExtendArm()); <del> addSequential(new LoadBall()); <add> addParallel(new ExtendArm()); <add> addParallel(new LoadBall()); <ide> addSequential(new FireAndReloadSequence()); <ide> addSequential(new DriveForward(), RobotConstants.AUTONOMOUS_DRIVE_DURATION); <ide> }
Java
mit
cb73527bf121bc73f9adfec72edc13fb5a5be4e2
0
bmaxwell921/PixHellRedux
package com.phr.main.systems; import com.artemis.ComponentMapper; import com.artemis.Entity; import com.artemis.Filter; import com.artemis.systems.EntityProcessingSystem; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.math.Rectangle; import com.phr.main.PixHellGame; import com.phr.main.components.DimensionComp; import com.phr.main.components.PlayerComp; import com.phr.main.components.PositionComp; import com.phr.main.util.EntityFactory; public class EntityRemoveSys extends EntityProcessingSystem { private ComponentMapper<PositionComp> pcm; private ComponentMapper<DimensionComp> dcm; public EntityRemoveSys() { super(Filter.allComponents(PositionComp.class, DimensionComp.class).exclude(PlayerComp.class)); // Bounds are bigger than the actual screen so new enemies aren't killed } @Override public void initialize() { pcm = world.getMapper(PositionComp.class); dcm = world.getMapper(DimensionComp.class); } @Override protected void process(Entity e) { PositionComp pc = pcm.get(e); DimensionComp dc = dcm.get(e); if (!inBounds(pc, dc)) { e.deleteFromWorld(); // Gdx.app.log("Entity Remove", "Removed entity from the game"); } } private boolean inBounds(PositionComp pc, DimensionComp dc) { return pc.position.x >= 0 && pc.position.x < PixHellGame.VIRTUAL_WIDTH - dc.width // x values && pc.position.y >= -dc.height && pc.position.y <= PixHellGame.VIRTUAL_HEIGHT; // y values } }
core/src/com/phr/main/systems/EntityRemoveSys.java
package com.phr.main.systems; import com.artemis.ComponentMapper; import com.artemis.Entity; import com.artemis.Filter; import com.artemis.systems.EntityProcessingSystem; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.math.Rectangle; import com.phr.main.PixHellGame; import com.phr.main.components.DimensionComp; import com.phr.main.components.PlayerComp; import com.phr.main.components.PositionComp; import com.phr.main.util.EntityFactory; public class EntityRemoveSys extends EntityProcessingSystem { private ComponentMapper<PositionComp> pcm; private ComponentMapper<DimensionComp> dcm; public EntityRemoveSys() { super(Filter.allComponents(PositionComp.class, DimensionComp.class).exclude(PlayerComp.class)); // Bounds are bigger than the actual screen so new enemies aren't killed } @Override public void initialize() { pcm = world.getMapper(PositionComp.class); dcm = world.getMapper(DimensionComp.class); } @Override protected void process(Entity e) { PositionComp pc = pcm.get(e); DimensionComp dc = dcm.get(e); if (!inBounds(pc, dc)) { e.deleteFromWorld(); Gdx.app.log("Entity Remove", "Removed entity from the game"); } } private boolean inBounds(PositionComp pc, DimensionComp dc) { return pc.position.x >= 0 && pc.position.x < PixHellGame.VIRTUAL_WIDTH - dc.width // x values && pc.position.y >= -dc.height && pc.position.y <= PixHellGame.VIRTUAL_HEIGHT; // y values } }
Removed debugging code
core/src/com/phr/main/systems/EntityRemoveSys.java
Removed debugging code
<ide><path>ore/src/com/phr/main/systems/EntityRemoveSys.java <ide> if (!inBounds(pc, dc)) { <ide> e.deleteFromWorld(); <ide> <del> Gdx.app.log("Entity Remove", "Removed entity from the game"); <add>// Gdx.app.log("Entity Remove", "Removed entity from the game"); <ide> } <ide> } <ide>
Java
mit
a5a66f9f118473b977f7bf4b4ba02d3e32282e7f
0
DemigodsRPG/Demigods3
package com.censoredsoftware.Demigods.Engine.Listener; import java.util.ArrayList; import java.util.List; import org.bukkit.*; import org.bukkit.block.Block; import org.bukkit.entity.Item; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.*; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.inventory.ItemStack; import com.censoredsoftware.Demigods.API.AdminAPI; import com.censoredsoftware.Demigods.API.ZoneAPI; import com.censoredsoftware.Demigods.Engine.Block.Altar; import com.censoredsoftware.Demigods.Engine.Block.BlockFactory; import com.censoredsoftware.Demigods.Engine.Block.Shrine; import com.censoredsoftware.Demigods.Engine.Demigods; import com.censoredsoftware.Demigods.Engine.DemigodsData; import com.censoredsoftware.Demigods.Engine.Event.Altar.AltarCreateEvent; import com.censoredsoftware.Demigods.Engine.Event.Altar.AltarCreateEvent.AltarCreateCause; import com.censoredsoftware.Demigods.Engine.Event.Altar.AltarRemoveEvent; import com.censoredsoftware.Demigods.Engine.Event.Shrine.ShrineCreateEvent; import com.censoredsoftware.Demigods.Engine.Event.Shrine.ShrineRemoveEvent; import com.censoredsoftware.Demigods.Engine.PlayerCharacter.PlayerCharacter; import com.censoredsoftware.Demigods.Engine.Tracked.TrackedBlock; import com.censoredsoftware.Demigods.Engine.Tracked.TrackedLocation; import com.censoredsoftware.Demigods.Engine.Tracked.TrackedPlayer; public class BlockListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST) public void onBlockBreak(BlockBreakEvent event) { Location location = event.getBlock().getLocation(); if(TrackedBlock.isProtected(location)) { event.setCancelled(true); event.getPlayer().sendMessage(ChatColor.YELLOW + "That block is protected by a Deity!"); } } @EventHandler(priority = EventPriority.HIGHEST) public void onBlockIgnite(BlockIgniteEvent event) { Location location = event.getBlock().getLocation(); if(TrackedBlock.isProtected(location)) event.setCancelled(true); } @EventHandler(priority = EventPriority.HIGHEST) public void onBlockDamage(BlockDamageEvent event) { Location location = event.getBlock().getLocation(); if(TrackedBlock.isProtected(location)) event.setCancelled(true); } @EventHandler(priority = EventPriority.HIGHEST) public void onBlockPistonExtend(BlockPistonExtendEvent event) { List<Block> blocks = event.getBlocks(); for(Block block : blocks) { Location location = block.getLocation(); if(TrackedBlock.isProtected(location)) { event.setCancelled(true); break; } } } @EventHandler(priority = EventPriority.HIGHEST) public void onBlockPistonRetract(BlockPistonRetractEvent event) { final Block block = event.getBlock().getRelative(event.getDirection(), 2); if(TrackedBlock.isProtected(block.getLocation()) && event.isSticky()) { event.setCancelled(true); } } @EventHandler(priority = EventPriority.HIGHEST) public void divineBlockExplode(final EntityExplodeEvent event) // TODO: Clean up and make it generic to Protected Blocks { final List<Location> savedLocations = new ArrayList<Location>(); final List<Material> savedMaterials = new ArrayList<Material>(); final List<Byte> savedBytes = new ArrayList<Byte>(); List<Block> blocks = event.blockList(); for(Block block : blocks) { if(block.getType() == Material.TNT) continue; if(TrackedBlock.isProtected(block.getLocation())) { savedLocations.add(block.getLocation()); savedMaterials.add(block.getType()); savedBytes.add(block.getData()); } } Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(Demigods.plugin, new Runnable() { @Override public void run() { // Regenerate blocks int i = 0; for(Location location : savedLocations) { location.getBlock().setTypeIdAndData(savedMaterials.get(i).getId(), savedBytes.get(i), true); i++; } // Remove all drops from explosion zone for(Item drop : event.getLocation().getWorld().getEntitiesByClass(Item.class)) { Location location = drop.getLocation(); if(ZoneAPI.zoneAltar(location) != null) { drop.remove(); continue; } if(ZoneAPI.zoneShrine(location) != null) { drop.remove(); } } } }, 1); } @EventHandler(priority = EventPriority.HIGHEST) public void stopDestroyEnderCrystal(EntityDamageEvent event) { try { if(TrackedBlock.isProtected(event.getEntity().getLocation().subtract(0.5, 1.0, 0.5))) { event.setDamage(0); event.setCancelled(true); } } catch(Exception ignored) {} } @EventHandler(priority = EventPriority.HIGH) public void demigodsAdminWand(PlayerInteractEvent event) { if(event.getClickedBlock() == null) return; // Define variables Block clickedBlock = event.getClickedBlock(); Location location = clickedBlock.getLocation(); Player player = event.getPlayer(); /** * Handle Altars */ if(AdminAPI.useWand(player) && clickedBlock.getType().equals(Material.EMERALD_BLOCK)) { event.setCancelled(true); AltarCreateEvent altarEvent = new AltarCreateEvent(location, AltarCreateCause.ADMIN_WAND); Bukkit.getServer().getPluginManager().callEvent(altarEvent); player.sendMessage(ChatColor.GRAY + "Generating new Altar..."); BlockFactory.createAltar(location); player.sendMessage(ChatColor.GREEN + "Altar created!"); } if(AdminAPI.useWand(player) && Altar.isAltar(location)) { event.setCancelled(true); Altar altar = Altar.getAltar(location); if(DemigodsData.hasTimed(player.getName(), "destroy_altar")) { AltarRemoveEvent altarRemoveEvent = new AltarRemoveEvent(location, AltarRemoveEvent.AltarRemoveCause.ADMIN_WAND); Bukkit.getServer().getPluginManager().callEvent(altarRemoveEvent); if(altarRemoveEvent.isCancelled()) return; // Remove the Altar altar.remove(); DemigodsData.removeTimed(player.getName(), "destroy_altar"); player.sendMessage(ChatColor.GREEN + "Altar removed!"); } else { DemigodsData.saveTimed(player.getName(), "destroy_altar", true, 5); player.sendMessage(ChatColor.RED + "Right-click this Altar again to remove it."); } } /** * Handle Shrines */ if(TrackedPlayer.isImmortal(player)) { PlayerCharacter character = TrackedPlayer.getTracked(player).getCurrent(); if(event.getAction() == Action.RIGHT_CLICK_BLOCK && character.getDeity().getInfo().getClaimItems().contains(event.getPlayer().getItemInHand().getType()) && Shrine.validBlockConfiguration(event.getClickedBlock())) { try { // Shrine created! ShrineCreateEvent shrineCreateEvent = new ShrineCreateEvent(character, location); Bukkit.getServer().getPluginManager().callEvent(shrineCreateEvent); if(shrineCreateEvent.isCancelled()) return; BlockFactory.createShrine(character, location); location.getWorld().strikeLightningEffect(location); if(!player.getGameMode().equals(GameMode.CREATIVE)) { if(player.getItemInHand().getAmount() > 1) { ItemStack books = new ItemStack(player.getItemInHand().getType(), player.getInventory().getItemInHand().getAmount() - 1); player.setItemInHand(books); } else { player.getInventory().remove(Material.BOOK); } } player.sendMessage(ChatColor.GRAY + "The " + ChatColor.YELLOW + character.getAlliance() + "s" + ChatColor.GRAY + " are pleased..."); player.sendMessage(ChatColor.GRAY + "You have created a Shrine in the name of " + ChatColor.YELLOW + character.getDeity().getInfo().getName() + ChatColor.GRAY + "!"); } catch(Exception e) { // Creation of shrine failed... e.printStackTrace(); } } } if(AdminAPI.useWand(player) && Shrine.isShrine(location)) { event.setCancelled(true); Shrine shrine = Shrine.getShrine(location); if(DemigodsData.hasTimed(player.getName(), "destroy_shrine")) { ShrineRemoveEvent shrineRemoveEvent = new ShrineRemoveEvent(shrine.getCharacter(), location); Bukkit.getServer().getPluginManager().callEvent(shrineRemoveEvent); if(shrineRemoveEvent.isCancelled()) return; // Remove the Shrine shrine.remove(); DemigodsData.removeTimed(player.getName(), "destroy_shrine"); player.sendMessage(ChatColor.GREEN + "Shrine removed!"); return; } else { DemigodsData.saveTimed(player.getName(), "destroy_shrine", true, 5); player.sendMessage(ChatColor.RED + "Right-click this Shrine again to remove it."); return; } } } @EventHandler(priority = EventPriority.HIGH) public void divineBlockAlerts(PlayerMoveEvent event) { if(event.getFrom().distance(event.getTo()) < 0.1) return; // Define variables Player player = event.getPlayer(); Location to = event.getTo(); Location from = event.getFrom(); /** * Entering Altar */ if(ZoneAPI.enterZoneAltar(to, from) && !TrackedLocation.hasWarp(ZoneAPI.zoneAltar(to), TrackedPlayer.getTracked(player).getCurrent())) // TODO This is an annoying message. { // player.sendMessage(ChatColor.GRAY + "You've never set a warp at this Altar."); return; } } }
core/src/com/censoredsoftware/Demigods/Engine/Listener/BlockListener.java
package com.censoredsoftware.Demigods.Engine.Listener; import java.util.ArrayList; import java.util.List; import org.bukkit.*; import org.bukkit.block.Block; import org.bukkit.entity.Item; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.*; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.inventory.ItemStack; import com.censoredsoftware.Demigods.API.AdminAPI; import com.censoredsoftware.Demigods.API.ZoneAPI; import com.censoredsoftware.Demigods.Engine.Block.Altar; import com.censoredsoftware.Demigods.Engine.Block.BlockFactory; import com.censoredsoftware.Demigods.Engine.Block.Shrine; import com.censoredsoftware.Demigods.Engine.Demigods; import com.censoredsoftware.Demigods.Engine.DemigodsData; import com.censoredsoftware.Demigods.Engine.Event.Altar.AltarCreateEvent; import com.censoredsoftware.Demigods.Engine.Event.Altar.AltarCreateEvent.AltarCreateCause; import com.censoredsoftware.Demigods.Engine.Event.Altar.AltarRemoveEvent; import com.censoredsoftware.Demigods.Engine.Event.Shrine.ShrineCreateEvent; import com.censoredsoftware.Demigods.Engine.Event.Shrine.ShrineRemoveEvent; import com.censoredsoftware.Demigods.Engine.PlayerCharacter.PlayerCharacter; import com.censoredsoftware.Demigods.Engine.Tracked.TrackedBlock; import com.censoredsoftware.Demigods.Engine.Tracked.TrackedLocation; import com.censoredsoftware.Demigods.Engine.Tracked.TrackedPlayer; public class BlockListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST) public void onBlockBreak(BlockBreakEvent event) { Location location = event.getBlock().getLocation(); if(TrackedBlock.isProtected(location)) { event.setCancelled(true); event.getPlayer().sendMessage(ChatColor.YELLOW + "That block is protected by a Deity!"); } } @EventHandler(priority = EventPriority.HIGHEST) public void onBlockIgnite(BlockIgniteEvent event) { Location location = event.getBlock().getLocation(); if(TrackedBlock.isProtected(location)) event.setCancelled(true); } @EventHandler(priority = EventPriority.HIGHEST) public void onBlockDamage(BlockDamageEvent event) { Location location = event.getBlock().getLocation(); if(TrackedBlock.isProtected(location)) event.setCancelled(true); } @EventHandler(priority = EventPriority.HIGHEST) public void onBlockPistonExtend(BlockPistonExtendEvent event) { List<Block> blocks = event.getBlocks(); for(Block block : blocks) { Location location = block.getLocation(); if(TrackedBlock.isProtected(location)) { event.setCancelled(true); break; } } } @EventHandler(priority = EventPriority.HIGHEST) public void onBlockPistonRetract(BlockPistonRetractEvent event) { final Block block = event.getBlock().getRelative(event.getDirection(), 2); if(TrackedBlock.isProtected(block.getLocation()) && event.isSticky()) { event.setCancelled(true); } } @EventHandler(priority = EventPriority.HIGHEST) public void divineBlockExplode(final EntityExplodeEvent event) // TODO: Clean up and make it generic to Protected Blocks { final List<Location> savedLocations = new ArrayList<Location>(); final List<Material> savedMaterials = new ArrayList<Material>(); final List<Byte> savedBytes = new ArrayList<Byte>(); List<Block> blocks = event.blockList(); for(Block block : blocks) { if(block.getType() == Material.TNT) continue; if(TrackedBlock.isProtected(block.getLocation())) { savedLocations.add(block.getLocation()); savedMaterials.add(block.getType()); savedBytes.add(block.getData()); } } Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(Demigods.plugin, new Runnable() { @Override public void run() { // Regenerate blocks int i = 0; for(Location location : savedLocations) { location.getBlock().setTypeIdAndData(savedMaterials.get(i).getId(), savedBytes.get(i), true); i++; } // Remove all drops from explosion zone for(Item drop : event.getLocation().getWorld().getEntitiesByClass(Item.class)) { Location location = drop.getLocation(); if(ZoneAPI.zoneAltar(location) != null) { drop.remove(); continue; } if(ZoneAPI.zoneShrine(location) != null) { drop.remove(); } } } }, 1); } @EventHandler(priority = EventPriority.HIGHEST) public void stopDestroyEnderCrystal(EntityDamageEvent event) { try { if(TrackedBlock.isProtected(event.getEntity().getLocation().subtract(0.5, 1.0, 0.5))) { event.setDamage(0); event.setCancelled(true); } } catch(Exception ignored) {} } @EventHandler(priority = EventPriority.HIGH) public void demigodsAdminWand(PlayerInteractEvent event) { if(event.getClickedBlock() == null) return; // Define variables Block clickedBlock = event.getClickedBlock(); Location location = clickedBlock.getLocation(); Player player = event.getPlayer(); /** * Handle Altars */ if(AdminAPI.useWand(player) && clickedBlock.getType().equals(Material.EMERALD_BLOCK)) { event.setCancelled(true); AltarCreateEvent altarEvent = new AltarCreateEvent(location, AltarCreateCause.ADMIN_WAND); Bukkit.getServer().getPluginManager().callEvent(altarEvent); player.sendMessage(ChatColor.GRAY + "Generating new Altar..."); BlockFactory.createAltar(location); player.sendMessage(ChatColor.GREEN + "Altar created!"); } if(AdminAPI.useWand(player) && Altar.isAltar(location)) { event.setCancelled(true); Altar altar = Altar.getAltar(location); if(DemigodsData.hasTimed(player.getName(), "destroy_altar")) { AltarRemoveEvent altarRemoveEvent = new AltarRemoveEvent(location, AltarRemoveEvent.AltarRemoveCause.ADMIN_WAND); Bukkit.getServer().getPluginManager().callEvent(altarRemoveEvent); if(altarRemoveEvent.isCancelled()) return; // Remove the Altar altar.remove(); DemigodsData.removeTimed(player.getName(), "destroy_altar"); player.sendMessage(ChatColor.GREEN + "Altar removed!"); } else { DemigodsData.saveTimed(player.getName(), "destroy_altar", true, 5); player.sendMessage(ChatColor.RED + "Right-click this Altar again to remove it."); } } /** * Handle Shrines */ if(TrackedPlayer.isImmortal(player)) { PlayerCharacter character = TrackedPlayer.getTracked(player).getCurrent(); if(event.getAction() == Action.RIGHT_CLICK_BLOCK && character.getDeity().getInfo().getClaimItems().contains(event.getPlayer().getItemInHand().getType()) && Shrine.validBlockConfiguration(event.getClickedBlock())) { try { // Shrine created! ShrineCreateEvent shrineCreateEvent = new ShrineCreateEvent(character, location); Bukkit.getServer().getPluginManager().callEvent(shrineCreateEvent); if(shrineCreateEvent.isCancelled()) return; BlockFactory.createShrine(character, location); location.getWorld().strikeLightningEffect(location); if(!player.getGameMode().equals(GameMode.CREATIVE)) { if(player.getItemInHand().getAmount() > 1) { ItemStack books = new ItemStack(player.getItemInHand().getType(), player.getInventory().getItemInHand().getAmount() - 1); player.setItemInHand(books); } else { player.getInventory().remove(Material.BOOK); } } player.sendMessage(ChatColor.GRAY + "The " + ChatColor.YELLOW + character.getAlliance() + "s" + ChatColor.GRAY + " are pleased..."); player.sendMessage(ChatColor.GRAY + "You have created a Shrine in the name of " + ChatColor.YELLOW + character.getDeity().getInfo().getName() + ChatColor.GRAY + "!"); } catch(Exception e) { // Creation of shrine failed... e.printStackTrace(); } } } if(AdminAPI.useWand(player) && Shrine.isShrine(location)) { event.setCancelled(true); Shrine shrine = Shrine.getShrine(location); if(DemigodsData.hasTimed(player.getName(), "destroy_shrine")) { ShrineRemoveEvent shrineRemoveEvent = new ShrineRemoveEvent(shrine.getCharacter(), location); Bukkit.getServer().getPluginManager().callEvent(shrineRemoveEvent); if(shrineRemoveEvent.isCancelled()) return; // Remove the Shrine shrine.remove(); DemigodsData.removeTimed(player.getName(), "destroy_shrine"); player.sendMessage(ChatColor.GREEN + "Shrine removed!"); return; } else { DemigodsData.saveTimed(player.getName(), "destroy_shrine", true, 5); player.sendMessage(ChatColor.RED + "Right-click this Shrine again to remove it."); return; } } } @EventHandler(priority = EventPriority.HIGH) public void divineBlockAlerts(PlayerMoveEvent event) { if(event.getFrom().distance(event.getTo()) < 0.1) return; // Define variables Player player = event.getPlayer(); Location to = event.getTo(); Location from = event.getFrom(); /** * Entering Altar */ if(ZoneAPI.enterZoneAltar(to, from) && !TrackedLocation.hasWarp(ZoneAPI.zoneAltar(to), TrackedPlayer.getTracked(player).getCurrent())) // TODO This is an annoying message. { player.sendMessage(ChatColor.GRAY + "You've never set a warp at this Altar."); return; } } }
Turn off annoying message, for now.
core/src/com/censoredsoftware/Demigods/Engine/Listener/BlockListener.java
Turn off annoying message, for now.
<ide><path>ore/src/com/censoredsoftware/Demigods/Engine/Listener/BlockListener.java <ide> */ <ide> if(ZoneAPI.enterZoneAltar(to, from) && !TrackedLocation.hasWarp(ZoneAPI.zoneAltar(to), TrackedPlayer.getTracked(player).getCurrent())) // TODO This is an annoying message. <ide> { <del> player.sendMessage(ChatColor.GRAY + "You've never set a warp at this Altar."); <add> // player.sendMessage(ChatColor.GRAY + "You've never set a warp at this Altar."); <ide> return; <ide> } <ide> }
JavaScript
agpl-3.0
2764a4ff1daa57da2b99a191b4d84e257d0051a5
0
flamingo-geocms/flamingo,B3Partners/flamingo,B3Partners/flamingo,B3Partners/flamingo,B3Partners/flamingo,mvdstruijk/flamingo,flamingo-geocms/flamingo,flamingo-geocms/flamingo,mvdstruijk/flamingo,flamingo-geocms/flamingo,mvdstruijk/flamingo,mvdstruijk/flamingo
/** * @class * @constructor * @description A drawable vector layer */ Ext.define("viewer.viewercontroller.openlayers.OpenLayersVectorLayer",{ extend: "viewer.viewercontroller.controller.VectorLayer", point:null, line:null, polygon:null, drawFeatureControls:null, modifyFeature:null, enabledEvents: new Object(), mixins: { openLayersLayer: "viewer.viewercontroller.openlayers.OpenLayersLayer" }, constructor : function (config){ // TODO make styles work in openlayersvectorlayers delete config.style; viewer.viewercontroller.openlayers.OpenLayersVectorLayer.superclass.constructor.call(this, config); this.frameworkLayer = new OpenLayers.Layer.Vector(config.id, config); // Make all drawFeature controls: the controls to draw features on the vectorlayer //TODO: Make a circlecontrol this.point = new OpenLayers.Control.DrawFeature(this.frameworkLayer, OpenLayers.Handler.Point, { displayClass: 'olControlDrawFeaturePoint' }); this.line = new OpenLayers.Control.DrawFeature(this.frameworkLayer, OpenLayers.Handler.Path, { displayClass: 'olControlDrawFeaturePath' }); this.polygon = new OpenLayers.Control.DrawFeature(this.frameworkLayer, OpenLayers.Handler.Polygon, { displayClass: 'olControlDrawFeaturePolygon' }); this.drawFeatureControls = new Array(); this.drawFeatureControls.push(this.polygon); this.drawFeatureControls.push(this.line); this.drawFeatureControls.push(this.point); // The modifyfeature control allows us to edit and select features. this.modifyFeature = new OpenLayers.Control.ModifyFeature(this.frameworkLayer); var map = this.viewerController.mapComponent.getMap().getFrameworkMap(); map.addControl(this.point); map.addControl(this.line); map.addControl(this.polygon); map.addControl(this.modifyFeature); this.modifyFeature.selectControl.events.register("featurehighlighted", this, this.activeFeatureChanged); this.frameworkLayer.events.register("afterfeaturemodified", this, this.featureModified); this.frameworkLayer.events.register("featuremodified", this, this.featureModified); this.frameworkLayer.events.register("featureadded", this, this.featureAdded); this.modifyFeature.activate(); }, adjustStyle : function(){ this.viewerController.logger.error("OpenLayersVectorLayer.adjustStyle() not yet implemented!"); }, removeAllFeatures : function(){ this.getFrameworkLayer().removeAllFeatures(); }, getActiveFeature : function(){ var index = this.getFrameworkLayer().features.length - 1; var olFeature = this.getFrameworkLayer().features[index]; var featureObj = new Feature(); var feature = featureObj.fromOpenLayersFeature(olFeature); return feature; }, getFeature : function(id){ return this.getFrameworkLayer().features[id]; }, getAllFeatures : function(){ var olFeatures = this.getFrameworkLayer().features; var features = new Array(); var featureObj = new viewer.viewercontroller.controller.Feature(); for(var i = 0 ; i < olFeatures.length;i++){ var olFeature = olFeatures[i]; var feature = featureObj.fromOpenLayersFeature(olFeature); features.push(feature); } return features; }, addFeature : function(feature){ var features = new Array(); features.push(feature); this.addFeatures(features); }, addFeatures : function(features){ var olFeatures = new Array(); for(var i = 0 ; i < features.length ; i++){ var feature = features[i]; var olFeature = this.toOpenLayersFeature(feature); olFeatures.push(olFeature); } return this.getFrameworkLayer().addFeatures(olFeatures); }, drawFeature : function(type){ if(type == "Point"){ this.point.activate(); }else if(type == "LineString"){ this.line.activate(); }else if(type == "Polygon"){ this.polygon.activate(); }else{ throw ("Feature type >" + type + "< not implemented!"); } }, /** * Called when a feature is selected */ activeFeatureChanged : function (object){ var feature = this.fromOpenLayersFeature (object.feature); this.fireEvent(viewer.viewercontroller.controller.Event.ON_ACTIVE_FEATURE_CHANGED,this,feature); }, /** * Called when a feature is modified. */ featureModified : function (evt){ var featureObject = this.fromOpenLayersFeature(evt.feature); this.fireEvent(viewer.viewercontroller.controller.Event.ON_FEATURE_ADDED,this,featureObject); }, /** * Called when a feature is added to the vectorlayer. It deactivates all drawFeature controls, makes the added feature editable and fires @see viewer.viewercontroller.controller.Event.ON_FEATURE_ADDED */ featureAdded : function (object){ var feature = this.fromOpenLayersFeature (object.feature); for ( var i = 0 ; i < this.drawFeatureControls.length ; i++ ){ var control = this.drawFeatureControls[i]; control.deactivate(); } this.editFeature(object.feature); this.fireEvent(viewer.viewercontroller.controller.Event.ON_FEATURE_ADDED,this,feature); }, /** * Puts an openlayersfeature in editmode and fires an event: viewer.viewercontroller.controller.Event.ON_ACTIVE_FEATURE_CHANGED * TODO: fix the selecting of a newly added point (after adding another geometry first) */ editFeature : function (feature){ this.modifyFeature.selectControl.unselectAll(); this.modifyFeature.selectControl.select(feature); var featureObject = this.fromOpenLayersFeature (feature); this.fireEvent(viewer.viewercontroller.controller.Event.ON_ACTIVE_FEATURE_CHANGED,this,featureObject); }, /** * Converts this feature to a OpenLayersFeature * @return The OpenLayerstype feature */ toOpenLayersFeature : function(feature){ var geom = OpenLayers.Geometry.fromWKT(feature.wktgeom); var olFeature = new OpenLayers.Feature.Vector(geom); return olFeature; }, /** * Helper function: Converts the given OpenLayers Feature to the generic feature. * @param openLayersFeature The OpenLayersFeature to be converted * @return The generic feature */ fromOpenLayersFeature : function(openLayersFeature){ var feature = new viewer.viewercontroller.controller.Feature({id:openLayersFeature.id,wktgeom: openLayersFeature.geometry.toString()}); return feature; }, addListener : function (event, handler, scope){ var olSpecificEvent = this.viewerController.mapComponent.getSpecificEventName(event); if(olSpecificEvent){ if(!scope){ scope = this; } if(!olSpecificEvent == "featureadded"){ this.registerToLayer(olSpecificEvent); } }else{ this.viewerController.logger.warning("Event not listed in OpenLayersVectorLayer >"+ event + "<. The application might not work correctly."); } viewer.viewercontroller.openlayers.OpenLayersVectorLayer.superclass.addListener.call(this,event,handler,scope); }, /** * Add event to OpenLayersVectorLayer only once, to prevent multiple fired events. * @param specificEvent The openLayers specific event. */ registerToLayer : function (specificEvent){ if(this.enabledEvents[specificEvent] == null ||this.enabledEvents[specificEvent] == undefined){ this.enabledEvents[specificEvent] = true; this.frameworkLayer.events.register(specificEvent, this, this.handleEvent); } }, /** * Handles the events fired by OpenLayers.VectorLayer and propagates them to the registered objects. * */ handleEvent : function (event){ var options = new Object(); options.layer = this.map.getLayerByOpenLayersId(event.element.id); options.feature = this.fromOpenLayersFeature(event.feature); var eventName = this.viewerController.mapComponent.getGenericEventName(event.type); if(!eventName){ eventName = event; } this.fireEvent(eventName,options); } });
common/viewercontroller/OpenLayers/OpenLayersVectorLayer.js
/** * @class * @constructor * @description A drawable vector layer */ Ext.define("viewer.viewercontroller.openlayers.OpenLayersVectorLayer",{ extend: "viewer.viewercontroller.controller.VectorLayer", point:null, line:null, polygon:null, drawFeatureControls:null, modifyFeature:null, enabledEvents: new Object(), mixins: { openLayersLayer: "viewer.viewercontroller.openlayers.OpenLayersLayer" }, constructor : function (config){ delete config.style; viewer.viewercontroller.openlayers.OpenLayersVectorLayer.superclass.constructor.call(this, config); this.frameworkLayer = new OpenLayers.Layer.Vector(config.id, config); // Make all drawFeature controls: the controls to draw features on the vectorlayer //TODO: Make a circlecontrol this.point = new OpenLayers.Control.DrawFeature(this.frameworkLayer, OpenLayers.Handler.Point, { displayClass: 'olControlDrawFeaturePoint' }); this.line = new OpenLayers.Control.DrawFeature(this.frameworkLayer, OpenLayers.Handler.Path, { displayClass: 'olControlDrawFeaturePath' }); this.polygon = new OpenLayers.Control.DrawFeature(this.frameworkLayer, OpenLayers.Handler.Polygon, { displayClass: 'olControlDrawFeaturePolygon' }); this.drawFeatureControls = new Array(); this.drawFeatureControls.push(this.polygon); this.drawFeatureControls.push(this.line); this.drawFeatureControls.push(this.point); // The modifyfeature control allows us to edit and select features. this.modifyFeature = new OpenLayers.Control.ModifyFeature(this.frameworkLayer); var map = this.viewerController.mapComponent.getMap().getFrameworkMap(); map.addControl(this.point); map.addControl(this.line); map.addControl(this.polygon); map.addControl(this.modifyFeature); this.modifyFeature.selectControl.events.register("featurehighlighted", this, this.activeFeatureChanged); this.frameworkLayer.events.register("afterfeaturemodified", this, this.featureModified); this.frameworkLayer.events.register("featuremodified", this, this.featureModified); this.frameworkLayer.events.register("featureadded", this, this.featureAdded); this.modifyFeature.activate(); }, adjustStyle : function(){ this.viewerController.logger.error("OpenLayersVectorLayer.adjustStyle() not yet implemented!"); }, removeAllFeatures : function(){ this.getFrameworkLayer().removeAllFeatures(); }, getActiveFeature : function(){ var index = this.getFrameworkLayer().features.length - 1; var olFeature = this.getFrameworkLayer().features[index]; var featureObj = new Feature(); var feature = featureObj.fromOpenLayersFeature(olFeature); return feature; }, getFeature : function(id){ return this.getFrameworkLayer().features[id]; }, getAllFeatures : function(){ var olFeatures = this.getFrameworkLayer().features; var features = new Array(); var featureObj = new viewer.viewercontroller.controller.Feature(); for(var i = 0 ; i < olFeatures.length;i++){ var olFeature = olFeatures[i]; var feature = featureObj.fromOpenLayersFeature(olFeature); features.push(feature); } return features; }, addFeature : function(feature){ var features = new Array(); features.push(feature); this.addFeatures(features); }, addFeatures : function(features){ var olFeatures = new Array(); for(var i = 0 ; i < features.length ; i++){ var feature = features[i]; var olFeature = this.toOpenLayersFeature(feature); olFeatures.push(olFeature); } return this.getFrameworkLayer().addFeatures(olFeatures); }, drawFeature : function(type){ if(type == "Point"){ this.point.activate(); }else if(type == "LineString"){ this.line.activate(); }else if(type == "Polygon"){ this.polygon.activate(); }else{ throw ("Feature type >" + type + "< not implemented!"); } }, /** * Called when a feature is selected */ activeFeatureChanged : function (object){ var feature = this.fromOpenLayersFeature (object.feature); this.fireEvent(viewer.viewercontroller.controller.Event.ON_ACTIVE_FEATURE_CHANGED,this,feature); }, /** * Called when a feature is modified. */ featureModified : function (evt){ var featureObject = this.fromOpenLayersFeature(evt.feature); this.fireEvent(viewer.viewercontroller.controller.Event.ON_FEATURE_ADDED,this,featureObject); }, /** * Called when a feature is added to the vectorlayer. It deactivates all drawFeature controls, makes the added feature editable and fires @see viewer.viewercontroller.controller.Event.ON_FEATURE_ADDED */ featureAdded : function (object){ var feature = this.fromOpenLayersFeature (object.feature); for ( var i = 0 ; i < this.drawFeatureControls.length ; i++ ){ var control = this.drawFeatureControls[i]; control.deactivate(); } this.editFeature(object.feature); this.fireEvent(viewer.viewercontroller.controller.Event.ON_FEATURE_ADDED,this,feature); }, /** * Puts an openlayersfeature in editmode and fires an event: viewer.viewercontroller.controller.Event.ON_ACTIVE_FEATURE_CHANGED * TODO: fix the selecting of a newly added point (after adding another geometry first) */ editFeature : function (feature){ this.modifyFeature.selectControl.unselectAll(); this.modifyFeature.selectControl.select(feature); var featureObject = this.fromOpenLayersFeature (feature); this.fireEvent(viewer.viewercontroller.controller.Event.ON_ACTIVE_FEATURE_CHANGED,this,featureObject); }, /** * Converts this feature to a OpenLayersFeature * @return The OpenLayerstype feature */ toOpenLayersFeature : function(feature){ var geom = OpenLayers.Geometry.fromWKT(feature.wktgeom); var olFeature = new OpenLayers.Feature.Vector(geom); return olFeature; }, /** * Helper function: Converts the given OpenLayers Feature to the generic feature. * @param openLayersFeature The OpenLayersFeature to be converted * @return The generic feature */ fromOpenLayersFeature : function(openLayersFeature){ var feature = new viewer.viewercontroller.controller.Feature({id:openLayersFeature.id,wktgeom: openLayersFeature.geometry.toString()}); return feature; }, addListener : function (event, handler, scope){ var olSpecificEvent = this.viewerController.mapComponent.getSpecificEventName(event); if(olSpecificEvent){ if(!scope){ scope = this; } if(!olSpecificEvent == "featureadded"){ this.registerToLayer(olSpecificEvent); } }else{ this.viewerController.logger.warning("Event not listed in OpenLayersVectorLayer >"+ event + "<. The application might not work correctly."); } viewer.viewercontroller.openlayers.OpenLayersVectorLayer.superclass.addListener.call(this,event,handler,scope); }, /** * Add event to OpenLayersVectorLayer only once, to prevent multiple fired events. * @param specificEvent The openLayers specific event. */ registerToLayer : function (specificEvent){ if(this.enabledEvents[specificEvent] == null ||this.enabledEvents[specificEvent] == undefined){ this.enabledEvents[specificEvent] = true; this.frameworkLayer.events.register(specificEvent, this, this.handleEvent); } }, /** * Handles the events fired by OpenLayers.VectorLayer and propagates them to the registered objects. * */ handleEvent : function (event){ var options = new Object(); options.layer = this.map.getLayerByOpenLayersId(event.element.id); options.feature = this.fromOpenLayersFeature(event.feature); var eventName = this.viewerController.mapComponent.getGenericEventName(event.type); if(!eventName){ eventName = event; } this.fireEvent(eventName,options); } });
Styles in vectorlayers in OL are missing: todo added
common/viewercontroller/OpenLayers/OpenLayersVectorLayer.js
Styles in vectorlayers in OL are missing: todo added
<ide><path>ommon/viewercontroller/OpenLayers/OpenLayersVectorLayer.js <ide> openLayersLayer: "viewer.viewercontroller.openlayers.OpenLayersLayer" <ide> }, <ide> constructor : function (config){ <add> // TODO make styles work in openlayersvectorlayers <ide> delete config.style; <ide> viewer.viewercontroller.openlayers.OpenLayersVectorLayer.superclass.constructor.call(this, config); <ide> this.frameworkLayer = new OpenLayers.Layer.Vector(config.id, config);
JavaScript
mit
b706a0881e8dfe13dfb77230079a7b4a46296b1d
0
backend-br/backend-br.github.io,backend-br/backend-br.github.io
const generateLabels = labels => { labels = Array.isArray(labels) ? labels : [labels] labels = labels.filter(label => label.length) labels = labels.map(label => `<li>${label}</li>`) labels = labels.join('') if (!labels.length) { return '' } return ` <ul class="jobs--flags"> ${labels} </ul> ` } const generateLocation = location => location && location.length ? ` <p> <span class="fas fa-map"></span> <span>${location}</span> </p> ` : '' const getLocation = title => { const regex = /^(?:\[)(.*?)(?:\])/g const result = title.match(regex) if (Array.isArray(result) && result.length) { return result.shift().replace(/\[|\]/g, '') } return '' } const jobTitle = title => title.slice ? title.slice(0, 60) : title; const generateJob = ({ id, url, title, labels, location }) => ` <article class=" jobs--listing-item no-grow no-shrink tile is-flex-one-quarter-desktop is-flex-one-third-mobile is-flex-full " data-id="${id}" data-labels="${labels.filter(label => label.length).join(',')}" data-location="${location}" data-title="${title.replace(/^\[(.*?)\]\s?/g, '')}" > <a href="${url}" target="_blank"> <h4 class="is-size-5">${jobTitle(title.replace(/^\[(.*?)\]\s?/g, ''))}</h4> ${generateLabels(labels)} ${generateLocation(location)} </a> </article> ` const jobHideClass = 'jobs--listing-hidden' const setClass = job => { job = $(job) if (!job.hasClass(jobHideClass)) { job.addClass(jobHideClass) } }; const filterJobs = ({ key, value }) => { if (value === 'clear') { console.log(`clear`); return $(`.jobs--listing-item[data-${key}]`) .removeClass(jobHideClass) } $('.jobs--listing-item').forEach(job => { const dataset = job.dataset if ( !dataset || !dataset[key] || !dataset[key].length || typeof dataset[key] !== 'string' ) { return setClass(job) } const found = dataset[key] .match(new RegExp(value, 'gi')) if (!found || !found.length) { return setClass(job) } $(job).removeClass('jobs--listing-hidden') }) } const getPaginators = link => { const result = { next: false, last: false } if (!link) { return result } const links = link.split(',') const linkRegex = /^\s?<(.*?)>/g const relRegex = /"([a-z]{4})"/g links.forEach(it => { let url = it.match(linkRegex) let rel = it.match(relRegex) if (url && url.length) { url = url.shift().replace(/<|>|/g, '') } if (rel && rel.length) { rel = rel.shift().replace(/"+/g, '') } if (rel === 'next') { result.next = url } else { result.last = url } }) return result } const loadIssues = (url) => $.getJSON( url, (data, status, xhr) => { window.data = xhr const issues = $ .map(data, issue => ({ url: issue.html_url, title: issue.title, location: getLocation(issue.title), labels: $.map(issue.labels, label => label.name), id: issue.id })) .filter(issue => !$(`article[data-issue-id='${issue.id}']`).length) .map(generateJob) if (issues.length) { $('#jobsListingWrapper').append(issues.join('')) } const { next, last } = getPaginators(xhr.getResponseHeader('Link')) const loadBtn = $('#loadMoreJobs') const currentNextUrl = loadBtn.attr('data-next') if ( (!next && currentNextUrl.length) || !issues.length || next === url || next === currentNextUrl ) { loadBtn.html(loadBtn.attr('data-is-empty')) loadBtn.attr('disabled', true) return } loadBtn.attr('data-next', next) } ) document.addEventListener('DOMContentLoaded', () => { if (!$('#state').length) { return } const githubIssuesUrl = 'https://api.github.com/repos/backend-br/vagas/issues' loadIssues(githubIssuesUrl) const toWatch = [ { htmlId: 'state', filterKey: ['location'], clearValue: 'clear' }, { htmlId: 'language', filterKey: ['labels'], clearValue: 'clear' } ] toWatch.forEach(item => { $(`#${item.htmlId}`).on('change', e => { const value = $(`#${item.htmlId}`).val() item .filterKey .forEach( key => filterJobs({ key, value }) ) }) }) $('#keyword').on('input', e => { const value = $('#keyword').val() $('.jobs--listing-item').forEach(job => { const filterKeys = ['labels', 'location', 'title'] const dataset = job.dataset const keys = filterKeys.map(k => k); if (!dataset) { return setClass(job) } let keep = false while (keys.length) { const key = keys.shift() if (dataset[key]) { keep = true break; } } if (!keep) { return setClass(job) } let show = false while (filterKeys.length) { const key = filterKeys.shift() const found = dataset[key] .match(new RegExp(value, 'gi')) if (found && found.length) { show = true break; } } if (!show) { return setClass(job) } $(job).removeClass('jobs--listing-hidden') }) }) $('#clearFilter').on('click', e => { $('.jobs--listing-hidden') .removeClass('jobs--listing-hidden') toWatch .forEach( item => $(`#${item.htmlId}`).val(item.clearValue || '') ) }) $('#loadMoreJobs').on('click', e => { const loadBtn = $('#loadMoreJobs') const currentNextUrl = loadBtn.attr('data-next') loadIssues(currentNextUrl) }) })
themes/backendbrasil/assets/js/jobs.js
const generateLabels = labels => { labels = Array.isArray(labels) ? labels : [labels] labels = labels.filter(label => label.length) labels = labels.map(label => `<li>${label}</li>`) labels = labels.join('') if (!labels.length) { return '' } return ` <ul class="jobs--flags"> ${labels} </ul> ` } const generateLocation = location => location && location.length ? ` <p> <span class="fas fa-map"></span> <span>${location}</span> </p> ` : '' const getLocation = title => { const regex = /^(?:\[)(.*?)(?:\])/g const result = title.match(regex) if (Array.isArray(result) && result.length) { return result.shift().replace(/\[|\]/g, '') } return '' } const generateJob = ({ id, url, title, labels, location }) => ` <article class=" jobs--listing-item no-grow no-shrink tile is-flex-one-quarter-desktop is-flex-one-third-mobile is-flex-full " data-id="${id}" data-labels="${labels.filter(label => label.length).join(',')}" data-location="${location}" data-title="${title.replace(/^\[(.*?)\]\s?/g, '')}" > <a href="${url}" target="_blank"> <h4 class="is-size-5">${title.replace(/^\[(.*?)\]\s?/g, '')}</h4> ${generateLabels(labels)} ${generateLocation(location)} </a> </article> ` const jobHideClass = 'jobs--listing-hidden' const setClass = job => { job = $(job) if (!job.hasClass(jobHideClass)) { job.addClass(jobHideClass) } }; const filterJobs = ({ key, value }) => { if (value === 'clear') { console.log(`clear`); return $(`.jobs--listing-item[data-${key}]`) .removeClass(jobHideClass) } $('.jobs--listing-item').forEach(job => { const dataset = job.dataset if ( !dataset || !dataset[key] || !dataset[key].length || typeof dataset[key] !== 'string' ) { return setClass(job) } const found = dataset[key] .match(new RegExp(value, 'gi')) if (!found || !found.length) { return setClass(job) } $(job).removeClass('jobs--listing-hidden') }) } const getPaginators = link => { const result = { next: false, last: false } if (!link) { return result } const links = link.split(',') const linkRegex = /^\s?<(.*?)>/g const relRegex = /"([a-z]{4})"/g links.forEach(it => { let url = it.match(linkRegex) let rel = it.match(relRegex) if (url && url.length) { url = url.shift().replace(/<|>|/g, '') } if (rel && rel.length) { rel = rel.shift().replace(/"+/g, '') } if (rel === 'next') { result.next = url } else { result.last = url } }) return result } const loadIssues = (url) => $.getJSON( url, (data, status, xhr) => { window.data = xhr const issues = $ .map(data, issue => ({ url: issue.html_url, title: issue.title, location: getLocation(issue.title), labels: $.map(issue.labels, label => label.name), id: issue.id })) .filter(issue => !$(`article[data-issue-id='${issue.id}']`).length) .map(generateJob) if (issues.length) { $('#jobsListingWrapper').append(issues.join('')) } const { next, last } = getPaginators(xhr.getResponseHeader('Link')) const loadBtn = $('#loadMoreJobs') const currentNextUrl = loadBtn.attr('data-next') if ( (!next && currentNextUrl.length) || !issues.length || next === url || next === currentNextUrl ) { loadBtn.html(loadBtn.attr('data-is-empty')) loadBtn.attr('disabled', true) return } loadBtn.attr('data-next', next) } ) document.addEventListener('DOMContentLoaded', () => { if (!$('#state').length) { return } const githubIssuesUrl = 'https://api.github.com/repos/backend-br/vagas/issues' loadIssues(githubIssuesUrl) const toWatch = [ { htmlId: 'state', filterKey: ['location'], clearValue: 'clear' }, { htmlId: 'language', filterKey: ['labels'], clearValue: 'clear' } ] toWatch.forEach(item => { $(`#${item.htmlId}`).on('change', e => { const value = $(`#${item.htmlId}`).val() item .filterKey .forEach( key => filterJobs({ key, value }) ) }) }) $('#keyword').on('input', e => { const value = $('#keyword').val() $('.jobs--listing-item').forEach(job => { const filterKeys = ['labels', 'location', 'title'] const dataset = job.dataset const keys = filterKeys.map(k => k); if (!dataset) { return setClass(job) } let keep = false while (keys.length) { const key = keys.shift() if (dataset[key]) { keep = true break; } } if (!keep) { return setClass(job) } let show = false while (filterKeys.length) { const key = filterKeys.shift() const found = dataset[key] .match(new RegExp(value, 'gi')) if (found && found.length) { show = true break; } } if (!show) { return setClass(job) } $(job).removeClass('jobs--listing-hidden') }) }) $('#clearFilter').on('click', e => { $('.jobs--listing-hidden') .removeClass('jobs--listing-hidden') toWatch .forEach( item => $(`#${item.htmlId}`).val(item.clearValue || '') ) }) $('#loadMoreJobs').on('click', e => { const loadBtn = $('#loadMoreJobs') const currentNextUrl = loadBtn.attr('data-next') loadIssues(currentNextUrl) }) })
slice title
themes/backendbrasil/assets/js/jobs.js
slice title
<ide><path>hemes/backendbrasil/assets/js/jobs.js <ide> <ide> return '' <ide> } <add> <add>const jobTitle = title => title.slice ? title.slice(0, 60) : title; <ide> <ide> const generateJob = ({ id, url, title, labels, location }) => ` <ide> <article <ide> data-title="${title.replace(/^\[(.*?)\]\s?/g, '')}" <ide> > <ide> <a href="${url}" target="_blank"> <del> <h4 class="is-size-5">${title.replace(/^\[(.*?)\]\s?/g, '')}</h4> <add> <h4 class="is-size-5">${jobTitle(title.replace(/^\[(.*?)\]\s?/g, ''))}</h4> <ide> <ide> ${generateLabels(labels)} <ide>
Java
apache-2.0
c06a3d49e980df5d7b24d80ec360e70475f81757
0
clumsy/intellij-community,ibinti/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,wreckJ/intellij-community,izonder/intellij-community,Lekanich/intellij-community,samthor/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,jagguli/intellij-community,diorcety/intellij-community,dslomov/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,FHannes/intellij-community,adedayo/intellij-community,apixandru/intellij-community,retomerz/intellij-community,retomerz/intellij-community,dslomov/intellij-community,signed/intellij-community,kool79/intellij-community,clumsy/intellij-community,fnouama/intellij-community,samthor/intellij-community,petteyg/intellij-community,signed/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,holmes/intellij-community,diorcety/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,allotria/intellij-community,kdwink/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,Lekanich/intellij-community,slisson/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,semonte/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,blademainer/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,caot/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,robovm/robovm-studio,ryano144/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,blademainer/intellij-community,FHannes/intellij-community,holmes/intellij-community,kool79/intellij-community,holmes/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,slisson/intellij-community,da1z/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,asedunov/intellij-community,kool79/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,izonder/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,caot/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,ibinti/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,vladmm/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,FHannes/intellij-community,kdwink/intellij-community,signed/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,izonder/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,ibinti/intellij-community,supersven/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,samthor/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,allotria/intellij-community,slisson/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,holmes/intellij-community,diorcety/intellij-community,retomerz/intellij-community,fnouama/intellij-community,semonte/intellij-community,adedayo/intellij-community,asedunov/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,vladmm/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,apixandru/intellij-community,adedayo/intellij-community,samthor/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,apixandru/intellij-community,dslomov/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,kool79/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,allotria/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,asedunov/intellij-community,ibinti/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,blademainer/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,petteyg/intellij-community,blademainer/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,supersven/intellij-community,slisson/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,slisson/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,signed/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,amith01994/intellij-community,dslomov/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,apixandru/intellij-community,xfournet/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,semonte/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,holmes/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,supersven/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,xfournet/intellij-community,izonder/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,semonte/intellij-community,samthor/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,xfournet/intellij-community,clumsy/intellij-community,caot/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,robovm/robovm-studio,hurricup/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,youdonghai/intellij-community,samthor/intellij-community,allotria/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,apixandru/intellij-community,vladmm/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,signed/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,apixandru/intellij-community,slisson/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,holmes/intellij-community,ibinti/intellij-community,apixandru/intellij-community,kool79/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,caot/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,holmes/intellij-community,caot/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,xfournet/intellij-community,caot/intellij-community,ibinti/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,ryano144/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,retomerz/intellij-community,da1z/intellij-community,holmes/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,supersven/intellij-community,ibinti/intellij-community,kool79/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,adedayo/intellij-community,kool79/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,kdwink/intellij-community,semonte/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,wreckJ/intellij-community,supersven/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,clumsy/intellij-community,kool79/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,clumsy/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,FHannes/intellij-community,caot/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,supersven/intellij-community,izonder/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,hurricup/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,petteyg/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,holmes/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,supersven/intellij-community,supersven/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,hurricup/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,xfournet/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,supersven/intellij-community,izonder/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,fnouama/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,holmes/intellij-community,kool79/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,amith01994/intellij-community,da1z/intellij-community,adedayo/intellij-community,blademainer/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,caot/intellij-community,nicolargo/intellij-community,supersven/intellij-community,petteyg/intellij-community,signed/intellij-community,jagguli/intellij-community,asedunov/intellij-community,fitermay/intellij-community,ryano144/intellij-community,diorcety/intellij-community,petteyg/intellij-community,fnouama/intellij-community,FHannes/intellij-community,apixandru/intellij-community,signed/intellij-community,blademainer/intellij-community,da1z/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,signed/intellij-community,clumsy/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,signed/intellij-community,dslomov/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,ryano144/intellij-community,signed/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,asedunov/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.concurrency; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.util.ProgressIndicatorBase; import com.intellij.util.Consumer; import com.intellij.util.IncorrectOperationException; import com.intellij.util.Processor; import jsr166e.ForkJoinPool; import jsr166e.ForkJoinTask; import jsr166e.ForkJoinWorkerThread; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; /** * @author cdr */ public class JobLauncherImpl extends JobLauncher { private static final AtomicLong bits = new AtomicLong(); private static final ForkJoinPool.ForkJoinWorkerThreadFactory FACTORY = new ForkJoinPool.ForkJoinWorkerThreadFactory() { @Override public ForkJoinWorkerThread newThread(ForkJoinPool pool) { final int n = addThread(); ForkJoinWorkerThread thread = new ForkJoinWorkerThread(pool) { @Override protected void onTermination(Throwable exception) { finishThread(n); super.onTermination(exception); } }; thread.setName("JobScheduler FJ pool "+ n +"/"+ JobSchedulerImpl.CORES_COUNT); return thread; } private int addThread() { boolean set; int n; do { long l = bits.longValue(); long next = (l + 1) | l; n = Long.numberOfTrailingZeros(l + 1); set = bits.compareAndSet(l, next); } while (!set); return n; } private void finishThread(int n) { boolean set; do { long l = bits.get(); long next = l & ~(1L << n); set = bits.compareAndSet(l, next); } while (!set); } }; private static final ForkJoinPool pool = new ForkJoinPool(JobSchedulerImpl.CORES_COUNT, FACTORY, null, false); private static <T> boolean invokeConcurrentlyForAll(@NotNull final List<T> things, boolean runInReadAction, @NotNull final Processor<? super T> thingProcessor, @NotNull ProgressIndicator wrapper) throws ProcessCanceledException { ApplierCompleter applier = new ApplierCompleter(null, runInReadAction, wrapper, things, thingProcessor, 0, things.size(), null); try { pool.invoke(applier); if (applier.throwable != null) throw applier.throwable; } catch (ApplierCompleter.ComputationAbortedException e) { return false; } catch (RuntimeException e) { throw e; } catch (Error e) { throw e; } catch (Throwable e) { throw new RuntimeException(e); } assert applier.isDone(); return applier.completeTaskWhichFailToAcquireReadAction(); } @Override public <T> boolean invokeConcurrentlyUnderProgress(@NotNull List<? extends T>things, ProgressIndicator progress, boolean failFastOnAcquireReadAction, @NotNull final Processor<T> thingProcessor) throws ProcessCanceledException { return invokeConcurrentlyUnderProgress(things, progress, ApplicationManager.getApplication().isReadAccessAllowed(), failFastOnAcquireReadAction, thingProcessor); } @Override public <T> boolean invokeConcurrentlyUnderProgress(@NotNull final List<? extends T> things, ProgressIndicator progress, boolean runInReadAction, boolean failFastOnAcquireReadAction, @NotNull final Processor<T> thingProcessor) throws ProcessCanceledException { if (things.isEmpty()) return true; // supply our own indicator even if we haven't given one - to support cancellation final ProgressIndicator wrapper = progress == null ? new ProgressIndicatorBase() : new SensitiveProgressWrapper(progress); if (things.size() <= 1 || JobSchedulerImpl.CORES_COUNT <= 1) { final AtomicBoolean result = new AtomicBoolean(true); ProgressManager.getInstance().executeProcessUnderProgress(new Runnable() { @Override public void run() { //noinspection ForLoopReplaceableByForEach for (int i = 0; i < things.size(); i++) { T thing = things.get(i); if (!thingProcessor.process(thing)) { result.set(false); break; } } } }, wrapper); return result.get(); } return invokeConcurrentlyForAll(things, runInReadAction, thingProcessor, wrapper); } // This implementation is not really async @NotNull @Override public <T> AsyncFutureResult<Boolean> invokeConcurrentlyUnderProgressAsync(@NotNull List<? extends T> things, ProgressIndicator progress, boolean failFastOnAcquireReadAction, @NotNull Processor<T> thingProcessor) { final AsyncFutureResult<Boolean> asyncFutureResult = AsyncFutureFactory.getInstance().createAsyncFutureResult(); try { final boolean result = invokeConcurrentlyUnderProgress(things, progress, failFastOnAcquireReadAction, thingProcessor); asyncFutureResult.set(result); } catch (Throwable t) { asyncFutureResult.setException(t); } return asyncFutureResult; } @NotNull @Override public Job<Void> submitToJobThread(int priority, @NotNull final Runnable action, final Consumer<Future> onDoneCallback) { VoidForkJoinTask task = new VoidForkJoinTask(action, onDoneCallback); pool.submit(task); return task; } private static class VoidForkJoinTask extends ForkJoinTask<Void> implements Job<Void> { private final Runnable myAction; private final Consumer<Future> myOnDoneCallback; public VoidForkJoinTask(@NotNull Runnable action, @Nullable Consumer<Future> onDoneCallback) { myAction = action; myOnDoneCallback = onDoneCallback; } @Override public Void getRawResult() { return null; } @Override protected void setRawResult(Void value) { } @Override protected boolean exec() { try { myAction.run(); complete(null); // complete manually before calling callback } catch (Throwable throwable) { completeExceptionally(throwable); } finally { if (myOnDoneCallback != null) { myOnDoneCallback.consume(this); } } return true; } //////////////// Job @Override public String getTitle() { throw new IncorrectOperationException(); } @Override public boolean isCanceled() { return isCancelled(); } @Override public void addTask(@NotNull Callable<Void> task) { throw new IncorrectOperationException(); } @Override public void addTask(@NotNull Runnable task, Void result) { throw new IncorrectOperationException(); } @Override public void addTask(@NotNull Runnable task) { throw new IncorrectOperationException(); } @Override public List<Void> scheduleAndWaitForResults() throws Throwable { throw new IncorrectOperationException(); } @Override public void cancel() { cancel(true); } @Override public void schedule() { throw new IncorrectOperationException(); } @Override public void waitForCompletion(int millis) throws InterruptedException, ExecutionException, TimeoutException { get(millis, TimeUnit.MILLISECONDS); } } }
platform/platform-impl/src/com/intellij/concurrency/JobLauncherImpl.java
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.concurrency; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.util.ProgressIndicatorBase; import com.intellij.util.Consumer; import com.intellij.util.IncorrectOperationException; import com.intellij.util.Processor; import jsr166e.ForkJoinPool; import jsr166e.ForkJoinTask; import jsr166e.ForkJoinWorkerThread; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; /** * @author cdr */ public class JobLauncherImpl extends JobLauncher { private static final AtomicLong bits = new AtomicLong(); private static final ForkJoinPool.ForkJoinWorkerThreadFactory FACTORY = new ForkJoinPool.ForkJoinWorkerThreadFactory() { @Override public ForkJoinWorkerThread newThread(ForkJoinPool pool) { final int n = addThread(); ForkJoinWorkerThread thread = new ForkJoinWorkerThread(pool) { @Override protected void onTermination(Throwable exception) { finishThread(n); super.onTermination(exception); } }; thread.setName("JobScheduler FJ pool "+ n +"/"+ JobSchedulerImpl.CORES_COUNT); return thread; } private int addThread() { boolean set; int n; do { long l = bits.longValue(); long next = (l + 1) | l; n = Long.numberOfTrailingZeros(l + 1); set = bits.compareAndSet(l, next); } while (!set); return n; } private void finishThread(int n) { boolean set; do { long l = bits.get(); long next = l & ~(1L << n); set = bits.compareAndSet(l, next); } while (!set); } }; private static final ForkJoinPool pool = new ForkJoinPool(JobSchedulerImpl.CORES_COUNT, FACTORY, null, false); private static <T> boolean invokeConcurrentlyForAll(@NotNull final List<T> things, boolean runInReadAction, @NotNull final Processor<? super T> thingProcessor, @NotNull ProgressIndicator wrapper) throws ProcessCanceledException { ApplierCompleter applier = new ApplierCompleter(null, runInReadAction, wrapper, things, thingProcessor, 0, things.size(), null); try { pool.invoke(applier); if (applier.throwable != null) throw applier.throwable; } catch (ApplierCompleter.ComputationAbortedException e) { return false; } catch (RuntimeException e) { throw e; } catch (Error e) { throw e; } catch (Throwable e) { throw new RuntimeException(e); } assert applier.isDone(); return applier.completeTaskWhichFailToAcquireReadAction(); } @Override public <T> boolean invokeConcurrentlyUnderProgress(@NotNull List<? extends T>things, ProgressIndicator progress, boolean failFastOnAcquireReadAction, @NotNull final Processor<T> thingProcessor) throws ProcessCanceledException { return invokeConcurrentlyUnderProgress(things, progress, ApplicationManager.getApplication().isReadAccessAllowed(), failFastOnAcquireReadAction, thingProcessor); } @Override public <T> boolean invokeConcurrentlyUnderProgress(@NotNull final List<? extends T> things, ProgressIndicator progress, boolean runInReadAction, boolean failFastOnAcquireReadAction, @NotNull final Processor<T> thingProcessor) throws ProcessCanceledException { if (things.isEmpty()) return true; // supply our own indicator even if we haven't given one - to support cancellation final ProgressIndicator wrapper = progress == null ? new ProgressIndicatorBase() : new SensitiveProgressWrapper(progress); if (things.size() <= 1 || JobSchedulerImpl.CORES_COUNT <= 2) { final AtomicBoolean result = new AtomicBoolean(true); ProgressManager.getInstance().executeProcessUnderProgress(new Runnable() { @Override public void run() { //noinspection ForLoopReplaceableByForEach for (int i = 0; i < things.size(); i++) { T thing = things.get(i); if (!thingProcessor.process(thing)) { result.set(false); break; } } } }, wrapper); return result.get(); } return invokeConcurrentlyForAll(things, runInReadAction, thingProcessor, wrapper); } // This implementation is not really async @NotNull @Override public <T> AsyncFutureResult<Boolean> invokeConcurrentlyUnderProgressAsync(@NotNull List<? extends T> things, ProgressIndicator progress, boolean failFastOnAcquireReadAction, @NotNull Processor<T> thingProcessor) { final AsyncFutureResult<Boolean> asyncFutureResult = AsyncFutureFactory.getInstance().createAsyncFutureResult(); try { final boolean result = invokeConcurrentlyUnderProgress(things, progress, failFastOnAcquireReadAction, thingProcessor); asyncFutureResult.set(result); } catch (Throwable t) { asyncFutureResult.setException(t); } return asyncFutureResult; } @NotNull @Override public Job<Void> submitToJobThread(int priority, @NotNull final Runnable action, final Consumer<Future> onDoneCallback) { VoidForkJoinTask task = new VoidForkJoinTask(action, onDoneCallback); pool.submit(task); return task; } private static class VoidForkJoinTask extends ForkJoinTask<Void> implements Job<Void> { private final Runnable myAction; private final Consumer<Future> myOnDoneCallback; public VoidForkJoinTask(@NotNull Runnable action, @Nullable Consumer<Future> onDoneCallback) { myAction = action; myOnDoneCallback = onDoneCallback; } @Override public Void getRawResult() { return null; } @Override protected void setRawResult(Void value) { } @Override protected boolean exec() { try { myAction.run(); complete(null); // complete manually before calling callback } catch (Throwable throwable) { completeExceptionally(throwable); } finally { if (myOnDoneCallback != null) { myOnDoneCallback.consume(this); } } return true; } //////////////// Job @Override public String getTitle() { throw new IncorrectOperationException(); } @Override public boolean isCanceled() { return isCancelled(); } @Override public void addTask(@NotNull Callable<Void> task) { throw new IncorrectOperationException(); } @Override public void addTask(@NotNull Runnable task, Void result) { throw new IncorrectOperationException(); } @Override public void addTask(@NotNull Runnable task) { throw new IncorrectOperationException(); } @Override public List<Void> scheduleAndWaitForResults() throws Throwable { throw new IncorrectOperationException(); } @Override public void cancel() { cancel(true); } @Override public void schedule() { throw new IncorrectOperationException(); } @Override public void waitForCompletion(int millis) throws InterruptedException, ExecutionException, TimeoutException { get(millis, TimeUnit.MILLISECONDS); } } }
allow to fork on two cores (virtualized environments often offer as many)
platform/platform-impl/src/com/intellij/concurrency/JobLauncherImpl.java
allow to fork on two cores (virtualized environments often offer as many)
<ide><path>latform/platform-impl/src/com/intellij/concurrency/JobLauncherImpl.java <ide> // supply our own indicator even if we haven't given one - to support cancellation <ide> final ProgressIndicator wrapper = progress == null ? new ProgressIndicatorBase() : new SensitiveProgressWrapper(progress); <ide> <del> if (things.size() <= 1 || JobSchedulerImpl.CORES_COUNT <= 2) { <add> if (things.size() <= 1 || JobSchedulerImpl.CORES_COUNT <= 1) { <ide> final AtomicBoolean result = new AtomicBoolean(true); <ide> ProgressManager.getInstance().executeProcessUnderProgress(new Runnable() { <ide> @Override
Java
apache-2.0
bdeffa4b24f00a6b18cca6550963ff199b48e19d
0
grgrzybek/karaf,grgrzybek/karaf,grgrzybek/karaf
/* * 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.karaf.shell.commands.impl; import org.apache.karaf.shell.commands.Argument; import org.apache.karaf.shell.commands.Command; import org.apache.karaf.shell.console.AbstractAction; import org.apache.karaf.shell.console.SessionProperties; /** * Command to change the completion mode while using the shell console. */ @Command(scope = "shell", name = "completion", description = "Display or change the completion mode on the current console session.") public class CompletionAction extends AbstractAction { @Argument(index = 0, name = "mode", description = "The completion mode to set. The valid completion modes are: global, first, subshell.", required = false, multiValued = false) String mode; protected Object doExecute() throws Exception { if (mode == null) { System.out.println(session.get(SessionProperties.COMPLETION_MODE)); return null; } if (!mode.equalsIgnoreCase("global") && !mode.equalsIgnoreCase("first") && !mode.equalsIgnoreCase("subshell")) { System.err.println("The completion mode is not correct. The valid modes are: global, first, subshell. See documentation for details."); return null; } mode = mode.toUpperCase(); session.put(SessionProperties.COMPLETION_MODE, mode); return null; } }
shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/CompletionAction.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.karaf.shell.commands.impl; import org.apache.karaf.shell.commands.Argument; import org.apache.karaf.shell.commands.Command; import org.apache.karaf.shell.console.AbstractAction; import org.apache.karaf.shell.console.SessionProperties; /** * Command to change the completion mode while using the shell console. */ @Command(scope = "shell", name = "completion", description = "Change the completion mode on the current console session.") public class CompletionAction extends AbstractAction { @Argument(index = 0, name = "mode", description = "", required = true, multiValued = false) String mode; protected Object doExecute() throws Exception { if (!mode.equalsIgnoreCase("global") && !mode.equalsIgnoreCase("first") && !mode.equalsIgnoreCase("subshell")) { System.err.println("The completion mode is not correct. The valid modes are: global, first, subshell. See documentation for details."); return null; } session.put(SessionProperties.COMPLETION_MODE, mode); return null; } }
[KARAF-2496] Improvements on the shell:completion command git-svn-id: 71d8a689455c5fbb0f077bc40adcfc391e14cb9d@1530935 13f79535-47bb-0310-9956-ffa450edef68
shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/CompletionAction.java
[KARAF-2496] Improvements on the shell:completion command
<ide><path>hell/commands/src/main/java/org/apache/karaf/shell/commands/impl/CompletionAction.java <ide> /** <ide> * Command to change the completion mode while using the shell console. <ide> */ <del>@Command(scope = "shell", name = "completion", description = "Change the completion mode on the current console session.") <add>@Command(scope = "shell", name = "completion", description = "Display or change the completion mode on the current console session.") <ide> public class CompletionAction extends AbstractAction { <ide> <del> @Argument(index = 0, name = "mode", description = "", required = true, multiValued = false) <add> @Argument(index = 0, name = "mode", description = "The completion mode to set. The valid completion modes are: global, first, subshell.", required = false, multiValued = false) <ide> String mode; <ide> <ide> protected Object doExecute() throws Exception { <add> if (mode == null) { <add> System.out.println(session.get(SessionProperties.COMPLETION_MODE)); <add> return null; <add> } <add> <ide> if (!mode.equalsIgnoreCase("global") && !mode.equalsIgnoreCase("first") && !mode.equalsIgnoreCase("subshell")) { <ide> System.err.println("The completion mode is not correct. The valid modes are: global, first, subshell. See documentation for details."); <ide> return null; <ide> } <add> <add> mode = mode.toUpperCase(); <ide> <ide> session.put(SessionProperties.COMPLETION_MODE, mode); <ide> return null;
Java
apache-2.0
a1a4e0b623b69ad0f092019e5b213f8da1ddd1c6
0
ORRTIZ/omultisafepay
/******************************************************************************* * (C) Copyright 2015 Somonar B.V. * Licensed under the Apache License 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.somonar.payment.omultisafepay; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigDecimal; import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.UtilDateTime; import org.ofbiz.base.util.UtilHttp; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.base.util.UtilProperties; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.ofbiz.entity.Delegator; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.GenericValue; import org.ofbiz.entity.transaction.GenericTransactionException; import org.ofbiz.entity.transaction.TransactionUtil; import org.ofbiz.order.order.*; import org.ofbiz.product.store.ProductStoreWorker; import org.ofbiz.service.GenericServiceException; import org.ofbiz.service.LocalDispatcher; import org.ofbiz.service.ModelService; import org.ofbiz.entity.transaction.GenericTransactionException; import org.ofbiz.entity.transaction.TransactionUtil; public class MultiSafepayClient { public static final String module = MultiSafepayClient.class.getName(); public static final String resource = "AccountingUiLabels"; public static final String resourceErr = "AccountingErrorUiLabels"; public static final String commonResource = "CommonUiLabels"; public static final String oMultiSafepayResource = "omultisafepay-UiLabels"; /** Initiate MultisafePayEvents Request * @throws IOException */ public static String cancelResponse (HttpServletRequest request, HttpServletResponse response) throws IOException { String orderId = request.getParameter("transactionid"); request.setAttribute("orderId", orderId); return "success"; } public static String notifyResponse (HttpServletRequest request, HttpServletResponse response) throws IOException { String orderId = request.getParameter("transactionid"); request.setAttribute("orderId", orderId); return "success"; } public static String redirectResponse (HttpServletRequest request, HttpServletResponse response) throws IOException { Locale locale = UtilHttp.getLocale(request); Delegator delegator = (Delegator) request.getAttribute("delegator"); LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher"); GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin"); Map<String,Object> paramMap = UtilHttp.getParameterMap(request); Debug.logInfo("in" + module + " - paramMap is: " + paramMap,module); Debug.logInfo("in" + module + " locale is: " + locale,module); Debug.logInfo("in" + module + " delegator is: " + delegator.getDelegatorName(), module); Debug.logInfo("in" + module + " tenantId is: " + delegator.getDelegatorTenantId(), module); String orderId = request.getParameter("transactionid"); Debug.logInfo("in" + module + " orderId is: " + orderId,module); // get the order header GenericValue orderHeader = null; try { orderHeader = delegator.findOne("OrderHeader", UtilMisc.toMap("orderId", orderId), false); } catch (GenericEntityException e) { Debug.logError(e, "Cannot get the order header for order: " + orderId, module); request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resourceErr, "MultisafePayEvents.problemsGettingOrderHeader", locale)); return "error"; } // get the order total BigDecimal bd = new BigDecimal("100.0"); bd.setScale(0); bd.stripTrailingZeros(); String orderTotalLong = orderHeader.getBigDecimal("grandTotal").multiply(bd).toPlainString(); int index_point = orderTotalLong.indexOf("."); orderTotalLong = orderTotalLong.substring(0, index_point); String orderTotal = orderHeader.getBigDecimal("grandTotal").toPlainString(); String currencyUom = orderHeader.getString("currencyUom"); // attempt to start a transaction boolean okay = true; boolean beganTransaction = false; try { beganTransaction = TransactionUtil.begin(); okay = OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId); Debug.logInfo("okay is: " + okay,module); if (okay) { // set the payment preference okay = setPaymentPreferences(delegator, dispatcher, userLogin, orderId, request, orderTotal); } } catch (Exception e) { String errMsg = "Error handling multisafepay redirect"; Debug.logError(e, errMsg, module); try { TransactionUtil.rollback(beganTransaction, errMsg, e); } catch (GenericTransactionException gte2) { Debug.logError(gte2, "Unable to rollback transaction", module); } } finally { if (!okay) { try { TransactionUtil.rollback(beganTransaction, "Failure in processing multisafepay redirect", null); } catch (GenericTransactionException gte) { Debug.logError(gte, "Unable to rollback transaction", module); } } else { try { TransactionUtil.commit(beganTransaction); } catch (GenericTransactionException gte) { Debug.logError(gte, "Unable to commit transaction", module); } } } if (okay) { // attempt to release the offline hold on the order (workflow) OrderChangeHelper.releaseInitialOrderHold(dispatcher, orderId); } request.setAttribute("orderId", orderId); return "success"; } private static boolean setPaymentPreference(LocalDispatcher dispatcher, GenericValue userLogin, GenericValue paymentPreference, HttpServletRequest request, String orderTotal) { Locale locale = UtilHttp.getLocale(request); String paymentType = "Betaling klant"; String paymentAmount = orderTotal; String paymentStatus = "Pending"; String transactionId = ""; List <GenericValue> toStore = new LinkedList <GenericValue> (); // PayPal returns the timestamp in the format 'hh:mm:ss Jan 1, 2000 PST' // Parse this into a valid Timestamp Object Calendar cal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss MMM d, yyyy z"); java.sql.Timestamp authDate = null; try { authDate = new java.sql.Timestamp(sdf.parse(sdf.format(cal.getTime())).getTime()); } catch (ParseException e) { Debug.logError(e, "Cannot parse date string: " + sdf.format(cal.getTime()), module); authDate = UtilDateTime.nowTimestamp(); } catch (NullPointerException e) { Debug.logError(e, "Cannot parse date string: " + sdf.format(cal.getTime()), module); authDate = UtilDateTime.nowTimestamp(); } paymentPreference.set("maxAmount", new BigDecimal(paymentAmount)); if (paymentStatus.equals("Completed")) { paymentPreference.set("statusId", "PAYMENT_RECEIVED"); } else if (paymentStatus.equals("Pending")) { paymentPreference.set("statusId", "PAYMENT_NOT_RECEIVED"); } else { paymentPreference.set("statusId", "PAYMENT_CANCELLED"); } toStore.add(paymentPreference); Delegator delegator = paymentPreference.getDelegator(); // create the PaymentGatewayResponse String responseId = delegator.getNextSeqId("PaymentGatewayResponse"); GenericValue response = delegator.makeValue("PaymentGatewayResponse"); response.set("paymentGatewayResponseId", responseId); response.set("paymentServiceTypeEnumId", "PRDS_PAY_EXTERNAL"); response.set("orderPaymentPreferenceId", paymentPreference.get("orderPaymentPreferenceId")); response.set("paymentMethodTypeId", paymentPreference.get("paymentMethodTypeId")); response.set("paymentMethodId", paymentPreference.get("paymentMethodId")); // set the auth info response.set("amount", new BigDecimal(paymentAmount)); response.set("referenceNum", transactionId); response.set("gatewayCode", paymentStatus); response.set("gatewayFlag", paymentStatus.substring(0,1)); response.set("gatewayMessage", paymentType); response.set("transactionDate", authDate); toStore.add(response); try { delegator.storeAll(toStore); } catch (GenericEntityException e) { Debug.logError(e, "Cannot set payment preference/payment info", module); return false; } // create a payment record too Map <String, Object> results = null; try { String comment = UtilProperties.getMessage(oMultiSafepayResource, "PaymentTransactionViaMultiSafepay", locale); results = dispatcher.runSync("createPaymentFromPreference", UtilMisc.toMap("userLogin", userLogin, "orderPaymentPreferenceId", paymentPreference.get("orderPaymentPreferenceId"), "comments", comment)); } catch (GenericServiceException e) { Debug.logError(e, "Failed to execute service createPaymentFromPreference", module); request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resourceErr, "payPalEvents.failedToExecuteServiceCreatePaymentFromPreference", locale)); return false; } if ((results == null) || (results.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_ERROR))) { Debug.logError((String) results.get(ModelService.ERROR_MESSAGE), module); request.setAttribute("_ERROR_MESSAGE_", results.get(ModelService.ERROR_MESSAGE)); return false; } return true; } private static boolean setPaymentPreferences(Delegator delegator, LocalDispatcher dispatcher, GenericValue userLogin, String orderId, HttpServletRequest request, String orderTotal) { Debug.logVerbose("Setting payment preferences..", module); List <GenericValue> paymentPrefs = null; try { Map <String, String> paymentFields = UtilMisc.toMap("orderId", orderId, "statusId", "PAYMENT_NOT_RECEIVED"); paymentPrefs = delegator.findByAnd("OrderPaymentPreference", paymentFields, null, false); } catch (GenericEntityException e) { Debug.logError(e, "Cannot get payment preferences for order #" + orderId, module); return false; } if (paymentPrefs.size() > 0) { Iterator <GenericValue> i = paymentPrefs.iterator(); while (i.hasNext()) { GenericValue pref = i.next(); boolean okay = setPaymentPreference(dispatcher, userLogin, pref, request, orderTotal); if (!okay) return false; } } return true; } }
src/com/somonar/payment/omultisafepay/MultiSafepayClient.java
/******************************************************************************* * (C) Copyright 2015 Somonar B.V. * Licensed under the Apache License 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.somonar.payment.omultisafepay; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigDecimal; import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.UtilDateTime; import org.ofbiz.base.util.UtilHttp; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.base.util.UtilProperties; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.ofbiz.entity.Delegator; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.GenericValue; import org.ofbiz.entity.transaction.GenericTransactionException; import org.ofbiz.entity.transaction.TransactionUtil; import org.ofbiz.order.order.*; import org.ofbiz.product.store.ProductStoreWorker; import org.ofbiz.service.GenericServiceException; import org.ofbiz.service.LocalDispatcher; import org.ofbiz.service.ModelService; import org.ofbiz.entity.transaction.GenericTransactionException; import org.ofbiz.entity.transaction.TransactionUtil; public class MultiSafepayClient { public static final String module = MultiSafepayClient.class.getName(); public static final String resource = "AccountingUiLabels"; public static final String resourceErr = "AccountingErrorUiLabels"; public static final String commonResource = "CommonUiLabels"; public static final string oMultiSafepayResource = "omultisafepay-UiLabels"; /** Initiate MultisafePayEvents Request * @throws IOException */ public static String cancelResponse (HttpServletRequest request, HttpServletResponse response) throws IOException { String orderId = request.getParameter("transactionid"); request.setAttribute("orderId", orderId); return "success"; } public static String notifyResponse (HttpServletRequest request, HttpServletResponse response) throws IOException { String orderId = request.getParameter("transactionid"); request.setAttribute("orderId", orderId); return "success"; } public static String redirectResponse (HttpServletRequest request, HttpServletResponse response) throws IOException { Locale locale = UtilHttp.getLocale(request); Delegator delegator = (Delegator) request.getAttribute("delegator"); LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher"); GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin"); Map<String,Object> paramMap = UtilHttp.getParameterMap(request); Debug.logInfo("in" + module + " - paramMap is: " + paramMap,module); Debug.logInfo("in" + module + " locale is: " + locale,module); Debug.logInfo("in" + module + " delegator is: " + delegator.getDelegatorName(), module); Debug.logInfo("in" + module + " tenantId is: " + delegator.getDelegatorTenantId(), module); String orderId = request.getParameter("transactionid"); Debug.logInfo("in" + module + " orderId is: " + orderId,module); // get the order header GenericValue orderHeader = null; try { orderHeader = delegator.findOne("OrderHeader", UtilMisc.toMap("orderId", orderId), false); } catch (GenericEntityException e) { Debug.logError(e, "Cannot get the order header for order: " + orderId, module); request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resourceErr, "MultisafePayEvents.problemsGettingOrderHeader", locale)); return "error"; } // get the order total BigDecimal bd = new BigDecimal("100.0"); bd.setScale(0); bd.stripTrailingZeros(); String orderTotalLong = orderHeader.getBigDecimal("grandTotal").multiply(bd).toPlainString(); int index_point = orderTotalLong.indexOf("."); orderTotalLong = orderTotalLong.substring(0, index_point); String orderTotal = orderHeader.getBigDecimal("grandTotal").toPlainString(); String currencyUom = orderHeader.getString("currencyUom"); // attempt to start a transaction boolean okay = true; boolean beganTransaction = false; try { beganTransaction = TransactionUtil.begin(); okay = OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId); Debug.logInfo("okay is: " + okay,module); if (okay) { // set the payment preference okay = setPaymentPreferences(delegator, dispatcher, userLogin, orderId, request, orderTotal); } } catch (Exception e) { String errMsg = "Error handling multisafepay redirect"; Debug.logError(e, errMsg, module); try { TransactionUtil.rollback(beganTransaction, errMsg, e); } catch (GenericTransactionException gte2) { Debug.logError(gte2, "Unable to rollback transaction", module); } } finally { if (!okay) { try { TransactionUtil.rollback(beganTransaction, "Failure in processing multisafepay redirect", null); } catch (GenericTransactionException gte) { Debug.logError(gte, "Unable to rollback transaction", module); } } else { try { TransactionUtil.commit(beganTransaction); } catch (GenericTransactionException gte) { Debug.logError(gte, "Unable to commit transaction", module); } } } if (okay) { // attempt to release the offline hold on the order (workflow) OrderChangeHelper.releaseInitialOrderHold(dispatcher, orderId); } request.setAttribute("orderId", orderId); return "success"; } private static boolean setPaymentPreference(LocalDispatcher dispatcher, GenericValue userLogin, GenericValue paymentPreference, HttpServletRequest request, String orderTotal) { Locale locale = UtilHttp.getLocale(request); String paymentType = "Betaling klant"; String paymentAmount = orderTotal; String paymentStatus = "Pending"; String transactionId = ""; List <GenericValue> toStore = new LinkedList <GenericValue> (); // PayPal returns the timestamp in the format 'hh:mm:ss Jan 1, 2000 PST' // Parse this into a valid Timestamp Object Calendar cal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss MMM d, yyyy z"); java.sql.Timestamp authDate = null; try { authDate = new java.sql.Timestamp(sdf.parse(sdf.format(cal.getTime())).getTime()); } catch (ParseException e) { Debug.logError(e, "Cannot parse date string: " + sdf.format(cal.getTime()), module); authDate = UtilDateTime.nowTimestamp(); } catch (NullPointerException e) { Debug.logError(e, "Cannot parse date string: " + sdf.format(cal.getTime()), module); authDate = UtilDateTime.nowTimestamp(); } paymentPreference.set("maxAmount", new BigDecimal(paymentAmount)); if (paymentStatus.equals("Completed")) { paymentPreference.set("statusId", "PAYMENT_RECEIVED"); } else if (paymentStatus.equals("Pending")) { paymentPreference.set("statusId", "PAYMENT_NOT_RECEIVED"); } else { paymentPreference.set("statusId", "PAYMENT_CANCELLED"); } toStore.add(paymentPreference); Delegator delegator = paymentPreference.getDelegator(); // create the PaymentGatewayResponse String responseId = delegator.getNextSeqId("PaymentGatewayResponse"); GenericValue response = delegator.makeValue("PaymentGatewayResponse"); response.set("paymentGatewayResponseId", responseId); response.set("paymentServiceTypeEnumId", "PRDS_PAY_EXTERNAL"); response.set("orderPaymentPreferenceId", paymentPreference.get("orderPaymentPreferenceId")); response.set("paymentMethodTypeId", paymentPreference.get("paymentMethodTypeId")); response.set("paymentMethodId", paymentPreference.get("paymentMethodId")); // set the auth info response.set("amount", new BigDecimal(paymentAmount)); response.set("referenceNum", transactionId); response.set("gatewayCode", paymentStatus); response.set("gatewayFlag", paymentStatus.substring(0,1)); response.set("gatewayMessage", paymentType); response.set("transactionDate", authDate); toStore.add(response); try { delegator.storeAll(toStore); } catch (GenericEntityException e) { Debug.logError(e, "Cannot set payment preference/payment info", module); return false; } // create a payment record too Map <String, Object> results = null; try { String comment = UtilProperties.getMessage(oMultiSafepayResource, "PaymentTransactionViaMultiSafepay", locale); results = dispatcher.runSync("createPaymentFromPreference", UtilMisc.toMap("userLogin", userLogin, "orderPaymentPreferenceId", paymentPreference.get("orderPaymentPreferenceId"), "comments", comment)); } catch (GenericServiceException e) { Debug.logError(e, "Failed to execute service createPaymentFromPreference", module); request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resourceErr, "payPalEvents.failedToExecuteServiceCreatePaymentFromPreference", locale)); return false; } if ((results == null) || (results.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_ERROR))) { Debug.logError((String) results.get(ModelService.ERROR_MESSAGE), module); request.setAttribute("_ERROR_MESSAGE_", results.get(ModelService.ERROR_MESSAGE)); return false; } return true; } private static boolean setPaymentPreferences(Delegator delegator, LocalDispatcher dispatcher, GenericValue userLogin, String orderId, HttpServletRequest request, String orderTotal) { Debug.logVerbose("Setting payment preferences..", module); List <GenericValue> paymentPrefs = null; try { Map <String, String> paymentFields = UtilMisc.toMap("orderId", orderId, "statusId", "PAYMENT_NOT_RECEIVED"); paymentPrefs = delegator.findByAnd("OrderPaymentPreference", paymentFields, null, false); } catch (GenericEntityException e) { Debug.logError(e, "Cannot get payment preferences for order #" + orderId, module); return false; } if (paymentPrefs.size() > 0) { Iterator <GenericValue> i = paymentPrefs.iterator(); while (i.hasNext()) { GenericValue pref = i.next(); boolean okay = setPaymentPreference(dispatcher, userLogin, pref, request, orderTotal); if (!okay) return false; } } return true; } }
fixed typo
src/com/somonar/payment/omultisafepay/MultiSafepayClient.java
fixed typo
<ide><path>rc/com/somonar/payment/omultisafepay/MultiSafepayClient.java <ide> public static final String resource = "AccountingUiLabels"; <ide> public static final String resourceErr = "AccountingErrorUiLabels"; <ide> public static final String commonResource = "CommonUiLabels"; <del> public static final string oMultiSafepayResource = "omultisafepay-UiLabels"; <add> public static final String oMultiSafepayResource = "omultisafepay-UiLabels"; <ide> <ide> /** Initiate MultisafePayEvents Request <ide> * @throws IOException */
Java
apache-2.0
e327e2e8ad1ac14093f6ced3692fe356758945cd
0
bluekeyes/sshj,Juraldinio/sshj,Boris-de/sshj,joprsal/sshj,hierynomus/sshj,juddgaddie/sshj,cloudera/sshj,hierynomus/sshj
/* * Copyright 2010 Shikhar Bhushan * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.schmizz.sshj.common; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class StreamCopier extends Thread { private static final Logger LOG = LoggerFactory.getLogger(StreamCopier.class); public interface ErrorCallback { void onError(IOException ioe); } public static ErrorCallback closeOnErrorCallback(final Closeable... toClose) { return new ErrorCallback() { public void onError(IOException ioe) { IOUtils.closeQuietly(toClose); } }; } public static long copy(InputStream in, OutputStream out, int bufSize, boolean keepFlushing) throws IOException { long count = 0; final long startTime = System.currentTimeMillis(); final byte[] buf = new byte[bufSize]; int read; while ((read = in.read(buf)) != -1) { out.write(buf, 0, read); count += read; if (keepFlushing) out.flush(); } if (!keepFlushing) out.flush(); final double sizeKiB = count / 1024.0; final double timeSeconds = (System.currentTimeMillis() - startTime) / 1000.0; LOG.info(sizeKiB + " KiB transferred in {} seconds ({} KiB/s)", timeSeconds, (sizeKiB / timeSeconds)); return count; } public static String copyStreamToString(InputStream stream) throws IOException { final StringBuilder sb = new StringBuilder(); int read; while ((read = stream.read()) != -1) sb.append((char) read); return sb.toString(); } private final Logger log; private final InputStream in; private final OutputStream out; private int bufSize = 1; private boolean keepFlushing = true; private ErrorCallback errCB = new ErrorCallback() { public void onError(IOException ioe) { } }; // Default null cb public StreamCopier(String name, InputStream in, OutputStream out) { this.in = in; this.out = out; setName("streamCopier"); log = LoggerFactory.getLogger(name); } public StreamCopier bufSize(int size) { bufSize = size; return this; } public StreamCopier keepFlushing(boolean choice) { keepFlushing = choice; return this; } public StreamCopier daemon(boolean choice) { setDaemon(choice); return this; } public StreamCopier errorCallback(ErrorCallback errCB) { this.errCB = errCB; return this; } @Override public void run() { try { log.debug("Wil pipe from {} to {}", in, out); copy(in, out, bufSize, keepFlushing); log.debug("EOF on {}", in); } catch (IOException ioe) { log.error("In pipe from {} to {}: " + ioe.toString(), in, out); errCB.onError(ioe); } } }
src/main/java/net/schmizz/sshj/common/StreamCopier.java
/* * Copyright 2010 Shikhar Bhushan * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.schmizz.sshj.common; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; public class StreamCopier extends Thread { private static final Logger LOG = LoggerFactory.getLogger(StreamCopier.class); public interface ErrorCallback { void onError(IOException ioe); } public static ErrorCallback closeOnErrorCallback(final Closeable... toClose) { final Closeable[] closeables = Arrays.copyOf(toClose, toClose.length); return new ErrorCallback() { public void onError(IOException ioe) { IOUtils.closeQuietly(closeables); } }; } public static long copy(InputStream in, OutputStream out, int bufSize, boolean keepFlushing) throws IOException { long count = 0; final long startTime = System.currentTimeMillis(); final byte[] buf = new byte[bufSize]; int read; while ((read = in.read(buf)) != -1) { out.write(buf, 0, read); count += read; if (keepFlushing) out.flush(); } if (!keepFlushing) out.flush(); final double sizeKiB = count / 1024.0; final double timeSeconds = (System.currentTimeMillis() - startTime) / 1000.0; LOG.info(sizeKiB + " KiB transferred in {} seconds ({} KiB/s)", timeSeconds, (sizeKiB / timeSeconds)); return count; } public static String copyStreamToString(InputStream stream) throws IOException { final StringBuilder sb = new StringBuilder(); int read; while ((read = stream.read()) != -1) sb.append((char) read); return sb.toString(); } private final Logger log; private final InputStream in; private final OutputStream out; private int bufSize = 1; private boolean keepFlushing = true; private ErrorCallback errCB = new ErrorCallback() { public void onError(IOException ioe) { } }; // Default null cb public StreamCopier(String name, InputStream in, OutputStream out) { this.in = in; this.out = out; setName("streamCopier"); log = LoggerFactory.getLogger(name); } public StreamCopier bufSize(int size) { bufSize = size; return this; } public StreamCopier keepFlushing(boolean choice) { keepFlushing = choice; return this; } public StreamCopier daemon(boolean choice) { setDaemon(choice); return this; } public StreamCopier errorCallback(ErrorCallback errCB) { this.errCB = errCB; return this; } @Override public void run() { try { log.debug("Wil pipe from {} to {}", in, out); copy(in, out, bufSize, keepFlushing); log.debug("EOF on {}", in); } catch (IOException ioe) { log.error("In pipe from {} to {}: " + ioe.toString(), in, out); errCB.onError(ioe); } } }
no need to copy
src/main/java/net/schmizz/sshj/common/StreamCopier.java
no need to copy
<ide><path>rc/main/java/net/schmizz/sshj/common/StreamCopier.java <ide> import java.io.IOException; <ide> import java.io.InputStream; <ide> import java.io.OutputStream; <del>import java.util.Arrays; <ide> <ide> public class StreamCopier <ide> extends Thread { <ide> } <ide> <ide> public static ErrorCallback closeOnErrorCallback(final Closeable... toClose) { <del> final Closeable[] closeables = Arrays.copyOf(toClose, toClose.length); <ide> return new ErrorCallback() { <ide> public void onError(IOException ioe) { <del> IOUtils.closeQuietly(closeables); <add> IOUtils.closeQuietly(toClose); <ide> } <ide> }; <ide> }
Java
lgpl-2.1
72fbd4718a39d058ae17ba450a8bac01bd4f39cb
0
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,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.chart; import java.util.HashMap; import java.util.Map; import org.junit.Assert; import org.junit.Test; import org.xwiki.chart.internal.DefaultChartGenerator; import org.xwiki.chart.model.ChartModel; import org.xwiki.chart.model.DefaultChartModel; import org.xwiki.test.AbstractComponentTestCase; /** * Test case for {@link DefaultChartGenerator}. * * @version $Id$ * @since 2.0M1 */ public class DefaultChartGeneratorTest extends AbstractComponentTestCase { /** * The {@link ChartGenerator} component. */ private ChartGenerator chartGenerator; /** * The {@link ChartModel}. */ private ChartModel model; /** * {@inheritDoc} */ protected void registerComponents() throws Exception { Short dataArray[][] = { {1, 2, 3}, {1, 3, 5}}; String rowHeaders[] = {"1", "2"}; String columnHeaders[] = {"1", "2", "3"}; this.model = new DefaultChartModel(dataArray, rowHeaders, columnHeaders); this.chartGenerator = getComponentManager().lookup(ChartGenerator.class); } /** * Test pie chart generation. * * @throws ChartGeneratorException if an error occurs while generating the chart. */ @Test public final void testPieChart() throws ChartGeneratorException { Map<String, String> parameters = new HashMap<String, String>(); parameters.put(ChartGenerator.TITLE_PARAM, "Test pie chart"); parameters.put(ChartGenerator.TYPE_PARAM, "pie"); parameters.put(ChartGenerator.SERIES_PARAM, "rows"); byte[] chart = chartGenerator.generate(model, parameters); Assert.assertNotNull(chart); } /** * Test bar chart generation. * * @throws ChartGeneratorException if an error occurs while generating the chart. */ @Test public final void testBarChart() throws ChartGeneratorException { Map<String, String> parameters = new HashMap<String, String>(); parameters.put(ChartGenerator.TITLE_PARAM, "Test bar chart"); parameters.put(ChartGenerator.TYPE_PARAM, "bar"); parameters.put(ChartGenerator.SERIES_PARAM, "rows"); byte[] chart = chartGenerator.generate(model, parameters); Assert.assertNotNull(chart); } /** * Test line chart generation. * * @throws ChartGeneratorException if an error occurs while generating the chart. */ @Test public final void testLineChart() throws ChartGeneratorException { Map<String, String> parameters = new HashMap<String, String>(); parameters.put(ChartGenerator.TITLE_PARAM, "Test line chart"); parameters.put(ChartGenerator.TYPE_PARAM, "line"); parameters.put(ChartGenerator.SERIES_PARAM, "rows"); byte[] chart = chartGenerator.generate(model, parameters); Assert.assertNotNull(chart); } /** * Test area chart generation. * * @throws ChartGeneratorException if an error occurs while generating the chart. */ @Test public final void testAreaChart() throws ChartGeneratorException { Map<String, String> parameters = new HashMap<String, String>(); parameters.put(ChartGenerator.TITLE_PARAM, "Test area chart"); parameters.put(ChartGenerator.TYPE_PARAM, "area"); parameters.put(ChartGenerator.SERIES_PARAM, "rows"); byte[] chart = chartGenerator.generate(model, parameters); Assert.assertNotNull(chart); } }
xwiki-chart/xwiki-chart-renderer/src/test/java/org/xwiki/chart/DefaultChartGeneratorTest.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.chart; import java.util.HashMap; import java.util.Map; import org.xwiki.chart.internal.DefaultChartGenerator; import org.xwiki.chart.model.ChartModel; import org.xwiki.chart.model.DefaultChartModel; import org.xwiki.test.AbstractXWikiComponentTestCase; /** * Test case for {@link DefaultChartGenerator}. * * @version $Id$ * @since 2.0M1 */ public class DefaultChartGeneratorTest extends AbstractXWikiComponentTestCase { /** * The {@link ChartGenerator} component. */ private ChartGenerator chartGenerator; /** * The {@link ChartModel}. */ private ChartModel model; /** * {@inheritDoc} */ protected void setUp() throws Exception { super.setUp(); Short dataArray[][] = { {1, 2, 3}, {1, 3, 5}}; String rowHeaders[] = {"1", "2"}; String columnHeaders[] = {"1", "2", "3"}; this.model = new DefaultChartModel(dataArray, rowHeaders, columnHeaders); this.chartGenerator = getComponentManager().lookup(ChartGenerator.class); } /** * Test pie chart generation. * * @throws ChartGeneratorException if an error occurs while generating the chart. */ public final void testPieChart() throws ChartGeneratorException { Map<String, String> parameters = new HashMap<String, String>(); parameters.put(ChartGenerator.TITLE_PARAM, "Test pie chart"); parameters.put(ChartGenerator.TYPE_PARAM, "pie"); parameters.put(ChartGenerator.SERIES_PARAM, "rows"); byte[] chart = chartGenerator.generate(model, parameters); assertNotNull(chart); } /** * Test bar chart generation. * * @throws ChartGeneratorException if an error occurs while generating the chart. */ public final void testBarChart() throws ChartGeneratorException { Map<String, String> parameters = new HashMap<String, String>(); parameters.put(ChartGenerator.TITLE_PARAM, "Test bar chart"); parameters.put(ChartGenerator.TYPE_PARAM, "bar"); parameters.put(ChartGenerator.SERIES_PARAM, "rows"); byte[] chart = chartGenerator.generate(model, parameters); assertNotNull(chart); } /** * Test line chart generation. * * @throws ChartGeneratorException if an error occurs while generating the chart. */ public final void testLineChart() throws ChartGeneratorException { Map<String, String> parameters = new HashMap<String, String>(); parameters.put(ChartGenerator.TITLE_PARAM, "Test line chart"); parameters.put(ChartGenerator.TYPE_PARAM, "line"); parameters.put(ChartGenerator.SERIES_PARAM, "rows"); byte[] chart = chartGenerator.generate(model, parameters); assertNotNull(chart); } /** * Test area chart generation. * * @throws ChartGeneratorException if an error occurs while generating the chart. */ public final void testAreaChart() throws ChartGeneratorException { Map<String, String> parameters = new HashMap<String, String>(); parameters.put(ChartGenerator.TITLE_PARAM, "Test area chart"); parameters.put(ChartGenerator.TYPE_PARAM, "area"); parameters.put(ChartGenerator.SERIES_PARAM, "rows"); byte[] chart = chartGenerator.generate(model, parameters); assertNotNull(chart); } }
Convert tests to JUnit 4 git-svn-id: d23d7a6431d93e1bdd218a46658458610974b053@35719 f329d543-caf0-0310-9063-dda96c69346f
xwiki-chart/xwiki-chart-renderer/src/test/java/org/xwiki/chart/DefaultChartGeneratorTest.java
Convert tests to JUnit 4
<ide><path>wiki-chart/xwiki-chart-renderer/src/test/java/org/xwiki/chart/DefaultChartGeneratorTest.java <ide> import java.util.HashMap; <ide> import java.util.Map; <ide> <add>import org.junit.Assert; <add>import org.junit.Test; <ide> import org.xwiki.chart.internal.DefaultChartGenerator; <ide> import org.xwiki.chart.model.ChartModel; <ide> import org.xwiki.chart.model.DefaultChartModel; <del>import org.xwiki.test.AbstractXWikiComponentTestCase; <add>import org.xwiki.test.AbstractComponentTestCase; <ide> <ide> /** <ide> * Test case for {@link DefaultChartGenerator}. <ide> * @version $Id$ <ide> * @since 2.0M1 <ide> */ <del>public class DefaultChartGeneratorTest extends AbstractXWikiComponentTestCase <add>public class DefaultChartGeneratorTest extends AbstractComponentTestCase <ide> { <ide> /** <ide> * The {@link ChartGenerator} component. <ide> /** <ide> * {@inheritDoc} <ide> */ <del> protected void setUp() throws Exception <add> protected void registerComponents() throws Exception <ide> { <del> super.setUp(); <ide> Short dataArray[][] = { {1, 2, 3}, {1, 3, 5}}; <ide> String rowHeaders[] = {"1", "2"}; <ide> String columnHeaders[] = {"1", "2", "3"}; <ide> * <ide> * @throws ChartGeneratorException if an error occurs while generating the chart. <ide> */ <add> @Test <ide> public final void testPieChart() throws ChartGeneratorException <ide> { <ide> Map<String, String> parameters = new HashMap<String, String>(); <ide> parameters.put(ChartGenerator.SERIES_PARAM, "rows"); <ide> <ide> byte[] chart = chartGenerator.generate(model, parameters); <del> assertNotNull(chart); <add> Assert.assertNotNull(chart); <ide> } <ide> <ide> /** <ide> * <ide> * @throws ChartGeneratorException if an error occurs while generating the chart. <ide> */ <add> @Test <ide> public final void testBarChart() throws ChartGeneratorException <ide> { <ide> Map<String, String> parameters = new HashMap<String, String>(); <ide> parameters.put(ChartGenerator.SERIES_PARAM, "rows"); <ide> <ide> byte[] chart = chartGenerator.generate(model, parameters); <del> assertNotNull(chart); <add> Assert.assertNotNull(chart); <ide> } <ide> <ide> /** <ide> * <ide> * @throws ChartGeneratorException if an error occurs while generating the chart. <ide> */ <add> @Test <ide> public final void testLineChart() throws ChartGeneratorException <ide> { <ide> Map<String, String> parameters = new HashMap<String, String>(); <ide> parameters.put(ChartGenerator.SERIES_PARAM, "rows"); <ide> <ide> byte[] chart = chartGenerator.generate(model, parameters); <del> assertNotNull(chart); <add> Assert.assertNotNull(chart); <ide> } <ide> <ide> /** <ide> * <ide> * @throws ChartGeneratorException if an error occurs while generating the chart. <ide> */ <add> @Test <ide> public final void testAreaChart() throws ChartGeneratorException <ide> { <ide> Map<String, String> parameters = new HashMap<String, String>(); <ide> parameters.put(ChartGenerator.SERIES_PARAM, "rows"); <ide> <ide> byte[] chart = chartGenerator.generate(model, parameters); <del> assertNotNull(chart); <add> Assert.assertNotNull(chart); <ide> } <ide> }
Java
bsd-3-clause
9474eee0aac0f42a93e2526d6fd3a2c24c18b380
0
uw-dims/tupelo,uw-dims/tupelo,uw-dims/tupelo,uw-dims/tupelo,uw-dims/tupelo
/** * Copyright © 2015, University of Washington * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of the University of Washington nor the names * of its contributors may be used to endorse or promote products * derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL UNIVERSITY OF * WASHINGTON BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package edu.uw.apl.tupelo.logging; import org.apache.log4j.Layout; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.ThrowableInformation; import java.io.PrintWriter; import java.io.StringWriter; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; /** * A log4j Layout, used by an Appender (and recall we have defined an * AMQP Appender), providing a log record format as used/requested by * Dims/DD. * At construction time, we create a uuid. This does essentially same * job as a pid, since we only expect one Layout per logging * subsystem per VM (or classloader at least) */ public class LogMonLayout extends Layout { private final UUID uuid; static private final String ISO8601 = "yyyy-MM-dd'T'HH:mm:ss.SSS000XXX"; static private String HOSTNAME = "UNKNOWN"; static { try { InetAddress ia = InetAddress.getLocalHost(); HOSTNAME = ia.getCanonicalHostName(); } catch( UnknownHostException uhe ) { } } static private SimpleDateFormat dateFormatter; static private String pidString = null; public LogMonLayout() { uuid = UUID.randomUUID(); dateFormatter = new SimpleDateFormat( ISO8601 ); if(pidString == null){ getProcessId(); } } @SuppressWarnings("restriction") /** * Attempts to get the process ID. * This can fail for a number of reasons. * Source: http://stackoverflow.com/a/12066696 */ private void getProcessId(){ int pid = 0; try{ java.lang.management.RuntimeMXBean runtime = java.lang.management.ManagementFactory.getRuntimeMXBean(); java.lang.reflect.Field jvm = runtime.getClass().getDeclaredField("jvm"); jvm.setAccessible(true); sun.management.VMManagement mgmt = (sun.management.VMManagement) jvm.get(runtime); java.lang.reflect.Method pid_method = mgmt.getClass().getDeclaredMethod("getProcessId"); pid_method.setAccessible(true); pid = (Integer) pid_method.invoke(mgmt); } catch(Exception e){ // Ignore } if(pid > 0){ pidString = ""+pid; } else { pidString = "-"; } } /** * format a given LoggingEvent to a string * @param loggingEvent * @return String representation of LoggingEvent */ @Override public String format( LoggingEvent le ) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter( sw ); writeBasic( le, pw ); writeThrowable( le, pw ); return sw.toString(); } private void writeBasic( LoggingEvent le, PrintWriter pw ) { pw.print( dateFormatter.format( new Date() ) ); pw.print( " " ); pw.print( HOSTNAME ); pw.print( " " ); pw.print( uuid ); pw.print( " tupelo-http-store [" ); pw.print( le.getLoggerName() ); pw.print( "] [" + pidString+"] " ); pw.print( le.getLevel() ); pw.print( " " ); pw.println( "'" + le.getMessage() + "'" ); } private void writeThrowable( LoggingEvent le, PrintWriter pw ) { ThrowableInformation ti = le.getThrowableInformation(); if( ti == null ) return; } /** * Declares that this layout does not ignore throwable if available * @return */ @Override public boolean ignoresThrowable() { return false; } /** * Just fulfilling the interface/abstract class requirements */ @Override public void activateOptions() { } }
logging/src/main/java/edu/uw/apl/tupelo/logging/LogMonLayout.java
/** * Copyright © 2015, University of Washington * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of the University of Washington nor the names * of its contributors may be used to endorse or promote products * derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL UNIVERSITY OF * WASHINGTON BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package edu.uw.apl.tupelo.logging; import org.apache.log4j.Layout; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.ThrowableInformation; import java.io.PrintWriter; import java.io.StringWriter; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; /** * A log4j Layout, used by an Appender (and recall we have defined an * AMQP Appender), providing a log record format as used/requested by * Dims/DD. * At construction time, we create a uuid. This does essentially same * job as a pid, since we only expect one Layout per logging * subsystem per VM (or classloader at least) */ public class LogMonLayout extends Layout { public LogMonLayout() { uuid = UUID.randomUUID(); } /** * format a given LoggingEvent to a string * @param loggingEvent * @return String representation of LoggingEvent */ @Override public String format( LoggingEvent le ) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter( sw ); writeBasic( le, pw ); writeThrowable( le, pw ); return sw.toString(); } private void writeBasic( LoggingEvent le, PrintWriter pw ) { SimpleDateFormat sdf = new SimpleDateFormat( ISO8601 ); pw.print( sdf.format( new Date() ) ); pw.print( " " ); pw.print( HOSTNAME ); pw.print( " " ); pw.print( uuid ); pw.print( " " ); pw.print( le.getLoggerName() ); pw.print( " " ); pw.print( le.getLevel() ); pw.print( " " ); pw.println( "'" + le.getMessage() + "'" ); } private void writeThrowable( LoggingEvent le, PrintWriter pw ) { ThrowableInformation ti = le.getThrowableInformation(); if( ti == null ) return; } /** * Declares that this layout does not ignore throwable if available * @return */ @Override public boolean ignoresThrowable() { return false; } /** * Just fulfilling the interface/abstract class requirements */ @Override public void activateOptions() { } private final UUID uuid; static private final String ISO8601 = "yyyy-MM-dd'T'HH:mm:ss.SSS000XXX"; static private String HOSTNAME = "UNKNOWN"; static { try { InetAddress ia = InetAddress.getLocalHost(); HOSTNAME = ia.getCanonicalHostName(); } catch( UnknownHostException uhe ) { } } } // eof
Update the AMQP log format
logging/src/main/java/edu/uw/apl/tupelo/logging/LogMonLayout.java
Update the AMQP log format
<ide><path>ogging/src/main/java/edu/uw/apl/tupelo/logging/LogMonLayout.java <ide> */ <ide> <ide> public class LogMonLayout extends Layout { <add> private final UUID uuid; <ide> <add> static private final String ISO8601 = "yyyy-MM-dd'T'HH:mm:ss.SSS000XXX"; <add> <add> static private String HOSTNAME = "UNKNOWN"; <add> static { <add> try { <add> InetAddress ia = InetAddress.getLocalHost(); <add> HOSTNAME = ia.getCanonicalHostName(); <add> } catch( UnknownHostException uhe ) { <add> } <add> } <add> <add> static private SimpleDateFormat dateFormatter; <add> static private String pidString = null; <ide> <ide> public LogMonLayout() { <ide> uuid = UUID.randomUUID(); <add> dateFormatter = new SimpleDateFormat( ISO8601 ); <add> if(pidString == null){ <add> getProcessId(); <add> } <ide> } <del> <add> <add> @SuppressWarnings("restriction") <add> /** <add> * Attempts to get the process ID. <add> * This can fail for a number of reasons. <add> * Source: http://stackoverflow.com/a/12066696 <add> */ <add> private void getProcessId(){ <add> int pid = 0; <add> try{ <add> java.lang.management.RuntimeMXBean runtime = java.lang.management.ManagementFactory.getRuntimeMXBean(); <add> java.lang.reflect.Field jvm = runtime.getClass().getDeclaredField("jvm"); <add> jvm.setAccessible(true); <add> sun.management.VMManagement mgmt = (sun.management.VMManagement) jvm.get(runtime); <add> java.lang.reflect.Method pid_method = mgmt.getClass().getDeclaredMethod("getProcessId"); <add> pid_method.setAccessible(true); <add> <add> pid = (Integer) pid_method.invoke(mgmt); <add> } catch(Exception e){ <add> // Ignore <add> } <add> if(pid > 0){ <add> pidString = ""+pid; <add> } else { <add> pidString = "-"; <add> } <add> } <add> <ide> /** <ide> * format a given LoggingEvent to a string <ide> * @param loggingEvent <ide> } <ide> <ide> private void writeBasic( LoggingEvent le, PrintWriter pw ) { <del> SimpleDateFormat sdf = new SimpleDateFormat( ISO8601 ); <del> pw.print( sdf.format( new Date() ) ); <add> pw.print( dateFormatter.format( new Date() ) ); <ide> pw.print( " " ); <ide> pw.print( HOSTNAME ); <ide> pw.print( " " ); <ide> pw.print( uuid ); <del> pw.print( " " ); <add> pw.print( " tupelo-http-store [" ); <ide> pw.print( le.getLoggerName() ); <del> pw.print( " " ); <add> pw.print( "] [" + pidString+"] " ); <ide> pw.print( le.getLevel() ); <ide> pw.print( " " ); <ide> pw.println( "'" + le.getMessage() + "'" ); <ide> @Override <ide> public void activateOptions() { <ide> } <del> <del> <del> private final UUID uuid; <del> <del> static private final String ISO8601 = "yyyy-MM-dd'T'HH:mm:ss.SSS000XXX"; <del> <del> static private String HOSTNAME = "UNKNOWN"; <del> static { <del> try { <del> InetAddress ia = InetAddress.getLocalHost(); <del> HOSTNAME = ia.getCanonicalHostName(); <del> } catch( UnknownHostException uhe ) { <del> } <del> } <ide> } <del> <del>// eof
Java
apache-2.0
882ab889621b587eea5e6a5d845e68db208a1e49
0
btmura/rbb
package com.btmura.android.reddit.widget; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Rect; import android.graphics.RectF; import android.text.BoringLayout; import android.text.Layout; import android.text.Layout.Alignment; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.StaticLayout; import android.text.TextUtils; import android.text.TextUtils.TruncateAt; import android.text.style.ClickableSpan; import android.text.style.ForegroundColorSpan; import android.util.AttributeSet; import android.util.Log; import android.view.GestureDetector; import android.view.GestureDetector.OnGestureListener; import android.view.MotionEvent; import com.btmura.android.reddit.BuildConfig; import com.btmura.android.reddit.R; import com.btmura.android.reddit.accounts.AccountUtils; import com.btmura.android.reddit.database.Things; import com.btmura.android.reddit.text.Formatter; import com.btmura.android.reddit.text.RelativeTime; public class ThingView extends CustomView implements OnGestureListener { public static final String TAG = "ThingView"; private static final Formatter FORMATTER = new Formatter(); private final GestureDetector detector; private OnVoteListener listener; private int kind; private int likes; private String linkTitle; private int thingBodyWidth; private String thumbnailUrl; private String thingId; private String title; private Bitmap bitmap; private boolean drawVotingArrows; private boolean drawScore; private CharSequence bodyText; private String scoreText; private final SpannableStringBuilder statusText = new SpannableStringBuilder(); private final SpannableStringBuilder longDetailsText = new SpannableStringBuilder(); private String shortDetailsText; private Layout linkTitleLayout; private Layout titleLayout; private Layout bodyLayout; private Layout statusLayout; private Layout detailsLayout; private Rect scoreBounds; private RectF bodyBounds; private int rightHeight; private int minHeight; public ThingView(Context context) { this(context, null); } public ThingView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public ThingView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); detector = new GestureDetector(context, this); init(context); } private void init(Context context) { VotingArrows.init(context); Thumbnail.init(context); } public void setOnVoteListener(OnVoteListener listener) { this.listener = listener; } public void setThumbnailBitmap(Bitmap bitmap) { this.bitmap = bitmap; invalidate(); } public void setData(String accountName, String author, String body, long createdUtc, String domain, int downs, int kind, int likes, String linkTitle, long nowTimeMs, int numComments, boolean over18, String parentSubreddit, int score, String subreddit, int thingBodyWidth, String thingId, String thumbnailUrl, String title, int ups) { this.kind = kind; this.likes = likes; this.linkTitle = linkTitle; this.thingBodyWidth = thingBodyWidth; this.thingId = thingId; this.thumbnailUrl = thumbnailUrl; this.title = title; drawVotingArrows = AccountUtils.isAccount(accountName); drawScore = drawVotingArrows && kind == Things.KIND_LINK; if (drawScore) { if (scoreBounds == null) { scoreBounds = new Rect(); } scoreText = VotingArrows.getScoreText(score); } setStatusText(author, createdUtc, kind, nowTimeMs, numComments, over18, parentSubreddit, score, subreddit, drawVotingArrows); setDetailsText(domain, downs, ups); if (!TextUtils.isEmpty(body)) { bodyText = FORMATTER.formatSpans(getContext(), body); if (bodyBounds == null) { bodyBounds = new RectF(); } } else { bodyText = null; } requestLayout(); } private void setStatusText(String author, long createdUtc, int kind, long nowTimeMs, int numComments, boolean over18, String parentSubreddit, int score, String subreddit, boolean votable) { Context c = getContext(); Resources r = getResources(); statusText.clear(); statusText.clearSpans(); if (over18) { String nsfw = c.getString(R.string.nsfw); statusText.append(nsfw).append(" "); statusText.setSpan(new ForegroundColorSpan(Color.RED), 0, nsfw.length(), 0); } if (!subreddit.equalsIgnoreCase(parentSubreddit)) { statusText.append(subreddit).append(" "); } statusText.append(author).append(" "); if (!votable) { statusText.append(r.getQuantityString(R.plurals.points, score, score)).append(" "); } statusText.append(RelativeTime.format(c, nowTimeMs, createdUtc)).append(" "); if (kind == Things.KIND_LINK) { statusText.append(r.getQuantityString(R.plurals.comments, numComments, numComments)); } } private void setDetailsText(String domain, int downs, int ups) { Resources r = getResources(); longDetailsText.clear(); longDetailsText.append(r.getQuantityString(R.plurals.votes_up, ups, ups)) .append(" "); longDetailsText.append(r.getQuantityString(R.plurals.votes_down, downs, downs)) .append(" "); if (!TextUtils.isEmpty(domain)) { longDetailsText.append(domain); shortDetailsText = domain; } else { shortDetailsText = ""; } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int measuredWidth = 0; int measuredHeight = 0; int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); switch (widthMode) { case MeasureSpec.AT_MOST: case MeasureSpec.EXACTLY: measuredWidth = widthSize; break; case MeasureSpec.UNSPECIFIED: measuredWidth = getSuggestedMinimumWidth(); break; } int titleWidth; int detailsWidth; CharSequence detailsText; if (thingBodyWidth > 0) { titleWidth = Math.min(measuredWidth, thingBodyWidth) - PADDING * 2; int remainingWidth = measuredWidth - thingBodyWidth - PADDING * 2; if (remainingWidth > MAX_DETAILS_WIDTH) { detailsWidth = MAX_DETAILS_WIDTH; detailsText = longDetailsText; } else if (remainingWidth > MIN_DETAILS_WIDTH) { detailsWidth = MIN_DETAILS_WIDTH; detailsText = shortDetailsText; } else { detailsWidth = 0; detailsText = ""; } } else { titleWidth = measuredWidth - PADDING * 2; detailsWidth = 0; detailsText = ""; } int leftGadgetWidth = 0; if (drawVotingArrows) { leftGadgetWidth += VotingArrows.getWidth(drawVotingArrows) + PADDING; if (drawScore) { VotingArrows.measureScoreText(scoreText, scoreBounds); } } if (!TextUtils.isEmpty(thumbnailUrl)) { leftGadgetWidth += Thumbnail.getWidth() + PADDING; } titleWidth -= leftGadgetWidth; int linkTitleWidth = measuredWidth - PADDING * 2; int statusWidth = measuredWidth - PADDING * 2 - leftGadgetWidth; if (detailsWidth > 0) { statusWidth -= detailsWidth + PADDING; } linkTitleWidth = Math.max(0, linkTitleWidth); titleWidth = Math.max(0, titleWidth); statusWidth = Math.max(0, statusWidth); detailsWidth = Math.max(0, detailsWidth); int leftHeight = 0; if (drawVotingArrows) { leftHeight = Math.max(leftHeight, VotingArrows.getHeight(drawVotingArrows, drawScore)); } if (kind == Things.KIND_LINK) { leftHeight = Math.max(leftHeight, Thumbnail.getHeight()); } linkTitleLayout = null; titleLayout = null; bodyLayout = null; rightHeight = 0; if (!TextUtils.isEmpty(linkTitle)) { linkTitleLayout = createLinkTitleLayout(linkTitleWidth); rightHeight += linkTitleLayout.getHeight() + ELEMENT_PADDING; } if (!TextUtils.isEmpty(title)) { titleLayout = createTitleLayout(titleWidth); rightHeight += titleLayout.getHeight() + ELEMENT_PADDING; } if (!TextUtils.isEmpty(bodyText)) { bodyLayout = createBodyLayout(titleWidth); rightHeight += bodyLayout.getHeight() + ELEMENT_PADDING; } if (!TextUtils.isEmpty(statusText)) { statusLayout = createStatusLayout(statusWidth); rightHeight += statusLayout.getHeight(); } detailsLayout = null; if (detailsWidth > 0) { detailsLayout = makeBoringLayout(THING_STATUS, detailsText, detailsWidth, Alignment.ALIGN_OPPOSITE); } minHeight = PADDING + Math.max(leftHeight, rightHeight) + PADDING; // Move from left to right one more time. int x = PADDING; if (drawVotingArrows) { x += VotingArrows.getWidth(drawVotingArrows); } if (bodyLayout != null) { bodyBounds.left = x; x += bodyLayout.getWidth(); bodyBounds.right = x; } // Move from top to bottom one more time. int y = (minHeight - rightHeight) / 2; if (linkTitleLayout != null) { y += linkTitleLayout.getHeight() + ELEMENT_PADDING; } if (isTopStatus() && statusLayout != null) { y += statusLayout.getHeight() + ELEMENT_PADDING; } if (bodyLayout != null) { bodyBounds.top = y; y += bodyLayout.getHeight(); bodyBounds.bottom = y; } int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); switch (heightMode) { case MeasureSpec.AT_MOST: case MeasureSpec.EXACTLY: measuredHeight = heightSize; break; case MeasureSpec.UNSPECIFIED: measuredHeight = minHeight; break; } setMeasuredDimension(measuredWidth, measuredHeight); } private boolean isTopStatus() { return kind == Things.KIND_COMMENT; } private Layout createLinkTitleLayout(int width) { CharSequence truncated = TextUtils.ellipsize(linkTitle, TEXT_PAINTS[THING_LINK_TITLE], width, TruncateAt.END); return makeStaticLayout(THING_LINK_TITLE, truncated, width); } private Layout createTitleLayout(int width) { return makeStaticLayout(THING_TITLE, title, width); } private Layout createBodyLayout(int width) { return makeStaticLayout(THING_BODY, bodyText, width); } private Layout createStatusLayout(int width) { return makeBoringLayout(THING_STATUS, statusText, width, Alignment.ALIGN_NORMAL); } private static Layout makeStaticLayout(int paint, CharSequence text, int width) { return new StaticLayout(text, TEXT_PAINTS[paint], width, Alignment.ALIGN_NORMAL, 1f, 0f, true); } private static Layout makeBoringLayout(int paint, CharSequence text, int width, Alignment alignment) { BoringLayout.Metrics m = BoringLayout.isBoring(text, TEXT_PAINTS[paint]); return BoringLayout.make(text, TEXT_PAINTS[paint], width, alignment, 1f, 0f, m, true, TruncateAt.END, width); } @Override protected void onDraw(Canvas c) { if (detailsLayout != null) { int dx = c.getWidth() - PADDING - detailsLayout.getWidth(); int dy = (c.getHeight() - detailsLayout.getHeight()) / 2; c.translate(dx, dy); detailsLayout.draw(c); c.translate(-dx, -dy); } c.translate(PADDING, PADDING); if (linkTitleLayout != null) { linkTitleLayout.draw(c); c.translate(0, linkTitleLayout.getHeight() + ELEMENT_PADDING); } if (drawVotingArrows) { VotingArrows.draw(c, bitmap, scoreText, scoreBounds, likes, drawScore, true); c.translate(VotingArrows.getWidth(drawVotingArrows) + PADDING, 0); } if (!TextUtils.isEmpty(thumbnailUrl)) { Thumbnail.draw(c, bitmap); c.translate(Thumbnail.getWidth() + PADDING, 0); } c.translate(0, -PADDING + (minHeight - rightHeight) / 2); // Render the status at the top for comments. if (isTopStatus() && statusLayout != null) { statusLayout.draw(c); c.translate(0, statusLayout.getHeight() + ELEMENT_PADDING); } if (titleLayout != null) { titleLayout.draw(c); c.translate(0, titleLayout.getHeight() + ELEMENT_PADDING); } if (bodyLayout != null) { bodyLayout.draw(c); c.translate(0, bodyLayout.getHeight() + ELEMENT_PADDING); } // Render the status at the bottom for non-comments. if (!isTopStatus() && statusLayout != null) { statusLayout.draw(c); } } @Override public boolean onTouchEvent(MotionEvent e) { return detector.onTouchEvent(e) || onBodyTouchEvent(e) || super.onTouchEvent(e); } private boolean onBodyTouchEvent(MotionEvent e) { int action = e.getAction(); if ((action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_UP) && bodyText instanceof Spannable && bodyBounds != null && bodyBounds.contains(e.getX(), e.getY())) { float localX = e.getX() - bodyBounds.left; float localY = e.getY() - bodyBounds.top; int line = bodyLayout.getLineForVertical(Math.round(localY)); int offset = bodyLayout.getOffsetForHorizontal(line, localX); float right = bodyBounds.left + bodyLayout.getLineRight(line); if (BuildConfig.DEBUG) { Log.d(TAG, "b: " + bodyBounds + " x: " + e.getX() + " y: " + e.getY()); } if (localX > right) { if (BuildConfig.DEBUG) { Log.d(TAG, "lx: " + localX + " r: " + right); } return false; } Spannable bodySpan = (Spannable) bodyText; ClickableSpan[] spans = bodySpan.getSpans(offset, offset, ClickableSpan.class); if (spans != null && spans.length > 0) { if (action == MotionEvent.ACTION_UP) { spans[0].onClick(this); } return true; } } return false; } public boolean onDown(MotionEvent e) { return VotingArrows.onDown(e, getTopOffset(), 0, drawVotingArrows, drawScore, true); } public boolean onSingleTapUp(MotionEvent e) { return VotingArrows.onSingleTapUp(e, getTopOffset(), 0, drawVotingArrows, drawScore, true, listener, thingId); } private float getTopOffset() { return linkTitleLayout != null ? linkTitleLayout.getHeight() + ELEMENT_PADDING : 0; } public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { return false; } public void onLongPress(MotionEvent e) { } public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { return false; } public void onShowPress(MotionEvent e) { } }
src/com/btmura/android/reddit/widget/ThingView.java
package com.btmura.android.reddit.widget; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Rect; import android.graphics.RectF; import android.text.BoringLayout; import android.text.Layout; import android.text.Layout.Alignment; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.StaticLayout; import android.text.TextUtils; import android.text.TextUtils.TruncateAt; import android.text.style.ClickableSpan; import android.text.style.ForegroundColorSpan; import android.util.AttributeSet; import android.util.Log; import android.view.GestureDetector; import android.view.GestureDetector.OnGestureListener; import android.view.MotionEvent; import com.btmura.android.reddit.BuildConfig; import com.btmura.android.reddit.R; import com.btmura.android.reddit.accounts.AccountUtils; import com.btmura.android.reddit.database.Things; import com.btmura.android.reddit.text.Formatter; import com.btmura.android.reddit.text.RelativeTime; public class ThingView extends CustomView implements OnGestureListener { public static final String TAG = "ThingView"; private static final Formatter FORMATTER = new Formatter(); private final GestureDetector detector; private OnVoteListener listener; private int kind; private int likes; private String linkTitle; private int thingBodyWidth; private String thumbnailUrl; private String thingId; private String title; private Bitmap bitmap; private boolean drawVotingArrows; private boolean drawScore; private CharSequence bodyText; private String scoreText; private final SpannableStringBuilder statusText = new SpannableStringBuilder(); private final SpannableStringBuilder longDetailsText = new SpannableStringBuilder(); private String shortDetailsText; private Layout linkTitleLayout; private Layout titleLayout; private Layout bodyLayout; private Layout statusLayout; private Layout detailsLayout; private Rect scoreBounds; private RectF bodyBounds; private int rightHeight; private int minHeight; public ThingView(Context context) { this(context, null); } public ThingView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public ThingView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); detector = new GestureDetector(context, this); init(context); } private void init(Context context) { VotingArrows.init(context); Thumbnail.init(context); } public void setOnVoteListener(OnVoteListener listener) { this.listener = listener; } public void setThumbnailBitmap(Bitmap bitmap) { this.bitmap = bitmap; invalidate(); } public void setData(String accountName, String author, String body, long createdUtc, String domain, int downs, int kind, int likes, String linkTitle, long nowTimeMs, int numComments, boolean over18, String parentSubreddit, int score, String subreddit, int thingBodyWidth, String thingId, String thumbnailUrl, String title, int ups) { this.kind = kind; this.likes = likes; this.linkTitle = linkTitle; this.thingBodyWidth = thingBodyWidth; this.thingId = thingId; this.thumbnailUrl = thumbnailUrl; this.title = title; drawVotingArrows = AccountUtils.isAccount(accountName); drawScore = drawVotingArrows && kind == Things.KIND_LINK; if (drawScore) { if (scoreBounds == null) { scoreBounds = new Rect(); } scoreText = VotingArrows.getScoreText(score); } setStatusText(author, createdUtc, kind, nowTimeMs, numComments, over18, parentSubreddit, score, subreddit, drawVotingArrows); setDetailsText(domain, downs, ups); if (!TextUtils.isEmpty(body)) { bodyText = FORMATTER.formatSpans(getContext(), body); if (bodyBounds == null) { bodyBounds = new RectF(); } } else { bodyText = null; } requestLayout(); } private void setStatusText(String author, long createdUtc, int kind, long nowTimeMs, int numComments, boolean over18, String parentSubreddit, int score, String subreddit, boolean votable) { Context c = getContext(); Resources r = getResources(); statusText.clear(); statusText.clearSpans(); if (over18) { String nsfw = c.getString(R.string.nsfw); statusText.append(nsfw).append(" "); statusText.setSpan(new ForegroundColorSpan(Color.RED), 0, nsfw.length(), 0); } if (!subreddit.equalsIgnoreCase(parentSubreddit)) { statusText.append(subreddit).append(" "); } statusText.append(author).append(" "); if (!votable) { statusText.append(r.getQuantityString(R.plurals.points, score, score)).append(" "); } statusText.append(RelativeTime.format(c, nowTimeMs, createdUtc)).append(" "); if (kind == Things.KIND_LINK) { statusText.append(r.getQuantityString(R.plurals.comments, numComments, numComments)); } } private void setDetailsText(String domain, int downs, int ups) { Resources r = getResources(); longDetailsText.clear(); longDetailsText.append(r.getQuantityString(R.plurals.votes_up, ups, ups)) .append(" "); longDetailsText.append(r.getQuantityString(R.plurals.votes_down, downs, downs)) .append(" "); if (!TextUtils.isEmpty(domain)) { longDetailsText.append(domain); shortDetailsText = domain; } else { shortDetailsText = ""; } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int measuredWidth = 0; int measuredHeight = 0; int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); switch (widthMode) { case MeasureSpec.AT_MOST: case MeasureSpec.EXACTLY: measuredWidth = widthSize; break; case MeasureSpec.UNSPECIFIED: measuredWidth = getSuggestedMinimumWidth(); break; } int titleWidth; int detailsWidth; CharSequence detailsText; if (thingBodyWidth > 0) { titleWidth = Math.min(measuredWidth, thingBodyWidth) - PADDING * 2; int remainingWidth = measuredWidth - thingBodyWidth - PADDING * 2; if (remainingWidth > MAX_DETAILS_WIDTH) { detailsWidth = MAX_DETAILS_WIDTH; detailsText = longDetailsText; } else if (remainingWidth > MIN_DETAILS_WIDTH) { detailsWidth = MIN_DETAILS_WIDTH; detailsText = shortDetailsText; } else { detailsWidth = 0; detailsText = ""; } } else { titleWidth = measuredWidth - PADDING * 2; detailsWidth = 0; detailsText = ""; } int leftGadgetWidth = 0; if (drawVotingArrows) { leftGadgetWidth += VotingArrows.getWidth(drawVotingArrows) + PADDING; if (drawScore) { VotingArrows.measureScoreText(scoreText, scoreBounds); } } if (!TextUtils.isEmpty(thumbnailUrl)) { leftGadgetWidth += Thumbnail.getWidth() + PADDING; } titleWidth -= leftGadgetWidth; int linkTitleWidth = measuredWidth - PADDING * 2; int statusWidth = measuredWidth - PADDING * 2 - leftGadgetWidth; if (detailsWidth > 0) { statusWidth -= detailsWidth + PADDING; } linkTitleWidth = Math.max(0, linkTitleWidth); titleWidth = Math.max(0, titleWidth); statusWidth = Math.max(0, statusWidth); detailsWidth = Math.max(0, detailsWidth); int leftHeight = 0; if (drawVotingArrows) { leftHeight = Math.max(leftHeight, VotingArrows.getHeight(drawVotingArrows, drawScore)); } if (kind == Things.KIND_LINK) { leftHeight = Math.max(leftHeight, Thumbnail.getHeight()); } linkTitleLayout = null; titleLayout = null; bodyLayout = null; rightHeight = 0; if (!TextUtils.isEmpty(linkTitle)) { linkTitleLayout = createLinkTitleLayout(linkTitleWidth); rightHeight += linkTitleLayout.getHeight() + ELEMENT_PADDING; } if (!TextUtils.isEmpty(title)) { titleLayout = createTitleLayout(titleWidth); rightHeight += titleLayout.getHeight() + ELEMENT_PADDING; } if (!TextUtils.isEmpty(bodyText)) { bodyLayout = createBodyLayout(titleWidth); rightHeight += bodyLayout.getHeight() + ELEMENT_PADDING; } if (!TextUtils.isEmpty(statusText)) { statusLayout = createStatusLayout(statusWidth); rightHeight += statusLayout.getHeight(); } detailsLayout = null; if (detailsWidth > 0) { detailsLayout = makeBoringLayout(THING_STATUS, detailsText, detailsWidth, Alignment.ALIGN_OPPOSITE); } minHeight = PADDING + Math.max(leftHeight, rightHeight) + PADDING; // Move from left to right one more time. int x = PADDING; if (drawVotingArrows) { x += VotingArrows.getWidth(drawVotingArrows); } if (bodyLayout != null) { bodyBounds.left = x; x += bodyLayout.getWidth(); bodyBounds.right = x; } // Move from top to bottom one more time. int y = (minHeight - rightHeight) / 2; if (linkTitleLayout != null) { y += linkTitleLayout.getHeight() + ELEMENT_PADDING; } if (isTopStatus() && statusLayout != null) { y += statusLayout.getHeight() + ELEMENT_PADDING; } if (bodyLayout != null) { bodyBounds.top = y; y += bodyLayout.getHeight(); bodyBounds.bottom = y; } int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); switch (heightMode) { case MeasureSpec.AT_MOST: case MeasureSpec.EXACTLY: measuredHeight = heightSize; break; case MeasureSpec.UNSPECIFIED: measuredHeight = minHeight; break; } setMeasuredDimension(measuredWidth, measuredHeight); } private boolean isTopStatus() { return kind == Things.KIND_COMMENT; } private Layout createLinkTitleLayout(int width) { CharSequence truncated = TextUtils.ellipsize(linkTitle, TEXT_PAINTS[THING_LINK_TITLE], width, TruncateAt.END); return new StaticLayout(truncated, TEXT_PAINTS[THING_LINK_TITLE], width, Alignment.ALIGN_NORMAL, 1f, 0f, true); } private Layout createTitleLayout(int width) { return new StaticLayout(title, TEXT_PAINTS[THING_TITLE], width, Alignment.ALIGN_NORMAL, 1f, 0f, true); } private Layout createBodyLayout(int width) { return new StaticLayout(bodyText, TEXT_PAINTS[THING_BODY], width, Alignment.ALIGN_NORMAL, 1f, 0f, true); } private Layout createStatusLayout(int width) { return makeBoringLayout(THING_STATUS, statusText, width, Alignment.ALIGN_NORMAL); } private static Layout makeBoringLayout(int paint, CharSequence text, int width, Alignment alignment) { BoringLayout.Metrics m = BoringLayout.isBoring(text, TEXT_PAINTS[paint]); return BoringLayout.make(text, TEXT_PAINTS[paint], width, alignment, 1f, 0f, m, true, TruncateAt.END, width); } @Override protected void onDraw(Canvas c) { if (detailsLayout != null) { int dx = c.getWidth() - PADDING - detailsLayout.getWidth(); int dy = (c.getHeight() - detailsLayout.getHeight()) / 2; c.translate(dx, dy); detailsLayout.draw(c); c.translate(-dx, -dy); } c.translate(PADDING, PADDING); if (linkTitleLayout != null) { linkTitleLayout.draw(c); c.translate(0, linkTitleLayout.getHeight() + ELEMENT_PADDING); } if (drawVotingArrows) { VotingArrows.draw(c, bitmap, scoreText, scoreBounds, likes, drawScore, true); c.translate(VotingArrows.getWidth(drawVotingArrows) + PADDING, 0); } if (!TextUtils.isEmpty(thumbnailUrl)) { Thumbnail.draw(c, bitmap); c.translate(Thumbnail.getWidth() + PADDING, 0); } c.translate(0, -PADDING + (minHeight - rightHeight) / 2); // Render the status at the top for comments. if (isTopStatus() && statusLayout != null) { statusLayout.draw(c); c.translate(0, statusLayout.getHeight() + ELEMENT_PADDING); } if (titleLayout != null) { titleLayout.draw(c); c.translate(0, titleLayout.getHeight() + ELEMENT_PADDING); } if (bodyLayout != null) { bodyLayout.draw(c); c.translate(0, bodyLayout.getHeight() + ELEMENT_PADDING); } // Render the status at the bottom for non-comments. if (!isTopStatus() && statusLayout != null) { statusLayout.draw(c); } } @Override public boolean onTouchEvent(MotionEvent e) { return detector.onTouchEvent(e) || onBodyTouchEvent(e) || super.onTouchEvent(e); } private boolean onBodyTouchEvent(MotionEvent e) { int action = e.getAction(); if ((action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_UP) && bodyText instanceof Spannable && bodyBounds != null && bodyBounds.contains(e.getX(), e.getY())) { float localX = e.getX() - bodyBounds.left; float localY = e.getY() - bodyBounds.top; int line = bodyLayout.getLineForVertical(Math.round(localY)); int offset = bodyLayout.getOffsetForHorizontal(line, localX); float right = bodyBounds.left + bodyLayout.getLineRight(line); if (BuildConfig.DEBUG) { Log.d(TAG, "b: " + bodyBounds + " x: " + e.getX() + " y: " + e.getY()); } if (localX > right) { if (BuildConfig.DEBUG) { Log.d(TAG, "lx: " + localX + " r: " + right); } return false; } Spannable bodySpan = (Spannable) bodyText; ClickableSpan[] spans = bodySpan.getSpans(offset, offset, ClickableSpan.class); if (spans != null && spans.length > 0) { if (action == MotionEvent.ACTION_UP) { spans[0].onClick(this); } return true; } } return false; } public boolean onDown(MotionEvent e) { return VotingArrows.onDown(e, getTopOffset(), 0, drawVotingArrows, drawScore, true); } public boolean onSingleTapUp(MotionEvent e) { return VotingArrows.onSingleTapUp(e, getTopOffset(), 0, drawVotingArrows, drawScore, true, listener, thingId); } private float getTopOffset() { return linkTitleLayout != null ? linkTitleLayout.getHeight() + ELEMENT_PADDING : 0; } public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { return false; } public void onLongPress(MotionEvent e) { } public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { return false; } public void onShowPress(MotionEvent e) { } }
Some unimportant refactoring in ThingView
src/com/btmura/android/reddit/widget/ThingView.java
Some unimportant refactoring in ThingView
<ide><path>rc/com/btmura/android/reddit/widget/ThingView.java <ide> private Layout createLinkTitleLayout(int width) { <ide> CharSequence truncated = TextUtils.ellipsize(linkTitle, <ide> TEXT_PAINTS[THING_LINK_TITLE], width, TruncateAt.END); <del> return new StaticLayout(truncated, TEXT_PAINTS[THING_LINK_TITLE], width, <del> Alignment.ALIGN_NORMAL, 1f, 0f, true); <add> return makeStaticLayout(THING_LINK_TITLE, truncated, width); <ide> } <ide> <ide> private Layout createTitleLayout(int width) { <del> return new StaticLayout(title, TEXT_PAINTS[THING_TITLE], width, <del> Alignment.ALIGN_NORMAL, 1f, 0f, true); <add> return makeStaticLayout(THING_TITLE, title, width); <ide> } <ide> <ide> private Layout createBodyLayout(int width) { <del> return new StaticLayout(bodyText, TEXT_PAINTS[THING_BODY], width, <del> Alignment.ALIGN_NORMAL, 1f, 0f, true); <add> return makeStaticLayout(THING_BODY, bodyText, width); <ide> } <ide> <ide> private Layout createStatusLayout(int width) { <ide> return makeBoringLayout(THING_STATUS, statusText, width, Alignment.ALIGN_NORMAL); <add> } <add> <add> private static Layout makeStaticLayout(int paint, CharSequence text, int width) { <add> return new StaticLayout(text, TEXT_PAINTS[paint], width, <add> Alignment.ALIGN_NORMAL, 1f, 0f, true); <ide> } <ide> <ide> private static Layout makeBoringLayout(int paint, CharSequence text, int width,
JavaScript
mit
6480232c4840f62e94463f4287f70d10351d92c0
0
rabchev/web-terminal,rabchev/web-terminal,rabchev/web-terminal
/*jslint plusplus: true, devel: true, nomen: true, vars: true, node: true, indent: 4, maxerr: 50 */ /*global require, exports, module */ var io = require("socket.io"), send = require("send"), connect = require("connect"), path = require("path"), exec = require('child_process').exec, pkg = require("../package.json"), config = pkg.config || {}, standalone; function redirect(res, url) { "use strict"; res.statusCode = 301; res.setHeader("Location", url); res.end("Redirecting to " + url); } function initialize(server, options, fn) { "use strict"; if ("function" === typeof options) { fn = options; options = {}; } if ("undefined" === typeof server) { if (process.env.PORT) { server = (+process.env.PORT); } else { server = config.port || 80; } } if ("number" === typeof server) { // if a port number is passed var port = server; if (options && options.key) { server = require("https").createServer(options); } else { server = require("http").createServer(); } server.listen(port, fn); standalone = true; } server.on("request", function (req, res) { if (req.url.indexOf(config.root) === 0) { send(req, req.url.substr(config.root.length)) .root(path.normalize(__dirname + "/../web")) .on('error', function (err) { res.statusCode = err.status || 500; res.end(err.message); }) .on('directory', function () { redirect(res, req.url + "/"); }) .pipe(res); } else if (standalone) { redirect(res, config.root); } }); io = io.listen(server); io.sockets.on("connection", function (socket) { socket.on("console", function (command, callBack) { console.log(command); exec(command, function (error, stdout, stderr) { if (error) { console.log(stderr); callBack(stderr); } console.log(stdout); callBack(stdout); }); }); }); } exports = module.exports = initialize;
lib/shell.js
/*jslint plusplus: true, devel: true, nomen: true, vars: true, node: true, indent: 4, maxerr: 50 */ /*global require, exports, module */ var io = require("socket.io"), send = require("send"), connect = require("connect"), path = require("path"), exec = require('child_process').exec, pkg = require("../package.json"), config = pkg.config || {}, standalone; function redirect(res, url) { "use strict"; res.statusCode = 301; res.setHeader("Location", url); res.end("Redirecting to " + url); } function initialize(server, options, fn) { "use strict"; if ("function" === typeof options) { fn = options; options = {}; } if ("undefined" === typeof server) { if (process.env.PORT) { server = (+process.env.PORT); } else { server = config.port || 80; } } if ("number" === typeof server) { // if a port number is passed var port = server; if (options && options.key) { server = require("https").createServer(options); } else { server = require("http").createServer(); } server.listen(port, fn); standalone = true; } server.on("request", function (req, res) { if (req.url.indexOf(config.root) === 0) { send(req, req.url.substr(config.root.length)) .root(path.normalize(__dirname + "/../web")) .on('error', function (err) { res.statusCode = err.status || 500; res.end(err.message); }) .on('directory', function () { redirect(res, req.url + "/"); }) .pipe(res); } else if (standalone) { redirect(res, config.root); } }); io = io.listen(server); io.sockets.on("connection", function (socket) { socket.on("console", function (command, callBack) { console.log(command); exec(command, function (error, stdout, stderr) { if (error) { console.log("error: "); console.log(error); } console.log(stdout); callBack(stdout); }); }); }); } exports = module.exports = initialize;
Terminal fixes
lib/shell.js
Terminal fixes
<ide><path>ib/shell.js <ide> <ide> exec(command, function (error, stdout, stderr) { <ide> if (error) { <del> console.log("error: "); <del> console.log(error); <add> console.log(stderr); <add> callBack(stderr); <ide> } <ide> <ide> console.log(stdout);
Java
lgpl-2.1
2b601404e42293694e9c6fc4d653f960633274af
0
yuan39/TuxGuitar,yuan39/TuxGuitar,yuan39/TuxGuitar,yuan39/TuxGuitar,yuan39/TuxGuitar
/* * Created on 30-nov-2005 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package org.herac.tuxguitar.gui.editors.tab; import java.util.Iterator; import java.util.List; import org.herac.tuxguitar.gui.TuxGuitar; import org.herac.tuxguitar.gui.editors.TGPainter; import org.herac.tuxguitar.gui.editors.tab.layout.TrackSpacing; import org.herac.tuxguitar.gui.editors.tab.layout.ViewLayout; import org.herac.tuxguitar.gui.util.MidiTickUtil; import org.herac.tuxguitar.song.managers.TGMeasureManager; import org.herac.tuxguitar.song.managers.TGSongManager; import org.herac.tuxguitar.song.models.TGBeat; import org.herac.tuxguitar.song.models.TGDuration; import org.herac.tuxguitar.song.models.TGNote; import org.herac.tuxguitar.song.models.TGString; import org.herac.tuxguitar.song.models.TGVelocities; /** * @author julian * * TODO To change the template for this generated type comment go to Window - Preferences - Java - Code Style - Code Templates */ public class Caret { private Tablature tablature; private TGTrackImpl selectedTrack; private TGMeasureImpl selectedMeasure; //private TGDurationable selectedComponent; private TGDuration selectedDuration; private long position; private int string; private boolean changes; private int velocity; private TGNote selectedNote; private TGBeat selectedBeat; public Caret(Tablature tablature) { this.tablature = tablature; this.selectedDuration = getSongManager().getFactory().newDuration(); this.string = 1; this.velocity = TGVelocities.DEFAULT; this.changes = false; } public synchronized void update(){ int trackNumber = (this.selectedTrack != null)?this.selectedTrack.getNumber():1; update(trackNumber,this.position,this.string); } public synchronized void update(int trackNumber){ update(trackNumber,this.position,this.string); } public synchronized void update(int trackNumber,long position,int string){ update(trackNumber, position, string,getVelocity()); } public synchronized void update(int trackNumber,long position,int string,int velocity) { long realPosition = ((TuxGuitar.instance().getPlayer().isRunning())?MidiTickUtil.getStart(TuxGuitar.instance().getPlayer().getTickPosition()):position); TGTrackImpl track = findTrack(trackNumber); TGMeasureImpl measure = findMeasure(realPosition,track); TGBeat beat = findBeat(realPosition,measure); if(track != null && measure != null && beat != null){ moveTo(track, measure, beat,string); } setVelocity(velocity); } public void moveTo(TGTrackImpl selectedTrack, TGMeasureImpl selectedMeasure, TGBeat selectedBeat,int string) { this.selectedTrack = selectedTrack; this.selectedMeasure = selectedMeasure; this.selectedBeat = selectedBeat; this.string = string; this.updatePosition(); this.updateDuration(); this.checkString(); this.updateNote(); this.updateBeat(); this.checkTransport(); this.setChanges(true); } private TGTrackImpl findTrack(int number){ TGTrackImpl track = (TGTrackImpl)getSongManager().getTrack(number); if(track == null){ track = (TGTrackImpl)getSongManager().getFirstTrack(); } return track; } private TGMeasureImpl findMeasure(long position,TGTrackImpl track){ TGMeasureImpl measure = null; if(track != null){ measure = (TGMeasureImpl)getSongManager().getTrackManager().getMeasureAt(track,position); if(measure == null){ measure = (TGMeasureImpl)getSongManager().getTrackManager().getFirstMeasure(track); } } return measure; } private TGBeat findBeat(long position,TGMeasureImpl measure){ TGBeat beat = null; if(measure != null){ TGMeasureManager manager = getSongManager().getMeasureManager(); beat = manager.getBeatIn(measure, position); if (beat == null) { beat = manager.getFirstBeat(measure.getBeats()); } } return beat; } public synchronized void goToTickPosition(){ long start = MidiTickUtil.getStart(TuxGuitar.instance().getPlayer().getTickPosition()); this.update(this.selectedTrack.getNumber(),start,this.string); this.setChanges(true); } public void paintCaret(ViewLayout layout,TGPainter painter) { if(!TuxGuitar.instance().getPlayer().isRunning()){ if (this.selectedMeasure != null && this.selectedBeat instanceof TGBeatImpl) { TGBeatImpl beat = (TGBeatImpl)this.selectedBeat; if( (layout.getStyle() & ViewLayout.DISPLAY_TABLATURE) != 0){ int stringSpacing = this.tablature.getViewLayout().getStringSpacing(); int leftSpacing = beat.getMeasureImpl().getHeaderImpl().getLeftSpacing(layout); int x = this.selectedMeasure.getPosX() + beat.getPosX() + beat.getSpacing() + leftSpacing - 5; int y = this.selectedMeasure.getPosY() + this.selectedMeasure.getTs().getPosition(TrackSpacing.POSITION_TABLATURE) + ((this.string * stringSpacing) - stringSpacing) - 7; int width = 14; int height = 14; layout.setCaretStyle(painter); painter.initPath(); painter.addRectangle(x, y, width, height); painter.closePath(); } else if( (layout.getStyle() & ViewLayout.DISPLAY_SCORE) != 0){ int line = this.tablature.getViewLayout().getScoreLineSpacing(); int leftSpacing = beat.getMeasureImpl().getHeaderImpl().getLeftSpacing(layout); float xMargin = (2.0f * layout.getScale()); float x1 = this.selectedMeasure.getPosX() + beat.getPosX() + beat.getSpacing() + leftSpacing - xMargin; float x2 = (x1 + layout.getResources().getScoreNoteWidth() + xMargin); float y1 = this.selectedMeasure.getPosY() + this.selectedMeasure.getTs().getPosition(TrackSpacing.POSITION_TOP) - line; float y2 = this.selectedMeasure.getPosY() + this.selectedMeasure.getTs().getPosition(TrackSpacing.POSITION_BOTTOM); layout.setCaretStyle(painter); painter.initPath(); painter.moveTo(x1, y1); painter.lineTo(x1 + ((x2 - x1) / 2f), y1 + (line / 2f)); painter.lineTo(x2, y1); painter.moveTo(x1, y2 + line); painter.lineTo(x1 + ((x2 - x1) / 2f), y2 + (line / 2f)); painter.lineTo(x2, y2 + line); painter.closePath(); } } } } public boolean moveRight() { if (getSelectedBeat() != null) { TGMeasureImpl measure = getMeasure(); TGBeat beat = getSongManager().getMeasureManager().getNextBeat(measure.getBeats(),getSelectedBeat()); if (beat == null){ //si no habia mas componentes. busco el siguiente compas measure = (TGMeasureImpl)getSongManager().getTrackManager().getNextMeasure(getMeasure()); if (measure == null) { return false; } beat = getSongManager().getMeasureManager().getFirstBeat(measure.getBeats()); } moveTo(getTrack(), measure, beat, getStringNumber()); } return true; } public void moveLeft() { if (getSelectedBeat() != null) { TGMeasureImpl measure = getMeasure(); TGBeat beat = getSongManager().getMeasureManager().getPreviousBeat(measure.getBeats(),getSelectedBeat()); if (beat == null) { //si no habia mas componentes. busco el compas anterior measure = (TGMeasureImpl)getSongManager().getTrackManager().getPrevMeasure(getMeasure()); if (measure == null) { return; } beat = getSongManager().getMeasureManager().getLastBeat(measure.getBeats()); } moveTo(getTrack(), measure, beat, getStringNumber()); } } /** * Luego de mover el Caret. cambia la duracion seleccionada por la del componente. solo si lo que resta del compas no esta vacio */ private void updateDuration() { if (this.selectedBeat != null && !this.selectedBeat.isRestBeat()) { this.selectedBeat.getDuration().copy(this.selectedDuration); /* boolean hasNotes = false; Iterator it = getMeasure().getComponentsBeforeEnd(getSelectedComponent().getStart()).iterator(); while (it.hasNext()) { TGDurationable component = (TGDurationable) it.next(); if (component instanceof TGNoteImpl) { hasNotes = true; break; } } if (hasNotes) { if(this.selectedComponent instanceof TGSilenceImpl){ long length = this.selectedComponent.getDuration().getTime(); List components = getMeasure().getComponents(TGMeasure.C_LIST_NOTATION); TGDurationable nextComponent = getSongManager().getMeasureManager().getNextComponent(components,getSelectedComponent()); while(nextComponent != null && nextComponent instanceof TGSilenceImpl){ length += nextComponent.getDuration().getTime(); nextComponent = getSongManager().getMeasureManager().getNextComponent(components,nextComponent); } if(this.selectedDuration.getTime() > length){ this.selectedComponent.getDuration().copy(this.selectedDuration); } }else{ this.selectedComponent.getDuration().copy(this.selectedDuration); } } */ } } public void moveUp() { int stringCount = this.selectedTrack.stringCount() ; int nextString = (( (this.string - 2 + stringCount) % stringCount) + 1); setStringNumber(nextString); } public void moveDown() { int stringCount = this.selectedTrack.stringCount() ; int nextString = ( (this.string % stringCount) + 1); setStringNumber(nextString); } public void setStringNumber(int number){ this.string = number; this.updateNote(); } public int getStringNumber(){ return this.string; } public long getPosition() { return this.position; } public TGMeasureImpl getMeasure() { return this.selectedMeasure; } public TGTrackImpl getTrack() { return this.selectedTrack; } public TGDuration getDuration() { return this.selectedDuration; } public void setSelectedDuration(TGDuration selectedDuration) { this.selectedDuration = selectedDuration; } public TGString getSelectedString() { List strings = this.selectedTrack.getStrings(); Iterator it = strings.iterator(); while (it.hasNext()) { TGString instrumentString = (TGString) it.next(); if (instrumentString.getNumber() == this.string) { return instrumentString; } } return null; } public void changeDuration(TGDuration duration){ getSongManager().getMeasureManager().changeDuration(getMeasure(),getSelectedBeat(),duration, true); setChanges(true); } private void updatePosition(){ this.position = getSelectedBeat().getStart(); } private void checkString(){ int stringCount = getTrack().getStrings().size(); if(this.string > stringCount){ this.string = stringCount; } } private void checkTransport(){ TuxGuitar.instance().getTransport().gotoMeasure(getMeasure().getHeader()); } public boolean hasChanges() { return this.changes; } public void setChanges(boolean changes) { this.changes = changes; } public int getVelocity() { return this.velocity; } public void setVelocity(int velocity) { this.velocity = velocity; } private void updateNote(){ this.selectedNote = getSongManager().getMeasureManager().getNote(getMeasure(),getPosition(),getSelectedString().getNumber()); } public TGNote getSelectedNote(){ return this.selectedNote; } private void updateBeat(){ this.selectedBeat = getSongManager().getMeasureManager().getBeat(getMeasure(),getPosition()); } public TGBeatImpl getSelectedBeat(){ return (TGBeatImpl)this.selectedBeat; } public TGSongManager getSongManager(){ return this.tablature.getSongManager(); } }
TuxGuitar/src/org/herac/tuxguitar/gui/editors/tab/Caret.java
/* * Created on 30-nov-2005 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package org.herac.tuxguitar.gui.editors.tab; import java.util.Iterator; import java.util.List; import org.herac.tuxguitar.gui.TuxGuitar; import org.herac.tuxguitar.gui.editors.TGPainter; import org.herac.tuxguitar.gui.editors.tab.layout.TrackSpacing; import org.herac.tuxguitar.gui.editors.tab.layout.ViewLayout; import org.herac.tuxguitar.gui.util.MidiTickUtil; import org.herac.tuxguitar.song.managers.TGMeasureManager; import org.herac.tuxguitar.song.managers.TGSongManager; import org.herac.tuxguitar.song.models.TGBeat; import org.herac.tuxguitar.song.models.TGDuration; import org.herac.tuxguitar.song.models.TGNote; import org.herac.tuxguitar.song.models.TGString; import org.herac.tuxguitar.song.models.TGVelocities; /** * @author julian * * TODO To change the template for this generated type comment go to Window - Preferences - Java - Code Style - Code Templates */ public class Caret { private Tablature tablature; private TGTrackImpl selectedTrack; private TGMeasureImpl selectedMeasure; //private TGDurationable selectedComponent; private TGDuration selectedDuration; private long position; private int string; private boolean changes; private int velocity; private TGNote selectedNote; private TGBeat selectedBeat; public Caret(Tablature tablature) { this.tablature = tablature; this.selectedDuration = getSongManager().getFactory().newDuration(); this.string = 1; this.velocity = TGVelocities.DEFAULT; this.changes = false; } public synchronized void update(){ int trackNumber = (this.selectedTrack != null)?this.selectedTrack.getNumber():1; update(trackNumber,this.position,this.string); } public synchronized void update(int trackNumber){ update(trackNumber,this.position,this.string); } public synchronized void update(int trackNumber,long position,int string){ update(trackNumber, position, string,getVelocity()); } public synchronized void update(int trackNumber,long position,int string,int velocity) { long realPosition = ((TuxGuitar.instance().getPlayer().isRunning())?MidiTickUtil.getStart(TuxGuitar.instance().getPlayer().getTickPosition()):position); TGTrackImpl track = findTrack(trackNumber); TGMeasureImpl measure = findMeasure(realPosition,track); TGBeat beat = findBeat(realPosition,measure); if(track != null && measure != null && beat != null){ moveTo(track, measure, beat,string); } setVelocity(velocity); } public void moveTo(TGTrackImpl selectedTrack, TGMeasureImpl selectedMeasure, TGBeat selectedBeat,int string) { this.selectedTrack = selectedTrack; this.selectedMeasure = selectedMeasure; this.selectedBeat = selectedBeat; this.string = string; this.updatePosition(); this.updateDuration(); this.checkString(); this.updateNote(); this.updateBeat(); this.checkTransport(); this.setChanges(true); } private TGTrackImpl findTrack(int number){ TGTrackImpl track = (TGTrackImpl)getSongManager().getTrack(number); if(track == null){ track = (TGTrackImpl)getSongManager().getFirstTrack(); } return track; } private TGMeasureImpl findMeasure(long position,TGTrackImpl track){ TGMeasureImpl measure = null; if(track != null){ measure = (TGMeasureImpl)getSongManager().getTrackManager().getMeasureAt(track,position); if(measure == null){ measure = (TGMeasureImpl)getSongManager().getTrackManager().getFirstMeasure(track); } } return measure; } private TGBeat findBeat(long position,TGMeasureImpl measure){ TGBeat beat = null; if(measure != null){ TGMeasureManager manager = getSongManager().getMeasureManager(); beat = manager.getBeatIn(measure, position); if (beat == null) { beat = manager.getFirstBeat(measure.getBeats()); } } return beat; } public synchronized void goToTickPosition(){ long start = MidiTickUtil.getStart(TuxGuitar.instance().getPlayer().getTickPosition()); if(!getSongManager().isAtPosition(this.selectedMeasure.getHeader(),start)){ this.update(this.selectedTrack.getNumber(),start,this.string); this.setChanges(true); } } public void paintCaret(ViewLayout layout,TGPainter painter) { if(!TuxGuitar.instance().getPlayer().isRunning()){ if (this.selectedMeasure != null && this.selectedBeat instanceof TGBeatImpl) { TGBeatImpl beat = (TGBeatImpl)this.selectedBeat; if( (layout.getStyle() & ViewLayout.DISPLAY_TABLATURE) != 0){ int stringSpacing = this.tablature.getViewLayout().getStringSpacing(); int leftSpacing = beat.getMeasureImpl().getHeaderImpl().getLeftSpacing(layout); int x = this.selectedMeasure.getPosX() + beat.getPosX() + beat.getSpacing() + leftSpacing - 5; int y = this.selectedMeasure.getPosY() + this.selectedMeasure.getTs().getPosition(TrackSpacing.POSITION_TABLATURE) + ((this.string * stringSpacing) - stringSpacing) - 7; int width = 14; int height = 14; layout.setCaretStyle(painter); painter.initPath(); painter.addRectangle(x, y, width, height); painter.closePath(); } else if( (layout.getStyle() & ViewLayout.DISPLAY_SCORE) != 0){ int line = this.tablature.getViewLayout().getScoreLineSpacing(); int leftSpacing = beat.getMeasureImpl().getHeaderImpl().getLeftSpacing(layout); float xMargin = (2.0f * layout.getScale()); float x1 = this.selectedMeasure.getPosX() + beat.getPosX() + beat.getSpacing() + leftSpacing - xMargin; float x2 = (x1 + layout.getResources().getScoreNoteWidth() + xMargin); float y1 = this.selectedMeasure.getPosY() + this.selectedMeasure.getTs().getPosition(TrackSpacing.POSITION_TOP) - line; float y2 = this.selectedMeasure.getPosY() + this.selectedMeasure.getTs().getPosition(TrackSpacing.POSITION_BOTTOM); layout.setCaretStyle(painter); painter.initPath(); painter.moveTo(x1, y1); painter.lineTo(x1 + ((x2 - x1) / 2f), y1 + (line / 2f)); painter.lineTo(x2, y1); painter.moveTo(x1, y2 + line); painter.lineTo(x1 + ((x2 - x1) / 2f), y2 + (line / 2f)); painter.lineTo(x2, y2 + line); painter.closePath(); } } } } public boolean moveRight() { if (getSelectedBeat() != null) { TGMeasureImpl measure = getMeasure(); TGBeat beat = getSongManager().getMeasureManager().getNextBeat(measure.getBeats(),getSelectedBeat()); if (beat == null){ //si no habia mas componentes. busco el siguiente compas measure = (TGMeasureImpl)getSongManager().getTrackManager().getNextMeasure(getMeasure()); if (measure == null) { return false; } beat = getSongManager().getMeasureManager().getFirstBeat(measure.getBeats()); } moveTo(getTrack(), measure, beat, getStringNumber()); } return true; } public void moveLeft() { if (getSelectedBeat() != null) { TGMeasureImpl measure = getMeasure(); TGBeat beat = getSongManager().getMeasureManager().getPreviousBeat(measure.getBeats(),getSelectedBeat()); if (beat == null) { //si no habia mas componentes. busco el compas anterior measure = (TGMeasureImpl)getSongManager().getTrackManager().getPrevMeasure(getMeasure()); if (measure == null) { return; } beat = getSongManager().getMeasureManager().getLastBeat(measure.getBeats()); } moveTo(getTrack(), measure, beat, getStringNumber()); } } /** * Luego de mover el Caret. cambia la duracion seleccionada por la del componente. solo si lo que resta del compas no esta vacio */ private void updateDuration() { if (this.selectedBeat != null && !this.selectedBeat.isRestBeat()) { this.selectedBeat.getDuration().copy(this.selectedDuration); /* boolean hasNotes = false; Iterator it = getMeasure().getComponentsBeforeEnd(getSelectedComponent().getStart()).iterator(); while (it.hasNext()) { TGDurationable component = (TGDurationable) it.next(); if (component instanceof TGNoteImpl) { hasNotes = true; break; } } if (hasNotes) { if(this.selectedComponent instanceof TGSilenceImpl){ long length = this.selectedComponent.getDuration().getTime(); List components = getMeasure().getComponents(TGMeasure.C_LIST_NOTATION); TGDurationable nextComponent = getSongManager().getMeasureManager().getNextComponent(components,getSelectedComponent()); while(nextComponent != null && nextComponent instanceof TGSilenceImpl){ length += nextComponent.getDuration().getTime(); nextComponent = getSongManager().getMeasureManager().getNextComponent(components,nextComponent); } if(this.selectedDuration.getTime() > length){ this.selectedComponent.getDuration().copy(this.selectedDuration); } }else{ this.selectedComponent.getDuration().copy(this.selectedDuration); } } */ } } public void moveUp() { int stringCount = this.selectedTrack.stringCount() ; int nextString = (( (this.string - 2 + stringCount) % stringCount) + 1); setStringNumber(nextString); } public void moveDown() { int stringCount = this.selectedTrack.stringCount() ; int nextString = ( (this.string % stringCount) + 1); setStringNumber(nextString); } public void setStringNumber(int number){ this.string = number; this.updateNote(); } public int getStringNumber(){ return this.string; } public long getPosition() { return this.position; } public TGMeasureImpl getMeasure() { return this.selectedMeasure; } public TGTrackImpl getTrack() { return this.selectedTrack; } public TGDuration getDuration() { return this.selectedDuration; } public void setSelectedDuration(TGDuration selectedDuration) { this.selectedDuration = selectedDuration; } public TGString getSelectedString() { List strings = this.selectedTrack.getStrings(); Iterator it = strings.iterator(); while (it.hasNext()) { TGString instrumentString = (TGString) it.next(); if (instrumentString.getNumber() == this.string) { return instrumentString; } } return null; } public void changeDuration(TGDuration duration){ getSongManager().getMeasureManager().changeDuration(getMeasure(),getSelectedBeat(),duration, true); setChanges(true); } private void updatePosition(){ this.position = getSelectedBeat().getStart(); } private void checkString(){ int stringCount = getTrack().getStrings().size(); if(this.string > stringCount){ this.string = stringCount; } } private void checkTransport(){ TuxGuitar.instance().getTransport().gotoMeasure(getMeasure().getHeader()); } public boolean hasChanges() { return this.changes; } public void setChanges(boolean changes) { this.changes = changes; } public int getVelocity() { return this.velocity; } public void setVelocity(int velocity) { this.velocity = velocity; } private void updateNote(){ this.selectedNote = getSongManager().getMeasureManager().getNote(getMeasure(),getPosition(),getSelectedString().getNumber()); } public TGNote getSelectedNote(){ return this.selectedNote; } private void updateBeat(){ this.selectedBeat = getSongManager().getMeasureManager().getBeat(getMeasure(),getPosition()); } public TGBeatImpl getSelectedBeat(){ return (TGBeatImpl)this.selectedBeat; } public TGSongManager getSongManager(){ return this.tablature.getSongManager(); } }
git-svn-id: https://tuxguitar.svn.sourceforge.net/svnroot/tuxguitar/trunk@66 e5ace225-184b-0410-aeed-e0aa2ff36a70
TuxGuitar/src/org/herac/tuxguitar/gui/editors/tab/Caret.java
<ide><path>uxGuitar/src/org/herac/tuxguitar/gui/editors/tab/Caret.java <ide> <ide> public synchronized void goToTickPosition(){ <ide> long start = MidiTickUtil.getStart(TuxGuitar.instance().getPlayer().getTickPosition()); <del> if(!getSongManager().isAtPosition(this.selectedMeasure.getHeader(),start)){ <del> this.update(this.selectedTrack.getNumber(),start,this.string); <del> this.setChanges(true); <del> } <add> this.update(this.selectedTrack.getNumber(),start,this.string); <add> this.setChanges(true); <ide> } <ide> <ide> public void paintCaret(ViewLayout layout,TGPainter painter) {
Java
apache-2.0
92e6ab6f2caa3bffe32f59b25c17158ebc83474c
0
apache/uima-uimaj,apache/uima-uimaj,apache/uima-uimaj,apache/uima-uimaj,apache/uima-uimaj
uimaj-core/src/main/java/org/apache/uima/cas/impl/AnnotStream.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.uima.cas.impl; import java.util.Comparator; import java.util.Iterator; import java.util.Optional; import java.util.Spliterator; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.BinaryOperator; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.IntFunction; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.function.ToDoubleFunction; import java.util.function.ToIntFunction; import java.util.function.ToLongFunction; import java.util.stream.Collector; import java.util.stream.DoubleStream; import java.util.stream.IntStream; import java.util.stream.LongStream; import java.util.stream.Stream; import org.apache.uima.cas.Type; import org.apache.uima.cas.text.AnnotationFS; import org.apache.uima.jcas.cas.TOP; import org.apache.uima.jcas.impl.JCasImpl; /** * A builder class for streams over Annotation Indexes * Use: * AnnotStream as = new AnnotStream( optional args ); * as.<configure methods and args>; // chained * e.g. reverse(), boundedBy(fs), strict(true), unambiguous(true), typePriorities(false) * * as.stream() - followed by normal stream operations * as.spliterator() */ public class AnnotStream <T extends AnnotationFS> implements Stream<T> { private final CASImpl cas; private TypeImpl type; private boolean isReverse; private boolean isStrict; private boolean isUnambiguous; private boolean isUseTypePriorities; private TOP boundingFs; AnnotStream(FsIndex_singletype fsi) { this.cas = fsi.casImpl; this.type = fsi.getTypeImpl(); } public AnnotStream reverse() {return reverse(true);} public AnnotStream reverse(boolean b) {isReverse = b; return this;} public AnnotStream strict() { return strict(true); } public AnnotStream strict(boolean b) {isStrict = b; return this;} public AnnotStream useTypePriorities() { return useTypePriorities(true); } public AnnotStream useTypePriorities(boolean b) {isUseTypePriorities = b; return this;} public AnnotStream boundingFs(TOP fs) { boundingFs = fs; return this;} /************************************************* * Stream methods *************************************************/ @Override public Iterator<T> iterator() {return null; // maybeMakeStream().iterator(); } // @Override // public Spliterator<T> spliterator() { // // TODO Auto-generated method stub // return null; // } @Override public boolean isParallel() { // TODO Auto-generated method stub return false; } @Override public Stream<T> sequential() { // TODO Auto-generated method stub return null; } @Override public Stream<T> parallel() { // TODO Auto-generated method stub return null; } @Override public Stream<T> unordered() { // TODO Auto-generated method stub return null; } @Override public Stream<T> onClose(Runnable closeHandler) { // TODO Auto-generated method stub return null; } @Override public void close() { // TODO Auto-generated method stub } @Override public Stream<T> filter(Predicate<? super T> predicate) { // TODO Auto-generated method stub return null; } @Override public <R> Stream<R> map(Function<? super T, ? extends R> mapper) { // TODO Auto-generated method stub return null; } @Override public IntStream mapToInt(ToIntFunction<? super T> mapper) { // TODO Auto-generated method stub return null; } @Override public LongStream mapToLong(ToLongFunction<? super T> mapper) { // TODO Auto-generated method stub return null; } @Override public DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper) { // TODO Auto-generated method stub return null; } @Override public <R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper) { // TODO Auto-generated method stub return null; } @Override public IntStream flatMapToInt(Function<? super T, ? extends IntStream> mapper) { // TODO Auto-generated method stub return null; } @Override public LongStream flatMapToLong(Function<? super T, ? extends LongStream> mapper) { // TODO Auto-generated method stub return null; } @Override public DoubleStream flatMapToDouble(Function<? super T, ? extends DoubleStream> mapper) { // TODO Auto-generated method stub return null; } @Override public Stream<T> distinct() { // TODO Auto-generated method stub return null; } @Override public Stream<T> sorted() { // TODO Auto-generated method stub return null; } @Override public Stream<T> sorted(Comparator<? super T> comparator) { // TODO Auto-generated method stub return null; } @Override public Stream<T> peek(Consumer<? super T> action) { // TODO Auto-generated method stub return null; } @Override public Stream<T> limit(long maxSize) { // TODO Auto-generated method stub return null; } @Override public Stream<T> skip(long n) { // TODO Auto-generated method stub return null; } @Override public void forEach(Consumer<? super T> action) { // TODO Auto-generated method stub } @Override public void forEachOrdered(Consumer<? super T> action) { // TODO Auto-generated method stub } @Override public Object[] toArray() { // TODO Auto-generated method stub return null; } @Override public <A> A[] toArray(IntFunction<A[]> generator) { // TODO Auto-generated method stub return null; } @Override public T reduce(T identity, BinaryOperator<T> accumulator) { // TODO Auto-generated method stub return null; } @Override public Optional<T> reduce(BinaryOperator<T> accumulator) { // TODO Auto-generated method stub return null; } @Override public <U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner) { // TODO Auto-generated method stub return null; } @Override public <R> R collect(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner) { // TODO Auto-generated method stub return null; } @Override public <R, A> R collect(Collector<? super T, A, R> collector) { // TODO Auto-generated method stub return null; } @Override public Optional<T> min(Comparator<? super T> comparator) { // TODO Auto-generated method stub return null; } @Override public Optional<T> max(Comparator<? super T> comparator) { // TODO Auto-generated method stub return null; } @Override public long count() { // TODO Auto-generated method stub return 0; } @Override public boolean anyMatch(Predicate<? super T> predicate) { // TODO Auto-generated method stub return false; } @Override public boolean allMatch(Predicate<? super T> predicate) { // TODO Auto-generated method stub return false; } @Override public boolean noneMatch(Predicate<? super T> predicate) { // TODO Auto-generated method stub return false; } @Override public Optional<T> findFirst() { // TODO Auto-generated method stub return null; } @Override public Optional<T> findAny() { // TODO Auto-generated method stub return null; } @Override public Spliterator<T> spliterator() { // TODO Auto-generated method stub return null; } }
[UIMA-5115] delete unused trial class accidentally checked in git-svn-id: 2a54995f166126d351a7f865b2a601044a84628f@1763204 13f79535-47bb-0310-9956-ffa450edef68
uimaj-core/src/main/java/org/apache/uima/cas/impl/AnnotStream.java
[UIMA-5115] delete unused trial class accidentally checked in
<ide><path>imaj-core/src/main/java/org/apache/uima/cas/impl/AnnotStream.java <del>/* <del> * Licensed to the Apache Software Foundation (ASF) under one <del> * or more contributor license agreements. See the NOTICE file <del> * distributed with this work for additional information <del> * regarding copyright ownership. The ASF licenses this file <del> * to you under the Apache License, Version 2.0 (the <del> * "License"); you may not use this file except in compliance <del> * with the License. You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, <del> * software distributed under the License is distributed on an <del> * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY <del> * KIND, either express or implied. See the License for the <del> * specific language governing permissions and limitations <del> * under the License. <del> */ <del> <del>package org.apache.uima.cas.impl; <del> <del>import java.util.Comparator; <del>import java.util.Iterator; <del>import java.util.Optional; <del>import java.util.Spliterator; <del>import java.util.function.BiConsumer; <del>import java.util.function.BiFunction; <del>import java.util.function.BinaryOperator; <del>import java.util.function.Consumer; <del>import java.util.function.Function; <del>import java.util.function.IntFunction; <del>import java.util.function.Predicate; <del>import java.util.function.Supplier; <del>import java.util.function.ToDoubleFunction; <del>import java.util.function.ToIntFunction; <del>import java.util.function.ToLongFunction; <del>import java.util.stream.Collector; <del>import java.util.stream.DoubleStream; <del>import java.util.stream.IntStream; <del>import java.util.stream.LongStream; <del>import java.util.stream.Stream; <del> <del>import org.apache.uima.cas.Type; <del>import org.apache.uima.cas.text.AnnotationFS; <del>import org.apache.uima.jcas.cas.TOP; <del>import org.apache.uima.jcas.impl.JCasImpl; <del> <del>/** <del> * A builder class for streams over Annotation Indexes <del> * Use: <del> * AnnotStream as = new AnnotStream( optional args ); <del> * as.<configure methods and args>; // chained <del> * e.g. reverse(), boundedBy(fs), strict(true), unambiguous(true), typePriorities(false) <del> * <del> * as.stream() - followed by normal stream operations <del> * as.spliterator() <del> */ <del>public class AnnotStream <T extends AnnotationFS> implements Stream<T> { <del> <del> private final CASImpl cas; <del> private TypeImpl type; <del> private boolean isReverse; <del> private boolean isStrict; <del> private boolean isUnambiguous; <del> private boolean isUseTypePriorities; <del> private TOP boundingFs; <del> <del> AnnotStream(FsIndex_singletype fsi) { <del> this.cas = fsi.casImpl; <del> this.type = fsi.getTypeImpl(); <del> } <del> <del> public AnnotStream reverse() {return reverse(true);} <del> public AnnotStream reverse(boolean b) {isReverse = b; return this;} <del> <del> public AnnotStream strict() { return strict(true); } <del> public AnnotStream strict(boolean b) {isStrict = b; return this;} <del> <del> public AnnotStream useTypePriorities() { return useTypePriorities(true); } <del> public AnnotStream useTypePriorities(boolean b) {isUseTypePriorities = b; return this;} <del> <del> public AnnotStream boundingFs(TOP fs) { boundingFs = fs; return this;} <del> <del> /************************************************* <del> * Stream methods <del> *************************************************/ <del> @Override <del> public Iterator<T> iterator() {return null; <del>// maybeMakeStream().iterator(); <del> } <del> <del>// @Override <del>// public Spliterator<T> spliterator() { <del>// // TODO Auto-generated method stub <del>// return null; <del>// } <del> <del> @Override <del> public boolean isParallel() { <del> // TODO Auto-generated method stub <del> return false; <del> } <del> <del> @Override <del> public Stream<T> sequential() { <del> // TODO Auto-generated method stub <del> return null; <del> } <del> <del> @Override <del> public Stream<T> parallel() { <del> // TODO Auto-generated method stub <del> return null; <del> } <del> <del> @Override <del> public Stream<T> unordered() { <del> // TODO Auto-generated method stub <del> return null; <del> } <del> <del> @Override <del> public Stream<T> onClose(Runnable closeHandler) { <del> // TODO Auto-generated method stub <del> return null; <del> } <del> <del> @Override <del> public void close() { <del> // TODO Auto-generated method stub <del> <del> } <del> <del> @Override <del> public Stream<T> filter(Predicate<? super T> predicate) { <del> // TODO Auto-generated method stub <del> return null; <del> } <del> <del> @Override <del> public <R> Stream<R> map(Function<? super T, ? extends R> mapper) { <del> // TODO Auto-generated method stub <del> return null; <del> } <del> <del> @Override <del> public IntStream mapToInt(ToIntFunction<? super T> mapper) { <del> // TODO Auto-generated method stub <del> return null; <del> } <del> <del> @Override <del> public LongStream mapToLong(ToLongFunction<? super T> mapper) { <del> // TODO Auto-generated method stub <del> return null; <del> } <del> <del> @Override <del> public DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper) { <del> // TODO Auto-generated method stub <del> return null; <del> } <del> <del> @Override <del> public <R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper) { <del> // TODO Auto-generated method stub <del> return null; <del> } <del> <del> @Override <del> public IntStream flatMapToInt(Function<? super T, ? extends IntStream> mapper) { <del> // TODO Auto-generated method stub <del> return null; <del> } <del> <del> @Override <del> public LongStream flatMapToLong(Function<? super T, ? extends LongStream> mapper) { <del> // TODO Auto-generated method stub <del> return null; <del> } <del> <del> @Override <del> public DoubleStream flatMapToDouble(Function<? super T, ? extends DoubleStream> mapper) { <del> // TODO Auto-generated method stub <del> return null; <del> } <del> <del> @Override <del> public Stream<T> distinct() { <del> // TODO Auto-generated method stub <del> return null; <del> } <del> <del> @Override <del> public Stream<T> sorted() { <del> // TODO Auto-generated method stub <del> return null; <del> } <del> <del> @Override <del> public Stream<T> sorted(Comparator<? super T> comparator) { <del> // TODO Auto-generated method stub <del> return null; <del> } <del> <del> @Override <del> public Stream<T> peek(Consumer<? super T> action) { <del> // TODO Auto-generated method stub <del> return null; <del> } <del> <del> @Override <del> public Stream<T> limit(long maxSize) { <del> // TODO Auto-generated method stub <del> return null; <del> } <del> <del> @Override <del> public Stream<T> skip(long n) { <del> // TODO Auto-generated method stub <del> return null; <del> } <del> <del> @Override <del> public void forEach(Consumer<? super T> action) { <del> // TODO Auto-generated method stub <del> <del> } <del> <del> @Override <del> public void forEachOrdered(Consumer<? super T> action) { <del> // TODO Auto-generated method stub <del> <del> } <del> <del> @Override <del> public Object[] toArray() { <del> // TODO Auto-generated method stub <del> return null; <del> } <del> <del> @Override <del> public <A> A[] toArray(IntFunction<A[]> generator) { <del> // TODO Auto-generated method stub <del> return null; <del> } <del> <del> @Override <del> public T reduce(T identity, BinaryOperator<T> accumulator) { <del> // TODO Auto-generated method stub <del> return null; <del> } <del> <del> @Override <del> public Optional<T> reduce(BinaryOperator<T> accumulator) { <del> // TODO Auto-generated method stub <del> return null; <del> } <del> <del> @Override <del> public <U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, <del> BinaryOperator<U> combiner) { <del> // TODO Auto-generated method stub <del> return null; <del> } <del> <del> @Override <del> public <R> R collect(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, <del> BiConsumer<R, R> combiner) { <del> // TODO Auto-generated method stub <del> return null; <del> } <del> <del> @Override <del> public <R, A> R collect(Collector<? super T, A, R> collector) { <del> // TODO Auto-generated method stub <del> return null; <del> } <del> <del> @Override <del> public Optional<T> min(Comparator<? super T> comparator) { <del> // TODO Auto-generated method stub <del> return null; <del> } <del> <del> @Override <del> public Optional<T> max(Comparator<? super T> comparator) { <del> // TODO Auto-generated method stub <del> return null; <del> } <del> <del> @Override <del> public long count() { <del> // TODO Auto-generated method stub <del> return 0; <del> } <del> <del> @Override <del> public boolean anyMatch(Predicate<? super T> predicate) { <del> // TODO Auto-generated method stub <del> return false; <del> } <del> <del> @Override <del> public boolean allMatch(Predicate<? super T> predicate) { <del> // TODO Auto-generated method stub <del> return false; <del> } <del> <del> @Override <del> public boolean noneMatch(Predicate<? super T> predicate) { <del> // TODO Auto-generated method stub <del> return false; <del> } <del> <del> @Override <del> public Optional<T> findFirst() { <del> // TODO Auto-generated method stub <del> return null; <del> } <del> <del> @Override <del> public Optional<T> findAny() { <del> // TODO Auto-generated method stub <del> return null; <del> } <del> <del> @Override <del> public Spliterator<T> spliterator() { <del> // TODO Auto-generated method stub <del> return null; <del> } <del> <del>}
Java
agpl-3.0
132ecc9ac3e152e3adabf6926afe433300ab2bdf
0
bitsquare/bitsquare,bitsquare/bitsquare
/* * This file is part of Bisq. * * Bisq is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * Bisq is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.cli; import bisq.proto.grpc.OfferInfo; import bisq.proto.grpc.TradeInfo; import io.grpc.StatusRuntimeException; import joptsimple.OptionParser; import joptsimple.OptionSet; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.math.BigDecimal; import java.util.Date; import java.util.List; import lombok.extern.slf4j.Slf4j; import static bisq.cli.CurrencyFormat.*; import static bisq.cli.Method.*; import static bisq.cli.opts.OptLabel.*; import static bisq.cli.table.builder.TableType.*; import static bisq.proto.grpc.GetOfferCategoryReply.OfferCategory.BSQ_SWAP; import static java.lang.String.format; import static java.lang.System.err; import static java.lang.System.exit; import static java.lang.System.out; import static java.math.BigDecimal.ZERO; import bisq.cli.opts.ArgumentList; import bisq.cli.opts.CancelOfferOptionParser; import bisq.cli.opts.CreateCryptoCurrencyPaymentAcctOptionParser; import bisq.cli.opts.CreateOfferOptionParser; import bisq.cli.opts.CreatePaymentAcctOptionParser; import bisq.cli.opts.EditOfferOptionParser; import bisq.cli.opts.GetAddressBalanceOptionParser; import bisq.cli.opts.GetBTCMarketPriceOptionParser; import bisq.cli.opts.GetBalanceOptionParser; import bisq.cli.opts.GetOffersOptionParser; import bisq.cli.opts.GetPaymentAcctFormOptionParser; import bisq.cli.opts.GetTradeOptionParser; import bisq.cli.opts.GetTransactionOptionParser; import bisq.cli.opts.OfferIdOptionParser; import bisq.cli.opts.RegisterDisputeAgentOptionParser; import bisq.cli.opts.RemoveWalletPasswordOptionParser; import bisq.cli.opts.SendBsqOptionParser; import bisq.cli.opts.SendBtcOptionParser; import bisq.cli.opts.SetTxFeeRateOptionParser; import bisq.cli.opts.SetWalletPasswordOptionParser; import bisq.cli.opts.SimpleMethodOptionParser; import bisq.cli.opts.TakeOfferOptionParser; import bisq.cli.opts.UnlockWalletOptionParser; import bisq.cli.opts.VerifyBsqSentToAddressOptionParser; import bisq.cli.opts.WithdrawFundsOptionParser; import bisq.cli.table.builder.TableBuilder; /** * A command-line client for the Bisq gRPC API. */ @Slf4j public class CliMain { public static void main(String[] args) { try { run(args); } catch (Throwable t) { err.println("Error: " + t.getMessage()); exit(1); } } public static void run(String[] args) { var parser = new OptionParser(); var helpOpt = parser.accepts(OPT_HELP, "Print this help text") .forHelp(); var hostOpt = parser.accepts(OPT_HOST, "rpc server hostname or ip") .withRequiredArg() .defaultsTo("localhost"); var portOpt = parser.accepts(OPT_PORT, "rpc server port") .withRequiredArg() .ofType(Integer.class) .defaultsTo(9998); var passwordOpt = parser.accepts(OPT_PASSWORD, "rpc server password") .withRequiredArg(); // Parse the CLI opts host, port, password, method name, and help. The help opt // may indicate the user is asking for method level help, and will be excluded // from the parsed options if a method opt is present in String[] args. OptionSet options = parser.parse(new ArgumentList(args).getCLIArguments()); @SuppressWarnings("unchecked") var nonOptionArgs = (List<String>) options.nonOptionArguments(); // If neither the help opt nor a method name is present, print CLI level help // to stderr and throw an exception. if (!options.has(helpOpt) && nonOptionArgs.isEmpty()) { printHelp(parser, err); throw new IllegalArgumentException("no method specified"); } // If the help opt is present, but not a method name, print CLI level help // to stdout. if (options.has(helpOpt) && nonOptionArgs.isEmpty()) { printHelp(parser, out); return; } var host = options.valueOf(hostOpt); var port = options.valueOf(portOpt); var password = options.valueOf(passwordOpt); if (password == null) throw new IllegalArgumentException("missing required 'password' option"); var methodName = nonOptionArgs.get(0); Method method; try { method = getMethodFromCmd(methodName); } catch (IllegalArgumentException ex) { throw new IllegalArgumentException(format("'%s' is not a supported method", methodName)); } GrpcClient client = new GrpcClient(host, port, password); try { switch (method) { case getversion: { if (new SimpleMethodOptionParser(args).parse().isForHelp()) { out.println(client.getMethodHelp(method)); return; } var version = client.getVersion(); out.println(version); return; } case getbalance: { var opts = new GetBalanceOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var currencyCode = opts.getCurrencyCode(); var balances = client.getBalances(currencyCode); switch (currencyCode.toUpperCase()) { case "BSQ": new TableBuilder(BSQ_BALANCE_TBL, balances.getBsq()).build().print(out); break; case "BTC": new TableBuilder(BTC_BALANCE_TBL, balances.getBtc()).build().print(out); break; case "": default: { out.println("BTC"); new TableBuilder(BTC_BALANCE_TBL, balances.getBtc()).build().print(out); out.println("BSQ"); new TableBuilder(BSQ_BALANCE_TBL, balances.getBsq()).build().print(out); break; } } return; } case getaddressbalance: { var opts = new GetAddressBalanceOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var address = opts.getAddress(); var addressBalance = client.getAddressBalance(address); new TableBuilder(ADDRESS_BALANCE_TBL, addressBalance).build().print(out); return; } case getbtcprice: { var opts = new GetBTCMarketPriceOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var currencyCode = opts.getCurrencyCode(); var price = client.getBtcPrice(currencyCode); out.println(formatInternalFiatPrice(price)); return; } case getfundingaddresses: { if (new SimpleMethodOptionParser(args).parse().isForHelp()) { out.println(client.getMethodHelp(method)); return; } var fundingAddresses = client.getFundingAddresses(); new TableBuilder(ADDRESS_BALANCE_TBL, fundingAddresses).build().print(out); return; } case getunusedbsqaddress: { if (new SimpleMethodOptionParser(args).parse().isForHelp()) { out.println(client.getMethodHelp(method)); return; } var address = client.getUnusedBsqAddress(); out.println(address); return; } case sendbsq: { var opts = new SendBsqOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var address = opts.getAddress(); var amount = opts.getAmount(); verifyStringIsValidDecimal(OPT_AMOUNT, amount); var txFeeRate = opts.getFeeRate(); if (!txFeeRate.isEmpty()) verifyStringIsValidLong(OPT_TX_FEE_RATE, txFeeRate); var txInfo = client.sendBsq(address, amount, txFeeRate); out.printf("%s bsq sent to %s in tx %s%n", amount, address, txInfo.getTxId()); return; } case sendbtc: { var opts = new SendBtcOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var address = opts.getAddress(); var amount = opts.getAmount(); verifyStringIsValidDecimal(OPT_AMOUNT, amount); var txFeeRate = opts.getFeeRate(); if (!txFeeRate.isEmpty()) verifyStringIsValidLong(OPT_TX_FEE_RATE, txFeeRate); var memo = opts.getMemo(); var txInfo = client.sendBtc(address, amount, txFeeRate, memo); out.printf("%s btc sent to %s in tx %s%n", amount, address, txInfo.getTxId()); return; } case verifybsqsenttoaddress: { var opts = new VerifyBsqSentToAddressOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var address = opts.getAddress(); var amount = opts.getAmount(); verifyStringIsValidDecimal(OPT_AMOUNT, amount); var bsqWasSent = client.verifyBsqSentToAddress(address, amount); out.printf("%s bsq %s sent to address %s%n", amount, bsqWasSent ? "has been" : "has not been", address); return; } case gettxfeerate: { if (new SimpleMethodOptionParser(args).parse().isForHelp()) { out.println(client.getMethodHelp(method)); return; } var txFeeRate = client.getTxFeeRate(); out.println(formatTxFeeRateInfo(txFeeRate)); return; } case settxfeerate: { var opts = new SetTxFeeRateOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var txFeeRate = client.setTxFeeRate(toLong(opts.getFeeRate())); out.println(formatTxFeeRateInfo(txFeeRate)); return; } case unsettxfeerate: { if (new SimpleMethodOptionParser(args).parse().isForHelp()) { out.println(client.getMethodHelp(method)); return; } var txFeeRate = client.unsetTxFeeRate(); out.println(formatTxFeeRateInfo(txFeeRate)); return; } case gettransaction: { var opts = new GetTransactionOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var txId = opts.getTxId(); var tx = client.getTransaction(txId); new TableBuilder(TRANSACTION_TBL, tx).build().print(out); return; } case createoffer: { var opts = new CreateOfferOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var isSwap = opts.getIsSwap(); var paymentAcctId = opts.getPaymentAccountId(); var direction = opts.getDirection(); var currencyCode = opts.getCurrencyCode(); var amount = toSatoshis(opts.getAmount()); var minAmount = toSatoshis(opts.getMinAmount()); var useMarketBasedPrice = opts.isUsingMktPriceMargin(); var fixedPrice = opts.getFixedPrice(); var marketPriceMargin = opts.getMktPriceMarginAsBigDecimal(); var securityDeposit = isSwap ? 0.00 : toSecurityDepositAsPct(opts.getSecurityDeposit()); var makerFeeCurrencyCode = opts.getMakerFeeCurrencyCode(); var triggerPrice = 0; // Cannot be defined until offer is in book. OfferInfo offer; if (isSwap) { offer = client.createBsqSwapOffer(direction, amount, minAmount, fixedPrice); } else { offer = client.createOffer(direction, currencyCode, amount, minAmount, useMarketBasedPrice, fixedPrice, marketPriceMargin.doubleValue(), securityDeposit, paymentAcctId, makerFeeCurrencyCode, triggerPrice); } new TableBuilder(OFFER_TBL, offer).build().print(out); return; } case editoffer: { var opts = new EditOfferOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var offerId = opts.getOfferId(); var fixedPrice = opts.getFixedPrice(); var isUsingMktPriceMargin = opts.isUsingMktPriceMargin(); var marketPriceMargin = opts.getMktPriceMarginAsBigDecimal(); var triggerPrice = toInternalTriggerPrice(client, offerId, opts.getTriggerPriceAsBigDecimal()); var enable = opts.getEnableAsSignedInt(); var editOfferType = opts.getOfferEditType(); client.editOffer(offerId, fixedPrice, isUsingMktPriceMargin, marketPriceMargin.doubleValue(), triggerPrice, enable, editOfferType); out.println("offer has been edited"); return; } case canceloffer: { var opts = new CancelOfferOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var offerId = opts.getOfferId(); client.cancelOffer(offerId); out.println("offer canceled and removed from offer book"); return; } case getoffer: { var opts = new OfferIdOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var offerId = opts.getOfferId(); var offer = client.getOffer(offerId); new TableBuilder(OFFER_TBL, offer).build().print(out); return; } case getmyoffer: { var opts = new OfferIdOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var offerId = opts.getOfferId(); var offer = client.getMyOffer(offerId); new TableBuilder(OFFER_TBL, offer).build().print(out); return; } case getoffers: { var opts = new GetOffersOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var direction = opts.getDirection(); var currencyCode = opts.getCurrencyCode(); List<OfferInfo> offers = client.getOffers(direction, currencyCode); if (offers.isEmpty()) out.printf("no %s %s offers found%n", direction, currencyCode); else new TableBuilder(OFFER_TBL, offers).build().print(out); return; } case getmyoffers: { var opts = new GetOffersOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var direction = opts.getDirection(); var currencyCode = opts.getCurrencyCode(); List<OfferInfo> offers = client.getMyOffers(direction, currencyCode); if (offers.isEmpty()) out.printf("no %s %s offers found%n", direction, currencyCode); else new TableBuilder(OFFER_TBL, offers).build().print(out); return; } case takeoffer: { var offerIdOpt = new OfferIdOptionParser(args).parse(); if (offerIdOpt.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var offerId = offerIdOpt.getOfferId(); TradeInfo trade; // We only send an 'offer-id' param when taking a BsqSwapOffer. // Find out what kind of offer is being taken before sending a // 'takeoffer' request. var offerCategory = client.getAvailableOfferCategory(offerId); if (offerCategory.equals(BSQ_SWAP)) { trade = client.takeBsqSwapOffer(offerId); } else { var opts = new TakeOfferOptionParser(args).parse(); var paymentAccountId = opts.getPaymentAccountId(); var takerFeeCurrencyCode = opts.getTakerFeeCurrencyCode(); trade = client.takeOffer(offerId, paymentAccountId, takerFeeCurrencyCode); } out.printf("trade %s successfully taken%n", trade.getTradeId()); return; } case gettrade: { // TODO make short-id a valid argument? var opts = new GetTradeOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var tradeId = opts.getTradeId(); var showContract = opts.getShowContract(); var trade = client.getTrade(tradeId); if (showContract) out.println(trade.getContractAsJson()); else new TableBuilder(TRADE_DETAIL_TBL, trade).build().print(out); return; } case confirmpaymentstarted: { var opts = new GetTradeOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var tradeId = opts.getTradeId(); client.confirmPaymentStarted(tradeId); out.printf("trade %s payment started message sent%n", tradeId); return; } case confirmpaymentreceived: { var opts = new GetTradeOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var tradeId = opts.getTradeId(); client.confirmPaymentReceived(tradeId); out.printf("trade %s payment received message sent%n", tradeId); return; } case keepfunds: { var opts = new GetTradeOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var tradeId = opts.getTradeId(); client.keepFunds(tradeId); out.printf("funds from trade %s saved in bisq wallet%n", tradeId); return; } case withdrawfunds: { var opts = new WithdrawFundsOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var tradeId = opts.getTradeId(); var address = opts.getAddress(); // Multi-word memos must be double-quoted. var memo = opts.getMemo(); client.withdrawFunds(tradeId, address, memo); out.printf("trade %s funds sent to btc address %s%n", tradeId, address); return; } case getpaymentmethods: { if (new SimpleMethodOptionParser(args).parse().isForHelp()) { out.println(client.getMethodHelp(method)); return; } var paymentMethods = client.getPaymentMethods(); paymentMethods.forEach(p -> out.println(p.getId())); return; } case getpaymentacctform: { var opts = new GetPaymentAcctFormOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var paymentMethodId = opts.getPaymentMethodId(); String jsonString = client.getPaymentAcctFormAsJson(paymentMethodId); File jsonFile = saveFileToDisk(paymentMethodId.toLowerCase(), ".json", jsonString); out.printf("payment account form %s%nsaved to %s%n", jsonString, jsonFile.getAbsolutePath()); out.println("Edit the file, and use as the argument to a 'createpaymentacct' command."); return; } case createpaymentacct: { var opts = new CreatePaymentAcctOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var paymentAccountForm = opts.getPaymentAcctForm(); String jsonString; try { jsonString = new String(Files.readAllBytes(paymentAccountForm)); } catch (IOException e) { throw new IllegalStateException( format("could not read %s", paymentAccountForm)); } var paymentAccount = client.createPaymentAccount(jsonString); out.println("payment account saved"); new TableBuilder(PAYMENT_ACCOUNT_TBL, paymentAccount).build().print(out); return; } case createcryptopaymentacct: { var opts = new CreateCryptoCurrencyPaymentAcctOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var accountName = opts.getAccountName(); var currencyCode = opts.getCurrencyCode(); var address = opts.getAddress(); var isTradeInstant = opts.getIsTradeInstant(); var paymentAccount = client.createCryptoCurrencyPaymentAccount(accountName, currencyCode, address, isTradeInstant); out.println("payment account saved"); new TableBuilder(PAYMENT_ACCOUNT_TBL, paymentAccount).build().print(out); return; } case getpaymentaccts: { if (new SimpleMethodOptionParser(args).parse().isForHelp()) { out.println(client.getMethodHelp(method)); return; } var paymentAccounts = client.getPaymentAccounts(); if (paymentAccounts.size() > 0) new TableBuilder(PAYMENT_ACCOUNT_TBL, paymentAccounts).build().print(out); else out.println("no payment accounts are saved"); return; } case lockwallet: { if (new SimpleMethodOptionParser(args).parse().isForHelp()) { out.println(client.getMethodHelp(method)); return; } client.lockWallet(); out.println("wallet locked"); return; } case unlockwallet: { var opts = new UnlockWalletOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var walletPassword = opts.getPassword(); var timeout = opts.getUnlockTimeout(); client.unlockWallet(walletPassword, timeout); out.println("wallet unlocked"); return; } case removewalletpassword: { var opts = new RemoveWalletPasswordOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var walletPassword = opts.getPassword(); client.removeWalletPassword(walletPassword); out.println("wallet decrypted"); return; } case setwalletpassword: { var opts = new SetWalletPasswordOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var walletPassword = opts.getPassword(); var newWalletPassword = opts.getNewPassword(); client.setWalletPassword(walletPassword, newWalletPassword); out.println("wallet encrypted" + (!newWalletPassword.isEmpty() ? " with new password" : "")); return; } case registerdisputeagent: { var opts = new RegisterDisputeAgentOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var disputeAgentType = opts.getDisputeAgentType(); var registrationKey = opts.getRegistrationKey(); client.registerDisputeAgent(disputeAgentType, registrationKey); out.println(disputeAgentType + " registered"); return; } case stop: { if (new SimpleMethodOptionParser(args).parse().isForHelp()) { out.println(client.getMethodHelp(method)); return; } client.stopServer(); out.println("server shutdown signal received"); return; } default: { throw new RuntimeException(format("unhandled method '%s'", method)); } } } catch (StatusRuntimeException ex) { // Remove the leading gRPC status code (e.g. "UNKNOWN: ") from the message String message = ex.getMessage().replaceFirst("^[A-Z_]+: ", ""); if (message.equals("io exception")) throw new RuntimeException(message + ", server may not be running", ex); else throw new RuntimeException(message, ex); } } private static Method getMethodFromCmd(String methodName) { // TODO if we use const type for enum we need add some mapping. Even if we don't // change now it is handy to have flexibility in case we change internal code // and don't want to break user commands. return Method.valueOf(methodName.toLowerCase()); } @SuppressWarnings("SameParameterValue") private static void verifyStringIsValidDecimal(String optionLabel, String optionValue) { try { Double.parseDouble(optionValue); } catch (NumberFormatException ex) { throw new IllegalArgumentException(format("--%s=%s, '%s' is not a number", optionLabel, optionValue, optionValue)); } } @SuppressWarnings("SameParameterValue") private static void verifyStringIsValidLong(String optionLabel, String optionValue) { try { Long.parseLong(optionValue); } catch (NumberFormatException ex) { throw new IllegalArgumentException(format("--%s=%s, '%s' is not a number", optionLabel, optionValue, optionValue)); } } private static long toLong(String param) { try { return Long.parseLong(param); } catch (NumberFormatException ex) { throw new IllegalArgumentException(format("'%s' is not a number", param)); } } private static long toInternalTriggerPrice(GrpcClient client, String offerId, BigDecimal unscaledTriggerPrice) { if (unscaledTriggerPrice.compareTo(ZERO) >= 0) { // Unfortunately, the EditOffer proto triggerPrice field was declared as // a long instead of a string, so the CLI has to look at the offer to know // how to scale the trigger-price (for a fiat or altcoin offer) param sent // to the server in its 'editoffer' request. That means a preliminary round // trip to the server: a 'getmyoffer' request. var offer = client.getMyOffer(offerId); if (offer.getCounterCurrencyCode().equals("BTC")) return toInternalCryptoCurrencyPrice(unscaledTriggerPrice); else return toInternalFiatPrice(unscaledTriggerPrice); } else { return 0L; } } private static File saveFileToDisk(String prefix, @SuppressWarnings("SameParameterValue") String suffix, String text) { String timestamp = Long.toUnsignedString(new Date().getTime()); String relativeFileName = prefix + "_" + timestamp + suffix; try { Path path = Paths.get(relativeFileName); if (!Files.exists(path)) { try (PrintWriter out = new PrintWriter(path.toString())) { out.println(text); } return path.toAbsolutePath().toFile(); } else { throw new IllegalStateException(format("could not overwrite existing file '%s'", relativeFileName)); } } catch (FileNotFoundException e) { throw new IllegalStateException(format("could not create file '%s'", relativeFileName)); } } private static void printHelp(OptionParser parser, @SuppressWarnings("SameParameterValue") PrintStream stream) { try { stream.println("Bisq RPC Client"); stream.println(); stream.println("Usage: bisq-cli [options] <method> [params]"); stream.println(); parser.printHelpOn(stream); stream.println(); String rowFormat = "%-25s%-52s%s%n"; stream.format(rowFormat, "Method", "Params", "Description"); stream.format(rowFormat, "------", "------", "------------"); stream.format(rowFormat, getversion.name(), "", "Get server version"); stream.println(); stream.format(rowFormat, getbalance.name(), "[--currency-code=<bsq|btc>]", "Get server wallet balances"); stream.println(); stream.format(rowFormat, getaddressbalance.name(), "--address=<btc-address>", "Get server wallet address balance"); stream.println(); stream.format(rowFormat, getbtcprice.name(), "--currency-code=<currency-code>", "Get current market btc price"); stream.println(); stream.format(rowFormat, getfundingaddresses.name(), "", "Get BTC funding addresses"); stream.println(); stream.format(rowFormat, getunusedbsqaddress.name(), "", "Get unused BSQ address"); stream.println(); stream.format(rowFormat, sendbsq.name(), "--address=<bsq-address> --amount=<bsq-amount> \\", "Send BSQ"); stream.format(rowFormat, "", "[--tx-fee-rate=<sats/byte>]", ""); stream.println(); stream.format(rowFormat, sendbtc.name(), "--address=<btc-address> --amount=<btc-amount> \\", "Send BTC"); stream.format(rowFormat, "", "[--tx-fee-rate=<sats/byte>]", ""); stream.format(rowFormat, "", "[--memo=<\"memo\">]", ""); stream.println(); stream.format(rowFormat, verifybsqsenttoaddress.name(), "--address=<bsq-address> --amount=<bsq-amount>", "Verify amount was sent to BSQ wallet address"); stream.println(); stream.format(rowFormat, gettxfeerate.name(), "", "Get current tx fee rate in sats/byte"); stream.println(); stream.format(rowFormat, settxfeerate.name(), "--tx-fee-rate=<sats/byte>", "Set custom tx fee rate in sats/byte"); stream.println(); stream.format(rowFormat, unsettxfeerate.name(), "", "Unset custom tx fee rate"); stream.println(); stream.format(rowFormat, gettransaction.name(), "--transaction-id=<transaction-id>", "Get transaction with id"); stream.println(); stream.format(rowFormat, createoffer.name(), "--payment-account=<payment-account-id> \\", "Create and place an offer"); stream.format(rowFormat, "", "--direction=<buy|sell> \\", ""); stream.format(rowFormat, "", "--currency-code=<currency-code> \\", ""); stream.format(rowFormat, "", "--amount=<btc-amount> \\", ""); stream.format(rowFormat, "", "[--min-amount=<min-btc-amount>] \\", ""); stream.format(rowFormat, "", "--fixed-price=<price> | --market-price=margin=<percent> \\", ""); stream.format(rowFormat, "", "--security-deposit=<percent> \\", ""); stream.format(rowFormat, "", "[--fee-currency=<bsq|btc>]", ""); stream.format(rowFormat, "", "[--trigger-price=<price>]", ""); stream.format(rowFormat, "", "[--swap=<true|false>]", ""); stream.println(); stream.format(rowFormat, editoffer.name(), "--offer-id=<offer-id> \\", "Edit offer with id"); stream.format(rowFormat, "", "[--fixed-price=<price>] \\", ""); stream.format(rowFormat, "", "[--market-price-margin=<percent>] \\", ""); stream.format(rowFormat, "", "[--trigger-price=<price>] \\", ""); stream.format(rowFormat, "", "[--enabled=<true|false>]", ""); stream.println(); stream.format(rowFormat, canceloffer.name(), "--offer-id=<offer-id>", "Cancel offer with id"); stream.println(); stream.format(rowFormat, getoffer.name(), "--offer-id=<offer-id>", "Get current offer with id"); stream.println(); stream.format(rowFormat, getmyoffer.name(), "--offer-id=<offer-id>", "Get my current offer with id"); stream.println(); stream.format(rowFormat, getoffers.name(), "--direction=<buy|sell> \\", "Get current offers"); stream.format(rowFormat, "", "--currency-code=<currency-code>", ""); stream.println(); stream.format(rowFormat, getmyoffers.name(), "--direction=<buy|sell> \\", "Get my current offers"); stream.format(rowFormat, "", "--currency-code=<currency-code>", ""); stream.println(); stream.format(rowFormat, takeoffer.name(), "--offer-id=<offer-id> \\", "Take offer with id"); stream.format(rowFormat, "", "[--payment-account=<payment-account-id>]", ""); stream.format(rowFormat, "", "[--fee-currency=<btc|bsq>]", ""); stream.println(); stream.format(rowFormat, gettrade.name(), "--trade-id=<trade-id> \\", "Get trade summary or full contract"); stream.format(rowFormat, "", "[--show-contract=<true|false>]", ""); stream.println(); stream.format(rowFormat, confirmpaymentstarted.name(), "--trade-id=<trade-id>", "Confirm payment started"); stream.println(); stream.format(rowFormat, confirmpaymentreceived.name(), "--trade-id=<trade-id>", "Confirm payment received"); stream.println(); stream.format(rowFormat, keepfunds.name(), "--trade-id=<trade-id>", "Keep received funds in Bisq wallet"); stream.println(); stream.format(rowFormat, withdrawfunds.name(), "--trade-id=<trade-id> --address=<btc-address> \\", "Withdraw received funds to external wallet address"); stream.format(rowFormat, "", "[--memo=<\"memo\">]", ""); stream.println(); stream.format(rowFormat, getpaymentmethods.name(), "", "Get list of supported payment account method ids"); stream.println(); stream.format(rowFormat, getpaymentacctform.name(), "--payment-method-id=<payment-method-id>", "Get a new payment account form"); stream.println(); stream.format(rowFormat, createpaymentacct.name(), "--payment-account-form=<path>", "Create a new payment account"); stream.println(); stream.format(rowFormat, createcryptopaymentacct.name(), "--account-name=<name> \\", "Create a new cryptocurrency payment account"); stream.format(rowFormat, "", "--currency-code=<bsq> \\", ""); stream.format(rowFormat, "", "--address=<bsq-address>", ""); stream.format(rowFormat, "", "--trade-instant=<true|false>", ""); stream.println(); stream.format(rowFormat, getpaymentaccts.name(), "", "Get user payment accounts"); stream.println(); stream.format(rowFormat, lockwallet.name(), "", "Remove wallet password from memory, locking the wallet"); stream.println(); stream.format(rowFormat, unlockwallet.name(), "--wallet-password=<password> --timeout=<seconds>", "Store wallet password in memory for timeout seconds"); stream.println(); stream.format(rowFormat, setwalletpassword.name(), "--wallet-password=<password> \\", "Encrypt wallet with password, or set new password on encrypted wallet"); stream.format(rowFormat, "", "[--new-wallet-password=<new-password>]", ""); stream.println(); stream.format(rowFormat, stop.name(), "", "Shut down the server"); stream.println(); stream.println("Method Help Usage: bisq-cli [options] <method> --help"); stream.println(); } catch (IOException ex) { ex.printStackTrace(stream); } } }
cli/src/main/java/bisq/cli/CliMain.java
/* * This file is part of Bisq. * * Bisq is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * Bisq is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.cli; import bisq.proto.grpc.OfferInfo; import bisq.proto.grpc.TradeInfo; import io.grpc.StatusRuntimeException; import joptsimple.OptionParser; import joptsimple.OptionSet; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.math.BigDecimal; import java.util.Date; import java.util.List; import lombok.extern.slf4j.Slf4j; import static bisq.cli.CurrencyFormat.*; import static bisq.cli.Method.*; import static bisq.cli.opts.OptLabel.*; import static bisq.cli.table.builder.TableType.*; import static bisq.proto.grpc.GetOfferCategoryReply.OfferCategory.BSQ_SWAP; import static java.lang.String.format; import static java.lang.System.err; import static java.lang.System.exit; import static java.lang.System.out; import static java.math.BigDecimal.ZERO; import bisq.cli.opts.ArgumentList; import bisq.cli.opts.CancelOfferOptionParser; import bisq.cli.opts.CreateCryptoCurrencyPaymentAcctOptionParser; import bisq.cli.opts.CreateOfferOptionParser; import bisq.cli.opts.CreatePaymentAcctOptionParser; import bisq.cli.opts.EditOfferOptionParser; import bisq.cli.opts.GetAddressBalanceOptionParser; import bisq.cli.opts.GetBTCMarketPriceOptionParser; import bisq.cli.opts.GetBalanceOptionParser; import bisq.cli.opts.GetOffersOptionParser; import bisq.cli.opts.GetPaymentAcctFormOptionParser; import bisq.cli.opts.GetTradeOptionParser; import bisq.cli.opts.GetTransactionOptionParser; import bisq.cli.opts.OfferIdOptionParser; import bisq.cli.opts.RegisterDisputeAgentOptionParser; import bisq.cli.opts.RemoveWalletPasswordOptionParser; import bisq.cli.opts.SendBsqOptionParser; import bisq.cli.opts.SendBtcOptionParser; import bisq.cli.opts.SetTxFeeRateOptionParser; import bisq.cli.opts.SetWalletPasswordOptionParser; import bisq.cli.opts.SimpleMethodOptionParser; import bisq.cli.opts.TakeOfferOptionParser; import bisq.cli.opts.UnlockWalletOptionParser; import bisq.cli.opts.VerifyBsqSentToAddressOptionParser; import bisq.cli.opts.WithdrawFundsOptionParser; import bisq.cli.table.builder.TableBuilder; /** * A command-line client for the Bisq gRPC API. */ @Slf4j public class CliMain { public static void main(String[] args) { try { run(args); } catch (Throwable t) { err.println("Error: " + t.getMessage()); exit(1); } } public static void run(String[] args) { var parser = new OptionParser(); var helpOpt = parser.accepts(OPT_HELP, "Print this help text") .forHelp(); var hostOpt = parser.accepts(OPT_HOST, "rpc server hostname or ip") .withRequiredArg() .defaultsTo("localhost"); var portOpt = parser.accepts(OPT_PORT, "rpc server port") .withRequiredArg() .ofType(Integer.class) .defaultsTo(9998); var passwordOpt = parser.accepts(OPT_PASSWORD, "rpc server password") .withRequiredArg(); // Parse the CLI opts host, port, password, method name, and help. The help opt // may indicate the user is asking for method level help, and will be excluded // from the parsed options if a method opt is present in String[] args. OptionSet options = parser.parse(new ArgumentList(args).getCLIArguments()); @SuppressWarnings("unchecked") var nonOptionArgs = (List<String>) options.nonOptionArguments(); // If neither the help opt nor a method name is present, print CLI level help // to stderr and throw an exception. if (!options.has(helpOpt) && nonOptionArgs.isEmpty()) { printHelp(parser, err); throw new IllegalArgumentException("no method specified"); } // If the help opt is present, but not a method name, print CLI level help // to stdout. if (options.has(helpOpt) && nonOptionArgs.isEmpty()) { printHelp(parser, out); return; } var host = options.valueOf(hostOpt); var port = options.valueOf(portOpt); var password = options.valueOf(passwordOpt); if (password == null) throw new IllegalArgumentException("missing required 'password' option"); var methodName = nonOptionArgs.get(0); Method method; try { method = getMethodFromCmd(methodName); } catch (IllegalArgumentException ex) { throw new IllegalArgumentException(format("'%s' is not a supported method", methodName)); } GrpcClient client = new GrpcClient(host, port, password); try { switch (method) { case getversion: { if (new SimpleMethodOptionParser(args).parse().isForHelp()) { out.println(client.getMethodHelp(method)); return; } var version = client.getVersion(); out.println(version); return; } case getbalance: { var opts = new GetBalanceOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var currencyCode = opts.getCurrencyCode(); var balances = client.getBalances(currencyCode); switch (currencyCode.toUpperCase()) { case "BSQ": new TableBuilder(BSQ_BALANCE_TBL, balances.getBsq()).build().print(out); break; case "BTC": new TableBuilder(BTC_BALANCE_TBL, balances.getBtc()).build().print(out); break; case "": default: { out.println("BTC"); new TableBuilder(BTC_BALANCE_TBL, balances.getBtc()).build().print(out); out.println("BSQ"); new TableBuilder(BSQ_BALANCE_TBL, balances.getBsq()).build().print(out); break; } } return; } case getaddressbalance: { var opts = new GetAddressBalanceOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var address = opts.getAddress(); var addressBalance = client.getAddressBalance(address); new TableBuilder(ADDRESS_BALANCE_TBL, addressBalance).build().print(out); return; } case getbtcprice: { var opts = new GetBTCMarketPriceOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var currencyCode = opts.getCurrencyCode(); var price = client.getBtcPrice(currencyCode); out.println(formatInternalFiatPrice(price)); return; } case getfundingaddresses: { if (new SimpleMethodOptionParser(args).parse().isForHelp()) { out.println(client.getMethodHelp(method)); return; } var fundingAddresses = client.getFundingAddresses(); new TableBuilder(ADDRESS_BALANCE_TBL, fundingAddresses).build().print(out); return; } case getunusedbsqaddress: { if (new SimpleMethodOptionParser(args).parse().isForHelp()) { out.println(client.getMethodHelp(method)); return; } var address = client.getUnusedBsqAddress(); out.println(address); return; } case sendbsq: { var opts = new SendBsqOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var address = opts.getAddress(); var amount = opts.getAmount(); verifyStringIsValidDecimal(OPT_AMOUNT, amount); var txFeeRate = opts.getFeeRate(); if (!txFeeRate.isEmpty()) verifyStringIsValidLong(OPT_TX_FEE_RATE, txFeeRate); var txInfo = client.sendBsq(address, amount, txFeeRate); out.printf("%s bsq sent to %s in tx %s%n", amount, address, txInfo.getTxId()); return; } case sendbtc: { var opts = new SendBtcOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var address = opts.getAddress(); var amount = opts.getAmount(); verifyStringIsValidDecimal(OPT_AMOUNT, amount); var txFeeRate = opts.getFeeRate(); if (!txFeeRate.isEmpty()) verifyStringIsValidLong(OPT_TX_FEE_RATE, txFeeRate); var memo = opts.getMemo(); var txInfo = client.sendBtc(address, amount, txFeeRate, memo); out.printf("%s btc sent to %s in tx %s%n", amount, address, txInfo.getTxId()); return; } case verifybsqsenttoaddress: { var opts = new VerifyBsqSentToAddressOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var address = opts.getAddress(); var amount = opts.getAmount(); verifyStringIsValidDecimal(OPT_AMOUNT, amount); var bsqWasSent = client.verifyBsqSentToAddress(address, amount); out.printf("%s bsq %s sent to address %s%n", amount, bsqWasSent ? "has been" : "has not been", address); return; } case gettxfeerate: { if (new SimpleMethodOptionParser(args).parse().isForHelp()) { out.println(client.getMethodHelp(method)); return; } var txFeeRate = client.getTxFeeRate(); out.println(formatTxFeeRateInfo(txFeeRate)); return; } case settxfeerate: { var opts = new SetTxFeeRateOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var txFeeRate = client.setTxFeeRate(toLong(opts.getFeeRate())); out.println(formatTxFeeRateInfo(txFeeRate)); return; } case unsettxfeerate: { if (new SimpleMethodOptionParser(args).parse().isForHelp()) { out.println(client.getMethodHelp(method)); return; } var txFeeRate = client.unsetTxFeeRate(); out.println(formatTxFeeRateInfo(txFeeRate)); return; } case gettransaction: { var opts = new GetTransactionOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var txId = opts.getTxId(); var tx = client.getTransaction(txId); new TableBuilder(TRANSACTION_TBL, tx).build().print(out); return; } case createoffer: { var opts = new CreateOfferOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var paymentAcctId = opts.getPaymentAccountId(); var direction = opts.getDirection(); var currencyCode = opts.getCurrencyCode(); var amount = toSatoshis(opts.getAmount()); var minAmount = toSatoshis(opts.getMinAmount()); var useMarketBasedPrice = opts.isUsingMktPriceMargin(); var fixedPrice = opts.getFixedPrice(); var marketPriceMargin = opts.getMktPriceMarginAsBigDecimal(); var securityDeposit = toSecurityDepositAsPct(opts.getSecurityDeposit()); var makerFeeCurrencyCode = opts.getMakerFeeCurrencyCode(); var triggerPrice = 0; // Cannot be defined until offer is in book. var offer = client.createOffer(direction, currencyCode, amount, minAmount, useMarketBasedPrice, fixedPrice, marketPriceMargin.doubleValue(), securityDeposit, paymentAcctId, makerFeeCurrencyCode, triggerPrice); new TableBuilder(OFFER_TBL, offer).build().print(out); return; } case editoffer: { var opts = new EditOfferOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var offerId = opts.getOfferId(); var fixedPrice = opts.getFixedPrice(); var isUsingMktPriceMargin = opts.isUsingMktPriceMargin(); var marketPriceMargin = opts.getMktPriceMarginAsBigDecimal(); var triggerPrice = toInternalTriggerPrice(client, offerId, opts.getTriggerPriceAsBigDecimal()); var enable = opts.getEnableAsSignedInt(); var editOfferType = opts.getOfferEditType(); client.editOffer(offerId, fixedPrice, isUsingMktPriceMargin, marketPriceMargin.doubleValue(), triggerPrice, enable, editOfferType); out.println("offer has been edited"); return; } case canceloffer: { var opts = new CancelOfferOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var offerId = opts.getOfferId(); client.cancelOffer(offerId); out.println("offer canceled and removed from offer book"); return; } case getoffer: { var opts = new OfferIdOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var offerId = opts.getOfferId(); var offer = client.getOffer(offerId); new TableBuilder(OFFER_TBL, offer).build().print(out); return; } case getmyoffer: { var opts = new OfferIdOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var offerId = opts.getOfferId(); var offer = client.getMyOffer(offerId); new TableBuilder(OFFER_TBL, offer).build().print(out); return; } case getoffers: { var opts = new GetOffersOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var direction = opts.getDirection(); var currencyCode = opts.getCurrencyCode(); List<OfferInfo> offers = client.getOffers(direction, currencyCode); if (offers.isEmpty()) out.printf("no %s %s offers found%n", direction, currencyCode); else new TableBuilder(OFFER_TBL, offers).build().print(out); return; } case getmyoffers: { var opts = new GetOffersOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var direction = opts.getDirection(); var currencyCode = opts.getCurrencyCode(); List<OfferInfo> offers = client.getMyOffers(direction, currencyCode); if (offers.isEmpty()) out.printf("no %s %s offers found%n", direction, currencyCode); else new TableBuilder(OFFER_TBL, offers).build().print(out); return; } case takeoffer: { var offerIdOpt = new OfferIdOptionParser(args).parse(); if (offerIdOpt.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var offerId = offerIdOpt.getOfferId(); TradeInfo trade; // We only send an 'offer-id' param when taking a BsqSwapOffer. // Find out what kind of offer is being taken before sending a // 'takeoffer' request. var offerCategory = client.getAvailableOfferCategory(offerId); if (offerCategory.equals(BSQ_SWAP)) { trade = client.takeBsqSwapOffer(offerId); } else { var opts = new TakeOfferOptionParser(args).parse(); var paymentAccountId = opts.getPaymentAccountId(); var takerFeeCurrencyCode = opts.getTakerFeeCurrencyCode(); trade = client.takeOffer(offerId, paymentAccountId, takerFeeCurrencyCode); } out.printf("trade %s successfully taken%n", trade.getTradeId()); return; } case gettrade: { // TODO make short-id a valid argument? var opts = new GetTradeOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var tradeId = opts.getTradeId(); var showContract = opts.getShowContract(); var trade = client.getTrade(tradeId); if (showContract) out.println(trade.getContractAsJson()); else new TableBuilder(TRADE_DETAIL_TBL, trade).build().print(out); return; } case confirmpaymentstarted: { var opts = new GetTradeOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var tradeId = opts.getTradeId(); client.confirmPaymentStarted(tradeId); out.printf("trade %s payment started message sent%n", tradeId); return; } case confirmpaymentreceived: { var opts = new GetTradeOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var tradeId = opts.getTradeId(); client.confirmPaymentReceived(tradeId); out.printf("trade %s payment received message sent%n", tradeId); return; } case keepfunds: { var opts = new GetTradeOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var tradeId = opts.getTradeId(); client.keepFunds(tradeId); out.printf("funds from trade %s saved in bisq wallet%n", tradeId); return; } case withdrawfunds: { var opts = new WithdrawFundsOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var tradeId = opts.getTradeId(); var address = opts.getAddress(); // Multi-word memos must be double-quoted. var memo = opts.getMemo(); client.withdrawFunds(tradeId, address, memo); out.printf("trade %s funds sent to btc address %s%n", tradeId, address); return; } case getpaymentmethods: { if (new SimpleMethodOptionParser(args).parse().isForHelp()) { out.println(client.getMethodHelp(method)); return; } var paymentMethods = client.getPaymentMethods(); paymentMethods.forEach(p -> out.println(p.getId())); return; } case getpaymentacctform: { var opts = new GetPaymentAcctFormOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var paymentMethodId = opts.getPaymentMethodId(); String jsonString = client.getPaymentAcctFormAsJson(paymentMethodId); File jsonFile = saveFileToDisk(paymentMethodId.toLowerCase(), ".json", jsonString); out.printf("payment account form %s%nsaved to %s%n", jsonString, jsonFile.getAbsolutePath()); out.println("Edit the file, and use as the argument to a 'createpaymentacct' command."); return; } case createpaymentacct: { var opts = new CreatePaymentAcctOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var paymentAccountForm = opts.getPaymentAcctForm(); String jsonString; try { jsonString = new String(Files.readAllBytes(paymentAccountForm)); } catch (IOException e) { throw new IllegalStateException( format("could not read %s", paymentAccountForm)); } var paymentAccount = client.createPaymentAccount(jsonString); out.println("payment account saved"); new TableBuilder(PAYMENT_ACCOUNT_TBL, paymentAccount).build().print(out); return; } case createcryptopaymentacct: { var opts = new CreateCryptoCurrencyPaymentAcctOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var accountName = opts.getAccountName(); var currencyCode = opts.getCurrencyCode(); var address = opts.getAddress(); var isTradeInstant = opts.getIsTradeInstant(); var paymentAccount = client.createCryptoCurrencyPaymentAccount(accountName, currencyCode, address, isTradeInstant); out.println("payment account saved"); new TableBuilder(PAYMENT_ACCOUNT_TBL, paymentAccount).build().print(out); return; } case getpaymentaccts: { if (new SimpleMethodOptionParser(args).parse().isForHelp()) { out.println(client.getMethodHelp(method)); return; } var paymentAccounts = client.getPaymentAccounts(); if (paymentAccounts.size() > 0) new TableBuilder(PAYMENT_ACCOUNT_TBL, paymentAccounts).build().print(out); else out.println("no payment accounts are saved"); return; } case lockwallet: { if (new SimpleMethodOptionParser(args).parse().isForHelp()) { out.println(client.getMethodHelp(method)); return; } client.lockWallet(); out.println("wallet locked"); return; } case unlockwallet: { var opts = new UnlockWalletOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var walletPassword = opts.getPassword(); var timeout = opts.getUnlockTimeout(); client.unlockWallet(walletPassword, timeout); out.println("wallet unlocked"); return; } case removewalletpassword: { var opts = new RemoveWalletPasswordOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var walletPassword = opts.getPassword(); client.removeWalletPassword(walletPassword); out.println("wallet decrypted"); return; } case setwalletpassword: { var opts = new SetWalletPasswordOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var walletPassword = opts.getPassword(); var newWalletPassword = opts.getNewPassword(); client.setWalletPassword(walletPassword, newWalletPassword); out.println("wallet encrypted" + (!newWalletPassword.isEmpty() ? " with new password" : "")); return; } case registerdisputeagent: { var opts = new RegisterDisputeAgentOptionParser(args).parse(); if (opts.isForHelp()) { out.println(client.getMethodHelp(method)); return; } var disputeAgentType = opts.getDisputeAgentType(); var registrationKey = opts.getRegistrationKey(); client.registerDisputeAgent(disputeAgentType, registrationKey); out.println(disputeAgentType + " registered"); return; } case stop: { if (new SimpleMethodOptionParser(args).parse().isForHelp()) { out.println(client.getMethodHelp(method)); return; } client.stopServer(); out.println("server shutdown signal received"); return; } default: { throw new RuntimeException(format("unhandled method '%s'", method)); } } } catch (StatusRuntimeException ex) { // Remove the leading gRPC status code (e.g. "UNKNOWN: ") from the message String message = ex.getMessage().replaceFirst("^[A-Z_]+: ", ""); if (message.equals("io exception")) throw new RuntimeException(message + ", server may not be running", ex); else throw new RuntimeException(message, ex); } } private static Method getMethodFromCmd(String methodName) { // TODO if we use const type for enum we need add some mapping. Even if we don't // change now it is handy to have flexibility in case we change internal code // and don't want to break user commands. return Method.valueOf(methodName.toLowerCase()); } @SuppressWarnings("SameParameterValue") private static void verifyStringIsValidDecimal(String optionLabel, String optionValue) { try { Double.parseDouble(optionValue); } catch (NumberFormatException ex) { throw new IllegalArgumentException(format("--%s=%s, '%s' is not a number", optionLabel, optionValue, optionValue)); } } @SuppressWarnings("SameParameterValue") private static void verifyStringIsValidLong(String optionLabel, String optionValue) { try { Long.parseLong(optionValue); } catch (NumberFormatException ex) { throw new IllegalArgumentException(format("--%s=%s, '%s' is not a number", optionLabel, optionValue, optionValue)); } } private static long toLong(String param) { try { return Long.parseLong(param); } catch (NumberFormatException ex) { throw new IllegalArgumentException(format("'%s' is not a number", param)); } } private static long toInternalTriggerPrice(GrpcClient client, String offerId, BigDecimal unscaledTriggerPrice) { if (unscaledTriggerPrice.compareTo(ZERO) >= 0) { // Unfortunately, the EditOffer proto triggerPrice field was declared as // a long instead of a string, so the CLI has to look at the offer to know // how to scale the trigger-price (for a fiat or altcoin offer) param sent // to the server in its 'editoffer' request. That means a preliminary round // trip to the server: a 'getmyoffer' request. var offer = client.getMyOffer(offerId); if (offer.getCounterCurrencyCode().equals("BTC")) return toInternalCryptoCurrencyPrice(unscaledTriggerPrice); else return toInternalFiatPrice(unscaledTriggerPrice); } else { return 0L; } } private static File saveFileToDisk(String prefix, @SuppressWarnings("SameParameterValue") String suffix, String text) { String timestamp = Long.toUnsignedString(new Date().getTime()); String relativeFileName = prefix + "_" + timestamp + suffix; try { Path path = Paths.get(relativeFileName); if (!Files.exists(path)) { try (PrintWriter out = new PrintWriter(path.toString())) { out.println(text); } return path.toAbsolutePath().toFile(); } else { throw new IllegalStateException(format("could not overwrite existing file '%s'", relativeFileName)); } } catch (FileNotFoundException e) { throw new IllegalStateException(format("could not create file '%s'", relativeFileName)); } } private static void printHelp(OptionParser parser, @SuppressWarnings("SameParameterValue") PrintStream stream) { try { stream.println("Bisq RPC Client"); stream.println(); stream.println("Usage: bisq-cli [options] <method> [params]"); stream.println(); parser.printHelpOn(stream); stream.println(); String rowFormat = "%-25s%-52s%s%n"; stream.format(rowFormat, "Method", "Params", "Description"); stream.format(rowFormat, "------", "------", "------------"); stream.format(rowFormat, getversion.name(), "", "Get server version"); stream.println(); stream.format(rowFormat, getbalance.name(), "[--currency-code=<bsq|btc>]", "Get server wallet balances"); stream.println(); stream.format(rowFormat, getaddressbalance.name(), "--address=<btc-address>", "Get server wallet address balance"); stream.println(); stream.format(rowFormat, getbtcprice.name(), "--currency-code=<currency-code>", "Get current market btc price"); stream.println(); stream.format(rowFormat, getfundingaddresses.name(), "", "Get BTC funding addresses"); stream.println(); stream.format(rowFormat, getunusedbsqaddress.name(), "", "Get unused BSQ address"); stream.println(); stream.format(rowFormat, sendbsq.name(), "--address=<bsq-address> --amount=<bsq-amount> \\", "Send BSQ"); stream.format(rowFormat, "", "[--tx-fee-rate=<sats/byte>]", ""); stream.println(); stream.format(rowFormat, sendbtc.name(), "--address=<btc-address> --amount=<btc-amount> \\", "Send BTC"); stream.format(rowFormat, "", "[--tx-fee-rate=<sats/byte>]", ""); stream.format(rowFormat, "", "[--memo=<\"memo\">]", ""); stream.println(); stream.format(rowFormat, verifybsqsenttoaddress.name(), "--address=<bsq-address> --amount=<bsq-amount>", "Verify amount was sent to BSQ wallet address"); stream.println(); stream.format(rowFormat, gettxfeerate.name(), "", "Get current tx fee rate in sats/byte"); stream.println(); stream.format(rowFormat, settxfeerate.name(), "--tx-fee-rate=<sats/byte>", "Set custom tx fee rate in sats/byte"); stream.println(); stream.format(rowFormat, unsettxfeerate.name(), "", "Unset custom tx fee rate"); stream.println(); stream.format(rowFormat, gettransaction.name(), "--transaction-id=<transaction-id>", "Get transaction with id"); stream.println(); stream.format(rowFormat, createoffer.name(), "--payment-account=<payment-account-id> \\", "Create and place an offer"); stream.format(rowFormat, "", "--direction=<buy|sell> \\", ""); stream.format(rowFormat, "", "--currency-code=<currency-code> \\", ""); stream.format(rowFormat, "", "--amount=<btc-amount> \\", ""); stream.format(rowFormat, "", "[--min-amount=<min-btc-amount>] \\", ""); stream.format(rowFormat, "", "--fixed-price=<price> | --market-price=margin=<percent> \\", ""); stream.format(rowFormat, "", "--security-deposit=<percent> \\", ""); stream.format(rowFormat, "", "[--fee-currency=<bsq|btc>]", ""); stream.format(rowFormat, "", "[--trigger-price=<price>]", ""); stream.println(); stream.format(rowFormat, editoffer.name(), "--offer-id=<offer-id> \\", "Edit offer with id"); stream.format(rowFormat, "", "[--fixed-price=<price>] \\", ""); stream.format(rowFormat, "", "[--market-price-margin=<percent>] \\", ""); stream.format(rowFormat, "", "[--trigger-price=<price>] \\", ""); stream.format(rowFormat, "", "[--enabled=<true|false>]", ""); stream.println(); stream.format(rowFormat, canceloffer.name(), "--offer-id=<offer-id>", "Cancel offer with id"); stream.println(); stream.format(rowFormat, getoffer.name(), "--offer-id=<offer-id>", "Get current offer with id"); stream.println(); stream.format(rowFormat, getmyoffer.name(), "--offer-id=<offer-id>", "Get my current offer with id"); stream.println(); stream.format(rowFormat, getoffers.name(), "--direction=<buy|sell> \\", "Get current offers"); stream.format(rowFormat, "", "--currency-code=<currency-code>", ""); stream.println(); stream.format(rowFormat, getmyoffers.name(), "--direction=<buy|sell> \\", "Get my current offers"); stream.format(rowFormat, "", "--currency-code=<currency-code>", ""); stream.println(); stream.format(rowFormat, takeoffer.name(), "--offer-id=<offer-id> \\", "Take offer with id"); stream.format(rowFormat, "", "[--payment-account=<payment-account-id>]", ""); stream.format(rowFormat, "", "[--fee-currency=<btc|bsq>]", ""); stream.println(); stream.format(rowFormat, gettrade.name(), "--trade-id=<trade-id> \\", "Get trade summary or full contract"); stream.format(rowFormat, "", "[--show-contract=<true|false>]", ""); stream.println(); stream.format(rowFormat, confirmpaymentstarted.name(), "--trade-id=<trade-id>", "Confirm payment started"); stream.println(); stream.format(rowFormat, confirmpaymentreceived.name(), "--trade-id=<trade-id>", "Confirm payment received"); stream.println(); stream.format(rowFormat, keepfunds.name(), "--trade-id=<trade-id>", "Keep received funds in Bisq wallet"); stream.println(); stream.format(rowFormat, withdrawfunds.name(), "--trade-id=<trade-id> --address=<btc-address> \\", "Withdraw received funds to external wallet address"); stream.format(rowFormat, "", "[--memo=<\"memo\">]", ""); stream.println(); stream.format(rowFormat, getpaymentmethods.name(), "", "Get list of supported payment account method ids"); stream.println(); stream.format(rowFormat, getpaymentacctform.name(), "--payment-method-id=<payment-method-id>", "Get a new payment account form"); stream.println(); stream.format(rowFormat, createpaymentacct.name(), "--payment-account-form=<path>", "Create a new payment account"); stream.println(); stream.format(rowFormat, createcryptopaymentacct.name(), "--account-name=<name> \\", "Create a new cryptocurrency payment account"); stream.format(rowFormat, "", "--currency-code=<bsq> \\", ""); stream.format(rowFormat, "", "--address=<bsq-address>", ""); stream.format(rowFormat, "", "--trade-instant=<true|false>", ""); stream.println(); stream.format(rowFormat, getpaymentaccts.name(), "", "Get user payment accounts"); stream.println(); stream.format(rowFormat, lockwallet.name(), "", "Remove wallet password from memory, locking the wallet"); stream.println(); stream.format(rowFormat, unlockwallet.name(), "--wallet-password=<password> --timeout=<seconds>", "Store wallet password in memory for timeout seconds"); stream.println(); stream.format(rowFormat, setwalletpassword.name(), "--wallet-password=<password> \\", "Encrypt wallet with password, or set new password on encrypted wallet"); stream.format(rowFormat, "", "[--new-wallet-password=<new-password>]", ""); stream.println(); stream.format(rowFormat, stop.name(), "", "Shut down the server"); stream.println(); stream.println("Method Help Usage: bisq-cli [options] <method> --help"); stream.println(); } catch (IOException ex) { ex.printStackTrace(stream); } } }
Adjust CliMain's createoffer for BSQ swaps
cli/src/main/java/bisq/cli/CliMain.java
Adjust CliMain's createoffer for BSQ swaps
<ide><path>li/src/main/java/bisq/cli/CliMain.java <ide> out.println(client.getMethodHelp(method)); <ide> return; <ide> } <add> var isSwap = opts.getIsSwap(); <ide> var paymentAcctId = opts.getPaymentAccountId(); <ide> var direction = opts.getDirection(); <ide> var currencyCode = opts.getCurrencyCode(); <ide> var useMarketBasedPrice = opts.isUsingMktPriceMargin(); <ide> var fixedPrice = opts.getFixedPrice(); <ide> var marketPriceMargin = opts.getMktPriceMarginAsBigDecimal(); <del> var securityDeposit = toSecurityDepositAsPct(opts.getSecurityDeposit()); <add> var securityDeposit = isSwap ? 0.00 : toSecurityDepositAsPct(opts.getSecurityDeposit()); <ide> var makerFeeCurrencyCode = opts.getMakerFeeCurrencyCode(); <ide> var triggerPrice = 0; // Cannot be defined until offer is in book. <del> var offer = client.createOffer(direction, <del> currencyCode, <del> amount, <del> minAmount, <del> useMarketBasedPrice, <del> fixedPrice, <del> marketPriceMargin.doubleValue(), <del> securityDeposit, <del> paymentAcctId, <del> makerFeeCurrencyCode, <del> triggerPrice); <add> OfferInfo offer; <add> if (isSwap) { <add> offer = client.createBsqSwapOffer(direction, <add> amount, <add> minAmount, <add> fixedPrice); <add> } else { <add> offer = client.createOffer(direction, <add> currencyCode, <add> amount, <add> minAmount, <add> useMarketBasedPrice, <add> fixedPrice, <add> marketPriceMargin.doubleValue(), <add> securityDeposit, <add> paymentAcctId, <add> makerFeeCurrencyCode, <add> triggerPrice); <add> } <ide> new TableBuilder(OFFER_TBL, offer).build().print(out); <ide> return; <ide> } <ide> stream.format(rowFormat, "", "--security-deposit=<percent> \\", ""); <ide> stream.format(rowFormat, "", "[--fee-currency=<bsq|btc>]", ""); <ide> stream.format(rowFormat, "", "[--trigger-price=<price>]", ""); <add> stream.format(rowFormat, "", "[--swap=<true|false>]", ""); <ide> stream.println(); <ide> stream.format(rowFormat, editoffer.name(), "--offer-id=<offer-id> \\", "Edit offer with id"); <ide> stream.format(rowFormat, "", "[--fixed-price=<price>] \\", "");
JavaScript
mit
61f2f0d4661979c9f7d3a9bf41658ef99cc86063
0
c2gconsulting/bp-core,c2gconsulting/bp-core,c2gconsulting/bp-core,c2gconsulting/bp-core,c2gconsulting/bp-core
import _ from 'underscore'; import moment from 'moment'; let littleHelpers = { paddArrayWithZeros: function(array, fullLengthWithZeros) { let lengthOfArray = array.length for(let i = 0; i < fullLengthWithZeros - lengthOfArray; i++) { array.push(0) } } } let getEmployeedEmployees = (paygrade, period, businessId, businessUnitConfig) => { check(paygrade, Array); const year = period.year; const month = period.month; const firsDayOfPeriod = `${month}-01-${year} GMT`; const DateLimit = new Date(firsDayOfPeriod); let dateLimitMoment = moment(DateLimit) let dateLimitMonth = dateLimitMoment.month() let dateLimitYear = dateLimitMoment.year() if(businessUnitConfig) { let checkEmployeeResumptionForPayroll = businessUnitConfig.checkEmployeeResumptionForPayroll if(checkEmployeeResumptionForPayroll) { let allUsers = Meteor.users.find({'employeeProfile.employment.status': 'Active', $or: [ {'employeeProfile.employment.terminationDate': {$gt: DateLimit}}, {'employeeProfile.employment.terminationDate': null}, {'employeeProfile.employment.terminationDate' : ''}, {'employeeProfile.employment.terminationDate' : { $exists : false } } ], 'employeeProfile.employment.paygrade': {$in: paygrade}, 'businessIds': businessId, 'employee': true }).fetch(); let users = [] allUsers.forEach(aUser => { let userHireDate = aUser.employeeProfile.employment.hireDate if(userHireDate) { let userHireDateMoment = moment(userHireDate) if(dateLimitMoment.isSameOrAfter(userHireDateMoment)) { users.push(aUser) } } }) return users } else { return Meteor.users.find({'employeeProfile.employment.status': 'Active', $or: [ {'employeeProfile.employment.terminationDate': {$gt: DateLimit}}, {'employeeProfile.employment.terminationDate': null}, {'employeeProfile.employment.terminationDate' : { $exists : false } } ], 'employeeProfile.employment.paygrade': {$in: paygrade}, 'businessIds': businessId, 'employee': true }).fetch(); } } else { return [] } }; /** * Payruns Methods */ Meteor.methods({ /* Get net monthly pay amount NMP */ 'exportPaymentsforPeriod': (businessId, period) => { //get all payroll result for specified period if employee is authorized check(period, String); check(businessId, String); const result = Payruns.find({businessId: businessId, period: period}).fetch(); const paytypes = [], export_header = ["Full Name", "Employee Number", "Period"]; //for every header, loop at employee payment and populate value result.forEach(x => { let payments = x.payment; // for every payment, push value if it exists or 0.00 into result payments.forEach(p => { const header = {code: p.code , reference: p.reference}; const index = _.findLastIndex(paytypes, header); if(index === -1) { paytypes.push(header); export_header.push(p.code); } }); }); //header population complete now use header index and fill each employee data // review this method const data = []; result.forEach(x => { // for every payment, push value if it exists or 0.00 into result //get personnel details first let employee = Meteor.users.findOne({_id: x.employeeId}); if (employee) { //push employee name, employeeId and period const employeePay = []; employeePay.push(employee.profile.fullName); employeePay.push(employee.employeeProfile.employeeId); employeePay.push(x.period); paytypes.forEach(p => { const payments = x.payment; const index = _.findLastIndex(payments, p); if(index > -1) { employeePay.push(payments[index].amountPC); } else { employeePay.push(0.00); } }); data.push(employeePay); } }); let exportData = {fields: export_header, data: data}; return exportData ; }, /* Get net monthly pay amount NMP */ 'ExportNetPayResult': (businessId, period) => { //get all payroll result for specified period if employee is authorized check(period, String); check(businessId, String); if(!Core.hasPayrollAccess(Meteor.userId())){ throw new Meteor.Error(401, 'Unauthorized'); } else { const header = [ "Full Name", "Bank", "Account Number", ]; let tenantId = Core.getTenantId(Meteor.userId()) let tenant = Tenants.findOne(tenantId) const result = Payruns.find({businessId: businessId, period: period}).fetch(); const netpay = result.map(x => { let dataRow = [] let employee = Meteor.users.findOne({_id: x.employeeId}); if(employee){ dataRow = [ employee.profile.fullName, employee.employeeProfile.payment.bank || '', employee.employeeProfile.payment.accountNumber || '' ]; } let numPayments = x.payment.length for(let i = 0; i < numPayments; i++) { if(x.payment[i].code === 'NMP') {// Got a net pay if(x.payment[i].reference === 'Standard') { let foundAmountHeader = _.find(header, aHeader => { return aHeader === 'Amount (' + tenant.baseCurrency.iso + ')' }) if(!foundAmountHeader) { header.push('Amount (' + tenant.baseCurrency.iso + ')') } dataRow.push(x.payment[i].amountPC) } else if(x.payment[i].reference.startsWith('Standard_')) { let currency = x.payment[i].reference.substring('Standard_'.length) let foundAmountHeader = _.find(header, aHeader => { return aHeader === 'Amount (' + currency + ')' }) if(!foundAmountHeader) { header.push('Amount (' + currency + ')') } dataRow.push(x.payment[i].amountPC) } } } return dataRow }); return {fields: header, data: netpay}; } }, /* Get net monthly pay amount NMP */ 'getnetPayResult': (businessId, period) => { //get all payroll result for specified period if employee is authorized check(period, String); check(businessId, String); if(Core.hasPayrollAccess(this.userid)){ throw new Meteor.Error(401, 'Unauthorized'); } else { const header = [ "Full Name", "Bank", "Account Number", ]; let tenantId = Core.getTenantId(Meteor.userId()) let tenant = Tenants.findOne(tenantId) const result = Payruns.find({businessId: businessId, period: period}).fetch(); const netpayData = result.map(x => { let dataRow = [] let employee = Meteor.users.findOne({_id: x.employeeId}); if(employee) { dataRow = [ employee._id, employee.profile.fullName, employee.employeeProfile.payment.bank, employee.employeeProfile.payment.accountNumber || '' ]; littleHelpers.paddArrayWithZeros(dataRow, header.length - 1) } let numPayments = x.payment.length for(let i = 0; i < numPayments; i++) { if(x.payment[i].code === 'NMP') {// Got a net pay if(x.payment[i].reference === 'Standard') { let indexOfHeader = -1 let foundAmountHeader = _.find(header, (aHeader, headerIndex) => { if(aHeader === 'Amount (' + tenant.baseCurrency.iso + ')') { indexOfHeader = headerIndex return true } }) if(!foundAmountHeader) { header.push('Amount (' + tenant.baseCurrency.iso + ')') dataRow.push(0) indexOfHeader = dataRow.length - 1 } else { indexOfHeader += 1 } dataRow[indexOfHeader] = x.payment[i].amountPC } else if(x.payment[i].reference.startsWith('Standard_')) { let indexOfHeader = -1 let currency = x.payment[i].reference.substring('Standard_'.length) let foundAmountHeader = _.find(header, (aHeader, headerIndex) => { if(aHeader === 'Amount (' + currency + ')') { indexOfHeader = headerIndex return true } }) if(!foundAmountHeader) { header.push('Amount (' + currency + ')') dataRow.push(0) indexOfHeader = dataRow.length - 1 } else { indexOfHeader += 1 } // dataRow.push(x.payment[i].amountPC) dataRow[indexOfHeader] = x.payment[i].amountPC } } } return dataRow }); return { headers: header, data: netpayData } } }, /* Export Tax payment */ 'exportTaxResult': (businessId, period) => { //get all payroll result for specified period if employee is authorized check(period, String); check(businessId, String); if(Core.hasPayrollAccess(this.userid)){ throw new Meteor.Error(401, 'Unauthorized'); } else { const result = Payruns.find({businessId: businessId, period: period, 'payment.reference': 'Tax'}).fetch(); const tax = result.map(x => { const taxIndex = _.findLastIndex(x.payment, {reference: 'Tax'}); //get amount in paytype currency for standard paytype NMP(Net monthly pay) if(taxIndex > -1) { const amountLC = x.payment[taxIndex].amountLC; //get employee details let employee = Meteor.users.findOne({_id: x.employeeId}); if(employee){ return [ employee.profile.fullName, employee.employeeProfile.state, employee.employeeProfile.payment.taxPayerId, amountLC ]; } } }); const header = [ "Full Name", "Resident State", "Tax Payer ID", "Amount" ]; return {fields: header, data: tax}; } }, /* Get Tax pay */ 'getTaxResult': (businessId, period) => { //get all payroll result for specified period if employee is authorized check(period, String); check(businessId, String); if(Core.hasPayrollAccess(this.userid)){ throw new Meteor.Error(401, 'Unauthorized'); } else { const result = Payruns.find({businessId: businessId, period: period, 'payment.reference': 'Tax'}).fetch(); const tax = result.map(x => { const taxIndex = _.findLastIndex(x.payment, {reference: 'Tax'}); //get amount in paytype currency for standard paytype NMP(Net monthly pay) if(taxIndex > -1) { const taxCode = x.payment[taxIndex].code; const amountPC = x.payment[taxIndex].amountPC; //get employee details let employee = Meteor.users.findOne({_id: x.employeeId}); if(employee){ const info = { fullName: employee.profile.fullName, state: employee.employeeProfile.state, code: taxCode, taxPayerId: employee.employeeProfile.payment.taxPayerId, amount: amountPC }; return info; } } }); return tax; } }, 'exportPensionResult': (businessId, period) => { //get all payroll result for specified period if employee is authorized check(period, String); check(businessId, String); if(Core.hasPayrollAccess(this.userId)){ throw new Meteor.Error(401, 'Unauthorized'); } else { const result = Payruns.find({businessId: businessId, period: period, 'payment.reference': 'Pension'}).fetch(); const pension = result.map(x => { const pensionsContribution = _.where(x.payment, {reference: 'Pension'}); //get all pension pay) if(pensionsContribution.length) { const pensionAmount = {}; let pensionDescription; pensionsContribution.forEach(x => { //pension is always suffixed with _EE or _ER const pensionLength = x.code.length; if (!pensionDescription) pensionDescription = x.description; const type = x.code.substring(pensionLength, pensionLength - 3); //returns _EE or _ER if(type === '_EE') pensionAmount.employeeContribution = x.amountPC; if(type === '_ER') pensionAmount.employerContribution = x.amountPC; }); //get employee details let employee = Meteor.users.findOne({_id: x.employeeId}); if(employee){ return [ employee.profile.fullName, employee.employeeProfile.payment.pensionmanager, employee.employeeProfile.payment.RSAPin, pensionAmount.employeeContribution, pensionAmount.employerContribution ] } } }); const header = [ "Full Name", "Pension Fund Administrator", "RSA PIN", "Employee Contribution", "Employer Contribution" ]; return {fields: header, data: pension}; } }, 'getPensionResult': (businessId, period) => { //get all payroll result for specified period if employee is authorized check(period, String); check(businessId, String); if(Core.hasPayrollAccess(this.userId)){ throw new Meteor.Error(401, 'Unauthorized'); } else { const result = Payruns.find({businessId: businessId, period: period, 'payment.reference': 'Pension'}).fetch(); const pension = result.map(x => { const pensionsContribution = _.where(x.payment, {reference: 'Pension'}); //get all pension pay) if(pensionsContribution.length) { const pensionAmount = {}; let pensionDescription; pensionsContribution.forEach(x => { //pension is always suffixed with _EE or _ER const pensionLength = x.code.length; if (!pensionDescription) pensionDescription = x.description; const type = x.code.substring(pensionLength, pensionLength - 3); //returns _EE or _ER if(type === '_EE') pensionAmount.employeeContribution = x.amountPC; if(type === '_ER') pensionAmount.employerContribution = x.amountPC; }); //get employee details let employee = Meteor.users.findOne({_id: x.employeeId}); if(employee){ const info = { fullName: employee.profile.fullName, pensionManager: employee.employeeProfile.payment.pensionmanager, pin: employee.employeeProfile.payment.RSAPin, employeeContribution: pensionAmount.employeeContribution, employerContribution: pensionAmount.employerContribution } return info; } } }); return pension; } }, /* Payment run */ "payrun/process": function (obj, businessId) { //check if user is in businessId if (!this.userId && Core.hasPayrollAccess(this.userId)) { throw new Meteor.Error(401, "Unauthorized"); } let userId = Meteor.userId(); this.unblock(); console.log(obj); let employees = obj.employees; const paygrades = obj.paygrades; const period = obj.period; const runtype = obj.type; const annuals = obj.annuals; let retroactivePayrun = obj.retroactivePayrun if(retroactivePayrun === 'true') { retroactivePayrun = true } else { retroactivePayrun = false } check(employees, Array); check(period, Object); check(runtype, String); check(paygrades, Array); let res; let payObj = {}; let businessUnitConfig = BusinessUnitCustomConfigs.findOne({businessId: businessId}) //get all selected employees --Condition-- if employees selected, ideally there should be no paygrade if (employees.length === 0 && paygrades.length > 0) { res = getEmployeedEmployees(paygrades, period, businessId, businessUnitConfig); //res contains employees ready for payment processing if (res && res.length > 0) { payObj = processEmployeePay(Meteor.userId(), res, annuals, businessId, period, businessUnitConfig, retroactivePayrun, false); } } else if (employees.length > 0) { const year = period.year; const month = period.month; const firsDayOfPeriod = `${month}-01-${year} GMT`; const DateLimit = new Date(firsDayOfPeriod); //get all employees specified //return empoloyee and reason why payroll cannot be run for such employee if any let users = [] if(businessUnitConfig) { let checkEmployeeResumptionForPayroll = businessUnitConfig.checkEmployeeResumptionForPayroll if(checkEmployeeResumptionForPayroll) { let allUsers = Meteor.users.find({_id: {$in: employees}, $or: [ {'employeeProfile.employment.terminationDate': {$gt: DateLimit}}, {'employeeProfile.employment.terminationDate': null}, {'employeeProfile.employment.terminationDate': ""}, {'employeeProfile.employment.terminationDate' : { $exists : false } } ], 'employeeProfile.employment.status': 'Active', 'businessIds': businessId }).fetch(); let dateLimitMoment = moment(DateLimit) let dateLimitMonth = dateLimitMoment.month() let dateLimitYear = dateLimitMoment.year() allUsers.forEach(aUser => { let userHireDate = aUser.employeeProfile.employment.hireDate if(userHireDate) { let userHireDateMoment = moment(userHireDate) if(dateLimitMoment.isSameOrAfter(userHireDateMoment)) { users.push(aUser) } } }) } else { users = Meteor.users.find({_id: {$in: employees}, $or: [ {'employeeProfile.employment.terminationDate': {$gt: DateLimit}}, {'employeeProfile.employment.terminationDate': null}, {'employeeProfile.employment.terminationDate': ""}, {'employeeProfile.employment.terminationDate' : { $exists : false } } ], 'employeeProfile.employment.status': 'Active', 'businessIds': businessId }).fetch(); } } payObj = users && processEmployeePay(Meteor.userId(), users, annuals, businessId, period, businessUnitConfig, retroactivePayrun, false); } //if live run and no error then save result if (runtype === 'LiveRun' && payObj.error.length === 0){ //store result in Payrun Collection. try { let payrollApprovalConfig = PayrollApprovalConfigs.findOne({businessId: businessId}) let requirePayrollApproval; let approvals; if(payrollApprovalConfig) { if(payrollApprovalConfig.requirePayrollApproval) { requirePayrollApproval = true } else { requirePayrollApproval = false } approvals = [] } else { approvals = null } payObj.payrun.forEach(x => { x.payrunDoneBy = userId x.requirePayrollApproval = requirePayrollApproval x.approvals = approvals Payruns.insert(x); }) payObj.result.forEach(x => { x.period = `${period.month}${period.year}` x.businessId = businessId x.employeeId = x.payslip.employee.employeeUserId PayResults.insert(x); }) } catch (e){ console.log(e); } } else { console.log("Payrun errors: " + JSON.stringify(payObj.error)); } //just return something for now .... testing return {payObj, runtype, period}; } }); /* I am truly sorry for the code you are about to read. It was bad when I started working on it. The function was too long to start refactoring. I could have broken something so I didn't clean it up. */ // // use oop // instantiate payment object for employee with props for all methods required processEmployeePay = function (currentUserId, employees, includedAnnuals, businessId, period, businessUnitConfig, isRetroActivePayrunEnabled, isDoingARetroActivePayrunNow) { let paygrades = []; let payresult = []; // holds result that will be sent to client let payrun = []; //holds payrun for storing if not simulation let specifiedAsProcess = function (paytype) { return _.indexOf(includedAnnuals, paytype) !== -1 ? true : false; }; processingError = []; let count = 0; const periodFormat = period.month + period.year;// format is 012017 ex. let tenantId = Core.getTenantId(currentUserId) let tenant = Tenants.findOne(tenantId) let currencyRatesForPeriod = Currencies.find({businessId: businessId, period: periodFormat}).fetch() let runPayrun = (counter) => { let x = employees[counter]; if (x) { //first check if result exist for employee for that period and if not, continue processing. result = Payruns.findOne({employeeId: x._id, period: periodFormat, businessId: businessId}); if (result){ //add relevant errors const error = {}; error.employee = `${x.employeeProfile.employeeId} - ${x.profile.fullName}`; error.reason = `Payment Exists for Period ${periodFormat}`; error.details = `Cannot Process Payroll for Employee ... as Payment for this period exists. To run payroll, Contact Admin to cross-check and delete previous payment data if neccessary`; processingError.push(error); } else { if(isRetroActivePayrunEnabled && !isDoingARetroActivePayrunNow) { const payrunPeriodAsDate = new Date(`${period.month}-01-${period.year} GMT`); const payrunPeriodAsMoment = moment(payrunPeriodAsDate); const prevMonthMoment = payrunPeriodAsMoment.subtract(1, 'month') const payrunPeriodForPrevMonth = prevMonthMoment.format("MMYYYY") let prevMonth = payrunPeriodForPrevMonth.substring(0, 2) let prevMonthYear = payrunPeriodForPrevMonth.substring(2) let doesEmpHavePayrunForPrevMonth = Payruns.findOne({ period: payrunPeriodForPrevMonth, employeeId: x._id }) if(!doesEmpHavePayrunForPrevMonth) { let retroactivity = processEmployeePay(Meteor.userId(), [x], includedAnnuals, businessId, {month: prevMonth, year: prevMonthYear}, businessUnitConfig, isRetroActivePayrunEnabled, true); let retroactivityResult = retroactivity.result let retroactivityError = retroactivity.error let retroactivityPayrun = retroactivity.payrun payresult = payresult.concat(retroactivityResult) processingError = processingError.concat(retroactivityError) payrun = payrun.concat(retroactivityPayrun) } } const employeeResult = { businessId: businessId, employeeId: x._id, period: periodFormat, payment : [] }; //holds every payment to be saved for employee in payrun //-- const year = period.year; const month = period.month; const firsDayOfPeriod = `${month}-01-${year} GMT`; const firsDayOfPeriodAsDate = new Date(firsDayOfPeriod); let numDaysEmployeeCanWorkInMonth = getDaysEmployeeCanWorkInMonth(x, firsDayOfPeriodAsDate) let totalNumWeekDaysInMonth = getWeekDays(firsDayOfPeriodAsDate, moment(firsDayOfPeriodAsDate).endOf('month').toDate()).length //-- //--Time recording things const projectsPayDetails = getFractionForCalcProjectsPayValue(businessId, period.month, period.year, totalNumWeekDaysInMonth, x._id) // {duration: , fraction: } const costCentersPayDetails = getFractionForCalcCostCentersPayValue(businessId, period.month, period.year, totalNumWeekDaysInMonth, x._id) // {duration: , fraction: } let totalHoursWorkedInPeriod = projectsPayDetails.duration + costCentersPayDetails.duration //-- const pg = x.employeeProfile.employment.paygrade; //paygrade let pt = x.employeeProfile.employment.paytypes; //paytype let grade, pgp; //grade(paygrade) && pgp(paygroup); const gradeIndex = _.findLastIndex(paygrades, {_id: pg}); let empSpecificType; //contains employee payments derived from paygrade if (gradeIndex !== -1) { grade = paygrades[gradeIndex]; empSpecificType = determineRule(pt, grade); } else { //get paygrade and update paygrades grade = getEmployeeGrade(pg); if (grade) { paygrades.push(grade); empSpecificType = determineRule(pt, grade); } } if (grade && grade.hasOwnProperty('payGroups') && grade.payGroups.length > 0) { pgp = grade.payGroups[0]; //first element of paygroup// {review} } //payElemnts derivation; const {tax, pension} = getPaygroup(pgp); let defaultTaxBucket = 0, pensionBucket = 0, log = []; //check if pagrade uses default tax bucket let assignedTaxBucket, grossIncomeBucket = 0, totalsBucket = 0, reliefBucket = 0; let empDerivedPayElements = []; let benefit = [], deduction = [], others = []; let rules = new ruleJS(); rules.init(); let skipToNextEmployee = false; //-- let paymentsAccountingForCurrency = {benefit: {}, deduction: {}, others: {}} // Each key in each of the above keys will be a currency code // Each object for each currency code will be an array of payments //-- try { //let formular = x.value let paytypes = empSpecificType.map(x => { //changes paygrades of currently processed employee to include paytypes let ptype = PayTypes.findOne({_id: x.paytype, 'status': 'Active'}); delete x.paytype; _.extend(x, ptype); return x; }); //import additonal pay and duduction value based on employeeProfile.employeeId for period in collection AdditionalPayments. const addPay = AdditionalPayments.find({businessId: businessId, employee: x.employeeProfile.employeeId, period: periodFormat}).fetch(); //include additional pay to match paytype values if(addPay && addPay.length > 0) { let formattedPay = getPaytypeIdandValue(addPay, businessId) || []; if(formattedPay && formattedPay.length > 0) { formattedPay.forEach(x => { let index = _.findLastIndex(paytypes, {_id: x._id}); if (index > -1) { //found paytypes[index].value = x.value; paytypes[index].additionalPay = true; //add additional pay flag to skip monthly division } }); } } paytypes.forEach((x, index) => { //skip processing of Annual non selected annual paytypes //revisit this to factor in all payment frequency and create a logic on how processing is made if (x.frequency !== 'Annually' || (x.frequency === 'Annually' && specifiedAsProcess(x._id))) { // if (true) { let input = [], processing = []; input.push({ code: 'Number of days employee can work in month', value: numDaysEmployeeCanWorkInMonth }) input.push({ code: 'Number of hours employee can work in month', value: numDaysEmployeeCanWorkInMonth * 8 }) input.push({ code: 'Number of working days in month', value: totalNumWeekDaysInMonth }) if(x.isTimeWritingDependent) { input.push({ code: 'Hours worked on projects in month', value: projectsPayDetails.duration }) input.push({ code: 'Hours worked on cost centers in month', value: costCentersPayDetails.duration }) input.push({ code: 'Pay from cost-centers multiplier fraction', value: costCentersPayDetails.fraction }) } let boundary = [...paytypes]; //available types as at current processing boundary.length = index + 1; //format boundary for display in log let clone = boundary.map(x => { let b = {}; b.code = x.code; b.value = x.value; return b; }); input = input.concat(clone); let formula = x.value; let old = formula; if (formula) { //replace all wagetypes with values for (var i = 0; i < index; i++) { const code = paytypes[i].code ? paytypes[i].code.toUpperCase() : paytypes[i].code; const pattern = `\\b${code}\\b`; const regex = new RegExp(pattern, "g"); formula = formula.replace(regex, paytypes[i].value); } //do the same for all contansts and replace the values //will find a better way of doing this... NOTE let k = Constants.find({'businessId': businessId, 'status': 'Active'}).fetch(); //limit constant to only Bu constant k.forEach(c => { const code = c.code ? c.code.toUpperCase() : c.code; const pattern = `\\b${code}\\b`; const regex = new RegExp(pattern, "g"); formula = formula.replace(regex, c.value); }); processing.push({code: x.code, previous: old, derived: formula}); var parsed = rules.parse(formula, ''); if (parsed.result !== null && !isNaN(parsed.result)) { //negate value if paytype is deduction. x.parsedValue = x.type === 'Deduction' ? parsed.result.toFixed(2) * -1 : parsed.result.toFixed(2); //defaulting to 2 dp ... Make configurable; //-- let netPayTypeAmount; //net amount used if payment type is monthly if(x.frequency === 'Monthly' && !x.additionalPay){ netPayTypeAmount = (x.parsedValue / 12).toFixed(2); processing.push({code: `${x.code} - Monthly(NET)`, derived: netPayTypeAmount}); } //if add to total, add wt to totalsBucket totalsBucket += x.addToTotal ? parseFloat(x.parsedValue) : 0; //-- //add parsed value to defaultTax bucket if paytype is taxable if(tenant.baseCurrency.iso === x.currency) { defaultTaxBucket += x.taxable ? parseFloat(x.parsedValue) : 0; } else { defaultTaxBucket += x.taxable ? convertForeignCurrencyToBaseCurrency(x, parseFloat(x.parsedValue), currencyRatesForPeriod) : 0 } // console.log(`defaultTaxBucket`, defaultTaxBucket) //-- //for reliefs add to relief bucket if(tenant.baseCurrency.iso === x.currency) { reliefBucket += x.reliefFromTax ? parseFloat(x.parsedValue) : 0; } else { reliefBucket += x.reliefFromTax ? convertForeignCurrencyToBaseCurrency(x, parseFloat(x.parsedValue), currencyRatesForPeriod) : 0 } //assigned bucket if one of the paytype is selected as tax bucket if(tenant.baseCurrency.iso === x.currency) { if(x._id === tax.bucket) { assignedTaxBucket = { title: x.title, code: x.code, currency: x.currency || "", value: parseFloat(x.parsedValue) } } else { assignedTaxBucket = null } } else { if(x._id === tax.bucket) { assignedTaxBucket = { title: x.title, code: x.code, currency: x.currency || "", value: convertForeignCurrencyToBaseCurrency(x, parseFloat(x.parsedValue), currencyRatesForPeriod) } } else { assignedTaxBucket = null } } // console.log(`assignedTaxBucket`, assignedTaxBucket) /// Intentional comment ... does not break the payrun // processing.push({code: x.code, taxBucket: defaultTaxBucket}); /// //if paytype in pension then add to default pension buket const ptIndex = pension && _.indexOf(pension.payTypes, x._id); pensionBucket += ptIndex !== -1 ? parseFloat(x.parsedValue) : 0; // add parsed value to pension bucket if paytype is found //gross income for pension relief; if(tenant.baseCurrency.iso === x.currency) { grossIncomeBucket += tax.grossIncomeBucket === x._id ? parseFloat(x.parsedValue) : 0; } else { grossIncomeBucket += tax.grossIncomeBucket === x._id ? convertForeignCurrencyToBaseCurrency(x, parseFloat(x.parsedValue), currencyRatesForPeriod) : 0 } /// Intentional comment ... does not break the payrun // processing.push({code: x.code, pensionBucket: pensionBucket}); /// //set value let value = 0 if(netPayTypeAmount) { value = netPayTypeAmount } else { value = parseFloat(x.parsedValue); } //-- let projectPayAmount = 0 let costCenterPayAmount = 0 let projectsPay = [] if(x.isTimeWritingDependent) { if(totalHoursWorkedInPeriod > 0 && !x.additionalPay) { let totalWorkHoursInYear = 2080 let numberOfMonthsInYear = 12 projectsPayDetails.projectDurations.forEach(aProject => { // const fraction = aProject.duration * (numberOfMonthsInYear / totalWorkHoursInYear) const fraction = aProject.duration / (numDaysEmployeeCanWorkInMonth * 8) let individualProjectPayAmount = fraction * value if(tenant.baseCurrency.iso !== x.currency) { individualProjectPayAmount = convertForeignCurrencyToBaseCurrency(x, projectPayAmount, currencyRatesForPeriod) } projectsPay.push({ projectId: aProject.project, durationInHours: aProject.duration, payAmount: individualProjectPayAmount }) }) let projectsTotalPayInPayTypeCurrency = projectsPayDetails.fraction * value costCenterPayAmount = costCentersPayDetails.fraction * value value = projectsTotalPayInPayTypeCurrency + costCenterPayAmount if(tenant.baseCurrency.iso !== x.currency) { processing.push({code: `Pay from projects(${x.currency})`, derived: `(${projectsPayDetails.duration} / ${totalNumWeekDaysInMonth} * 8) * ${value}`}); processing.push({code: `Pay from projects(${x.currency})`, derived: projectsTotalPayInPayTypeCurrency}); processing.push({code: "Pay from projects(NGN)", derived: `(${projectsPayDetails.duration} / ${totalNumWeekDaysInMonth} * 8) * ${value} * currency rate`}); processing.push({code: "Pay from projects(NGN)", derived: `${projectsPayDetails.fraction} * ${value} * currency rate`}); projectPayAmount = convertForeignCurrencyToBaseCurrency(x, projectsTotalPayInPayTypeCurrency, currencyRatesForPeriod) } else { projectPayAmount = projectsTotalPayInPayTypeCurrency processing.push({code: "Pay from projects(NGN)", derived: `${projectsPayDetails.fraction} * ${value}`}); } //-- if(tenant.baseCurrency.iso !== x.currency) { processing.push({code: `Pay from projects(${x.currency})`, derived: `(${costCentersPayDetails.duration} / ${totalNumWeekDaysInMonth} * 8) * ${value} * currency rate`}); processing.push({code: `Pay from cost centers(${x.currency})`, derived: `${costCentersPayDetails.fraction} * ${value} * currency rate`}); costCenterPayAmount = convertForeignCurrencyToBaseCurrency(x, costCenterPayAmount, currencyRatesForPeriod) } else { processing.push({code: `Pay from cost centers(${x.currency})`, derived: `${costCentersPayDetails.fraction} * ${value}`}); } processing.push({code: `Pay from projects(${x.currency})`, derived: projectPayAmount}); processing.push({code: `Pay from cost centers(${x.currency})`, derived: costCenterPayAmount}); processing.push({code: x.code, derived: `(Pay from projects(${x.currency})) + (Pay from cost-center(${x.currency}))`}); processing.push({code: x.code, derived: value}); } else { value = 0 processing.push({code: x.code, derived: value}); } } else { // let totalWorkHoursInYear = 2080 // let numberOfMonthsInYear = 12 costCenterPayAmount = value * ((numDaysEmployeeCanWorkInMonth) / totalNumWeekDaysInMonth) value = costCenterPayAmount if(tenant.baseCurrency.iso !== x.currency) { costCenterPayAmount = convertForeignCurrencyToBaseCurrency(x, costCenterPayAmount, currencyRatesForPeriod) // processing.push({code: x.code + " - (Payment accounting for resumption date)", derived: ` ${value} * (${numDaysEmployeeCanWorkInMonth}) / ${totalNumWeekDaysInMonth}) * currency rate`}); processing.push({code: x.code + " - (Payment accounting for resumption date)", derived: ` ${value} * (${numDaysEmployeeCanWorkInMonth}) / ${totalNumWeekDaysInMonth})`}); } else { processing.push({code: x.code + " - (Payment accounting for resumption date)", derived: ` ${value} * (${numDaysEmployeeCanWorkInMonth}) / ${totalNumWeekDaysInMonth})`}); } processing.push({code: x.code, derived: value}); } //-- let valueInForeignCurrency = value if(tenant.baseCurrency.iso !== x.currency) { let currencyRateForPayType = _.find(currencyRatesForPeriod, (aCurrency) => { return aCurrency.code === x.currency }) // if(currencyRateForPayType) { // if(!isNaN(currencyRateForPayType.rateToBaseCurrency)) { // value = value * currencyRateForPayType.rateToBaseCurrency // } // } } //-- switch (x.type) { case 'Benefit': //add to payslip benefit if display in payslip if (x.addToTotal) { let paymentObj = { title: x.title, code: x.code, currency: x.currency || "", value, valueInForeignCurrency } benefit.push(paymentObj); let paymentsForCurrency = paymentsAccountingForCurrency.benefit[x.currency] if(!paymentsForCurrency) { paymentsAccountingForCurrency.benefit[x.currency] = {payments: []} } paymentsAccountingForCurrency.benefit[x.currency].payments.push({ title: x.title, code: x.code, currency: x.currency, taxable: x.taxable, value }) } else if(!x.addToTotal){ others.push({ title: x.title, code: x.code, currency: x.currency || "", value, valueInForeignCurrency }); let paymentsForCurrency = paymentsAccountingForCurrency.others[x.currency] if(!paymentsForCurrency) { paymentsAccountingForCurrency.others[x.currency] = {payments: []} } paymentsAccountingForCurrency.others[x.currency].payments.push({ title: x.title, code: x.code, currency: x.currency, taxable: x.taxable, value }) } break; case 'Deduction': if (x.addToTotal){ deduction.push({ title: x.title, code: x.code, currency: x.currency || "", value, valueInForeignCurrency: '' }); let paymentsForCurrency = paymentsAccountingForCurrency.deduction[x.currency] if(!paymentsForCurrency) { paymentsAccountingForCurrency.deduction[x.currency] = {payments: []} } paymentsAccountingForCurrency.deduction[x.currency].payments.push({ title: x.title, code: x.code, currency: x.currency, taxable: x.taxable, // redundant. Deductions can't be taxable value }) } else if(!x.addToTotal){ others.push({ title: x.title, code: x.code, currency: x.currency || "", value, valueInForeignCurrency }); let paymentsForCurrency = paymentsAccountingForCurrency.others[x.currency] if(!paymentsForCurrency) { paymentsAccountingForCurrency.others[x.currency] = {payments: []} } paymentsAccountingForCurrency.others[x.currency].payments.push({ title: x.title, code: x.code, currency: x.currency, taxable: x.taxable, value }) } } //add value to result employeeResult.payment.push({ id: x._id, reference: 'Paytype', amountLC: value, amountPC: valueInForeignCurrency, projectPayAmount: projectPayAmount, costCenterPayAmount: costCenterPayAmount, projectsPay: projectsPay, code: x.code, description: x.title, type: (x.displayInPayslip && !x.addToTotal) ? 'Others': x.type }); log.push({paytype: x.code, input: input, processing: processing}); } else { //when there is an error, stop processing this employee and move to the next one processing.push({code: x.code, derived: `Unable to handle Paytype Derivative ${formula} = ${parsed}`}); log.push({paytype: x.code, input: input, processing: processing}); throw new PaytypeException('Unable to handle Paytype Derivative', `${formula} = ${parsed.error}`); } empDerivedPayElements.push(x); // } } }) // console.log(`paymentsAccountingForCurrency: `, JSON.stringify(paymentsAccountingForCurrency)) } catch (e) { const error = {}; error.employee = `${x.employeeProfile.employeeId} - ${x.profile.fullName}`; error.reason = e.message; error.details = e.paytype; processingError.push(error); //set processing to false and do not save result. skipToNextEmployee = true } if(!skipToNextEmployee) {//further processing after evaluation of all paytypes! pension calculation and tax calculation //get employee and employer contribution const {employerPenContrib, employeePenContrib, grossPension, pensionLog} = getPensionContribution(pensionBucket, pension); //@@technicalPaytype //populate result for employee and employer pension contribution if(pension){ employeeResult.payment.push({id: pension._id, reference: 'Pension', amountLC: employeePenContrib, amountPC: '', code: pension.code + '_EE', description: pension.name + ' Employee', type: 'Deduction'}); employeeResult.payment.push({id: pension._id, reference: 'Pension', amountLC: employerPenContrib, amountPC: '', code: pension.code + '_ER', description: pension.name + ' Employer', type: 'Others'}); if(!paymentsAccountingForCurrency.deduction['NGN']) { paymentsAccountingForCurrency.deduction['NGN'] = {payments: []} } if(!paymentsAccountingForCurrency.others['NGN']) { paymentsAccountingForCurrency.others['NGN'] = {payments: []} } paymentsAccountingForCurrency.deduction['NGN'].payments.push({ title: pension.name + ' Employee', code: pension.code + '_EE', currency: 'NGN', reference: 'Pension', value: -1 * employeePenContrib }) paymentsAccountingForCurrency.others['NGN'].payments.push({ title: pension.name + ' Employer', code: pension.code + '_ER', currency: 'NGN', reference: 'Pension', value: employerPenContrib }) } if(pensionLog) //add pension calculation log log.push(pensionLog); //add employee to relief Bucket reliefBucket += (grossPension || 0); //nagate employee Pension contribution and add to relief bucket //--Tax processing follows // let netTax = null let netTaxLocal = 0 let netTaxForeign = 0 let taxLog = null const effectiveTaxDetails = Tax.findOne({isUsingEffectiveTaxRate: true, employees: x._id, status: 'Active'}); if(effectiveTaxDetails) { const taxComputationInput = [ {code: 'Effective Tax Rate', value: effectiveTaxDetails.effectiveTaxRate}, // {code: 'TaxBucket', value: taxBucket} ]; if(assignedTaxBucket) { netTaxLocal = (assignedTaxBucket.value * effectiveTaxDetails.effectiveTaxRate) taxComputationInput.push( {code: 'TaxBucket', value: assignedTaxBucket.value} ) const taxProcessing = []; taxProcessing.push({code: 'Tax', derived: '(taxBucket * Effective Tax Rate)'}); taxProcessing.push({code: 'Tax', derived: netTaxLocal }); netTaxLocal = parseFloat(netTaxLocal).toFixed(2) taxLog = {paytype: effectiveTaxDetails.code, input: taxComputationInput, processing: taxProcessing}; //populate result for tax if(tenant.baseCurrency.iso === assignedTaxBucket.currency) { employeeResult.payment.push({id: tax._id, reference: 'Tax', amountLC: netTaxLocal, amountPC: '', code: tax.code, description: tax.name, type: 'Deduction' }); } else { employeeResult.payment.push({id: tax._id, reference: 'Tax', amountLC: '', amountPC: netTaxLocal, code: tax.code, description: tax.name, type: 'Deduction' }); } } else { let taxableIncomeInDiffCurrencies = {} let benefitsDeductionsAndOthers = Object.keys(paymentsAccountingForCurrency) benefitsDeductionsAndOthers.forEach(aPayCategory => { let payCategoryCurrencies = Object.keys(paymentsAccountingForCurrency[aPayCategory]) payCategoryCurrencies.forEach(aCurrency => { if(!taxableIncomeInDiffCurrencies[aCurrency]) { taxableIncomeInDiffCurrencies[aCurrency] = 0 } let paymentsInCurrency = paymentsAccountingForCurrency[aPayCategory][aCurrency] paymentsInCurrency.payments.forEach(aPayment => { if(aPayment.taxable) { let paymentAsFloat = parseFloat(aPayment.value) if(!isNaN(paymentAsFloat)) { taxableIncomeInDiffCurrencies[aCurrency] += paymentAsFloat } } }) }) }) // console.log(`taxableIncomeInDiffCurrencies: `, JSON.stringify(taxableIncomeInDiffCurrencies)) //-- const taxProcessing = []; let taxCurrencies = Object.keys(taxableIncomeInDiffCurrencies) taxCurrencies.forEach(aCurrency => { let taxableIncome = taxableIncomeInDiffCurrencies[aCurrency] if(!paymentsAccountingForCurrency.deduction[aCurrency]) { paymentsAccountingForCurrency.deduction[aCurrency] = {payments: []} } if(aCurrency === tenant.baseCurrency.iso) { netTaxLocal = (taxableIncome * effectiveTaxDetails.effectiveTaxRate) paymentsAccountingForCurrency.deduction[aCurrency].payments.push({ title: tax.name, code: tax.code, currency: aCurrency, // taxable: true, reference: 'Tax', value: netTaxLocal * -1 }) } else { netTaxForeign = (taxableIncome * effectiveTaxDetails.effectiveTaxRate) paymentsAccountingForCurrency.deduction[aCurrency].payments.push({ title: tax.name, code: tax.code, currency: aCurrency, // taxable: true, reference: 'Tax', value: netTaxForeign * -1 }) } //-- taxComputationInput.push({ code: `TaxBucket(${aCurrency})`, value: taxableIncome }) //-- taxProcessing.push({code: `Tax(${aCurrency})`, derived: '(TaxBucket * Effective Tax Rate)'}); taxProcessing.push({code: `Tax(${aCurrency})`, derived: (taxableIncome * effectiveTaxDetails.effectiveTaxRate) }); }) //-- taxLog = {paytype: effectiveTaxDetails.code, input: taxComputationInput, processing: taxProcessing}; employeeResult.payment.push({ id: tax._id, reference: 'Tax', amountLC: netTaxLocal, amountPC: netTaxForeign, code: tax.code, description: tax.name, type: 'Deduction' }); } } else { let taxBucket = null; if(assignedTaxBucket) {//automatically use default tax bucket if tax bucket not found taxBucket = assignedTaxBucket.value } else { taxBucket = defaultTaxBucket } let taxCalculationResult = calculateTax(reliefBucket, taxBucket, grossIncomeBucket, tax); //@@technicalPaytype netTaxLocal = taxCalculationResult.netTax taxLog = taxCalculationResult.taxLog //populate result for tax employeeResult.payment.push({id: tax._id, reference: 'Tax', amountLC: netTaxLocal, amountPC: '', code: tax.code, description: tax.name, type: 'Deduction'}); //-- paymentsAccountingForCurrency.deduction['NGN'].payments.push({ title: tax.name, code: tax.code, currency: 'NGN', reference: 'Tax', value: netTaxLocal * -1 }) } if(taxLog) log.push(taxLog); //collate results and populate paySlip; and push to payresult let final = {}; final.log = log; //payrun processing log final.payslip = {benefit: benefit, deduction: deduction}; //pension and tax are also deduction final.payslip.deduction.push({ title: tax.code, code: tax.name, value: netTaxLocal * -1, valueInForeignCurrency: netTaxForeign * -1 }); // negate add tax to deduction //--End of Tax processing if(pension) { let valueInForeignCurrency = '' final.payslip.deduction.push({title: `${pension.code}_EE`, code: `${pension.name} Employee`, value: employeePenContrib * -1, valueInForeignCurrency}); // if(pension.displayEmployerInPayslip) { valueInForeignCurrency = '' final.payslip.others = others.concat([{title: `${pension.code}_ER`, code: `${pension.name} Employer`, value: employerPenContrib, valueInForeignCurrency}]); //if employer contribution (displayEmployerInPayslip) add to other payments // } } else { final.payslip.others = others } //-- final.payslipWithCurrencyDelineation = paymentsAccountingForCurrency //-- let benefitsDeductionsAndOthers = Object.keys(paymentsAccountingForCurrency) let netPayWithCurrencyDelineation = {} let deductionWithCurrencyDelineation = {} benefitsDeductionsAndOthers.forEach(aPayCategory => { let payCategoryCurrencies = Object.keys(paymentsAccountingForCurrency[aPayCategory]) payCategoryCurrencies.forEach(aCurrency => { let total = 0 let paymentsInCurrency = paymentsAccountingForCurrency[aPayCategory][aCurrency] if(!paymentsInCurrency) { paymentsAccountingForCurrency[aPayCategory][aCurrency] = {payments: []} paymentsInCurrency = paymentsAccountingForCurrency[aPayCategory][aCurrency] } paymentsInCurrency.payments.forEach(aPayment => { let paymentAsFloat = parseFloat(aPayment.value) if(!isNaN(paymentAsFloat)) { total += paymentAsFloat } }) paymentsInCurrency.total = total //-- if(aPayCategory === 'benefit') { if(netPayWithCurrencyDelineation[aCurrency]) { netPayWithCurrencyDelineation[aCurrency] = netPayWithCurrencyDelineation[aCurrency] + total } else { netPayWithCurrencyDelineation[aCurrency] = total } } else if(aPayCategory === 'deduction') { if(netPayWithCurrencyDelineation[aCurrency]) { netPayWithCurrencyDelineation[aCurrency] = netPayWithCurrencyDelineation[aCurrency] + total } else { netPayWithCurrencyDelineation[aCurrency] = total } //-- if(deductionWithCurrencyDelineation[aCurrency]) { deductionWithCurrencyDelineation[aCurrency] = deductionWithCurrencyDelineation[aCurrency] + total } else { deductionWithCurrencyDelineation[aCurrency] = total } } else if(aPayCategory === 'others') {// Do nothing } }) }) const employeeDetails = getDetailsInPayslip(x); paymentsAccountingForCurrency.employee = employeeDetails; paymentsAccountingForCurrency.employee.grade = grade.code; paymentsAccountingForCurrency.employee.gradeId = grade._id; //-- let netPayCurrencies = Object.keys(netPayWithCurrencyDelineation) netPayCurrencies.forEach(currency => { if(currency === tenant.baseCurrency.iso) { employeeResult.payment.push({ reference: 'Standard', amountLC: netPayWithCurrencyDelineation[currency], amountPC: netPayWithCurrencyDelineation[currency], code: 'NMP', description: 'Net Payment', type: 'netPayment' }); final.payslip['totalPayment'] = paymentsAccountingForCurrency.benefit[currency].total final.payslip['netPayment'] = netPayWithCurrencyDelineation[currency] } else { employeeResult.payment.push({ reference: 'Standard_' + currency, amountLC: netPayWithCurrencyDelineation[currency], amountPC: netPayWithCurrencyDelineation[currency], code: 'NMP', description: 'Net Payment ' + currency, type: 'netPayment' }); final.payslip['totalPayment_' + currency] = paymentsAccountingForCurrency.benefit[currency].total final.payslip['netPayment_' + currency] = netPayWithCurrencyDelineation[currency] } }) //-- let deductionCurrencies = Object.keys(deductionWithCurrencyDelineation) deductionCurrencies.forEach(currency => { if(currency === tenant.baseCurrency.iso) { employeeResult.payment.push({ reference: 'Standard-1', amountLC: deductionWithCurrencyDelineation[currency], amountPC: deductionWithCurrencyDelineation[currency], code: 'TDEDUCT', description: 'Total Deduction', type: 'totalDeduction' }); final.payslip['totalDeduction'] = deductionWithCurrencyDelineation[currency] } else { employeeResult.payment.push({ reference: 'Standard-1_' + currency, amountLC: deductionWithCurrencyDelineation[currency], amountPC: deductionWithCurrencyDelineation[currency], code: 'TDEDUCT', description: 'Total Deduction ' + currency, type: 'totalDeduction' }); final.payslip['totalDeduction_' + currency] = deductionWithCurrencyDelineation[currency] } }) //--Deprecated method for calculating net pay //calculate net payment as payment - deductions; // negate and add pension to deduction // const totalPayment = sumPayments(final.payslip.benefit); // const totalDeduction = sumPayments(final.payslip.deduction); // const netPayment = parseFloat(totalPayment) + parseFloat(totalDeduction); //@@technicalPaytype //populate result for net payment // employeeResult.payment.push({reference: 'Standard', amountLC: netPayment, amountPC: getNetPayInForeignCurrency(netPayment, grade, currencyRatesForPeriod), code: 'NMP', description: 'Net Payment', type: 'netPayment' }); // employeeResult.payment.push({reference: 'Standard-1', amountLC: totalDeduction, amountPC: getNetPayInForeignCurrency(totalDeduction, grade, currencyRatesForPeriod), code: 'TDEDUCT', description: 'Total Deduction', type: 'totalDeduction' }); // final.payslip.totalPayment = totalPayment; // final.payslip.totalDeduction = totalDeduction; // final.payslip.netPayment = netPayment; //-- //Add currently process employee details to final.payslip.employee const employee = getDetailsInPayslip(x); final.payslip.employee = employee; final.payslip.employee.grade = grade.code; final.payslip.employee.gradeId = grade._id; final.payslip.period = period //payement will also be sent to result for factoring and storage; payresult.push(final); // also push employee result payrun.push(employeeResult); //factor payments for storage if not simulation //map default buckets and paytypes used to assigned in config. } else { //when there is an exception let final = {}; final.log = log; //payrun processing log final.payslip = {benefit: [], deduction: []}; //Add currently process employee details to final.payslip.employee const employee = getDetailsInPayslip(x); final.payslip.employee = employee; if(grade) { final.payslip.employee.grade = grade.code; } else { final.payslip.employee.grade = ""; } final.error = true; //payement will also be sent to result for factoring and storage; payresult.push(final); } } count++; runPayrun(count); } else { // end of recursion } }; runPayrun(count); //after the recurssion return result to calling function; return {result: payresult, error:processingError, payrun}; }; function getDaysEmployeeCanWorkInMonth(employee, firstDayOfMonthDateObj) { let employeeResumption = employee.employeeProfile.employment.hireDate // console.log(`\n employee id: `, employee._id) if(!employeeResumption || employeeResumption === '') { employeeResumption = firstDayOfMonthDateObj } let employeeResumptionMoment = moment(employeeResumption) let monthDateMoment = moment(firstDayOfMonthDateObj) let endOfMonthDate = moment(firstDayOfMonthDateObj).endOf('month').toDate() let numDaysToWorkInMonth = 0 if(employeeResumptionMoment.year() === monthDateMoment.year()) { if (employeeResumptionMoment.month() === monthDateMoment.month()) { numDaysToWorkInMonth = getWeekDays(employeeResumption, endOfMonthDate).length } else if(employeeResumptionMoment.month() > monthDateMoment.month()) { numDaysToWorkInMonth = 0 } else { numDaysToWorkInMonth = getWeekDays(firstDayOfMonthDateObj, endOfMonthDate).length } } else if(employeeResumptionMoment.year() > monthDateMoment.year()) { numDaysToWorkInMonth = 0 } else if(employeeResumptionMoment.year() < monthDateMoment.year()) { numDaysToWorkInMonth = getWeekDays(firstDayOfMonthDateObj, endOfMonthDate).length } return numDaysToWorkInMonth } function getWeekDays(startDate, endDate) { let startDateMoment = moment(startDate) let endDateMoment = moment(endDate) let numberOfDays = endDateMoment.diff(startDateMoment, 'days') + 1 let startDateMomentClone = moment(startDateMoment); // use a clone let weekDates = [] while (numberOfDays > 0) { if (startDateMomentClone.isoWeekday() !== 6 && startDateMomentClone.isoWeekday() !== 7) { weekDates.push(moment(startDateMomentClone).toDate()) // calling moment here cos I need a clone } startDateMomentClone.add(1, 'days'); numberOfDays -= 1; } return weekDates } // function getPayAmountInForeignCurrency(payTypeDetails, amountInLocalCurrency, currencyRatesForPeriod) { // let amountInForeignCurrency = null // let currencyRateForPayType = _.find(currencyRatesForPeriod, (aCurrency) => { // return aCurrency.code === payTypeDetails.currency // }) // if(currencyRateForPayType) { // if(!isNaN(currencyRateForPayType.rateToBaseCurrency)) { // amountInForeignCurrency = amountInLocalCurrency * currencyRateForPayType.rateToBaseCurrency // } // } // return amountInForeignCurrency // } function convertForeignCurrencyToBaseCurrency(payTypeDetails, amountInLocalCurrency, currencyRatesForPeriod) { let amountInForeignCurrency = null let currencyRateForPayType = _.find(currencyRatesForPeriod, (aCurrency) => { return aCurrency.code === payTypeDetails.currency }) if(currencyRateForPayType) { if(!isNaN(currencyRateForPayType.rateToBaseCurrency)) { amountInForeignCurrency = amountInLocalCurrency * currencyRateForPayType.rateToBaseCurrency } } return amountInForeignCurrency } /* This function can also be used for the total deduction */ function getNetPayInForeignCurrency(amountInLocalCurrency, payGrade, currencyRatesForPeriod) { if(payGrade) { let netPayAlternativeCurrency = payGrade.netPayAlternativeCurrency let currencyInPeriod = _.find(currencyRatesForPeriod, (aCurrency) => { return aCurrency.code === netPayAlternativeCurrency }) if(currencyInPeriod) { let rateToBaseCurrency = currencyInPeriod.rateToBaseCurrency return (rateToBaseCurrency > 0) ? (amountInLocalCurrency / rateToBaseCurrency).toFixed(2) : amountInLocalCurrency } else { return amountInLocalCurrency } } else { return amountInLocalCurrency } } function getFractionForCalcProjectsPayValue(businessId, periodMonth, periodYear, totalNumWeekDaysInMonth, employeeUserId) { const firsDayOfPeriod = `${periodMonth}-01-${periodYear} GMT`; const startDate = moment(new Date(firsDayOfPeriod)).startOf('month').toDate(); const endDate = moment(startDate).endOf('month').toDate(); let queryObj = { businessId: businessId, project: {$exists : true}, day: {$gte: startDate, $lt: endDate}, employeeId: employeeUserId, status: 'Approved' } let allProjectTimesInMonth = TimeWritings.aggregate([ { $match: queryObj}, { $group: { _id: { "empUserId": "$employeeId", "project": "$project" }, duration: { $sum: "$duration" } } } ]); //-- // let totalWorkHoursInYear = 2080 // let numberOfMonthsInYear = 12 if(allProjectTimesInMonth) { if(allProjectTimesInMonth.length > 0) { let projectDurations = [] let totalProjectsDuration = 0 allProjectTimesInMonth.forEach(aProjectTime => { totalProjectsDuration += aProjectTime.duration projectDurations.push({ project: aProjectTime._id.project, duration: aProjectTime.duration }) }) // const fraction = totalProjectsDuration * numberOfMonthsInYear / totalWorkHoursInYear const fraction = totalProjectsDuration / (totalNumWeekDaysInMonth * 8) return {duration: totalProjectsDuration, fraction, projectDurations} } else { return {duration: 0, fraction: 0, projectDurations: []} } } else { return {duration: 0, fraction: 0, projectDurations: []} } } function getFractionForCalcCostCentersPayValue(businessId, periodMonth, periodYear, totalNumWeekDaysInMonth, employeeUserId) { const firsDayOfPeriod = `${periodMonth}-01-${periodYear} GMT`; const startDate = moment(new Date(firsDayOfPeriod)).startOf('month').toDate(); const endDate = moment(startDate).endOf('month').toDate(); let queryObj = { businessId: businessId, costCenter: {$exists : true}, day: {$gte: startDate, $lt: endDate}, employeeId: employeeUserId, status: 'Approved' } let allCostCenterTimesInMonth = TimeWritings.aggregate([ { $match: queryObj}, { $group: {_id: "$employeeId", duration: { $sum: "$duration" }}} ]); //-- // let totalWorkHoursInYear = 2080 // let numberOfMonthsInYear = 12 if(allCostCenterTimesInMonth) { if(allCostCenterTimesInMonth.length === 1) { const duration = allCostCenterTimesInMonth[0].duration // const fraction = duration * numberOfMonthsInYear / totalWorkHoursInYear const fraction = duration / (totalNumWeekDaysInMonth * 8) return {duration, fraction} } else { return {duration: 0, fraction: 0} } } else { return {duration: 0, fraction: 0} } } function derivePayElement(person) { let gradePaytypes = PayGrades.find({_id: person.employeeProfile.employment.paygrade}); return "done"; //get employee pay grade } function getEmployeeGrade(gradeId) { return PayGrades.findOne({_id: gradeId, status: 'Active'}); } function determineRule(paytype, grade) { //grade contains processing rules while paytypes contains personal employee rules let pt = [...grade.payTypes]; const empGrade = pt.map(x => { const newX = {...x} let index = _.findLastIndex(paytype, {'paytype': x.paytype}); if (index !== -1) { //derive rule based on employee assigned if no value assinged, use grade derivative if (paytype[index].value) { newX.value = paytype[index].value; } } //return same rule return newX; }); return empGrade; } function getPaygroup(paygrade) { const pg = PayGroups.findOne({_id: paygrade, status: 'Active'}); const penTax = {}; if (pg) { if (pg.tax) { const tax = Tax.findOne({_id: pg.tax, status: 'Active'}); tax ? penTax.tax = tax : null; } if (pg.pension) { const pension = Pensions.findOne({_id: pg.pension, status: 'Active'}); pension ? penTax.pension = pension : null; } } return penTax; } //return employer and employee contribution function getPensionContribution(pensionBucket, pension) { //@import pension bucket float, pension doc. //all elements of pension already derived into pensionBucket //calculate employer and employee contribution if (pension) { const input = [{code: 'Pension Bucket', value: pensionBucket}]; const processing = []; const eerate = pension.employeeContributionRate; const errate = pension.employerContributionRate; const employee = (eerate / 100) * pensionBucket; processing.push({code: `Employee rate`, derived: `(${eerate} / 100) * ${pensionBucket}` }); processing.push({code: `Employee rate`, derived: employee }); const employer = (errate / 100) * pensionBucket; processing.push({code: `Employer rate`, derived: `(${errate} / 100) * ${pensionBucket}` }); processing.push({code: `Employer rate`, derived: employer }); const netee = employee / 12; const neter = employer / 12; //log for net employee contribution processing.push({code: `Employer rate`, derived: `(${employer} / 12) ` }); processing.push({code: `Employer Net Rate`, derived: neter }); //log for net employee contribution processing.push({code: `Employee rate`, derived: `(${employee} / 12) ` }); processing.push({code: `Employee Net Rate`, derived: netee }); const log = {paytype: pension.code, input: input, processing: processing}; return {employeePenContrib: parseFloat(netee).toFixed(2), employerPenContrib: parseFloat(neter).toFixed(2), grossPension: employee, pensionLog: log}; } else { return {employeePenContrib: null, employerPenContrib: null} } } //from taxable income calculate tax and return value function calculateTax(relief, taxBucket, grossIncomeBucket, tax) { //@import taxBucket (defualt tax bucket or valuated passed bucket) //@import tax (tax doc configured ) //calculate reliefs //no checks done yet exceptions NAN undefined checkes //return result {finalTax: log[] } const input = [{code: 'Relief', value: relief}, {code: 'TaxBucket', value: taxBucket}, {code: 'GrossIncomeBucket', value: grossIncomeBucket}]; const processing = []; const grossIncomeRelief = (tax.grossIncomeRelief / 100) * grossIncomeBucket; processing.push({code: 'Gross Income Relief', derived: '(grossIncomeRelief / 100) * grossIncomeBucket'}); processing.push({code: 'Gross Income Relief', derived: grossIncomeRelief }); const consolidatedRelief = tax.consolidatedRelief; processing.push({code: `Consolidated Relief defined in ${tax.code}`, derived: consolidatedRelief }); const totalRelief = grossIncomeRelief + consolidatedRelief + relief; processing.push({code: `Total Relief`, derived: 'grossIncomeRelief + consolidatedRelief + relief' }); processing.push({code: `Total Relief`, derived: totalRelief }); let taxableIncome = taxBucket - totalRelief; processing.push({code: `Taxable Income`, derived: 'taxBucket - totalRelief' }); processing.push({code: `Taxable Income`, derived: taxableIncome }); let totalTax = 0; //apply tax rules on taxable income const rules = [...tax.rules]; let isTaxableIncomeLessThanFirstUpperLimit = false //add log for debugging //deduct upper limit from taxable income //no need to calcuate tax if taxable income- if (taxableIncome >= rules[0].upperLimit) { for (let i = 0; i < rules.length; i++) { let x = rules[i]; if (x.range !== 'Over') { processing.push({code: `Total Tax(${x.range} ${x.upperLimit})`, derived: `${x.rate} * (${taxableIncome} - ${x.upperLimit}) / 100` }); if (taxableIncome >= x.upperLimit) { taxableIncome -= x.upperLimit; totalTax += x.rate * (x.upperLimit / 100); } else { totalTax += x.rate * (taxableIncome / 100); break; } processing.push({code: `Total Tax(${x.range} ${x.upperLimit})`, derived: totalTax }); } else { processing.push({code: `Total Tax(${x.range} ${x.upperLimit})`, derived: `${x.rate} * (${taxableIncome}) / 100` }); totalTax += x.rate * (taxableIncome / 100); processing.push({code: `Total Tax(${x.range} ${x.upperLimit})`, derived: totalTax }); } } } else { isTaxableIncomeLessThanFirstUpperLimit = true } const netTax = totalTax / 12; if(isTaxableIncomeLessThanFirstUpperLimit) { processing.push({code: `Net Tax(Total Tax / 12 ) - {Fail! Taxable income is less than first upper limit of tax rule}`, derived: `${totalTax}` / 12 }); processing.push({code: `Net Tax - {Fail! Taxable income is less than first upper limit of tax rule}`, derived: netTax }); } else { processing.push({code: `Net Tax(Total Tax / 12 )`, derived: `${totalTax}` / 12 }); processing.push({code: `Net Tax`, derived: netTax }); } const log = {paytype: tax.code, input: input, processing: processing}; return {netTax: parseFloat(netTax).toFixed(2), taxLog: log}; } /* Sum payments in groups @import array */ function sumPayments(payments){ const newPay = [...payments]; const sum = newPay.reduce(function(total, val) { return total + parseFloat(val.value); }, 0); return parseFloat(sum).toFixed(2) ; } /* import employee doc. return {} object containing employee details to be displayed on payslip */ function getDetailsInPayslip(employee){ let details = {}; details.employeeUserId = employee._id; details.employeeId = employee.employeeProfile.employeeId; details.fullname = employee.profile.fullName; details.accountNumber = employee.employeeProfile.payment.accountNumber || ""; details.bank = employee.employeeProfile.payment.bank || ""; // add other details return details; } function getPaytypeIdandValue(additionalPay, businessId) { let newAddPay = [...additionalPay]; let paytypes = []; //lazyload paytypes to reduce number of database query. newAddPay.forEach(x => { const paytype = PayTypes.findOne({code: x.paytype, businessId: businessId, status: 'Active'}); if(paytype) paytype.value = x.amount.toString(); // add the value as additional pay value paytypes.push(paytype); }); return paytypes; } function PaytypeException(message, paytype) { this.message = message; this.name = 'PaytypeEvaluationException'; this.paytype = paytype; }
main/app/server/methods/payruns.js
import _ from 'underscore'; import moment from 'moment'; let littleHelpers = { paddArrayWithZeros: function(array, fullLengthWithZeros) { let lengthOfArray = array.length for(let i = 0; i < fullLengthWithZeros - lengthOfArray; i++) { array.push(0) } } } let getEmployeedEmployees = (paygrade, period, businessId, businessUnitConfig) => { check(paygrade, Array); const year = period.year; const month = period.month; const firsDayOfPeriod = `${month}-01-${year} GMT`; const DateLimit = new Date(firsDayOfPeriod); let dateLimitMoment = moment(DateLimit) let dateLimitMonth = dateLimitMoment.month() let dateLimitYear = dateLimitMoment.year() if(businessUnitConfig) { let checkEmployeeResumptionForPayroll = businessUnitConfig.checkEmployeeResumptionForPayroll if(checkEmployeeResumptionForPayroll) { let allUsers = Meteor.users.find({'employeeProfile.employment.status': 'Active', $or: [ {'employeeProfile.employment.terminationDate': {$gt: DateLimit}}, {'employeeProfile.employment.terminationDate': null}, {'employeeProfile.employment.terminationDate' : ''}, {'employeeProfile.employment.terminationDate' : { $exists : false } } ], 'employeeProfile.employment.paygrade': {$in: paygrade}, 'businessIds': businessId, 'employee': true }).fetch(); let users = [] allUsers.forEach(aUser => { let userHireDate = aUser.employeeProfile.employment.hireDate if(userHireDate) { let userHireDateMoment = moment(userHireDate) if(dateLimitMoment.isSameOrAfter(userHireDateMoment)) { users.push(aUser) } } }) return users } else { return Meteor.users.find({'employeeProfile.employment.status': 'Active', $or: [ {'employeeProfile.employment.terminationDate': {$gt: DateLimit}}, {'employeeProfile.employment.terminationDate': null}, {'employeeProfile.employment.terminationDate' : { $exists : false } } ], 'employeeProfile.employment.paygrade': {$in: paygrade}, 'businessIds': businessId, 'employee': true }).fetch(); } } else { return [] } }; /** * Payruns Methods */ Meteor.methods({ /* Get net monthly pay amount NMP */ 'exportPaymentsforPeriod': (businessId, period) => { //get all payroll result for specified period if employee is authorized check(period, String); check(businessId, String); const result = Payruns.find({businessId: businessId, period: period}).fetch(); const paytypes = [], export_header = ["Full Name", "Employee Number", "Period"]; //for every header, loop at employee payment and populate value result.forEach(x => { let payments = x.payment; // for every payment, push value if it exists or 0.00 into result payments.forEach(p => { const header = {code: p.code , reference: p.reference}; const index = _.findLastIndex(paytypes, header); if(index === -1) { paytypes.push(header); export_header.push(p.code); } }); }); //header population complete now use header index and fill each employee data // review this method const data = []; result.forEach(x => { // for every payment, push value if it exists or 0.00 into result //get personnel details first let employee = Meteor.users.findOne({_id: x.employeeId}); if (employee) { //push employee name, employeeId and period const employeePay = []; employeePay.push(employee.profile.fullName); employeePay.push(employee.employeeProfile.employeeId); employeePay.push(x.period); paytypes.forEach(p => { const payments = x.payment; const index = _.findLastIndex(payments, p); if(index > -1) { employeePay.push(payments[index].amountPC); } else { employeePay.push(0.00); } }); data.push(employeePay); } }); let exportData = {fields: export_header, data: data}; return exportData ; }, /* Get net monthly pay amount NMP */ 'ExportNetPayResult': (businessId, period) => { //get all payroll result for specified period if employee is authorized check(period, String); check(businessId, String); if(!Core.hasPayrollAccess(Meteor.userId())){ throw new Meteor.Error(401, 'Unauthorized'); } else { const header = [ "Full Name", "Bank", "Account Number", ]; let tenantId = Core.getTenantId(Meteor.userId()) let tenant = Tenants.findOne(tenantId) const result = Payruns.find({businessId: businessId, period: period}).fetch(); const netpay = result.map(x => { let dataRow = [] let employee = Meteor.users.findOne({_id: x.employeeId}); if(employee){ dataRow = [ employee.profile.fullName, employee.employeeProfile.payment.bank || '', employee.employeeProfile.payment.accountNumber || '' ]; } let numPayments = x.payment.length for(let i = 0; i < numPayments; i++) { if(x.payment[i].code === 'NMP') {// Got a net pay if(x.payment[i].reference === 'Standard') { let foundAmountHeader = _.find(header, aHeader => { return aHeader === 'Amount (' + tenant.baseCurrency.iso + ')' }) if(!foundAmountHeader) { header.push('Amount (' + tenant.baseCurrency.iso + ')') } dataRow.push(x.payment[i].amountPC) } else if(x.payment[i].reference.startsWith('Standard_')) { let currency = x.payment[i].reference.substring('Standard_'.length) let foundAmountHeader = _.find(header, aHeader => { return aHeader === 'Amount (' + currency + ')' }) if(!foundAmountHeader) { header.push('Amount (' + currency + ')') } dataRow.push(x.payment[i].amountPC) } } } return dataRow }); return {fields: header, data: netpay}; } }, /* Get net monthly pay amount NMP */ 'getnetPayResult': (businessId, period) => { //get all payroll result for specified period if employee is authorized check(period, String); check(businessId, String); if(Core.hasPayrollAccess(this.userid)){ throw new Meteor.Error(401, 'Unauthorized'); } else { const header = [ "Full Name", "Bank", "Account Number", ]; let tenantId = Core.getTenantId(Meteor.userId()) let tenant = Tenants.findOne(tenantId) const result = Payruns.find({businessId: businessId, period: period}).fetch(); const netpayData = result.map(x => { let dataRow = [] let employee = Meteor.users.findOne({_id: x.employeeId}); if(employee) { dataRow = [ employee._id, employee.profile.fullName, employee.employeeProfile.payment.bank, employee.employeeProfile.payment.accountNumber || '' ]; littleHelpers.paddArrayWithZeros(dataRow, header.length - 1) } let numPayments = x.payment.length for(let i = 0; i < numPayments; i++) { if(x.payment[i].code === 'NMP') {// Got a net pay if(x.payment[i].reference === 'Standard') { let indexOfHeader = -1 let foundAmountHeader = _.find(header, (aHeader, headerIndex) => { if(aHeader === 'Amount (' + tenant.baseCurrency.iso + ')') { indexOfHeader = headerIndex return true } }) if(!foundAmountHeader) { header.push('Amount (' + tenant.baseCurrency.iso + ')') dataRow.push(0) indexOfHeader = dataRow.length - 1 } else { indexOfHeader += 1 } dataRow[indexOfHeader] = x.payment[i].amountPC } else if(x.payment[i].reference.startsWith('Standard_')) { let indexOfHeader = -1 let currency = x.payment[i].reference.substring('Standard_'.length) let foundAmountHeader = _.find(header, (aHeader, headerIndex) => { if(aHeader === 'Amount (' + currency + ')') { indexOfHeader = headerIndex return true } }) if(!foundAmountHeader) { header.push('Amount (' + currency + ')') dataRow.push(0) indexOfHeader = dataRow.length - 1 } else { indexOfHeader += 1 } // dataRow.push(x.payment[i].amountPC) dataRow[indexOfHeader] = x.payment[i].amountPC } } } return dataRow }); return { headers: header, data: netpayData } } }, /* Export Tax payment */ 'exportTaxResult': (businessId, period) => { //get all payroll result for specified period if employee is authorized check(period, String); check(businessId, String); if(Core.hasPayrollAccess(this.userid)){ throw new Meteor.Error(401, 'Unauthorized'); } else { const result = Payruns.find({businessId: businessId, period: period, 'payment.reference': 'Tax'}).fetch(); const tax = result.map(x => { const taxIndex = _.findLastIndex(x.payment, {reference: 'Tax'}); //get amount in paytype currency for standard paytype NMP(Net monthly pay) if(taxIndex > -1) { const amountLC = x.payment[taxIndex].amountLC; //get employee details let employee = Meteor.users.findOne({_id: x.employeeId}); if(employee){ return [ employee.profile.fullName, employee.employeeProfile.state, employee.employeeProfile.payment.taxPayerId, amountLC ]; } } }); const header = [ "Full Name", "Resident State", "Tax Payer ID", "Amount" ]; return {fields: header, data: tax}; } }, /* Get Tax pay */ 'getTaxResult': (businessId, period) => { //get all payroll result for specified period if employee is authorized check(period, String); check(businessId, String); if(Core.hasPayrollAccess(this.userid)){ throw new Meteor.Error(401, 'Unauthorized'); } else { const result = Payruns.find({businessId: businessId, period: period, 'payment.reference': 'Tax'}).fetch(); const tax = result.map(x => { const taxIndex = _.findLastIndex(x.payment, {reference: 'Tax'}); //get amount in paytype currency for standard paytype NMP(Net monthly pay) if(taxIndex > -1) { const taxCode = x.payment[taxIndex].code; const amountPC = x.payment[taxIndex].amountPC; //get employee details let employee = Meteor.users.findOne({_id: x.employeeId}); if(employee){ const info = { fullName: employee.profile.fullName, state: employee.employeeProfile.state, code: taxCode, taxPayerId: employee.employeeProfile.payment.taxPayerId, amount: amountPC }; return info; } } }); return tax; } }, 'exportPensionResult': (businessId, period) => { //get all payroll result for specified period if employee is authorized check(period, String); check(businessId, String); if(Core.hasPayrollAccess(this.userId)){ throw new Meteor.Error(401, 'Unauthorized'); } else { const result = Payruns.find({businessId: businessId, period: period, 'payment.reference': 'Pension'}).fetch(); const pension = result.map(x => { const pensionsContribution = _.where(x.payment, {reference: 'Pension'}); //get all pension pay) if(pensionsContribution.length) { const pensionAmount = {}; let pensionDescription; pensionsContribution.forEach(x => { //pension is always suffixed with _EE or _ER const pensionLength = x.code.length; if (!pensionDescription) pensionDescription = x.description; const type = x.code.substring(pensionLength, pensionLength - 3); //returns _EE or _ER if(type === '_EE') pensionAmount.employeeContribution = x.amountPC; if(type === '_ER') pensionAmount.employerContribution = x.amountPC; }); //get employee details let employee = Meteor.users.findOne({_id: x.employeeId}); if(employee){ return [ employee.profile.fullName, employee.employeeProfile.payment.pensionmanager, employee.employeeProfile.payment.RSAPin, pensionAmount.employeeContribution, pensionAmount.employerContribution ] } } }); const header = [ "Full Name", "Pension Fund Administrator", "RSA PIN", "Employee Contribution", "Employer Contribution" ]; return {fields: header, data: pension}; } }, 'getPensionResult': (businessId, period) => { //get all payroll result for specified period if employee is authorized check(period, String); check(businessId, String); if(Core.hasPayrollAccess(this.userId)){ throw new Meteor.Error(401, 'Unauthorized'); } else { const result = Payruns.find({businessId: businessId, period: period, 'payment.reference': 'Pension'}).fetch(); const pension = result.map(x => { const pensionsContribution = _.where(x.payment, {reference: 'Pension'}); //get all pension pay) if(pensionsContribution.length) { const pensionAmount = {}; let pensionDescription; pensionsContribution.forEach(x => { //pension is always suffixed with _EE or _ER const pensionLength = x.code.length; if (!pensionDescription) pensionDescription = x.description; const type = x.code.substring(pensionLength, pensionLength - 3); //returns _EE or _ER if(type === '_EE') pensionAmount.employeeContribution = x.amountPC; if(type === '_ER') pensionAmount.employerContribution = x.amountPC; }); //get employee details let employee = Meteor.users.findOne({_id: x.employeeId}); if(employee){ const info = { fullName: employee.profile.fullName, pensionManager: employee.employeeProfile.payment.pensionmanager, pin: employee.employeeProfile.payment.RSAPin, employeeContribution: pensionAmount.employeeContribution, employerContribution: pensionAmount.employerContribution } return info; } } }); return pension; } }, /* Payment run */ "payrun/process": function (obj, businessId) { //check if user is in businessId if (!this.userId && Core.hasPayrollAccess(this.userId)) { throw new Meteor.Error(401, "Unauthorized"); } let userId = Meteor.userId(); this.unblock(); console.log(obj); let employees = obj.employees; const paygrades = obj.paygrades; const period = obj.period; const runtype = obj.type; const annuals = obj.annuals; let retroactivePayrun = obj.retroactivePayrun if(retroactivePayrun === 'true') { retroactivePayrun = true } else { retroactivePayrun = false } check(employees, Array); check(period, Object); check(runtype, String); check(paygrades, Array); let res; let payObj = {}; let businessUnitConfig = BusinessUnitCustomConfigs.findOne({businessId: businessId}) //get all selected employees --Condition-- if employees selected, ideally there should be no paygrade if (employees.length === 0 && paygrades.length > 0) { res = getEmployeedEmployees(paygrades, period, businessId, businessUnitConfig); //res contains employees ready for payment processing if (res && res.length > 0) { payObj = processEmployeePay(Meteor.userId(), res, annuals, businessId, period, businessUnitConfig, retroactivePayrun, false); } } else if (employees.length > 0) { const year = period.year; const month = period.month; const firsDayOfPeriod = `${month}-01-${year} GMT`; const DateLimit = new Date(firsDayOfPeriod); //get all employees specified //return empoloyee and reason why payroll cannot be run for such employee if any let users = [] if(businessUnitConfig) { let checkEmployeeResumptionForPayroll = businessUnitConfig.checkEmployeeResumptionForPayroll if(checkEmployeeResumptionForPayroll) { let allUsers = Meteor.users.find({_id: {$in: employees}, $or: [ {'employeeProfile.employment.terminationDate': {$gt: DateLimit}}, {'employeeProfile.employment.terminationDate': null}, {'employeeProfile.employment.terminationDate': ""}, {'employeeProfile.employment.terminationDate' : { $exists : false } } ], 'employeeProfile.employment.status': 'Active', 'businessIds': businessId }).fetch(); let dateLimitMoment = moment(DateLimit) let dateLimitMonth = dateLimitMoment.month() let dateLimitYear = dateLimitMoment.year() allUsers.forEach(aUser => { let userHireDate = aUser.employeeProfile.employment.hireDate if(userHireDate) { let userHireDateMoment = moment(userHireDate) if(dateLimitMoment.isSameOrAfter(userHireDateMoment)) { users.push(aUser) } } }) } else { users = Meteor.users.find({_id: {$in: employees}, $or: [ {'employeeProfile.employment.terminationDate': {$gt: DateLimit}}, {'employeeProfile.employment.terminationDate': null}, {'employeeProfile.employment.terminationDate': ""}, {'employeeProfile.employment.terminationDate' : { $exists : false } } ], 'employeeProfile.employment.status': 'Active', 'businessIds': businessId }).fetch(); } } payObj = users && processEmployeePay(Meteor.userId(), users, annuals, businessId, period, businessUnitConfig, retroactivePayrun, false); } //if live run and no error then save result if (runtype === 'LiveRun' && payObj.error.length === 0){ //store result in Payrun Collection. try { let payrollApprovalConfig = PayrollApprovalConfigs.findOne({businessId: businessId}) let requirePayrollApproval; let approvals; if(payrollApprovalConfig) { if(payrollApprovalConfig.requirePayrollApproval) { requirePayrollApproval = true } else { requirePayrollApproval = false } approvals = [] } else { approvals = null } payObj.payrun.forEach(x => { x.payrunDoneBy = userId x.requirePayrollApproval = requirePayrollApproval x.approvals = approvals Payruns.insert(x); }) payObj.result.forEach(x => { x.period = `${period.month}${period.year}` x.businessId = businessId x.employeeId = x.payslip.employee.employeeUserId PayResults.insert(x); }) } catch (e){ console.log(e); } } else { console.log("Payrun errors: " + JSON.stringify(payObj.error)); } //just return something for now .... testing return {payObj, runtype, period}; } }); /* I am truly sorry for the code you are about to read. It was bad when I started working on it. The function was too long to start refactoring. I could have broken something so I didn't clean it up. */ // // use oop // instantiate payment object for employee with props for all methods required processEmployeePay = function (currentUserId, employees, includedAnnuals, businessId, period, businessUnitConfig, isRetroActivePayrunEnabled, isDoingARetroActivePayrunNow) { let paygrades = []; let payresult = []; // holds result that will be sent to client let payrun = []; //holds payrun for storing if not simulation let specifiedAsProcess = function (paytype) { return _.indexOf(includedAnnuals, paytype) !== -1 ? true : false; }; processingError = []; let count = 0; const periodFormat = period.month + period.year;// format is 012017 ex. let tenantId = Core.getTenantId(currentUserId) let tenant = Tenants.findOne(tenantId) let currencyRatesForPeriod = Currencies.find({businessId: businessId, period: periodFormat}).fetch() let runPayrun = (counter) => { let x = employees[counter]; if (x) { //first check if result exist for employee for that period and if not, continue processing. result = Payruns.findOne({employeeId: x._id, period: periodFormat, businessId: businessId}); if (result){ //add relevant errors const error = {}; error.employee = `${x.employeeProfile.employeeId} - ${x.profile.fullName}`; error.reason = `Payment Exists for Period ${periodFormat}`; error.details = `Cannot Process Payroll for Employee ... as Payment for this period exists. To run payroll, Contact Admin to cross-check and delete previous payment data if neccessary`; processingError.push(error); } else { if(isRetroActivePayrunEnabled && !isDoingARetroActivePayrunNow) { const payrunPeriodAsDate = new Date(`${period.month}-01-${period.year} GMT`); const payrunPeriodAsMoment = moment(payrunPeriodAsDate); const prevMonthMoment = payrunPeriodAsMoment.subtract(1, 'month') const payrunPeriodForPrevMonth = prevMonthMoment.format("MMYYYY") let prevMonth = payrunPeriodForPrevMonth.substring(0, 2) let prevMonthYear = payrunPeriodForPrevMonth.substring(2) let doesEmpHavePayrunForPrevMonth = Payruns.findOne({ period: payrunPeriodForPrevMonth, employeeId: x._id }) if(!doesEmpHavePayrunForPrevMonth) { let retroactivity = processEmployeePay(Meteor.userId(), [x], includedAnnuals, businessId, {month: prevMonth, year: prevMonthYear}, businessUnitConfig, isRetroActivePayrunEnabled, true); let retroactivityResult = retroactivity.result let retroactivityError = retroactivity.error let retroactivityPayrun = retroactivity.payrun payresult = payresult.concat(retroactivityResult) processingError = processingError.concat(retroactivityError) payrun = payrun.concat(retroactivityPayrun) } } const employeeResult = { businessId: businessId, employeeId: x._id, period: periodFormat, payment : [] }; //holds every payment to be saved for employee in payrun //-- const year = period.year; const month = period.month; const firsDayOfPeriod = `${month}-01-${year} GMT`; const firsDayOfPeriodAsDate = new Date(firsDayOfPeriod); let numDaysEmployeeCanWorkInMonth = getDaysEmployeeCanWorkInMonth(x, firsDayOfPeriodAsDate) let totalNumWeekDaysInMonth = getWeekDays(firsDayOfPeriodAsDate, moment(firsDayOfPeriodAsDate).endOf('month').toDate()).length //-- //--Time recording things const projectsPayDetails = getFractionForCalcProjectsPayValue(businessId, period.month, period.year, x._id) // {duration: , fraction: } const costCentersPayDetails = getFractionForCalcCostCentersPayValue(businessId, period.month, period.year, x._id) // {duration: , fraction: } let totalHoursWorkedInPeriod = projectsPayDetails.duration + costCentersPayDetails.duration //-- const pg = x.employeeProfile.employment.paygrade; //paygrade let pt = x.employeeProfile.employment.paytypes; //paytype let grade, pgp; //grade(paygrade) && pgp(paygroup); const gradeIndex = _.findLastIndex(paygrades, {_id: pg}); let empSpecificType; //contains employee payments derived from paygrade if (gradeIndex !== -1) { grade = paygrades[gradeIndex]; empSpecificType = determineRule(pt, grade); } else { //get paygrade and update paygrades grade = getEmployeeGrade(pg); if (grade) { paygrades.push(grade); empSpecificType = determineRule(pt, grade); } } if (grade && grade.hasOwnProperty('payGroups') && grade.payGroups.length > 0) { pgp = grade.payGroups[0]; //first element of paygroup// {review} } //payElemnts derivation; const {tax, pension} = getPaygroup(pgp); let defaultTaxBucket = 0, pensionBucket = 0, log = []; //check if pagrade uses default tax bucket let assignedTaxBucket, grossIncomeBucket = 0, totalsBucket = 0, reliefBucket = 0; let empDerivedPayElements = []; let benefit = [], deduction = [], others = []; let rules = new ruleJS(); rules.init(); let skipToNextEmployee = false; //-- let paymentsAccountingForCurrency = {benefit: {}, deduction: {}, others: {}} // Each key in each of the above keys will be a currency code // Each object for each currency code will be an array of payments //-- try { //let formular = x.value let paytypes = empSpecificType.map(x => { //changes paygrades of currently processed employee to include paytypes let ptype = PayTypes.findOne({_id: x.paytype, 'status': 'Active'}); delete x.paytype; _.extend(x, ptype); return x; }); //import additonal pay and duduction value based on employeeProfile.employeeId for period in collection AdditionalPayments. const addPay = AdditionalPayments.find({businessId: businessId, employee: x.employeeProfile.employeeId, period: periodFormat}).fetch(); //include additional pay to match paytype values if(addPay && addPay.length > 0) { let formattedPay = getPaytypeIdandValue(addPay, businessId) || []; if(formattedPay && formattedPay.length > 0) { formattedPay.forEach(x => { let index = _.findLastIndex(paytypes, {_id: x._id}); if (index > -1) { //found paytypes[index].value = x.value; paytypes[index].additionalPay = true; //add additional pay flag to skip monthly division } }); } } paytypes.forEach((x, index) => { //skip processing of Annual non selected annual paytypes //revisit this to factor in all payment frequency and create a logic on how processing is made if (x.frequency !== 'Annually' || (x.frequency === 'Annually' && specifiedAsProcess(x._id))) { // if (true) { let input = [], processing = []; input.push({ code: 'Number of days employee can work in month', value: numDaysEmployeeCanWorkInMonth }) input.push({ code: 'Number of hours employee can work in month', value: numDaysEmployeeCanWorkInMonth * 8 }) input.push({ code: 'Number of week days in month', value: totalNumWeekDaysInMonth }) if(x.isTimeWritingDependent) { input.push({ code: 'Hours worked on projects in month', value: projectsPayDetails.duration }) input.push({ code: 'Hours worked on cost centers in month', value: costCentersPayDetails.duration }) input.push({ code: 'Pay from cost-centers multiplier fraction', value: costCentersPayDetails.fraction }) } let boundary = [...paytypes]; //available types as at current processing boundary.length = index + 1; //format boundary for display in log let clone = boundary.map(x => { let b = {}; b.code = x.code; b.value = x.value; return b; }); input = input.concat(clone); let formula = x.value; let old = formula; if (formula) { //replace all wagetypes with values for (var i = 0; i < index; i++) { const code = paytypes[i].code ? paytypes[i].code.toUpperCase() : paytypes[i].code; const pattern = `\\b${code}\\b`; const regex = new RegExp(pattern, "g"); formula = formula.replace(regex, paytypes[i].value); } //do the same for all contansts and replace the values //will find a better way of doing this... NOTE let k = Constants.find({'businessId': businessId, 'status': 'Active'}).fetch(); //limit constant to only Bu constant k.forEach(c => { const code = c.code ? c.code.toUpperCase() : c.code; const pattern = `\\b${code}\\b`; const regex = new RegExp(pattern, "g"); formula = formula.replace(regex, c.value); }); processing.push({code: x.code, previous: old, derived: formula}); var parsed = rules.parse(formula, ''); if (parsed.result !== null && !isNaN(parsed.result)) { //negate value if paytype is deduction. x.parsedValue = x.type === 'Deduction' ? parsed.result.toFixed(2) * -1 : parsed.result.toFixed(2); //defaulting to 2 dp ... Make configurable; //-- let netPayTypeAmount; //net amount used if payment type is monthly if(x.frequency === 'Monthly' && !x.additionalPay){ netPayTypeAmount = (x.parsedValue / 12).toFixed(2); processing.push({code: `${x.code} - Monthly(NET)`, derived: netPayTypeAmount}); } //if add to total, add wt to totalsBucket totalsBucket += x.addToTotal ? parseFloat(x.parsedValue) : 0; //-- //add parsed value to defaultTax bucket if paytype is taxable if(tenant.baseCurrency.iso === x.currency) { defaultTaxBucket += x.taxable ? parseFloat(x.parsedValue) : 0; } else { defaultTaxBucket += x.taxable ? getPayAmountInForeignCurrency(x, parseFloat(x.parsedValue), currencyRatesForPeriod) : 0 } // console.log(`defaultTaxBucket`, defaultTaxBucket) //-- //for reliefs add to relief bucket if(tenant.baseCurrency.iso === x.currency) { reliefBucket += x.reliefFromTax ? parseFloat(x.parsedValue) : 0; } else { reliefBucket += x.reliefFromTax ? getPayAmountInForeignCurrency(x, parseFloat(x.parsedValue), currencyRatesForPeriod) : 0 } //assigned bucket if one of the paytype is selected as tax bucket if(tenant.baseCurrency.iso === x.currency) { if(x._id === tax.bucket) { assignedTaxBucket = { title: x.title, code: x.code, currency: x.currency || "", value: parseFloat(x.parsedValue) } } else { assignedTaxBucket = null } } else { if(x._id === tax.bucket) { assignedTaxBucket = { title: x.title, code: x.code, currency: x.currency || "", value: getPayAmountInForeignCurrency(x, parseFloat(x.parsedValue), currencyRatesForPeriod) } } else { assignedTaxBucket = null } } // console.log(`assignedTaxBucket`, assignedTaxBucket) processing.push({code: x.code, taxBucket: defaultTaxBucket}); //if paytype in pension then add to default pension buket const ptIndex = pension && _.indexOf(pension.payTypes, x._id); pensionBucket += ptIndex !== -1 ? parseFloat(x.parsedValue) : 0; // add parsed value to pension bucket if paytype is found //gross income for pension relief; if(tenant.baseCurrency.iso === x.currency) { grossIncomeBucket += tax.grossIncomeBucket === x._id ? parseFloat(x.parsedValue) : 0; } else { grossIncomeBucket += tax.grossIncomeBucket === x._id ? getPayAmountInForeignCurrency(x, parseFloat(x.parsedValue), currencyRatesForPeriod) : 0 } processing.push({code: x.code, pensionBucket: pensionBucket}); //set value let value = 0 if(netPayTypeAmount) { value = netPayTypeAmount } else { value = parseFloat(x.parsedValue); } //-- let projectPayAmount = 0 let costCenterPayAmount = 0 let projectsPay = [] if(x.isTimeWritingDependent) { if(totalHoursWorkedInPeriod > 0 && !x.additionalPay) { let totalWorkHoursInYear = 2080 let numberOfMonthsInYear = 12 projectsPayDetails.projectDurations.forEach(aProject => { // const fraction = aProject.duration * (numberOfMonthsInYear / totalWorkHoursInYear) const fraction = aProject.duration / (numDaysEmployeeCanWorkInMonth * 8) let projectPayAmount = fraction * value projectsPay.push({ projectId: aProject.project, durationInHours: aProject.duration, payAmount: projectPayAmount }) }) projectPayAmount = projectsPayDetails.fraction * value costCenterPayAmount = costCentersPayDetails.fraction * value value = projectPayAmount + costCenterPayAmount processing.push({code: "Pay from projects", derived: projectPayAmount}); processing.push({code: "Pay from cost centers", derived: costCenterPayAmount}); processing.push({code: x.code, derived: "(Pay from projects) + (Pay from cost-center)"}); processing.push({code: x.code, derived: value}); } else { value = 0 processing.push({code: x.code, derived: value}); } } else { processing.push({code: x.code, derived: value}); let totalWorkHoursInYear = 2080 let numberOfMonthsInYear = 12 processing.push({code: x.code + " - (Payment accounting for resumption date)", derived: ` ${value} * (${numDaysEmployeeCanWorkInMonth}) / ${totalNumWeekDaysInMonth})`}); costCenterPayAmount = value * ((numDaysEmployeeCanWorkInMonth) / totalNumWeekDaysInMonth) value = costCenterPayAmount processing.push({code: x.code, derived: value}); } //-- let valueInForeignCurrency = value if(tenant.baseCurrency.iso !== x.currency) { let currencyRateForPayType = _.find(currencyRatesForPeriod, (aCurrency) => { return aCurrency.code === x.currency }) // if(currencyRateForPayType) { // if(!isNaN(currencyRateForPayType.rateToBaseCurrency)) { // value = value * currencyRateForPayType.rateToBaseCurrency // } // } } //-- switch (x.type) { case 'Benefit': //add to payslip benefit if display in payslip if (x.addToTotal) { let paymentObj = { title: x.title, code: x.code, currency: x.currency || "", value, valueInForeignCurrency } benefit.push(paymentObj); let paymentsForCurrency = paymentsAccountingForCurrency.benefit[x.currency] if(!paymentsForCurrency) { paymentsAccountingForCurrency.benefit[x.currency] = {payments: []} } paymentsAccountingForCurrency.benefit[x.currency].payments.push({ title: x.title, code: x.code, currency: x.currency, taxable: x.taxable, value }) } else if(!x.addToTotal){ others.push({ title: x.title, code: x.code, currency: x.currency || "", value, valueInForeignCurrency }); let paymentsForCurrency = paymentsAccountingForCurrency.others[x.currency] if(!paymentsForCurrency) { paymentsAccountingForCurrency.others[x.currency] = {payments: []} } paymentsAccountingForCurrency.others[x.currency].payments.push({ title: x.title, code: x.code, currency: x.currency, taxable: x.taxable, value }) } break; case 'Deduction': if (x.addToTotal){ deduction.push({ title: x.title, code: x.code, currency: x.currency || "", value, valueInForeignCurrency: '' }); let paymentsForCurrency = paymentsAccountingForCurrency.deduction[x.currency] if(!paymentsForCurrency) { paymentsAccountingForCurrency.deduction[x.currency] = {payments: []} } paymentsAccountingForCurrency.deduction[x.currency].payments.push({ title: x.title, code: x.code, currency: x.currency, taxable: x.taxable, // redundant. Deductions can't be taxable value }) } else if(!x.addToTotal){ others.push({ title: x.title, code: x.code, currency: x.currency || "", value, valueInForeignCurrency }); let paymentsForCurrency = paymentsAccountingForCurrency.others[x.currency] if(!paymentsForCurrency) { paymentsAccountingForCurrency.others[x.currency] = {payments: []} } paymentsAccountingForCurrency.others[x.currency].payments.push({ title: x.title, code: x.code, currency: x.currency, taxable: x.taxable, value }) } } //add value to result employeeResult.payment.push({ id: x._id, reference: 'Paytype', amountLC: value, amountPC: valueInForeignCurrency, projectPayAmount: projectPayAmount, costCenterPayAmount: costCenterPayAmount, projectsPay: projectsPay, code: x.code, description: x.title, type: (x.displayInPayslip && !x.addToTotal) ? 'Others': x.type }); log.push({paytype: x.code, input: input, processing: processing}); } else { //when there is an error, stop processing this employee and move to the next one processing.push({code: x.code, derived: `Unable to handle Paytype Derivative ${formula} = ${parsed}`}); log.push({paytype: x.code, input: input, processing: processing}); throw new PaytypeException('Unable to handle Paytype Derivative', `${formula} = ${parsed.error}`); } empDerivedPayElements.push(x); // } } }) // console.log(`paymentsAccountingForCurrency: `, JSON.stringify(paymentsAccountingForCurrency)) } catch (e) { const error = {}; error.employee = `${x.employeeProfile.employeeId} - ${x.profile.fullName}`; error.reason = e.message; error.details = e.paytype; processingError.push(error); //set processing to false and do not save result. skipToNextEmployee = true } if(!skipToNextEmployee) {//further processing after evaluation of all paytypes! pension calculation and tax calculation //get employee and employer contribution const {employerPenContrib, employeePenContrib, grossPension, pensionLog} = getPensionContribution(pensionBucket, pension); //@@technicalPaytype //populate result for employee and employer pension contribution if(pension){ employeeResult.payment.push({id: pension._id, reference: 'Pension', amountLC: employeePenContrib, amountPC: '', code: pension.code + '_EE', description: pension.name + ' Employee', type: 'Deduction'}); employeeResult.payment.push({id: pension._id, reference: 'Pension', amountLC: employerPenContrib, amountPC: '', code: pension.code + '_ER', description: pension.name + ' Employer', type: 'Others'}); if(!paymentsAccountingForCurrency.deduction['NGN']) { paymentsAccountingForCurrency.deduction['NGN'] = {payments: []} } if(!paymentsAccountingForCurrency.others['NGN']) { paymentsAccountingForCurrency.others['NGN'] = {payments: []} } paymentsAccountingForCurrency.deduction['NGN'].payments.push({ title: pension.name + ' Employee', code: pension.code + '_EE', currency: 'NGN', reference: 'Pension', value: -1 * employeePenContrib }) paymentsAccountingForCurrency.others['NGN'].payments.push({ title: pension.name + ' Employer', code: pension.code + '_ER', currency: 'NGN', reference: 'Pension', value: employerPenContrib }) } if(pensionLog) //add pension calculation log log.push(pensionLog); //add employee to relief Bucket reliefBucket += (grossPension || 0); //nagate employee Pension contribution and add to relief bucket //--Tax processing follows // let netTax = null let netTaxLocal = 0 let netTaxForeign = 0 let taxLog = null const effectiveTaxDetails = Tax.findOne({isUsingEffectiveTaxRate: true, employees: x._id, status: 'Active'}); if(effectiveTaxDetails) { const taxComputationInput = [ {code: 'Effective Tax Rate', value: effectiveTaxDetails.effectiveTaxRate}, // {code: 'TaxBucket', value: taxBucket} ]; if(assignedTaxBucket) { netTaxLocal = (assignedTaxBucket.value * effectiveTaxDetails.effectiveTaxRate) taxComputationInput.push( {code: 'TaxBucket', value: assignedTaxBucket.value} ) const taxProcessing = []; taxProcessing.push({code: 'Tax', derived: '(taxBucket * Effective Tax Rate)'}); taxProcessing.push({code: 'Tax', derived: netTaxLocal }); netTaxLocal = parseFloat(netTaxLocal).toFixed(2) taxLog = {paytype: effectiveTaxDetails.code, input: taxComputationInput, processing: taxProcessing}; //populate result for tax if(tenant.baseCurrency.iso === assignedTaxBucket.currency) { employeeResult.payment.push({id: tax._id, reference: 'Tax', amountLC: netTaxLocal, amountPC: '', code: tax.code, description: tax.name, type: 'Deduction' }); } else { employeeResult.payment.push({id: tax._id, reference: 'Tax', amountLC: '', amountPC: netTaxLocal, code: tax.code, description: tax.name, type: 'Deduction' }); } } else { let taxableIncomeInDiffCurrencies = {} let benefitsDeductionsAndOthers = Object.keys(paymentsAccountingForCurrency) benefitsDeductionsAndOthers.forEach(aPayCategory => { let payCategoryCurrencies = Object.keys(paymentsAccountingForCurrency[aPayCategory]) payCategoryCurrencies.forEach(aCurrency => { if(!taxableIncomeInDiffCurrencies[aCurrency]) { taxableIncomeInDiffCurrencies[aCurrency] = 0 } let paymentsInCurrency = paymentsAccountingForCurrency[aPayCategory][aCurrency] paymentsInCurrency.payments.forEach(aPayment => { if(aPayment.taxable) { let paymentAsFloat = parseFloat(aPayment.value) if(!isNaN(paymentAsFloat)) { taxableIncomeInDiffCurrencies[aCurrency] += paymentAsFloat } } }) }) }) // console.log(`taxableIncomeInDiffCurrencies: `, JSON.stringify(taxableIncomeInDiffCurrencies)) //-- const taxProcessing = []; let taxCurrencies = Object.keys(taxableIncomeInDiffCurrencies) taxCurrencies.forEach(aCurrency => { let taxableIncome = taxableIncomeInDiffCurrencies[aCurrency] if(!paymentsAccountingForCurrency.deduction[aCurrency]) { paymentsAccountingForCurrency.deduction[aCurrency] = {payments: []} } if(aCurrency === tenant.baseCurrency.iso) { netTaxLocal = (taxableIncome * effectiveTaxDetails.effectiveTaxRate) paymentsAccountingForCurrency.deduction[aCurrency].payments.push({ title: tax.name, code: tax.code, currency: aCurrency, // taxable: true, reference: 'Tax', value: netTaxLocal * -1 }) } else { netTaxForeign = (taxableIncome * effectiveTaxDetails.effectiveTaxRate) paymentsAccountingForCurrency.deduction[aCurrency].payments.push({ title: tax.name, code: tax.code, currency: aCurrency, // taxable: true, reference: 'Tax', value: netTaxForeign * -1 }) } //-- taxComputationInput.push({ code: `TaxBucket(${aCurrency})`, value: taxableIncome }) //-- taxProcessing.push({code: `Tax(${aCurrency})`, derived: '(TaxBucket * Effective Tax Rate)'}); taxProcessing.push({code: `Tax(${aCurrency})`, derived: (taxableIncome * effectiveTaxDetails.effectiveTaxRate) }); }) //-- taxLog = {paytype: effectiveTaxDetails.code, input: taxComputationInput, processing: taxProcessing}; employeeResult.payment.push({ id: tax._id, reference: 'Tax', amountLC: netTaxLocal, amountPC: netTaxForeign, code: tax.code, description: tax.name, type: 'Deduction' }); } } else { let taxBucket = null; if(assignedTaxBucket) {//automatically use default tax bucket if tax bucket not found taxBucket = assignedTaxBucket.value } else { taxBucket = defaultTaxBucket } let taxCalculationResult = calculateTax(reliefBucket, taxBucket, grossIncomeBucket, tax); //@@technicalPaytype netTaxLocal = taxCalculationResult.netTax taxLog = taxCalculationResult.taxLog //populate result for tax employeeResult.payment.push({id: tax._id, reference: 'Tax', amountLC: netTaxLocal, amountPC: '', code: tax.code, description: tax.name, type: 'Deduction'}); //-- paymentsAccountingForCurrency.deduction['NGN'].payments.push({ title: tax.name, code: tax.code, currency: 'NGN', reference: 'Tax', value: netTaxLocal * -1 }) } if(taxLog) log.push(taxLog); //collate results and populate paySlip; and push to payresult let final = {}; final.log = log; //payrun processing log final.payslip = {benefit: benefit, deduction: deduction}; //pension and tax are also deduction final.payslip.deduction.push({ title: tax.code, code: tax.name, value: netTaxLocal * -1, valueInForeignCurrency: netTaxForeign * -1 }); // negate add tax to deduction //--End of Tax processing if(pension) { let valueInForeignCurrency = '' final.payslip.deduction.push({title: `${pension.code}_EE`, code: `${pension.name} Employee`, value: employeePenContrib * -1, valueInForeignCurrency}); // if(pension.displayEmployerInPayslip) { valueInForeignCurrency = '' final.payslip.others = others.concat([{title: `${pension.code}_ER`, code: `${pension.name} Employer`, value: employerPenContrib, valueInForeignCurrency}]); //if employer contribution (displayEmployerInPayslip) add to other payments // } } else { final.payslip.others = others } //-- final.payslipWithCurrencyDelineation = paymentsAccountingForCurrency //-- let benefitsDeductionsAndOthers = Object.keys(paymentsAccountingForCurrency) let netPayWithCurrencyDelineation = {} let deductionWithCurrencyDelineation = {} benefitsDeductionsAndOthers.forEach(aPayCategory => { let payCategoryCurrencies = Object.keys(paymentsAccountingForCurrency[aPayCategory]) payCategoryCurrencies.forEach(aCurrency => { let total = 0 let paymentsInCurrency = paymentsAccountingForCurrency[aPayCategory][aCurrency] if(!paymentsInCurrency) { paymentsAccountingForCurrency[aPayCategory][aCurrency] = {payments: []} paymentsInCurrency = paymentsAccountingForCurrency[aPayCategory][aCurrency] } paymentsInCurrency.payments.forEach(aPayment => { let paymentAsFloat = parseFloat(aPayment.value) if(!isNaN(paymentAsFloat)) { total += paymentAsFloat } }) paymentsInCurrency.total = total //-- if(aPayCategory === 'benefit') { if(netPayWithCurrencyDelineation[aCurrency]) { netPayWithCurrencyDelineation[aCurrency] = netPayWithCurrencyDelineation[aCurrency] + total } else { netPayWithCurrencyDelineation[aCurrency] = total } } else if(aPayCategory === 'deduction') { if(netPayWithCurrencyDelineation[aCurrency]) { netPayWithCurrencyDelineation[aCurrency] = netPayWithCurrencyDelineation[aCurrency] + total } else { netPayWithCurrencyDelineation[aCurrency] = total } //-- if(deductionWithCurrencyDelineation[aCurrency]) { deductionWithCurrencyDelineation[aCurrency] = deductionWithCurrencyDelineation[aCurrency] + total } else { deductionWithCurrencyDelineation[aCurrency] = total } } else if(aPayCategory === 'others') {// Do nothing } }) }) const employeeDetails = getDetailsInPayslip(x); paymentsAccountingForCurrency.employee = employeeDetails; paymentsAccountingForCurrency.employee.grade = grade.code; paymentsAccountingForCurrency.employee.gradeId = grade._id; //-- let netPayCurrencies = Object.keys(netPayWithCurrencyDelineation) netPayCurrencies.forEach(currency => { if(currency === tenant.baseCurrency.iso) { employeeResult.payment.push({ reference: 'Standard', amountLC: netPayWithCurrencyDelineation[currency], amountPC: netPayWithCurrencyDelineation[currency], code: 'NMP', description: 'Net Payment', type: 'netPayment' }); final.payslip['totalPayment'] = paymentsAccountingForCurrency.benefit[currency].total final.payslip['netPayment'] = netPayWithCurrencyDelineation[currency] } else { employeeResult.payment.push({ reference: 'Standard_' + currency, amountLC: netPayWithCurrencyDelineation[currency], amountPC: netPayWithCurrencyDelineation[currency], code: 'NMP', description: 'Net Payment ' + currency, type: 'netPayment' }); final.payslip['totalPayment_' + currency] = paymentsAccountingForCurrency.benefit[currency].total final.payslip['netPayment_' + currency] = netPayWithCurrencyDelineation[currency] } }) //-- let deductionCurrencies = Object.keys(deductionWithCurrencyDelineation) deductionCurrencies.forEach(currency => { if(currency === tenant.baseCurrency.iso) { employeeResult.payment.push({ reference: 'Standard-1', amountLC: deductionWithCurrencyDelineation[currency], amountPC: deductionWithCurrencyDelineation[currency], code: 'TDEDUCT', description: 'Total Deduction', type: 'totalDeduction' }); final.payslip['totalDeduction'] = deductionWithCurrencyDelineation[currency] } else { employeeResult.payment.push({ reference: 'Standard-1_' + currency, amountLC: deductionWithCurrencyDelineation[currency], amountPC: deductionWithCurrencyDelineation[currency], code: 'TDEDUCT', description: 'Total Deduction ' + currency, type: 'totalDeduction' }); final.payslip['totalDeduction_' + currency] = deductionWithCurrencyDelineation[currency] } }) //--Deprecated method for calculating net pay //calculate net payment as payment - deductions; // negate and add pension to deduction // const totalPayment = sumPayments(final.payslip.benefit); // const totalDeduction = sumPayments(final.payslip.deduction); // const netPayment = parseFloat(totalPayment) + parseFloat(totalDeduction); //@@technicalPaytype //populate result for net payment // employeeResult.payment.push({reference: 'Standard', amountLC: netPayment, amountPC: getNetPayInForeignCurrency(netPayment, grade, currencyRatesForPeriod), code: 'NMP', description: 'Net Payment', type: 'netPayment' }); // employeeResult.payment.push({reference: 'Standard-1', amountLC: totalDeduction, amountPC: getNetPayInForeignCurrency(totalDeduction, grade, currencyRatesForPeriod), code: 'TDEDUCT', description: 'Total Deduction', type: 'totalDeduction' }); // final.payslip.totalPayment = totalPayment; // final.payslip.totalDeduction = totalDeduction; // final.payslip.netPayment = netPayment; //-- //Add currently process employee details to final.payslip.employee const employee = getDetailsInPayslip(x); final.payslip.employee = employee; final.payslip.employee.grade = grade.code; final.payslip.employee.gradeId = grade._id; final.payslip.period = period //payement will also be sent to result for factoring and storage; payresult.push(final); // also push employee result payrun.push(employeeResult); //factor payments for storage if not simulation //map default buckets and paytypes used to assigned in config. } else { //when there is an exception let final = {}; final.log = log; //payrun processing log final.payslip = {benefit: [], deduction: []}; //Add currently process employee details to final.payslip.employee const employee = getDetailsInPayslip(x); final.payslip.employee = employee; if(grade) { final.payslip.employee.grade = grade.code; } else { final.payslip.employee.grade = ""; } final.error = true; //payement will also be sent to result for factoring and storage; payresult.push(final); } } count++; runPayrun(count); } else { // end of recursion } }; runPayrun(count); //after the recurssion return result to calling function; return {result: payresult, error:processingError, payrun}; }; function getDaysEmployeeCanWorkInMonth(employee, firstDayOfMonthDateObj) { let employeeResumption = employee.employeeProfile.employment.hireDate // console.log(`\n employee id: `, employee._id) if(!employeeResumption || employeeResumption === '') { employeeResumption = firstDayOfMonthDateObj } let employeeResumptionMoment = moment(employeeResumption) let monthDateMoment = moment(firstDayOfMonthDateObj) let endOfMonthDate = moment(firstDayOfMonthDateObj).endOf('month').toDate() let numDaysToWorkInMonth = 0 if(employeeResumptionMoment.year() === monthDateMoment.year()) { if (employeeResumptionMoment.month() === monthDateMoment.month()) { numDaysToWorkInMonth = getWeekDays(employeeResumption, endOfMonthDate).length } else if(employeeResumptionMoment.month() > monthDateMoment.month()) { numDaysToWorkInMonth = 0 } else { numDaysToWorkInMonth = getWeekDays(firstDayOfMonthDateObj, endOfMonthDate).length } } else if(employeeResumptionMoment.year() > monthDateMoment.year()) { numDaysToWorkInMonth = 0 } else if(employeeResumptionMoment.year() < monthDateMoment.year()) { numDaysToWorkInMonth = getWeekDays(firstDayOfMonthDateObj, endOfMonthDate).length } return numDaysToWorkInMonth } function getWeekDays(startDate, endDate) { let startDateMoment = moment(startDate) let endDateMoment = moment(endDate) let numberOfDays = endDateMoment.diff(startDateMoment, 'days') + 1 let startDateMomentClone = moment(startDateMoment); // use a clone let weekDates = [] while (numberOfDays > 0) { if (startDateMomentClone.isoWeekday() !== 6 && startDateMomentClone.isoWeekday() !== 7) { weekDates.push(moment(startDateMomentClone).toDate()) // calling moment here cos I need a clone } startDateMomentClone.add(1, 'days'); numberOfDays -= 1; } return weekDates } function getPayAmountInForeignCurrency(payTypeDetails, amountInLocalCurrency, currencyRatesForPeriod) { let amountInForeignCurrency = null let currencyRateForPayType = _.find(currencyRatesForPeriod, (aCurrency) => { return aCurrency.code === payTypeDetails.currency }) if(currencyRateForPayType) { if(!isNaN(currencyRateForPayType.rateToBaseCurrency)) { amountInForeignCurrency = amountInLocalCurrency * currencyRateForPayType.rateToBaseCurrency } } return amountInForeignCurrency } /* This function can also be used for the total deduction */ function getNetPayInForeignCurrency(amountInLocalCurrency, payGrade, currencyRatesForPeriod) { if(payGrade) { let netPayAlternativeCurrency = payGrade.netPayAlternativeCurrency let currencyInPeriod = _.find(currencyRatesForPeriod, (aCurrency) => { return aCurrency.code === netPayAlternativeCurrency }) if(currencyInPeriod) { let rateToBaseCurrency = currencyInPeriod.rateToBaseCurrency return (rateToBaseCurrency > 0) ? (amountInLocalCurrency / rateToBaseCurrency).toFixed(2) : amountInLocalCurrency } else { return amountInLocalCurrency } } else { return amountInLocalCurrency } } function getFractionForCalcProjectsPayValue(businessId, periodMonth, periodYear, employeeUserId) { const firsDayOfPeriod = `${periodMonth}-01-${periodYear} GMT`; const startDate = moment(new Date(firsDayOfPeriod)).startOf('month').toDate(); const endDate = moment(startDate).endOf('month').toDate(); let queryObj = { businessId: businessId, project: {$exists : true}, day: {$gte: startDate, $lt: endDate}, employeeId: employeeUserId, status: 'Approved' } let allProjectTimesInMonth = TimeWritings.aggregate([ { $match: queryObj}, { $group: { _id: { "empUserId": "$employeeId", "project": "$project" }, duration: { $sum: "$duration" } } } ]); //-- let totalWorkHoursInYear = 2080 let numberOfMonthsInYear = 12 if(allProjectTimesInMonth) { if(allProjectTimesInMonth.length > 0) { // console.log(`allProjectTimesInMonth: `, allProjectTimesInMonth) let projectDurations = [] let totalProjectsDuration = 0 allProjectTimesInMonth.forEach(aProjectTime => { totalProjectsDuration += aProjectTime.duration projectDurations.push({ project: aProjectTime._id.project, duration: aProjectTime.duration }) }) const fraction = totalProjectsDuration * numberOfMonthsInYear / totalWorkHoursInYear return {duration: totalProjectsDuration, fraction, projectDurations} } else { return {duration: 0, fraction: 0, projectDurations: []} } } else { return {duration: 0, fraction: 0, projectDurations: []} } } function getFractionForCalcCostCentersPayValue(businessId, periodMonth, periodYear, employeeUserId) { const firsDayOfPeriod = `${periodMonth}-01-${periodYear} GMT`; const startDate = moment(new Date(firsDayOfPeriod)).startOf('month').toDate(); const endDate = moment(startDate).endOf('month').toDate(); let queryObj = { businessId: businessId, costCenter: {$exists : true}, day: {$gte: startDate, $lt: endDate}, employeeId: employeeUserId, status: 'Approved' } let allCostCenterTimesInMonth = TimeWritings.aggregate([ { $match: queryObj}, { $group: {_id: "$employeeId", duration: { $sum: "$duration" }}} ]); //-- let totalWorkHoursInYear = 2080 let numberOfMonthsInYear = 12 if(allCostCenterTimesInMonth) { if(allCostCenterTimesInMonth.length === 1) { const duration = allCostCenterTimesInMonth[0].duration const fraction = duration * numberOfMonthsInYear / totalWorkHoursInYear return {duration, fraction} } else { return {duration: 0, fraction: 0} } } else { return {duration: 0, fraction: 0} } } function derivePayElement(person) { let gradePaytypes = PayGrades.find({_id: person.employeeProfile.employment.paygrade}); return "done"; //get employee pay grade } function getEmployeeGrade(gradeId) { return PayGrades.findOne({_id: gradeId, status: 'Active'}); } function determineRule(paytype, grade) { //grade contains processing rules while paytypes contains personal employee rules let pt = [...grade.payTypes]; const empGrade = pt.map(x => { const newX = {...x} let index = _.findLastIndex(paytype, {'paytype': x.paytype}); if (index !== -1) { //derive rule based on employee assigned if no value assinged, use grade derivative if (paytype[index].value) { newX.value = paytype[index].value; } } //return same rule return newX; }); return empGrade; } function getPaygroup(paygrade) { const pg = PayGroups.findOne({_id: paygrade, status: 'Active'}); const penTax = {}; if (pg) { if (pg.tax) { const tax = Tax.findOne({_id: pg.tax, status: 'Active'}); tax ? penTax.tax = tax : null; } if (pg.pension) { const pension = Pensions.findOne({_id: pg.pension, status: 'Active'}); pension ? penTax.pension = pension : null; } } return penTax; } //return employer and employee contribution function getPensionContribution(pensionBucket, pension) { //@import pension bucket float, pension doc. //all elements of pension already derived into pensionBucket //calculate employer and employee contribution if (pension) { const input = [{code: 'Pension Bucket', value: pensionBucket}]; const processing = []; const eerate = pension.employeeContributionRate; const errate = pension.employerContributionRate; const employee = (eerate / 100) * pensionBucket; processing.push({code: `Employee rate`, derived: `(${eerate} / 100) * ${pensionBucket}` }); processing.push({code: `Employee rate`, derived: employee }); const employer = (errate / 100) * pensionBucket; processing.push({code: `Employer rate`, derived: `(${errate} / 100) * ${pensionBucket}` }); processing.push({code: `Employer rate`, derived: employer }); const netee = employee / 12; const neter = employer / 12; //log for net employee contribution processing.push({code: `Employer rate`, derived: `(${employer} / 12) ` }); processing.push({code: `Employer Net Rate`, derived: neter }); //log for net employee contribution processing.push({code: `Employee rate`, derived: `(${employee} / 12) ` }); processing.push({code: `Employee Net Rate`, derived: netee }); const log = {paytype: pension.code, input: input, processing: processing}; return {employeePenContrib: parseFloat(netee).toFixed(2), employerPenContrib: parseFloat(neter).toFixed(2), grossPension: employee, pensionLog: log}; } else { return {employeePenContrib: null, employerPenContrib: null} } } //from taxable income calculate tax and return value function calculateTax(relief, taxBucket, grossIncomeBucket, tax) { //@import taxBucket (defualt tax bucket or valuated passed bucket) //@import tax (tax doc configured ) //calculate reliefs //no checks done yet exceptions NAN undefined checkes //return result {finalTax: log[] } const input = [{code: 'Relief', value: relief}, {code: 'TaxBucket', value: taxBucket}, {code: 'GrossIncomeBucket', value: grossIncomeBucket}]; const processing = []; const grossIncomeRelief = (tax.grossIncomeRelief / 100) * grossIncomeBucket; processing.push({code: 'Gross Income Relief', derived: '(grossIncomeRelief / 100) * grossIncomeBucket'}); processing.push({code: 'Gross Income Relief', derived: grossIncomeRelief }); const consolidatedRelief = tax.consolidatedRelief; processing.push({code: `Consolidated Relief defined in ${tax.code}`, derived: consolidatedRelief }); const totalRelief = grossIncomeRelief + consolidatedRelief + relief; processing.push({code: `Total Relief`, derived: 'grossIncomeRelief + consolidatedRelief + relief' }); processing.push({code: `Total Relief`, derived: totalRelief }); let taxableIncome = taxBucket - totalRelief; processing.push({code: `Taxable Income`, derived: 'taxBucket - totalRelief' }); processing.push({code: `Taxable Income`, derived: taxableIncome }); let totalTax = 0; //apply tax rules on taxable income const rules = [...tax.rules]; let isTaxableIncomeLessThanFirstUpperLimit = false //add log for debugging //deduct upper limit from taxable income //no need to calcuate tax if taxable income- if (taxableIncome >= rules[0].upperLimit) { for (let i = 0; i < rules.length; i++) { let x = rules[i]; if (x.range !== 'Over') { processing.push({code: `Total Tax(${x.range} ${x.upperLimit})`, derived: `${x.rate} * (${taxableIncome} - ${x.upperLimit}) / 100` }); if (taxableIncome >= x.upperLimit) { taxableIncome -= x.upperLimit; totalTax += x.rate * (x.upperLimit / 100); } else { totalTax += x.rate * (taxableIncome / 100); break; } processing.push({code: `Total Tax(${x.range} ${x.upperLimit})`, derived: totalTax }); } else { processing.push({code: `Total Tax(${x.range} ${x.upperLimit})`, derived: `${x.rate} * (${taxableIncome}) / 100` }); totalTax += x.rate * (taxableIncome / 100); processing.push({code: `Total Tax(${x.range} ${x.upperLimit})`, derived: totalTax }); } } } else { isTaxableIncomeLessThanFirstUpperLimit = true } const netTax = totalTax / 12; if(isTaxableIncomeLessThanFirstUpperLimit) { processing.push({code: `Net Tax(Total Tax / 12 ) - {Fail! Taxable income is less than first upper limit of tax rule}`, derived: `${totalTax}` / 12 }); processing.push({code: `Net Tax - {Fail! Taxable income is less than first upper limit of tax rule}`, derived: netTax }); } else { processing.push({code: `Net Tax(Total Tax / 12 )`, derived: `${totalTax}` / 12 }); processing.push({code: `Net Tax`, derived: netTax }); } const log = {paytype: tax.code, input: input, processing: processing}; return {netTax: parseFloat(netTax).toFixed(2), taxLog: log}; } /* Sum payments in groups @import array */ function sumPayments(payments){ const newPay = [...payments]; const sum = newPay.reduce(function(total, val) { return total + parseFloat(val.value); }, 0); return parseFloat(sum).toFixed(2) ; } /* import employee doc. return {} object containing employee details to be displayed on payslip */ function getDetailsInPayslip(employee){ let details = {}; details.employeeUserId = employee._id; details.employeeId = employee.employeeProfile.employeeId; details.fullname = employee.profile.fullName; details.accountNumber = employee.employeeProfile.payment.accountNumber || ""; details.bank = employee.employeeProfile.payment.bank || ""; // add other details return details; } function getPaytypeIdandValue(additionalPay, businessId) { let newAddPay = [...additionalPay]; let paytypes = []; //lazyload paytypes to reduce number of database query. newAddPay.forEach(x => { const paytype = PayTypes.findOne({code: x.paytype, businessId: businessId, status: 'Active'}); if(paytype) paytype.value = x.amount.toString(); // add the value as additional pay value paytypes.push(paytype); }); return paytypes; } function PaytypeException(message, paytype) { this.message = message; this.name = 'PaytypeEvaluationException'; this.paytype = paytype; }
converting project and cost center payments for sap integration
main/app/server/methods/payruns.js
converting project and cost center payments for sap integration
<ide><path>ain/app/server/methods/payruns.js <ide> //-- <ide> //--Time recording things <ide> const projectsPayDetails = <del> getFractionForCalcProjectsPayValue(businessId, period.month, period.year, x._id) <add> getFractionForCalcProjectsPayValue(businessId, period.month, period.year, totalNumWeekDaysInMonth, x._id) <ide> // {duration: , fraction: } <ide> <ide> const costCentersPayDetails = <del> getFractionForCalcCostCentersPayValue(businessId, period.month, period.year, x._id) <add> getFractionForCalcCostCentersPayValue(businessId, period.month, period.year, totalNumWeekDaysInMonth, x._id) <ide> // {duration: , fraction: } <ide> <ide> let totalHoursWorkedInPeriod = projectsPayDetails.duration + costCentersPayDetails.duration <ide> }) <ide> <ide> input.push({ <del> code: 'Number of week days in month', <add> code: 'Number of working days in month', <ide> value: totalNumWeekDaysInMonth <ide> }) <ide> <ide> if(tenant.baseCurrency.iso === x.currency) { <ide> defaultTaxBucket += x.taxable ? parseFloat(x.parsedValue) : 0; <ide> } else { <del> defaultTaxBucket += x.taxable ? getPayAmountInForeignCurrency(x, parseFloat(x.parsedValue), currencyRatesForPeriod) : 0 <add> defaultTaxBucket += x.taxable ? convertForeignCurrencyToBaseCurrency(x, parseFloat(x.parsedValue), currencyRatesForPeriod) : 0 <ide> } <ide> // console.log(`defaultTaxBucket`, defaultTaxBucket) <ide> <ide> if(tenant.baseCurrency.iso === x.currency) { <ide> reliefBucket += x.reliefFromTax ? parseFloat(x.parsedValue) : 0; <ide> } else { <del> reliefBucket += x.reliefFromTax ? getPayAmountInForeignCurrency(x, parseFloat(x.parsedValue), currencyRatesForPeriod) : 0 <add> reliefBucket += x.reliefFromTax ? convertForeignCurrencyToBaseCurrency(x, parseFloat(x.parsedValue), currencyRatesForPeriod) : 0 <ide> } <ide> <ide> //assigned bucket if one of the paytype is selected as tax bucket <ide> title: x.title, <ide> code: x.code, <ide> currency: x.currency || "", <del> value: getPayAmountInForeignCurrency(x, parseFloat(x.parsedValue), currencyRatesForPeriod) <add> value: convertForeignCurrencyToBaseCurrency(x, parseFloat(x.parsedValue), currencyRatesForPeriod) <ide> } <ide> } else { <ide> assignedTaxBucket = null <ide> } <ide> } <ide> // console.log(`assignedTaxBucket`, assignedTaxBucket) <del> <del> processing.push({code: x.code, taxBucket: defaultTaxBucket}); <add> /// Intentional comment ... does not break the payrun <add> // processing.push({code: x.code, taxBucket: defaultTaxBucket}); <add> /// <ide> <ide> //if paytype in pension then add to default pension buket <ide> const ptIndex = pension && _.indexOf(pension.payTypes, x._id); <ide> if(tenant.baseCurrency.iso === x.currency) { <ide> grossIncomeBucket += tax.grossIncomeBucket === x._id ? parseFloat(x.parsedValue) : 0; <ide> } else { <del> grossIncomeBucket += tax.grossIncomeBucket === x._id ? getPayAmountInForeignCurrency(x, parseFloat(x.parsedValue), currencyRatesForPeriod) : 0 <add> grossIncomeBucket += tax.grossIncomeBucket === x._id ? convertForeignCurrencyToBaseCurrency(x, parseFloat(x.parsedValue), currencyRatesForPeriod) : 0 <ide> } <del> processing.push({code: x.code, pensionBucket: pensionBucket}); <add> <add> /// Intentional comment ... does not break the payrun <add> // processing.push({code: x.code, pensionBucket: pensionBucket}); <add> /// <ide> <ide> //set value <ide> let value = 0 <ide> projectsPayDetails.projectDurations.forEach(aProject => { <ide> // const fraction = aProject.duration * (numberOfMonthsInYear / totalWorkHoursInYear) <ide> const fraction = aProject.duration / (numDaysEmployeeCanWorkInMonth * 8) <del> let projectPayAmount = fraction * value <add> let individualProjectPayAmount = fraction * value <add> if(tenant.baseCurrency.iso !== x.currency) { <add> individualProjectPayAmount = convertForeignCurrencyToBaseCurrency(x, projectPayAmount, currencyRatesForPeriod) <add> } <ide> <ide> projectsPay.push({ <ide> projectId: aProject.project, <ide> durationInHours: aProject.duration, <del> payAmount: projectPayAmount <add> payAmount: individualProjectPayAmount <ide> }) <ide> }) <del> projectPayAmount = projectsPayDetails.fraction * value <add> let projectsTotalPayInPayTypeCurrency = projectsPayDetails.fraction * value <ide> costCenterPayAmount = costCentersPayDetails.fraction * value <del> value = projectPayAmount + costCenterPayAmount <del> <del> processing.push({code: "Pay from projects", derived: projectPayAmount}); <del> processing.push({code: "Pay from cost centers", derived: costCenterPayAmount}); <del> <del> processing.push({code: x.code, derived: "(Pay from projects) + (Pay from cost-center)"}); <add> <add> value = projectsTotalPayInPayTypeCurrency + costCenterPayAmount <add> <add> if(tenant.baseCurrency.iso !== x.currency) { <add> processing.push({code: `Pay from projects(${x.currency})`, derived: `(${projectsPayDetails.duration} / ${totalNumWeekDaysInMonth} * 8) * ${value}`}); <add> processing.push({code: `Pay from projects(${x.currency})`, derived: projectsTotalPayInPayTypeCurrency}); <add> <add> processing.push({code: "Pay from projects(NGN)", derived: `(${projectsPayDetails.duration} / ${totalNumWeekDaysInMonth} * 8) * ${value} * currency rate`}); <add> <add> processing.push({code: "Pay from projects(NGN)", derived: `${projectsPayDetails.fraction} * ${value} * currency rate`}); <add> projectPayAmount = convertForeignCurrencyToBaseCurrency(x, projectsTotalPayInPayTypeCurrency, currencyRatesForPeriod) <add> } else { <add> projectPayAmount = projectsTotalPayInPayTypeCurrency <add> processing.push({code: "Pay from projects(NGN)", derived: `${projectsPayDetails.fraction} * ${value}`}); <add> } <add> //-- <add> if(tenant.baseCurrency.iso !== x.currency) { <add> processing.push({code: `Pay from projects(${x.currency})`, derived: `(${costCentersPayDetails.duration} / ${totalNumWeekDaysInMonth} * 8) * ${value} * currency rate`}); <add> <add> processing.push({code: `Pay from cost centers(${x.currency})`, derived: `${costCentersPayDetails.fraction} * ${value} * currency rate`}); <add> costCenterPayAmount = convertForeignCurrencyToBaseCurrency(x, costCenterPayAmount, currencyRatesForPeriod) <add> } else { <add> processing.push({code: `Pay from cost centers(${x.currency})`, derived: `${costCentersPayDetails.fraction} * ${value}`}); <add> } <add> <add> processing.push({code: `Pay from projects(${x.currency})`, derived: projectPayAmount}); <add> processing.push({code: `Pay from cost centers(${x.currency})`, derived: costCenterPayAmount}); <add> <add> processing.push({code: x.code, derived: `(Pay from projects(${x.currency})) + (Pay from cost-center(${x.currency}))`}); <ide> processing.push({code: x.code, derived: value}); <ide> } else { <ide> value = 0 <ide> processing.push({code: x.code, derived: value}); <ide> } <ide> } else { <del> processing.push({code: x.code, derived: value}); <del> let totalWorkHoursInYear = 2080 <del> let numberOfMonthsInYear = 12 <del> <del> processing.push({code: x.code + " - (Payment accounting for resumption date)", derived: ` ${value} * (${numDaysEmployeeCanWorkInMonth}) / ${totalNumWeekDaysInMonth})`}); <add> // let totalWorkHoursInYear = 2080 <add> // let numberOfMonthsInYear = 12 <ide> <ide> costCenterPayAmount = value * ((numDaysEmployeeCanWorkInMonth) / totalNumWeekDaysInMonth) <del> <ide> value = costCenterPayAmount <ide> <add> if(tenant.baseCurrency.iso !== x.currency) { <add> costCenterPayAmount = convertForeignCurrencyToBaseCurrency(x, costCenterPayAmount, currencyRatesForPeriod) <add> // processing.push({code: x.code + " - (Payment accounting for resumption date)", derived: ` ${value} * (${numDaysEmployeeCanWorkInMonth}) / ${totalNumWeekDaysInMonth}) * currency rate`}); <add> processing.push({code: x.code + " - (Payment accounting for resumption date)", derived: ` ${value} * (${numDaysEmployeeCanWorkInMonth}) / ${totalNumWeekDaysInMonth})`}); <add> } else { <add> processing.push({code: x.code + " - (Payment accounting for resumption date)", derived: ` ${value} * (${numDaysEmployeeCanWorkInMonth}) / ${totalNumWeekDaysInMonth})`}); <add> } <ide> processing.push({code: x.code, derived: value}); <ide> } <ide> //-- <ide> return weekDates <ide> } <ide> <del>function getPayAmountInForeignCurrency(payTypeDetails, amountInLocalCurrency, currencyRatesForPeriod) { <add>// function getPayAmountInForeignCurrency(payTypeDetails, amountInLocalCurrency, currencyRatesForPeriod) { <add>// let amountInForeignCurrency = null <add> <add>// let currencyRateForPayType = _.find(currencyRatesForPeriod, (aCurrency) => { <add>// return aCurrency.code === payTypeDetails.currency <add>// }) <add>// if(currencyRateForPayType) { <add>// if(!isNaN(currencyRateForPayType.rateToBaseCurrency)) { <add>// amountInForeignCurrency = amountInLocalCurrency * currencyRateForPayType.rateToBaseCurrency <add>// } <add>// } <add>// return amountInForeignCurrency <add>// } <add> <add>function convertForeignCurrencyToBaseCurrency(payTypeDetails, amountInLocalCurrency, currencyRatesForPeriod) { <ide> let amountInForeignCurrency = null <ide> <ide> let currencyRateForPayType = _.find(currencyRatesForPeriod, (aCurrency) => { <ide> } <ide> } <ide> <del>function getFractionForCalcProjectsPayValue(businessId, periodMonth, periodYear, employeeUserId) { <add>function getFractionForCalcProjectsPayValue(businessId, periodMonth, periodYear, totalNumWeekDaysInMonth, employeeUserId) { <ide> const firsDayOfPeriod = `${periodMonth}-01-${periodYear} GMT`; <ide> <ide> const startDate = moment(new Date(firsDayOfPeriod)).startOf('month').toDate(); <ide> } } <ide> ]); <ide> //-- <del> let totalWorkHoursInYear = 2080 <del> let numberOfMonthsInYear = 12 <add> // let totalWorkHoursInYear = 2080 <add> // let numberOfMonthsInYear = 12 <ide> <ide> if(allProjectTimesInMonth) { <ide> if(allProjectTimesInMonth.length > 0) { <del> // console.log(`allProjectTimesInMonth: `, allProjectTimesInMonth) <ide> let projectDurations = [] <ide> <ide> let totalProjectsDuration = 0 <ide> duration: aProjectTime.duration <ide> }) <ide> }) <del> const fraction = totalProjectsDuration * numberOfMonthsInYear / totalWorkHoursInYear <add> // const fraction = totalProjectsDuration * numberOfMonthsInYear / totalWorkHoursInYear <add> const fraction = totalProjectsDuration / (totalNumWeekDaysInMonth * 8) <add> <ide> return {duration: totalProjectsDuration, fraction, projectDurations} <ide> } else { <ide> return {duration: 0, fraction: 0, projectDurations: []} <ide> } <ide> } <ide> <del>function getFractionForCalcCostCentersPayValue(businessId, periodMonth, periodYear, employeeUserId) { <add>function getFractionForCalcCostCentersPayValue(businessId, periodMonth, periodYear, totalNumWeekDaysInMonth, employeeUserId) { <ide> const firsDayOfPeriod = `${periodMonth}-01-${periodYear} GMT`; <ide> <ide> const startDate = moment(new Date(firsDayOfPeriod)).startOf('month').toDate(); <ide> { $group: {_id: "$employeeId", duration: { $sum: "$duration" }}} <ide> ]); <ide> //-- <del> let totalWorkHoursInYear = 2080 <del> let numberOfMonthsInYear = 12 <add> // let totalWorkHoursInYear = 2080 <add> // let numberOfMonthsInYear = 12 <ide> <ide> if(allCostCenterTimesInMonth) { <ide> if(allCostCenterTimesInMonth.length === 1) { <ide> const duration = allCostCenterTimesInMonth[0].duration <del> const fraction = duration * numberOfMonthsInYear / totalWorkHoursInYear <add> // const fraction = duration * numberOfMonthsInYear / totalWorkHoursInYear <add> const fraction = duration / (totalNumWeekDaysInMonth * 8) <add> <ide> return {duration, fraction} <ide> } else { <ide> return {duration: 0, fraction: 0}
JavaScript
mit
6488814d722bfed88cbc1c0f921bf4e23af21640
0
GrapeSalad/scrabble01,GrapeSalad/scrabble01,aglines-epicodus/scrabble01,aglines-epicodus/scrabble01
var initialBag = JSON.parse(bag); // console.log(initialBag); // test dictionary var dictionary = ["cat", "tree", "rain", "wind"]; function Bag() { this.bagTiles = initialBag; }; function Game() { this.board = []; this.currentPlayer = ""; }; function Player(name, rack) { this.name = name; this.score = 0; this.rack = rack; this.partialWord = []; this.currentWord = []; }; function Tile() { this.letter; this.letterValue; }; function Cell(x, y) { this.x = x; this.y = y; this.pointMultiplier = ""; this.occupied = false; this.tile = {}; } function Rack() { this.rackTiles = []; this.needNumber = 7; }; Game.prototype.Turn = function () { // option to pass : var turnType = "" if (turnType === "pass") { // go to next turn; return? } if (turnType === "submit") { // we're given partialWord letters, build completeWord // for now, only check ONE word style, the one they meant to play if (checkHorizontalPosition()) { completeHorizontalWord(this.currentPlayer.partialWord); } if (checkVerticalPosition()) { completeVerticalWord(this.currentPlayer.partialWord); } if ( checkValidWord(this.currentPlayer.completeWord)) { countScore(); } } }; // TURN function Player.prototype.buildWordSection = function (cell) { this.partialWord.push(cell); }; Game.prototype.generateBoard = function () { for (var i = 0; i < 15; i++) { for (var j = 0; j < 15; j++) { var cell = new Cell (i, j) this.board.push(cell); } } }; Game.prototype.completeHorizontalWord = function (partialWord) { var completeWord = []; var horizontal = this.board[partialWord[0].y];// take whole horizontal array from board with y coord var firstX = partialWord[0].x; var lastX = partialWord[partialWord.length-1].x; // TODO: sort (cells) partialWord array // because a user might not drop in a straightforward order for (var i = partialWord[0].x; i <= partialWord[partialWord.length-1].x; i++) { if (typeof horizontal[i].tile != 'undefined') { completeWord.push(horizontal[i]); } else { return false; } } // debugger; // Check the beginning of horiz array to see if empty // also check if we're at the edge of the board while ((firstX-1)>=0 && (typeof horizontal[firstX-1].tile != 'undefined')) { completeWord.unshift(horizontal[firstX-1]); firstX--; } // Check the end of horiz array to see if empty while ((lastX+1<=14)&& (typeof horizontal[lastX+1].tile != 'undefined')) { completeWord.push(horizontal[lastX+1]); lastX++; } return completeWord; }; Game.prototype.completeVerticalWord = function (partialWord) { var completeWord = []; var vertical = this.board[partialWord[0].x]; //take whole vertical array var firstY = partialWord[0].y; var lastY = partialWord[partialWord.length-1].y; // TODO: sort (cells) partialWord array // because a user might not drop in a straightforward order for (var i = partialWord[0].y; i <=partialWord[partialWord.length].y; i++) { if (typeof vertical[i].tile != 'undefined') { completeWord.push(vertical[i]); } else { return false; } } debugger; // Check the beginning of horiz array to see if empty // also check if we're at the edge of the board while ( (firstY-1)>=0 && (typeof vertical[firstY-1].tile != 'undefined')) { completeWord.unshift(vertical[firstY-1]); firstY--; } while ( (lastY+1<=14) && (typeof vertical[lastY+1].tile != 'undefined')) { completeWord.push(horizontal[lastY+1]); lastY++; } return completeWord; }; // assemble "partial" word, player's new tiles // completeWord will be new tiles plus old tiles already on board Player.prototype.buildPartialWord = function (cell) { this.partialWord.push(cell); }; Player.prototype.playerScore = function (wordScore) { return this.score += wordScore; }; Rack.prototype.generateRack = function (needNumber,initialBag) { for (var i = 0; i < needNumber; i++) { var currentRandomInt = getRandomInt(0, initialBag.length-1); this.rackTiles.push(initialBag[currentRandomInt]); initialBag.splice(currentRandomInt, 1); }; } Game.prototype.checkForEndGame = function () { if (true) { } }; Game.prototype.checkVerticalPosition = function () { var checkVertical; for (var i = 0; i < this.currentPlayer.partialWord.length-1; i++) { if ([i].x === [i+1].x) { checkVertical = true; } else { checkVertical = false; } } return checkVertical; }; Game.prototype.checkHorizontalPosition = function () { var checkHorizontal; for (var i = 0; i < this.currentPlayer.partialWord.length-1; i++) { if ([i].y === [i+1].y) { checkHorizontal = true; } else { checkHorizontal = false; } } return checkHorizontal; }; Game.prototype.checkValidWord = function () { var wordString =""; for (var i = 0; i < this.currentPlayer.currentWord.length; i++) { wordString+=this.currentPlayer.currentWord[i].tile.letter; console.log("this.currentPlayer.currentWord[i].tile.letter = ", this.currentPlayer.currentWord[i].tile.letter); } return dictionary.includes(wordString); }; Game.prototype.countScore = function() { var wordScoreMultiplier = 1; var currentWordScore = 0; debugger; for (var i = 0; i < this.currentPlayer.currentWord.length-1; i++) { if (this.currentPlayer.currentWord[i].pointMultiplier === "2L") { currentWordScore += this.currentPlayer.currentWord[i].tile.letterValue * 2 } else if (this.currentPlayer.currentWord[i].pointMultiplier === "3L") { currentWordScore += this.currentPlayer.currentWord[i].tile.letterValue * 3 } else if (this.currentPlayer.currentWord[i].pointMultiplier === "2W") { currentWordScore += this.currentPlayer.currentWord[i].tile.letterValue; var wordScoreMultiplier = 2; } else if (this.currentPlayer.currentWord[i].pointMultiplier === "3W") { currentWordScore += this.currentPlayer.currentWord[i].tile.letterValue; var wordScoreMultiplier = 3; } else { currentWordScore += this.currentPlayer.currentWord[i].tile.letterValue; } }; currentWordScore *= wordScoreMultiplier; return currentWordScore; }; //=========================================================================== $(function () { var scrabbleGame = new Game(); scrabbleGame.generateBoard(); // console.table(scrabbleGame.board); var rack = new Rack(); rack.generateRack(7, initialBag); var player = new Player ("Tom", rack); }); function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min)) + min; }; // }; ////////////////////// USER INTERFACE $(document).ready(function(){ //DRAG AND DROP SQUARES $("div.makeMeDraggable").draggable( { opacity: .4, create: function(){ $(this).data('position',$(this).position()) }, cursorAt: {left:15}, cursor: 'move', start: function(){ $(this).stop(true,true) } }); $('div.row').find('.cell').droppable({ drop:function(event, ui){ snapToMiddle(ui.draggable,$(this)); var inputCellTileString = $(this).droppable(0).attr('id').split('-'); console.log(inputCellTileString); var cellYAxis = inputCellTileString[0]; var cellXAxis = inputCellTileString[1]; var cellScoreVariant = inputCellTileString[2]; console.log("The cell is occupied on the y axis at: " + cellYAxis); console.log("The cell is occupied on the x axis at: " + cellXAxis); console.log("The cell has a score variant of: " + cellScoreVariant); } }); function snapToMiddle(dragger, target){ var offset = target.offset(); var topMove = (target.outerHeight(true) - dragger.outerHeight(true)) / 2; var leftMove= (target.outerWidth(true) - dragger.outerWidth(true)) / 2; dragger.offset({ top: topMove + offset.top, left: leftMove + offset.left }); }; //TILE BAG USER INTERFACE $(".clickable img").click(function(){ // var playerRack = newRack.generateRack(7, initialBag); // console.log(generatePlayerRack); }); //PLAYER BUTTON INPUT $("button#score").click(function(){ console.log("SCORE!"); }); $("button#reset").click(function(){ console.log("RESET"); }); $("button#pass").click(function(){ var turnType = "pass"; console.log("PASS"); }); });
js/scripts.js
var initialBag = JSON.parse(bag); // console.log(initialBag); // test dictionary var dictionary = ["cat", "tree", "rain", "wind"]; function Bag() { this.bagTiles = initialBag; }; function Game() { this.board = []; this.currentPlayer = ""; }; function Player(name, rack) { this.name = name; this.score = 0; this.rack = rack; this.partialWord = []; this.currentWord = []; }; function Tile() { this.letter; this.letterValue; }; function Cell(x, y) { this.x = x; this.y = y; this.pointMultiplier = ""; this.occupied = false; this.tile = {}; } function Rack() { this.rackTiles = []; this.needNumber = 7; }; Game.prototype.Turn = function () { // option to pass : var turnType = "" if (turnType === "pass") { // go to next turn; return? } if (turnType === "submit") { // we're given partialWord letters, build completeWord // for now, only check ONE word style, the one they meant to play if (checkHorizontalPosition()) { completeHorizontalWord(this.currentPlayer.partialWord); } if (checkVerticalPosition()) { completeVerticalWord(this.currentPlayer.partialWord); } if ( checkValidWord(this.currentPlayer.completeWord) } }; // TURN function Player.prototype.buildWordSection = function (cell) { this.partialWord.push(cell); }; Game.prototype.generateBoard = function () { for (var i = 0; i < 15; i++) { for (var j = 0; j < 15; j++) { var cell = new Cell (i, j) this.board.push(cell); } } }; Game.prototype.completeHorizontalWord = function (partialWord) { var completeWord = []; var horizontal = this.board[partialWord[0].y];// take whole horizontal array from board with y coord var firstX = partialWord[0].x; var lastX = partialWord[partialWord.length-1].x; // TODO: sort (cells) partialWord array // because a user might not drop in a straightforward order for (var i = partialWord[0].x; i <= partialWord[partialWord.length-1].x; i++) { if (typeof horizontal[i].tile != 'undefined') { completeWord.push(horizontal[i]); } else { return false; } } // debugger; // Check the beginning of horiz array to see if empty // also check if we're at the edge of the board while ((firstX-1)>=0 && (typeof horizontal[firstX-1].tile != 'undefined')) { completeWord.unshift(horizontal[firstX-1]); firstX--; } // Check the end of horiz array to see if empty while ((lastX+1<=14)&& (typeof horizontal[lastX+1].tile != 'undefined')) { completeWord.push(horizontal[lastX+1]); lastX++; } return completeWord; }; Game.prototype.completeVerticalWord = function (partialWord) { var completeWord = []; var vertical = this.board[partialWord[0].x]; //take whole vertical array var firstY = partialWord[0].y; var lastY = partialWord[partialWord.length-1].y; // TODO: sort (cells) partialWord array // because a user might not drop in a straightforward order for (var i = partialWord[0].y; i <=partialWord[partialWord.length].y; i++) { if (typeof vertical[i].tile != 'undefined') { completeWord.push(vertical[i]); } else { return false; } } debugger; // Check the beginning of horiz array to see if empty // also check if we're at the edge of the board while ( (firstY-1)>=0 && (typeof vertical[firstY-1].tile != 'undefined')) { completeWord.unshift(vertical[firstY-1]); firstY--; } while ( (lastY+1<=14) && (typeof vertical[lastY+1].tile != 'undefined')) { completeWord.push(horizontal[lastY+1]); lastY++; } return completeWord; }; // assemble "partial" word, player's new tiles // completeWord will be new tiles plus old tiles already on board Player.prototype.buildPartialWord = function (cell) { this.partialWord.push(cell); }; Player.prototype.playerScore = function (wordScore) { return this.score += wordScore; }; Rack.prototype.generateRack = function (needNumber,initialBag) { for (var i = 0; i < needNumber; i++) { var currentRandomInt = getRandomInt(0, initialBag.length-1); this.rackTiles.push(initialBag[currentRandomInt]); initialBag.splice(currentRandomInt, 1); }; } Game.prototype.checkForEndGame = function () { // game ends when conditions met: // 1. initialBag is empty // 2. one player's rack is empty // for (var i = 1; i <= numberOfPlayers.length; i+1) { // // check player rack to see if empty // } // if ( initialBag === []) && // // } }; Game.prototype.checkVerticalPosition = function () { var checkVertical; <<<<<<< HEAD for (var i = 0; i < this.currentPlayer.partialWord.length-1; i++) { ======= for (var i = 0; i < partialWord.length-1; i++) { >>>>>>> 83406f9cc6bc949bfcf78ad57c461ac4c4d41935 if ([i].x === [i+1].x) { checkVertical = true; } else { checkVertical = false; } } return checkVertical; }; Game.prototype.checkHorizontalPosition = function () { var checkHorizontal; <<<<<<< HEAD for (var i = 0; i < this.currentPlayer.partialWord.length-1; i++) { ======= for (var i = 0; i < partialWord.length-1; i++) { >>>>>>> 83406f9cc6bc949bfcf78ad57c461ac4c4d41935 if ([i].y === [i+1].y) { checkHorizontal = true; } else { checkHorizontal = false; } } return checkHorizontal; }; Game.prototype.checkValidWord = function () { var wordString =""; for (var i = 0; i < this.currentPlayer.currentWord.length; i++) { wordString+=this.currentPlayer.currentWord[i].tile.letter; console.log("this.currentPlayer.currentWord[i].tile.letter = "this.currentPlayer.currentWord[i].tile.letter); } return dictionary.includes(wordString); }; Game.prototype.countScore = function() { var wordScoreMultiplier = 1; var currentWordScore = 0; debugger; for (var i = 0; i < this.currentPlayer.currentWord.length-1; i++) { if (this.currentPlayer.currentWord[i].pointMultiplier === "2L") { currentWordScore += this.currentPlayer.currentWord[i].tile.letterValue * 2 } else if (this.currentPlayer.currentWord[i].pointMultiplier === "3L") { currentWordScore += this.currentPlayer.currentWord[i].tile.letterValue * 3 } else if (this.currentPlayer.currentWord[i].pointMultiplier === "2W") { currentWordScore += this.currentPlayer.currentWord[i].tile.letterValue; var wordScoreMultiplier = 2; } else if (this.currentPlayer.currentWord[i].pointMultiplier === "3W") { currentWordScore += this.currentPlayer.currentWord[i].tile.letterValue; var wordScoreMultiplier = 3; } else { currentWordScore += this.currentPlayer.currentWord[i].tile.letterValue; } }; currentWordScore *= wordScoreMultiplier; return currentWordScore; }; //=========================================================================== $(function () { var scrabbleGame = new Game(); scrabbleGame.generateBoard(); // console.table(scrabbleGame.board); var rack = new Rack(); rack.generateRack(7, initialBag); var player = new Player ("Tom", rack); }); function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min)) + min; }; // }; ////////////////////// USER INTERFACE $(document).ready(function(){ //DRAG AND DROP SQUARES $("div.makeMeDraggable").draggable( { opacity: .4, create: function(){ $(this).data('position',$(this).position()) }, cursorAt: {left:15}, cursor: 'move', start: function(){ $(this).stop(true,true) } }); $('div.row').find('.cell').droppable({ drop:function(event, ui){ snapToMiddle(ui.draggable,$(this)); var inputCellTileString = $(this).droppable(0).attr('id').split('-'); console.log(inputCellTileString); var cellYAxis = inputCellTileString[0]; var cellXAxis = inputCellTileString[1]; var cellScoreVariant = inputCellTileString[2]; console.log("The cell is occupied on the y axis at: " + cellYAxis); console.log("The cell is occupied on the x axis at: " + cellXAxis); console.log("The cell has a score variant of: " + cellScoreVariant); } }); function snapToMiddle(dragger, target){ var offset = target.offset(); var topMove = (target.outerHeight(true) - dragger.outerHeight(true)) / 2; var leftMove= (target.outerWidth(true) - dragger.outerWidth(true)) / 2; dragger.offset({ top: topMove + offset.top, left: leftMove + offset.left }); }; //TILE BAG USER INTERFACE $(".clickable img").click(function(){ // var playerRack = newRack.generateRack(7, initialBag); // console.log(generatePlayerRack); }); //PLAYER BUTTON INPUT $("button#score").click(function(){ console.log("SCORE!"); }); $("button#reset").click(function(){ console.log("RESET"); }); $("button#pass").click(function(){ console.log("PASS"); }); });
add line to resolve conflict
js/scripts.js
add line to resolve conflict
<ide><path>s/scripts.js <ide> if (checkVerticalPosition()) { <ide> completeVerticalWord(this.currentPlayer.partialWord); <ide> } <del> if ( checkValidWord(this.currentPlayer.completeWord) <add> if ( checkValidWord(this.currentPlayer.completeWord)) { <add> countScore(); <add> } <ide> } <ide> }; // TURN function <ide> <ide> } <ide> <ide> Game.prototype.checkForEndGame = function () { <del> // game ends when conditions met: <del> // 1. initialBag is empty <del> // 2. one player's rack is empty <del> // for (var i = 1; i <= numberOfPlayers.length; i+1) { <del> // // check player rack to see if empty <del> // } <del> // if ( initialBag === []) && <del> // <del> // } <add> if (true) { <add> <add> } <ide> }; <ide> <ide> <ide> Game.prototype.checkVerticalPosition = function () { <ide> var checkVertical; <del><<<<<<< HEAD <ide> for (var i = 0; i < this.currentPlayer.partialWord.length-1; i++) { <del>======= <del> for (var i = 0; i < partialWord.length-1; i++) { <del>>>>>>>> 83406f9cc6bc949bfcf78ad57c461ac4c4d41935 <add> <ide> if ([i].x === [i+1].x) { <ide> checkVertical = true; <ide> } else { <ide> <ide> Game.prototype.checkHorizontalPosition = function () { <ide> var checkHorizontal; <del><<<<<<< HEAD <add> <ide> for (var i = 0; i < this.currentPlayer.partialWord.length-1; i++) { <del>======= <del> for (var i = 0; i < partialWord.length-1; i++) { <del>>>>>>>> 83406f9cc6bc949bfcf78ad57c461ac4c4d41935 <add> <ide> if ([i].y === [i+1].y) { <ide> checkHorizontal = true; <ide> } else { <ide> <ide> for (var i = 0; i < this.currentPlayer.currentWord.length; i++) { <ide> wordString+=this.currentPlayer.currentWord[i].tile.letter; <del> console.log("this.currentPlayer.currentWord[i].tile.letter = "this.currentPlayer.currentWord[i].tile.letter); <add> console.log("this.currentPlayer.currentWord[i].tile.letter = ", this.currentPlayer.currentWord[i].tile.letter); <ide> <ide> } <ide> return dictionary.includes(wordString); <ide> debugger; <ide> <ide> for (var i = 0; i < this.currentPlayer.currentWord.length-1; i++) { <del> <del> <ide> <ide> if (this.currentPlayer.currentWord[i].pointMultiplier === "2L") { <ide> currentWordScore += this.currentPlayer.currentWord[i].tile.letterValue * 2 <ide> rack.generateRack(7, initialBag); <ide> var player = new Player ("Tom", rack); <ide> <del> <ide> }); <ide> <ide> function getRandomInt(min, max) { <ide> max = Math.floor(max); <ide> return Math.floor(Math.random() * (max - min)) + min; <ide> }; <del> <ide> <ide> <ide> // }; <ide> }); <ide> <ide> $("button#pass").click(function(){ <add> var turnType = "pass"; <ide> console.log("PASS"); <ide> }); <ide> });
JavaScript
mit
1cc6a0f8141b7dd860b03e29fcfe4e5585da8257
0
dschalk/monads-for-functional-javascript,dschalk/monads-for-functional-javascript,dschalk/JS-monads-stable,dschalk/JS-monads-stable
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { throw err; }; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 102); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports) { "use strict"; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ module.exports = Stream; function Stream(source) { this.source = source; } /***/ }, /* 1 */ /***/ function(module, exports) { "use strict"; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ module.exports = Pipe; /** * A sink mixin that simply forwards event, end, and error to * another sink. * @param sink * @constructor */ function Pipe(sink) { this.sink = sink; } Pipe.prototype.event = function (t, x) { return this.sink.event(t, x); }; Pipe.prototype.end = function (t, x) { return this.sink.end(t, x); }; Pipe.prototype.error = function (t, e) { return this.sink.error(t, e); }; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Disposable = __webpack_require__(72); var SettableDisposable = __webpack_require__(73); var isPromise = __webpack_require__(11).isPromise; var base = __webpack_require__(3); var map = base.map; var identity = base.id; exports.tryDispose = tryDispose; exports.create = create; exports.once = once; exports.empty = empty; exports.all = all; exports.settable = settable; exports.promised = promised; /** * Call disposable.dispose. If it returns a promise, catch promise * error and forward it through the provided sink. * @param {number} t time * @param {{dispose: function}} disposable * @param {{error: function}} sink * @return {*} result of disposable.dispose */ function tryDispose(t, disposable, sink) { var result = disposeSafely(disposable); return isPromise(result) ? result.catch(function (e) { sink.error(t, e); }) : result; } /** * Create a new Disposable which will dispose its underlying resource * at most once. * @param {function} dispose function * @param {*?} data any data to be passed to disposer function * @return {Disposable} */ function create(dispose, data) { return once(new Disposable(dispose, data)); } /** * Create a noop disposable. Can be used to satisfy a Disposable * requirement when no actual resource needs to be disposed. * @return {Disposable|exports|module.exports} */ function empty() { return new Disposable(identity, void 0); } /** * Create a disposable that will dispose all input disposables in parallel. * @param {Array<Disposable>} disposables * @return {Disposable} */ function all(disposables) { return create(disposeAll, disposables); } function disposeAll(disposables) { return Promise.all(map(disposeSafely, disposables)); } function disposeSafely(disposable) { try { return disposable.dispose(); } catch (e) { return Promise.reject(e); } } /** * Create a disposable from a promise for another disposable * @param {Promise<Disposable>} disposablePromise * @return {Disposable} */ function promised(disposablePromise) { return create(disposePromise, disposablePromise); } function disposePromise(disposablePromise) { return disposablePromise.then(disposeOne); } function disposeOne(disposable) { return disposable.dispose(); } /** * Create a disposable proxy that allows its underlying disposable to * be set later. * @return {SettableDisposable} */ function settable() { return new SettableDisposable(); } /** * Wrap an existing disposable (which may not already have been once()d) * so that it will only dispose its underlying resource at most once. * @param {{ dispose: function() }} disposable * @return {Disposable} wrapped disposable */ function once(disposable) { return new Disposable(disposeMemoized, memoized(disposable)); } function disposeMemoized(memoized) { if (!memoized.disposed) { memoized.disposed = true; memoized.value = disposeSafely(memoized.disposable); memoized.disposable = void 0; } return memoized.value; } function memoized(disposable) { return { disposed: false, disposable: disposable, value: void 0 }; } /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;'use strict'; (function (global, factory) { if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [exports], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (typeof exports !== "undefined") { factory(exports); } else { var mod = { exports: {} }; factory(mod.exports); global.mostPrelude = mod.exports; } })(undefined, function (exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); /** @license MIT License (c) copyright 2010-2016 original author or authors */ // Non-mutating array operations // cons :: a -> [a] -> [a] // a with x prepended function cons(x, a) { var l = a.length; var b = new Array(l + 1); b[0] = x; for (var i = 0; i < l; ++i) { b[i + 1] = a[i]; } return b; } // append :: a -> [a] -> [a] // a with x appended function append(x, a) { var l = a.length; var b = new Array(l + 1); for (var i = 0; i < l; ++i) { b[i] = a[i]; } b[l] = x; return b; } // drop :: Int -> [a] -> [a] // drop first n elements function drop(n, a) { // eslint-disable-line complexity if (n < 0) { throw new TypeError('n must be >= 0'); } var l = a.length; if (n === 0 || l === 0) { return a; } if (n >= l) { return []; } return unsafeDrop(n, a, l - n); } // unsafeDrop :: Int -> [a] -> Int -> [a] // Internal helper for drop function unsafeDrop(n, a, l) { var b = new Array(l); for (var i = 0; i < l; ++i) { b[i] = a[n + i]; } return b; } // tail :: [a] -> [a] // drop head element function tail(a) { return drop(1, a); } // copy :: [a] -> [a] // duplicate a (shallow duplication) function copy(a) { var l = a.length; var b = new Array(l); for (var i = 0; i < l; ++i) { b[i] = a[i]; } return b; } // map :: (a -> b) -> [a] -> [b] // transform each element with f function map(f, a) { var l = a.length; var b = new Array(l); for (var i = 0; i < l; ++i) { b[i] = f(a[i]); } return b; } // reduce :: (a -> b -> a) -> a -> [b] -> a // accumulate via left-fold function reduce(f, z, a) { var r = z; for (var i = 0, l = a.length; i < l; ++i) { r = f(r, a[i], i); } return r; } // replace :: a -> Int -> [a] // replace element at index function replace(x, i, a) { // eslint-disable-line complexity if (i < 0) { throw new TypeError('i must be >= 0'); } var l = a.length; var b = new Array(l); for (var j = 0; j < l; ++j) { b[j] = i === j ? x : a[j]; } return b; } // remove :: Int -> [a] -> [a] // remove element at index function remove(i, a) { // eslint-disable-line complexity if (i < 0) { throw new TypeError('i must be >= 0'); } var l = a.length; if (l === 0 || i >= l) { // exit early if index beyond end of array return a; } if (l === 1) { // exit early if index in bounds and length === 1 return []; } return unsafeRemove(i, a, l - 1); } // unsafeRemove :: Int -> [a] -> Int -> [a] // Internal helper to remove element at index function unsafeRemove(i, a, l) { var b = new Array(l); var j = void 0; for (j = 0; j < i; ++j) { b[j] = a[j]; } for (j = i; j < l; ++j) { b[j] = a[j + 1]; } return b; } // removeAll :: (a -> boolean) -> [a] -> [a] // remove all elements matching a predicate function removeAll(f, a) { var l = a.length; var b = new Array(l); var j = 0; for (var x, i = 0; i < l; ++i) { x = a[i]; if (!f(x)) { b[j] = x; ++j; } } b.length = j; return b; } // findIndex :: a -> [a] -> Int // find index of x in a, from the left function findIndex(x, a) { for (var i = 0, l = a.length; i < l; ++i) { if (x === a[i]) { return i; } } return -1; } // isArrayLike :: * -> boolean // Return true iff x is array-like function isArrayLike(x) { return x != null && typeof x.length === 'number' && typeof x !== 'function'; } /** @license MIT License (c) copyright 2010-2016 original author or authors */ // id :: a -> a var id = function id(x) { return x; }; // compose :: (b -> c) -> (a -> b) -> (a -> c) var compose = function compose(f, g) { return function (x) { return f(g(x)); }; }; // apply :: (a -> b) -> a -> b var apply = function apply(f, x) { return f(x); }; // curry2 :: ((a, b) -> c) -> (a -> b -> c) function curry2(f) { function curried(a, b) { switch (arguments.length) { case 0: return curried; case 1: return function (b) { return f(a, b); }; default: return f(a, b); } } return curried; } // curry3 :: ((a, b, c) -> d) -> (a -> b -> c -> d) function curry3(f) { function curried(a, b, c) { // eslint-disable-line complexity switch (arguments.length) { case 0: return curried; case 1: return curry2(function (b, c) { return f(a, b, c); }); case 2: return function (c) { return f(a, b, c); }; default: return f(a, b, c); } } return curried; } exports.cons = cons; exports.append = append; exports.drop = drop; exports.tail = tail; exports.copy = copy; exports.map = map; exports.reduce = reduce; exports.replace = replace; exports.remove = remove; exports.removeAll = removeAll; exports.findIndex = findIndex; exports.isArrayLike = isArrayLike; exports.id = id; exports.compose = compose; exports.apply = apply; exports.curry2 = curry2; exports.curry3 = curry3; }); /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var base = __webpack_require__(3); var core = __webpack_require__(7); var from = __webpack_require__(84).from; var periodic = __webpack_require__(90).periodic; /** * Core stream type * @type {Stream} */ exports.Stream = Stream; // Add of and empty to constructor for fantasy-land compat exports.of = Stream.of = core.of; exports.just = core.of; // easier ES6 import alias exports.empty = Stream.empty = core.empty; exports.never = core.never; exports.from = from; exports.periodic = periodic; //----------------------------------------------------------------------- // Creating var create = __webpack_require__(83); /** * Create a stream by imperatively pushing events. * @param {function(add:function(x), end:function(e)):function} run function * that will receive 2 functions as arguments, the first to add new values to the * stream and the second to end the stream. It may *return* a function that * will be called once all consumers have stopped observing the stream. * @returns {Stream} stream containing all events added by run before end */ exports.create = create.create; //----------------------------------------------------------------------- // Adapting other sources var events = __webpack_require__(86); /** * Create a stream of events from the supplied EventTarget or EventEmitter * @param {String} event event name * @param {EventTarget|EventEmitter} source EventTarget or EventEmitter. The source * must support either addEventListener/removeEventListener (w3c EventTarget: * http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget), * or addListener/removeListener (node EventEmitter: http://nodejs.org/api/events.html) * @returns {Stream} stream of events of the specified type from the source */ exports.fromEvent = events.fromEvent; //----------------------------------------------------------------------- // Observing var observe = __webpack_require__(63); exports.observe = observe.observe; exports.forEach = observe.observe; exports.drain = observe.drain; /** * Process all the events in the stream * @returns {Promise} promise that fulfills when the stream ends, or rejects * if the stream fails with an unhandled error. */ Stream.prototype.observe = Stream.prototype.forEach = function (f) { return observe.observe(f, this); }; /** * Consume all events in the stream, without providing a function to process each. * This causes a stream to become active and begin emitting events, and is useful * in cases where all processing has been setup upstream via other combinators, and * there is no need to process the terminal events. * @returns {Promise} promise that fulfills when the stream ends, or rejects * if the stream fails with an unhandled error. */ Stream.prototype.drain = function () { return observe.drain(this); }; //------------------------------------------------------- var loop = __webpack_require__(61).loop; exports.loop = loop; /** * Generalized feedback loop. Call a stepper function for each event. The stepper * will be called with 2 params: the current seed and the an event value. It must * return a new { seed, value } pair. The `seed` will be fed back into the next * invocation of stepper, and the `value` will be propagated as the event value. * @param {function(seed:*, value:*):{seed:*, value:*}} stepper loop step function * @param {*} seed initial seed value passed to first stepper call * @returns {Stream} new stream whose values are the `value` field of the objects * returned by the stepper */ Stream.prototype.loop = function (stepper, seed) { return loop(stepper, seed, this); }; //------------------------------------------------------- var accumulate = __webpack_require__(54); exports.scan = accumulate.scan; exports.reduce = accumulate.reduce; /** * Create a stream containing successive reduce results of applying f to * the previous reduce result and the current stream item. * @param {function(result:*, x:*):*} f reducer function * @param {*} initial initial value * @returns {Stream} new stream containing successive reduce results */ Stream.prototype.scan = function (f, initial) { return accumulate.scan(f, initial, this); }; /** * Reduce the stream to produce a single result. Note that reducing an infinite * stream will return a Promise that never fulfills, but that may reject if an error * occurs. * @param {function(result:*, x:*):*} f reducer function * @param {*} initial optional initial value * @returns {Promise} promise for the file result of the reduce */ Stream.prototype.reduce = function (f, initial) { return accumulate.reduce(f, initial, this); }; //----------------------------------------------------------------------- // Building and extending var unfold = __webpack_require__(91); var iterate = __webpack_require__(89); var generate = __webpack_require__(88); var build = __webpack_require__(23); exports.unfold = unfold.unfold; exports.iterate = iterate.iterate; exports.generate = generate.generate; exports.cycle = build.cycle; exports.concat = build.concat; exports.startWith = build.cons; /** * @deprecated * Tie this stream into a circle, thus creating an infinite stream * @returns {Stream} new infinite stream */ Stream.prototype.cycle = function () { return build.cycle(this); }; /** * @param {Stream} tail * @returns {Stream} new stream containing all items in this followed by * all items in tail */ Stream.prototype.concat = function (tail) { return build.concat(this, tail); }; /** * @param {*} x value to prepend * @returns {Stream} a new stream with x prepended */ Stream.prototype.startWith = function (x) { return build.cons(x, this); }; //----------------------------------------------------------------------- // Transforming var transform = __webpack_require__(12); var applicative = __webpack_require__(55); exports.map = transform.map; exports.constant = transform.constant; exports.tap = transform.tap; exports.ap = applicative.ap; /** * Transform each value in the stream by applying f to each * @param {function(*):*} f mapping function * @returns {Stream} stream containing items transformed by f */ Stream.prototype.map = function (f) { return transform.map(f, this); }; /** * Assume this stream contains functions, and apply each function to each item * in the provided stream. This generates, in effect, a cross product. * @param {Stream} xs stream of items to which * @returns {Stream} stream containing the cross product of items */ Stream.prototype.ap = function (xs) { return applicative.ap(this, xs); }; /** * Replace each value in the stream with x * @param {*} x * @returns {Stream} stream containing items replaced with x */ Stream.prototype.constant = function (x) { return transform.constant(x, this); }; /** * Perform a side effect for each item in the stream * @param {function(x:*):*} f side effect to execute for each item. The * return value will be discarded. * @returns {Stream} new stream containing the same items as this stream */ Stream.prototype.tap = function (f) { return transform.tap(f, this); }; //----------------------------------------------------------------------- // Transducer support var transduce = __webpack_require__(70); exports.transduce = transduce.transduce; /** * Transform this stream by passing its events through a transducer. * @param {function} transducer transducer function * @return {Stream} stream of events transformed by the transducer */ Stream.prototype.transduce = function (transducer) { return transduce.transduce(transducer, this); }; //----------------------------------------------------------------------- // FlatMapping var flatMap = __webpack_require__(26); exports.flatMap = exports.chain = flatMap.flatMap; exports.join = flatMap.join; /** * Map each value in the stream to a new stream, and merge it into the * returned outer stream. Event arrival times are preserved. * @param {function(x:*):Stream} f chaining function, must return a Stream * @returns {Stream} new stream containing all events from each stream returned by f */ Stream.prototype.flatMap = Stream.prototype.chain = function (f) { return flatMap.flatMap(f, this); }; /** * Monadic join. Flatten a Stream<Stream<X>> to Stream<X> by merging inner * streams to the outer. Event arrival times are preserved. * @returns {Stream<X>} new stream containing all events of all inner streams */ Stream.prototype.join = function () { return flatMap.join(this); }; var continueWith = __webpack_require__(25).continueWith; exports.continueWith = continueWith; exports.flatMapEnd = continueWith; /** * Map the end event to a new stream, and begin emitting its values. * @param {function(x:*):Stream} f function that receives the end event value, * and *must* return a new Stream to continue with. * @returns {Stream} new stream that emits all events from the original stream, * followed by all events from the stream returned by f. */ Stream.prototype.continueWith = Stream.prototype.flatMapEnd = function (f) { return continueWith(f, this); }; var concatMap = __webpack_require__(56).concatMap; exports.concatMap = concatMap; Stream.prototype.concatMap = function (f) { return concatMap(f, this); }; //----------------------------------------------------------------------- // Concurrent merging var mergeConcurrently = __webpack_require__(8); exports.mergeConcurrently = mergeConcurrently.mergeConcurrently; /** * Flatten a Stream<Stream<X>> to Stream<X> by merging inner * streams to the outer, limiting the number of inner streams that may * be active concurrently. * @param {number} concurrency at most this many inner streams will be * allowed to be active concurrently. * @return {Stream<X>} new stream containing all events of all inner * streams, with limited concurrency. */ Stream.prototype.mergeConcurrently = function (concurrency) { return mergeConcurrently.mergeConcurrently(concurrency, this); }; //----------------------------------------------------------------------- // Merging var merge = __webpack_require__(62); exports.merge = merge.merge; exports.mergeArray = merge.mergeArray; /** * Merge this stream and all the provided streams * @returns {Stream} stream containing items from this stream and s in time * order. If two events are simultaneous they will be merged in * arbitrary order. */ Stream.prototype.merge = function () /*...streams*/{ return merge.mergeArray(base.cons(this, arguments)); }; //----------------------------------------------------------------------- // Combining var combine = __webpack_require__(24); exports.combine = combine.combine; exports.combineArray = combine.combineArray; /** * Combine latest events from all input streams * @param {function(...events):*} f function to combine most recent events * @returns {Stream} stream containing the result of applying f to the most recent * event of each input stream, whenever a new event arrives on any stream. */ Stream.prototype.combine = function (f /*, ...streams*/) { return combine.combineArray(f, base.replace(this, 0, arguments)); }; //----------------------------------------------------------------------- // Sampling var sample = __webpack_require__(65); exports.sample = sample.sample; exports.sampleWith = sample.sampleWith; /** * When an event arrives on sampler, emit the latest event value from stream. * @param {Stream} sampler stream of events at whose arrival time * signal's latest value will be propagated * @returns {Stream} sampled stream of values */ Stream.prototype.sampleWith = function (sampler) { return sample.sampleWith(sampler, this); }; /** * When an event arrives on this stream, emit the result of calling f with the latest * values of all streams being sampled * @param {function(...values):*} f function to apply to each set of sampled values * @returns {Stream} stream of sampled and transformed values */ Stream.prototype.sample = function (f /* ...streams */) { return sample.sampleArray(f, this, base.tail(arguments)); }; //----------------------------------------------------------------------- // Zipping var zip = __webpack_require__(71); exports.zip = zip.zip; /** * Pair-wise combine items with those in s. Given 2 streams: * [1,2,3] zipWith f [4,5,6] -> [f(1,4),f(2,5),f(3,6)] * Note: zip causes fast streams to buffer and wait for slow streams. * @param {function(a:Stream, b:Stream, ...):*} f function to combine items * @returns {Stream} new stream containing pairs */ Stream.prototype.zip = function (f /*, ...streams*/) { return zip.zipArray(f, base.replace(this, 0, arguments)); }; //----------------------------------------------------------------------- // Switching var switchLatest = __webpack_require__(67).switch; exports.switch = switchLatest; exports.switchLatest = switchLatest; /** * Given a stream of streams, return a new stream that adopts the behavior * of the most recent inner stream. * @returns {Stream} switching stream */ Stream.prototype.switch = Stream.prototype.switchLatest = function () { return switchLatest(this); }; //----------------------------------------------------------------------- // Filtering var filter = __webpack_require__(59); exports.filter = filter.filter; exports.skipRepeats = exports.distinct = filter.skipRepeats; exports.skipRepeatsWith = exports.distinctBy = filter.skipRepeatsWith; /** * Retain only items matching a predicate * stream: -12345678- * filter(x => x % 2 === 0, stream): --2-4-6-8- * @param {function(x:*):boolean} p filtering predicate called for each item * @returns {Stream} stream containing only items for which predicate returns truthy */ Stream.prototype.filter = function (p) { return filter.filter(p, this); }; /** * Skip repeated events, using === to compare items * stream: -abbcd- * distinct(stream): -ab-cd- * @returns {Stream} stream with no repeated events */ Stream.prototype.skipRepeats = function () { return filter.skipRepeats(this); }; /** * Skip repeated events, using supplied equals function to compare items * @param {function(a:*, b:*):boolean} equals function to compare items * @returns {Stream} stream with no repeated events */ Stream.prototype.skipRepeatsWith = function (equals) { return filter.skipRepeatsWith(equals, this); }; //----------------------------------------------------------------------- // Slicing var slice = __webpack_require__(66); exports.take = slice.take; exports.skip = slice.skip; exports.slice = slice.slice; exports.takeWhile = slice.takeWhile; exports.skipWhile = slice.skipWhile; /** * stream: -abcd- * take(2, stream): -ab| * @param {Number} n take up to this many events * @returns {Stream} stream containing at most the first n items from this stream */ Stream.prototype.take = function (n) { return slice.take(n, this); }; /** * stream: -abcd-> * skip(2, stream): ---cd-> * @param {Number} n skip this many events * @returns {Stream} stream not containing the first n events */ Stream.prototype.skip = function (n) { return slice.skip(n, this); }; /** * Slice a stream by event index. Equivalent to, but more efficient than * stream.take(end).skip(start); * NOTE: Negative start and end are not supported * @param {Number} start skip all events before the start index * @param {Number} end allow all events from the start index to the end index * @returns {Stream} stream containing items where start <= index < end */ Stream.prototype.slice = function (start, end) { return slice.slice(start, end, this); }; /** * stream: -123451234-> * takeWhile(x => x < 5, stream): -1234| * @param {function(x:*):boolean} p predicate * @returns {Stream} stream containing items up to, but not including, the * first item for which p returns falsy. */ Stream.prototype.takeWhile = function (p) { return slice.takeWhile(p, this); }; /** * stream: -123451234-> * skipWhile(x => x < 5, stream): -----51234-> * @param {function(x:*):boolean} p predicate * @returns {Stream} stream containing items following *and including* the * first item for which p returns falsy. */ Stream.prototype.skipWhile = function (p) { return slice.skipWhile(p, this); }; //----------------------------------------------------------------------- // Time slicing var timeslice = __webpack_require__(68); exports.until = exports.takeUntil = timeslice.takeUntil; exports.since = exports.skipUntil = timeslice.skipUntil; exports.during = timeslice.during; /** * stream: -a-b-c-d-e-f-g-> * signal: -------x * takeUntil(signal, stream): -a-b-c-| * @param {Stream} signal retain only events in stream before the first * event in signal * @returns {Stream} new stream containing only events that occur before * the first event in signal. */ Stream.prototype.until = Stream.prototype.takeUntil = function (signal) { return timeslice.takeUntil(signal, this); }; /** * stream: -a-b-c-d-e-f-g-> * signal: -------x * takeUntil(signal, stream): -------d-e-f-g-> * @param {Stream} signal retain only events in stream at or after the first * event in signal * @returns {Stream} new stream containing only events that occur after * the first event in signal. */ Stream.prototype.since = Stream.prototype.skipUntil = function (signal) { return timeslice.skipUntil(signal, this); }; /** * stream: -a-b-c-d-e-f-g-> * timeWindow: -----s * s: -----t * stream.during(timeWindow): -----c-d-e-| * @param {Stream<Stream>} timeWindow a stream whose first event (s) represents * the window start time. That event (s) is itself a stream whose first event (t) * represents the window end time * @returns {Stream} new stream containing only events within the provided timespan */ Stream.prototype.during = function (timeWindow) { return timeslice.during(timeWindow, this); }; //----------------------------------------------------------------------- // Delaying var delay = __webpack_require__(57).delay; exports.delay = delay; /** * @param {Number} delayTime milliseconds to delay each item * @returns {Stream} new stream containing the same items, but delayed by ms */ Stream.prototype.delay = function (delayTime) { return delay(delayTime, this); }; //----------------------------------------------------------------------- // Getting event timestamp var timestamp = __webpack_require__(69).timestamp; exports.timestamp = timestamp; /** * Expose event timestamps into the stream. Turns a Stream<X> into * Stream<{time:t, value:X}> * @returns {Stream<{time:number, value:*}>} */ Stream.prototype.timestamp = function () { return timestamp(this); }; //----------------------------------------------------------------------- // Rate limiting var limit = __webpack_require__(60); exports.throttle = limit.throttle; exports.debounce = limit.debounce; /** * Limit the rate of events * stream: abcd----abcd---- * throttle(2, stream): a-c-----a-c----- * @param {Number} period time to suppress events * @returns {Stream} new stream that skips events for throttle period */ Stream.prototype.throttle = function (period) { return limit.throttle(period, this); }; /** * Wait for a burst of events to subside and emit only the last event in the burst * stream: abcd----abcd---- * debounce(2, stream): -----d-------d-- * @param {Number} period events occuring more frequently than this * on the provided scheduler will be suppressed * @returns {Stream} new debounced stream */ Stream.prototype.debounce = function (period) { return limit.debounce(period, this); }; //----------------------------------------------------------------------- // Awaiting Promises var promises = __webpack_require__(64); exports.fromPromise = promises.fromPromise; exports.await = promises.awaitPromises; /** * Await promises, turning a Stream<Promise<X>> into Stream<X>. Preserves * event order, but timeshifts events based on promise resolution time. * @returns {Stream<X>} stream containing non-promise values */ Stream.prototype.await = function () { return promises.awaitPromises(this); }; //----------------------------------------------------------------------- // Error handling var errors = __webpack_require__(58); exports.recoverWith = errors.flatMapError; exports.flatMapError = errors.flatMapError; exports.throwError = errors.throwError; /** * If this stream encounters an error, recover and continue with items from stream * returned by f. * stream: -a-b-c-X- * f(X): d-e-f-g- * flatMapError(f, stream): -a-b-c-d-e-f-g- * @param {function(error:*):Stream} f function which returns a new stream * @returns {Stream} new stream which will recover from an error by calling f */ Stream.prototype.recoverWith = Stream.prototype.flatMapError = function (f) { return errors.flatMapError(f, this); }; //----------------------------------------------------------------------- // Multicasting var multicast = __webpack_require__(5).default; exports.multicast = multicast; /** * Transform the stream into multicast stream. That means that many subscribers * to the stream will not cause multiple invocations of the internal machinery. * @returns {Stream} new stream which will multicast events to all observers. */ Stream.prototype.multicast = function () { return multicast(this); }; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;'use strict'; (function (global, factory) { if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [exports, __webpack_require__(3)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (typeof exports !== "undefined") { factory(exports, require('@most/prelude')); } else { var mod = { exports: {} }; factory(mod.exports, global.prelude); global.mostMulticast = mod.exports; } })(undefined, function (exports, _prelude) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.MulticastSource = undefined; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var MulticastDisposable = function () { function MulticastDisposable(source, sink) { _classCallCheck(this, MulticastDisposable); this.source = source; this.sink = sink; this.disposed = false; } _createClass(MulticastDisposable, [{ key: 'dispose', value: function dispose() { if (this.disposed) { return; } this.disposed = true; var remaining = this.source.remove(this.sink); return remaining === 0 && this.source._dispose(); } }]); return MulticastDisposable; }(); function tryEvent(t, x, sink) { try { sink.event(t, x); } catch (e) { sink.error(t, e); } } function tryEnd(t, x, sink) { try { sink.end(t, x); } catch (e) { sink.error(t, e); } } var dispose = function dispose(disposable) { return disposable.dispose(); }; var emptyDisposable = { dispose: function dispose() {} }; var MulticastSource = function () { function MulticastSource(source) { _classCallCheck(this, MulticastSource); this.source = source; this.sinks = []; this._disposable = emptyDisposable; } _createClass(MulticastSource, [{ key: 'run', value: function run(sink, scheduler) { var n = this.add(sink); if (n === 1) { this._disposable = this.source.run(this, scheduler); } return new MulticastDisposable(this, sink); } }, { key: '_dispose', value: function _dispose() { var disposable = this._disposable; this._disposable = emptyDisposable; return Promise.resolve(disposable).then(dispose); } }, { key: 'add', value: function add(sink) { this.sinks = (0, _prelude.append)(sink, this.sinks); return this.sinks.length; } }, { key: 'remove', value: function remove(sink) { var i = (0, _prelude.findIndex)(sink, this.sinks); // istanbul ignore next if (i >= 0) { this.sinks = (0, _prelude.remove)(i, this.sinks); } return this.sinks.length; } }, { key: 'event', value: function event(time, value) { var s = this.sinks; if (s.length === 1) { return s[0].event(time, value); } for (var i = 0; i < s.length; ++i) { tryEvent(time, value, s[i]); } } }, { key: 'end', value: function end(time, value) { var s = this.sinks; for (var i = 0; i < s.length; ++i) { tryEnd(time, value, s[i]); } } }, { key: 'error', value: function error(time, err) { var s = this.sinks; for (var i = 0; i < s.length; ++i) { s[i].error(time, err); } } }]); return MulticastSource; }(); function multicast(stream) { var source = stream.source; return source instanceof MulticastSource ? stream : new stream.constructor(new MulticastSource(source)); } exports.MulticastSource = MulticastSource; exports.default = multicast; }); /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var fatal = __webpack_require__(28); module.exports = PropagateTask; function PropagateTask(run, value, sink) { this._run = run; this.value = value; this.sink = sink; this.active = true; } PropagateTask.event = function (value, sink) { return new PropagateTask(emit, value, sink); }; PropagateTask.end = function (value, sink) { return new PropagateTask(end, value, sink); }; PropagateTask.error = function (value, sink) { return new PropagateTask(error, value, sink); }; PropagateTask.prototype.dispose = function () { this.active = false; }; PropagateTask.prototype.run = function (t) { if (!this.active) { return; } this._run(t, this.value, this.sink); }; PropagateTask.prototype.error = function (t, e) { if (!this.active) { return fatal(e); } this.sink.error(t, e); }; function error(t, e, sink) { sink.error(t, e); } function emit(t, x, sink) { sink.event(t, x); } function end(t, x, sink) { sink.end(t, x); } /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var ValueSource = __webpack_require__(34); var dispose = __webpack_require__(2); var PropagateTask = __webpack_require__(6); exports.of = streamOf; exports.empty = empty; exports.never = never; /** * Stream containing only x * @param {*} x * @returns {Stream} */ function streamOf(x) { return new Stream(new ValueSource(emit, x)); } function emit(t, x, sink) { sink.event(0, x); sink.end(0, void 0); } /** * Stream containing no events and ends immediately * @returns {Stream} */ function empty() { return EMPTY; } function EmptySource() {} EmptySource.prototype.run = function (sink, scheduler) { var task = PropagateTask.end(void 0, sink); scheduler.asap(task); return dispose.create(disposeEmpty, task); }; function disposeEmpty(task) { return task.dispose(); } var EMPTY = new Stream(new EmptySource()); /** * Stream containing no events and never ends * @returns {Stream} */ function never() { return NEVER; } function NeverSource() {} NeverSource.prototype.run = function () { return dispose.empty(); }; var NEVER = new Stream(new NeverSource()); /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var dispose = __webpack_require__(2); var LinkedList = __webpack_require__(52); var identity = __webpack_require__(3).id; exports.mergeConcurrently = mergeConcurrently; exports.mergeMapConcurrently = mergeMapConcurrently; function mergeConcurrently(concurrency, stream) { return mergeMapConcurrently(identity, concurrency, stream); } function mergeMapConcurrently(f, concurrency, stream) { return new Stream(new MergeConcurrently(f, concurrency, stream.source)); } function MergeConcurrently(f, concurrency, source) { this.f = f; this.concurrency = concurrency; this.source = source; } MergeConcurrently.prototype.run = function (sink, scheduler) { return new Outer(this.f, this.concurrency, this.source, sink, scheduler); }; function Outer(f, concurrency, source, sink, scheduler) { this.f = f; this.concurrency = concurrency; this.sink = sink; this.scheduler = scheduler; this.pending = []; this.current = new LinkedList(); this.disposable = dispose.once(source.run(this, scheduler)); this.active = true; } Outer.prototype.event = function (t, x) { this._addInner(t, x); }; Outer.prototype._addInner = function (t, stream) { if (this.current.length < this.concurrency) { this._startInner(t, stream); } else { this.pending.push(stream); } }; Outer.prototype._startInner = function (t, stream) { var innerSink = new Inner(t, this, this.sink); this.current.add(innerSink); innerSink.disposable = mapAndRun(this.f, innerSink, this.scheduler, stream); }; function mapAndRun(f, innerSink, scheduler, stream) { return f(stream).source.run(innerSink, scheduler); } Outer.prototype.end = function (t, x) { this.active = false; dispose.tryDispose(t, this.disposable, this.sink); this._checkEnd(t, x); }; Outer.prototype.error = function (t, e) { this.active = false; this.sink.error(t, e); }; Outer.prototype.dispose = function () { this.active = false; this.pending.length = 0; return Promise.all([this.disposable.dispose(), this.current.dispose()]); }; Outer.prototype._endInner = function (t, x, inner) { this.current.remove(inner); dispose.tryDispose(t, inner, this); if (this.pending.length === 0) { this._checkEnd(t, x); } else { this._startInner(t, this.pending.shift()); } }; Outer.prototype._checkEnd = function (t, x) { if (!this.active && this.current.isEmpty()) { this.sink.end(t, x); } }; function Inner(time, outer, sink) { this.prev = this.next = null; this.time = time; this.outer = outer; this.sink = sink; this.disposable = void 0; } Inner.prototype.event = function (t, x) { this.sink.event(Math.max(t, this.time), x); }; Inner.prototype.end = function (t, x) { this.outer._endInner(Math.max(t, this.time), x, this); }; Inner.prototype.error = function (t, e) { this.outer.error(Math.max(t, this.time), e); }; Inner.prototype.dispose = function () { return this.disposable.dispose(); }; /***/ }, /* 9 */ /***/ function(module, exports) { "use strict"; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ exports.tryEvent = tryEvent; exports.tryEnd = tryEnd; function tryEvent(t, x, sink) { try { sink.event(t, x); } catch (e) { sink.error(t, e); } } function tryEnd(t, x, sink) { try { sink.end(t, x); } catch (e) { sink.error(t, e); } } /***/ }, /* 10 */ /***/ function(module, exports) { 'use strict'; module.exports = { array: Array.isArray, primitive: function primitive(s) { return typeof s === 'string' || typeof s === 'number'; } }; /***/ }, /* 11 */ /***/ function(module, exports) { 'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ exports.isPromise = isPromise; function isPromise(p) { return p !== null && (typeof p === 'undefined' ? 'undefined' : _typeof(p)) === 'object' && typeof p.then === 'function'; } /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var Map = __webpack_require__(30); exports.map = map; exports.constant = constant; exports.tap = tap; /** * Transform each value in the stream by applying f to each * @param {function(*):*} f mapping function * @param {Stream} stream stream to map * @returns {Stream} stream containing items transformed by f */ function map(f, stream) { return new Stream(Map.create(f, stream.source)); } /** * Replace each value in the stream with x * @param {*} x * @param {Stream} stream * @returns {Stream} stream containing items replaced with x */ function constant(x, stream) { return map(function () { return x; }, stream); } /** * Perform a side effect for each item in the stream * @param {function(x:*):*} f side effect to execute for each item. The * return value will be discarded. * @param {Stream} stream stream to tap * @returns {Stream} new stream containing the same items as this stream */ function tap(f, stream) { return map(function (x) { f(x); return x; }, stream); } /***/ }, /* 13 */ /***/ function(module, exports) { "use strict"; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ module.exports = invoke; function invoke(f, args) { /*eslint complexity: [2,7]*/ switch (args.length) { case 0: return f(); case 1: return f(args[0]); case 2: return f(args[0], args[1]); case 3: return f(args[0], args[1], args[2]); case 4: return f(args[0], args[1], args[2], args[3]); case 5: return f(args[0], args[1], args[2], args[3], args[4]); default: return f.apply(void 0, args); } } /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Sink = __webpack_require__(1); module.exports = IndexSink; IndexSink.hasValue = hasValue; function hasValue(indexSink) { return indexSink.hasValue; } function IndexSink(i, sink) { this.index = i; this.sink = sink; this.active = true; this.hasValue = false; this.value = void 0; } IndexSink.prototype.event = function (t, x) { if (!this.active) { return; } this.value = x; this.hasValue = true; this.sink.event(t, this); }; IndexSink.prototype.end = function (t, x) { if (!this.active) { return; } this.active = false; this.sink.end(t, { index: this.index, value: x }); }; IndexSink.prototype.error = Sink.prototype.error; /***/ }, /* 15 */ /***/ function(module, exports) { "use strict"; module.exports = function (sel, data, children, text, elm) { var key = data === undefined ? undefined : data.key; return { sel: sel, data: data, children: children, text: text, elm: elm, key: key }; }; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.mockDOMSource = exports.makeDOMDriver = exports.video = exports.ul = exports.u = exports.tr = exports.title = exports.thead = exports.th = exports.tfoot = exports.textarea = exports.td = exports.tbody = exports.table = exports.sup = exports.sub = exports.style = exports.strong = exports.span = exports.source = exports.small = exports.select = exports.section = exports.script = exports.samp = exports.s = exports.ruby = exports.rt = exports.rp = exports.q = exports.pre = exports.param = exports.p = exports.option = exports.optgroup = exports.ol = exports.object = exports.noscript = exports.nav = exports.meta = exports.menu = exports.mark = exports.map = exports.main = exports.link = exports.li = exports.legend = exports.label = exports.keygen = exports.kbd = exports.ins = exports.input = exports.img = exports.iframe = exports.i = exports.html = exports.hr = exports.hgroup = exports.header = exports.head = exports.h6 = exports.h5 = exports.h4 = exports.h3 = exports.h2 = exports.h1 = exports.form = exports.footer = exports.figure = exports.figcaption = exports.fieldset = exports.embed = exports.em = exports.dt = exports.dl = exports.div = exports.dir = exports.dfn = exports.del = exports.dd = exports.colgroup = exports.col = exports.code = exports.cite = exports.caption = exports.canvas = exports.button = exports.br = exports.body = exports.blockquote = exports.bdo = exports.bdi = exports.base = exports.b = exports.audio = exports.aside = exports.article = exports.area = exports.address = exports.abbr = exports.a = exports.h = exports.thunk = exports.modules = undefined; var _makeDOMDriver = __webpack_require__(42); Object.defineProperty(exports, 'makeDOMDriver', { enumerable: true, get: function get() { return _makeDOMDriver.makeDOMDriver; } }); var _mockDOMSource = __webpack_require__(43); Object.defineProperty(exports, 'mockDOMSource', { enumerable: true, get: function get() { return _mockDOMSource.mockDOMSource; } }); var _modules = __webpack_require__(21); var modules = _interopRequireWildcard(_modules); var _thunk = __webpack_require__(101); var _thunk2 = _interopRequireDefault(_thunk); var _hyperscript = __webpack_require__(41); var _hyperscript2 = _interopRequireDefault(_hyperscript); var _hyperscriptHelpers = __webpack_require__(47); var _hyperscriptHelpers2 = _interopRequireDefault(_hyperscriptHelpers); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {};if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } }newObj.default = obj;return newObj; } } exports.modules = modules; exports.thunk = _thunk2.default; exports.h = _hyperscript2.default; var _hh = (0, _hyperscriptHelpers2.default)(_hyperscript2.default); var a = _hh.a; var abbr = _hh.abbr; var address = _hh.address; var area = _hh.area; var article = _hh.article; var aside = _hh.aside; var audio = _hh.audio; var b = _hh.b; var base = _hh.base; var bdi = _hh.bdi; var bdo = _hh.bdo; var blockquote = _hh.blockquote; var body = _hh.body; var br = _hh.br; var button = _hh.button; var canvas = _hh.canvas; var caption = _hh.caption; var cite = _hh.cite; var code = _hh.code; var col = _hh.col; var colgroup = _hh.colgroup; var dd = _hh.dd; var del = _hh.del; var dfn = _hh.dfn; var dir = _hh.dir; var div = _hh.div; var dl = _hh.dl; var dt = _hh.dt; var em = _hh.em; var embed = _hh.embed; var fieldset = _hh.fieldset; var figcaption = _hh.figcaption; var figure = _hh.figure; var footer = _hh.footer; var form = _hh.form; var h1 = _hh.h1; var h2 = _hh.h2; var h3 = _hh.h3; var h4 = _hh.h4; var h5 = _hh.h5; var h6 = _hh.h6; var head = _hh.head; var header = _hh.header; var hgroup = _hh.hgroup; var hr = _hh.hr; var html = _hh.html; var i = _hh.i; var iframe = _hh.iframe; var img = _hh.img; var input = _hh.input; var ins = _hh.ins; var kbd = _hh.kbd; var keygen = _hh.keygen; var label = _hh.label; var legend = _hh.legend; var li = _hh.li; var link = _hh.link; var main = _hh.main; var map = _hh.map; var mark = _hh.mark; var menu = _hh.menu; var meta = _hh.meta; var nav = _hh.nav; var noscript = _hh.noscript; var object = _hh.object; var ol = _hh.ol; var optgroup = _hh.optgroup; var option = _hh.option; var p = _hh.p; var param = _hh.param; var pre = _hh.pre; var q = _hh.q; var rp = _hh.rp; var rt = _hh.rt; var ruby = _hh.ruby; var s = _hh.s; var samp = _hh.samp; var script = _hh.script; var section = _hh.section; var select = _hh.select; var small = _hh.small; var source = _hh.source; var span = _hh.span; var strong = _hh.strong; var style = _hh.style; var sub = _hh.sub; var sup = _hh.sup; var table = _hh.table; var tbody = _hh.tbody; var td = _hh.td; var textarea = _hh.textarea; var tfoot = _hh.tfoot; var th = _hh.th; var thead = _hh.thead; var title = _hh.title; var tr = _hh.tr; var u = _hh.u; var ul = _hh.ul; var video = _hh.video; exports.a = a; exports.abbr = abbr; exports.address = address; exports.area = area; exports.article = article; exports.aside = aside; exports.audio = audio; exports.b = b; exports.base = base; exports.bdi = bdi; exports.bdo = bdo; exports.blockquote = blockquote; exports.body = body; exports.br = br; exports.button = button; exports.canvas = canvas; exports.caption = caption; exports.cite = cite; exports.code = code; exports.col = col; exports.colgroup = colgroup; exports.dd = dd; exports.del = del; exports.dfn = dfn; exports.dir = dir; exports.div = div; exports.dl = dl; exports.dt = dt; exports.em = em; exports.embed = embed; exports.fieldset = fieldset; exports.figcaption = figcaption; exports.figure = figure; exports.footer = footer; exports.form = form; exports.h1 = h1; exports.h2 = h2; exports.h3 = h3; exports.h4 = h4; exports.h5 = h5; exports.h6 = h6; exports.head = head; exports.header = header; exports.hgroup = hgroup; exports.hr = hr; exports.html = html; exports.i = i; exports.iframe = iframe; exports.img = img; exports.input = input; exports.ins = ins; exports.kbd = kbd; exports.keygen = keygen; exports.label = label; exports.legend = legend; exports.li = li; exports.link = link; exports.main = main; exports.map = map; exports.mark = mark; exports.menu = menu; exports.meta = meta; exports.nav = nav; exports.noscript = noscript; exports.object = object; exports.ol = ol; exports.optgroup = optgroup; exports.option = option; exports.p = p; exports.param = param; exports.pre = pre; exports.q = q; exports.rp = rp; exports.rt = rt; exports.ruby = ruby; exports.s = s; exports.samp = samp; exports.script = script; exports.section = section; exports.select = select; exports.small = small; exports.source = source; exports.span = span; exports.strong = strong; exports.style = style; exports.sub = sub; exports.sup = sup; exports.table = table; exports.tbody = tbody; exports.td = td; exports.textarea = textarea; exports.tfoot = tfoot; exports.th = th; exports.thead = thead; exports.title = title; exports.tr = tr; exports.u = u; exports.ul = ul; exports.video = video; /***/ }, /* 17 */ /***/ function(module, exports) { 'use strict'; // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; (function () { try { cachedSetTimeout = setTimeout; } catch (e) { cachedSetTimeout = function cachedSetTimeout() { throw new Error('setTimeout is not defined'); }; } try { cachedClearTimeout = clearTimeout; } catch (e) { cachedClearTimeout = function cachedClearTimeout() { throw new Error('clearTimeout is not defined'); }; } })(); var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = cachedSetTimeout(cleanUpNextTick); draining = true; var len = queue.length; while (len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; cachedClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { cachedSetTimeout(drainQueue, 0); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/'; }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function () { return 0; }; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.makeEventsSelector = undefined; var _domEvent = __webpack_require__(39); var _makeIsStrictlyInRootScope = __webpack_require__(20); var matchesSelector = void 0; try { matchesSelector = __webpack_require__(48); } catch (e) { matchesSelector = function matchesSelector() {}; } var eventTypesThatDontBubble = ['load', 'unload', 'focus', 'blur', 'mouseenter', 'mouseleave', 'submit', 'change', 'reset', 'timeupdate', 'playing', 'waiting', 'seeking', 'seeked', 'ended', 'loadedmetadata', 'loadeddata', 'canplay', 'canplaythrough', 'durationchange', 'play', 'pause', 'ratechange', 'volumechange', 'suspend', 'emptied', 'stalled']; function maybeMutateEventPropagationAttributes(event) { if (!event.hasOwnProperty('propagationHasBeenStopped')) { (function () { event.propagationHasBeenStopped = false; var oldStopPropagation = event.stopPropagation; event.stopPropagation = function stopPropagation() { oldStopPropagation.call(this); this.propagationHasBeenStopped = true; }; })(); } } function mutateEventCurrentTarget(event, currentTargetElement) { try { Object.defineProperty(event, 'currentTarget', { value: currentTargetElement, configurable: true }); } catch (err) { console.log('please use event.ownerTarget'); } event.ownerTarget = currentTargetElement; } function makeSimulateBubbling(namespace, rootEl) { var isStrictlyInRootScope = (0, _makeIsStrictlyInRootScope.makeIsStrictlyInRootScope)(namespace); var descendantSel = namespace.join(' '); var topSel = namespace.join(''); var roof = rootEl.parentElement; return function simulateBubbling(ev) { maybeMutateEventPropagationAttributes(ev); if (ev.propagationHasBeenStopped) { return false; } for (var el = ev.target; el && el !== roof; el = el.parentElement) { if (!isStrictlyInRootScope(el)) { continue; } if (matchesSelector(el, descendantSel) || matchesSelector(el, topSel)) { mutateEventCurrentTarget(ev, el); return true; } } return false; }; } var defaults = { useCapture: false }; function makeEventsSelector(rootElement$, namespace) { return function eventsSelector(type) { var options = arguments.length <= 1 || arguments[1] === undefined ? defaults : arguments[1]; if (typeof type !== 'string') { throw new Error('DOM driver\'s events() expects argument to be a ' + 'string representing the event type to listen for.'); } var useCapture = false; if (typeof options.useCapture === 'boolean') { useCapture = options.useCapture; } if (eventTypesThatDontBubble.indexOf(type) !== -1) { useCapture = true; } return rootElement$.map(function (rootElement) { return { rootElement: rootElement, namespace: namespace }; }).skipRepeatsWith(function (prev, curr) { return prev.namespace.join('') === curr.namespace.join(''); }).map(function (_ref) { var rootElement = _ref.rootElement; if (!namespace || namespace.length === 0) { return (0, _domEvent.domEvent)(type, rootElement, useCapture); } var simulateBubbling = makeSimulateBubbling(namespace, rootElement); return (0, _domEvent.domEvent)(type, rootElement, useCapture).filter(simulateBubbling); }).switch().multicast(); }; } exports.makeEventsSelector = makeEventsSelector; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.isolateSource = exports.isolateSink = undefined; var _utils = __webpack_require__(22); var isolateSource = function isolateSource(source_, scope) { return source_.select('.' + _utils.SCOPE_PREFIX + scope); }; var isolateSink = function isolateSink(sink, scope) { return sink.map(function (vTree) { if (vTree.sel.indexOf('' + _utils.SCOPE_PREFIX + scope) === -1) { if (vTree.data.ns) { // svg elements var _vTree$data$attrs = vTree.data.attrs; var attrs = _vTree$data$attrs === undefined ? {} : _vTree$data$attrs; attrs.class = (attrs.class || '') + ' ' + _utils.SCOPE_PREFIX + scope; } else { vTree.sel = vTree.sel + '.' + _utils.SCOPE_PREFIX + scope; } } return vTree; }); }; exports.isolateSink = isolateSink; exports.isolateSource = isolateSource; /***/ }, /* 20 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function makeIsStrictlyInRootScope(namespace) { var classIsForeign = function classIsForeign(c) { var matched = c.match(/cycle-scope-(\S+)/); return matched && namespace.indexOf("." + c) === -1; }; var classIsDomestic = function classIsDomestic(c) { var matched = c.match(/cycle-scope-(\S+)/); return matched && namespace.indexOf("." + c) !== -1; }; return function isStrictlyInRootScope(leaf) { var some = Array.prototype.some; var split = String.prototype.split; for (var el = leaf; el; el = el.parentElement) { var classList = el.classList || split.call(el.className, " "); if (some.call(classList, classIsDomestic)) { return true; } if (some.call(classList, classIsForeign)) { return false; } } return true; }; } exports.makeIsStrictlyInRootScope = makeIsStrictlyInRootScope; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.EventsModule = exports.HeroModule = exports.AttrsModule = exports.PropsModule = exports.ClassModule = exports.StyleModule = undefined; var _class = __webpack_require__(95); var _class2 = _interopRequireDefault(_class); var _props = __webpack_require__(98); var _props2 = _interopRequireDefault(_props); var _attributes = __webpack_require__(94); var _attributes2 = _interopRequireDefault(_attributes); var _eventlisteners = __webpack_require__(96); var _eventlisteners2 = _interopRequireDefault(_eventlisteners); var _style = __webpack_require__(99); var _style2 = _interopRequireDefault(_style); var _hero = __webpack_require__(97); var _hero2 = _interopRequireDefault(_hero); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = [_style2.default, _class2.default, _props2.default, _attributes2.default]; exports.StyleModule = _style2.default; exports.ClassModule = _class2.default; exports.PropsModule = _props2.default; exports.AttrsModule = _attributes2.default; exports.HeroModule = _hero2.default; exports.EventsModule = _eventlisteners2.default; /***/ }, /* 22 */ /***/ function(module, exports) { "use strict"; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; Object.defineProperty(exports, "__esModule", { value: true }); var SCOPE_PREFIX = "cycle-scope-"; var isElement = function isElement(obj) { return (typeof HTMLElement === "undefined" ? "undefined" : _typeof(HTMLElement)) === "object" ? obj instanceof HTMLElement || obj instanceof DocumentFragment : obj && (typeof obj === "undefined" ? "undefined" : _typeof(obj)) === "object" && obj !== null && (obj.nodeType === 1 || obj.nodeType === 11) && typeof obj.nodeName === "string"; }; var domSelectorParser = function domSelectorParser(selectors) { var domElement = typeof selectors === "string" ? document.querySelector(selectors) : selectors; if (typeof domElement === "string" && domElement === null) { throw new Error("Cannot render into unknown element `" + selectors + "`"); } else if (!isElement(domElement)) { throw new Error("Given container is not a DOM element neither a " + "selector string."); } return domElement; }; exports.domSelectorParser = domSelectorParser; exports.SCOPE_PREFIX = SCOPE_PREFIX; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var streamOf = __webpack_require__(7).of; var continueWith = __webpack_require__(25).continueWith; exports.concat = concat; exports.cycle = cycle; exports.cons = cons; /** * @param {*} x value to prepend * @param {Stream} stream * @returns {Stream} new stream with x prepended */ function cons(x, stream) { return concat(streamOf(x), stream); } /** * @param {Stream} left * @param {Stream} right * @returns {Stream} new stream containing all events in left followed by all * events in right. This *timeshifts* right to the end of left. */ function concat(left, right) { return continueWith(function () { return right; }, left); } /** * @deprecated * Tie stream into a circle, creating an infinite stream * @param {Stream} stream * @returns {Stream} new infinite stream */ function cycle(stream) { return continueWith(function cycleNext() { return cycle(stream); }, stream); } /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var transform = __webpack_require__(12); var core = __webpack_require__(7); var Pipe = __webpack_require__(1); var IndexSink = __webpack_require__(14); var dispose = __webpack_require__(2); var base = __webpack_require__(3); var invoke = __webpack_require__(13); var hasValue = IndexSink.hasValue; var map = base.map; var tail = base.tail; exports.combineArray = combineArray; exports.combine = combine; /** * Combine latest events from all input streams * @param {function(...events):*} f function to combine most recent events * @returns {Stream} stream containing the result of applying f to the most recent * event of each input stream, whenever a new event arrives on any stream. */ function combine(f /*, ...streams */) { return combineArray(f, tail(arguments)); } /** * Combine latest events from all input streams * @param {function(...events):*} f function to combine most recent events * @param {[Stream]} streams most recent events * @returns {Stream} stream containing the result of applying f to the most recent * event of each input stream, whenever a new event arrives on any stream. */ function combineArray(f, streams) { var l = streams.length; return l === 0 ? core.empty() : l === 1 ? transform.map(f, streams[0]) : new Stream(combineSources(f, streams)); } function combineSources(f, streams) { return new Combine(f, map(getSource, streams)); } function getSource(stream) { return stream.source; } function Combine(f, sources) { this.f = f; this.sources = sources; } Combine.prototype.run = function (sink, scheduler) { var l = this.sources.length; var disposables = new Array(l); var sinks = new Array(l); var mergeSink = new CombineSink(disposables, sinks, sink, this.f); for (var indexSink, i = 0; i < l; ++i) { indexSink = sinks[i] = new IndexSink(i, mergeSink); disposables[i] = this.sources[i].run(indexSink, scheduler); } return dispose.all(disposables); }; function CombineSink(disposables, sinks, sink, f) { this.sink = sink; this.disposables = disposables; this.sinks = sinks; this.f = f; this.values = new Array(sinks.length); this.ready = false; this.activeCount = sinks.length; } CombineSink.prototype.error = Pipe.prototype.error; CombineSink.prototype.event = function (t, indexedValue) { if (!this.ready) { this.ready = this.sinks.every(hasValue); } this.values[indexedValue.index] = indexedValue.value; if (this.ready) { this.sink.event(t, invoke(this.f, this.values)); } }; CombineSink.prototype.end = function (t, indexedValue) { dispose.tryDispose(t, this.disposables[indexedValue.index], this.sink); if (--this.activeCount === 0) { this.sink.end(t, indexedValue.value); } }; /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var Sink = __webpack_require__(1); var dispose = __webpack_require__(2); var isPromise = __webpack_require__(11).isPromise; exports.continueWith = continueWith; function continueWith(f, stream) { return new Stream(new ContinueWith(f, stream.source)); } function ContinueWith(f, source) { this.f = f; this.source = source; } ContinueWith.prototype.run = function (sink, scheduler) { return new ContinueWithSink(this.f, this.source, sink, scheduler); }; function ContinueWithSink(f, source, sink, scheduler) { this.f = f; this.sink = sink; this.scheduler = scheduler; this.active = true; this.disposable = dispose.once(source.run(this, scheduler)); } ContinueWithSink.prototype.error = Sink.prototype.error; ContinueWithSink.prototype.event = function (t, x) { if (!this.active) { return; } this.sink.event(t, x); }; ContinueWithSink.prototype.end = function (t, x) { if (!this.active) { return; } var result = dispose.tryDispose(t, this.disposable, this.sink); this.disposable = isPromise(result) ? dispose.promised(this._thenContinue(result, x)) : this._continue(this.f, x); }; ContinueWithSink.prototype._thenContinue = function (p, x) { var self = this; return p.then(function () { return self._continue(self.f, x); }); }; ContinueWithSink.prototype._continue = function (f, x) { return f(x).source.run(this.sink, this.scheduler); }; ContinueWithSink.prototype.dispose = function () { this.active = false; return this.disposable.dispose(); }; /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var mergeConcurrently = __webpack_require__(8).mergeConcurrently; var mergeMapConcurrently = __webpack_require__(8).mergeMapConcurrently; exports.flatMap = flatMap; exports.join = join; /** * Map each value in the stream to a new stream, and merge it into the * returned outer stream. Event arrival times are preserved. * @param {function(x:*):Stream} f chaining function, must return a Stream * @param {Stream} stream * @returns {Stream} new stream containing all events from each stream returned by f */ function flatMap(f, stream) { return mergeMapConcurrently(f, Infinity, stream); } /** * Monadic join. Flatten a Stream<Stream<X>> to Stream<X> by merging inner * streams to the outer. Event arrival times are preserved. * @param {Stream<Stream<X>>} stream stream of streams * @returns {Stream<X>} new stream containing all events of all inner streams */ function join(stream) { return mergeConcurrently(Infinity, stream); } /***/ }, /* 27 */ /***/ function(module, exports) { "use strict"; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ module.exports = defer; function defer(task) { return Promise.resolve(task).then(runTask); } function runTask(task) { try { return task.run(); } catch (e) { return task.error(e); } } /***/ }, /* 28 */ /***/ function(module, exports) { "use strict"; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ module.exports = fatalError; function fatalError(e) { setTimeout(function () { throw e; }, 0); } /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Pipe = __webpack_require__(1); module.exports = Filter; function Filter(p, source) { this.p = p; this.source = source; } /** * Create a filtered source, fusing adjacent filter.filter if possible * @param {function(x:*):boolean} p filtering predicate * @param {{run:function}} source source to filter * @returns {Filter} filtered source */ Filter.create = function createFilter(p, source) { if (source instanceof Filter) { return new Filter(and(source.p, p), source.source); } return new Filter(p, source); }; Filter.prototype.run = function (sink, scheduler) { return this.source.run(new FilterSink(this.p, sink), scheduler); }; function FilterSink(p, sink) { this.p = p; this.sink = sink; } FilterSink.prototype.end = Pipe.prototype.end; FilterSink.prototype.error = Pipe.prototype.error; FilterSink.prototype.event = function (t, x) { var p = this.p; p(x) && this.sink.event(t, x); }; function and(p, q) { return function (x) { return p(x) && q(x); }; } /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Pipe = __webpack_require__(1); var Filter = __webpack_require__(29); var FilterMap = __webpack_require__(74); var base = __webpack_require__(3); module.exports = Map; function Map(f, source) { this.f = f; this.source = source; } /** * Create a mapped source, fusing adjacent map.map, filter.map, * and filter.map.map if possible * @param {function(*):*} f mapping function * @param {{run:function}} source source to map * @returns {Map|FilterMap} mapped source, possibly fused */ Map.create = function createMap(f, source) { if (source instanceof Map) { return new Map(base.compose(f, source.f), source.source); } if (source instanceof Filter) { return new FilterMap(source.p, f, source.source); } if (source instanceof FilterMap) { return new FilterMap(source.p, base.compose(f, source.f), source.source); } return new Map(f, source); }; Map.prototype.run = function (sink, scheduler) { return this.source.run(new MapSink(this.f, sink), scheduler); }; function MapSink(f, sink) { this.f = f; this.sink = sink; } MapSink.prototype.end = Pipe.prototype.end; MapSink.prototype.error = Pipe.prototype.error; MapSink.prototype.event = function (t, x) { var f = this.f; this.sink.event(t, f(x)); }; /***/ }, /* 31 */ /***/ function(module, exports) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ exports.isIterable = isIterable; exports.getIterator = getIterator; exports.makeIterable = makeIterable; /*global Set, Symbol*/ var iteratorSymbol; // Firefox ships a partial implementation using the name @@iterator. // https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14 if (typeof Set === 'function' && typeof new Set()['@@iterator'] === 'function') { iteratorSymbol = '@@iterator'; } else { iteratorSymbol = typeof Symbol === 'function' && Symbol.iterator || '_es6shim_iterator_'; } function isIterable(o) { return typeof o[iteratorSymbol] === 'function'; } function getIterator(o) { return o[iteratorSymbol](); } function makeIterable(f, o) { o[iteratorSymbol] = f; return o; } /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Observer = __webpack_require__(79); var dispose = __webpack_require__(2); var defaultScheduler = __webpack_require__(76); exports.withDefaultScheduler = withDefaultScheduler; exports.withScheduler = withScheduler; function withDefaultScheduler(f, source) { return withScheduler(f, source, defaultScheduler); } function withScheduler(f, source, scheduler) { return new Promise(function (resolve, reject) { runSource(f, source, scheduler, resolve, reject); }); } function runSource(f, source, scheduler, resolve, reject) { var disposable = dispose.settable(); var observer = new Observer(f, resolve, reject, disposable); disposable.setDisposable(source.run(observer, scheduler)); } /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var defer = __webpack_require__(27); module.exports = DeferredSink; function DeferredSink(sink) { this.sink = sink; this.events = []; this.length = 0; this.active = true; } DeferredSink.prototype.event = function (t, x) { if (!this.active) { return; } if (this.length === 0) { defer(new PropagateAllTask(this)); } this.events[this.length++] = { time: t, value: x }; }; DeferredSink.prototype.error = function (t, e) { this.active = false; defer(new ErrorTask(t, e, this.sink)); }; DeferredSink.prototype.end = function (t, x) { this.active = false; defer(new EndTask(t, x, this.sink)); }; function PropagateAllTask(deferred) { this.deferred = deferred; } PropagateAllTask.prototype.run = function () { var p = this.deferred; var events = p.events; var sink = p.sink; var event; for (var i = 0, l = p.length; i < l; ++i) { event = events[i]; sink.event(event.time, event.value); events[i] = void 0; } p.length = 0; }; PropagateAllTask.prototype.error = function (e) { this.deferred.error(0, e); }; function EndTask(t, x, sink) { this.time = t; this.value = x; this.sink = sink; } EndTask.prototype.run = function () { this.sink.end(this.time, this.value); }; EndTask.prototype.error = function (e) { this.sink.error(this.time, e); }; function ErrorTask(t, e, sink) { this.time = t; this.value = e; this.sink = sink; } ErrorTask.prototype.run = function () { this.sink.error(this.time, this.value); }; ErrorTask.prototype.error = function (e) { throw e; }; /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var PropagateTask = __webpack_require__(6); module.exports = ValueSource; function ValueSource(emit, x) { this.emit = emit; this.value = x; } ValueSource.prototype.run = function (sink, scheduler) { return new ValueProducer(this.emit, this.value, sink, scheduler); }; function ValueProducer(emit, x, sink, scheduler) { this.task = scheduler.asap(new PropagateTask(emit, x, sink)); } ValueProducer.prototype.dispose = function () { return this.task.cancel(); }; /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = selectorParser; var _browserSplit = __webpack_require__(46); var _browserSplit2 = _interopRequireDefault(_browserSplit); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var classIdSplit = /([\.#]?[a-zA-Z0-9\u007F-\uFFFF_:-]+)/; var notClassId = /^\.|#/; function selectorParser() { var selector = arguments.length <= 0 || arguments[0] === undefined ? '' : arguments[0]; var tagName = undefined; var id = ''; var classes = []; var tagParts = (0, _browserSplit2.default)(selector, classIdSplit); if (notClassId.test(tagParts[1]) || selector === '') { tagName = 'div'; } var part = undefined; var type = undefined; var i = undefined; for (i = 0; i < tagParts.length; i++) { part = tagParts[i]; if (!part) { continue; } type = part.charAt(0); if (!tagName) { tagName = part; } else if (type === '.') { classes.push(part.substring(1, part.length)); } else if (type === '#') { id = part.substring(1, part.length); } } return { tagName: tagName, id: id, className: classes.join(' ') }; } /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var VNode = __webpack_require__(15); var is = __webpack_require__(10); function addNS(data, children) { data.ns = 'http://www.w3.org/2000/svg'; if (children !== undefined) { for (var i = 0; i < children.length; ++i) { addNS(children[i].data, children[i].children); } } } module.exports = function h(sel, b, c) { var data = {}, children, text, i; if (arguments.length === 3) { data = b; if (is.array(c)) { children = c; } else if (is.primitive(c)) { text = c; } } else if (arguments.length === 2) { if (is.array(b)) { children = b; } else if (is.primitive(b)) { text = b; } else { data = b; } } if (is.array(children)) { for (i = 0; i < children.length; ++i) { if (is.primitive(children[i])) children[i] = VNode(undefined, undefined, undefined, children[i]); } } if (sel[0] === 's' && sel[1] === 'v' && sel[2] === 'g') { addNS(data, children); } return VNode(sel, data, children, text, undefined); }; /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.run = undefined; var _mostSubject = __webpack_require__(51); function makeSinkProxies(drivers) { var sinkProxies = {}; var keys = Object.keys(drivers); for (var i = 0; i < keys.length; i++) { sinkProxies[keys[i]] = (0, _mostSubject.holdSubject)(1); } return sinkProxies; } function callDrivers(drivers, sinkProxies) { var sources = {}; var keys = Object.keys(drivers); for (var i = 0; i < keys.length; i++) { var name = keys[i]; sources[name] = drivers[name](sinkProxies[name].stream, name); } return sources; } function makeHandleError(observer, onError) { return function handleError(err) { observer.error(err); onError(err); }; } function replicateMany(_ref) { var sinks = _ref.sinks; var sinkProxies = _ref.sinkProxies; var disposableStream = _ref.disposableStream; var onError = _ref.onError; var sinkKeys = Object.keys(sinks); for (var i = 0; i < sinkKeys.length; i++) { var name = sinkKeys[i]; if (sinkProxies.hasOwnProperty(name)) { var observer = sinkProxies[name].observer; sinks[name].until(disposableStream).observe(observer.next).then(observer.complete).catch(makeHandleError(observer, onError)); } } } function assertSinks(sinks) { var keys = Object.keys(sinks); for (var i = 0; i < keys.length; i++) { if (!sinks[keys[i]] || typeof sinks[keys[i]].observe !== 'function') { throw new Error('Sink \'' + keys[i] + '\' must be a most.Stream'); } } return sinks; } var logErrorToConsole = typeof console !== 'undefined' && console.error ? function (error) { console.error(error.stack || error); } : Function.prototype; var defaults = { onError: logErrorToConsole }; function runInputGuard(_ref2) { var main = _ref2.main; var drivers = _ref2.drivers; var onError = _ref2.onError; if (typeof main !== 'function') { throw new Error('First argument given to run() must be the ' + '\'main\' function.'); } if ((typeof drivers === 'undefined' ? 'undefined' : _typeof(drivers)) !== 'object' || drivers === null) { throw new Error('Second argument given to run() must be an ' + 'object with driver functions as properties.'); } if (!Object.keys(drivers).length) { throw new Error('Second argument given to run() must be an ' + 'object with at least one driver function declared as a property.'); } if (typeof onError !== 'function') { throw new Error('onError must be a function'); } } function run(main, drivers) { var _ref3 = arguments.length <= 2 || arguments[2] === undefined ? defaults : arguments[2]; var _ref3$onError = _ref3.onError; var onError = _ref3$onError === undefined ? logErrorToConsole : _ref3$onError; runInputGuard({ main: main, drivers: drivers, onError: onError }); var _subject = (0, _mostSubject.subject)(); var disposableObserver = _subject.observer; var disposableStream = _subject.stream; var sinkProxies = makeSinkProxies(drivers); var sources = callDrivers(drivers, sinkProxies); var sinks = assertSinks(main(sources)); replicateMany({ sinks: sinks, sinkProxies: sinkProxies, disposableStream: disposableStream, onError: onError }); function dispose() { disposableObserver.next(1); disposableObserver.complete(); } return { sinks: sinks, sources: sources, dispose: dispose }; } exports.default = { run: run }; exports.run = run; /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _dom = __webpack_require__(16); /* import {subject} from 'most-subject' var sub = subject var observer = sub.observer; var stream = sub.stream; */ var Monad = function Monad(value, ID) { var _this = this; this.x = value; if (arguments.length === 1) this.id = 'anonymous';else this.id = ID; this.bnd = function (func) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } return func.apply(undefined, [_this.x].concat(args)); }; this.ret = function (a) { window[_this.id] = new Monad(a, _this.id); return window[_this.id]; }; }; var mMname = new Monad('Fred', 'mMname'); var monad = (0, _dom.h)('pre', { style: { color: '#AFEEEE' } }, ' var Monad = function Monad(z, g) {\n var _this = this;\n\n this.x = z;\n if (arguments.length === 1) {\n this.id = \'anonymous\';\n } else {\n this.id = g;\n };\n\n this.bnd = function (func, ...args) {\n return func(_this.x, ...args);\n };\n\n this.ret = function (a) {\n O.[_this.id] = new Monad(a, _this.id);\n return O.[_this.id]\n };\n }; '); var monadIt = (0, _dom.h)('pre', { style: { color: '#AFEEEE' } }, ' var MonadItter = function MonadItter() {\n var _this = this;\n this.p = function () {};\n \n this.release = function (...args) {\n return this.p(...args);\n };\n \n this.bnd = function (func) {\n _this.p = func;\n };\n }; '); var ret = (0, _dom.h)('pre', { style: { color: '#AFEEEE' } }, ' var ret = function ret(v, id) {\n if (arguments.length === 1) {\n return (new Monad(v, \'anonymous\'));\n }\n window[id] = new Monad(v, id);\n return window[id];\n }; '); var fib = (0, _dom.h)('pre', ' mM$fib.stream.addListener({\n next: v => {\n if (v[2] > 1) {mM$fib.ret([v[1], v[0] + v[1], v[2] -1])}\n else {\n mM19.ret(v[1]);\n }\n },\n error: err => console.error(err),\n complete: () => console.log(\'completed\')\n });\n\n const fibPress$ = sources.DOM\n .select(\'input#code\').events(\'keydown\');\n\n const fibPressAction$ = fibPress$.map(e => {\n if (e.target.value == \'\') {return};\n if( e.keyCode == 13 && Number.isInteger(e.target.value*1) ) {\n mM21.ret(e.target.value);\n mM$fib.ret([0, 1, e.target.value]);\n }\n if( e.keyCode == 13 && !Number.isInteger(e.target.value*1 )) {\n mM19.ret("You didn\'t provide an integer");\n }\n }); '); var driver = (0, _dom.h)('pre', ' var websocketsDriver = function () {\n return create((add) => {\n socket.onmessage = msg => add(msg)\n })\n };\n'); var messages = (0, _dom.h)('pre', ' const messages$ = (sources.WS).map(e => \n mMtem.ret(e.data.split(\',\')).bnd(v => {\n mMZ10.bnd(() => game([v[3], v[4], v[5], v[6]]))\n mMZ11.bnd(() => updateScoreboard(v[3]));\n mMZ12.bnd(() => mM6\n .ret(v[2] + \' successfully logged in.\'))\n mMZ13.bnd(() => updateMessages(v))\n mMZ14.bnd(() => mMgoals2.ret(\'The winner is \' + v[2] ))\n mMZ15.bnd(() => mMgoals2.ret(\'A player named \' + \n O.mMname.x + \'is currently logged in. Page will refresh in 4 seconds.\')\n .bnd(refresh))\n mMZ16.bnd(() => {if (O.mMname.x != v[2]) {mMgoals2.ret(v[2] + v[3])}})\n mMZ17.bnd(() => {\n if (v[3] == \'no file\') {\n mMtaskList.ret([])\n } \n else {\n process(e.data)\n }\n })\n mMtemp.ret(e.data.split(\',\')[0])\n .bnd(next, \'CA#$42\', mMZ10)\n .bnd(next, \'CB#$42\', mMZ11)\n .bnd(next, \'CC#$42\', mMZ12)\n .bnd(next, \'CD#$42\', mMZ13)\n .bnd(next, \'CE#$42\', mMZ14)\n .bnd(next, \'EE#$42\', mMZ15)\n .bnd(next, \'DE#$42\', mMZ16)\n .bnd(next, \'DD#$42\', mMZ17)\n }) \n });\n \n var next = function next(x, y, mon2) {\n if (x === y) {\n mon2.release();\n }\n return ret(x);\n }'); var Monad$ = (0, _dom.h)('pre', ' var Monad$ = function Monad$(z, g) {\n var _this = this;\n this.subject = subject();\n this.observer = this.subject.observer;\n this.stream = this.subject.stream;\n this.x = z;\n this.id = g;\n\n this.bnd = function (func, ...args) {\n return func(_this.x, ...args);\n };\n\n this.ret = function (a) {\n O[_this.id] = new Monad$(a,_this.id);\n _this.observer.next(a);\n return O[_this.id];\n };\n };\n '); var nums = (0, _dom.h)('pre', ' \n const numClick$ = sources.DOM\n .select(\'.num\').events(\'click\');\n \n const numClickAction$ = numClick$.map(e => {\n console.log(e);\n if (O.mM3.x.length < 2) {\n O.mM3.bnd(push, e.target.innerHTML, O.mM3)\n mM28.ret(O.mMhistorymM1.x[O.mMindex2.x])\n .bnd(spliceRemove, e.target.id, mMtemp)\n .bnd(v => game(v));\n if (O.mM3.x.length === 2 && O.mM8.x !== 0) {\n updateCalc();\n }\n };\n }).startWith([0,0,0,0]);\n\n const opClick$ = sources.DOM\n .select(\'.op\').events(\'click\');\n \n const opClickAction$ = opClick$.map(e => {\n mM8.ret(e.target.textContent);\n if (O.mM3.x.length === 2) {\n updateCalc();\n }\n })\n\n var game = function game (v) {\n mM1.ret(v);\n O.mMindex.bnd(add, 1, mMindex)\n .bnd(i => O.mMhistorymM1.bnd(spliceAdd, i, O.mM1, O.mMhistorymM1))\n document.getElementById(\'0\').innerHTML = O.mM1.x[0]; \n document.getElementById(\'1\').innerHTML = O.mM1.x[1]; \n document.getElementById(\'2\').innerHTML = O.mM1.x[2]; \n document.getElementById(\'3\').innerHTML = O.mM1.x[3]; \n cleanup()\n };\n }); '); var arrayFuncs = (0, _dom.h)('pre', ' var push = function push(y,v,mon) {\n if (Array.isArray(y)) {\n let ar = [];\n let keys = Object.keys(y);\n for (let k in keys) {ar[k] = y[k]};\n ar.push(v);\n return mon.ret(ar); \n }\n console.log(\'The value provided to push is not an array\');\n return ret(y);\n };\n \n var spliceRemove = function splice(x, j, mon) {\n if (Array.isArray(x)) {\n let ar = [];\n let keys = Object.keys(x);\n for (let k in keys) {ar[k] = x[k]};\n ar.splice(j,1);\n return mon.ret(ar); \n }\n console.log(\'The value provided to spliceRemove is not an array\');\n return ret(x);\n };\n \n var spliceAdd = function splice(x, index, value, mon) {\n if (Array.isArray(x)) {\n let ar = [];\n let keys = Object.keys(x);\n for (let k in keys) {ar[k] = x[k]};\n ar.splice(index, 0, value);\n return mon.ret(ar); \n }\n console.log(\'The value provided to spliceAdd is not an array\');\n return ret(x);\n };\n \n var splice = function splice(x, start, end, mon) {\n if (Array.isArray(x)) {\n let ar = [];\n let keys = Object.keys(x);\n for (let k in keys) {ar[k] = x[k]};\n ar.splice(start, end);\n return mon.ret(ar); \n }\n console.log(\'The value provided to spliceAdd is not an array\');\n return ret(x);\n };\n '); var cleanup = (0, _dom.h)('pre', ' function cleanup (x) {\n let target0 = document.getElementById(\'0\');\n let target1 = document.getElementById(\'1\');\n let target2 = document.getElementById(\'2\');\n let target3 = document.getElementById(\'3\');\n let targetAr = [target0, target1, target2, target3];\n for (let i in [0,1,2,3]) {\n if (targetAr[i].innerHTML == \'undefined\' ) {\n targetAr[i].style.display = \'none\';\n }\n else {\n targetAr[i].style.display = \'inline\';\n }\n }\n return ret(x);\n }; '); var travel = (0, _dom.h)('pre', ' const forwardClick$ = sources.DOM\n .select(\'#forward2\').events(\'click\');\n \n const backClick$ = sources.DOM\n .select(\'#back2\').events(\'click\');\n \n const forwardClickAction$ = forwardClick$.map(() => {\n if (O.mMindex2.x < (O.mMhistorymM1.x.length - 1)) {\n inc(O.mMindex2.x, mMindex2)\n .bnd(() => mM$3.ret(\'Hello\'))\n }\n });\n \n const backClickAction$ = backClick$.map(() => {\n if (O.mMindex2.x > 0) {\n dec(O.mMindex2.x, mMindex2)\n .bnd(() => mM$3.ret(\'You bet!\'))\n }\n });\n\n const mM$3Action$ = mM$3.stream.map(v => {\n document.getElementById(\'0\').innerHTML = (O.mMhistorymM1.x[O.mMindex2.x])[0]; \n document.getElementById(\'1\').innerHTML = (O.mMhistorymM1.x[O.mMindex2.x])[1]; \n document.getElementById(\'2\').innerHTML = (O.mMhistorymM1.x[O.mMindex2.x])[2]; \n document.getElementById(\'3\').innerHTML = (O.mMhistorymM1.x[O.mMindex2.x])[3]; \n cleanup();\n }) '); var C42 = (0, _dom.h)('pre', ' mMZ10.bnd(() => mM$1\n .ret([O.mMar.x[3], O.mMar.x[4], O.mMar.x[5], O.mMar.x[6]])\n .bnd(() => mM$2.ret([]))\n .bnd(displayInline,\'0\')\n .bnd(displayInline,\'1\')\n .bnd(displayInline,\'2\')\n .bnd(displayInline,\'3\')); '); var taskStream = (0, _dom.h)('pre', ' \n }); '); var deleteTask2 = (0, _dom.h)('pre', ' mMZ19.bnd(() => O.mM$task.bnd(spliceRemove, O.mMar.x[3], mM$task));\n '); var newTask = (0, _dom.h)('pre', ' const newTask$ = sources.DOM\n .select(\'input.newTask\').events(\'keydown\'); \n\n const newTaskAction$ = newTask$.map(e => {\n let ob = {};\n var alert = \'\';\n var ar = e.target.value.split(\',\');\n var ar2 = ar.slice(2);\n var task = \'\';\n if (ar.length < 4) {\n task = ar[2];\n }\n if (ar.length > 3) {\n task = ar2.reduce((a,b) => a + \'$*$*$\' + b);\n }\n if( e.keyCode == 13 ) {\n if ( ar.length < 3 ) {\n alert = \'You should enter "author, responsible party, task" separated by commas\';\n document.getElementById(\'alert\').innerHTML = alert;\n }\n\n else if ( (O.mMar2.x.filter(v => (v.task == task)).length) > 0 ) {\n document.getElementById(\'alert\').innerHTML = task + " is already listed.";\n }\n\n else if ( ar.length > 2 ) {\n O.mM$taskList.bnd(addString, task + \',yellow, none, false,\' + ar[0] + \',\' + ar[1], mM$taskList);\n e.target.value = \'\';\n document.getElementById(\'alert\').innerHTML = \'\';\n } \n } \n }; '); var process = (0, _dom.h)('pre', ' const process = function(str) {\n let a = str.split(",");\n console.log(\'In process. str and a are: \', str, a);\n if (a == undefined) {\n return;\n };\n if (a.length < 9) {\n return\n };\n let ob = {};\n let ar = a.slice(3)\n let s = ar.reduce((a,b) => a + \',\' + b);\n if (mM$taskList.x.length < 5) {\n O.mM$taskList.ret(s);\n }\n let ar2 = [];\n let tempArray = [];\n if (ar.length < 6) {return};\n if ((ar.length % 6) !== 0) {\n document.getElementById(\'alert\').innerHTML = \'Error: array length is: \' + length;\n } else {\n let keys = Array(ar.length/6).fill(1);\n keys.map(_ => {\n ar2.push(\n {\n task: convertBack(ar.shift()),\n color: ar.shift(),\n textDecoration: ar.shift(),\n checked: ar.shift() === \'true\',\n author: ar.shift(),\n responsible: ar.shift()\n }\n )\n })\n console.log(\'In process ar2 is: \', ar2)\n let keys2 = Object.keys(ar2);\n for (let k in keys) {\n tempArray.push(\n h(\'div.todo\', [\n h(\'span.task3\', {style: {color: ar2[k].color, textDecoration: ar2[k].textDecoration}},\n \'Task: \' + ar2[k].task ), \n h(\'br\'),\n h(\'button#edit1\', \'Edit\' ),\n h(\'input#edit2\', {props: {type: \'textarea\', value: ar2[k].task}, style: {display: \'none\'}} ), \n h(\'span#author.tao\', \'Author: \' + ar2[k].author + \' / \' + \'Responsibility: \' + ar2[k].responsible),\n h(\'br\'),\n h(\'input#cb\', {props: {type: \'checkbox\', checked: ar2[k].checked}, style: {color: ar2[k].color,\n textDecoration: ar2[k].textDecoration} } ), \n h(\'label.cbox\', { props: {for: \'#cb\'}}, \'Completed\' ),\n h(\'button.delete\', \'Delete\' ), \n h(\'br\'),\n h(\'hr\')])\n )\n }\n mMtaskList.ret(tempArray)\n }\n }; '); var colorClick = (0, _dom.h)('pre', ' const colorClick$ = sources.DOM\n .select(\'#cb\').events(\'click\')\n \n const colorAction$ = colorClick$.map(e => {\n let index = getIndex(e);\n let s = O.mM$taskList.x;\n let ar = s.split(\',\');\n let n = 6 * index + 3;\n let j = 6 * index + 2;\n let k = 6 * index + 1;\n let checked = ar[n];\n if (checked == \'true\') {\n ar[n] = \'false\'; \n ar[k] = \'yellow\'; \n ar[j] = \'none\'; \n }\n else {\n ar[n] = \'true\'; \n ar[k] = \'lightGreen\'; \n ar[j] = \'line-through\'; \n }\n mM$taskList.ret( ar.reduce((a,b) => a + \',\' + b) )\n }); \n \n var getIndex = function getIndex (event_object) {\n var task = event_object.currentTarget.parentNode.innerText;\n var possibilities = event_object.currentTarget.parentNode.parentNode.childNodes;\n var keys = Object.keys(possibilities);\n for (let k in keys) {\n if (task == possibilities[k].innerText) {\n return k\n }\n }\n console.log(\'In getIndex. No match\');\n } '); var edit = (0, _dom.h)('pre', ' const edit1$ = sources.DOM\n .select(\'#edit1\').events(\'click\')\n \n const edit1Action$ = edit1$.map(e => {\n let index = getIndex2(e);\n O.mMtaskList.x[index].children[3].elm.style.display = \'block\';\n });\n\n const edit2$ = sources.DOM\n .select(\'#edit2\').events(\'keypress\')\n \n const edit2Action$ = edit2$.map(e => {\n let v = e.target.value;\n let index = getIndex2(e);\n if( e.keyCode == 13 ) {\n process2(v, index);\n O.mMtaskList.x[index].children[3].elm.style.display = \'none\';\n }\n });\n\n const process2 = function(str, index) {\n let a = O.mM$taskList.x;\n let ar = a.split(\',\');\n let task = str.split(\',\').reduce((a,b) => ar + \'$*$*$\' + b)\n ar[index * 6] = task;\n let s = ar.reduce((a,b) => a + \',\' + b);\n mM$taskList.ret(s);\n };\n\n var getIndex2 = function getIndex2 (e) {\n var elem = e.currentTarget.parentNode.children[0].innerHTML\n var elem2 = e.currentTarget.parentNode.parentNode.childNodes\n var keys = Object.keys(elem2);\n for (let k in keys) {\n if (elem == elem2[k].childNodes[0].innerHTML) {\n return k\n }\n console.log(\'In getIndex2. No match\');\n }\n } '); var mM$task = (0, _dom.h)('pre', ' const taskAction$ = mM$taskList.stream.map(str => {\n socket.send(\'TD#$42\' + \',\' + O.mMgroup.x.trim() + \n \',\' + O.mMname.x.trim() + \',\' + \'@\' + str);\n }); '); var updateCalc = (0, _dom.h)('pre', ' function updateCalc() { \n O.mM3.bnd(ar => mM7 // O.mM3 contributes O.mM3.x to the computation.\n .ret(calc(ar[0], O.mM8.x, ar[1])) // O.mM8.x is the operator string.\n .bnd(result => // The return value of calc(), which is O.mM7.x, is used three times.\n { O.mM1.bnd(push, result, mM1).bnd(z =>\n mM$1.ret(z)); // Updates the display. \n if (result == 20) {score(O.mM13.x, 1)}; \n if (result == 18) {score(O.mM13.x, 3)};\n }\n )) \n reset()\n };\n\n var score = function score(x,j) {\n if ((x + j) == 20) {\n mMgoals.ret(O.mMgoals.x == 2 ? 0 : (O.mMgoals.x + 1)); \n mM13.ret(0).bnd(mMindex.ret);\n mMhistorymM1.ret([[0,0,0,0]]);\n socket.send(\'CG#$42,\' + O.mMgroup.x + \',\' + O.mMname.x + \',\' + -x + \',\' + O.mMgoals.x); \n if (O.mMgoals.x == 0) {\n socket.send(\'CE#$42,\' + O.mMgroup.x + \',\' + O.mMname.x + \',nothing \');\n }\n socket.send(\'CA#$42,\' + O.mMgroup.x.trim() + \',\' + O.mMname.x.trim() + \',6,6,12,20\');\n return;\n }\n if ((x + j) % 5 == 0) {\n socket.send(\'CG#$42,\' + O.mMgroup.x + \',\' + O.mMname.x + \',\'+ (j+5)+\',\' + O.mMgoals.x); \n mM13.ret(x + j + 5);\n socket.send(\'CA#$42,\' + O.mMgroup.x.trim() + \',\' + O.mMname.x.trim() + \',6,6,12,20\');\n return;\n } \n socket.send(\'CG#$42,\' + O.mMgroup.x + \',\' + O.mMname.x + \',\'+j+\',\' + O.mMgoals.x); \n mM13.ret(x + j);\n socket.send(\'CA#$42,\' + O.mMgroup.x.trim() + \',\' + O.mMname.x.trim() + \',6,6,12,20\');\n }\n\n var reset = function reset () {\n mM3.ret([])\n .bnd(() => mM4.ret(0)\n .bnd(mM8.ret)\n .bnd(cleanup)) // Hides \'undefined\' values in the display.\n }\n\n var updateScoreboard = function updateScoreboard(v) { // v is received from the server.\n let ar2 = v.split("<br>");\n let ar = ar.slice();\n return mMscoreboard.ret(ar);\n }; '); var testZ = (0, _dom.h)('pre', ' mMZ1.bnd(v => O.mMt1.bnd(add,v,mMt1)\n .bnd(cube,mMt2)\n .bnd(() => mMt3.ret(O.mMt1.x + \' cubed is \' + O.mMt2.x))) \n \n mMZ2.bnd(v => cube(v).bnd(w => mMt3.ret(v + \' cubed is \' + w))) '); var quad = (0, _dom.h)('pre', ' const quad$ = sources.DOM\n .select(\'#quad\').events(\'keypress\') // Motorcycle way to get user input.\n \n const quadAction$ = quad$.map((e) => {\n if( e.keyCode == 13 ) {\n mMZ3.release(e.target.value) // Releases mMZ (below).\n document.getElementById(\'quad\').value = \'\';\n }\n });\n\n var solve = function solve () {\n mMZ3.bnd(a => \n mMtemp.ret(a) \n .bnd(innerHTML, \'\', \'quad6\', mMtemp) \n .bnd(innerHTML, a + " * x * x ", \'quad5\', mMtemp)\n .bnd(a =>\n mMZ3.bnd(b => mMtemp.ret(b)\n .bnd(innerHTML, " + " + b + " * x ", \'quad6\', mMtemp).bnd(b =>\n mMZ3.bnd(c => {\n let x = qS1(a,b,c);\n let y = qS2(a,b,c); \n document.getElementById(\'quad5\').innerHTML = \n \'The results are: x = \' + x + \' and x =\';\n document.getElementById(\'quad6\').innerHTML = y; \n solve();\n })))))\n }();\n\n var qS1 = function qS1 (a, b, c) {\n let n = (b*(-1)) + (Math.sqrt(b*b - 4*a*c));\n if (n != n) {\n return "No solution";\n }\n return n/(2*a);\n }\n\n var qS2 = function qS2 (a, b, c) {\n let n = (b*(-1)) - (Math.sqrt(b*b - 4*a*c));\n if (n != n) {\n return "No solution";\n }\n return n/(2*a);\n \n var innerHTML = function innerHTML (x, v, u, m) { \n document.getElementById(u).innerHTML = v;\n return m.ret(x);\n } '); var mdem1 = (0, _dom.h)('pre', ' var equals = function equals (x, mon1, mon2, mon3) {\n if (mon1.id === mon2.id && mon1.x === mon2.x) {\n mon3.ret(\'true\');\n } else mon3.ret(\'false\');\n return ret(x);\n }\n \n var add = function(x,b,mon) {\n if (arguments.length === 3) {\n return mon.ret(x + b);\n }\n return ret(x+b);\n }\n\n var cube = function(v,mon) {\n if (arguments.length === 2) {\n return mon.ret(v*v*v);\n }\n return ret(v*v*v);\n } '); var runTest = (0, _dom.h)('pre', ' var runTest = function monTest () {\n mM5.bnd( equals, \n m.ret(0).bnd(v => add(v, 3, m).bnd(cube)), \n m.ret(0).bnd(add, 3, m).bnd(cube), mMa)\n\n mM5.bnd(equals, m, m.bnd(m.ret), mMb)\n\n mM5.bnd(equals, m, m.ret(m.x), mMc)\n } '); var inc = (0, _dom.h)('pre', ' var inc = function inc(x, mon) {\n return mon.ret(x + 1);\n };\n\n var spliceAdd = function spliceAdd(x, index, value, mon) {\n if (Array.isArray(x)) {\n let ar = [];\n let keys = Object.keys(x);\n for (let k in keys) {ar[k] = x[k]};\n ar.splice(index, 0, value);\n return mon.ret(ar); \n }\n console.log(\'The value provided to spliceAdd is not an array\');\n return ret(x);\n } '); var todoStream = (0, _dom.h)('pre', ' const taskAction$ = mM$taskList.stream.map(str => {\n socket.send(\'TD#$42\' + \',\' + O.mMgroup.x.trim() + \n \',\' + O.mMname.x.trim() + \',\' + \'@\' + str);\n }); '); var p3 = (0, _dom.h)('pre', ' \n '); var p4 = (0, _dom.h)('pre', ' \n '); var p5 = (0, _dom.h)('pre', ' \n '); var add = (0, _dom.h)('pre', ' var add = function(x,b,mon) {\n if (arguments.length === 3) {\n return mon.ret(x + b);\n }\n return ret(x+b); \n }; '); var ret_add_cube = (0, _dom.h)('pre', ' var ret = function ret(v, id) {\n if (arguments.length === 1) {\n return (new Monad(v, \'anonymous\'));\n }\n window[id] = new Monad(v, id);\n return window[id];\n } \n\n var add = function(x,b,mon) {\n if (arguments.length === 3) {\n return mon.ret(x + b);\n }\n return ret(x+b);\n };\n\n var cube = function(v,mon) {\n if (arguments.length === 2) {\n return mon.ret(v*v*v);\n }\n return ret(v*v*v);\n} '); var seed = (0, _dom.h)('pre', ' mM$prime.ret([[2],3]) '); var traverse = (0, _dom.h)('pre', ' \n const forwardClick$ = sources.DOM\n .select(\'#forward\').events(\'click\');\n\n const backClick$ = sources.DOM\n .select(\'#back\').events(\'click\');\n\n const forwardAction$ = forwardClick$.map(() => {\n if (O.mMindex.x < (O.mMhistorymM1.x.length - 1)) {\n O.mMindex.bnd(add, 1, mMindex)\n .bnd(mM$3.ret)\n }\n });\n\n const backAction$ = backClick$.map(() => {\n if (O.mMindex.x > 0) {\n O.mMindex.bnd(add, -1, mMindex)\n .bnd(mM$3.ret)\n socket.send(\'DE#$42,\' + O.mMgroup.x.trim() + \',\' + O.mMname.x.trim() + \', clicked the BACK button. \');\n }\n });\n\n var game = function game (v) {\n mM1.ret(v);\n O.mMindex.bnd(add, 1, mMindex)\n .bnd(i => O.mMhistorymM1.bnd(spliceAdd, i, O.mM1, O.mMhistorymM1))\n document.getElementById(\'0\').innerHTML = O.mM1.x[0]; \n document.getElementById(\'1\').innerHTML = O.mM1.x[1]; \n document.getElementById(\'2\').innerHTML = O.mM1.x[2]; \n document.getElementById(\'3\').innerHTML = O.mM1.x[3]; \n cleanup()\n };\n\n var trav = function trav (v) {\n document.getElementById(\'0\').innerHTML = (O.mMhistorymM1.x[v].x)[0]; \n document.getElementById(\'1\').innerHTML = (O.mMhistorymM1.x[v].x)[1]; \n document.getElementById(\'2\').innerHTML = (O.mMhistorymM1.x[v].x)[2]; \n document.getElementById(\'3\').innerHTML = (O.mMhistorymM1.x[v].x)[3]; \n cleanup();\n } '); var MonadState = (0, _dom.h)('pre', ' var MonadState = function MonadState (g, state, value, p) {\n var _this = this;\n this.id = g;\n this.s = state;\n this.a = value;\n this.process = p;\n this.bnd = function (func, ...args) {\n return func(_this.s, ...args); // bnd provides instances\' state to func.\n };\n this.run = function(st) { \n let s = _this.process(st); \n let a = s[3];\n window[_this.id] = new MonadState(_this.id, s, a, _this.process);\n return window[_this.id];\n }\n } '); var primesMonad = (0, _dom.h)('pre', ' var primesMonad = new MonadState(\'primesMonad\', [2, \'\', 3, [2]], [2], primes_state) \n\n var primes_state = function primes_state(x) {\n var v = x.slice();\n while (2 == 2) {\n if (v[3].every(e => ((v[0]/e) != Math.floor(v[0]/e)))) {\n v[3].push(v[0]);\n }\n if (v[3][v[3].length - 1] > v[2]) { break }; // Not an infinite loop afterall\n v[0]+=2;\n }\n return v;\n } '); var fibsMonad = (0, _dom.h)('pre', ' var fibsMonad = new MonadState(\'fibsMonad\', [0, 1, 3, [0,1]], [0,1], fibs_state ) \n\n var fibs_state = function fibs_state(ar) {\n var a = ar.slice();\n while (a[3].length < a[2]) {\n a = [a[1], a[0] + a[1], a[2], a[3].concat(a[0])];\n }\n return a\n } '); var tr3 = (0, _dom.h)('pre', ' var tr3 = function tr (fibsArray, primesArray) {\n var bound = Math.ceil(Math.sqrt(fibsArray[fibsArray.length - 1]))\n var primes;\n if (primesArray[primesArray.length - 1] >= bound) {\n primes = primesArray.filter(v => v <= bound);\n } \n else {primes = primesArray.slice()};\n var ar = [];\n var fibs = fibsArray.slice(3);\n fibs.map (f => {\n if ( primesArray.every(p => (f % p != 0 || f == p))) ar.push(f);\n })\n return [fibsArray, primes, ar]\n } '); var primeFibInterface = (0, _dom.h)('pre', ' const fibKeyPress5$ = sources.DOM\n .select(\'input#fib92\').events(\'keydown\');\n\n const primeFib$ = fibKeyPress5$.map(e => {\n if( e.keyCode == 13 ) {\n var res = fibsMonad\n .run([0, 1, e.target.value, []])\n .bnd(fibsState => fibsMonad\n .bnd(fpTransformer, primesMonad)\n .bnd(primesState => tr3(fibsState[3],primesState[3])))\n document.getElementById(\'PF_9\').innerHTML = res[0];\n document.getElementById(\'PF_22\').innerHTML = res[1];\n document.getElementById(\'primeFibs\').innerHTML = res[2];\n }\n }); '); var fpTransformer = (0, _dom.h)('pre', ' var fpTransformer = function fpTransformer (s, m) {\n var bound = Math.ceil(Math.sqrt(s[3][s[3].length - 1]));\n if (bound > m.a[m.a.length - 1] ) {\n m.run([m.s[0], "from the fibKeyPress5$ handler", bound, primesMonad.a])\n }\n return m;\n } '); var innerHTML = (0, _dom.h)('pre', ' var innerHTML = function innerHTML (x, v, u, m) { \n document.getElementById(u).innerHTML = v;\n return m.ret(x);\n } '); var seed2 = (0, _dom.h)('pre', ' \n '); exports.default = { monad: monad, monadIt: monadIt, fib: fib, driver: driver, messages: messages, next: next, Monad$: Monad$, updateCalc: updateCalc, arrayFuncs: arrayFuncs, travel: travel, nums: nums, cleanup: cleanup, ret: ret, C42: C42, taskStream: taskStream, newTask: newTask, process: process, mM$task: mM$task, addString: addString, colorClick: colorClick, edit: edit, testZ: testZ, quad: quad, mdem1: mdem1, runTest: runTest, todoStream: todoStream, inc: inc, ret_add_cube: ret_add_cube, seed: seed, add: add, traverse: traverse, MonadState: MonadState, primesMonad: primesMonad, fibsMonad: fibsMonad, primeFibInterface: primeFibInterface, tr3: tr3, fpTransformer: fpTransformer, innerHTML: innerHTML }; /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;'use strict'; (function (global, factory) { if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [exports, __webpack_require__(4)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (typeof exports !== "undefined") { factory(exports, require('most')); } else { var mod = { exports: {} }; factory(mod.exports, global.most); global.mostDomEvent = mod.exports; } })(undefined, function (exports, _most) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.touchcancel = exports.touchmove = exports.touchend = exports.touchstart = exports.pointerleave = exports.pointerout = exports.pointerenter = exports.pointerover = exports.pointermove = exports.pointerup = exports.pointerdown = exports.unload = exports.load = exports.popstate = exports.hashchange = exports.error = exports.scroll = exports.resize = exports.contextmenu = exports.input = exports.keyup = exports.keypress = exports.keydown = exports.submit = exports.select = exports.change = exports.mouseleave = exports.mouseout = exports.mouseenter = exports.mouseover = exports.mousemove = exports.mouseup = exports.mousedown = exports.dblclick = exports.click = exports.focusout = exports.focusin = exports.focus = exports.blur = exports.domEvent = undefined; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var domEvent = function domEvent(event, node) { var capture = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2]; return new _most.Stream(new DomEvent(event, node, capture)); }; var blur = function blur(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('blur', node, capture); }; var focus = function focus(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('focus', node, capture); }; var focusin = function focusin(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('focusin', node, capture); }; var focusout = function focusout(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('focusout', node, capture); }; var click = function click(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('click', node, capture); }; var dblclick = function dblclick(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('dblclick', node, capture); }; var mousedown = function mousedown(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('mousedown', node, capture); }; var mouseup = function mouseup(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('mouseup', node, capture); }; var mousemove = function mousemove(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('mousemove', node, capture); }; var mouseover = function mouseover(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('mouseover', node, capture); }; var mouseenter = function mouseenter(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('mouseenter', node, capture); }; var mouseout = function mouseout(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('mouseout', node, capture); }; var mouseleave = function mouseleave(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('mouseleave', node, capture); }; var change = function change(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('change', node, capture); }; var select = function select(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('select', node, capture); }; var submit = function submit(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('submit', node, capture); }; var keydown = function keydown(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('keydown', node, capture); }; var keypress = function keypress(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('keypress', node, capture); }; var keyup = function keyup(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('keyup', node, capture); }; var input = function input(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('input', node, capture); }; var contextmenu = function contextmenu(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('contextmenu', node, capture); }; var resize = function resize(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('resize', node, capture); }; var scroll = function scroll(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('scroll', node, capture); }; var error = function error(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('error', node, capture); }; var hashchange = function hashchange(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('hashchange', node, capture); }; var popstate = function popstate(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('popstate', node, capture); }; var load = function load(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('load', node, capture); }; var unload = function unload(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('unload', node, capture); }; var pointerdown = function pointerdown(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('pointerdown', node, capture); }; var pointerup = function pointerup(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('pointerup', node, capture); }; var pointermove = function pointermove(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('pointermove', node, capture); }; var pointerover = function pointerover(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('pointerover', node, capture); }; var pointerenter = function pointerenter(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('pointerenter', node, capture); }; var pointerout = function pointerout(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('pointerout', node, capture); }; var pointerleave = function pointerleave(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('pointerleave', node, capture); }; var touchstart = function touchstart(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('touchstart', node, capture); }; var touchend = function touchend(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('touchend', node, capture); }; var touchmove = function touchmove(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('touchmove', node, capture); }; var touchcancel = function touchcancel(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('touchcancel', node, capture); }; var DomEvent = function () { function DomEvent(event, node, capture) { _classCallCheck(this, DomEvent); this.event = event; this.node = node; this.capture = capture; } _createClass(DomEvent, [{ key: 'run', value: function run(sink, scheduler) { var _this = this; var send = function send(e) { return tryEvent(scheduler.now(), e, sink); }; var dispose = function dispose() { return _this.node.removeEventListener(_this.event, send, _this.capture); }; this.node.addEventListener(this.event, send, this.capture); return { dispose: dispose }; } }]); return DomEvent; }(); function tryEvent(t, x, sink) { try { sink.event(t, x); } catch (e) { sink.error(t, e); } } exports.domEvent = domEvent; exports.blur = blur; exports.focus = focus; exports.focusin = focusin; exports.focusout = focusout; exports.click = click; exports.dblclick = dblclick; exports.mousedown = mousedown; exports.mouseup = mouseup; exports.mousemove = mousemove; exports.mouseover = mouseover; exports.mouseenter = mouseenter; exports.mouseout = mouseout; exports.mouseleave = mouseleave; exports.change = change; exports.select = select; exports.submit = submit; exports.keydown = keydown; exports.keypress = keypress; exports.keyup = keyup; exports.input = input; exports.contextmenu = contextmenu; exports.resize = resize; exports.scroll = scroll; exports.error = error; exports.hashchange = hashchange; exports.popstate = popstate; exports.load = load; exports.unload = unload; exports.pointerdown = pointerdown; exports.pointerup = pointerup; exports.pointermove = pointermove; exports.pointerover = pointerover; exports.pointerenter = pointerenter; exports.pointerout = pointerout; exports.pointerleave = pointerleave; exports.touchstart = touchstart; exports.touchend = touchend; exports.touchmove = touchmove; exports.touchcancel = touchcancel; }); /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;'use strict'; (function (global, factory) { if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [exports, __webpack_require__(5)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (typeof exports !== "undefined") { factory(exports, require('@most/multicast')); } else { var mod = { exports: {} }; factory(mod.exports, global.multicast); global.mostHold = mod.exports; } })(undefined, function (exports, _multicast) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); // hold :: Stream a -> Stream a var index = function index(stream) { return new stream.constructor(new _multicast.MulticastSource(new Hold(stream.source))); }; var Hold = function () { function Hold(source) { _classCallCheck(this, Hold); this.source = source; this.time = -Infinity; this.value = void 0; } _createClass(Hold, [{ key: 'run', value: function run(sink, scheduler) { /* istanbul ignore else */ if (sink._hold !== this) { sink._hold = this; sink._holdAdd = sink.add; sink.add = holdAdd; sink._holdEvent = sink.event; sink.event = holdEvent; } return this.source.run(sink, scheduler); } }]); return Hold; }(); function holdAdd(sink) { var len = this._holdAdd(sink); /* istanbul ignore else */ if (this._hold.time >= 0) { sink.event(this._hold.time, this._hold.value); } return len; } function holdEvent(t, x) { /* istanbul ignore else */ if (t >= this._hold.time) { this._hold.time = t; this._hold.value = x; } return this._holdEvent(t, x); } exports.default = index; }); /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _vnode = __webpack_require__(15); var _vnode2 = _interopRequireDefault(_vnode); var _is = __webpack_require__(10); var _is2 = _interopRequireDefault(_is); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var isObservable = function isObservable(x) { return typeof x.observe === 'function'; }; var addNSToObservable = function addNSToObservable(vNode) { addNS(vNode.data, vNode.children); // eslint-disable-line }; function addNS(data, children) { data.ns = 'http://www.w3.org/2000/svg'; if (typeof children !== 'undefined' && _is2.default.array(children)) { for (var i = 0; i < children.length; ++i) { if (isObservable(children[i])) { children[i] = children[i].tap(addNSToObservable); } else { addNS(children[i].data, children[i].children); } } } } /* eslint-disable */ function h(sel, b, c) { var data = {}; var children = void 0; var text = void 0; var i = void 0; if (arguments.length === 3) { data = b; if (_is2.default.array(c)) { children = c; } else if (_is2.default.primitive(c)) { text = c; } } else if (arguments.length === 2) { if (_is2.default.array(b)) { children = b; } else if (_is2.default.primitive(b)) { text = b; } else { data = b; } } if (_is2.default.array(children)) { for (i = 0; i < children.length; ++i) { if (_is2.default.primitive(children[i])) { children[i] = (0, _vnode2.default)(undefined, undefined, undefined, children[i]); } } } if (sel[0] === 's' && sel[1] === 'v' && sel[2] === 'g') { addNS(data, children); } return (0, _vnode2.default)(sel, data || {}, children, text, undefined); } /* eslint-enable */ exports.default = h; /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.makeDOMDriver = undefined; var _most = __webpack_require__(4); var _hold = __webpack_require__(40); var _hold2 = _interopRequireDefault(_hold); var _snabbdom = __webpack_require__(100); var _h = __webpack_require__(36); var _h2 = _interopRequireDefault(_h); var _classNameFromVNode = __webpack_require__(92); var _classNameFromVNode2 = _interopRequireDefault(_classNameFromVNode); var _selectorParser2 = __webpack_require__(35); var _selectorParser3 = _interopRequireDefault(_selectorParser2); var _utils = __webpack_require__(22); var _modules = __webpack_require__(21); var _modules2 = _interopRequireDefault(_modules); var _transposition = __webpack_require__(45); var _isolate = __webpack_require__(19); var _select = __webpack_require__(44); var _events = __webpack_require__(18); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function makeVNodeWrapper(rootElement) { return function vNodeWrapper(vNode) { var _selectorParser = (0, _selectorParser3.default)(vNode.sel); var selectorTagName = _selectorParser.tagName; var selectorId = _selectorParser.id; var vNodeClassName = (0, _classNameFromVNode2.default)(vNode); var _vNode$data = vNode.data; var vNodeData = _vNode$data === undefined ? {} : _vNode$data; var _vNodeData$props = vNodeData.props; var vNodeDataProps = _vNodeData$props === undefined ? {} : _vNodeData$props; var _vNodeDataProps$id = vNodeDataProps.id; var vNodeId = _vNodeDataProps$id === undefined ? selectorId : _vNodeDataProps$id; var isVNodeAndRootElementIdentical = vNodeId.toUpperCase() === rootElement.id.toUpperCase() && selectorTagName.toUpperCase() === rootElement.tagName.toUpperCase() && vNodeClassName.toUpperCase() === rootElement.className.toUpperCase(); if (isVNodeAndRootElementIdentical) { return vNode; } var tagName = rootElement.tagName; var id = rootElement.id; var className = rootElement.className; var elementId = id ? '#' + id : ''; var elementClassName = className ? '.' + className.split(' ').join('.') : ''; return (0, _h2.default)('' + tagName + elementId + elementClassName, {}, [vNode]); }; } function DOMDriverInputGuard(view$) { if (!view$ || typeof view$.observe !== 'function') { throw new Error('The DOM driver function expects as input an ' + 'Observable of virtual DOM elements'); } } function defaultOnErrorFn(msg) { if (console && console.error) { console.error(msg); } else { console.log(msg); } } var defaults = { modules: _modules2.default, onError: defaultOnErrorFn }; function makeDOMDriver(container) { var _ref = arguments.length <= 1 || arguments[1] === undefined ? defaults : arguments[1]; var _ref$modules = _ref.modules; var modules = _ref$modules === undefined ? _modules2.default : _ref$modules; var _ref$onError = _ref.onError; var onError = _ref$onError === undefined ? defaultOnErrorFn : _ref$onError; var patch = (0, _snabbdom.init)(modules); var rootElement = (0, _utils.domSelectorParser)(container); if (!Array.isArray(modules)) { throw new Error('Optional modules option must be ' + 'an array for snabbdom modules'); } if (typeof onError !== 'function') { throw new Error('Optional onError opition must be ' + 'a function to approriately handle your errors'); } function DOMDriver(view$) { DOMDriverInputGuard(view$); var rootElement$ = (0, _hold2.default)(view$.map(_transposition.transposeVTree).switch().map(makeVNodeWrapper(rootElement)).scan(patch, rootElement).skip(1).recoverWith(function (err) { onError(err); return (0, _most.throwError)(err); }).map(function (_ref2) { var elm = _ref2.elm; return elm; })); rootElement$.drain(); return { observable: rootElement$, namespace: [], select: (0, _select.makeElementSelector)(rootElement$), events: (0, _events.makeEventsSelector)(rootElement$), isolateSink: _isolate.isolateSink, isolateSource: _isolate.isolateSource }; } return DOMDriver; } exports.makeDOMDriver = makeDOMDriver; /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.mockDOMSource = undefined; var _most = __webpack_require__(4); var _most2 = _interopRequireDefault(_most); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var emptyStream = _most2.default.empty(); function getEventsStreamForSelector(mockedEventTypes) { return function getEventsStream(eventType) { for (var key in mockedEventTypes) { if (mockedEventTypes.hasOwnProperty(key) && key === eventType) { return mockedEventTypes[key]; } } return emptyStream; }; } function makeMockSelector(mockedSelectors) { return function select(selector) { for (var key in mockedSelectors) { if (mockedSelectors.hasOwnProperty(key) && key === selector) { var observable = emptyStream; if (mockedSelectors[key].hasOwnProperty('observable')) { observable = mockedSelectors[key].observable; } return { observable: observable, select: makeMockSelector(mockedSelectors[key]), events: getEventsStreamForSelector(mockedSelectors[key]) }; } } return { observable: emptyStream, select: makeMockSelector(mockedSelectors), events: function events() { return emptyStream; } }; }; } function mockDOMSource() { var mockedSelectors = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; return { observable: emptyStream, select: makeMockSelector(mockedSelectors), events: function events() { return emptyStream; } }; } exports.mockDOMSource = mockDOMSource; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.makeIsStrictlyInRootScope = exports.makeElementSelector = undefined; var _makeIsStrictlyInRootScope = __webpack_require__(20); var _events = __webpack_require__(18); var _isolate = __webpack_require__(19); var isValidString = function isValidString(param) { return typeof param === 'string' && param.length > 0; }; var contains = function contains(str, match) { return str.indexOf(match) > -1; }; var isNotTagName = function isNotTagName(param) { return isValidString(param) && contains(param, '.') || contains(param, '#') || contains(param, ':'); }; function sortNamespace(a, b) { if (isNotTagName(a) && isNotTagName(b)) { return 0; } return isNotTagName(a) ? 1 : -1; } function removeDuplicates(arr) { var newArray = []; arr.forEach(function (element) { if (newArray.indexOf(element) === -1) { newArray.push(element); } }); return newArray; } var getScope = function getScope(namespace) { return namespace.filter(function (c) { return c.indexOf('.cycle-scope') > -1; }); }; function makeFindElements(namespace) { return function findElements(rootElement) { if (namespace.join('') === '') { return rootElement; } var slice = Array.prototype.slice; var scope = getScope(namespace); // Uses global selector && is isolated if (namespace.indexOf('*') > -1 && scope.length > 0) { // grab top-level boundary of scope var topNode = rootElement.querySelector(scope.join(' ')); // grab all children var childNodes = topNode.getElementsByTagName('*'); return removeDuplicates([topNode].concat(slice.call(childNodes))).filter((0, _makeIsStrictlyInRootScope.makeIsStrictlyInRootScope)(namespace)); } return removeDuplicates(slice.call(rootElement.querySelectorAll(namespace.join(' '))).concat(slice.call(rootElement.querySelectorAll(namespace.join(''))))).filter((0, _makeIsStrictlyInRootScope.makeIsStrictlyInRootScope)(namespace)); }; } function makeElementSelector(rootElement$) { return function elementSelector(selector) { if (typeof selector !== 'string') { throw new Error('DOM driver\'s select() expects the argument to be a ' + 'string as a CSS selector'); } var namespace = this.namespace; var trimmedSelector = selector.trim(); var childNamespace = trimmedSelector === ':root' ? namespace : namespace.concat(trimmedSelector).sort(sortNamespace); return { observable: rootElement$.map(makeFindElements(childNamespace)), namespace: childNamespace, select: makeElementSelector(rootElement$), events: (0, _events.makeEventsSelector)(rootElement$, childNamespace), isolateSource: _isolate.isolateSource, isolateSink: _isolate.isolateSink }; }; } exports.makeElementSelector = makeElementSelector; exports.makeIsStrictlyInRootScope = _makeIsStrictlyInRootScope.makeIsStrictlyInRootScope; /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.transposeVTree = undefined; var _most = __webpack_require__(4); var _most2 = _interopRequireDefault(_most); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function createVTree(vTree, children) { return { sel: vTree.sel, data: vTree.data, text: vTree.text, elm: vTree.elm, key: vTree.key, children: children }; } function transposeVTree(vTree) { if (!vTree) { return null; } else if (vTree && _typeof(vTree.data) === 'object' && vTree.data.static) { return _most2.default.just(vTree); } else if (typeof vTree.observe === 'function') { return vTree.map(transposeVTree).switch(); } else if ((typeof vTree === 'undefined' ? 'undefined' : _typeof(vTree)) === 'object') { if (!vTree.children || vTree.children.length === 0) { return _most2.default.just(vTree); } var vTreeChildren = vTree.children.map(transposeVTree).filter(function (x) { return x !== null; }); return vTreeChildren.length === 0 ? _most2.default.just(createVTree(vTree, vTreeChildren)) : _most2.default.combineArray(function () { for (var _len = arguments.length, children = Array(_len), _key = 0; _key < _len; _key++) { children[_key] = arguments[_key]; } return createVTree(vTree, children); }, vTreeChildren); } else { throw new Error('Unhandled vTree Value'); } } exports.transposeVTree = transposeVTree; /***/ }, /* 46 */ /***/ function(module, exports) { "use strict"; /*! * Cross-Browser Split 1.1.1 * Copyright 2007-2012 Steven Levithan <stevenlevithan.com> * Available under the MIT License * ECMAScript compliant, uniform cross-browser split method */ /** * Splits a string into an array of strings using a regex or string separator. Matches of the * separator are not included in the result array. However, if `separator` is a regex that contains * capturing groups, backreferences are spliced into the result each time `separator` is matched. * Fixes browser bugs compared to the native `String.prototype.split` and can be used reliably * cross-browser. * @param {String} str String to split. * @param {RegExp|String} separator Regex or string to use for separating the string. * @param {Number} [limit] Maximum number of items to include in the result array. * @returns {Array} Array of substrings. * @example * * // Basic use * split('a b c d', ' '); * // -> ['a', 'b', 'c', 'd'] * * // With limit * split('a b c d', ' ', 2); * // -> ['a', 'b'] * * // Backreferences in result array * split('..word1 word2..', /([a-z]+)(\d+)/i); * // -> ['..', 'word', '1', ' ', 'word', '2', '..'] */ module.exports = function split(undef) { var nativeSplit = String.prototype.split, compliantExecNpcg = /()??/.exec("")[1] === undef, // NPCG: nonparticipating capturing group self; self = function self(str, separator, limit) { // If `separator` is not a regex, use `nativeSplit` if (Object.prototype.toString.call(separator) !== "[object RegExp]") { return nativeSplit.call(str, separator, limit); } var output = [], flags = (separator.ignoreCase ? "i" : "") + (separator.multiline ? "m" : "") + (separator.extended ? "x" : "") + ( // Proposed for ES6 separator.sticky ? "y" : ""), // Firefox 3+ lastLastIndex = 0, // Make `global` and avoid `lastIndex` issues by working with a copy separator = new RegExp(separator.source, flags + "g"), separator2, match, lastIndex, lastLength; str += ""; // Type-convert if (!compliantExecNpcg) { // Doesn't need flags gy, but they don't hurt separator2 = new RegExp("^" + separator.source + "$(?!\\s)", flags); } /* Values for `limit`, per the spec: * If undefined: 4294967295 // Math.pow(2, 32) - 1 * If 0, Infinity, or NaN: 0 * If positive number: limit = Math.floor(limit); if (limit > 4294967295) limit -= 4294967296; * If negative number: 4294967296 - Math.floor(Math.abs(limit)) * If other: Type-convert, then use the above rules */ limit = limit === undef ? -1 >>> 0 : // Math.pow(2, 32) - 1 limit >>> 0; // ToUint32(limit) while (match = separator.exec(str)) { // `separator.lastIndex` is not reliable cross-browser lastIndex = match.index + match[0].length; if (lastIndex > lastLastIndex) { output.push(str.slice(lastLastIndex, match.index)); // Fix browsers whose `exec` methods don't consistently return `undefined` for // nonparticipating capturing groups if (!compliantExecNpcg && match.length > 1) { match[0].replace(separator2, function () { for (var i = 1; i < arguments.length - 2; i++) { if (arguments[i] === undef) { match[i] = undef; } } }); } if (match.length > 1 && match.index < str.length) { Array.prototype.push.apply(output, match.slice(1)); } lastLength = match[0].length; lastLastIndex = lastIndex; if (output.length >= limit) { break; } } if (separator.lastIndex === match.index) { separator.lastIndex++; // Avoid an infinite loop } } if (lastLastIndex === str.length) { if (lastLength || !separator.test("")) { output.push(""); } } else { output.push(str.slice(lastLastIndex)); } return output.length > limit ? output.slice(0, limit) : output; }; return self; }(); /***/ }, /* 47 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var isValidString = function isValidString(param) { return typeof param === 'string' && param.length > 0; }; var startsWith = function startsWith(string, start) { return string[0] === start; }; var isSelector = function isSelector(param) { return isValidString(param) && (startsWith(param, '.') || startsWith(param, '#')); }; var node = function node(h) { return function (tagName) { return function (first) { for (var _len = arguments.length, rest = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { rest[_key - 1] = arguments[_key]; } if (isSelector(first)) { return h.apply(undefined, [tagName + first].concat(rest)); } else { return h.apply(undefined, [tagName, first].concat(rest)); } }; }; }; var TAG_NAMES = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'dd', 'del', 'dfn', 'dir', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'menu', 'meta', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'p', 'param', 'pre', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'u', 'ul', 'video', 'progress']; exports['default'] = function (h) { var createTag = node(h); var exported = { TAG_NAMES: TAG_NAMES, isSelector: isSelector, createTag: createTag }; TAG_NAMES.forEach(function (n) { exported[n] = createTag(n); }); return exported; }; module.exports = exports['default']; /***/ }, /* 48 */ /***/ function(module, exports) { 'use strict'; var proto = Element.prototype; var vendor = proto.matches || proto.matchesSelector || proto.webkitMatchesSelector || proto.mozMatchesSelector || proto.msMatchesSelector || proto.oMatchesSelector; module.exports = match; /** * Match `el` to `selector`. * * @param {Element} el * @param {String} selector * @return {Boolean} * @api public */ function match(el, selector) { if (vendor) return vendor.call(el, selector); var nodes = el.parentNode.querySelectorAll(selector); for (var i = 0; i < nodes.length; i++) { if (nodes[i] == el) return true; } return false; } /***/ }, /* 49 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor); } }return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function tryEvent(sink, scheduler, event) { try { sink.event(scheduler.now(), event); } catch (err) { sink.error(scheduler.now(), err); } } function tryEnd(sink, scheduler, event) { try { sink.end(scheduler.now(), event); } catch (err) { sink.error(scheduler.now(), err); } } var Observer = function () { function Observer() { var _this = this; _classCallCheck(this, Observer); this.run = function (sink, scheduler) { return _this._run(sink, scheduler); }; this.next = function (x) { return _this._next(x); }; this.error = function (err) { return _this._error(err); }; this.complete = function (x) { return _this._complete(x); }; } _createClass(Observer, [{ key: "_run", value: function _run(sink, scheduler) { this.sink = sink; this.scheduler = scheduler; this.active = true; return this; } }, { key: "dispose", value: function dispose() { this.active = false; } }, { key: "_next", value: function _next(value) { if (!this.active) { return; } tryEvent(this.sink, this.scheduler, value); } }, { key: "_error", value: function _error(err) { this.active = false; this.sink.error(this.scheduler.now(), err); } }, { key: "_complete", value: function _complete(value) { if (!this.active) { return; } this.active = false; tryEnd(this.sink, this.scheduler, value); } }]); return Observer; }(); exports.Observer = Observer; /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.replay = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor); } }return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor; }; }(); var _most = __webpack_require__(4); var _multicast = __webpack_require__(5); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function pushEvents(sink, buffer) { var i = 0; for (; i < buffer.length; ++i) { var item = buffer[i]; sink.event(item.time, item.value); } } function replayAdd(sink) { var length = this._replayAdd(sink); if (this._replay.buffer.length > 0) { pushEvents(sink, this._replay.buffer); } return length; } function addToBuffer(event, replay) { if (replay.buffer.length >= replay.bufferSize) { replay.buffer.shift(); } replay.buffer.push(event); } function replayEvent(time, value) { if (this._replay.bufferSize > 0) { addToBuffer({ time: time, value: value }, this._replay); } this._replayEvent(time, value); } var Replay = function () { function Replay(bufferSize, source) { _classCallCheck(this, Replay); this.source = source; this.bufferSize = bufferSize; this.buffer = []; } _createClass(Replay, [{ key: 'run', value: function run(sink, scheduler) { if (sink._replay !== this) { sink._replay = this; sink._replayAdd = sink.add; sink.add = replayAdd; sink._replayEvent = sink.event; sink.event = replayEvent; } return this.source.run(sink, scheduler); } }]); return Replay; }(); var replay = function replay(bufferSize, stream) { return new _most.Stream(new _multicast.MulticastSource(new Replay(bufferSize, stream.source))); }; exports.replay = replay; /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.holdSubject = exports.subject = undefined; var _most = __webpack_require__(4); var _multicast = __webpack_require__(5); var _Observer = __webpack_require__(49); var _Replay = __webpack_require__(50); function create(hold, bufferSize, initialValue) { var observer = new _Observer.Observer(); var stream = hold ? (0, _Replay.replay)(bufferSize, new _most.Stream(observer)) : new _most.Stream(new _multicast.MulticastSource(observer)); stream.drain(); if (typeof initialValue !== 'undefined') { observer.next(initialValue); } return { stream: stream, observer: observer }; } function subject() { return create(false, 0); } function holdSubject() { var bufferSize = arguments.length <= 0 || arguments[0] === undefined ? 1 : arguments[0]; var initialValue = arguments[1]; if (bufferSize < 1) { throw new Error('First argument to holdSubject is expected to be an ' + 'integer greater than or equal to 1'); } return create(true, bufferSize, initialValue); } exports.subject = subject; exports.holdSubject = holdSubject; /***/ }, /* 52 */ /***/ function(module, exports) { "use strict"; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ module.exports = LinkedList; /** * Doubly linked list * @constructor */ function LinkedList() { this.head = null; this.length = 0; } /** * Add a node to the end of the list * @param {{prev:Object|null, next:Object|null, dispose:function}} x node to add */ LinkedList.prototype.add = function (x) { if (this.head !== null) { this.head.prev = x; x.next = this.head; } this.head = x; ++this.length; }; /** * Remove the provided node from the list * @param {{prev:Object|null, next:Object|null, dispose:function}} x node to remove */ LinkedList.prototype.remove = function (x) { --this.length; if (x === this.head) { this.head = this.head.next; } if (x.next !== null) { x.next.prev = x.prev; x.next = null; } if (x.prev !== null) { x.prev.next = x.next; x.prev = null; } }; /** * @returns {boolean} true iff there are no nodes in the list */ LinkedList.prototype.isEmpty = function () { return this.length === 0; }; /** * Dispose all nodes * @returns {Promise} promise that fulfills when all nodes have been disposed, * or rejects if an error occurs while disposing */ LinkedList.prototype.dispose = function () { if (this.isEmpty()) { return Promise.resolve(); } var promises = []; var x = this.head; this.head = null; this.length = 0; while (x !== null) { promises.push(x.dispose()); x = x.next; } return Promise.all(promises); }; /***/ }, /* 53 */ /***/ function(module, exports) { "use strict"; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ // Based on https://github.com/petkaantonov/deque module.exports = Queue; function Queue(capPow2) { this._capacity = capPow2 || 32; this._length = 0; this._head = 0; } Queue.prototype.push = function (x) { var len = this._length; this._checkCapacity(len + 1); var i = this._head + len & this._capacity - 1; this[i] = x; this._length = len + 1; }; Queue.prototype.shift = function () { var head = this._head; var x = this[head]; this[head] = void 0; this._head = head + 1 & this._capacity - 1; this._length--; return x; }; Queue.prototype.isEmpty = function () { return this._length === 0; }; Queue.prototype.length = function () { return this._length; }; Queue.prototype._checkCapacity = function (size) { if (this._capacity < size) { this._ensureCapacity(this._capacity << 1); } }; Queue.prototype._ensureCapacity = function (capacity) { var oldCapacity = this._capacity; this._capacity = capacity; var last = this._head + this._length; if (last > oldCapacity) { copy(this, 0, this, oldCapacity, last & oldCapacity - 1); } }; function copy(src, srcIndex, dst, dstIndex, len) { for (var j = 0; j < len; ++j) { dst[j + dstIndex] = src[j + srcIndex]; src[j + srcIndex] = void 0; } } /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var Pipe = __webpack_require__(1); var runSource = __webpack_require__(32); var cons = __webpack_require__(23).cons; exports.scan = scan; exports.reduce = reduce; /** * Create a stream containing successive reduce results of applying f to * the previous reduce result and the current stream item. * @param {function(result:*, x:*):*} f reducer function * @param {*} initial initial value * @param {Stream} stream stream to scan * @returns {Stream} new stream containing successive reduce results */ function scan(f, initial, stream) { return cons(initial, new Stream(new Accumulate(ScanSink, f, initial, stream.source))); } function ScanSink(f, z, sink) { this.f = f; this.value = z; this.sink = sink; } ScanSink.prototype.event = function (t, x) { var f = this.f; this.value = f(this.value, x); this.sink.event(t, this.value); }; ScanSink.prototype.error = Pipe.prototype.error; ScanSink.prototype.end = Pipe.prototype.end; /** * Reduce a stream to produce a single result. Note that reducing an infinite * stream will return a Promise that never fulfills, but that may reject if an error * occurs. * @param {function(result:*, x:*):*} f reducer function * @param {*} initial initial value * @param {Stream} stream to reduce * @returns {Promise} promise for the file result of the reduce */ function reduce(f, initial, stream) { return runSource.withDefaultScheduler(noop, new Accumulate(AccumulateSink, f, initial, stream.source)); } function Accumulate(SinkType, f, z, source) { this.SinkType = SinkType; this.f = f; this.value = z; this.source = source; } Accumulate.prototype.run = function (sink, scheduler) { return this.source.run(new this.SinkType(this.f, this.value, sink), scheduler); }; function AccumulateSink(f, z, sink) { this.f = f; this.value = z; this.sink = sink; } AccumulateSink.prototype.event = function (t, x) { var f = this.f; this.value = f(this.value, x); this.sink.event(t, this.value); }; AccumulateSink.prototype.error = Pipe.prototype.error; AccumulateSink.prototype.end = function (t) { this.sink.end(t, this.value); }; function noop() {} /***/ }, /* 55 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var combine = __webpack_require__(24).combine; var apply = __webpack_require__(3).apply; exports.ap = ap; /** * Assume fs is a stream containing functions, and apply the latest function * in fs to the latest value in xs. * fs: --f---------g--------h------> * xs: -a-------b-------c-------d--> * ap(fs, xs): --fa-----fb-gb---gc--hc--hd-> * @param {Stream} fs stream of functions to apply to the latest x * @param {Stream} xs stream of values to which to apply all the latest f * @returns {Stream} stream containing all the applications of fs to xs */ function ap(fs, xs) { return combine(apply, fs, xs); } /***/ }, /* 56 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var mergeMapConcurrently = __webpack_require__(8).mergeMapConcurrently; exports.concatMap = concatMap; /** * Map each value in stream to a new stream, and concatenate them all * stream: -a---b---cX * f(a): 1-1-1-1X * f(b): -2-2-2-2X * f(c): -3-3-3-3X * stream.concatMap(f): -1-1-1-1-2-2-2-2-3-3-3-3X * @param {function(x:*):Stream} f function to map each value to a stream * @param {Stream} stream * @returns {Stream} new stream containing all events from each stream returned by f */ function concatMap(f, stream) { return mergeMapConcurrently(f, 1, stream); } /***/ }, /* 57 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var Sink = __webpack_require__(1); var dispose = __webpack_require__(2); var PropagateTask = __webpack_require__(6); exports.delay = delay; /** * @param {Number} delayTime milliseconds to delay each item * @param {Stream} stream * @returns {Stream} new stream containing the same items, but delayed by ms */ function delay(delayTime, stream) { return delayTime <= 0 ? stream : new Stream(new Delay(delayTime, stream.source)); } function Delay(dt, source) { this.dt = dt; this.source = source; } Delay.prototype.run = function (sink, scheduler) { var delaySink = new DelaySink(this.dt, sink, scheduler); return dispose.all([delaySink, this.source.run(delaySink, scheduler)]); }; function DelaySink(dt, sink, scheduler) { this.dt = dt; this.sink = sink; this.scheduler = scheduler; } DelaySink.prototype.dispose = function () { var self = this; this.scheduler.cancelAll(function (task) { return task.sink === self.sink; }); }; DelaySink.prototype.event = function (t, x) { this.scheduler.delay(this.dt, PropagateTask.event(x, this.sink)); }; DelaySink.prototype.end = function (t, x) { this.scheduler.delay(this.dt, PropagateTask.end(x, this.sink)); }; DelaySink.prototype.error = Sink.prototype.error; /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var ValueSource = __webpack_require__(34); var SafeSink = __webpack_require__(80); var Pipe = __webpack_require__(1); var dispose = __webpack_require__(2); var tryEvent = __webpack_require__(9); var isPromise = __webpack_require__(11).isPromise; exports.flatMapError = recoverWith; exports.recoverWith = recoverWith; exports.throwError = throwError; /** * If stream encounters an error, recover and continue with items from stream * returned by f. * @param {function(error:*):Stream} f function which returns a new stream * @param {Stream} stream * @returns {Stream} new stream which will recover from an error by calling f */ function recoverWith(f, stream) { return new Stream(new RecoverWith(f, stream.source)); } /** * Create a stream containing only an error * @param {*} e error value, preferably an Error or Error subtype * @returns {Stream} new stream containing only an error */ function throwError(e) { return new Stream(new ValueSource(error, e)); } function error(t, e, sink) { sink.error(t, e); } function RecoverWith(f, source) { this.f = f; this.source = source; } RecoverWith.prototype.run = function (sink, scheduler) { return new RecoverWithSink(this.f, this.source, sink, scheduler); }; function RecoverWithSink(f, source, sink, scheduler) { this.f = f; this.sink = new SafeSink(sink); this.scheduler = scheduler; this.disposable = source.run(this, scheduler); } RecoverWithSink.prototype.event = function (t, x) { tryEvent.tryEvent(t, x, this.sink); }; RecoverWithSink.prototype.end = function (t, x) { tryEvent.tryEnd(t, x, this.sink); }; RecoverWithSink.prototype.error = function (t, e) { var nextSink = this.sink.disable(); var result = dispose.tryDispose(t, this.disposable, nextSink); this.disposable = isPromise(result) ? dispose.promised(this._thenContinue(result, e, nextSink)) : this._continue(this.f, e, nextSink); }; RecoverWithSink.prototype._thenContinue = function (p, x, sink) { var self = this; return p.then(function () { return self._continue(self.f, x, sink); }); }; RecoverWithSink.prototype._continue = function (f, x, sink) { return f(x).source.run(sink, this.scheduler); }; RecoverWithSink.prototype.dispose = function () { return this.disposable.dispose(); }; /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var Sink = __webpack_require__(1); var Filter = __webpack_require__(29); exports.filter = filter; exports.skipRepeats = skipRepeats; exports.skipRepeatsWith = skipRepeatsWith; /** * Retain only items matching a predicate * @param {function(x:*):boolean} p filtering predicate called for each item * @param {Stream} stream stream to filter * @returns {Stream} stream containing only items for which predicate returns truthy */ function filter(p, stream) { return new Stream(Filter.create(p, stream.source)); } /** * Skip repeated events, using === to detect duplicates * @param {Stream} stream stream from which to omit repeated events * @returns {Stream} stream without repeated events */ function skipRepeats(stream) { return skipRepeatsWith(same, stream); } /** * Skip repeated events using the provided equals function to detect duplicates * @param {function(a:*, b:*):boolean} equals optional function to compare items * @param {Stream} stream stream from which to omit repeated events * @returns {Stream} stream without repeated events */ function skipRepeatsWith(equals, stream) { return new Stream(new SkipRepeats(equals, stream.source)); } function SkipRepeats(equals, source) { this.equals = equals; this.source = source; } SkipRepeats.prototype.run = function (sink, scheduler) { return this.source.run(new SkipRepeatsSink(this.equals, sink), scheduler); }; function SkipRepeatsSink(equals, sink) { this.equals = equals; this.sink = sink; this.value = void 0; this.init = true; } SkipRepeatsSink.prototype.end = Sink.prototype.end; SkipRepeatsSink.prototype.error = Sink.prototype.error; SkipRepeatsSink.prototype.event = function (t, x) { if (this.init) { this.init = false; this.value = x; this.sink.event(t, x); } else if (!this.equals(this.value, x)) { this.value = x; this.sink.event(t, x); } }; function same(a, b) { return a === b; } /***/ }, /* 60 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var Sink = __webpack_require__(1); var dispose = __webpack_require__(2); var PropagateTask = __webpack_require__(6); exports.throttle = throttle; exports.debounce = debounce; /** * Limit the rate of events by suppressing events that occur too often * @param {Number} period time to suppress events * @param {Stream} stream * @returns {Stream} */ function throttle(period, stream) { return new Stream(new Throttle(period, stream.source)); } function Throttle(period, source) { this.dt = period; this.source = source; } Throttle.prototype.run = function (sink, scheduler) { return this.source.run(new ThrottleSink(this.dt, sink), scheduler); }; function ThrottleSink(dt, sink) { this.time = 0; this.dt = dt; this.sink = sink; } ThrottleSink.prototype.event = function (t, x) { if (t >= this.time) { this.time = t + this.dt; this.sink.event(t, x); } }; ThrottleSink.prototype.end = Sink.prototype.end; ThrottleSink.prototype.error = Sink.prototype.error; /** * Wait for a burst of events to subside and emit only the last event in the burst * @param {Number} period events occuring more frequently than this * will be suppressed * @param {Stream} stream stream to debounce * @returns {Stream} new debounced stream */ function debounce(period, stream) { return new Stream(new Debounce(period, stream.source)); } function Debounce(dt, source) { this.dt = dt; this.source = source; } Debounce.prototype.run = function (sink, scheduler) { return new DebounceSink(this.dt, this.source, sink, scheduler); }; function DebounceSink(dt, source, sink, scheduler) { this.dt = dt; this.sink = sink; this.scheduler = scheduler; this.value = void 0; this.timer = null; var sourceDisposable = source.run(this, scheduler); this.disposable = dispose.all([this, sourceDisposable]); } DebounceSink.prototype.event = function (t, x) { this._clearTimer(); this.value = x; this.timer = this.scheduler.delay(this.dt, PropagateTask.event(x, this.sink)); }; DebounceSink.prototype.end = function (t, x) { if (this._clearTimer()) { this.sink.event(t, this.value); this.value = void 0; } this.sink.end(t, x); }; DebounceSink.prototype.error = function (t, x) { this._clearTimer(); this.sink.error(t, x); }; DebounceSink.prototype.dispose = function () { this._clearTimer(); }; DebounceSink.prototype._clearTimer = function () { if (this.timer === null) { return false; } this.timer.cancel(); this.timer = null; return true; }; /***/ }, /* 61 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var Pipe = __webpack_require__(1); exports.loop = loop; /** * Generalized feedback loop. Call a stepper function for each event. The stepper * will be called with 2 params: the current seed and the an event value. It must * return a new { seed, value } pair. The `seed` will be fed back into the next * invocation of stepper, and the `value` will be propagated as the event value. * @param {function(seed:*, value:*):{seed:*, value:*}} stepper loop step function * @param {*} seed initial seed value passed to first stepper call * @param {Stream} stream event stream * @returns {Stream} new stream whose values are the `value` field of the objects * returned by the stepper */ function loop(stepper, seed, stream) { return new Stream(new Loop(stepper, seed, stream.source)); } function Loop(stepper, seed, source) { this.step = stepper; this.seed = seed; this.source = source; } Loop.prototype.run = function (sink, scheduler) { return this.source.run(new LoopSink(this.step, this.seed, sink), scheduler); }; function LoopSink(stepper, seed, sink) { this.step = stepper; this.seed = seed; this.sink = sink; } LoopSink.prototype.error = Pipe.prototype.error; LoopSink.prototype.event = function (t, x) { var result = this.step(this.seed, x); this.seed = result.seed; this.sink.event(t, result.value); }; LoopSink.prototype.end = function (t) { this.sink.end(t, this.seed); }; /***/ }, /* 62 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var Pipe = __webpack_require__(1); var IndexSink = __webpack_require__(14); var empty = __webpack_require__(7).empty; var dispose = __webpack_require__(2); var base = __webpack_require__(3); var copy = base.copy; var reduce = base.reduce; exports.merge = merge; exports.mergeArray = mergeArray; /** * @returns {Stream} stream containing events from all streams in the argument * list in time order. If two events are simultaneous they will be merged in * arbitrary order. */ function merge() /*...streams*/{ return mergeArray(copy(arguments)); } /** * @param {Array} streams array of stream to merge * @returns {Stream} stream containing events from all input observables * in time order. If two events are simultaneous they will be merged in * arbitrary order. */ function mergeArray(streams) { var l = streams.length; return l === 0 ? empty() : l === 1 ? streams[0] : new Stream(mergeSources(streams)); } /** * This implements fusion/flattening for merge. It will * fuse adjacent merge operations. For example: * - a.merge(b).merge(c) effectively becomes merge(a, b, c) * - merge(a, merge(b, c)) effectively becomes merge(a, b, c) * It does this by concatenating the sources arrays of * any nested Merge sources, in effect "flattening" nested * merge operations into a single merge. */ function mergeSources(streams) { return new Merge(reduce(appendSources, [], streams)); } function appendSources(sources, stream) { var source = stream.source; return source instanceof Merge ? sources.concat(source.sources) : sources.concat(source); } function Merge(sources) { this.sources = sources; } Merge.prototype.run = function (sink, scheduler) { var l = this.sources.length; var disposables = new Array(l); var sinks = new Array(l); var mergeSink = new MergeSink(disposables, sinks, sink); for (var indexSink, i = 0; i < l; ++i) { indexSink = sinks[i] = new IndexSink(i, mergeSink); disposables[i] = this.sources[i].run(indexSink, scheduler); } return dispose.all(disposables); }; function MergeSink(disposables, sinks, sink) { this.sink = sink; this.disposables = disposables; this.activeCount = sinks.length; } MergeSink.prototype.error = Pipe.prototype.error; MergeSink.prototype.event = function (t, indexValue) { this.sink.event(t, indexValue.value); }; MergeSink.prototype.end = function (t, indexedValue) { dispose.tryDispose(t, this.disposables[indexedValue.index], this.sink); if (--this.activeCount === 0) { this.sink.end(t, indexedValue.value); } }; /***/ }, /* 63 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var runSource = __webpack_require__(32); exports.observe = observe; exports.drain = drain; /** * Observe all the event values in the stream in time order. The * provided function `f` will be called for each event value * @param {function(x:T):*} f function to call with each event value * @param {Stream<T>} stream stream to observe * @return {Promise} promise that fulfills after the stream ends without * an error, or rejects if the stream ends with an error. */ function observe(f, stream) { return runSource.withDefaultScheduler(f, stream.source); } /** * "Run" a stream by * @param stream * @return {*} */ function drain(stream) { return runSource.withDefaultScheduler(noop, stream.source); } function noop() {} /***/ }, /* 64 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var fatal = __webpack_require__(28); var just = __webpack_require__(7).of; exports.fromPromise = fromPromise; exports.awaitPromises = awaitPromises; /** * Create a stream containing only the promise's fulfillment * value at the time it fulfills. * @param {Promise<T>} p promise * @return {Stream<T>} stream containing promise's fulfillment value. * If the promise rejects, the stream will error */ function fromPromise(p) { return awaitPromises(just(p)); } /** * Turn a Stream<Promise<T>> into Stream<T> by awaiting each promise. * Event order is preserved. * @param {Stream<Promise<T>>} stream * @return {Stream<T>} stream of fulfillment values. The stream will * error if any promise rejects. */ function awaitPromises(stream) { return new Stream(new Await(stream.source)); } function Await(source) { this.source = source; } Await.prototype.run = function (sink, scheduler) { return this.source.run(new AwaitSink(sink, scheduler), scheduler); }; function AwaitSink(sink, scheduler) { this.sink = sink; this.scheduler = scheduler; this.queue = Promise.resolve(); var self = this; // Pre-create closures, to avoid creating them per event this._eventBound = function (x) { self.sink.event(self.scheduler.now(), x); }; this._endBound = function (x) { self.sink.end(self.scheduler.now(), x); }; this._errorBound = function (e) { self.sink.error(self.scheduler.now(), e); }; } AwaitSink.prototype.event = function (t, promise) { var self = this; this.queue = this.queue.then(function () { return self._event(promise); }).catch(this._errorBound); }; AwaitSink.prototype.end = function (t, x) { var self = this; this.queue = this.queue.then(function () { return self._end(x); }).catch(this._errorBound); }; AwaitSink.prototype.error = function (t, e) { var self = this; // Don't resolve error values, propagate directly this.queue = this.queue.then(function () { return self._errorBound(e); }).catch(fatal); }; AwaitSink.prototype._event = function (promise) { return promise.then(this._eventBound); }; AwaitSink.prototype._end = function (x) { return Promise.resolve(x).then(this._endBound); }; /***/ }, /* 65 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var Pipe = __webpack_require__(1); var dispose = __webpack_require__(2); var base = __webpack_require__(3); var invoke = __webpack_require__(13); exports.sample = sample; exports.sampleWith = sampleWith; exports.sampleArray = sampleArray; /** * When an event arrives on sampler, emit the result of calling f with the latest * values of all streams being sampled * @param {function(...values):*} f function to apply to each set of sampled values * @param {Stream} sampler streams will be sampled whenever an event arrives * on sampler * @returns {Stream} stream of sampled and transformed values */ function sample(f, sampler /*, ...streams */) { return sampleArray(f, sampler, base.drop(2, arguments)); } /** * When an event arrives on sampler, emit the latest event value from stream. * @param {Stream} sampler stream of events at whose arrival time * stream's latest value will be propagated * @param {Stream} stream stream of values * @returns {Stream} sampled stream of values */ function sampleWith(sampler, stream) { return new Stream(new Sampler(base.id, sampler.source, [stream.source])); } function sampleArray(f, sampler, streams) { return new Stream(new Sampler(f, sampler.source, base.map(getSource, streams))); } function getSource(stream) { return stream.source; } function Sampler(f, sampler, sources) { this.f = f; this.sampler = sampler; this.sources = sources; } Sampler.prototype.run = function (sink, scheduler) { var l = this.sources.length; var disposables = new Array(l + 1); var sinks = new Array(l); var sampleSink = new SampleSink(this.f, sinks, sink); for (var hold, i = 0; i < l; ++i) { hold = sinks[i] = new Hold(sampleSink); disposables[i] = this.sources[i].run(hold, scheduler); } disposables[i] = this.sampler.run(sampleSink, scheduler); return dispose.all(disposables); }; function Hold(sink) { this.sink = sink; this.hasValue = false; } Hold.prototype.event = function (t, x) { this.value = x; this.hasValue = true; this.sink._notify(this); }; Hold.prototype.end = function () {}; Hold.prototype.error = Pipe.prototype.error; function SampleSink(f, sinks, sink) { this.f = f; this.sinks = sinks; this.sink = sink; this.active = false; } SampleSink.prototype._notify = function () { if (!this.active) { this.active = this.sinks.every(hasValue); } }; SampleSink.prototype.event = function (t) { if (this.active) { this.sink.event(t, invoke(this.f, base.map(getValue, this.sinks))); } }; SampleSink.prototype.end = Pipe.prototype.end; SampleSink.prototype.error = Pipe.prototype.error; function hasValue(hold) { return hold.hasValue; } function getValue(hold) { return hold.value; } /***/ }, /* 66 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var Sink = __webpack_require__(1); var core = __webpack_require__(7); var dispose = __webpack_require__(2); var Map = __webpack_require__(30); exports.take = take; exports.skip = skip; exports.slice = slice; exports.takeWhile = takeWhile; exports.skipWhile = skipWhile; /** * @param {number} n * @param {Stream} stream * @returns {Stream} new stream containing only up to the first n items from stream */ function take(n, stream) { return slice(0, n, stream); } /** * @param {number} n * @param {Stream} stream * @returns {Stream} new stream with the first n items removed */ function skip(n, stream) { return slice(n, Infinity, stream); } /** * Slice a stream by index. Negative start/end indexes are not supported * @param {number} start * @param {number} end * @param {Stream} stream * @returns {Stream} stream containing items where start <= index < end */ function slice(start, end, stream) { return end <= start ? core.empty() : new Stream(sliceSource(start, end, stream.source)); } function sliceSource(start, end, source) { return source instanceof Map ? commuteMapSlice(start, end, source) : source instanceof Slice ? fuseSlice(start, end, source) : new Slice(start, end, source); } function commuteMapSlice(start, end, source) { return Map.create(source.f, sliceSource(start, end, source.source)); } function fuseSlice(start, end, source) { start += source.min; end = Math.min(end + source.min, source.max); return new Slice(start, end, source.source); } function Slice(min, max, source) { this.source = source; this.min = min; this.max = max; } Slice.prototype.run = function (sink, scheduler) { return new SliceSink(this.min, this.max - this.min, this.source, sink, scheduler); }; function SliceSink(skip, take, source, sink, scheduler) { this.sink = sink; this.skip = skip; this.take = take; this.disposable = dispose.once(source.run(this, scheduler)); } SliceSink.prototype.end = Sink.prototype.end; SliceSink.prototype.error = Sink.prototype.error; SliceSink.prototype.event = function (t, x) { if (this.skip > 0) { this.skip -= 1; return; } if (this.take === 0) { return; } this.take -= 1; this.sink.event(t, x); if (this.take === 0) { this.dispose(); this.sink.end(t, x); } }; SliceSink.prototype.dispose = function () { return this.disposable.dispose(); }; function takeWhile(p, stream) { return new Stream(new TakeWhile(p, stream.source)); } function TakeWhile(p, source) { this.p = p; this.source = source; } TakeWhile.prototype.run = function (sink, scheduler) { return new TakeWhileSink(this.p, this.source, sink, scheduler); }; function TakeWhileSink(p, source, sink, scheduler) { this.p = p; this.sink = sink; this.active = true; this.disposable = dispose.once(source.run(this, scheduler)); } TakeWhileSink.prototype.end = Sink.prototype.end; TakeWhileSink.prototype.error = Sink.prototype.error; TakeWhileSink.prototype.event = function (t, x) { if (!this.active) { return; } var p = this.p; this.active = p(x); if (this.active) { this.sink.event(t, x); } else { this.dispose(); this.sink.end(t, x); } }; TakeWhileSink.prototype.dispose = function () { return this.disposable.dispose(); }; function skipWhile(p, stream) { return new Stream(new SkipWhile(p, stream.source)); } function SkipWhile(p, source) { this.p = p; this.source = source; } SkipWhile.prototype.run = function (sink, scheduler) { return this.source.run(new SkipWhileSink(this.p, sink), scheduler); }; function SkipWhileSink(p, sink) { this.p = p; this.sink = sink; this.skipping = true; } SkipWhileSink.prototype.end = Sink.prototype.end; SkipWhileSink.prototype.error = Sink.prototype.error; SkipWhileSink.prototype.event = function (t, x) { if (this.skipping) { var p = this.p; this.skipping = p(x); if (this.skipping) { return; } } this.sink.event(t, x); }; /***/ }, /* 67 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var dispose = __webpack_require__(2); exports.switch = switchLatest; /** * Given a stream of streams, return a new stream that adopts the behavior * of the most recent inner stream. * @param {Stream} stream of streams on which to switch * @returns {Stream} switching stream */ function switchLatest(stream) { return new Stream(new Switch(stream.source)); } function Switch(source) { this.source = source; } Switch.prototype.run = function (sink, scheduler) { var switchSink = new SwitchSink(sink, scheduler); return dispose.all(switchSink, this.source.run(switchSink, scheduler)); }; function SwitchSink(sink, scheduler) { this.sink = sink; this.scheduler = scheduler; this.current = null; this.ended = false; } SwitchSink.prototype.event = function (t, stream) { this._disposeCurrent(t); // TODO: capture the result of this dispose this.current = new Segment(t, Infinity, this, this.sink); this.current.disposable = stream.source.run(this.current, this.scheduler); }; SwitchSink.prototype.end = function (t, x) { this.ended = true; this._checkEnd(t, x); }; SwitchSink.prototype.error = function (t, e) { this.ended = true; this.sink.error(t, e); }; SwitchSink.prototype.dispose = function () { return this._disposeCurrent(0); }; SwitchSink.prototype._disposeCurrent = function (t) { if (this.current !== null) { return this.current._dispose(t); } }; SwitchSink.prototype._disposeInner = function (t, inner) { inner._dispose(t); // TODO: capture the result of this dispose if (inner === this.current) { this.current = null; } }; SwitchSink.prototype._checkEnd = function (t, x) { if (this.ended && this.current === null) { this.sink.end(t, x); } }; SwitchSink.prototype._endInner = function (t, x, inner) { this._disposeInner(t, inner); this._checkEnd(t, x); }; SwitchSink.prototype._errorInner = function (t, e, inner) { this._disposeInner(t, inner); this.sink.error(t, e); }; function Segment(min, max, outer, sink) { this.min = min; this.max = max; this.outer = outer; this.sink = sink; this.disposable = dispose.empty(); } Segment.prototype.event = function (t, x) { if (t < this.max) { this.sink.event(Math.max(t, this.min), x); } }; Segment.prototype.end = function (t, x) { this.outer._endInner(Math.max(t, this.min), x, this); }; Segment.prototype.error = function (t, e) { this.outer._errorInner(Math.max(t, this.min), e, this); }; Segment.prototype._dispose = function (t) { this.max = t; dispose.tryDispose(t, this.disposable, this.sink); }; /***/ }, /* 68 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var Pipe = __webpack_require__(1); var dispose = __webpack_require__(2); var join = __webpack_require__(26).join; exports.during = during; exports.takeUntil = takeUntil; exports.skipUntil = skipUntil; function takeUntil(signal, stream) { return new Stream(new Until(signal.source, stream.source)); } function skipUntil(signal, stream) { return new Stream(new Since(signal.source, stream.source)); } function during(timeWindow, stream) { return takeUntil(join(timeWindow), skipUntil(timeWindow, stream)); } function Until(maxSignal, source) { this.maxSignal = maxSignal; this.source = source; } Until.prototype.run = function (sink, scheduler) { var min = new Bound(-Infinity, sink); var max = new UpperBound(this.maxSignal, sink, scheduler); var disposable = this.source.run(new TimeWindowSink(min, max, sink), scheduler); return dispose.all([min, max, disposable]); }; function Since(minSignal, source) { this.minSignal = minSignal; this.source = source; } Since.prototype.run = function (sink, scheduler) { var min = new LowerBound(this.minSignal, sink, scheduler); var max = new Bound(Infinity, sink); var disposable = this.source.run(new TimeWindowSink(min, max, sink), scheduler); return dispose.all([min, max, disposable]); }; function Bound(value, sink) { this.value = value; this.sink = sink; } Bound.prototype.error = Pipe.prototype.error; Bound.prototype.event = noop; Bound.prototype.end = noop; Bound.prototype.dispose = noop; function TimeWindowSink(min, max, sink) { this.min = min; this.max = max; this.sink = sink; } TimeWindowSink.prototype.event = function (t, x) { if (t >= this.min.value && t < this.max.value) { this.sink.event(t, x); } }; TimeWindowSink.prototype.error = Pipe.prototype.error; TimeWindowSink.prototype.end = Pipe.prototype.end; function LowerBound(signal, sink, scheduler) { this.value = Infinity; this.sink = sink; this.disposable = signal.run(this, scheduler); } LowerBound.prototype.event = function (t /*, x */) { if (t < this.value) { this.value = t; } }; LowerBound.prototype.end = noop; LowerBound.prototype.error = Pipe.prototype.error; LowerBound.prototype.dispose = function () { return this.disposable.dispose(); }; function UpperBound(signal, sink, scheduler) { this.value = Infinity; this.sink = sink; this.disposable = signal.run(this, scheduler); } UpperBound.prototype.event = function (t, x) { if (t < this.value) { this.value = t; this.sink.end(t, x); } }; UpperBound.prototype.end = noop; UpperBound.prototype.error = Pipe.prototype.error; UpperBound.prototype.dispose = function () { return this.disposable.dispose(); }; function noop() {} /***/ }, /* 69 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var Sink = __webpack_require__(1); exports.timestamp = timestamp; function timestamp(stream) { return new Stream(new Timestamp(stream.source)); } function Timestamp(source) { this.source = source; } Timestamp.prototype.run = function (sink, scheduler) { return this.source.run(new TimestampSink(sink), scheduler); }; function TimestampSink(sink) { this.sink = sink; } TimestampSink.prototype.end = Sink.prototype.end; TimestampSink.prototype.error = Sink.prototype.error; TimestampSink.prototype.event = function (t, x) { this.sink.event(t, { time: t, value: x }); }; /***/ }, /* 70 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); exports.transduce = transduce; /** * Transform a stream by passing its events through a transducer. * @param {function} transducer transducer function * @param {Stream} stream stream whose events will be passed through the * transducer * @return {Stream} stream of events transformed by the transducer */ function transduce(transducer, stream) { return new Stream(new Transduce(transducer, stream.source)); } function Transduce(transducer, source) { this.transducer = transducer; this.source = source; } Transduce.prototype.run = function (sink, scheduler) { var xf = this.transducer(new Transformer(sink)); return this.source.run(new TransduceSink(getTxHandler(xf), sink), scheduler); }; function TransduceSink(adapter, sink) { this.xf = adapter; this.sink = sink; } TransduceSink.prototype.event = function (t, x) { var next = this.xf.step(t, x); return this.xf.isReduced(next) ? this.sink.end(t, this.xf.getResult(next)) : next; }; TransduceSink.prototype.end = function (t, x) { return this.xf.result(x); }; TransduceSink.prototype.error = function (t, e) { return this.sink.error(t, e); }; function Transformer(sink) { this.time = -Infinity; this.sink = sink; } Transformer.prototype['@@transducer/init'] = Transformer.prototype.init = function () {}; Transformer.prototype['@@transducer/step'] = Transformer.prototype.step = function (t, x) { if (!isNaN(t)) { this.time = Math.max(t, this.time); } return this.sink.event(this.time, x); }; Transformer.prototype['@@transducer/result'] = Transformer.prototype.result = function (x) { return this.sink.end(this.time, x); }; /** * Given an object supporting the new or legacy transducer protocol, * create an adapter for it. * @param {object} tx transform * @returns {TxAdapter|LegacyTxAdapter} */ function getTxHandler(tx) { return typeof tx['@@transducer/step'] === 'function' ? new TxAdapter(tx) : new LegacyTxAdapter(tx); } /** * Adapter for new official transducer protocol * @param {object} tx transform * @constructor */ function TxAdapter(tx) { this.tx = tx; } TxAdapter.prototype.step = function (t, x) { return this.tx['@@transducer/step'](t, x); }; TxAdapter.prototype.result = function (x) { return this.tx['@@transducer/result'](x); }; TxAdapter.prototype.isReduced = function (x) { return x != null && x['@@transducer/reduced']; }; TxAdapter.prototype.getResult = function (x) { return x['@@transducer/value']; }; /** * Adapter for older transducer protocol * @param {object} tx transform * @constructor */ function LegacyTxAdapter(tx) { this.tx = tx; } LegacyTxAdapter.prototype.step = function (t, x) { return this.tx.step(t, x); }; LegacyTxAdapter.prototype.result = function (x) { return this.tx.result(x); }; LegacyTxAdapter.prototype.isReduced = function (x) { return x != null && x.__transducers_reduced__; }; LegacyTxAdapter.prototype.getResult = function (x) { return x.value; }; /***/ }, /* 71 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var transform = __webpack_require__(12); var core = __webpack_require__(7); var Sink = __webpack_require__(1); var IndexSink = __webpack_require__(14); var dispose = __webpack_require__(2); var base = __webpack_require__(3); var invoke = __webpack_require__(13); var Queue = __webpack_require__(53); var map = base.map; var tail = base.tail; exports.zip = zip; exports.zipArray = zipArray; /** * Combine streams pairwise (or tuple-wise) by index by applying f to values * at corresponding indices. The returned stream ends when any of the input * streams ends. * @param {function} f function to combine values * @returns {Stream} new stream with items at corresponding indices combined * using f */ function zip(f /*,...streams */) { return zipArray(f, tail(arguments)); } /** * Combine streams pairwise (or tuple-wise) by index by applying f to values * at corresponding indices. The returned stream ends when any of the input * streams ends. * @param {function} f function to combine values * @param {[Stream]} streams streams to zip using f * @returns {Stream} new stream with items at corresponding indices combined * using f */ function zipArray(f, streams) { return streams.length === 0 ? core.empty() : streams.length === 1 ? transform.map(f, streams[0]) : new Stream(new Zip(f, map(getSource, streams))); } function getSource(stream) { return stream.source; } function Zip(f, sources) { this.f = f; this.sources = sources; } Zip.prototype.run = function (sink, scheduler) { var l = this.sources.length; var disposables = new Array(l); var sinks = new Array(l); var buffers = new Array(l); var zipSink = new ZipSink(this.f, buffers, sinks, sink); for (var indexSink, i = 0; i < l; ++i) { buffers[i] = new Queue(); indexSink = sinks[i] = new IndexSink(i, zipSink); disposables[i] = this.sources[i].run(indexSink, scheduler); } return dispose.all(disposables); }; function ZipSink(f, buffers, sinks, sink) { this.f = f; this.sinks = sinks; this.sink = sink; this.buffers = buffers; } ZipSink.prototype.event = function (t, indexedValue) { var buffers = this.buffers; var buffer = buffers[indexedValue.index]; buffer.push(indexedValue.value); if (buffer.length() === 1) { if (!ready(this.buffers)) { return; } emitZipped(this.f, t, buffers, this.sink); if (ended(this.buffers, this.sinks)) { this.sink.end(t, void 0); } } }; ZipSink.prototype.end = function (t, indexedValue) { var buffer = this.buffers[indexedValue.index]; if (buffer.isEmpty()) { this.sink.end(t, indexedValue.value); } }; ZipSink.prototype.error = Sink.prototype.error; function emitZipped(f, t, buffers, sink) { sink.event(t, invoke(f, map(head, buffers))); } function head(buffer) { return buffer.shift(); } function ended(buffers, sinks) { for (var i = 0, l = buffers.length; i < l; ++i) { if (buffers[i].isEmpty() && !sinks[i].active) { return true; } } return false; } function ready(buffers) { for (var i = 0, l = buffers.length; i < l; ++i) { if (buffers[i].isEmpty()) { return false; } } return true; } /***/ }, /* 72 */ /***/ function(module, exports) { "use strict"; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ module.exports = Disposable; /** * Create a new Disposable which will dispose its underlying resource. * @param {function} dispose function * @param {*?} data any data to be passed to disposer function * @constructor */ function Disposable(dispose, data) { this._dispose = dispose; this._data = data; } Disposable.prototype.dispose = function () { return this._dispose(this._data); }; /***/ }, /* 73 */ /***/ function(module, exports) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ module.exports = SettableDisposable; function SettableDisposable() { this.disposable = void 0; this.disposed = false; this._resolve = void 0; var self = this; this.result = new Promise(function (resolve) { self._resolve = resolve; }); } SettableDisposable.prototype.setDisposable = function (disposable) { if (this.disposable !== void 0) { throw new Error('setDisposable called more than once'); } this.disposable = disposable; if (this.disposed) { this._resolve(disposable.dispose()); } }; SettableDisposable.prototype.dispose = function () { if (this.disposed) { return this.result; } this.disposed = true; if (this.disposable !== void 0) { this.result = this.disposable.dispose(); } return this.result; }; /***/ }, /* 74 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Pipe = __webpack_require__(1); module.exports = FilterMap; function FilterMap(p, f, source) { this.p = p; this.f = f; this.source = source; } FilterMap.prototype.run = function (sink, scheduler) { return this.source.run(new FilterMapSink(this.p, this.f, sink), scheduler); }; function FilterMapSink(p, f, sink) { this.p = p; this.f = f; this.sink = sink; } FilterMapSink.prototype.event = function (t, x) { var f = this.f; var p = this.p; p(x) && this.sink.event(t, f(x)); }; FilterMapSink.prototype.end = Pipe.prototype.end; FilterMapSink.prototype.error = Pipe.prototype.error; /***/ }, /* 75 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var base = __webpack_require__(3); module.exports = Scheduler; function ScheduledTask(delay, period, task, scheduler) { this.time = delay; this.period = period; this.task = task; this.scheduler = scheduler; this.active = true; } ScheduledTask.prototype.run = function () { return this.task.run(this.time); }; ScheduledTask.prototype.error = function (e) { return this.task.error(this.time, e); }; ScheduledTask.prototype.cancel = function () { this.scheduler.cancel(this); return this.task.dispose(); }; function runTask(task) { try { return task.run(); } catch (e) { return task.error(e); } } function Scheduler(timer) { this.timer = timer; this._timer = null; this._nextArrival = 0; this._tasks = []; var self = this; this._runReadyTasksBound = function () { self._runReadyTasks(self.now()); }; } Scheduler.prototype.now = function () { return this.timer.now(); }; Scheduler.prototype.asap = function (task) { return this.schedule(0, -1, task); }; Scheduler.prototype.delay = function (delay, task) { return this.schedule(delay, -1, task); }; Scheduler.prototype.periodic = function (period, task) { return this.schedule(0, period, task); }; Scheduler.prototype.schedule = function (delay, period, task) { var now = this.now(); var st = new ScheduledTask(now + Math.max(0, delay), period, task, this); insertByTime(st, this._tasks); this._scheduleNextRun(now); return st; }; Scheduler.prototype.cancel = function (task) { task.active = false; var i = binarySearch(task.time, this._tasks); if (i >= 0 && i < this._tasks.length) { var at = base.findIndex(task, this._tasks[i].events); if (at >= 0) { this._tasks[i].events.splice(at, 1); this._reschedule(); } } }; Scheduler.prototype.cancelAll = function (f) { for (var i = 0; i < this._tasks.length; ++i) { removeAllFrom(f, this._tasks[i]); } this._reschedule(); }; function removeAllFrom(f, timeslot) { timeslot.events = base.removeAll(f, timeslot.events); } Scheduler.prototype._reschedule = function () { if (this._tasks.length === 0) { this._unschedule(); } else { this._scheduleNextRun(this.now()); } }; Scheduler.prototype._unschedule = function () { this.timer.clearTimer(this._timer); this._timer = null; }; Scheduler.prototype._scheduleNextRun = function (now) { if (this._tasks.length === 0) { return; } var nextArrival = this._tasks[0].time; if (this._timer === null) { this._scheduleNextArrival(nextArrival, now); } else if (nextArrival < this._nextArrival) { this._unschedule(); this._scheduleNextArrival(nextArrival, now); } }; Scheduler.prototype._scheduleNextArrival = function (nextArrival, now) { this._nextArrival = nextArrival; var delay = Math.max(0, nextArrival - now); this._timer = this.timer.setTimer(this._runReadyTasksBound, delay); }; Scheduler.prototype._runReadyTasks = function (now) { this._timer = null; this._tasks = this._findAndRunTasks(now); this._scheduleNextRun(this.now()); }; Scheduler.prototype._findAndRunTasks = function (now) { var tasks = this._tasks; var l = tasks.length; var i = 0; while (i < l && tasks[i].time <= now) { ++i; } this._tasks = tasks.slice(i); // Run all ready tasks for (var j = 0; j < i; ++j) { this._tasks = runTasks(tasks[j], this._tasks); } return this._tasks; }; function runTasks(timeslot, tasks) { var events = timeslot.events; for (var i = 0; i < events.length; ++i) { var task = events[i]; if (task.active) { runTask(task); // Reschedule periodic repeating tasks // Check active again, since a task may have canceled itself if (task.period >= 0) { task.time = task.time + task.period; insertByTime(task, tasks); } } } return tasks; } function insertByTime(task, timeslots) { var l = timeslots.length; if (l === 0) { timeslots.push(newTimeslot(task.time, [task])); return; } var i = binarySearch(task.time, timeslots); if (i >= l) { timeslots.push(newTimeslot(task.time, [task])); } else if (task.time === timeslots[i].time) { timeslots[i].events.push(task); } else { timeslots.splice(i, 0, newTimeslot(task.time, [task])); } } function binarySearch(t, sortedArray) { var lo = 0; var hi = sortedArray.length; var mid, y; while (lo < hi) { mid = Math.floor((lo + hi) / 2); y = sortedArray[mid]; if (t === y.time) { return mid; } else if (t < y.time) { hi = mid; } else { lo = mid + 1; } } return hi; } function newTimeslot(t, events) { return { time: t, events: events }; } /***/ }, /* 76 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Scheduler = __webpack_require__(75); var setTimeoutTimer = __webpack_require__(78); var nodeTimer = __webpack_require__(77); var isNode = (typeof process === 'undefined' ? 'undefined' : _typeof(process)) === 'object' && typeof process.nextTick === 'function'; module.exports = new Scheduler(isNode ? nodeTimer : setTimeoutTimer); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(17))) /***/ }, /* 77 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var defer = __webpack_require__(27); /*global setTimeout, clearTimeout*/ function Task(f) { this.f = f; this.active = true; } Task.prototype.run = function () { if (!this.active) { return; } var f = this.f; return f(); }; Task.prototype.error = function (e) { throw e; }; Task.prototype.cancel = function () { this.active = false; }; function runAsTask(f) { var task = new Task(f); defer(task); return task; } module.exports = { now: Date.now, setTimer: function setTimer(f, dt) { return dt <= 0 ? runAsTask(f) : setTimeout(f, dt); }, clearTimer: function clearTimer(t) { return t instanceof Task ? t.cancel() : clearTimeout(t); } }; /***/ }, /* 78 */ /***/ function(module, exports) { "use strict"; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ /*global setTimeout, clearTimeout*/ module.exports = { now: Date.now, setTimer: function setTimer(f, dt) { return setTimeout(f, dt); }, clearTimer: function clearTimer(t) { return clearTimeout(t); } }; /***/ }, /* 79 */ /***/ function(module, exports) { "use strict"; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ module.exports = Observer; /** * Sink that accepts functions to apply to each event, and to end, and error * signals. * @constructor */ function Observer(event, end, error, disposable) { this._event = event; this._end = end; this._error = error; this._disposable = disposable; this.active = true; } Observer.prototype.event = function (t, x) { if (!this.active) { return; } this._event(x); }; Observer.prototype.end = function (t, x) { if (!this.active) { return; } this.active = false; disposeThen(this._end, this._error, this._disposable, x); }; Observer.prototype.error = function (t, e) { this.active = false; disposeThen(this._error, this._error, this._disposable, e); }; function disposeThen(end, error, disposable, x) { Promise.resolve(disposable.dispose()).then(function () { end(x); }, error); } /***/ }, /* 80 */ /***/ function(module, exports) { "use strict"; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ module.exports = SafeSink; function SafeSink(sink) { this.sink = sink; this.active = true; } SafeSink.prototype.event = function (t, x) { if (!this.active) { return; } this.sink.event(t, x); }; SafeSink.prototype.end = function (t, x) { if (!this.active) { return; } this.disable(); this.sink.end(t, x); }; SafeSink.prototype.error = function (t, e) { this.disable(); this.sink.error(t, e); }; SafeSink.prototype.disable = function () { this.active = false; return this.sink; }; /***/ }, /* 81 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var DeferredSink = __webpack_require__(33); var dispose = __webpack_require__(2); var tryEvent = __webpack_require__(9); module.exports = EventEmitterSource; function EventEmitterSource(event, source) { this.event = event; this.source = source; } EventEmitterSource.prototype.run = function (sink, scheduler) { // NOTE: Because EventEmitter allows events in the same call stack as // a listener is added, use a DeferredSink to buffer events // until the stack clears, then propagate. This maintains most.js's // invariant that no event will be delivered in the same call stack // as an observer begins observing. var dsink = new DeferredSink(sink); function addEventVariadic(a) { var l = arguments.length; if (l > 1) { var arr = new Array(l); for (var i = 0; i < l; ++i) { arr[i] = arguments[i]; } tryEvent.tryEvent(scheduler.now(), arr, dsink); } else { tryEvent.tryEvent(scheduler.now(), a, dsink); } } this.source.addListener(this.event, addEventVariadic); return dispose.create(disposeEventEmitter, { target: this, addEvent: addEventVariadic }); }; function disposeEventEmitter(info) { var target = info.target; target.source.removeListener(target.event, info.addEvent); } /***/ }, /* 82 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var dispose = __webpack_require__(2); var tryEvent = __webpack_require__(9); module.exports = EventTargetSource; function EventTargetSource(event, source, capture) { this.event = event; this.source = source; this.capture = capture; } EventTargetSource.prototype.run = function (sink, scheduler) { function addEvent(e) { tryEvent.tryEvent(scheduler.now(), e, sink); } this.source.addEventListener(this.event, addEvent, this.capture); return dispose.create(disposeEventTarget, { target: this, addEvent: addEvent }); }; function disposeEventTarget(info) { var target = info.target; target.source.removeEventListener(target.event, info.addEvent, target.capture); } /***/ }, /* 83 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var MulticastSource = __webpack_require__(5).MulticastSource; var DeferredSink = __webpack_require__(33); var tryEvent = __webpack_require__(9); exports.create = create; function create(run) { return new Stream(new MulticastSource(new SubscriberSource(run))); } function SubscriberSource(subscribe) { this._subscribe = subscribe; } SubscriberSource.prototype.run = function (sink, scheduler) { return new Subscription(new DeferredSink(sink), scheduler, this._subscribe); }; function Subscription(sink, scheduler, subscribe) { this.sink = sink; this.scheduler = scheduler; this.active = true; this._unsubscribe = this._init(subscribe); } Subscription.prototype._init = function (subscribe) { var s = this; try { return subscribe(add, end, error); } catch (e) { error(e); } function add(x) { s._add(x); } function end(x) { s._end(x); } function error(e) { s._error(e); } }; Subscription.prototype._add = function (x) { if (!this.active) { return; } tryEvent.tryEvent(this.scheduler.now(), x, this.sink); }; Subscription.prototype._end = function (x) { if (!this.active) { return; } this.active = false; tryEvent.tryEnd(this.scheduler.now(), x, this.sink); }; Subscription.prototype._error = function (x) { this.active = false; this.sink.error(this.scheduler.now(), x); }; Subscription.prototype.dispose = function () { this.active = false; if (typeof this._unsubscribe === 'function') { return this._unsubscribe.call(void 0); } }; /***/ }, /* 84 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var fromArray = __webpack_require__(85).fromArray; var isIterable = __webpack_require__(31).isIterable; var fromIterable = __webpack_require__(87).fromIterable; var isArrayLike = __webpack_require__(3).isArrayLike; exports.from = from; function from(a) { if (Array.isArray(a) || isArrayLike(a)) { return fromArray(a); } if (isIterable(a)) { return fromIterable(a); } throw new TypeError('not iterable: ' + a); } /***/ }, /* 85 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var PropagateTask = __webpack_require__(6); exports.fromArray = fromArray; function fromArray(a) { return new Stream(new ArraySource(a)); } function ArraySource(a) { this.array = a; } ArraySource.prototype.run = function (sink, scheduler) { return new ArrayProducer(this.array, sink, scheduler); }; function ArrayProducer(array, sink, scheduler) { this.scheduler = scheduler; this.task = new PropagateTask(runProducer, array, sink); scheduler.asap(this.task); } ArrayProducer.prototype.dispose = function () { return this.task.dispose(); }; function runProducer(t, array, sink) { produce(this, array, sink); } function produce(task, array, sink) { for (var i = 0, l = array.length; i < l && task.active; ++i) { sink.event(0, array[i]); } task.active && end(); function end() { sink.end(0); } } /***/ }, /* 86 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var MulticastSource = __webpack_require__(5).MulticastSource; var EventTargetSource = __webpack_require__(82); var EventEmitterSource = __webpack_require__(81); exports.fromEvent = fromEvent; /** * Create a stream from an EventTarget, such as a DOM Node, or EventEmitter. * @param {String} event event type name, e.g. 'click' * @param {EventTarget|EventEmitter} source EventTarget or EventEmitter * @param {boolean?} useCapture for DOM events, whether to use * capturing--passed as 3rd parameter to addEventListener. * @returns {Stream} stream containing all events of the specified type * from the source. */ function fromEvent(event, source /*, useCapture = false */) { var s; if (typeof source.addEventListener === 'function' && typeof source.removeEventListener === 'function') { var capture = arguments.length > 2 && !!arguments[2]; s = new MulticastSource(new EventTargetSource(event, source, capture)); } else if (typeof source.addListener === 'function' && typeof source.removeListener === 'function') { s = new EventEmitterSource(event, source); } else { throw new Error('source must support addEventListener/removeEventListener or addListener/removeListener'); } return new Stream(s); } /***/ }, /* 87 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var getIterator = __webpack_require__(31).getIterator; var PropagateTask = __webpack_require__(6); exports.fromIterable = fromIterable; function fromIterable(iterable) { return new Stream(new IterableSource(iterable)); } function IterableSource(iterable) { this.iterable = iterable; } IterableSource.prototype.run = function (sink, scheduler) { return new IteratorProducer(getIterator(this.iterable), sink, scheduler); }; function IteratorProducer(iterator, sink, scheduler) { this.scheduler = scheduler; this.iterator = iterator; this.task = new PropagateTask(runProducer, this, sink); scheduler.asap(this.task); } IteratorProducer.prototype.dispose = function () { return this.task.dispose(); }; function runProducer(t, producer, sink) { var x = producer.iterator.next(); if (x.done) { sink.end(t, x.value); } else { sink.event(t, x.value); } producer.scheduler.asap(producer.task); } /***/ }, /* 88 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var base = __webpack_require__(3); exports.generate = generate; /** * Compute a stream using an *async* generator, which yields promises * to control event times. * @param f * @returns {Stream} */ function generate(f /*, ...args */) { return new Stream(new GenerateSource(f, base.tail(arguments))); } function GenerateSource(f, args) { this.f = f; this.args = args; } GenerateSource.prototype.run = function (sink, scheduler) { return new Generate(this.f.apply(void 0, this.args), sink, scheduler); }; function Generate(iterator, sink, scheduler) { this.iterator = iterator; this.sink = sink; this.scheduler = scheduler; this.active = true; var self = this; function err(e) { self.sink.error(self.scheduler.now(), e); } Promise.resolve(this).then(next).catch(err); } function next(generate, x) { return generate.active ? handle(generate, generate.iterator.next(x)) : x; } function handle(generate, result) { if (result.done) { return generate.sink.end(generate.scheduler.now(), result.value); } return Promise.resolve(result.value).then(function (x) { return emit(generate, x); }, function (e) { return error(generate, e); }); } function emit(generate, x) { generate.sink.event(generate.scheduler.now(), x); return next(generate, x); } function error(generate, e) { return handle(generate, generate.iterator.throw(e)); } Generate.prototype.dispose = function () { this.active = false; }; /***/ }, /* 89 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); exports.iterate = iterate; /** * Compute a stream by iteratively calling f to produce values * Event times may be controlled by returning a Promise from f * @param {function(x:*):*|Promise<*>} f * @param {*} x initial value * @returns {Stream} */ function iterate(f, x) { return new Stream(new IterateSource(f, x)); } function IterateSource(f, x) { this.f = f; this.value = x; } IterateSource.prototype.run = function (sink, scheduler) { return new Iterate(this.f, this.value, sink, scheduler); }; function Iterate(f, initial, sink, scheduler) { this.f = f; this.sink = sink; this.scheduler = scheduler; this.active = true; var x = initial; var self = this; function err(e) { self.sink.error(self.scheduler.now(), e); } function start(iterate) { return stepIterate(iterate, x); } Promise.resolve(this).then(start).catch(err); } Iterate.prototype.dispose = function () { this.active = false; }; function stepIterate(iterate, x) { iterate.sink.event(iterate.scheduler.now(), x); if (!iterate.active) { return x; } var f = iterate.f; return Promise.resolve(f(x)).then(function (y) { return continueIterate(iterate, y); }); } function continueIterate(iterate, x) { return !iterate.active ? iterate.value : stepIterate(iterate, x); } /***/ }, /* 90 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var dispose = __webpack_require__(2); var MulticastSource = __webpack_require__(5).MulticastSource; var PropagateTask = __webpack_require__(6); exports.periodic = periodic; /** * Create a stream that emits the current time periodically * @param {Number} period periodicity of events in millis * @param {*) value value to emit each period * @returns {Stream} new stream that emits the current time every period */ function periodic(period, value) { return new Stream(new MulticastSource(new Periodic(period, value))); } function Periodic(period, value) { this.period = period; this.value = value; } Periodic.prototype.run = function (sink, scheduler) { var task = scheduler.periodic(this.period, new PropagateTask(emit, this.value, sink)); return dispose.create(cancelTask, task); }; function cancelTask(task) { task.cancel(); } function emit(t, x, sink) { sink.event(t, x); } /***/ }, /* 91 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); exports.unfold = unfold; /** * Compute a stream by unfolding tuples of future values from a seed value * Event times may be controlled by returning a Promise from f * @param {function(seed:*):{value:*, seed:*, done:boolean}|Promise<{value:*, seed:*, done:boolean}>} f unfolding function accepts * a seed and returns a new tuple with a value, new seed, and boolean done flag. * If tuple.done is true, the stream will end. * @param {*} seed seed value * @returns {Stream} stream containing all value of all tuples produced by the * unfolding function. */ function unfold(f, seed) { return new Stream(new UnfoldSource(f, seed)); } function UnfoldSource(f, seed) { this.f = f; this.value = seed; } UnfoldSource.prototype.run = function (sink, scheduler) { return new Unfold(this.f, this.value, sink, scheduler); }; function Unfold(f, x, sink, scheduler) { this.f = f; this.sink = sink; this.scheduler = scheduler; this.active = true; var self = this; function err(e) { self.sink.error(self.scheduler.now(), e); } function start(unfold) { return stepUnfold(unfold, x); } Promise.resolve(this).then(start).catch(err); } Unfold.prototype.dispose = function () { this.active = false; }; function stepUnfold(unfold, x) { var f = unfold.f; return Promise.resolve(f(x)).then(function (tuple) { return continueUnfold(unfold, tuple); }); } function continueUnfold(unfold, tuple) { if (tuple.done) { unfold.sink.end(unfold.scheduler.now(), tuple.value); return tuple.value; } unfold.sink.event(unfold.scheduler.now(), tuple.value); if (!unfold.active) { return tuple.value; } return stepUnfold(unfold, tuple.seed); } /***/ }, /* 92 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = classNameFromVNode; var _selectorParser2 = __webpack_require__(35); var _selectorParser3 = _interopRequireDefault(_selectorParser2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function classNameFromVNode(vNode) { var _selectorParser = (0, _selectorParser3.default)(vNode.sel); var cn = _selectorParser.className; if (!vNode.data) { return cn; } var _vNode$data = vNode.data; var dataClass = _vNode$data.class; var props = _vNode$data.props; if (dataClass) { var c = Object.keys(vNode.data.class).filter(function (cl) { return vNode.data.class[cl]; }); cn += ' ' + c.join(' '); } if (props && props.className) { cn += ' ' + props.className; } return cn.trim(); } /***/ }, /* 93 */ /***/ function(module, exports) { "use strict"; function createElement(tagName) { return document.createElement(tagName); } function createElementNS(namespaceURI, qualifiedName) { return document.createElementNS(namespaceURI, qualifiedName); } function createTextNode(text) { return document.createTextNode(text); } function insertBefore(parentNode, newNode, referenceNode) { parentNode.insertBefore(newNode, referenceNode); } function removeChild(node, child) { node.removeChild(child); } function appendChild(node, child) { node.appendChild(child); } function parentNode(node) { return node.parentElement; } function nextSibling(node) { return node.nextSibling; } function tagName(node) { return node.tagName; } function setTextContent(node, text) { node.textContent = text; } module.exports = { createElement: createElement, createElementNS: createElementNS, createTextNode: createTextNode, appendChild: appendChild, removeChild: removeChild, insertBefore: insertBefore, parentNode: parentNode, nextSibling: nextSibling, tagName: tagName, setTextContent: setTextContent }; /***/ }, /* 94 */ /***/ function(module, exports) { "use strict"; var booleanAttrs = ["allowfullscreen", "async", "autofocus", "autoplay", "checked", "compact", "controls", "declare", "default", "defaultchecked", "defaultmuted", "defaultselected", "defer", "disabled", "draggable", "enabled", "formnovalidate", "hidden", "indeterminate", "inert", "ismap", "itemscope", "loop", "multiple", "muted", "nohref", "noresize", "noshade", "novalidate", "nowrap", "open", "pauseonexit", "readonly", "required", "reversed", "scoped", "seamless", "selected", "sortable", "spellcheck", "translate", "truespeed", "typemustmatch", "visible"]; var booleanAttrsDict = {}; for (var i = 0, len = booleanAttrs.length; i < len; i++) { booleanAttrsDict[booleanAttrs[i]] = true; } function updateAttrs(oldVnode, vnode) { var key, cur, old, elm = vnode.elm, oldAttrs = oldVnode.data.attrs || {}, attrs = vnode.data.attrs || {}; // update modified attributes, add new attributes for (key in attrs) { cur = attrs[key]; old = oldAttrs[key]; if (old !== cur) { // TODO: add support to namespaced attributes (setAttributeNS) if (!cur && booleanAttrsDict[key]) elm.removeAttribute(key);else elm.setAttribute(key, cur); } } //remove removed attributes // use `in` operator since the previous `for` iteration uses it (.i.e. add even attributes with undefined value) // the other option is to remove all attributes with value == undefined for (key in oldAttrs) { if (!(key in attrs)) { elm.removeAttribute(key); } } } module.exports = { create: updateAttrs, update: updateAttrs }; /***/ }, /* 95 */ /***/ function(module, exports) { 'use strict'; function updateClass(oldVnode, vnode) { var cur, name, elm = vnode.elm, oldClass = oldVnode.data.class || {}, klass = vnode.data.class || {}; for (name in oldClass) { if (!klass[name]) { elm.classList.remove(name); } } for (name in klass) { cur = klass[name]; if (cur !== oldClass[name]) { elm.classList[cur ? 'add' : 'remove'](name); } } } module.exports = { create: updateClass, update: updateClass }; /***/ }, /* 96 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var is = __webpack_require__(10); function arrInvoker(arr) { return function () { // Special case when length is two, for performance arr.length === 2 ? arr[0](arr[1]) : arr[0].apply(undefined, arr.slice(1)); }; } function fnInvoker(o) { return function (ev) { o.fn(ev); }; } function updateEventListeners(oldVnode, vnode) { var name, cur, old, elm = vnode.elm, oldOn = oldVnode.data.on || {}, on = vnode.data.on; if (!on) return; for (name in on) { cur = on[name]; old = oldOn[name]; if (old === undefined) { if (is.array(cur)) { elm.addEventListener(name, arrInvoker(cur)); } else { cur = { fn: cur }; on[name] = cur; elm.addEventListener(name, fnInvoker(cur)); } } else if (is.array(old)) { // Deliberately modify old array since it's captured in closure created with `arrInvoker` old.length = cur.length; for (var i = 0; i < old.length; ++i) { old[i] = cur[i]; }on[name] = old; } else { old.fn = cur; on[name] = old; } } } module.exports = { create: updateEventListeners, update: updateEventListeners }; /***/ }, /* 97 */ /***/ function(module, exports) { 'use strict'; var raf = typeof window !== 'undefined' && window.requestAnimationFrame || setTimeout; var nextFrame = function nextFrame(fn) { raf(function () { raf(fn); }); }; function setNextFrame(obj, prop, val) { nextFrame(function () { obj[prop] = val; }); } function getTextNodeRect(textNode) { var rect; if (document.createRange) { var range = document.createRange(); range.selectNodeContents(textNode); if (range.getBoundingClientRect) { rect = range.getBoundingClientRect(); } } return rect; } function calcTransformOrigin(isTextNode, textRect, boundingRect) { if (isTextNode) { if (textRect) { //calculate pixels to center of text from left edge of bounding box var relativeCenterX = textRect.left + textRect.width / 2 - boundingRect.left; var relativeCenterY = textRect.top + textRect.height / 2 - boundingRect.top; return relativeCenterX + 'px ' + relativeCenterY + 'px'; } } return '0 0'; //top left } function getTextDx(oldTextRect, newTextRect) { if (oldTextRect && newTextRect) { return oldTextRect.left + oldTextRect.width / 2 - (newTextRect.left + newTextRect.width / 2); } return 0; } function getTextDy(oldTextRect, newTextRect) { if (oldTextRect && newTextRect) { return oldTextRect.top + oldTextRect.height / 2 - (newTextRect.top + newTextRect.height / 2); } return 0; } function isTextElement(elm) { return elm.childNodes.length === 1 && elm.childNodes[0].nodeType === 3; } var removed, created; function pre(oldVnode, vnode) { removed = {}; created = []; } function create(oldVnode, vnode) { var hero = vnode.data.hero; if (hero && hero.id) { created.push(hero.id); created.push(vnode); } } function destroy(vnode) { var hero = vnode.data.hero; if (hero && hero.id) { var elm = vnode.elm; vnode.isTextNode = isTextElement(elm); //is this a text node? vnode.boundingRect = elm.getBoundingClientRect(); //save the bounding rectangle to a new property on the vnode vnode.textRect = vnode.isTextNode ? getTextNodeRect(elm.childNodes[0]) : null; //save bounding rect of inner text node var computedStyle = window.getComputedStyle(elm, null); //get current styles (includes inherited properties) vnode.savedStyle = JSON.parse(JSON.stringify(computedStyle)); //save a copy of computed style values removed[hero.id] = vnode; } } function post() { var i, id, newElm, oldVnode, oldElm, hRatio, wRatio, oldRect, newRect, dx, dy, origTransform, origTransition, newStyle, oldStyle, newComputedStyle, isTextNode, newTextRect, oldTextRect; for (i = 0; i < created.length; i += 2) { id = created[i]; newElm = created[i + 1].elm; oldVnode = removed[id]; if (oldVnode) { isTextNode = oldVnode.isTextNode && isTextElement(newElm); //Are old & new both text? newStyle = newElm.style; newComputedStyle = window.getComputedStyle(newElm, null); //get full computed style for new element oldElm = oldVnode.elm; oldStyle = oldElm.style; //Overall element bounding boxes newRect = newElm.getBoundingClientRect(); oldRect = oldVnode.boundingRect; //previously saved bounding rect //Text node bounding boxes & distances if (isTextNode) { newTextRect = getTextNodeRect(newElm.childNodes[0]); oldTextRect = oldVnode.textRect; dx = getTextDx(oldTextRect, newTextRect); dy = getTextDy(oldTextRect, newTextRect); } else { //Calculate distances between old & new positions dx = oldRect.left - newRect.left; dy = oldRect.top - newRect.top; } hRatio = newRect.height / Math.max(oldRect.height, 1); wRatio = isTextNode ? hRatio : newRect.width / Math.max(oldRect.width, 1); //text scales based on hRatio // Animate new element origTransform = newStyle.transform; origTransition = newStyle.transition; if (newComputedStyle.display === 'inline') //inline elements cannot be transformed newStyle.display = 'inline-block'; //this does not appear to have any negative side effects newStyle.transition = origTransition + 'transform 0s'; newStyle.transformOrigin = calcTransformOrigin(isTextNode, newTextRect, newRect); newStyle.opacity = '0'; newStyle.transform = origTransform + 'translate(' + dx + 'px, ' + dy + 'px) ' + 'scale(' + 1 / wRatio + ', ' + 1 / hRatio + ')'; setNextFrame(newStyle, 'transition', origTransition); setNextFrame(newStyle, 'transform', origTransform); setNextFrame(newStyle, 'opacity', '1'); // Animate old element for (var key in oldVnode.savedStyle) { //re-apply saved inherited properties if (parseInt(key) != key) { var ms = key.substring(0, 2) === 'ms'; var moz = key.substring(0, 3) === 'moz'; var webkit = key.substring(0, 6) === 'webkit'; if (!ms && !moz && !webkit) //ignore prefixed style properties oldStyle[key] = oldVnode.savedStyle[key]; } } oldStyle.position = 'absolute'; oldStyle.top = oldRect.top + 'px'; //start at existing position oldStyle.left = oldRect.left + 'px'; oldStyle.width = oldRect.width + 'px'; //Needed for elements who were sized relative to their parents oldStyle.height = oldRect.height + 'px'; //Needed for elements who were sized relative to their parents oldStyle.margin = 0; //Margin on hero element leads to incorrect positioning oldStyle.transformOrigin = calcTransformOrigin(isTextNode, oldTextRect, oldRect); oldStyle.transform = ''; oldStyle.opacity = '1'; document.body.appendChild(oldElm); setNextFrame(oldStyle, 'transform', 'translate(' + -dx + 'px, ' + -dy + 'px) scale(' + wRatio + ', ' + hRatio + ')'); //scale must be on far right for translate to be correct setNextFrame(oldStyle, 'opacity', '0'); oldElm.addEventListener('transitionend', function (ev) { if (ev.propertyName === 'transform') document.body.removeChild(ev.target); }); } } removed = created = undefined; } module.exports = { pre: pre, create: create, destroy: destroy, post: post }; /***/ }, /* 98 */ /***/ function(module, exports) { 'use strict'; function updateProps(oldVnode, vnode) { var key, cur, old, elm = vnode.elm, oldProps = oldVnode.data.props || {}, props = vnode.data.props || {}; for (key in oldProps) { if (!props[key]) { delete elm[key]; } } for (key in props) { cur = props[key]; old = oldProps[key]; if (old !== cur && (key !== 'value' || elm[key] !== cur)) { elm[key] = cur; } } } module.exports = { create: updateProps, update: updateProps }; /***/ }, /* 99 */ /***/ function(module, exports) { 'use strict'; var raf = typeof window !== 'undefined' && window.requestAnimationFrame || setTimeout; var nextFrame = function nextFrame(fn) { raf(function () { raf(fn); }); }; function setNextFrame(obj, prop, val) { nextFrame(function () { obj[prop] = val; }); } function updateStyle(oldVnode, vnode) { var cur, name, elm = vnode.elm, oldStyle = oldVnode.data.style || {}, style = vnode.data.style || {}, oldHasDel = 'delayed' in oldStyle; for (name in oldStyle) { if (!style[name]) { elm.style[name] = ''; } } for (name in style) { cur = style[name]; if (name === 'delayed') { for (name in style.delayed) { cur = style.delayed[name]; if (!oldHasDel || cur !== oldStyle.delayed[name]) { setNextFrame(elm.style, name, cur); } } } else if (name !== 'remove' && cur !== oldStyle[name]) { elm.style[name] = cur; } } } function applyDestroyStyle(vnode) { var style, name, elm = vnode.elm, s = vnode.data.style; if (!s || !(style = s.destroy)) return; for (name in style) { elm.style[name] = style[name]; } } function applyRemoveStyle(vnode, rm) { var s = vnode.data.style; if (!s || !s.remove) { rm(); return; } var name, elm = vnode.elm, idx, i = 0, maxDur = 0, compStyle, style = s.remove, amount = 0, applied = []; for (name in style) { applied.push(name); elm.style[name] = style[name]; } compStyle = getComputedStyle(elm); var props = compStyle['transition-property'].split(', '); for (; i < props.length; ++i) { if (applied.indexOf(props[i]) !== -1) amount++; } elm.addEventListener('transitionend', function (ev) { if (ev.target === elm) --amount; if (amount === 0) rm(); }); } module.exports = { create: updateStyle, update: updateStyle, destroy: applyDestroyStyle, remove: applyRemoveStyle }; /***/ }, /* 100 */ /***/ function(module, exports, __webpack_require__) { // jshint newcap: false /* global require, module, document, Node */ 'use strict'; var VNode = __webpack_require__(15); var is = __webpack_require__(10); var domApi = __webpack_require__(93); function isUndef(s) { return s === undefined; } function isDef(s) { return s !== undefined; } var emptyNode = VNode('', {}, [], undefined, undefined); function sameVnode(vnode1, vnode2) { return vnode1.key === vnode2.key && vnode1.sel === vnode2.sel; } function createKeyToOldIdx(children, beginIdx, endIdx) { var i, map = {}, key; for (i = beginIdx; i <= endIdx; ++i) { key = children[i].key; if (isDef(key)) map[key] = i; } return map; } var hooks = ['create', 'update', 'remove', 'destroy', 'pre', 'post']; function init(modules, api) { var i, j, cbs = {}; if (isUndef(api)) api = domApi; for (i = 0; i < hooks.length; ++i) { cbs[hooks[i]] = []; for (j = 0; j < modules.length; ++j) { if (modules[j][hooks[i]] !== undefined) cbs[hooks[i]].push(modules[j][hooks[i]]); } } function emptyNodeAt(elm) { return VNode(api.tagName(elm).toLowerCase(), {}, [], undefined, elm); } function createRmCb(childElm, listeners) { return function () { if (--listeners === 0) { var parent = api.parentNode(childElm); api.removeChild(parent, childElm); } }; } function createElm(vnode, insertedVnodeQueue) { var i, thunk, data = vnode.data; if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.init)) i(vnode); if (isDef(i = data.vnode)) { thunk = vnode; vnode = i; } } var elm, children = vnode.children, sel = vnode.sel; if (isDef(sel)) { // Parse selector var hashIdx = sel.indexOf('#'); var dotIdx = sel.indexOf('.', hashIdx); var hash = hashIdx > 0 ? hashIdx : sel.length; var dot = dotIdx > 0 ? dotIdx : sel.length; var tag = hashIdx !== -1 || dotIdx !== -1 ? sel.slice(0, Math.min(hash, dot)) : sel; elm = vnode.elm = isDef(data) && isDef(i = data.ns) ? api.createElementNS(i, tag) : api.createElement(tag); if (hash < dot) elm.id = sel.slice(hash + 1, dot); if (dotIdx > 0) elm.className = sel.slice(dot + 1).replace(/\./g, ' '); if (is.array(children)) { for (i = 0; i < children.length; ++i) { api.appendChild(elm, createElm(children[i], insertedVnodeQueue)); } } else if (is.primitive(vnode.text)) { api.appendChild(elm, api.createTextNode(vnode.text)); } for (i = 0; i < cbs.create.length; ++i) { cbs.create[i](emptyNode, vnode); }i = vnode.data.hook; // Reuse variable if (isDef(i)) { if (i.create) i.create(emptyNode, vnode); if (i.insert) insertedVnodeQueue.push(vnode); } } else { elm = vnode.elm = api.createTextNode(vnode.text); } if (isDef(thunk)) thunk.elm = vnode.elm; return vnode.elm; } function addVnodes(parentElm, before, vnodes, startIdx, endIdx, insertedVnodeQueue) { for (; startIdx <= endIdx; ++startIdx) { api.insertBefore(parentElm, createElm(vnodes[startIdx], insertedVnodeQueue), before); } } function invokeDestroyHook(vnode) { var i, j, data = vnode.data; if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.destroy)) i(vnode); for (i = 0; i < cbs.destroy.length; ++i) { cbs.destroy[i](vnode); }if (isDef(i = vnode.children)) { for (j = 0; j < vnode.children.length; ++j) { invokeDestroyHook(vnode.children[j]); } } if (isDef(i = data.vnode)) invokeDestroyHook(i); } } function removeVnodes(parentElm, vnodes, startIdx, endIdx) { for (; startIdx <= endIdx; ++startIdx) { var i, listeners, rm, ch = vnodes[startIdx]; if (isDef(ch)) { if (isDef(ch.sel)) { invokeDestroyHook(ch); listeners = cbs.remove.length + 1; rm = createRmCb(ch.elm, listeners); for (i = 0; i < cbs.remove.length; ++i) { cbs.remove[i](ch, rm); }if (isDef(i = ch.data) && isDef(i = i.hook) && isDef(i = i.remove)) { i(ch, rm); } else { rm(); } } else { // Text node api.removeChild(parentElm, ch.elm); } } } } function updateChildren(parentElm, oldCh, newCh, insertedVnodeQueue) { var oldStartIdx = 0, newStartIdx = 0; var oldEndIdx = oldCh.length - 1; var oldStartVnode = oldCh[0]; var oldEndVnode = oldCh[oldEndIdx]; var newEndIdx = newCh.length - 1; var newStartVnode = newCh[0]; var newEndVnode = newCh[newEndIdx]; var oldKeyToIdx, idxInOld, elmToMove, before; while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) { if (isUndef(oldStartVnode)) { oldStartVnode = oldCh[++oldStartIdx]; // Vnode has been moved left } else if (isUndef(oldEndVnode)) { oldEndVnode = oldCh[--oldEndIdx]; } else if (sameVnode(oldStartVnode, newStartVnode)) { patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue); oldStartVnode = oldCh[++oldStartIdx]; newStartVnode = newCh[++newStartIdx]; } else if (sameVnode(oldEndVnode, newEndVnode)) { patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue); oldEndVnode = oldCh[--oldEndIdx]; newEndVnode = newCh[--newEndIdx]; } else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue); api.insertBefore(parentElm, oldStartVnode.elm, api.nextSibling(oldEndVnode.elm)); oldStartVnode = oldCh[++oldStartIdx]; newEndVnode = newCh[--newEndIdx]; } else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue); api.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm); oldEndVnode = oldCh[--oldEndIdx]; newStartVnode = newCh[++newStartIdx]; } else { if (isUndef(oldKeyToIdx)) oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx); idxInOld = oldKeyToIdx[newStartVnode.key]; if (isUndef(idxInOld)) { // New element api.insertBefore(parentElm, createElm(newStartVnode, insertedVnodeQueue), oldStartVnode.elm); newStartVnode = newCh[++newStartIdx]; } else { elmToMove = oldCh[idxInOld]; patchVnode(elmToMove, newStartVnode, insertedVnodeQueue); oldCh[idxInOld] = undefined; api.insertBefore(parentElm, elmToMove.elm, oldStartVnode.elm); newStartVnode = newCh[++newStartIdx]; } } } if (oldStartIdx > oldEndIdx) { before = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm; addVnodes(parentElm, before, newCh, newStartIdx, newEndIdx, insertedVnodeQueue); } else if (newStartIdx > newEndIdx) { removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx); } } function patchVnode(oldVnode, vnode, insertedVnodeQueue) { var i, hook; if (isDef(i = vnode.data) && isDef(hook = i.hook) && isDef(i = hook.prepatch)) { i(oldVnode, vnode); } if (isDef(i = oldVnode.data) && isDef(i = i.vnode)) oldVnode = i; if (isDef(i = vnode.data) && isDef(i = i.vnode)) { patchVnode(oldVnode, i, insertedVnodeQueue); vnode.elm = i.elm; return; } var elm = vnode.elm = oldVnode.elm, oldCh = oldVnode.children, ch = vnode.children; if (oldVnode === vnode) return; if (!sameVnode(oldVnode, vnode)) { var parentElm = api.parentNode(oldVnode.elm); elm = createElm(vnode, insertedVnodeQueue); api.insertBefore(parentElm, elm, oldVnode.elm); removeVnodes(parentElm, [oldVnode], 0, 0); return; } if (isDef(vnode.data)) { for (i = 0; i < cbs.update.length; ++i) { cbs.update[i](oldVnode, vnode); }i = vnode.data.hook; if (isDef(i) && isDef(i = i.update)) i(oldVnode, vnode); } if (isUndef(vnode.text)) { if (isDef(oldCh) && isDef(ch)) { if (oldCh !== ch) updateChildren(elm, oldCh, ch, insertedVnodeQueue); } else if (isDef(ch)) { if (isDef(oldVnode.text)) api.setTextContent(elm, ''); addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue); } else if (isDef(oldCh)) { removeVnodes(elm, oldCh, 0, oldCh.length - 1); } else if (isDef(oldVnode.text)) { api.setTextContent(elm, ''); } } else if (oldVnode.text !== vnode.text) { api.setTextContent(elm, vnode.text); } if (isDef(hook) && isDef(i = hook.postpatch)) { i(oldVnode, vnode); } } return function (oldVnode, vnode) { var i, elm, parent; var insertedVnodeQueue = []; for (i = 0; i < cbs.pre.length; ++i) { cbs.pre[i](); }if (isUndef(oldVnode.sel)) { oldVnode = emptyNodeAt(oldVnode); } if (sameVnode(oldVnode, vnode)) { patchVnode(oldVnode, vnode, insertedVnodeQueue); } else { elm = oldVnode.elm; parent = api.parentNode(elm); createElm(vnode, insertedVnodeQueue); if (parent !== null) { api.insertBefore(parent, vnode.elm, api.nextSibling(elm)); removeVnodes(parent, [oldVnode], 0, 0); } } for (i = 0; i < insertedVnodeQueue.length; ++i) { insertedVnodeQueue[i].data.hook.insert(insertedVnodeQueue[i]); } for (i = 0; i < cbs.post.length; ++i) { cbs.post[i](); }return vnode; }; } module.exports = { init: init }; /***/ }, /* 101 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var h = __webpack_require__(36); function init(thunk) { var i, cur = thunk.data; cur.vnode = cur.fn.apply(undefined, cur.args); } function prepatch(oldThunk, thunk) { var i, old = oldThunk.data, cur = thunk.data; var oldArgs = old.args, args = cur.args; cur.vnode = old.vnode; if (old.fn !== cur.fn || oldArgs.length !== args.length) { cur.vnode = cur.fn.apply(undefined, args); return; } for (i = 0; i < args.length; ++i) { if (oldArgs[i] !== args[i]) { cur.vnode = cur.fn.apply(undefined, args); return; } } } module.exports = function (name, fn /* args */) { var i, args = []; for (i = 2; i < arguments.length; ++i) { args[i - 2] = arguments[i]; } return h('thunk' + name, { hook: { init: init, prepatch: prepatch }, fn: fn, args: args }); }; /***/ }, /* 102 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; var _core = __webpack_require__(37); var _core2 = _interopRequireDefault(_core); var _dom = __webpack_require__(16); var _most = __webpack_require__(4); var _code = __webpack_require__(38); var _code2 = _interopRequireDefault(_code); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function createWebSocket(path) { var host = window.location.hostname; if (host == '') host = 'localhost'; var uri = 'ws://' + host + ':3055' + path; var Socket = "MozWebSocket" in window ? MozWebSocket : WebSocket; return new Socket(uri); } var socket = createWebSocket('/'); var websocketsDriver = function websocketsDriver() { return (0, _most.create)(function (add) { socket.onmessage = function (msg) { return add(msg); }; }); }; function main(sources) { mMindex.ret(0); mMZ1.bnd(function (v) { return O.mMt1.bnd(add, v, mMt1).bnd(cube, mMt2).bnd(function () { return mMt3.ret(O.mMt1.x + ' cubed is ' + O.mMt2.x); }); }); mMZ2.bnd(function (v) { return cube(v).bnd(function (w) { return mMt3.ret(v + ' cubed is ' + w); }); }); var messages$ = sources.WS.map(function (e) { mMtem.ret(e.data.split(',')).bnd(function (v) { mMZ10.bnd(function () { return game([v[3], v[4], v[5], v[6]]); }); mMZ11.bnd(function () { return updateScoreboard(v[3]); }); mMZ12.bnd(function () { return mM6.ret(v[2] + ' successfully logged in.'); }); mMZ13.bnd(function () { return updateMessages(v); }); mMZ14.bnd(function () { return mMgoals2.ret('The winner is ' + v[2]); }); mMZ15.bnd(function () { return mMgoals2.ret('A player named ' + O.mMname.x + 'is currently logged in. Page will refresh in 4 seconds.').bnd(refresh); }); mMZ16.bnd(function () { if (O.mMname.x != v[2]) { mMgoals2.ret(v[2] + v[3]); } }); mMZ17.bnd(function () { if (v[3] == 'no file') { mMtaskList.ret([]); } else { process(e.data); } }); mMtemp.ret(e.data.split(',')[0]).bnd(next, 'CA#$42', mMZ10).bnd(next, 'CB#$42', mMZ11).bnd(next, 'CC#$42', mMZ12).bnd(next, 'CD#$42', mMZ13).bnd(next, 'CE#$42', mMZ14).bnd(next, 'EE#$42', mMZ15).bnd(next, 'DE#$42', mMZ16).bnd(next, 'DD#$42', mMZ17); }); }); var updateMessages = function updateMessages(ar) { var sender = ar[2]; mMhelper.ret(ar).bnd(splice, 0, 3, mMhelper).bnd(reduce).bnd(function (v) { return O.mMmsg.bnd(unshift, (0, _dom.h)('div', sender + ': ' + v), O.mMmsg); }); }; var loginPress$ = sources.DOM.select('input#login').events('keypress'); var loginPressAction$ = loginPress$.map(function (e) { var v = e.target.value; if (v == '') { return; } if (e.keyCode == 13) { socket.send("CC#$42" + v); mMname.ret(v.trim()); mM3.ret([]).bnd(mM2.ret); e.target.value = ''; document.getElementById('dice').style.display = 'block'; document.getElementById('rightPanel').style.display = 'block'; document.getElementById('log1').style.display = 'none'; document.getElementById('log2').style.display = 'block'; document.getElementById('gameDiv2').style.display = 'block'; } }); var groupPress$ = sources.DOM.select('input#group').events('keypress'); var groupPressAction$ = groupPress$.map(function (e) { var v = e.target.value; if (e.keyCode == 13) { mMgroup.ret(v); socket.send('CO#$42,' + v + ',' + O.mMname.x.trim() + ',' + v); mMgoals.ret(0); } }); var messagePress$ = sources.DOM.select('input.inputMessage').events('keydown'); var messagePressAction$ = messagePress$.map(function (e) { if (e.keyCode == 13) { socket.send('CD#$42,' + O.mMgroup.x.trim() + ',' + O.mMname.x.trim() + ',' + e.target.value); e.target.value = ''; } }); var task2 = function task(str) { console.log('In taskAction$. str is: ', str); socket.send('TD#$42' + ',' + O.mMgroup.x.trim() + ',' + O.mMname.x.trim() + ',' + '@' + str); }; var newTask$ = sources.DOM.select('input.newTask').events('keydown'); var newTaskAction$ = newTask$.map(function (e) { var ob = {}; var alert = ''; var task = ''; if (e.keyCode == 13) { var ar = e.target.value.split(','); if (ar.length < 3) { alert = 'You should enter "author, responsible party, task" separated by commas'; document.getElementById('alert').innerHTML = alert; } var ar2 = ar.slice(2); console.log('*************************************$$$$$$$$$$$_ar ', ar); if (ar2.length == 1) { task = ar[2]; } if (ar2.length > 1) { task = ar2.reduce(function (a, b) { return a + '$*$*$' + b; }); } if (O.mMar2.x.filter(function (v) { return v.task == task; }).length > 0) { document.getElementById('alert').innerHTML = task + " is already listed."; } else if (ar.length > 2) { O.mMcurrentList.bnd(addString, task + ',yellow, none, false,' + ar[0] + ',' + ar[1], mMtemp).bnd(function (v) { return task2(v); }); e.target.value = ''; document.getElementById('alert').innerHTML = ''; } } }); var process = function process(str) { var a = str.split(","); if (a == undefined) { return; }; if (a.length < 9) { return; }; var ob = {}; var ar = a.slice(3); var s = ar.reduce(function (a, b) { return a + ',' + b; }); console.log('In process. ar and s are: ', ar, s); var tempArray = []; if (ar.length < 6) { return; }; if (ar.length % 6 !== 0) { document.getElementById('alert').innerHTML = 'Error: array length is: ' + length; } mMcurrentList.ret(s); process3(ar); }; var process3 = function process3(a) { var ar5 = []; var keys = Array(a.length / 6).fill(1); keys.map(function (_) { ar5.push({ task: convertBack(a.shift()), color: a.shift(), textDecoration: a.shift(), checked: a.shift() === 'true', author: a.shift(), responsible: a.shift() }); }); mMar2.ret(ar5); process4(ar5); }; var process4 = function process4(a) { var tempArray = []; var keys = Object.keys(a); for (var k in keys) { tempArray.push((0, _dom.h)('div.todo', [(0, _dom.h)('span.task3', { style: { color: a[k].color, textDecoration: a[k].textDecoration } }, 'Task: ' + a[k].task), (0, _dom.h)('br'), (0, _dom.h)('button#edit1', 'Edit'), (0, _dom.h)('input#edit2', { props: { type: 'textarea', value: a[k].task }, style: { display: 'none' } }), (0, _dom.h)('span#author.tao', 'Author: ' + a[k].author + ' / ' + 'Responsibility: ' + a[k].responsible), (0, _dom.h)('br'), (0, _dom.h)('input#cb', { props: { type: 'checkbox', checked: a[k].checked }, style: { color: a[k].color, textDecoration: a[k].textDecoration } }), (0, _dom.h)('label.cbox', { props: { for: '#cb' } }, 'Completed'), (0, _dom.h)('button.delete', 'Delete'), (0, _dom.h)('br'), (0, _dom.h)('hr')])); } mMtaskList.ret(tempArray); }; var colorClick$ = sources.DOM.select('#cb').events('click'); var colorAction$ = colorClick$.map(function (e) { var index = getIndex(e); var s = O.mMcurrentList.x; var ar = s.split(','); var n = 6 * index + 3; var j = 6 * index + 2; var k = 6 * index + 1; var checked = ar[n]; if (checked == 'true') { ar[n] = 'false'; ar[k] = 'yellow'; ar[j] = 'none'; } else { ar[n] = 'true'; ar[k] = 'lightGreen'; ar[j] = 'line-through'; } task2(ar.reduce(function (a, b) { return a + ',' + b; })); }); var edit1$ = sources.DOM.select('#edit1').events('click'); var edit1Action$ = edit1$.map(function (e) { var index = getIndex2(e); O.mMtaskList.x[index].children[3].elm.style.display = 'block'; }); var edit2$ = sources.DOM.select('#edit2').events('keypress'); var edit2Action$ = edit2$.map(function (e) { var v = e.target.value; var index = getIndex2(e); if (e.keyCode == 13) { process2(v, index); O.mMtaskList.x[index].children[3].elm.style.display = 'none'; } }); var process2 = function process2(str, index) { var a = O.mMcurrentList.x; var ar = a.split(','); var task = str.split(',').reduce(function (a, b) { return ar + '$*$*$' + b; }); ar[index * 6] = task; var s = ar.reduce(function (a, b) { return a + ',' + b; }); task2(s); }; var deleteClick$ = sources.DOM.select('.delete').events('click'); var deleteAction$ = deleteClick$.map(function (e) { var index = getIndex(e); var s = O.mMcurrentList.x; var ar = s.split(','); var str = ''; ar.splice(index * 6, 6); if (ar.length > 0) { task2(ar.reduce(function (a, b) { return a + ',' + b; })); } else { socket.send('TX#$42' + ',' + O.mMgroup.x.trim() + ',' + O.mMname.x.trim()); mMtaskList.ret(''); } }); var chatClick$ = sources.DOM.select('#chat2').events('click'); var chatClickAction$ = chatClick$.map(function () { var el = document.getElementById('chatDiv'); el.style.display == 'none' ? el.style.display = 'inline' : el.style.display = 'none'; }); var captionClick$ = sources.DOM.select('#caption').events('click'); var captionClickAction$ = captionClick$.map(function () { var el = document.getElementById('captionDiv'); el.style.display == 'none' ? el.style.display = 'inline' : el.style.display = 'none'; }); var gameClick$ = sources.DOM.select('#game').events('click'); var gameClickAction$ = gameClick$.map(function () { var el = document.getElementById('gameDiv'); el.style.display == 'none' ? el.style.display = 'inline' : el.style.display = 'none'; var el2 = document.getElementById('gameDiv2'); el2.style.display == 'none' ? el2.style.display = 'inline' : el2.style.display = 'none'; }); var runTest$ = sources.DOM.select('#runTest').events('click'); var runTestAction$ = runTest$.map(function () { runTest(); }); var todoClick$ = sources.DOM.select('#todoButton').events('click'); var todoClickAction$ = todoClick$.map(function (e) { var el = document.getElementById('todoDiv'); el.style.display == 'none' ? el.style.display = 'inline' : el.style.display = 'none'; }); var rollClick$ = sources.DOM.select('.roll').events('click'); var rollClickAction$ = rollClick$.map(function (e) { mM13.ret(O.mM13.x - 1); mM8.ret(0); mM3.ret([]); socket.send('CG#$42,' + O.mMgroup.x.trim() + ',' + O.mMname.x.trim() + ',' + -1 + ',' + O.mMgoals.x); socket.send('CA#$42,' + O.mMgroup.x.trim() + ',' + O.mMname.x.trim() + ',6,6,12,20'); }); // ************************************************************************* Original Fibonacci enter var fib2 = function fib2(v) { if (v[2] > 1) { mM$fib.ret([v[1], v[0] + v[1], v[2] - 1]); } else { console.log(v[0]); mM19.ret(v[0]); } }; var fibPress$ = sources.DOM.select('input#code').events('keydown'); var fibPressAction$ = fibPress$.map(function (e) { if (e.target.value == '') { return; }; if (e.keyCode == 13 && Number.isInteger(e.target.value * 1)) { mM21.ret(e.target.value); fib2([0, 1, e.target.value]); } if (e.keyCode == 13 && !Number.isInteger(e.target.value * 1)) { mM19.ret("You didn't provide an integer"); } }); // ************************************************************************* END Original Fibonacci END // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> START PRIME FIB var fibKeyPress5$ = sources.DOM.select('input#fib92').events('keydown'); var primeFib$ = fibKeyPress5$.map(function (e) { if (e.keyCode == 13) { var res = fibsMonad.run([0, 1, e.target.value, []]).bnd(function (fibsState) { return fibsMonad.bnd(fpTransformer, primesMonad).bnd(function (primesState) { return tr3(fibsState[3], primesState[3]); }); }); document.getElementById('PF_9').innerHTML = res[0]; document.getElementById('PF_22').innerHTML = res[1]; document.getElementById('primeFibs').innerHTML = res[2]; } }); // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> END basic prime END // <>>><>><><><><>>>><><>< traversal ><><><><><><>>><><><><><><><><><><><>< START traversal window.onload = function (event) { console.log('onopen event: ', event); document.querySelector('input#login').focus(); mMitterfib5.release(200); // mM$prime5.ret([[2], 3, 3]); }; var forwardClick$ = sources.DOM.select('#forward').events('click'); var backClick$ = sources.DOM.select('#back').events('click'); var forwardAction$ = forwardClick$.map(function () { if (O.mMindex.x < O.mMhistorymM1.x.length - 1) { O.mMindex.bnd(add, 1, mMindex).bnd(function (v) { return trav(v); }); } }); var backAction$ = backClick$.map(function () { if (O.mMindex.x > 0) { O.mMindex.bnd(add, -1, mMindex).bnd(function (v) { return trav(v); }); socket.send('DE#$42,' + O.mMgroup.x.trim() + ',' + O.mMname.x.trim() + ', clicked the BACK button. '); } }); var numClick$ = sources.DOM.select('.num').events('click'); var numClickAction$ = numClick$.map(function (e) { console.log(e); if (O.mM3.x.length < 2) { O.mM3.bnd(push, e.target.innerHTML, O.mM3); mMtemp.ret(O.mMhistorymM1.x[O.mMindex.x].x).bnd(splice, e.target.id, 1, mMtemp).bnd(function (v) { return game(v); }); }; if (O.mM3.x.length === 2 && O.mM8.x !== 0) { updateCalc(); }; }).startWith([0, 0, 0, 0]); var opClick$ = sources.DOM.select('.op').events('click'); var opClickAction$ = opClick$.map(function (e) { mM8.ret(e.target.textContent); if (O.mM3.x.length === 2) { updateCalc(); } }); var game = function game(v) { mM1.ret(v); O.mMindex.bnd(add, 1, mMindex).bnd(function (i) { return O.mMhistorymM1.bnd(spliceAdd, i, O.mM1, O.mMhistorymM1); }); document.getElementById('0').innerHTML = O.mM1.x[0]; document.getElementById('1').innerHTML = O.mM1.x[1]; document.getElementById('2').innerHTML = O.mM1.x[2]; document.getElementById('3').innerHTML = O.mM1.x[3]; cleanup(); }; var trav = function trav(v) { document.getElementById('0').innerHTML = O.mMhistorymM1.x[v].x[0]; document.getElementById('1').innerHTML = O.mMhistorymM1.x[v].x[1]; document.getElementById('2').innerHTML = O.mMhistorymM1.x[v].x[2]; document.getElementById('3').innerHTML = O.mMhistorymM1.x[v].x[3]; cleanup(); }; function updateCalc() { O.mM3.bnd(function (x) { return mM7.ret(calc(x[0], O.mM8.x, x[1])).bnd(function (result) { O.mM1.bnd(push, result, mM1).bnd(function (z) { return game(z); }); if (result == 20) { score(O.mM13.x, 1); }; if (result == 18) { score(O.mM13.x, 3); }; }); }); reset(); }; // <>>><>><><><><>>>><><>< traversal ><><><><><><>>><><><><><><><><><><><>< END traversal var testZ = sources.DOM.select('#testZ').events('click'); var testZAction$ = testZ.map(function () { return mMZ1.release(1); }); var testQ = sources.DOM.select('#testQ').events('click'); var testQAction$ = testQ.map(function () { return mMt1.ret(-1).bnd(mM2.ret).bnd(function () { return mMZ1.release(1); }); }); var testW = sources.DOM.select('#testW').events('keypress'); var testWAction$ = testW.map(function (e) { if (e.keyCode == 13) { mMZ2.release(e.target.value); } }); var solve = function solve() { mMZ3.bnd(function (a) { return mMtemp.ret(a).bnd(innerHTML, '', 'quad6', mMtemp).bnd(innerHTML, a + " * x * x ", 'quad5', mMtemp).bnd(function (a) { return mMZ3.bnd(function (b) { return mMtemp.ret(b).bnd(innerHTML, " + " + b + " * x ", 'quad6', mMtemp).bnd(function (b) { return mMZ3.bnd(function (c) { var x = qS1(a, b, c); var y = qS2(a, b, c); document.getElementById('quad5').innerHTML = 'The results are: x = ' + x + ' and x ='; document.getElementById('quad6').innerHTML = y; solve(); }); }); }); }); }); }(); var quad$ = sources.DOM.select('#quad').events('keypress'); var quadAction$ = quad$.map(function (e) { if (e.keyCode == 13) { mMZ3.release(e.target.value); // Releases mMZ (below). document.getElementById('quad').value = ''; } }); var innerHTML = function innerHTML(x, v, u, m) { document.getElementById(u).innerHTML = v; return m.ret(x); }; var dummyClick$ = sources.DOM.select('#dummy').events('click'); var dummyAction$ = dummyClick$.map(function (e) { O.mMdummy.bnd(add, 1, mMdummy); console.log('<><><><><><><><><> In dummyAction$ e is: ', e); console.log(document.getElementById('dummy').click); console.log('<><><><><><><><><>'); var next = O.mM23.x[O.mM23.x.length - 1] * 1 + O.mM23.x[O.mM23.x.length - 2] * 1; O.mM23.bnd(push, next, mM23); document.getElementById('dummy2').innerHTML = O.mM23.x; }); var calcStream$ = (0, _most.merge)(forwardAction$, backAction$, dummyAction$, primeFib$, fibPressAction$, runTestAction$, quadAction$, testWAction$, testZAction$, testQAction$, edit1Action$, edit2Action$, colorAction$, deleteAction$, newTaskAction$, chatClickAction$, gameClickAction$, todoClickAction$, captionClickAction$, groupPressAction$, rollClickAction$, messagePressAction$, loginPressAction$, messages$, numClickAction$, opClickAction$); return { DOM: calcStream$.map(function () { return (0, _dom.h)('div.content', [(0, _dom.h)('div#rightPanel', { style: { display: 'none' } }, [(0, _dom.h)('span#tog', [(0, _dom.h)('button#game', { style: { fontSize: '16px' } }, 'TOGGLE GAME'), (0, _dom.h)('span.tao', ' '), (0, _dom.h)('button#todoButton', { style: { fontSize: '16px' } }, 'TOGGLE TODO LIST'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('button#chat2', { style: { fontSize: '16px' } }, 'TOGGLE CHAT'), (0, _dom.h)('span.tao', ' '), (0, _dom.h)('button#caption', { style: { fontSize: '16px' } }, 'TOGGLE CAPTION')]), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('div#gameDiv', [(0, _dom.h)('span', 'Group: ' + O.mMgroup.x), (0, _dom.h)('br'), (0, _dom.h)('span', 'Goals: ' + O.mMgoals.x), (0, _dom.h)('br'), (0, _dom.h)('span', 'Name: ' + O.mMname.x), (0, _dom.h)('br'), (0, _dom.h)('span', 'player[score][goals]'), (0, _dom.h)('div', O.mMscoreboard.x)]), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('div#todoDiv', [(0, _dom.h)('div#taskList', O.mMtaskList.x), (0, _dom.h)('span', 'Author, Responsible Person, Task: '), (0, _dom.h)('input.newTask')]), (0, _dom.h)('br'), (0, _dom.h)('span#alert'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('div#chatDiv', [(0, _dom.h)('div#messages', [(0, _dom.h)('span', 'Message: '), (0, _dom.h)('input.inputMessage'), (0, _dom.h)('div', O.mMmsg.x)])])]), (0, _dom.h)('div.leftPanel', { style: { width: '60%' } }, [(0, _dom.h)('br'), (0, _dom.h)('a.tao', { props: { href: '#common' } }, 'Common Patterns'), (0, _dom.h)('a.tao', { props: { href: '#tdList' } }, 'Todo List Explanation'), // h('a.tao', {props: {href: '#monads'}}, 'Why Call Them Monads' ), (0, _dom.h)('div#captionDiv', [(0, _dom.h)('h1', 'Motorcycle.js With JS-monads'), (0, _dom.h)('span.tao1', ' A shared, persistent todo list, '), (0, _dom.h)('br'), (0, _dom.h)('span.tao1', ' A websockets simulated dice game with a traversable history, '), (0, _dom.h)('br'), (0, _dom.h)('span.tao1', ' Group chat rooms and more demonstrations of efficient, '), (0, _dom.h)('br'), (0, _dom.h)('span.tao2', ' maintainable code using Motorcycle.js and JS-monads. ')]), (0, _dom.h)('br'), (0, _dom.h)('span.tao', 'This is a '), (0, _dom.h)('a', { props: { href: "https://github.com/motorcyclejs", target: "_blank" } }, 'Motorcycle.js'), (0, _dom.h)('span', ' application. Motorcycle.js is '), (0, _dom.h)('a', { props: { href: "https://github.com/cyclejs/core", target: "_blank" } }, 'Cycle.js'), (0, _dom.h)('span', ' using '), (0, _dom.h)('a', { props: { href: "https://github.com/cujojs/most", target: "_blank" } }, 'Most'), (0, _dom.h)('span', ' , '), (0, _dom.h)('span', ' and '), (0, _dom.h)('a', { props: { href: "https://github.com/paldepind/snabbdom", target: "_blank" } }, 'Snabbdom'), (0, _dom.h)('span', ' instead of RxJS and virtual-dom. The code for this repository is at '), (0, _dom.h)('a', { props: { href: "https://github.com/dschalk/JS-monads-stable", target: "_blank" } }, 'JS-monads-stable'), (0, _dom.h)('div#gameDiv2', { style: { display: 'none' } }, [(0, _dom.h)('br'), (0, _dom.h)('span', ' Here are the basic rules:'), (0, _dom.h)('p', 'RULES: If clicking two numbers and an operator (in any order) results in 20 or 18, the score increases by 1 or 3, respectively. If the score becomes 0 or is evenly divisible by 5, 5 points are added. A score of 25 results in one goal. That can only be achieved by arriving at a score of 20, which jumps the score to 25. Directly computing 25 results in a score of 30, and no goal. Each time ROLL is clicked, one point is deducted. Three goals wins the game. '), (0, _dom.h)('button#0.num'), (0, _dom.h)('button#1.num'), (0, _dom.h)('button#2.num'), (0, _dom.h)('button#3.num'), (0, _dom.h)('br'), (0, _dom.h)('button#4.op', 'add'), (0, _dom.h)('button#5.op', 'subtract'), (0, _dom.h)('button#5.op', 'mult'), (0, _dom.h)('button#5.op', 'div'), (0, _dom.h)('button#5.op', 'concat'), (0, _dom.h)('br'), (0, _dom.h)('div#dice', { style: { display: 'none' } }, [(0, _dom.h)('button.roll', 'ROLL'), (0, _dom.h)('br'), (0, _dom.h)('button#back', 'BACK'), (0, _dom.h)('button#forward', 'FORWARD')])]), (0, _dom.h)('div#log1', [(0, _dom.h)('p', 'IN ORDER TO SEE THE GAME, TODO LIST, AND CHAT DEMONSTRATIONS, YOU MUST ENTER SOMETHING BELOW.'), (0, _dom.h)('span', 'Name: '), (0, _dom.h)('input#login', { props: { placeholder: "focus on; start typing" } })]), (0, _dom.h)('p', O.mM6.x), (0, _dom.h)('div#log2', { style: { display: 'none' } }, [(0, _dom.h)('span', 'Change group: '), (0, _dom.h)('input#group')]), (0, _dom.h)('p', O.mMsoloAlert.x), (0, _dom.h)('p', 'People who are in the same group, other than solo, share the same todo list, messages, and simulated dice game. In order to see any of these, you must establish an identity on the server by logging in. The websockets connection terminates if the first message the server receives does not come from the sign in form. You can enter any random numbers or letters you like. The only check is to make sure someone hasn\t already signed in with whatever you have selected. '), (0, _dom.h)('hr'), (0, _dom.h)('h1', 'The Monads'), (0, _dom.h)('p', ' I call instances of the Monad and MonadState constructors "monads". Instances of Monad can probably be shown to be category theory monads in a restricted space where the bnd() method takes only a single argument, and that argument is a function mapping any Javascript value to some instance of Monad. But bnd() can take multiple arguments, and the return value doesn\'t have to be an instance of Monad. As you will see, I impose some restrictions on what I do with Monad instances for the sake of maintainability, predictability, and organization. If I had helpers on a project, I would ask them to do the same. I wouldn\'t modify the code to make it throw whenever someone attempted to deviate from the restrictions. Some would say that such a modification would be helpful, catching potential bugs before things went too far. I think it would be insulting; and who knows, there might be occasions when deviating would be the sensible thing to do. Anyway, here is Monad: '), (0, _dom.h)('h2', ' Monad '), _code2.default.monad, (0, _dom.h)('p', ' Monad\'s bnd() and ret() methods provide functionality similar to the Haskell ">>=" (pronounced "bind") operator and the Haskell "return" function. They even conform to the optional Haskell monad laws. The following equality expressions demonstrate how the monads work.Note that ret(v) creates a monad with m.id == "Anonymous" and x = v, and for any monad instance m with m.id == "m", and some Javascript value v, m.ret(v) creates or mutates O.m such that O.m.id = "m" and O.m.x == v. The Monad instance m remains unchanged. Let m be an instance of Monad and let v be any Javascript value (number, array, function, monad, ...), then the following expressions return true: '), (0, _dom.h)('pre', ' m.ret(v).x == m.ret(v).bnd(m.ret).x // m.ret(v) re-sets m.x to v so v is the same on both sides.\n m.ret(v).x == m.ret(v).ret(m.x).x\n m.ret(v).bnd(add, 3).bnd(cube).x == ret(v).bnd(v => add(v, 3).bnd(cube)).x // Associativity\n ret(v).x == ret(v).bnd(ret).x\n ret(v).x == ret(ret(v).x).x '), (0, _dom.h)('p', ' where '), _code2.default.ret_add_cube, (0, _dom.h)('p', ' If the values of Monad instances are updated only through the use of the Monad ret() method, then the current state of the Monad instances exists in the mutable, global object named "O". Keeping changing monad state in one place (on the object "O") makes applications easier to reason about and easier to maintain. I treat Monad instances as though they were immutable, updating them only through the use of their ret() methods. '), (0, _dom.h)('p', ' In the examples shown on this page, the initial values of instances of Monad remain unchaged. The ret() method places updated instances of the monad calling ret() on O. From the definition of ret() we know that for any monad m and value v, m.ret(v) updates O.m such that O.m.x = v. The ret() method does not mutate the instances of Monad referenced by the attributes of O. For any instance of Monad named "m" with id "m" and value v (i.e., m.x == v is true), m.ret(v2) creates a new attribute of O with key "m" or, if O.m already exists. m.ret(v2) mutates O by changing the value to which O.m refers. Before the change, O.m.x == v. After m.ret(v2), O.m.x == v2. For most practical purposes, it is as if O.m.x is the only thing that changed. But O.m is not mutated. If there is a reference to the original O.m, it will be preserved and calls to m.ret() will not affect it. Every time m.ret() is called, O.m refers to a newly created semi-clone of m with m.x referring to a (usually) different value. The traversable game display keeps replaced monads named "O.mM1" in an array named "O.mMhistorymM1". '), (0, _dom.h)('h3', 'Examples'), (0, _dom.h)('p', ' The convention "a == b" in this presentation signifies that a == b is true. I press f12 and the press CTRL-R to reboot and then select "console", I can cut and paste the following expressions into the browser console and verify that the are true. I have installed developer tools, so this might not work for you immediately. '), (0, _dom.h)('p', ' From the definition of Monad, you can see that m1.bnd(m2.ret) results in m2.ret(m1.x) being called. After that operation, O.m2.x == v where m1.x == v. And if O.m1.x == v2, O.m1.bnd(m2.ret) results in O.m2.x == v2. If these assertions are perplexing, just take another look at the definition of Monad and work through the transformations one step at a time. Here are some examples of the use of the Monad methods bnd() and ret(): '), (0, _dom.h)('span.red3', 'cube(3)'), (0, _dom.h)('span.td2', ' creates an anonymous monad with x == 27 and id == "anonymous". '), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('span.red3', 'm.ret(3).bnd(v => m.ret(v*v*v)).bnd(x => console.log(x)) '), (0, _dom.h)('span.td2', 'Returns 27'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('span.red3', 'cube(3).bnd(m.ret)'), (0, _dom.h)('span.td2', ' O.m.x == 27 and O.m.id == "m". '), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('span.red3', 'cube(10).ret(cube(3).x)'), (0, _dom.h)('span.td2', ' O.anonymous.x == 27 '), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('span.red3', 'cube(3).ret(cube(10).x)'), (0, _dom.h)('span.td2', ' O.anonymous.x == 1000 '), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('span.red3', 'cube(3).bnd(cube(10).ret)'), (0, _dom.h)('span.td2', ' O.anonymous.x == 27 '), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('span.red3', 'cube(5, m)'), (0, _dom.h)('span.td2', ' leaves the monad m unchanged, O.m.x == 125, and O.m.id == "m". '), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('span.red3', 'cube(5).bnd(m.ret)'), (0, _dom.h)('span.td2', ' is equivalent to the previous example. m is unchanged and O.m.x == 125. '), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('span.red3', 'ret(5).bnd(cube).bnd(m.ret)'), (0, _dom.h)('span.td2', ' is equivalent to the previous two examples. O.m.x == 125. '), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('span.red3', 'm.ret(4).bnd(cube)'), (0, _dom.h)('span.td2', 'causes O.m.x == 4, and creates an anonymous monad with x == 64. '), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('span.red3', 'm.ret(4).bnd(cube, m)'), (0, _dom.h)('span.td2', ' leaves m unchanged, O.m.x == 64, and O.m.id == "m". '), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('span.tao', ' By the way, If you want to mutate m, '), (0, _dom.h)('span.red3', 'ret(newVal, "m")'), (0, _dom.h)('span', ' will do the job. Now m.x == newVal and m.id = "m". I haven\'t found a need to do that sort of thing. I like to confine changing monad state to the mutable, global object "O", and leave the plain monads alone. That keeps the application tidy and manageable. '), (0, _dom.h)('p', ' Here are some examples using the function add(): '), (0, _dom.h)('span.red3', 'add(3, 4)'), (0, _dom.h)('span.td2', ' creates a useless anonymous monad with x == 7 and id == "anonymous". '), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('span.red3', 'add(3, 4).bnd(m.ret)'), (0, _dom.h)('span.td2', ' causes O.m.x == 7 and O.m.id == "m". '), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('span.red3', 'add(3, 4, m)'), (0, _dom.h)('span.td2', ' is equivalent to the prior example. The result is O.m.x == 7, and O.m.id == "m". '), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('span.red3', 'm.ret(0).bnd(add, 3).bnd(cube)'), (0, _dom.h)('span.td2', 'leaves m unchanged, O.m.x == 0, and creates an anonymous monad with x == 27. '), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('span.red3', 'ret(0).bnd(add, 3).bnd(cube).bnd(m.ret)'), (0, _dom.h)('span.td2', 'causes O.m.x == 27, and O.m.id = "m". '), (0, _dom.h)('br'), (0, _dom.h)('br#iterLink'), (0, _dom.h)('br'), (0, _dom.h)('span.red3', 'ret(0).bnd(add, 2, m).bnd(cube, m2)'), (0, _dom.h)('span.td2', ' causes O.m.x == 2, and O.m2.x == 8. '), (0, _dom.h)('br'), (0, _dom.h)('h2', 'MonadItter'), (0, _dom.h)('p', ' MonadItter instances do not have monadic properties. I will eventually change the name to "Itter". '), (0, _dom.h)('p', 'For any instance of MonadIter, say "m", the statement "m.bnd(func)" causes m.p == func to be true. The statement "m.release(...args) causes p(...args) to execute. Here is the definition: '), _code2.default.monadIt, (0, _dom.h)('p', ' As shown later on this page, MonadIter instances control the routing of incoming websockets messages and the flow of action in the simulated dice game. In the demonstrations below, they behave much like ES2016 itterators. I prefer them over ES2016 itterators. '), (0, _dom.h)('p', 'The following example illustrates the use of release() with an argument. It also shows lambda expressions being provided as arguments for bnd() and the release() method providing arguments to the expressions captured by bnd(). The initial values of mMt1, mMt2, and mMt3 are 0, 0, and "" respectively. When this page loads, the following code runs: '), _code2.default.testZ, (0, _dom.h)('p', ' add() and cube() are defined in the Monad section (above). If you click "mMZ1.release(1)" several times, the code (above) beginning with "mMZ1" will run several times, each time with v == 1. The result, O.mMt3.x, is shown below the button. mMZ1.p (bnd()\'s argument) remains constant while mMZ1.release(1) is repeatedly called, yielding a different result each time. '), (0, _dom.h)('button#testZ', 'mMZ1.release(1)'), (0, _dom.h)('p.code2', O.mMt3.x), (0, _dom.h)('span', 'Refresh button: '), (0, _dom.h)('button#testQ', 'mMt1.ret(0).bnd(mMt2.ret)'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('span.tao', ' You can call '), (0, _dom.h)('span.green', 'mMZ2.release(v)'), (0, _dom.h)('span', ' by entering a value for v below: '), (0, _dom.h)('br'), (0, _dom.h)('span', 'Please enter an integer here: '), (0, _dom.h)('input#testW'), (0, _dom.h)('p', ' Here is another example. It demonstrates lambda expressions passing values to a remote location for use in a computation. If you enter three numbers consecutively below, I\'ll call them a, b, and c, then the quadratic equation will be used to find solutions for a*x**2 + b*x + c = 0. The a, b, and c you select might not have a solution. If a and b are positive numbers, you are likely to see solutions if c is a negative number. For example, 12, 12, and -24 yields the solutions 1 and -2. '), (0, _dom.h)('p.#quad4.code2'), (0, _dom.h)('span#quad5.red2'), (0, _dom.h)('span#quad6.red8'), (0, _dom.h)('p', 'Run mMZ3.release(v) three times for three numbers. The numbers are a, b, and c in ax*x + b*x + c = 0: '), (0, _dom.h)('input#quad'), (0, _dom.h)('p', 'Here is the code:'), _code2.default.quad, (0, _dom.h)('span#tdList'), // ***************************************************************************************************** START MonadState (0, _dom.h)('h2', 'MonadState and MonadState Transformers'), (0, _dom.h)('p', ' An instance of MonadState holds the current state and value of a computation. For any instance of MonadState, say m, these can be accessed through m.s and m.a, respectively. '), _code2.default.MonadState, (0, _dom.h)('p', ' MonadState reproduces some of the functionality found in the Haskel Module "Control.Monad.State.Lazy", inspired by the paper "Functional Programming with Overloading and Higher-Order Polymorphism", Mark P Jones (http://web.cecs.pdx.edu/~mpj/) Advanced School of Functional Programming, 1995. The following demonstrations use the MonadState instances fibsMonad and primesMonad to create and store arrays of fibonacci numbers and arrays of prime numbers, respectively. fibsMonad and primesMonad provide a simple way to compute lists of prime fibonacci numbers. Because the results of computations are stored in the a and s attributes of MonadState instances, it was easy to make sure that no prime number is ever computed twice in the prime Fibonacci demonstration. '), (0, _dom.h)('p', ' Here is the definition of fibsMonad, along with the definition of the function that becomes fibsMonad.process. '), _code2.default.fibsMonad, (0, _dom.h)('p', ' The other MonadState instance used in this demonstration is primesMonad. Here is its definition along with the function that becomes primesMonad.process: '), _code2.default.primesMonad, (0, _dom.h)('h3', ' MonadState transformers '), (0, _dom.h)('p', ' Transformers take instances of MonadState and return different instances of MonadState, possibly in a modified state. The method call "fibsMonad.bnd(fpTransformer, primesMonad)" returns primesMonad. Here is the definition of fpTransformer: '), _code2.default.fpTransformer, (0, _dom.h)('p', ' If the largest number in primesMonad.a is less than the square root of the largest number in fibsMonad.a, primesMonad is updated so that the largest number in primesMonad.a is greater than the square root of the largest number in fibsMonad.a. Otherwise, primesMonad is returned unchanged. '), (0, _dom.h)('p', ' The final computation in the prime Fibonacci numbers demonstration occurs when "tr3(fibsState[3],primesState[3]" is called. tr3() takes an array of fibonacci numbers and an array of prime numbers and returns an array containing an array of Fibonacci numbrs, an array of prime numbers, and an array of prime Fibonacci numbers. Here is the definition of tr3: '), _code2.default.tr3, (0, _dom.h)('p', ' With these support functions in place, user input is processed by (possibly) updating primesMonad and then calling fibsMonad.bnd() three times; first to extract fibsMonad.s, second to run fpTransformer to modify and then obtain primesMonad, and third to obtain primesMonad.s and run tr3(fibsState[3],primesState[3]). Here is the code: '), _code2.default.primeFibInterface, (0, _dom.h)('p', 'Only 48 fibonacci numbers need to be generated in order to get the eleventh prime Fibonacci number. But 5546 prime numbers need to be generated to test for divisibility into 2971215073. Finding the next Fibonacci number is just a matter of adding the previous two. Getting the next prime number is a more elaborate and time-consuming procedure. In this context, the time needed to compute 48 Fibonacci numbers is insignificant, so I didn\'t bother to save previously computed Fibonacci numbers in the prime Fibonacci demonstration. When a user enters a number smaller than the current length of fibsMonad.a, fibsMonad is modified such that its length becomes exactly what the user entered.'), (0, _dom.h)('p', ' I entered 44 in my desktop Ubuntu Chrome and Firefox browsers and got the first ten prime Fibonacci numbers. I then entered 48 and all eleven prime Fibonacci numbers appeared. I tried gradually incrementing upwards, but when I got to 56 I stopped due to impatience with the lag time. The 56th Fibonacci number was computed to be 139583862445. No new prime Fibonacci numbers appeared.'), (0, _dom.h)('p', ' These are the first eleven proven prime Fibonacci numbers: '), (0, _dom.h)('pre', '2,3,5,13,89,\n233,1597,28657,514229,433494437,\n2971215073 '), (0, _dom.h)('p', ' The number you enter below is the length of the list of Fibonacci numbers you want to generate. '), (0, _dom.h)('p'), (0, _dom.h)('input#fib92'), (0, _dom.h)('br'), (0, _dom.h)('span#PF_7.red6', 'Fibonacci Numbers'), (0, _dom.h)('br'), (0, _dom.h)('span#PF_9.red7'), (0, _dom.h)('br'), (0, _dom.h)('span#PF_21.red6', 'Prime Numbers'), (0, _dom.h)('br'), (0, _dom.h)('span#PF_22.red7'), (0, _dom.h)('br'), (0, _dom.h)('span#PF_8.red6', 'Prime Fibonacci Numbers'), (0, _dom.h)('br'), (0, _dom.h)('span#primeFibs.red7'), //************************************************************************************************************* END MonadState (0, _dom.h)('h2', 'Immutable Data And The State Object "O" '), (0, _dom.h)('h3', ' Mutations '), (0, _dom.h)('p', ' Mutations in this application are confined to the global state object "O", MonadIter instances, and within function scope. Functions in this application do not have side effects. If a function argument is an array, say "ar", I make a clone by calling "ar = ar.slice()" before mutating ar. That way, the original ar is uneffected by whatever happens inside the function. '), (0, _dom.h)('p', ' Regarding mutations of MonadItter instances: In the MonadItter examples (above), bnd() is called only once on each instance of MonadItter. Essentially, the bnd() method defines the MonadItter instances. The definitions of MonadItter instances create generic templates waiting for their bnd() methods to give them meaning. The p attribute of a MonadItter instance starts out referencing "f () {}" and refers to something useful when an argument is provided to its bnd() method. In this case, mutation can\'t possibly cause any mischief. '), (0, _dom.h)('h3', ' Monad Updates '), (0, _dom.h)('p', 'All monad updates caused by the monad ret() method are stored in the object "O". When a monad m executes m.ret(v) for some value "v", m remains unchanged and the O attribute O.m is created or, if it already exists, is replaced by the update; i.e., O.m.x == v becomes true. Older versions of m are subject to garbage collection unless there is a reference to them or to an object (arrays are objects) containing m. This is illustrated in the score-keeping code below. All score changes are captured by mM13.ret(). Therefore, O.mM13.x is always the current score. Replacing monad attributes in O is vaguely analogous to swapping out ServerState in the Haskell server\'s state TMVar. Older versions of ServerState can be preserved in the server just as prior versions of O.mM13 can be preserved in the front end. '), (0, _dom.h)('h3', 'Storing Monads That Have Been Replaced In O'), (0, _dom.h)('p', ' The history of the number display in the game can be traversed in either direction until a player achieves a goal. After that, the traversable history builds up until another goal is achieves. Players can use historical displays, so to keep competition fair, group members are notified when another member clicks the BACK button. '), _code2.default.traverse, (0, _dom.h)('p', ' It would have been more efficient to just save the arrays rather than the monads that hold them. But this isn\'t about recommended practices right now. It is a demonstration of a use of the not-mutated monads on the mutable global object "O". I write "not-mutated" because the monads can be clobbered anytime you want. But if values are replaced using the Monad ret() method, as is the case in this demonstration, monads on "O" are replaced, not mutated. '), (0, _dom.h)('h2', 'Updating the DOM'), (0, _dom.h)('h3', 'Todo List DOM Updates'), (0, _dom.h)('br'), (0, _dom.h)('h3', 'Dice Game DOM updates'), (0, _dom.h)('p', ' mMcurrentRoll.ret() is called only when (1) a new dice roll comes in from the server, (2) when a player clicks a number, and (3) when clicking a number or operator results in a computation being performed. These are the three things that require a DOM update. When a player clicks a number, it disappears from number display. When a computation is performed, the result is added to the number display, unless the result is 18 or 20. A result of 18 or 20 results in a new roll coming in from the server '), (0, _dom.h)('p', ' I like the way Cycle.js and Motorcycle.js are unopinionated. DOM updates can be accomplished by permanently placing a mutating list of strings in the virtual DOM description, or by calling element.innerHTML = newValue. Either way, the actual DOM gets mutatated immediately, and mutating the DOM is what interactive applications are all about. Well, unless you load fresh pages every time something changes. I guess some people are still doing that. '), (0, _dom.h)('hr'), (0, _dom.h)('h2', 'Concise Code Blocks For Information Control'), (0, _dom.h)('p', ' Incoming websockets messages trigger updates to the game display, the chat display, and the todo list display. The members of a group see what other members are doing; and in the case of the todo list, they see the current list when they sign in to the group. When any member of a group adds a task, crosses it out as completed, edits its description, or removes it, the server updates the persistent file and all members of the group immediately see the revised list. '), (0, _dom.h)('p', 'The code below shows how incoming websockets messages are routed. For example, mMZ10.release() is called when a new dice roll (prefixed by CA#$42) comes in. '), _code2.default.messages, (0, _dom.h)('p', ' The "mMZ" prefix designates instances of MonadIter. The bnd() method assigns its argument to the "p" attribute. "p" runs if and when the release() method is called. The next() function releases a specified MonadIter instance when the calling monad\'s value matches the specified value. next2() releases the specified monad when the specified condition returns true. The release method in next() has no argument, but next does take arguments, as illustrated below.'), (0, _dom.h)('span.tao', ' The incoming messages block is just a syntactic variation of a switch block, but that isn\'t all that MonadIter instances can do. They can provide fine-grained control over the lazy evaluation of blocks of code. Calling release() after a function completes some task provides Promise-like behavior. Error handling is optional. The MonadInter release(...args) method facilitates sequential evaluation of code blocks, remeniscent of video and blog explanations of ES6 iterators and generators. I prefer doing it with MonadIter over "yield" and "next". For one thing, ES6 generator "yield" blocks must be evaluated in a predetermined order. This link takes you back to the MonadIter section with interactive examples of the use of release() with arguments. '), (0, _dom.h)('a#tdList2', { props: { href: '#iterLink' } }, 'release() with arguments'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('a', { props: { href: '#top' } }, 'Back To The Top'), (0, _dom.h)('br'), (0, _dom.h)('h3', 'The Todo List'), (0, _dom.h)('p', ' Next, I\'ll go over some features of the todo list application. This will show how Motorcycle.js and the monads work together.'), (0, _dom.h)('p', 'Creation Of A Task: If you enter something like Susan, Fred, Pay the water bill, the editable task will appear in your browser and in the browsers of any members a group you might have created or joined. If you have loaded this page in another tab and changed to the same group in both, you will see the task in both tabs, barring some malfunction. The task has a delete button, an edit button, and a "Completed" checkbox. It shows that Susan authorized the task and Fred is responsible for making sure it gets done. Instead of entering an authority and responsible person, you can just enter two commas before the task description. Without two commas, a message appears requesting more information. '), _code2.default.newTask, (0, _dom.h)('p', 'mM$taskList caries a string representing the task list. mMtaskList.x.split(",") produces an array whose length is a multiple of six. Commas in the task description are replaced by "$*$*$" so split(",") will put the entire task description in a single element. Commas are re-inserted when the list arrives from the server for rendering. Although a task list is a nested virtual DOM object (Snabbdom vnode), it can be conveniently passed back and forth to the server as a string without resorting to JSON.stringify. Its type is Text on the server and String in the front end, becomming a virtual DOM node only once, when it arrives from the server prefixed by "DD#$42" causing "process(e.data) to execute. Here is process(): '), _code2.default.process, (0, _dom.h)('span.tao', 'As you see, the string becomes a list of six-element objects, then those objects are used to create a Snabbdom vnode which is handed to mM$taskList.ret() leading to the update of O.mMtaskList. O.mMtaskList.x sits permanently in the main virtual DOM description. '), (0, _dom.h)('a', { props: { href: "https://github.com/dschalk/JS-monads-stable" } }, 'https://github.com/dschalk/JS-monads-stable'), (0, _dom.h)('br'), (0, _dom.h)('p', ' Clicking "Completed": When the "Completed" button is clicked, the following code runs: '), _code2.default.colorClick, (0, _dom.h)('p', 'O.mMtaskList is split into an array. Every sixth element is the start of a new task. colorAction$ toggles the second, third, and fourth element in the task pinpointed by "index" * 6. getIndex finds the index of the first and only the element whose task description matches the one that is being marked "Completed". I say "only" because users are prevented from adding duplicate tasks. After the changes are made, the array of strings is reduced to one string and sent to the server by task2(). '), (0, _dom.h)('p', ' This is the code involved in editing a task description: '), _code2.default.edit, (0, _dom.h)('p', 'Clicking "Edit" causes a text box to be displayed. Pressing <ENTER> causes it to diappear. edit2Action$ obtains the edited description of the task and the index of the task iten and provides them as arguments to process. Process exchanges $*$*$ for any commas in the edited version and assigns the amended task description to the variable "task". O.mMtaskList.x is copied and split into an array. "index * 6" is replaced with "task" and the list of strings is reduced back to a single string and sent to the server for distribution. This pattern, - (1) split the string representation of the todo list into an array of strings, (2) do something, (3) reduce the list of strings back to a single string - is repeated when the "Delete" button is clicked. If the last item gets deleted, the server is instructed to delete the persistent file bearing the name of the group whose member deleted the last task. '), (0, _dom.h)('p#common', 'Cycle.js has been criticized for not keeping state in a single location, the way React.js does. Motorcycle.js didn\'t do it for me, or try to force me to do it, but it so happens that the current state of all active monads is in the object "O". I have written applications in Node.js and React.js, and I can say without a doubt that Motorcycle.js provides the best reactive interface for my purposes. '), (0, _dom.h)('hr'), (0, _dom.h)('a', { props: { href: '#top' } }, 'Back To The Top'), (0, _dom.h)('h2', 'Common Patterns'), (0, _dom.h)('p', 'Anyone not yet familiar with functional programming can learn by studying the definition of the Monad bnd() method and considering the common patterns presented below. Often, we want to give a named monad the value of an anonymous monad returned by a monadic computation. Here are some ways to accomplish that: '), (0, _dom.h)('p', 'For any monads m1 and m2 with values a and b respectively (in other words, m1.x == a and m2.x == b return true), m1.bnd(m2.ret) provides m1\'s value to m2.ret() causing O.m2 to have m1\'s value. So, after m1.bnd(m2.ret), m1.x == a, m2.x == b, O.m2.x == a all return true. The definition of Monad\s bnd() method shows that the function m2.ret() operates on m1.x. m1.bnd(m2.ret) is equivalent to m2.ret(m1.x). The stand-alone ret() function can be used to alter the current value of m2, rather than altering the value of O.m2. Here is one way of accomplishing this: m1.bnd(x => ret(x,"m2"). These relationships are demonstrated in the following tests: '), (0, _dom.h)('pre', ' ret(\'m1Val\',\'m1\')\n m1.x === \'m1Val\' // true\n ret(\'m2Val\', \'m2\')\n m2.x === \'m2Val\' // true\n\n m1.bnd(m2.ret)\n O.m2.x === \'m1Val\' // true\n m2.x === \'m2Val\' // still true\n\n m1.ret(\'newVal\')\n O.m1.bnd(v => ret(v, \'m2\'))\n m2.x === \'newVal\' // true\n O.m2.x === \'m1Val\' // true still the same '), (0, _dom.h)('p', ' Here are two basic ways to create a monad named "m" with id = "m" and value v: '), (0, _dom.h)('pre', ' var m = new Monad(v, "m");\n ret(v, "m"); '), (0, _dom.h)('p', 'Let m be a monad with id == "m" and value v. Its bnd() method can return an anonymous monad, a new named monad, or a previously existing monad containing the computation result. To illustrate, here is the definition of "add" along with five uses of it: '), _code2.default.add, (0, _dom.h)('p'), (0, _dom.h)('hr'), (0, _dom.h)('hr'), (0, _dom.h)('a', { props: { href: '#top' } }, 'Back To The Top'), (0, _dom.h)('a', { props: { href: '#top' } }, 'Back To The Top'), (0, _dom.h)('p'), (0, _dom.h)('p'), (0, _dom.h)('p'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('span#dummy2.red3'), (0, _dom.h)('hr'), (0, _dom.h)('button#dummy', O.mMdummy.x), (0, _dom.h)('p'), (0, _dom.h)('p'), (0, _dom.h)('p', '.'), (0, _dom.h)('p', '.'), (0, _dom.h)('p', '.'), (0, _dom.h)('p', '.'), (0, _dom.h)('p', '.'), (0, _dom.h)('p'), (0, _dom.h)('p'), (0, _dom.h)('p'), (0, _dom.h)('p'), (0, _dom.h)('p')])]); }) }; } function cleanup(x) { var target0 = document.getElementById('0'); var target1 = document.getElementById('1'); var target2 = document.getElementById('2'); var target3 = document.getElementById('3'); var targetAr = [target0, target1, target2, target3]; [0, 1, 2, 3].map(function (i) { if (targetAr[i].innerHTML == 'undefined') { targetAr[i].style.display = 'none'; } else { targetAr[i].style.display = 'inline'; } }); return ret(x); }; var score = function score(x, j) { if (x + j == 20) { mMgoals.ret(O.mMgoals.x == 2 ? 0 : O.mMgoals.x + 1); mM13.ret(0).bnd(mMindex.ret); mMhistorymM1.ret([ret([0, 0, 0, 0])]); socket.send('CG#$42,' + O.mMgroup.x + ',' + O.mMname.x + ',' + -x + ',' + O.mMgoals.x); if (O.mMgoals.x == 0) { socket.send('CE#$42,' + O.mMgroup.x + ',' + O.mMname.x + ',nothing '); } socket.send('CA#$42,' + O.mMgroup.x.trim() + ',' + O.mMname.x.trim() + ',6,6,12,20'); return; } if ((x + j) % 5 == 0) { socket.send('CG#$42,' + O.mMgroup.x + ',' + O.mMname.x + ',' + (j + 5) + ',' + O.mMgoals.x); mM13.ret(x + j + 5); socket.send('CA#$42,' + O.mMgroup.x.trim() + ',' + O.mMname.x.trim() + ',6,6,12,20'); return; } socket.send('CG#$42,' + O.mMgroup.x + ',' + O.mMname.x + ',' + j + ',' + O.mMgoals.x); mM13.ret(x + j); socket.send('CA#$42,' + O.mMgroup.x.trim() + ',' + O.mMname.x.trim() + ',6,6,12,20'); }; var reset = function reset() { mM3.ret([]).bnd(function () { return mM4.ret(0).bnd(mM8.ret).bnd(cleanup); }); }; var updateScoreboard = function updateScoreboard(v) { var ar2 = v.split("<br>"); var keys = Object.keys(ar2); var ar = []; keys.map(function (k) { ar.push((0, _dom.h)('div', ar2[k])); }); return mMscoreboard.ret(ar); }; var displayOff = function displayOff(x, a) { document.getElementById(a).style.display = 'none'; return ret(x); }; var displayInline = function displayInline(x, a) { if (document.getElementById(a)) document.getElementById(a).style.display = 'inline'; return ret(x); }; var newRoll = function newRoll(v) { socket.send('CA#$42,' + O.mMgroup.x.trim() + ',' + O.mMname.x.trim() + ',6,6,12,20'); return ret(v); }; var refresh = function refresh() { setTimeout(function () { document.location.reload(false); }, 4000); }; var sources = { DOM: (0, _dom.makeDOMDriver)('#main-container'), WS: websocketsDriver }; _core2.default.run(main, sources); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(17))) /***/ } /******/ ]);
client/dist/bundle.js
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { throw err; }; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 102); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports) { "use strict"; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ module.exports = Stream; function Stream(source) { this.source = source; } /***/ }, /* 1 */ /***/ function(module, exports) { "use strict"; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ module.exports = Pipe; /** * A sink mixin that simply forwards event, end, and error to * another sink. * @param sink * @constructor */ function Pipe(sink) { this.sink = sink; } Pipe.prototype.event = function (t, x) { return this.sink.event(t, x); }; Pipe.prototype.end = function (t, x) { return this.sink.end(t, x); }; Pipe.prototype.error = function (t, e) { return this.sink.error(t, e); }; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Disposable = __webpack_require__(72); var SettableDisposable = __webpack_require__(73); var isPromise = __webpack_require__(11).isPromise; var base = __webpack_require__(3); var map = base.map; var identity = base.id; exports.tryDispose = tryDispose; exports.create = create; exports.once = once; exports.empty = empty; exports.all = all; exports.settable = settable; exports.promised = promised; /** * Call disposable.dispose. If it returns a promise, catch promise * error and forward it through the provided sink. * @param {number} t time * @param {{dispose: function}} disposable * @param {{error: function}} sink * @return {*} result of disposable.dispose */ function tryDispose(t, disposable, sink) { var result = disposeSafely(disposable); return isPromise(result) ? result.catch(function (e) { sink.error(t, e); }) : result; } /** * Create a new Disposable which will dispose its underlying resource * at most once. * @param {function} dispose function * @param {*?} data any data to be passed to disposer function * @return {Disposable} */ function create(dispose, data) { return once(new Disposable(dispose, data)); } /** * Create a noop disposable. Can be used to satisfy a Disposable * requirement when no actual resource needs to be disposed. * @return {Disposable|exports|module.exports} */ function empty() { return new Disposable(identity, void 0); } /** * Create a disposable that will dispose all input disposables in parallel. * @param {Array<Disposable>} disposables * @return {Disposable} */ function all(disposables) { return create(disposeAll, disposables); } function disposeAll(disposables) { return Promise.all(map(disposeSafely, disposables)); } function disposeSafely(disposable) { try { return disposable.dispose(); } catch (e) { return Promise.reject(e); } } /** * Create a disposable from a promise for another disposable * @param {Promise<Disposable>} disposablePromise * @return {Disposable} */ function promised(disposablePromise) { return create(disposePromise, disposablePromise); } function disposePromise(disposablePromise) { return disposablePromise.then(disposeOne); } function disposeOne(disposable) { return disposable.dispose(); } /** * Create a disposable proxy that allows its underlying disposable to * be set later. * @return {SettableDisposable} */ function settable() { return new SettableDisposable(); } /** * Wrap an existing disposable (which may not already have been once()d) * so that it will only dispose its underlying resource at most once. * @param {{ dispose: function() }} disposable * @return {Disposable} wrapped disposable */ function once(disposable) { return new Disposable(disposeMemoized, memoized(disposable)); } function disposeMemoized(memoized) { if (!memoized.disposed) { memoized.disposed = true; memoized.value = disposeSafely(memoized.disposable); memoized.disposable = void 0; } return memoized.value; } function memoized(disposable) { return { disposed: false, disposable: disposable, value: void 0 }; } /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;'use strict'; (function (global, factory) { if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [exports], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (typeof exports !== "undefined") { factory(exports); } else { var mod = { exports: {} }; factory(mod.exports); global.mostPrelude = mod.exports; } })(undefined, function (exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); /** @license MIT License (c) copyright 2010-2016 original author or authors */ // Non-mutating array operations // cons :: a -> [a] -> [a] // a with x prepended function cons(x, a) { var l = a.length; var b = new Array(l + 1); b[0] = x; for (var i = 0; i < l; ++i) { b[i + 1] = a[i]; } return b; } // append :: a -> [a] -> [a] // a with x appended function append(x, a) { var l = a.length; var b = new Array(l + 1); for (var i = 0; i < l; ++i) { b[i] = a[i]; } b[l] = x; return b; } // drop :: Int -> [a] -> [a] // drop first n elements function drop(n, a) { // eslint-disable-line complexity if (n < 0) { throw new TypeError('n must be >= 0'); } var l = a.length; if (n === 0 || l === 0) { return a; } if (n >= l) { return []; } return unsafeDrop(n, a, l - n); } // unsafeDrop :: Int -> [a] -> Int -> [a] // Internal helper for drop function unsafeDrop(n, a, l) { var b = new Array(l); for (var i = 0; i < l; ++i) { b[i] = a[n + i]; } return b; } // tail :: [a] -> [a] // drop head element function tail(a) { return drop(1, a); } // copy :: [a] -> [a] // duplicate a (shallow duplication) function copy(a) { var l = a.length; var b = new Array(l); for (var i = 0; i < l; ++i) { b[i] = a[i]; } return b; } // map :: (a -> b) -> [a] -> [b] // transform each element with f function map(f, a) { var l = a.length; var b = new Array(l); for (var i = 0; i < l; ++i) { b[i] = f(a[i]); } return b; } // reduce :: (a -> b -> a) -> a -> [b] -> a // accumulate via left-fold function reduce(f, z, a) { var r = z; for (var i = 0, l = a.length; i < l; ++i) { r = f(r, a[i], i); } return r; } // replace :: a -> Int -> [a] // replace element at index function replace(x, i, a) { // eslint-disable-line complexity if (i < 0) { throw new TypeError('i must be >= 0'); } var l = a.length; var b = new Array(l); for (var j = 0; j < l; ++j) { b[j] = i === j ? x : a[j]; } return b; } // remove :: Int -> [a] -> [a] // remove element at index function remove(i, a) { // eslint-disable-line complexity if (i < 0) { throw new TypeError('i must be >= 0'); } var l = a.length; if (l === 0 || i >= l) { // exit early if index beyond end of array return a; } if (l === 1) { // exit early if index in bounds and length === 1 return []; } return unsafeRemove(i, a, l - 1); } // unsafeRemove :: Int -> [a] -> Int -> [a] // Internal helper to remove element at index function unsafeRemove(i, a, l) { var b = new Array(l); var j = void 0; for (j = 0; j < i; ++j) { b[j] = a[j]; } for (j = i; j < l; ++j) { b[j] = a[j + 1]; } return b; } // removeAll :: (a -> boolean) -> [a] -> [a] // remove all elements matching a predicate function removeAll(f, a) { var l = a.length; var b = new Array(l); var j = 0; for (var x, i = 0; i < l; ++i) { x = a[i]; if (!f(x)) { b[j] = x; ++j; } } b.length = j; return b; } // findIndex :: a -> [a] -> Int // find index of x in a, from the left function findIndex(x, a) { for (var i = 0, l = a.length; i < l; ++i) { if (x === a[i]) { return i; } } return -1; } // isArrayLike :: * -> boolean // Return true iff x is array-like function isArrayLike(x) { return x != null && typeof x.length === 'number' && typeof x !== 'function'; } /** @license MIT License (c) copyright 2010-2016 original author or authors */ // id :: a -> a var id = function id(x) { return x; }; // compose :: (b -> c) -> (a -> b) -> (a -> c) var compose = function compose(f, g) { return function (x) { return f(g(x)); }; }; // apply :: (a -> b) -> a -> b var apply = function apply(f, x) { return f(x); }; // curry2 :: ((a, b) -> c) -> (a -> b -> c) function curry2(f) { function curried(a, b) { switch (arguments.length) { case 0: return curried; case 1: return function (b) { return f(a, b); }; default: return f(a, b); } } return curried; } // curry3 :: ((a, b, c) -> d) -> (a -> b -> c -> d) function curry3(f) { function curried(a, b, c) { // eslint-disable-line complexity switch (arguments.length) { case 0: return curried; case 1: return curry2(function (b, c) { return f(a, b, c); }); case 2: return function (c) { return f(a, b, c); }; default: return f(a, b, c); } } return curried; } exports.cons = cons; exports.append = append; exports.drop = drop; exports.tail = tail; exports.copy = copy; exports.map = map; exports.reduce = reduce; exports.replace = replace; exports.remove = remove; exports.removeAll = removeAll; exports.findIndex = findIndex; exports.isArrayLike = isArrayLike; exports.id = id; exports.compose = compose; exports.apply = apply; exports.curry2 = curry2; exports.curry3 = curry3; }); /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var base = __webpack_require__(3); var core = __webpack_require__(7); var from = __webpack_require__(84).from; var periodic = __webpack_require__(90).periodic; /** * Core stream type * @type {Stream} */ exports.Stream = Stream; // Add of and empty to constructor for fantasy-land compat exports.of = Stream.of = core.of; exports.just = core.of; // easier ES6 import alias exports.empty = Stream.empty = core.empty; exports.never = core.never; exports.from = from; exports.periodic = periodic; //----------------------------------------------------------------------- // Creating var create = __webpack_require__(83); /** * Create a stream by imperatively pushing events. * @param {function(add:function(x), end:function(e)):function} run function * that will receive 2 functions as arguments, the first to add new values to the * stream and the second to end the stream. It may *return* a function that * will be called once all consumers have stopped observing the stream. * @returns {Stream} stream containing all events added by run before end */ exports.create = create.create; //----------------------------------------------------------------------- // Adapting other sources var events = __webpack_require__(86); /** * Create a stream of events from the supplied EventTarget or EventEmitter * @param {String} event event name * @param {EventTarget|EventEmitter} source EventTarget or EventEmitter. The source * must support either addEventListener/removeEventListener (w3c EventTarget: * http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget), * or addListener/removeListener (node EventEmitter: http://nodejs.org/api/events.html) * @returns {Stream} stream of events of the specified type from the source */ exports.fromEvent = events.fromEvent; //----------------------------------------------------------------------- // Observing var observe = __webpack_require__(63); exports.observe = observe.observe; exports.forEach = observe.observe; exports.drain = observe.drain; /** * Process all the events in the stream * @returns {Promise} promise that fulfills when the stream ends, or rejects * if the stream fails with an unhandled error. */ Stream.prototype.observe = Stream.prototype.forEach = function (f) { return observe.observe(f, this); }; /** * Consume all events in the stream, without providing a function to process each. * This causes a stream to become active and begin emitting events, and is useful * in cases where all processing has been setup upstream via other combinators, and * there is no need to process the terminal events. * @returns {Promise} promise that fulfills when the stream ends, or rejects * if the stream fails with an unhandled error. */ Stream.prototype.drain = function () { return observe.drain(this); }; //------------------------------------------------------- var loop = __webpack_require__(61).loop; exports.loop = loop; /** * Generalized feedback loop. Call a stepper function for each event. The stepper * will be called with 2 params: the current seed and the an event value. It must * return a new { seed, value } pair. The `seed` will be fed back into the next * invocation of stepper, and the `value` will be propagated as the event value. * @param {function(seed:*, value:*):{seed:*, value:*}} stepper loop step function * @param {*} seed initial seed value passed to first stepper call * @returns {Stream} new stream whose values are the `value` field of the objects * returned by the stepper */ Stream.prototype.loop = function (stepper, seed) { return loop(stepper, seed, this); }; //------------------------------------------------------- var accumulate = __webpack_require__(54); exports.scan = accumulate.scan; exports.reduce = accumulate.reduce; /** * Create a stream containing successive reduce results of applying f to * the previous reduce result and the current stream item. * @param {function(result:*, x:*):*} f reducer function * @param {*} initial initial value * @returns {Stream} new stream containing successive reduce results */ Stream.prototype.scan = function (f, initial) { return accumulate.scan(f, initial, this); }; /** * Reduce the stream to produce a single result. Note that reducing an infinite * stream will return a Promise that never fulfills, but that may reject if an error * occurs. * @param {function(result:*, x:*):*} f reducer function * @param {*} initial optional initial value * @returns {Promise} promise for the file result of the reduce */ Stream.prototype.reduce = function (f, initial) { return accumulate.reduce(f, initial, this); }; //----------------------------------------------------------------------- // Building and extending var unfold = __webpack_require__(91); var iterate = __webpack_require__(89); var generate = __webpack_require__(88); var build = __webpack_require__(23); exports.unfold = unfold.unfold; exports.iterate = iterate.iterate; exports.generate = generate.generate; exports.cycle = build.cycle; exports.concat = build.concat; exports.startWith = build.cons; /** * @deprecated * Tie this stream into a circle, thus creating an infinite stream * @returns {Stream} new infinite stream */ Stream.prototype.cycle = function () { return build.cycle(this); }; /** * @param {Stream} tail * @returns {Stream} new stream containing all items in this followed by * all items in tail */ Stream.prototype.concat = function (tail) { return build.concat(this, tail); }; /** * @param {*} x value to prepend * @returns {Stream} a new stream with x prepended */ Stream.prototype.startWith = function (x) { return build.cons(x, this); }; //----------------------------------------------------------------------- // Transforming var transform = __webpack_require__(12); var applicative = __webpack_require__(55); exports.map = transform.map; exports.constant = transform.constant; exports.tap = transform.tap; exports.ap = applicative.ap; /** * Transform each value in the stream by applying f to each * @param {function(*):*} f mapping function * @returns {Stream} stream containing items transformed by f */ Stream.prototype.map = function (f) { return transform.map(f, this); }; /** * Assume this stream contains functions, and apply each function to each item * in the provided stream. This generates, in effect, a cross product. * @param {Stream} xs stream of items to which * @returns {Stream} stream containing the cross product of items */ Stream.prototype.ap = function (xs) { return applicative.ap(this, xs); }; /** * Replace each value in the stream with x * @param {*} x * @returns {Stream} stream containing items replaced with x */ Stream.prototype.constant = function (x) { return transform.constant(x, this); }; /** * Perform a side effect for each item in the stream * @param {function(x:*):*} f side effect to execute for each item. The * return value will be discarded. * @returns {Stream} new stream containing the same items as this stream */ Stream.prototype.tap = function (f) { return transform.tap(f, this); }; //----------------------------------------------------------------------- // Transducer support var transduce = __webpack_require__(70); exports.transduce = transduce.transduce; /** * Transform this stream by passing its events through a transducer. * @param {function} transducer transducer function * @return {Stream} stream of events transformed by the transducer */ Stream.prototype.transduce = function (transducer) { return transduce.transduce(transducer, this); }; //----------------------------------------------------------------------- // FlatMapping var flatMap = __webpack_require__(26); exports.flatMap = exports.chain = flatMap.flatMap; exports.join = flatMap.join; /** * Map each value in the stream to a new stream, and merge it into the * returned outer stream. Event arrival times are preserved. * @param {function(x:*):Stream} f chaining function, must return a Stream * @returns {Stream} new stream containing all events from each stream returned by f */ Stream.prototype.flatMap = Stream.prototype.chain = function (f) { return flatMap.flatMap(f, this); }; /** * Monadic join. Flatten a Stream<Stream<X>> to Stream<X> by merging inner * streams to the outer. Event arrival times are preserved. * @returns {Stream<X>} new stream containing all events of all inner streams */ Stream.prototype.join = function () { return flatMap.join(this); }; var continueWith = __webpack_require__(25).continueWith; exports.continueWith = continueWith; exports.flatMapEnd = continueWith; /** * Map the end event to a new stream, and begin emitting its values. * @param {function(x:*):Stream} f function that receives the end event value, * and *must* return a new Stream to continue with. * @returns {Stream} new stream that emits all events from the original stream, * followed by all events from the stream returned by f. */ Stream.prototype.continueWith = Stream.prototype.flatMapEnd = function (f) { return continueWith(f, this); }; var concatMap = __webpack_require__(56).concatMap; exports.concatMap = concatMap; Stream.prototype.concatMap = function (f) { return concatMap(f, this); }; //----------------------------------------------------------------------- // Concurrent merging var mergeConcurrently = __webpack_require__(8); exports.mergeConcurrently = mergeConcurrently.mergeConcurrently; /** * Flatten a Stream<Stream<X>> to Stream<X> by merging inner * streams to the outer, limiting the number of inner streams that may * be active concurrently. * @param {number} concurrency at most this many inner streams will be * allowed to be active concurrently. * @return {Stream<X>} new stream containing all events of all inner * streams, with limited concurrency. */ Stream.prototype.mergeConcurrently = function (concurrency) { return mergeConcurrently.mergeConcurrently(concurrency, this); }; //----------------------------------------------------------------------- // Merging var merge = __webpack_require__(62); exports.merge = merge.merge; exports.mergeArray = merge.mergeArray; /** * Merge this stream and all the provided streams * @returns {Stream} stream containing items from this stream and s in time * order. If two events are simultaneous they will be merged in * arbitrary order. */ Stream.prototype.merge = function () /*...streams*/{ return merge.mergeArray(base.cons(this, arguments)); }; //----------------------------------------------------------------------- // Combining var combine = __webpack_require__(24); exports.combine = combine.combine; exports.combineArray = combine.combineArray; /** * Combine latest events from all input streams * @param {function(...events):*} f function to combine most recent events * @returns {Stream} stream containing the result of applying f to the most recent * event of each input stream, whenever a new event arrives on any stream. */ Stream.prototype.combine = function (f /*, ...streams*/) { return combine.combineArray(f, base.replace(this, 0, arguments)); }; //----------------------------------------------------------------------- // Sampling var sample = __webpack_require__(65); exports.sample = sample.sample; exports.sampleWith = sample.sampleWith; /** * When an event arrives on sampler, emit the latest event value from stream. * @param {Stream} sampler stream of events at whose arrival time * signal's latest value will be propagated * @returns {Stream} sampled stream of values */ Stream.prototype.sampleWith = function (sampler) { return sample.sampleWith(sampler, this); }; /** * When an event arrives on this stream, emit the result of calling f with the latest * values of all streams being sampled * @param {function(...values):*} f function to apply to each set of sampled values * @returns {Stream} stream of sampled and transformed values */ Stream.prototype.sample = function (f /* ...streams */) { return sample.sampleArray(f, this, base.tail(arguments)); }; //----------------------------------------------------------------------- // Zipping var zip = __webpack_require__(71); exports.zip = zip.zip; /** * Pair-wise combine items with those in s. Given 2 streams: * [1,2,3] zipWith f [4,5,6] -> [f(1,4),f(2,5),f(3,6)] * Note: zip causes fast streams to buffer and wait for slow streams. * @param {function(a:Stream, b:Stream, ...):*} f function to combine items * @returns {Stream} new stream containing pairs */ Stream.prototype.zip = function (f /*, ...streams*/) { return zip.zipArray(f, base.replace(this, 0, arguments)); }; //----------------------------------------------------------------------- // Switching var switchLatest = __webpack_require__(67).switch; exports.switch = switchLatest; exports.switchLatest = switchLatest; /** * Given a stream of streams, return a new stream that adopts the behavior * of the most recent inner stream. * @returns {Stream} switching stream */ Stream.prototype.switch = Stream.prototype.switchLatest = function () { return switchLatest(this); }; //----------------------------------------------------------------------- // Filtering var filter = __webpack_require__(59); exports.filter = filter.filter; exports.skipRepeats = exports.distinct = filter.skipRepeats; exports.skipRepeatsWith = exports.distinctBy = filter.skipRepeatsWith; /** * Retain only items matching a predicate * stream: -12345678- * filter(x => x % 2 === 0, stream): --2-4-6-8- * @param {function(x:*):boolean} p filtering predicate called for each item * @returns {Stream} stream containing only items for which predicate returns truthy */ Stream.prototype.filter = function (p) { return filter.filter(p, this); }; /** * Skip repeated events, using === to compare items * stream: -abbcd- * distinct(stream): -ab-cd- * @returns {Stream} stream with no repeated events */ Stream.prototype.skipRepeats = function () { return filter.skipRepeats(this); }; /** * Skip repeated events, using supplied equals function to compare items * @param {function(a:*, b:*):boolean} equals function to compare items * @returns {Stream} stream with no repeated events */ Stream.prototype.skipRepeatsWith = function (equals) { return filter.skipRepeatsWith(equals, this); }; //----------------------------------------------------------------------- // Slicing var slice = __webpack_require__(66); exports.take = slice.take; exports.skip = slice.skip; exports.slice = slice.slice; exports.takeWhile = slice.takeWhile; exports.skipWhile = slice.skipWhile; /** * stream: -abcd- * take(2, stream): -ab| * @param {Number} n take up to this many events * @returns {Stream} stream containing at most the first n items from this stream */ Stream.prototype.take = function (n) { return slice.take(n, this); }; /** * stream: -abcd-> * skip(2, stream): ---cd-> * @param {Number} n skip this many events * @returns {Stream} stream not containing the first n events */ Stream.prototype.skip = function (n) { return slice.skip(n, this); }; /** * Slice a stream by event index. Equivalent to, but more efficient than * stream.take(end).skip(start); * NOTE: Negative start and end are not supported * @param {Number} start skip all events before the start index * @param {Number} end allow all events from the start index to the end index * @returns {Stream} stream containing items where start <= index < end */ Stream.prototype.slice = function (start, end) { return slice.slice(start, end, this); }; /** * stream: -123451234-> * takeWhile(x => x < 5, stream): -1234| * @param {function(x:*):boolean} p predicate * @returns {Stream} stream containing items up to, but not including, the * first item for which p returns falsy. */ Stream.prototype.takeWhile = function (p) { return slice.takeWhile(p, this); }; /** * stream: -123451234-> * skipWhile(x => x < 5, stream): -----51234-> * @param {function(x:*):boolean} p predicate * @returns {Stream} stream containing items following *and including* the * first item for which p returns falsy. */ Stream.prototype.skipWhile = function (p) { return slice.skipWhile(p, this); }; //----------------------------------------------------------------------- // Time slicing var timeslice = __webpack_require__(68); exports.until = exports.takeUntil = timeslice.takeUntil; exports.since = exports.skipUntil = timeslice.skipUntil; exports.during = timeslice.during; /** * stream: -a-b-c-d-e-f-g-> * signal: -------x * takeUntil(signal, stream): -a-b-c-| * @param {Stream} signal retain only events in stream before the first * event in signal * @returns {Stream} new stream containing only events that occur before * the first event in signal. */ Stream.prototype.until = Stream.prototype.takeUntil = function (signal) { return timeslice.takeUntil(signal, this); }; /** * stream: -a-b-c-d-e-f-g-> * signal: -------x * takeUntil(signal, stream): -------d-e-f-g-> * @param {Stream} signal retain only events in stream at or after the first * event in signal * @returns {Stream} new stream containing only events that occur after * the first event in signal. */ Stream.prototype.since = Stream.prototype.skipUntil = function (signal) { return timeslice.skipUntil(signal, this); }; /** * stream: -a-b-c-d-e-f-g-> * timeWindow: -----s * s: -----t * stream.during(timeWindow): -----c-d-e-| * @param {Stream<Stream>} timeWindow a stream whose first event (s) represents * the window start time. That event (s) is itself a stream whose first event (t) * represents the window end time * @returns {Stream} new stream containing only events within the provided timespan */ Stream.prototype.during = function (timeWindow) { return timeslice.during(timeWindow, this); }; //----------------------------------------------------------------------- // Delaying var delay = __webpack_require__(57).delay; exports.delay = delay; /** * @param {Number} delayTime milliseconds to delay each item * @returns {Stream} new stream containing the same items, but delayed by ms */ Stream.prototype.delay = function (delayTime) { return delay(delayTime, this); }; //----------------------------------------------------------------------- // Getting event timestamp var timestamp = __webpack_require__(69).timestamp; exports.timestamp = timestamp; /** * Expose event timestamps into the stream. Turns a Stream<X> into * Stream<{time:t, value:X}> * @returns {Stream<{time:number, value:*}>} */ Stream.prototype.timestamp = function () { return timestamp(this); }; //----------------------------------------------------------------------- // Rate limiting var limit = __webpack_require__(60); exports.throttle = limit.throttle; exports.debounce = limit.debounce; /** * Limit the rate of events * stream: abcd----abcd---- * throttle(2, stream): a-c-----a-c----- * @param {Number} period time to suppress events * @returns {Stream} new stream that skips events for throttle period */ Stream.prototype.throttle = function (period) { return limit.throttle(period, this); }; /** * Wait for a burst of events to subside and emit only the last event in the burst * stream: abcd----abcd---- * debounce(2, stream): -----d-------d-- * @param {Number} period events occuring more frequently than this * on the provided scheduler will be suppressed * @returns {Stream} new debounced stream */ Stream.prototype.debounce = function (period) { return limit.debounce(period, this); }; //----------------------------------------------------------------------- // Awaiting Promises var promises = __webpack_require__(64); exports.fromPromise = promises.fromPromise; exports.await = promises.awaitPromises; /** * Await promises, turning a Stream<Promise<X>> into Stream<X>. Preserves * event order, but timeshifts events based on promise resolution time. * @returns {Stream<X>} stream containing non-promise values */ Stream.prototype.await = function () { return promises.awaitPromises(this); }; //----------------------------------------------------------------------- // Error handling var errors = __webpack_require__(58); exports.recoverWith = errors.flatMapError; exports.flatMapError = errors.flatMapError; exports.throwError = errors.throwError; /** * If this stream encounters an error, recover and continue with items from stream * returned by f. * stream: -a-b-c-X- * f(X): d-e-f-g- * flatMapError(f, stream): -a-b-c-d-e-f-g- * @param {function(error:*):Stream} f function which returns a new stream * @returns {Stream} new stream which will recover from an error by calling f */ Stream.prototype.recoverWith = Stream.prototype.flatMapError = function (f) { return errors.flatMapError(f, this); }; //----------------------------------------------------------------------- // Multicasting var multicast = __webpack_require__(5).default; exports.multicast = multicast; /** * Transform the stream into multicast stream. That means that many subscribers * to the stream will not cause multiple invocations of the internal machinery. * @returns {Stream} new stream which will multicast events to all observers. */ Stream.prototype.multicast = function () { return multicast(this); }; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;'use strict'; (function (global, factory) { if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [exports, __webpack_require__(3)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (typeof exports !== "undefined") { factory(exports, require('@most/prelude')); } else { var mod = { exports: {} }; factory(mod.exports, global.prelude); global.mostMulticast = mod.exports; } })(undefined, function (exports, _prelude) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.MulticastSource = undefined; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var MulticastDisposable = function () { function MulticastDisposable(source, sink) { _classCallCheck(this, MulticastDisposable); this.source = source; this.sink = sink; this.disposed = false; } _createClass(MulticastDisposable, [{ key: 'dispose', value: function dispose() { if (this.disposed) { return; } this.disposed = true; var remaining = this.source.remove(this.sink); return remaining === 0 && this.source._dispose(); } }]); return MulticastDisposable; }(); function tryEvent(t, x, sink) { try { sink.event(t, x); } catch (e) { sink.error(t, e); } } function tryEnd(t, x, sink) { try { sink.end(t, x); } catch (e) { sink.error(t, e); } } var dispose = function dispose(disposable) { return disposable.dispose(); }; var emptyDisposable = { dispose: function dispose() {} }; var MulticastSource = function () { function MulticastSource(source) { _classCallCheck(this, MulticastSource); this.source = source; this.sinks = []; this._disposable = emptyDisposable; } _createClass(MulticastSource, [{ key: 'run', value: function run(sink, scheduler) { var n = this.add(sink); if (n === 1) { this._disposable = this.source.run(this, scheduler); } return new MulticastDisposable(this, sink); } }, { key: '_dispose', value: function _dispose() { var disposable = this._disposable; this._disposable = emptyDisposable; return Promise.resolve(disposable).then(dispose); } }, { key: 'add', value: function add(sink) { this.sinks = (0, _prelude.append)(sink, this.sinks); return this.sinks.length; } }, { key: 'remove', value: function remove(sink) { var i = (0, _prelude.findIndex)(sink, this.sinks); // istanbul ignore next if (i >= 0) { this.sinks = (0, _prelude.remove)(i, this.sinks); } return this.sinks.length; } }, { key: 'event', value: function event(time, value) { var s = this.sinks; if (s.length === 1) { return s[0].event(time, value); } for (var i = 0; i < s.length; ++i) { tryEvent(time, value, s[i]); } } }, { key: 'end', value: function end(time, value) { var s = this.sinks; for (var i = 0; i < s.length; ++i) { tryEnd(time, value, s[i]); } } }, { key: 'error', value: function error(time, err) { var s = this.sinks; for (var i = 0; i < s.length; ++i) { s[i].error(time, err); } } }]); return MulticastSource; }(); function multicast(stream) { var source = stream.source; return source instanceof MulticastSource ? stream : new stream.constructor(new MulticastSource(source)); } exports.MulticastSource = MulticastSource; exports.default = multicast; }); /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var fatal = __webpack_require__(28); module.exports = PropagateTask; function PropagateTask(run, value, sink) { this._run = run; this.value = value; this.sink = sink; this.active = true; } PropagateTask.event = function (value, sink) { return new PropagateTask(emit, value, sink); }; PropagateTask.end = function (value, sink) { return new PropagateTask(end, value, sink); }; PropagateTask.error = function (value, sink) { return new PropagateTask(error, value, sink); }; PropagateTask.prototype.dispose = function () { this.active = false; }; PropagateTask.prototype.run = function (t) { if (!this.active) { return; } this._run(t, this.value, this.sink); }; PropagateTask.prototype.error = function (t, e) { if (!this.active) { return fatal(e); } this.sink.error(t, e); }; function error(t, e, sink) { sink.error(t, e); } function emit(t, x, sink) { sink.event(t, x); } function end(t, x, sink) { sink.end(t, x); } /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var ValueSource = __webpack_require__(34); var dispose = __webpack_require__(2); var PropagateTask = __webpack_require__(6); exports.of = streamOf; exports.empty = empty; exports.never = never; /** * Stream containing only x * @param {*} x * @returns {Stream} */ function streamOf(x) { return new Stream(new ValueSource(emit, x)); } function emit(t, x, sink) { sink.event(0, x); sink.end(0, void 0); } /** * Stream containing no events and ends immediately * @returns {Stream} */ function empty() { return EMPTY; } function EmptySource() {} EmptySource.prototype.run = function (sink, scheduler) { var task = PropagateTask.end(void 0, sink); scheduler.asap(task); return dispose.create(disposeEmpty, task); }; function disposeEmpty(task) { return task.dispose(); } var EMPTY = new Stream(new EmptySource()); /** * Stream containing no events and never ends * @returns {Stream} */ function never() { return NEVER; } function NeverSource() {} NeverSource.prototype.run = function () { return dispose.empty(); }; var NEVER = new Stream(new NeverSource()); /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var dispose = __webpack_require__(2); var LinkedList = __webpack_require__(52); var identity = __webpack_require__(3).id; exports.mergeConcurrently = mergeConcurrently; exports.mergeMapConcurrently = mergeMapConcurrently; function mergeConcurrently(concurrency, stream) { return mergeMapConcurrently(identity, concurrency, stream); } function mergeMapConcurrently(f, concurrency, stream) { return new Stream(new MergeConcurrently(f, concurrency, stream.source)); } function MergeConcurrently(f, concurrency, source) { this.f = f; this.concurrency = concurrency; this.source = source; } MergeConcurrently.prototype.run = function (sink, scheduler) { return new Outer(this.f, this.concurrency, this.source, sink, scheduler); }; function Outer(f, concurrency, source, sink, scheduler) { this.f = f; this.concurrency = concurrency; this.sink = sink; this.scheduler = scheduler; this.pending = []; this.current = new LinkedList(); this.disposable = dispose.once(source.run(this, scheduler)); this.active = true; } Outer.prototype.event = function (t, x) { this._addInner(t, x); }; Outer.prototype._addInner = function (t, stream) { if (this.current.length < this.concurrency) { this._startInner(t, stream); } else { this.pending.push(stream); } }; Outer.prototype._startInner = function (t, stream) { var innerSink = new Inner(t, this, this.sink); this.current.add(innerSink); innerSink.disposable = mapAndRun(this.f, innerSink, this.scheduler, stream); }; function mapAndRun(f, innerSink, scheduler, stream) { return f(stream).source.run(innerSink, scheduler); } Outer.prototype.end = function (t, x) { this.active = false; dispose.tryDispose(t, this.disposable, this.sink); this._checkEnd(t, x); }; Outer.prototype.error = function (t, e) { this.active = false; this.sink.error(t, e); }; Outer.prototype.dispose = function () { this.active = false; this.pending.length = 0; return Promise.all([this.disposable.dispose(), this.current.dispose()]); }; Outer.prototype._endInner = function (t, x, inner) { this.current.remove(inner); dispose.tryDispose(t, inner, this); if (this.pending.length === 0) { this._checkEnd(t, x); } else { this._startInner(t, this.pending.shift()); } }; Outer.prototype._checkEnd = function (t, x) { if (!this.active && this.current.isEmpty()) { this.sink.end(t, x); } }; function Inner(time, outer, sink) { this.prev = this.next = null; this.time = time; this.outer = outer; this.sink = sink; this.disposable = void 0; } Inner.prototype.event = function (t, x) { this.sink.event(Math.max(t, this.time), x); }; Inner.prototype.end = function (t, x) { this.outer._endInner(Math.max(t, this.time), x, this); }; Inner.prototype.error = function (t, e) { this.outer.error(Math.max(t, this.time), e); }; Inner.prototype.dispose = function () { return this.disposable.dispose(); }; /***/ }, /* 9 */ /***/ function(module, exports) { "use strict"; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ exports.tryEvent = tryEvent; exports.tryEnd = tryEnd; function tryEvent(t, x, sink) { try { sink.event(t, x); } catch (e) { sink.error(t, e); } } function tryEnd(t, x, sink) { try { sink.end(t, x); } catch (e) { sink.error(t, e); } } /***/ }, /* 10 */ /***/ function(module, exports) { 'use strict'; module.exports = { array: Array.isArray, primitive: function primitive(s) { return typeof s === 'string' || typeof s === 'number'; } }; /***/ }, /* 11 */ /***/ function(module, exports) { 'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ exports.isPromise = isPromise; function isPromise(p) { return p !== null && (typeof p === 'undefined' ? 'undefined' : _typeof(p)) === 'object' && typeof p.then === 'function'; } /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var Map = __webpack_require__(30); exports.map = map; exports.constant = constant; exports.tap = tap; /** * Transform each value in the stream by applying f to each * @param {function(*):*} f mapping function * @param {Stream} stream stream to map * @returns {Stream} stream containing items transformed by f */ function map(f, stream) { return new Stream(Map.create(f, stream.source)); } /** * Replace each value in the stream with x * @param {*} x * @param {Stream} stream * @returns {Stream} stream containing items replaced with x */ function constant(x, stream) { return map(function () { return x; }, stream); } /** * Perform a side effect for each item in the stream * @param {function(x:*):*} f side effect to execute for each item. The * return value will be discarded. * @param {Stream} stream stream to tap * @returns {Stream} new stream containing the same items as this stream */ function tap(f, stream) { return map(function (x) { f(x); return x; }, stream); } /***/ }, /* 13 */ /***/ function(module, exports) { "use strict"; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ module.exports = invoke; function invoke(f, args) { /*eslint complexity: [2,7]*/ switch (args.length) { case 0: return f(); case 1: return f(args[0]); case 2: return f(args[0], args[1]); case 3: return f(args[0], args[1], args[2]); case 4: return f(args[0], args[1], args[2], args[3]); case 5: return f(args[0], args[1], args[2], args[3], args[4]); default: return f.apply(void 0, args); } } /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Sink = __webpack_require__(1); module.exports = IndexSink; IndexSink.hasValue = hasValue; function hasValue(indexSink) { return indexSink.hasValue; } function IndexSink(i, sink) { this.index = i; this.sink = sink; this.active = true; this.hasValue = false; this.value = void 0; } IndexSink.prototype.event = function (t, x) { if (!this.active) { return; } this.value = x; this.hasValue = true; this.sink.event(t, this); }; IndexSink.prototype.end = function (t, x) { if (!this.active) { return; } this.active = false; this.sink.end(t, { index: this.index, value: x }); }; IndexSink.prototype.error = Sink.prototype.error; /***/ }, /* 15 */ /***/ function(module, exports) { "use strict"; module.exports = function (sel, data, children, text, elm) { var key = data === undefined ? undefined : data.key; return { sel: sel, data: data, children: children, text: text, elm: elm, key: key }; }; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.mockDOMSource = exports.makeDOMDriver = exports.video = exports.ul = exports.u = exports.tr = exports.title = exports.thead = exports.th = exports.tfoot = exports.textarea = exports.td = exports.tbody = exports.table = exports.sup = exports.sub = exports.style = exports.strong = exports.span = exports.source = exports.small = exports.select = exports.section = exports.script = exports.samp = exports.s = exports.ruby = exports.rt = exports.rp = exports.q = exports.pre = exports.param = exports.p = exports.option = exports.optgroup = exports.ol = exports.object = exports.noscript = exports.nav = exports.meta = exports.menu = exports.mark = exports.map = exports.main = exports.link = exports.li = exports.legend = exports.label = exports.keygen = exports.kbd = exports.ins = exports.input = exports.img = exports.iframe = exports.i = exports.html = exports.hr = exports.hgroup = exports.header = exports.head = exports.h6 = exports.h5 = exports.h4 = exports.h3 = exports.h2 = exports.h1 = exports.form = exports.footer = exports.figure = exports.figcaption = exports.fieldset = exports.embed = exports.em = exports.dt = exports.dl = exports.div = exports.dir = exports.dfn = exports.del = exports.dd = exports.colgroup = exports.col = exports.code = exports.cite = exports.caption = exports.canvas = exports.button = exports.br = exports.body = exports.blockquote = exports.bdo = exports.bdi = exports.base = exports.b = exports.audio = exports.aside = exports.article = exports.area = exports.address = exports.abbr = exports.a = exports.h = exports.thunk = exports.modules = undefined; var _makeDOMDriver = __webpack_require__(42); Object.defineProperty(exports, 'makeDOMDriver', { enumerable: true, get: function get() { return _makeDOMDriver.makeDOMDriver; } }); var _mockDOMSource = __webpack_require__(43); Object.defineProperty(exports, 'mockDOMSource', { enumerable: true, get: function get() { return _mockDOMSource.mockDOMSource; } }); var _modules = __webpack_require__(21); var modules = _interopRequireWildcard(_modules); var _thunk = __webpack_require__(101); var _thunk2 = _interopRequireDefault(_thunk); var _hyperscript = __webpack_require__(41); var _hyperscript2 = _interopRequireDefault(_hyperscript); var _hyperscriptHelpers = __webpack_require__(47); var _hyperscriptHelpers2 = _interopRequireDefault(_hyperscriptHelpers); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {};if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } }newObj.default = obj;return newObj; } } exports.modules = modules; exports.thunk = _thunk2.default; exports.h = _hyperscript2.default; var _hh = (0, _hyperscriptHelpers2.default)(_hyperscript2.default); var a = _hh.a; var abbr = _hh.abbr; var address = _hh.address; var area = _hh.area; var article = _hh.article; var aside = _hh.aside; var audio = _hh.audio; var b = _hh.b; var base = _hh.base; var bdi = _hh.bdi; var bdo = _hh.bdo; var blockquote = _hh.blockquote; var body = _hh.body; var br = _hh.br; var button = _hh.button; var canvas = _hh.canvas; var caption = _hh.caption; var cite = _hh.cite; var code = _hh.code; var col = _hh.col; var colgroup = _hh.colgroup; var dd = _hh.dd; var del = _hh.del; var dfn = _hh.dfn; var dir = _hh.dir; var div = _hh.div; var dl = _hh.dl; var dt = _hh.dt; var em = _hh.em; var embed = _hh.embed; var fieldset = _hh.fieldset; var figcaption = _hh.figcaption; var figure = _hh.figure; var footer = _hh.footer; var form = _hh.form; var h1 = _hh.h1; var h2 = _hh.h2; var h3 = _hh.h3; var h4 = _hh.h4; var h5 = _hh.h5; var h6 = _hh.h6; var head = _hh.head; var header = _hh.header; var hgroup = _hh.hgroup; var hr = _hh.hr; var html = _hh.html; var i = _hh.i; var iframe = _hh.iframe; var img = _hh.img; var input = _hh.input; var ins = _hh.ins; var kbd = _hh.kbd; var keygen = _hh.keygen; var label = _hh.label; var legend = _hh.legend; var li = _hh.li; var link = _hh.link; var main = _hh.main; var map = _hh.map; var mark = _hh.mark; var menu = _hh.menu; var meta = _hh.meta; var nav = _hh.nav; var noscript = _hh.noscript; var object = _hh.object; var ol = _hh.ol; var optgroup = _hh.optgroup; var option = _hh.option; var p = _hh.p; var param = _hh.param; var pre = _hh.pre; var q = _hh.q; var rp = _hh.rp; var rt = _hh.rt; var ruby = _hh.ruby; var s = _hh.s; var samp = _hh.samp; var script = _hh.script; var section = _hh.section; var select = _hh.select; var small = _hh.small; var source = _hh.source; var span = _hh.span; var strong = _hh.strong; var style = _hh.style; var sub = _hh.sub; var sup = _hh.sup; var table = _hh.table; var tbody = _hh.tbody; var td = _hh.td; var textarea = _hh.textarea; var tfoot = _hh.tfoot; var th = _hh.th; var thead = _hh.thead; var title = _hh.title; var tr = _hh.tr; var u = _hh.u; var ul = _hh.ul; var video = _hh.video; exports.a = a; exports.abbr = abbr; exports.address = address; exports.area = area; exports.article = article; exports.aside = aside; exports.audio = audio; exports.b = b; exports.base = base; exports.bdi = bdi; exports.bdo = bdo; exports.blockquote = blockquote; exports.body = body; exports.br = br; exports.button = button; exports.canvas = canvas; exports.caption = caption; exports.cite = cite; exports.code = code; exports.col = col; exports.colgroup = colgroup; exports.dd = dd; exports.del = del; exports.dfn = dfn; exports.dir = dir; exports.div = div; exports.dl = dl; exports.dt = dt; exports.em = em; exports.embed = embed; exports.fieldset = fieldset; exports.figcaption = figcaption; exports.figure = figure; exports.footer = footer; exports.form = form; exports.h1 = h1; exports.h2 = h2; exports.h3 = h3; exports.h4 = h4; exports.h5 = h5; exports.h6 = h6; exports.head = head; exports.header = header; exports.hgroup = hgroup; exports.hr = hr; exports.html = html; exports.i = i; exports.iframe = iframe; exports.img = img; exports.input = input; exports.ins = ins; exports.kbd = kbd; exports.keygen = keygen; exports.label = label; exports.legend = legend; exports.li = li; exports.link = link; exports.main = main; exports.map = map; exports.mark = mark; exports.menu = menu; exports.meta = meta; exports.nav = nav; exports.noscript = noscript; exports.object = object; exports.ol = ol; exports.optgroup = optgroup; exports.option = option; exports.p = p; exports.param = param; exports.pre = pre; exports.q = q; exports.rp = rp; exports.rt = rt; exports.ruby = ruby; exports.s = s; exports.samp = samp; exports.script = script; exports.section = section; exports.select = select; exports.small = small; exports.source = source; exports.span = span; exports.strong = strong; exports.style = style; exports.sub = sub; exports.sup = sup; exports.table = table; exports.tbody = tbody; exports.td = td; exports.textarea = textarea; exports.tfoot = tfoot; exports.th = th; exports.thead = thead; exports.title = title; exports.tr = tr; exports.u = u; exports.ul = ul; exports.video = video; /***/ }, /* 17 */ /***/ function(module, exports) { 'use strict'; // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; (function () { try { cachedSetTimeout = setTimeout; } catch (e) { cachedSetTimeout = function cachedSetTimeout() { throw new Error('setTimeout is not defined'); }; } try { cachedClearTimeout = clearTimeout; } catch (e) { cachedClearTimeout = function cachedClearTimeout() { throw new Error('clearTimeout is not defined'); }; } })(); var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = cachedSetTimeout(cleanUpNextTick); draining = true; var len = queue.length; while (len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; cachedClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { cachedSetTimeout(drainQueue, 0); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/'; }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function () { return 0; }; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.makeEventsSelector = undefined; var _domEvent = __webpack_require__(39); var _makeIsStrictlyInRootScope = __webpack_require__(20); var matchesSelector = void 0; try { matchesSelector = __webpack_require__(48); } catch (e) { matchesSelector = function matchesSelector() {}; } var eventTypesThatDontBubble = ['load', 'unload', 'focus', 'blur', 'mouseenter', 'mouseleave', 'submit', 'change', 'reset', 'timeupdate', 'playing', 'waiting', 'seeking', 'seeked', 'ended', 'loadedmetadata', 'loadeddata', 'canplay', 'canplaythrough', 'durationchange', 'play', 'pause', 'ratechange', 'volumechange', 'suspend', 'emptied', 'stalled']; function maybeMutateEventPropagationAttributes(event) { if (!event.hasOwnProperty('propagationHasBeenStopped')) { (function () { event.propagationHasBeenStopped = false; var oldStopPropagation = event.stopPropagation; event.stopPropagation = function stopPropagation() { oldStopPropagation.call(this); this.propagationHasBeenStopped = true; }; })(); } } function mutateEventCurrentTarget(event, currentTargetElement) { try { Object.defineProperty(event, 'currentTarget', { value: currentTargetElement, configurable: true }); } catch (err) { console.log('please use event.ownerTarget'); } event.ownerTarget = currentTargetElement; } function makeSimulateBubbling(namespace, rootEl) { var isStrictlyInRootScope = (0, _makeIsStrictlyInRootScope.makeIsStrictlyInRootScope)(namespace); var descendantSel = namespace.join(' '); var topSel = namespace.join(''); var roof = rootEl.parentElement; return function simulateBubbling(ev) { maybeMutateEventPropagationAttributes(ev); if (ev.propagationHasBeenStopped) { return false; } for (var el = ev.target; el && el !== roof; el = el.parentElement) { if (!isStrictlyInRootScope(el)) { continue; } if (matchesSelector(el, descendantSel) || matchesSelector(el, topSel)) { mutateEventCurrentTarget(ev, el); return true; } } return false; }; } var defaults = { useCapture: false }; function makeEventsSelector(rootElement$, namespace) { return function eventsSelector(type) { var options = arguments.length <= 1 || arguments[1] === undefined ? defaults : arguments[1]; if (typeof type !== 'string') { throw new Error('DOM driver\'s events() expects argument to be a ' + 'string representing the event type to listen for.'); } var useCapture = false; if (typeof options.useCapture === 'boolean') { useCapture = options.useCapture; } if (eventTypesThatDontBubble.indexOf(type) !== -1) { useCapture = true; } return rootElement$.map(function (rootElement) { return { rootElement: rootElement, namespace: namespace }; }).skipRepeatsWith(function (prev, curr) { return prev.namespace.join('') === curr.namespace.join(''); }).map(function (_ref) { var rootElement = _ref.rootElement; if (!namespace || namespace.length === 0) { return (0, _domEvent.domEvent)(type, rootElement, useCapture); } var simulateBubbling = makeSimulateBubbling(namespace, rootElement); return (0, _domEvent.domEvent)(type, rootElement, useCapture).filter(simulateBubbling); }).switch().multicast(); }; } exports.makeEventsSelector = makeEventsSelector; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.isolateSource = exports.isolateSink = undefined; var _utils = __webpack_require__(22); var isolateSource = function isolateSource(source_, scope) { return source_.select('.' + _utils.SCOPE_PREFIX + scope); }; var isolateSink = function isolateSink(sink, scope) { return sink.map(function (vTree) { if (vTree.sel.indexOf('' + _utils.SCOPE_PREFIX + scope) === -1) { if (vTree.data.ns) { // svg elements var _vTree$data$attrs = vTree.data.attrs; var attrs = _vTree$data$attrs === undefined ? {} : _vTree$data$attrs; attrs.class = (attrs.class || '') + ' ' + _utils.SCOPE_PREFIX + scope; } else { vTree.sel = vTree.sel + '.' + _utils.SCOPE_PREFIX + scope; } } return vTree; }); }; exports.isolateSink = isolateSink; exports.isolateSource = isolateSource; /***/ }, /* 20 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function makeIsStrictlyInRootScope(namespace) { var classIsForeign = function classIsForeign(c) { var matched = c.match(/cycle-scope-(\S+)/); return matched && namespace.indexOf("." + c) === -1; }; var classIsDomestic = function classIsDomestic(c) { var matched = c.match(/cycle-scope-(\S+)/); return matched && namespace.indexOf("." + c) !== -1; }; return function isStrictlyInRootScope(leaf) { var some = Array.prototype.some; var split = String.prototype.split; for (var el = leaf; el; el = el.parentElement) { var classList = el.classList || split.call(el.className, " "); if (some.call(classList, classIsDomestic)) { return true; } if (some.call(classList, classIsForeign)) { return false; } } return true; }; } exports.makeIsStrictlyInRootScope = makeIsStrictlyInRootScope; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.EventsModule = exports.HeroModule = exports.AttrsModule = exports.PropsModule = exports.ClassModule = exports.StyleModule = undefined; var _class = __webpack_require__(95); var _class2 = _interopRequireDefault(_class); var _props = __webpack_require__(98); var _props2 = _interopRequireDefault(_props); var _attributes = __webpack_require__(94); var _attributes2 = _interopRequireDefault(_attributes); var _eventlisteners = __webpack_require__(96); var _eventlisteners2 = _interopRequireDefault(_eventlisteners); var _style = __webpack_require__(99); var _style2 = _interopRequireDefault(_style); var _hero = __webpack_require__(97); var _hero2 = _interopRequireDefault(_hero); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = [_style2.default, _class2.default, _props2.default, _attributes2.default]; exports.StyleModule = _style2.default; exports.ClassModule = _class2.default; exports.PropsModule = _props2.default; exports.AttrsModule = _attributes2.default; exports.HeroModule = _hero2.default; exports.EventsModule = _eventlisteners2.default; /***/ }, /* 22 */ /***/ function(module, exports) { "use strict"; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; Object.defineProperty(exports, "__esModule", { value: true }); var SCOPE_PREFIX = "cycle-scope-"; var isElement = function isElement(obj) { return (typeof HTMLElement === "undefined" ? "undefined" : _typeof(HTMLElement)) === "object" ? obj instanceof HTMLElement || obj instanceof DocumentFragment : obj && (typeof obj === "undefined" ? "undefined" : _typeof(obj)) === "object" && obj !== null && (obj.nodeType === 1 || obj.nodeType === 11) && typeof obj.nodeName === "string"; }; var domSelectorParser = function domSelectorParser(selectors) { var domElement = typeof selectors === "string" ? document.querySelector(selectors) : selectors; if (typeof domElement === "string" && domElement === null) { throw new Error("Cannot render into unknown element `" + selectors + "`"); } else if (!isElement(domElement)) { throw new Error("Given container is not a DOM element neither a " + "selector string."); } return domElement; }; exports.domSelectorParser = domSelectorParser; exports.SCOPE_PREFIX = SCOPE_PREFIX; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var streamOf = __webpack_require__(7).of; var continueWith = __webpack_require__(25).continueWith; exports.concat = concat; exports.cycle = cycle; exports.cons = cons; /** * @param {*} x value to prepend * @param {Stream} stream * @returns {Stream} new stream with x prepended */ function cons(x, stream) { return concat(streamOf(x), stream); } /** * @param {Stream} left * @param {Stream} right * @returns {Stream} new stream containing all events in left followed by all * events in right. This *timeshifts* right to the end of left. */ function concat(left, right) { return continueWith(function () { return right; }, left); } /** * @deprecated * Tie stream into a circle, creating an infinite stream * @param {Stream} stream * @returns {Stream} new infinite stream */ function cycle(stream) { return continueWith(function cycleNext() { return cycle(stream); }, stream); } /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var transform = __webpack_require__(12); var core = __webpack_require__(7); var Pipe = __webpack_require__(1); var IndexSink = __webpack_require__(14); var dispose = __webpack_require__(2); var base = __webpack_require__(3); var invoke = __webpack_require__(13); var hasValue = IndexSink.hasValue; var map = base.map; var tail = base.tail; exports.combineArray = combineArray; exports.combine = combine; /** * Combine latest events from all input streams * @param {function(...events):*} f function to combine most recent events * @returns {Stream} stream containing the result of applying f to the most recent * event of each input stream, whenever a new event arrives on any stream. */ function combine(f /*, ...streams */) { return combineArray(f, tail(arguments)); } /** * Combine latest events from all input streams * @param {function(...events):*} f function to combine most recent events * @param {[Stream]} streams most recent events * @returns {Stream} stream containing the result of applying f to the most recent * event of each input stream, whenever a new event arrives on any stream. */ function combineArray(f, streams) { var l = streams.length; return l === 0 ? core.empty() : l === 1 ? transform.map(f, streams[0]) : new Stream(combineSources(f, streams)); } function combineSources(f, streams) { return new Combine(f, map(getSource, streams)); } function getSource(stream) { return stream.source; } function Combine(f, sources) { this.f = f; this.sources = sources; } Combine.prototype.run = function (sink, scheduler) { var l = this.sources.length; var disposables = new Array(l); var sinks = new Array(l); var mergeSink = new CombineSink(disposables, sinks, sink, this.f); for (var indexSink, i = 0; i < l; ++i) { indexSink = sinks[i] = new IndexSink(i, mergeSink); disposables[i] = this.sources[i].run(indexSink, scheduler); } return dispose.all(disposables); }; function CombineSink(disposables, sinks, sink, f) { this.sink = sink; this.disposables = disposables; this.sinks = sinks; this.f = f; this.values = new Array(sinks.length); this.ready = false; this.activeCount = sinks.length; } CombineSink.prototype.error = Pipe.prototype.error; CombineSink.prototype.event = function (t, indexedValue) { if (!this.ready) { this.ready = this.sinks.every(hasValue); } this.values[indexedValue.index] = indexedValue.value; if (this.ready) { this.sink.event(t, invoke(this.f, this.values)); } }; CombineSink.prototype.end = function (t, indexedValue) { dispose.tryDispose(t, this.disposables[indexedValue.index], this.sink); if (--this.activeCount === 0) { this.sink.end(t, indexedValue.value); } }; /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var Sink = __webpack_require__(1); var dispose = __webpack_require__(2); var isPromise = __webpack_require__(11).isPromise; exports.continueWith = continueWith; function continueWith(f, stream) { return new Stream(new ContinueWith(f, stream.source)); } function ContinueWith(f, source) { this.f = f; this.source = source; } ContinueWith.prototype.run = function (sink, scheduler) { return new ContinueWithSink(this.f, this.source, sink, scheduler); }; function ContinueWithSink(f, source, sink, scheduler) { this.f = f; this.sink = sink; this.scheduler = scheduler; this.active = true; this.disposable = dispose.once(source.run(this, scheduler)); } ContinueWithSink.prototype.error = Sink.prototype.error; ContinueWithSink.prototype.event = function (t, x) { if (!this.active) { return; } this.sink.event(t, x); }; ContinueWithSink.prototype.end = function (t, x) { if (!this.active) { return; } var result = dispose.tryDispose(t, this.disposable, this.sink); this.disposable = isPromise(result) ? dispose.promised(this._thenContinue(result, x)) : this._continue(this.f, x); }; ContinueWithSink.prototype._thenContinue = function (p, x) { var self = this; return p.then(function () { return self._continue(self.f, x); }); }; ContinueWithSink.prototype._continue = function (f, x) { return f(x).source.run(this.sink, this.scheduler); }; ContinueWithSink.prototype.dispose = function () { this.active = false; return this.disposable.dispose(); }; /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var mergeConcurrently = __webpack_require__(8).mergeConcurrently; var mergeMapConcurrently = __webpack_require__(8).mergeMapConcurrently; exports.flatMap = flatMap; exports.join = join; /** * Map each value in the stream to a new stream, and merge it into the * returned outer stream. Event arrival times are preserved. * @param {function(x:*):Stream} f chaining function, must return a Stream * @param {Stream} stream * @returns {Stream} new stream containing all events from each stream returned by f */ function flatMap(f, stream) { return mergeMapConcurrently(f, Infinity, stream); } /** * Monadic join. Flatten a Stream<Stream<X>> to Stream<X> by merging inner * streams to the outer. Event arrival times are preserved. * @param {Stream<Stream<X>>} stream stream of streams * @returns {Stream<X>} new stream containing all events of all inner streams */ function join(stream) { return mergeConcurrently(Infinity, stream); } /***/ }, /* 27 */ /***/ function(module, exports) { "use strict"; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ module.exports = defer; function defer(task) { return Promise.resolve(task).then(runTask); } function runTask(task) { try { return task.run(); } catch (e) { return task.error(e); } } /***/ }, /* 28 */ /***/ function(module, exports) { "use strict"; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ module.exports = fatalError; function fatalError(e) { setTimeout(function () { throw e; }, 0); } /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Pipe = __webpack_require__(1); module.exports = Filter; function Filter(p, source) { this.p = p; this.source = source; } /** * Create a filtered source, fusing adjacent filter.filter if possible * @param {function(x:*):boolean} p filtering predicate * @param {{run:function}} source source to filter * @returns {Filter} filtered source */ Filter.create = function createFilter(p, source) { if (source instanceof Filter) { return new Filter(and(source.p, p), source.source); } return new Filter(p, source); }; Filter.prototype.run = function (sink, scheduler) { return this.source.run(new FilterSink(this.p, sink), scheduler); }; function FilterSink(p, sink) { this.p = p; this.sink = sink; } FilterSink.prototype.end = Pipe.prototype.end; FilterSink.prototype.error = Pipe.prototype.error; FilterSink.prototype.event = function (t, x) { var p = this.p; p(x) && this.sink.event(t, x); }; function and(p, q) { return function (x) { return p(x) && q(x); }; } /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Pipe = __webpack_require__(1); var Filter = __webpack_require__(29); var FilterMap = __webpack_require__(74); var base = __webpack_require__(3); module.exports = Map; function Map(f, source) { this.f = f; this.source = source; } /** * Create a mapped source, fusing adjacent map.map, filter.map, * and filter.map.map if possible * @param {function(*):*} f mapping function * @param {{run:function}} source source to map * @returns {Map|FilterMap} mapped source, possibly fused */ Map.create = function createMap(f, source) { if (source instanceof Map) { return new Map(base.compose(f, source.f), source.source); } if (source instanceof Filter) { return new FilterMap(source.p, f, source.source); } if (source instanceof FilterMap) { return new FilterMap(source.p, base.compose(f, source.f), source.source); } return new Map(f, source); }; Map.prototype.run = function (sink, scheduler) { return this.source.run(new MapSink(this.f, sink), scheduler); }; function MapSink(f, sink) { this.f = f; this.sink = sink; } MapSink.prototype.end = Pipe.prototype.end; MapSink.prototype.error = Pipe.prototype.error; MapSink.prototype.event = function (t, x) { var f = this.f; this.sink.event(t, f(x)); }; /***/ }, /* 31 */ /***/ function(module, exports) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ exports.isIterable = isIterable; exports.getIterator = getIterator; exports.makeIterable = makeIterable; /*global Set, Symbol*/ var iteratorSymbol; // Firefox ships a partial implementation using the name @@iterator. // https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14 if (typeof Set === 'function' && typeof new Set()['@@iterator'] === 'function') { iteratorSymbol = '@@iterator'; } else { iteratorSymbol = typeof Symbol === 'function' && Symbol.iterator || '_es6shim_iterator_'; } function isIterable(o) { return typeof o[iteratorSymbol] === 'function'; } function getIterator(o) { return o[iteratorSymbol](); } function makeIterable(f, o) { o[iteratorSymbol] = f; return o; } /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Observer = __webpack_require__(79); var dispose = __webpack_require__(2); var defaultScheduler = __webpack_require__(76); exports.withDefaultScheduler = withDefaultScheduler; exports.withScheduler = withScheduler; function withDefaultScheduler(f, source) { return withScheduler(f, source, defaultScheduler); } function withScheduler(f, source, scheduler) { return new Promise(function (resolve, reject) { runSource(f, source, scheduler, resolve, reject); }); } function runSource(f, source, scheduler, resolve, reject) { var disposable = dispose.settable(); var observer = new Observer(f, resolve, reject, disposable); disposable.setDisposable(source.run(observer, scheduler)); } /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var defer = __webpack_require__(27); module.exports = DeferredSink; function DeferredSink(sink) { this.sink = sink; this.events = []; this.length = 0; this.active = true; } DeferredSink.prototype.event = function (t, x) { if (!this.active) { return; } if (this.length === 0) { defer(new PropagateAllTask(this)); } this.events[this.length++] = { time: t, value: x }; }; DeferredSink.prototype.error = function (t, e) { this.active = false; defer(new ErrorTask(t, e, this.sink)); }; DeferredSink.prototype.end = function (t, x) { this.active = false; defer(new EndTask(t, x, this.sink)); }; function PropagateAllTask(deferred) { this.deferred = deferred; } PropagateAllTask.prototype.run = function () { var p = this.deferred; var events = p.events; var sink = p.sink; var event; for (var i = 0, l = p.length; i < l; ++i) { event = events[i]; sink.event(event.time, event.value); events[i] = void 0; } p.length = 0; }; PropagateAllTask.prototype.error = function (e) { this.deferred.error(0, e); }; function EndTask(t, x, sink) { this.time = t; this.value = x; this.sink = sink; } EndTask.prototype.run = function () { this.sink.end(this.time, this.value); }; EndTask.prototype.error = function (e) { this.sink.error(this.time, e); }; function ErrorTask(t, e, sink) { this.time = t; this.value = e; this.sink = sink; } ErrorTask.prototype.run = function () { this.sink.error(this.time, this.value); }; ErrorTask.prototype.error = function (e) { throw e; }; /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var PropagateTask = __webpack_require__(6); module.exports = ValueSource; function ValueSource(emit, x) { this.emit = emit; this.value = x; } ValueSource.prototype.run = function (sink, scheduler) { return new ValueProducer(this.emit, this.value, sink, scheduler); }; function ValueProducer(emit, x, sink, scheduler) { this.task = scheduler.asap(new PropagateTask(emit, x, sink)); } ValueProducer.prototype.dispose = function () { return this.task.cancel(); }; /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = selectorParser; var _browserSplit = __webpack_require__(46); var _browserSplit2 = _interopRequireDefault(_browserSplit); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var classIdSplit = /([\.#]?[a-zA-Z0-9\u007F-\uFFFF_:-]+)/; var notClassId = /^\.|#/; function selectorParser() { var selector = arguments.length <= 0 || arguments[0] === undefined ? '' : arguments[0]; var tagName = undefined; var id = ''; var classes = []; var tagParts = (0, _browserSplit2.default)(selector, classIdSplit); if (notClassId.test(tagParts[1]) || selector === '') { tagName = 'div'; } var part = undefined; var type = undefined; var i = undefined; for (i = 0; i < tagParts.length; i++) { part = tagParts[i]; if (!part) { continue; } type = part.charAt(0); if (!tagName) { tagName = part; } else if (type === '.') { classes.push(part.substring(1, part.length)); } else if (type === '#') { id = part.substring(1, part.length); } } return { tagName: tagName, id: id, className: classes.join(' ') }; } /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var VNode = __webpack_require__(15); var is = __webpack_require__(10); function addNS(data, children) { data.ns = 'http://www.w3.org/2000/svg'; if (children !== undefined) { for (var i = 0; i < children.length; ++i) { addNS(children[i].data, children[i].children); } } } module.exports = function h(sel, b, c) { var data = {}, children, text, i; if (arguments.length === 3) { data = b; if (is.array(c)) { children = c; } else if (is.primitive(c)) { text = c; } } else if (arguments.length === 2) { if (is.array(b)) { children = b; } else if (is.primitive(b)) { text = b; } else { data = b; } } if (is.array(children)) { for (i = 0; i < children.length; ++i) { if (is.primitive(children[i])) children[i] = VNode(undefined, undefined, undefined, children[i]); } } if (sel[0] === 's' && sel[1] === 'v' && sel[2] === 'g') { addNS(data, children); } return VNode(sel, data, children, text, undefined); }; /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.run = undefined; var _mostSubject = __webpack_require__(51); function makeSinkProxies(drivers) { var sinkProxies = {}; var keys = Object.keys(drivers); for (var i = 0; i < keys.length; i++) { sinkProxies[keys[i]] = (0, _mostSubject.holdSubject)(1); } return sinkProxies; } function callDrivers(drivers, sinkProxies) { var sources = {}; var keys = Object.keys(drivers); for (var i = 0; i < keys.length; i++) { var name = keys[i]; sources[name] = drivers[name](sinkProxies[name].stream, name); } return sources; } function makeHandleError(observer, onError) { return function handleError(err) { observer.error(err); onError(err); }; } function replicateMany(_ref) { var sinks = _ref.sinks; var sinkProxies = _ref.sinkProxies; var disposableStream = _ref.disposableStream; var onError = _ref.onError; var sinkKeys = Object.keys(sinks); for (var i = 0; i < sinkKeys.length; i++) { var name = sinkKeys[i]; if (sinkProxies.hasOwnProperty(name)) { var observer = sinkProxies[name].observer; sinks[name].until(disposableStream).observe(observer.next).then(observer.complete).catch(makeHandleError(observer, onError)); } } } function assertSinks(sinks) { var keys = Object.keys(sinks); for (var i = 0; i < keys.length; i++) { if (!sinks[keys[i]] || typeof sinks[keys[i]].observe !== 'function') { throw new Error('Sink \'' + keys[i] + '\' must be a most.Stream'); } } return sinks; } var logErrorToConsole = typeof console !== 'undefined' && console.error ? function (error) { console.error(error.stack || error); } : Function.prototype; var defaults = { onError: logErrorToConsole }; function runInputGuard(_ref2) { var main = _ref2.main; var drivers = _ref2.drivers; var onError = _ref2.onError; if (typeof main !== 'function') { throw new Error('First argument given to run() must be the ' + '\'main\' function.'); } if ((typeof drivers === 'undefined' ? 'undefined' : _typeof(drivers)) !== 'object' || drivers === null) { throw new Error('Second argument given to run() must be an ' + 'object with driver functions as properties.'); } if (!Object.keys(drivers).length) { throw new Error('Second argument given to run() must be an ' + 'object with at least one driver function declared as a property.'); } if (typeof onError !== 'function') { throw new Error('onError must be a function'); } } function run(main, drivers) { var _ref3 = arguments.length <= 2 || arguments[2] === undefined ? defaults : arguments[2]; var _ref3$onError = _ref3.onError; var onError = _ref3$onError === undefined ? logErrorToConsole : _ref3$onError; runInputGuard({ main: main, drivers: drivers, onError: onError }); var _subject = (0, _mostSubject.subject)(); var disposableObserver = _subject.observer; var disposableStream = _subject.stream; var sinkProxies = makeSinkProxies(drivers); var sources = callDrivers(drivers, sinkProxies); var sinks = assertSinks(main(sources)); replicateMany({ sinks: sinks, sinkProxies: sinkProxies, disposableStream: disposableStream, onError: onError }); function dispose() { disposableObserver.next(1); disposableObserver.complete(); } return { sinks: sinks, sources: sources, dispose: dispose }; } exports.default = { run: run }; exports.run = run; /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _dom = __webpack_require__(16); /* import {subject} from 'most-subject' var sub = subject var observer = sub.observer; var stream = sub.stream; */ var Monad = function Monad(value, ID) { var _this = this; this.x = value; if (arguments.length === 1) this.id = 'anonymous';else this.id = ID; this.bnd = function (func) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } return func.apply(undefined, [_this.x].concat(args)); }; this.ret = function (a) { window[_this.id] = new Monad(a, _this.id); return window[_this.id]; }; }; var mMname = new Monad('Fred', 'mMname'); var monad = (0, _dom.h)('pre', { style: { color: '#AFEEEE' } }, ' var Monad = function Monad(z, g) {\n var _this = this;\n\n this.x = z;\n if (arguments.length === 1) {\n this.id = \'anonymous\';\n } else {\n this.id = g;\n };\n\n this.bnd = function (func, ...args) {\n return func(_this.x, ...args);\n };\n\n this.ret = function (a) {\n O.[_this.id] = new Monad(a, _this.id);\n return O.[_this.id]\n };\n }; '); var monadIt = (0, _dom.h)('pre', { style: { color: '#AFEEEE' } }, ' var MonadItter = function MonadItter() {\n var _this = this;\n this.p = function () {};\n \n this.release = function (...args) {\n return this.p(...args);\n };\n \n this.bnd = function (func) {\n _this.p = func;\n };\n }; '); var ret = (0, _dom.h)('pre', { style: { color: '#AFEEEE' } }, ' var ret = function ret(v, id) {\n if (arguments.length === 1) {\n return (new Monad(v, \'anonymous\'));\n }\n window[id] = new Monad(v, id);\n return window[id];\n }; '); var fib = (0, _dom.h)('pre', ' mM$fib.stream.addListener({\n next: v => {\n if (v[2] > 1) {mM$fib.ret([v[1], v[0] + v[1], v[2] -1])}\n else {\n mM19.ret(v[1]);\n }\n },\n error: err => console.error(err),\n complete: () => console.log(\'completed\')\n });\n\n const fibPress$ = sources.DOM\n .select(\'input#code\').events(\'keydown\');\n\n const fibPressAction$ = fibPress$.map(e => {\n if (e.target.value == \'\') {return};\n if( e.keyCode == 13 && Number.isInteger(e.target.value*1) ) {\n mM21.ret(e.target.value);\n mM$fib.ret([0, 1, e.target.value]);\n }\n if( e.keyCode == 13 && !Number.isInteger(e.target.value*1 )) {\n mM19.ret("You didn\'t provide an integer");\n }\n }); '); var driver = (0, _dom.h)('pre', ' var websocketsDriver = function () {\n return create((add) => {\n socket.onmessage = msg => add(msg)\n })\n };\n'); var messages = (0, _dom.h)('pre', ' const messages$ = (sources.WS).map(e => \n mMtem.ret(e.data.split(\',\')).bnd(v => {\n mMZ10.bnd(() => game([v[3], v[4], v[5], v[6]]))\n mMZ11.bnd(() => updateScoreboard(v[3]));\n mMZ12.bnd(() => mM6\n .ret(v[2] + \' successfully logged in.\'))\n mMZ13.bnd(() => updateMessages(v))\n mMZ14.bnd(() => mMgoals2.ret(\'The winner is \' + v[2] ))\n mMZ15.bnd(() => mMgoals2.ret(\'A player named \' + \n O.mMname.x + \'is currently logged in. Page will refresh in 4 seconds.\')\n .bnd(refresh))\n mMZ16.bnd(() => {if (O.mMname.x != v[2]) {mMgoals2.ret(v[2] + v[3])}})\n mMZ17.bnd(() => {\n if (v[3] == \'no file\') {\n mMtaskList.ret([])\n } \n else {\n process(e.data)\n }\n })\n mMtemp.ret(e.data.split(\',\')[0])\n .bnd(next, \'CA#$42\', mMZ10)\n .bnd(next, \'CB#$42\', mMZ11)\n .bnd(next, \'CC#$42\', mMZ12)\n .bnd(next, \'CD#$42\', mMZ13)\n .bnd(next, \'CE#$42\', mMZ14)\n .bnd(next, \'EE#$42\', mMZ15)\n .bnd(next, \'DE#$42\', mMZ16)\n .bnd(next, \'DD#$42\', mMZ17)\n }) \n });\n \n var next = function next(x, y, mon2) {\n if (x === y) {\n mon2.release();\n }\n return ret(x);\n }'); var Monad$ = (0, _dom.h)('pre', ' var Monad$ = function Monad$(z, g) {\n var _this = this;\n this.subject = subject();\n this.observer = this.subject.observer;\n this.stream = this.subject.stream;\n this.x = z;\n this.id = g;\n\n this.bnd = function (func, ...args) {\n return func(_this.x, ...args);\n };\n\n this.ret = function (a) {\n O[_this.id] = new Monad$(a,_this.id);\n _this.observer.next(a);\n return O[_this.id];\n };\n };\n '); var nums = (0, _dom.h)('pre', ' \n const numClick$ = sources.DOM\n .select(\'.num\').events(\'click\');\n \n const numClickAction$ = numClick$.map(e => {\n console.log(e);\n if (O.mM3.x.length < 2) {\n O.mM3.bnd(push, e.target.innerHTML, O.mM3)\n mM28.ret(O.mMhistorymM1.x[O.mMindex2.x])\n .bnd(spliceRemove, e.target.id, mMtemp)\n .bnd(v => game(v));\n if (O.mM3.x.length === 2 && O.mM8.x !== 0) {\n updateCalc();\n }\n };\n }).startWith([0,0,0,0]);\n\n const opClick$ = sources.DOM\n .select(\'.op\').events(\'click\');\n \n const opClickAction$ = opClick$.map(e => {\n mM8.ret(e.target.textContent);\n if (O.mM3.x.length === 2) {\n updateCalc();\n }\n })\n\n var game = function game (v) {\n mM1.ret(v);\n O.mMindex.bnd(add, 1, mMindex)\n .bnd(i => O.mMhistorymM1.bnd(spliceAdd, i, O.mM1, O.mMhistorymM1))\n document.getElementById(\'0\').innerHTML = O.mM1.x[0]; \n document.getElementById(\'1\').innerHTML = O.mM1.x[1]; \n document.getElementById(\'2\').innerHTML = O.mM1.x[2]; \n document.getElementById(\'3\').innerHTML = O.mM1.x[3]; \n cleanup()\n };\n }); '); var arrayFuncs = (0, _dom.h)('pre', ' var push = function push(y,v,mon) {\n if (Array.isArray(y)) {\n let ar = [];\n let keys = Object.keys(y);\n for (let k in keys) {ar[k] = y[k]};\n ar.push(v);\n return mon.ret(ar); \n }\n console.log(\'The value provided to push is not an array\');\n return ret(y);\n };\n \n var spliceRemove = function splice(x, j, mon) {\n if (Array.isArray(x)) {\n let ar = [];\n let keys = Object.keys(x);\n for (let k in keys) {ar[k] = x[k]};\n ar.splice(j,1);\n return mon.ret(ar); \n }\n console.log(\'The value provided to spliceRemove is not an array\');\n return ret(x);\n };\n \n var spliceAdd = function splice(x, index, value, mon) {\n if (Array.isArray(x)) {\n let ar = [];\n let keys = Object.keys(x);\n for (let k in keys) {ar[k] = x[k]};\n ar.splice(index, 0, value);\n return mon.ret(ar); \n }\n console.log(\'The value provided to spliceAdd is not an array\');\n return ret(x);\n };\n \n var splice = function splice(x, start, end, mon) {\n if (Array.isArray(x)) {\n let ar = [];\n let keys = Object.keys(x);\n for (let k in keys) {ar[k] = x[k]};\n ar.splice(start, end);\n return mon.ret(ar); \n }\n console.log(\'The value provided to spliceAdd is not an array\');\n return ret(x);\n };\n '); var cleanup = (0, _dom.h)('pre', ' function cleanup (x) {\n let target0 = document.getElementById(\'0\');\n let target1 = document.getElementById(\'1\');\n let target2 = document.getElementById(\'2\');\n let target3 = document.getElementById(\'3\');\n let targetAr = [target0, target1, target2, target3];\n for (let i in [0,1,2,3]) {\n if (targetAr[i].innerHTML == \'undefined\' ) {\n targetAr[i].style.display = \'none\';\n }\n else {\n targetAr[i].style.display = \'inline\';\n }\n }\n return ret(x);\n }; '); var travel = (0, _dom.h)('pre', ' const forwardClick$ = sources.DOM\n .select(\'#forward2\').events(\'click\');\n \n const backClick$ = sources.DOM\n .select(\'#back2\').events(\'click\');\n \n const forwardClickAction$ = forwardClick$.map(() => {\n if (O.mMindex2.x < (O.mMhistorymM1.x.length - 1)) {\n inc(O.mMindex2.x, mMindex2)\n .bnd(() => mM$3.ret(\'Hello\'))\n }\n });\n \n const backClickAction$ = backClick$.map(() => {\n if (O.mMindex2.x > 0) {\n dec(O.mMindex2.x, mMindex2)\n .bnd(() => mM$3.ret(\'You bet!\'))\n }\n });\n\n const mM$3Action$ = mM$3.stream.map(v => {\n document.getElementById(\'0\').innerHTML = (O.mMhistorymM1.x[O.mMindex2.x])[0]; \n document.getElementById(\'1\').innerHTML = (O.mMhistorymM1.x[O.mMindex2.x])[1]; \n document.getElementById(\'2\').innerHTML = (O.mMhistorymM1.x[O.mMindex2.x])[2]; \n document.getElementById(\'3\').innerHTML = (O.mMhistorymM1.x[O.mMindex2.x])[3]; \n cleanup();\n }) '); var C42 = (0, _dom.h)('pre', ' mMZ10.bnd(() => mM$1\n .ret([O.mMar.x[3], O.mMar.x[4], O.mMar.x[5], O.mMar.x[6]])\n .bnd(() => mM$2.ret([]))\n .bnd(displayInline,\'0\')\n .bnd(displayInline,\'1\')\n .bnd(displayInline,\'2\')\n .bnd(displayInline,\'3\')); '); var taskStream = (0, _dom.h)('pre', ' \n }); '); var deleteTask2 = (0, _dom.h)('pre', ' mMZ19.bnd(() => O.mM$task.bnd(spliceRemove, O.mMar.x[3], mM$task));\n '); var newTask = (0, _dom.h)('pre', ' const newTask$ = sources.DOM\n .select(\'input.newTask\').events(\'keydown\'); \n\n const newTaskAction$ = newTask$.map(e => {\n let ob = {};\n var alert = \'\';\n var ar = e.target.value.split(\',\');\n var ar2 = ar.slice(2);\n var task = \'\';\n if (ar.length < 4) {\n task = ar[2];\n }\n if (ar.length > 3) {\n task = ar2.reduce((a,b) => a + \'$*$*$\' + b);\n }\n if( e.keyCode == 13 ) {\n if ( ar.length < 3 ) {\n alert = \'You should enter "author, responsible party, task" separated by commas\';\n document.getElementById(\'alert\').innerHTML = alert;\n }\n\n else if ( (O.mMar2.x.filter(v => (v.task == task)).length) > 0 ) {\n document.getElementById(\'alert\').innerHTML = task + " is already listed.";\n }\n\n else if ( ar.length > 2 ) {\n O.mM$taskList.bnd(addString, task + \',yellow, none, false,\' + ar[0] + \',\' + ar[1], mM$taskList);\n e.target.value = \'\';\n document.getElementById(\'alert\').innerHTML = \'\';\n } \n } \n }; '); var process = (0, _dom.h)('pre', ' const process = function(str) {\n let a = str.split(",");\n console.log(\'In process. str and a are: \', str, a);\n if (a == undefined) {\n return;\n };\n if (a.length < 9) {\n return\n };\n let ob = {};\n let ar = a.slice(3)\n let s = ar.reduce((a,b) => a + \',\' + b);\n if (mM$taskList.x.length < 5) {\n O.mM$taskList.ret(s);\n }\n let ar2 = [];\n let tempArray = [];\n if (ar.length < 6) {return};\n if ((ar.length % 6) !== 0) {\n document.getElementById(\'alert\').innerHTML = \'Error: array length is: \' + length;\n } else {\n let keys = Array(ar.length/6).fill(1);\n keys.map(_ => {\n ar2.push(\n {\n task: convertBack(ar.shift()),\n color: ar.shift(),\n textDecoration: ar.shift(),\n checked: ar.shift() === \'true\',\n author: ar.shift(),\n responsible: ar.shift()\n }\n )\n })\n console.log(\'In process ar2 is: \', ar2)\n let keys2 = Object.keys(ar2);\n for (let k in keys) {\n tempArray.push(\n h(\'div.todo\', [\n h(\'span.task3\', {style: {color: ar2[k].color, textDecoration: ar2[k].textDecoration}},\n \'Task: \' + ar2[k].task ), \n h(\'br\'),\n h(\'button#edit1\', \'Edit\' ),\n h(\'input#edit2\', {props: {type: \'textarea\', value: ar2[k].task}, style: {display: \'none\'}} ), \n h(\'span#author.tao\', \'Author: \' + ar2[k].author + \' / \' + \'Responsibility: \' + ar2[k].responsible),\n h(\'br\'),\n h(\'input#cb\', {props: {type: \'checkbox\', checked: ar2[k].checked}, style: {color: ar2[k].color,\n textDecoration: ar2[k].textDecoration} } ), \n h(\'label.cbox\', { props: {for: \'#cb\'}}, \'Completed\' ),\n h(\'button.delete\', \'Delete\' ), \n h(\'br\'),\n h(\'hr\')])\n )\n }\n mMtaskList.ret(tempArray)\n }\n }; '); var colorClick = (0, _dom.h)('pre', ' const colorClick$ = sources.DOM\n .select(\'#cb\').events(\'click\')\n \n const colorAction$ = colorClick$.map(e => {\n let index = getIndex(e);\n let s = O.mM$taskList.x;\n let ar = s.split(\',\');\n let n = 6 * index + 3;\n let j = 6 * index + 2;\n let k = 6 * index + 1;\n let checked = ar[n];\n if (checked == \'true\') {\n ar[n] = \'false\'; \n ar[k] = \'yellow\'; \n ar[j] = \'none\'; \n }\n else {\n ar[n] = \'true\'; \n ar[k] = \'lightGreen\'; \n ar[j] = \'line-through\'; \n }\n mM$taskList.ret( ar.reduce((a,b) => a + \',\' + b) )\n }); \n \n var getIndex = function getIndex (event_object) {\n var task = event_object.currentTarget.parentNode.innerText;\n var possibilities = event_object.currentTarget.parentNode.parentNode.childNodes;\n var keys = Object.keys(possibilities);\n for (let k in keys) {\n if (task == possibilities[k].innerText) {\n return k\n }\n }\n console.log(\'In getIndex. No match\');\n } '); var edit = (0, _dom.h)('pre', ' const edit1$ = sources.DOM\n .select(\'#edit1\').events(\'click\')\n \n const edit1Action$ = edit1$.map(e => {\n let index = getIndex2(e);\n O.mMtaskList.x[index].children[3].elm.style.display = \'block\';\n });\n\n const edit2$ = sources.DOM\n .select(\'#edit2\').events(\'keypress\')\n \n const edit2Action$ = edit2$.map(e => {\n let v = e.target.value;\n let index = getIndex2(e);\n if( e.keyCode == 13 ) {\n process2(v, index);\n O.mMtaskList.x[index].children[3].elm.style.display = \'none\';\n }\n });\n\n const process2 = function(str, index) {\n let a = O.mM$taskList.x;\n let ar = a.split(\',\');\n let task = str.split(\',\').reduce((a,b) => ar + \'$*$*$\' + b)\n ar[index * 6] = task;\n let s = ar.reduce((a,b) => a + \',\' + b);\n mM$taskList.ret(s);\n };\n\n var getIndex2 = function getIndex2 (e) {\n var elem = e.currentTarget.parentNode.children[0].innerHTML\n var elem2 = e.currentTarget.parentNode.parentNode.childNodes\n var keys = Object.keys(elem2);\n for (let k in keys) {\n if (elem == elem2[k].childNodes[0].innerHTML) {\n return k\n }\n console.log(\'In getIndex2. No match\');\n }\n } '); var mM$task = (0, _dom.h)('pre', ' const taskAction$ = mM$taskList.stream.map(str => {\n socket.send(\'TD#$42\' + \',\' + O.mMgroup.x.trim() + \n \',\' + O.mMname.x.trim() + \',\' + \'@\' + str);\n }); '); var updateCalc = (0, _dom.h)('pre', ' function updateCalc() { \n O.mM3.bnd(ar => mM7 // O.mM3 contributes O.mM3.x to the computation.\n .ret(calc(ar[0], O.mM8.x, ar[1])) // O.mM8.x is the operator string.\n .bnd(result => // The return value of calc(), which is O.mM7.x, is used three times.\n { O.mM1.bnd(push, result, mM1).bnd(z =>\n mM$1.ret(z)); // Updates the display. \n if (result == 20) {score(O.mM13.x, 1)}; \n if (result == 18) {score(O.mM13.x, 3)};\n }\n )) \n reset()\n };\n\n var score = function score(x,j) {\n if ((x + j) == 20) {\n mMgoals.ret(O.mMgoals.x == 2 ? 0 : (O.mMgoals.x + 1)); \n mM13.ret(0).bnd(mMindex.ret);\n mMhistorymM1.ret([[0,0,0,0]]);\n socket.send(\'CG#$42,\' + O.mMgroup.x + \',\' + O.mMname.x + \',\' + -x + \',\' + O.mMgoals.x); \n if (O.mMgoals.x == 0) {\n socket.send(\'CE#$42,\' + O.mMgroup.x + \',\' + O.mMname.x + \',nothing \');\n }\n socket.send(\'CA#$42,\' + O.mMgroup.x.trim() + \',\' + O.mMname.x.trim() + \',6,6,12,20\');\n return;\n }\n if ((x + j) % 5 == 0) {\n socket.send(\'CG#$42,\' + O.mMgroup.x + \',\' + O.mMname.x + \',\'+ (j+5)+\',\' + O.mMgoals.x); \n mM13.ret(x + j + 5);\n socket.send(\'CA#$42,\' + O.mMgroup.x.trim() + \',\' + O.mMname.x.trim() + \',6,6,12,20\');\n return;\n } \n socket.send(\'CG#$42,\' + O.mMgroup.x + \',\' + O.mMname.x + \',\'+j+\',\' + O.mMgoals.x); \n mM13.ret(x + j);\n socket.send(\'CA#$42,\' + O.mMgroup.x.trim() + \',\' + O.mMname.x.trim() + \',6,6,12,20\');\n }\n\n var reset = function reset () {\n mM3.ret([])\n .bnd(() => mM4.ret(0)\n .bnd(mM8.ret)\n .bnd(cleanup)) // Hides \'undefined\' values in the display.\n }\n\n var updateScoreboard = function updateScoreboard(v) { // v is received from the server.\n let ar2 = v.split("<br>");\n let ar = ar.slice();\n return mMscoreboard.ret(ar);\n }; '); var testZ = (0, _dom.h)('pre', ' mMZ1.bnd(v => O.mMt1.bnd(add,v,mMt1)\n .bnd(cube,mMt2)\n .bnd(() => mMt3.ret(O.mMt1.x + \' cubed is \' + O.mMt2.x))) \n \n mMZ2.bnd(v => cube(v).bnd(w => mMt3.ret(v + \' cubed is \' + w))) '); var quad = (0, _dom.h)('pre', ' const quad$ = sources.DOM\n .select(\'#quad\').events(\'keypress\') // Motorcycle way to get user input.\n \n const quadAction$ = quad$.map((e) => {\n if( e.keyCode == 13 ) {\n mMZ3.release(e.target.value) // Releases mMZ (below).\n document.getElementById(\'quad\').value = \'\';\n }\n });\n\n var solve = function solve () {\n mMZ3.bnd(a => \n mMtemp.ret(a) \n .bnd(innerHTML, \'\', \'quad6\', mMtemp) \n .bnd(innerHTML, a + " * x * x ", \'quad5\', mMtemp)\n .bnd(a =>\n mMZ3.bnd(b => mMtemp.ret(b)\n .bnd(innerHTML, " + " + b + " * x ", \'quad6\', mMtemp).bnd(b =>\n mMZ3.bnd(c => {\n let x = qS1(a,b,c);\n let y = qS2(a,b,c); \n document.getElementById(\'quad5\').innerHTML = \n \'The results are: x = \' + x + \' and x =\';\n document.getElementById(\'quad6\').innerHTML = y; \n solve();\n })))))\n }();\n\n var qS1 = function qS1 (a, b, c) {\n let n = (b*(-1)) + (Math.sqrt(b*b - 4*a*c));\n if (n != n) {\n return "No solution";\n }\n return n/(2*a);\n }\n\n var qS2 = function qS2 (a, b, c) {\n let n = (b*(-1)) - (Math.sqrt(b*b - 4*a*c));\n if (n != n) {\n return "No solution";\n }\n return n/(2*a);\n \n var innerHTML = function innerHTML (x, v, u, m) { \n document.getElementById(u).innerHTML = v;\n return m.ret(x);\n } '); var mdem1 = (0, _dom.h)('pre', ' var equals = function equals (x, mon1, mon2, mon3) {\n if (mon1.id === mon2.id && mon1.x === mon2.x) {\n mon3.ret(\'true\');\n } else mon3.ret(\'false\');\n return ret(x);\n }\n \n var add = function(x,b,mon) {\n if (arguments.length === 3) {\n return mon.ret(x + b);\n }\n return ret(x+b);\n }\n\n var cube = function(v,mon) {\n if (arguments.length === 2) {\n return mon.ret(v*v*v);\n }\n return ret(v*v*v);\n } '); var runTest = (0, _dom.h)('pre', ' var runTest = function monTest () {\n mM5.bnd( equals, \n m.ret(0).bnd(v => add(v, 3, m).bnd(cube)), \n m.ret(0).bnd(add, 3, m).bnd(cube), mMa)\n\n mM5.bnd(equals, m, m.bnd(m.ret), mMb)\n\n mM5.bnd(equals, m, m.ret(m.x), mMc)\n } '); var inc = (0, _dom.h)('pre', ' var inc = function inc(x, mon) {\n return mon.ret(x + 1);\n };\n\n var spliceAdd = function spliceAdd(x, index, value, mon) {\n if (Array.isArray(x)) {\n let ar = [];\n let keys = Object.keys(x);\n for (let k in keys) {ar[k] = x[k]};\n ar.splice(index, 0, value);\n return mon.ret(ar); \n }\n console.log(\'The value provided to spliceAdd is not an array\');\n return ret(x);\n } '); var todoStream = (0, _dom.h)('pre', ' const taskAction$ = mM$taskList.stream.map(str => {\n socket.send(\'TD#$42\' + \',\' + O.mMgroup.x.trim() + \n \',\' + O.mMname.x.trim() + \',\' + \'@\' + str);\n }); '); var p3 = (0, _dom.h)('pre', ' \n '); var p4 = (0, _dom.h)('pre', ' \n '); var p5 = (0, _dom.h)('pre', ' \n '); var add = (0, _dom.h)('pre', ' var add = function(x,b,mon) {\n if (arguments.length === 3) {\n return mon.ret(x + b);\n }\n return ret(x+b); \n }; '); var ret_add_cube = (0, _dom.h)('pre', ' var ret = function ret(v, id) {\n if (arguments.length === 1) {\n return (new Monad(v, \'anonymous\'));\n }\n window[id] = new Monad(v, id);\n return window[id];\n } \n\n var add = function(x,b,mon) {\n if (arguments.length === 3) {\n return mon.ret(x + b);\n }\n return ret(x+b);\n };\n\n var cube = function(v,mon) {\n if (arguments.length === 2) {\n return mon.ret(v*v*v);\n }\n return ret(v*v*v);\n} '); var seed = (0, _dom.h)('pre', ' mM$prime.ret([[2],3]) '); var traverse = (0, _dom.h)('pre', ' \n const forwardClick$ = sources.DOM\n .select(\'#forward\').events(\'click\');\n\n const backClick$ = sources.DOM\n .select(\'#back\').events(\'click\');\n\n const forwardAction$ = forwardClick$.map(() => {\n if (O.mMindex.x < (O.mMhistorymM1.x.length - 1)) {\n O.mMindex.bnd(add, 1, mMindex)\n .bnd(mM$3.ret)\n }\n });\n\n const backAction$ = backClick$.map(() => {\n if (O.mMindex.x > 0) {\n O.mMindex.bnd(add, -1, mMindex)\n .bnd(mM$3.ret)\n socket.send(\'DE#$42,\' + O.mMgroup.x.trim() + \',\' + O.mMname.x.trim() + \', clicked the BACK button. \');\n }\n });\n\n var game = function game (v) {\n mM1.ret(v);\n O.mMindex.bnd(add, 1, mMindex)\n .bnd(i => O.mMhistorymM1.bnd(spliceAdd, i, O.mM1, O.mMhistorymM1))\n document.getElementById(\'0\').innerHTML = O.mM1.x[0]; \n document.getElementById(\'1\').innerHTML = O.mM1.x[1]; \n document.getElementById(\'2\').innerHTML = O.mM1.x[2]; \n document.getElementById(\'3\').innerHTML = O.mM1.x[3]; \n cleanup()\n };\n\n var trav = function trav (v) {\n document.getElementById(\'0\').innerHTML = (O.mMhistorymM1.x[v].x)[0]; \n document.getElementById(\'1\').innerHTML = (O.mMhistorymM1.x[v].x)[1]; \n document.getElementById(\'2\').innerHTML = (O.mMhistorymM1.x[v].x)[2]; \n document.getElementById(\'3\').innerHTML = (O.mMhistorymM1.x[v].x)[3]; \n cleanup();\n } '); var MonadState = (0, _dom.h)('pre', ' var MonadState = function MonadState (g, state, value, p) {\n var _this = this;\n this.id = g;\n this.s = state;\n this.a = value;\n this.process = p;\n this.bnd = function (func, ...args) {\n return func(_this.s, ...args); // bnd provides instances\' state to func.\n };\n this.run = function(st) { \n let s = _this.process(st); \n let a = s[3];\n window[_this.id] = new MonadState(_this.id, s, a, _this.process);\n return window[_this.id];\n }\n } '); var primesMonad = (0, _dom.h)('pre', ' var primesMonad = new MonadState(\'primesMonad\', [2, \'\', 3, [2]], [2], primes_state) \n\n var primes_state = function primes_state(x) {\n var v = x.slice();\n while (2 == 2) {\n if (v[3].every(e => ((v[0]/e) != Math.floor(v[0]/e)))) {\n v[3].push(v[0]);\n }\n if (v[3][v[3].length - 1] > v[2]) { break }; // Not an infinite loop afterall\n v[0]+=2;\n }\n return v;\n } '); var fibsMonad = (0, _dom.h)('pre', ' var fibsMonad = new MonadState(\'fibsMonad\', [0, 1, 3, [0,1]], [0,1], fibs_state ) \n\n var fibs_state = function fibs_state(ar) {\n var a = ar.slice();\n while (a[3].length < a[2]) {\n a = [a[1], a[0] + a[1], a[2], a[3].concat(a[0])];\n }\n return a\n } '); var tr3 = (0, _dom.h)('pre', ' var tr3 = function tr (fibsArray, primesArray) {\n var ar = [];\n var primes = primesArray.slice();\n var fibs = fibsArray.slice();\n var fib = fibsArray.slice(3);\n var bound = Math.round(Math.sqrt(fibs[fibs.length - 1]));\n if (bound < primesArray[primesArray.length - 1]) {\n primes = primes.filter(v => v <= bound);\n }\n fib.map (f => {\n if ( f < 2 ) return;\n if ( primes.every(p => (f % p != 0 || f == p))) ar.push(f);\n })\n return [fibs, primes, ar]\n } '); var primeFibInterface = (0, _dom.h)('pre', ' const fibKeyPress5$ = sources.DOM\n .select(\'input#fib92\').events(\'keydown\');\n\n const primeFib$ = fibKeyPress5$.map(e => {\n if( e.keyCode == 13 ) {\n var bound;\n fibsMonad.run([0, 1, e.target.value, []])\n .bnd(s => bound = Math.round(Math.sqrt(s[0])));\n if (bound > primesMonad.a[primesMonad.a.length - 1] ) {\n primesMonad.run([primesMonad.s[0], "from the fibKeyPress5$ handler", bound, primesMonad.a])\n }\n var res = fibsMonad\n .bnd(fibsState => fibsMonad // Gets the current state of fibsMonad\n .bnd(fpTransformer, primesMonad) // Returnes the (possibly modified) state of primesMonad\n .bnd(primesState => tr3(fibsState[3],primesState[3]))) // Runs tr3 on fibsMonad.s and the new primesMonad\n document.getElementById(\'PF_9\').innerHTML = res[0]; // res is the return value of tr3 (above)\n document.getElementById(\'PF_22\').innerHTML = res[1];\n document.getElementById(\'primeFibs\').innerHTML = res[2];\n }\n }); '); var fpTransformer = (0, _dom.h)('pre', ' var fpTransformer = function fpTransformer (s, m) {\n let bound = Math.round(Math.sqrt(s[1]));\n if (bound <= m.a[m.a.length - 1]) {\n return m;\n }\n return m.run([m.s[0], "From fpTransformer", bound, m.a])\n } '); var innerHTML = (0, _dom.h)('pre', ' var innerHTML = function innerHTML (x, v, u, m) { \n document.getElementById(u).innerHTML = v;\n return m.ret(x);\n } '); var seed2 = (0, _dom.h)('pre', ' \n '); exports.default = { monad: monad, monadIt: monadIt, fib: fib, driver: driver, messages: messages, next: next, Monad$: Monad$, updateCalc: updateCalc, arrayFuncs: arrayFuncs, travel: travel, nums: nums, cleanup: cleanup, ret: ret, C42: C42, taskStream: taskStream, newTask: newTask, process: process, mM$task: mM$task, addString: addString, colorClick: colorClick, edit: edit, testZ: testZ, quad: quad, mdem1: mdem1, runTest: runTest, todoStream: todoStream, inc: inc, ret_add_cube: ret_add_cube, seed: seed, add: add, traverse: traverse, MonadState: MonadState, primesMonad: primesMonad, fibsMonad: fibsMonad, primeFibInterface: primeFibInterface, tr3: tr3, fpTransformer: fpTransformer, innerHTML: innerHTML }; /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;'use strict'; (function (global, factory) { if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [exports, __webpack_require__(4)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (typeof exports !== "undefined") { factory(exports, require('most')); } else { var mod = { exports: {} }; factory(mod.exports, global.most); global.mostDomEvent = mod.exports; } })(undefined, function (exports, _most) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.touchcancel = exports.touchmove = exports.touchend = exports.touchstart = exports.pointerleave = exports.pointerout = exports.pointerenter = exports.pointerover = exports.pointermove = exports.pointerup = exports.pointerdown = exports.unload = exports.load = exports.popstate = exports.hashchange = exports.error = exports.scroll = exports.resize = exports.contextmenu = exports.input = exports.keyup = exports.keypress = exports.keydown = exports.submit = exports.select = exports.change = exports.mouseleave = exports.mouseout = exports.mouseenter = exports.mouseover = exports.mousemove = exports.mouseup = exports.mousedown = exports.dblclick = exports.click = exports.focusout = exports.focusin = exports.focus = exports.blur = exports.domEvent = undefined; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var domEvent = function domEvent(event, node) { var capture = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2]; return new _most.Stream(new DomEvent(event, node, capture)); }; var blur = function blur(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('blur', node, capture); }; var focus = function focus(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('focus', node, capture); }; var focusin = function focusin(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('focusin', node, capture); }; var focusout = function focusout(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('focusout', node, capture); }; var click = function click(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('click', node, capture); }; var dblclick = function dblclick(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('dblclick', node, capture); }; var mousedown = function mousedown(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('mousedown', node, capture); }; var mouseup = function mouseup(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('mouseup', node, capture); }; var mousemove = function mousemove(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('mousemove', node, capture); }; var mouseover = function mouseover(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('mouseover', node, capture); }; var mouseenter = function mouseenter(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('mouseenter', node, capture); }; var mouseout = function mouseout(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('mouseout', node, capture); }; var mouseleave = function mouseleave(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('mouseleave', node, capture); }; var change = function change(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('change', node, capture); }; var select = function select(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('select', node, capture); }; var submit = function submit(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('submit', node, capture); }; var keydown = function keydown(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('keydown', node, capture); }; var keypress = function keypress(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('keypress', node, capture); }; var keyup = function keyup(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('keyup', node, capture); }; var input = function input(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('input', node, capture); }; var contextmenu = function contextmenu(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('contextmenu', node, capture); }; var resize = function resize(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('resize', node, capture); }; var scroll = function scroll(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('scroll', node, capture); }; var error = function error(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('error', node, capture); }; var hashchange = function hashchange(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('hashchange', node, capture); }; var popstate = function popstate(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('popstate', node, capture); }; var load = function load(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('load', node, capture); }; var unload = function unload(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('unload', node, capture); }; var pointerdown = function pointerdown(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('pointerdown', node, capture); }; var pointerup = function pointerup(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('pointerup', node, capture); }; var pointermove = function pointermove(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('pointermove', node, capture); }; var pointerover = function pointerover(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('pointerover', node, capture); }; var pointerenter = function pointerenter(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('pointerenter', node, capture); }; var pointerout = function pointerout(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('pointerout', node, capture); }; var pointerleave = function pointerleave(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('pointerleave', node, capture); }; var touchstart = function touchstart(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('touchstart', node, capture); }; var touchend = function touchend(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('touchend', node, capture); }; var touchmove = function touchmove(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('touchmove', node, capture); }; var touchcancel = function touchcancel(node) { var capture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return domEvent('touchcancel', node, capture); }; var DomEvent = function () { function DomEvent(event, node, capture) { _classCallCheck(this, DomEvent); this.event = event; this.node = node; this.capture = capture; } _createClass(DomEvent, [{ key: 'run', value: function run(sink, scheduler) { var _this = this; var send = function send(e) { return tryEvent(scheduler.now(), e, sink); }; var dispose = function dispose() { return _this.node.removeEventListener(_this.event, send, _this.capture); }; this.node.addEventListener(this.event, send, this.capture); return { dispose: dispose }; } }]); return DomEvent; }(); function tryEvent(t, x, sink) { try { sink.event(t, x); } catch (e) { sink.error(t, e); } } exports.domEvent = domEvent; exports.blur = blur; exports.focus = focus; exports.focusin = focusin; exports.focusout = focusout; exports.click = click; exports.dblclick = dblclick; exports.mousedown = mousedown; exports.mouseup = mouseup; exports.mousemove = mousemove; exports.mouseover = mouseover; exports.mouseenter = mouseenter; exports.mouseout = mouseout; exports.mouseleave = mouseleave; exports.change = change; exports.select = select; exports.submit = submit; exports.keydown = keydown; exports.keypress = keypress; exports.keyup = keyup; exports.input = input; exports.contextmenu = contextmenu; exports.resize = resize; exports.scroll = scroll; exports.error = error; exports.hashchange = hashchange; exports.popstate = popstate; exports.load = load; exports.unload = unload; exports.pointerdown = pointerdown; exports.pointerup = pointerup; exports.pointermove = pointermove; exports.pointerover = pointerover; exports.pointerenter = pointerenter; exports.pointerout = pointerout; exports.pointerleave = pointerleave; exports.touchstart = touchstart; exports.touchend = touchend; exports.touchmove = touchmove; exports.touchcancel = touchcancel; }); /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;'use strict'; (function (global, factory) { if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [exports, __webpack_require__(5)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (typeof exports !== "undefined") { factory(exports, require('@most/multicast')); } else { var mod = { exports: {} }; factory(mod.exports, global.multicast); global.mostHold = mod.exports; } })(undefined, function (exports, _multicast) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); // hold :: Stream a -> Stream a var index = function index(stream) { return new stream.constructor(new _multicast.MulticastSource(new Hold(stream.source))); }; var Hold = function () { function Hold(source) { _classCallCheck(this, Hold); this.source = source; this.time = -Infinity; this.value = void 0; } _createClass(Hold, [{ key: 'run', value: function run(sink, scheduler) { /* istanbul ignore else */ if (sink._hold !== this) { sink._hold = this; sink._holdAdd = sink.add; sink.add = holdAdd; sink._holdEvent = sink.event; sink.event = holdEvent; } return this.source.run(sink, scheduler); } }]); return Hold; }(); function holdAdd(sink) { var len = this._holdAdd(sink); /* istanbul ignore else */ if (this._hold.time >= 0) { sink.event(this._hold.time, this._hold.value); } return len; } function holdEvent(t, x) { /* istanbul ignore else */ if (t >= this._hold.time) { this._hold.time = t; this._hold.value = x; } return this._holdEvent(t, x); } exports.default = index; }); /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _vnode = __webpack_require__(15); var _vnode2 = _interopRequireDefault(_vnode); var _is = __webpack_require__(10); var _is2 = _interopRequireDefault(_is); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var isObservable = function isObservable(x) { return typeof x.observe === 'function'; }; var addNSToObservable = function addNSToObservable(vNode) { addNS(vNode.data, vNode.children); // eslint-disable-line }; function addNS(data, children) { data.ns = 'http://www.w3.org/2000/svg'; if (typeof children !== 'undefined' && _is2.default.array(children)) { for (var i = 0; i < children.length; ++i) { if (isObservable(children[i])) { children[i] = children[i].tap(addNSToObservable); } else { addNS(children[i].data, children[i].children); } } } } /* eslint-disable */ function h(sel, b, c) { var data = {}; var children = void 0; var text = void 0; var i = void 0; if (arguments.length === 3) { data = b; if (_is2.default.array(c)) { children = c; } else if (_is2.default.primitive(c)) { text = c; } } else if (arguments.length === 2) { if (_is2.default.array(b)) { children = b; } else if (_is2.default.primitive(b)) { text = b; } else { data = b; } } if (_is2.default.array(children)) { for (i = 0; i < children.length; ++i) { if (_is2.default.primitive(children[i])) { children[i] = (0, _vnode2.default)(undefined, undefined, undefined, children[i]); } } } if (sel[0] === 's' && sel[1] === 'v' && sel[2] === 'g') { addNS(data, children); } return (0, _vnode2.default)(sel, data || {}, children, text, undefined); } /* eslint-enable */ exports.default = h; /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.makeDOMDriver = undefined; var _most = __webpack_require__(4); var _hold = __webpack_require__(40); var _hold2 = _interopRequireDefault(_hold); var _snabbdom = __webpack_require__(100); var _h = __webpack_require__(36); var _h2 = _interopRequireDefault(_h); var _classNameFromVNode = __webpack_require__(92); var _classNameFromVNode2 = _interopRequireDefault(_classNameFromVNode); var _selectorParser2 = __webpack_require__(35); var _selectorParser3 = _interopRequireDefault(_selectorParser2); var _utils = __webpack_require__(22); var _modules = __webpack_require__(21); var _modules2 = _interopRequireDefault(_modules); var _transposition = __webpack_require__(45); var _isolate = __webpack_require__(19); var _select = __webpack_require__(44); var _events = __webpack_require__(18); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function makeVNodeWrapper(rootElement) { return function vNodeWrapper(vNode) { var _selectorParser = (0, _selectorParser3.default)(vNode.sel); var selectorTagName = _selectorParser.tagName; var selectorId = _selectorParser.id; var vNodeClassName = (0, _classNameFromVNode2.default)(vNode); var _vNode$data = vNode.data; var vNodeData = _vNode$data === undefined ? {} : _vNode$data; var _vNodeData$props = vNodeData.props; var vNodeDataProps = _vNodeData$props === undefined ? {} : _vNodeData$props; var _vNodeDataProps$id = vNodeDataProps.id; var vNodeId = _vNodeDataProps$id === undefined ? selectorId : _vNodeDataProps$id; var isVNodeAndRootElementIdentical = vNodeId.toUpperCase() === rootElement.id.toUpperCase() && selectorTagName.toUpperCase() === rootElement.tagName.toUpperCase() && vNodeClassName.toUpperCase() === rootElement.className.toUpperCase(); if (isVNodeAndRootElementIdentical) { return vNode; } var tagName = rootElement.tagName; var id = rootElement.id; var className = rootElement.className; var elementId = id ? '#' + id : ''; var elementClassName = className ? '.' + className.split(' ').join('.') : ''; return (0, _h2.default)('' + tagName + elementId + elementClassName, {}, [vNode]); }; } function DOMDriverInputGuard(view$) { if (!view$ || typeof view$.observe !== 'function') { throw new Error('The DOM driver function expects as input an ' + 'Observable of virtual DOM elements'); } } function defaultOnErrorFn(msg) { if (console && console.error) { console.error(msg); } else { console.log(msg); } } var defaults = { modules: _modules2.default, onError: defaultOnErrorFn }; function makeDOMDriver(container) { var _ref = arguments.length <= 1 || arguments[1] === undefined ? defaults : arguments[1]; var _ref$modules = _ref.modules; var modules = _ref$modules === undefined ? _modules2.default : _ref$modules; var _ref$onError = _ref.onError; var onError = _ref$onError === undefined ? defaultOnErrorFn : _ref$onError; var patch = (0, _snabbdom.init)(modules); var rootElement = (0, _utils.domSelectorParser)(container); if (!Array.isArray(modules)) { throw new Error('Optional modules option must be ' + 'an array for snabbdom modules'); } if (typeof onError !== 'function') { throw new Error('Optional onError opition must be ' + 'a function to approriately handle your errors'); } function DOMDriver(view$) { DOMDriverInputGuard(view$); var rootElement$ = (0, _hold2.default)(view$.map(_transposition.transposeVTree).switch().map(makeVNodeWrapper(rootElement)).scan(patch, rootElement).skip(1).recoverWith(function (err) { onError(err); return (0, _most.throwError)(err); }).map(function (_ref2) { var elm = _ref2.elm; return elm; })); rootElement$.drain(); return { observable: rootElement$, namespace: [], select: (0, _select.makeElementSelector)(rootElement$), events: (0, _events.makeEventsSelector)(rootElement$), isolateSink: _isolate.isolateSink, isolateSource: _isolate.isolateSource }; } return DOMDriver; } exports.makeDOMDriver = makeDOMDriver; /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.mockDOMSource = undefined; var _most = __webpack_require__(4); var _most2 = _interopRequireDefault(_most); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var emptyStream = _most2.default.empty(); function getEventsStreamForSelector(mockedEventTypes) { return function getEventsStream(eventType) { for (var key in mockedEventTypes) { if (mockedEventTypes.hasOwnProperty(key) && key === eventType) { return mockedEventTypes[key]; } } return emptyStream; }; } function makeMockSelector(mockedSelectors) { return function select(selector) { for (var key in mockedSelectors) { if (mockedSelectors.hasOwnProperty(key) && key === selector) { var observable = emptyStream; if (mockedSelectors[key].hasOwnProperty('observable')) { observable = mockedSelectors[key].observable; } return { observable: observable, select: makeMockSelector(mockedSelectors[key]), events: getEventsStreamForSelector(mockedSelectors[key]) }; } } return { observable: emptyStream, select: makeMockSelector(mockedSelectors), events: function events() { return emptyStream; } }; }; } function mockDOMSource() { var mockedSelectors = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; return { observable: emptyStream, select: makeMockSelector(mockedSelectors), events: function events() { return emptyStream; } }; } exports.mockDOMSource = mockDOMSource; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.makeIsStrictlyInRootScope = exports.makeElementSelector = undefined; var _makeIsStrictlyInRootScope = __webpack_require__(20); var _events = __webpack_require__(18); var _isolate = __webpack_require__(19); var isValidString = function isValidString(param) { return typeof param === 'string' && param.length > 0; }; var contains = function contains(str, match) { return str.indexOf(match) > -1; }; var isNotTagName = function isNotTagName(param) { return isValidString(param) && contains(param, '.') || contains(param, '#') || contains(param, ':'); }; function sortNamespace(a, b) { if (isNotTagName(a) && isNotTagName(b)) { return 0; } return isNotTagName(a) ? 1 : -1; } function removeDuplicates(arr) { var newArray = []; arr.forEach(function (element) { if (newArray.indexOf(element) === -1) { newArray.push(element); } }); return newArray; } var getScope = function getScope(namespace) { return namespace.filter(function (c) { return c.indexOf('.cycle-scope') > -1; }); }; function makeFindElements(namespace) { return function findElements(rootElement) { if (namespace.join('') === '') { return rootElement; } var slice = Array.prototype.slice; var scope = getScope(namespace); // Uses global selector && is isolated if (namespace.indexOf('*') > -1 && scope.length > 0) { // grab top-level boundary of scope var topNode = rootElement.querySelector(scope.join(' ')); // grab all children var childNodes = topNode.getElementsByTagName('*'); return removeDuplicates([topNode].concat(slice.call(childNodes))).filter((0, _makeIsStrictlyInRootScope.makeIsStrictlyInRootScope)(namespace)); } return removeDuplicates(slice.call(rootElement.querySelectorAll(namespace.join(' '))).concat(slice.call(rootElement.querySelectorAll(namespace.join(''))))).filter((0, _makeIsStrictlyInRootScope.makeIsStrictlyInRootScope)(namespace)); }; } function makeElementSelector(rootElement$) { return function elementSelector(selector) { if (typeof selector !== 'string') { throw new Error('DOM driver\'s select() expects the argument to be a ' + 'string as a CSS selector'); } var namespace = this.namespace; var trimmedSelector = selector.trim(); var childNamespace = trimmedSelector === ':root' ? namespace : namespace.concat(trimmedSelector).sort(sortNamespace); return { observable: rootElement$.map(makeFindElements(childNamespace)), namespace: childNamespace, select: makeElementSelector(rootElement$), events: (0, _events.makeEventsSelector)(rootElement$, childNamespace), isolateSource: _isolate.isolateSource, isolateSink: _isolate.isolateSink }; }; } exports.makeElementSelector = makeElementSelector; exports.makeIsStrictlyInRootScope = _makeIsStrictlyInRootScope.makeIsStrictlyInRootScope; /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.transposeVTree = undefined; var _most = __webpack_require__(4); var _most2 = _interopRequireDefault(_most); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function createVTree(vTree, children) { return { sel: vTree.sel, data: vTree.data, text: vTree.text, elm: vTree.elm, key: vTree.key, children: children }; } function transposeVTree(vTree) { if (!vTree) { return null; } else if (vTree && _typeof(vTree.data) === 'object' && vTree.data.static) { return _most2.default.just(vTree); } else if (typeof vTree.observe === 'function') { return vTree.map(transposeVTree).switch(); } else if ((typeof vTree === 'undefined' ? 'undefined' : _typeof(vTree)) === 'object') { if (!vTree.children || vTree.children.length === 0) { return _most2.default.just(vTree); } var vTreeChildren = vTree.children.map(transposeVTree).filter(function (x) { return x !== null; }); return vTreeChildren.length === 0 ? _most2.default.just(createVTree(vTree, vTreeChildren)) : _most2.default.combineArray(function () { for (var _len = arguments.length, children = Array(_len), _key = 0; _key < _len; _key++) { children[_key] = arguments[_key]; } return createVTree(vTree, children); }, vTreeChildren); } else { throw new Error('Unhandled vTree Value'); } } exports.transposeVTree = transposeVTree; /***/ }, /* 46 */ /***/ function(module, exports) { "use strict"; /*! * Cross-Browser Split 1.1.1 * Copyright 2007-2012 Steven Levithan <stevenlevithan.com> * Available under the MIT License * ECMAScript compliant, uniform cross-browser split method */ /** * Splits a string into an array of strings using a regex or string separator. Matches of the * separator are not included in the result array. However, if `separator` is a regex that contains * capturing groups, backreferences are spliced into the result each time `separator` is matched. * Fixes browser bugs compared to the native `String.prototype.split` and can be used reliably * cross-browser. * @param {String} str String to split. * @param {RegExp|String} separator Regex or string to use for separating the string. * @param {Number} [limit] Maximum number of items to include in the result array. * @returns {Array} Array of substrings. * @example * * // Basic use * split('a b c d', ' '); * // -> ['a', 'b', 'c', 'd'] * * // With limit * split('a b c d', ' ', 2); * // -> ['a', 'b'] * * // Backreferences in result array * split('..word1 word2..', /([a-z]+)(\d+)/i); * // -> ['..', 'word', '1', ' ', 'word', '2', '..'] */ module.exports = function split(undef) { var nativeSplit = String.prototype.split, compliantExecNpcg = /()??/.exec("")[1] === undef, // NPCG: nonparticipating capturing group self; self = function self(str, separator, limit) { // If `separator` is not a regex, use `nativeSplit` if (Object.prototype.toString.call(separator) !== "[object RegExp]") { return nativeSplit.call(str, separator, limit); } var output = [], flags = (separator.ignoreCase ? "i" : "") + (separator.multiline ? "m" : "") + (separator.extended ? "x" : "") + ( // Proposed for ES6 separator.sticky ? "y" : ""), // Firefox 3+ lastLastIndex = 0, // Make `global` and avoid `lastIndex` issues by working with a copy separator = new RegExp(separator.source, flags + "g"), separator2, match, lastIndex, lastLength; str += ""; // Type-convert if (!compliantExecNpcg) { // Doesn't need flags gy, but they don't hurt separator2 = new RegExp("^" + separator.source + "$(?!\\s)", flags); } /* Values for `limit`, per the spec: * If undefined: 4294967295 // Math.pow(2, 32) - 1 * If 0, Infinity, or NaN: 0 * If positive number: limit = Math.floor(limit); if (limit > 4294967295) limit -= 4294967296; * If negative number: 4294967296 - Math.floor(Math.abs(limit)) * If other: Type-convert, then use the above rules */ limit = limit === undef ? -1 >>> 0 : // Math.pow(2, 32) - 1 limit >>> 0; // ToUint32(limit) while (match = separator.exec(str)) { // `separator.lastIndex` is not reliable cross-browser lastIndex = match.index + match[0].length; if (lastIndex > lastLastIndex) { output.push(str.slice(lastLastIndex, match.index)); // Fix browsers whose `exec` methods don't consistently return `undefined` for // nonparticipating capturing groups if (!compliantExecNpcg && match.length > 1) { match[0].replace(separator2, function () { for (var i = 1; i < arguments.length - 2; i++) { if (arguments[i] === undef) { match[i] = undef; } } }); } if (match.length > 1 && match.index < str.length) { Array.prototype.push.apply(output, match.slice(1)); } lastLength = match[0].length; lastLastIndex = lastIndex; if (output.length >= limit) { break; } } if (separator.lastIndex === match.index) { separator.lastIndex++; // Avoid an infinite loop } } if (lastLastIndex === str.length) { if (lastLength || !separator.test("")) { output.push(""); } } else { output.push(str.slice(lastLastIndex)); } return output.length > limit ? output.slice(0, limit) : output; }; return self; }(); /***/ }, /* 47 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var isValidString = function isValidString(param) { return typeof param === 'string' && param.length > 0; }; var startsWith = function startsWith(string, start) { return string[0] === start; }; var isSelector = function isSelector(param) { return isValidString(param) && (startsWith(param, '.') || startsWith(param, '#')); }; var node = function node(h) { return function (tagName) { return function (first) { for (var _len = arguments.length, rest = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { rest[_key - 1] = arguments[_key]; } if (isSelector(first)) { return h.apply(undefined, [tagName + first].concat(rest)); } else { return h.apply(undefined, [tagName, first].concat(rest)); } }; }; }; var TAG_NAMES = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'dd', 'del', 'dfn', 'dir', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'menu', 'meta', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'p', 'param', 'pre', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'u', 'ul', 'video', 'progress']; exports['default'] = function (h) { var createTag = node(h); var exported = { TAG_NAMES: TAG_NAMES, isSelector: isSelector, createTag: createTag }; TAG_NAMES.forEach(function (n) { exported[n] = createTag(n); }); return exported; }; module.exports = exports['default']; /***/ }, /* 48 */ /***/ function(module, exports) { 'use strict'; var proto = Element.prototype; var vendor = proto.matches || proto.matchesSelector || proto.webkitMatchesSelector || proto.mozMatchesSelector || proto.msMatchesSelector || proto.oMatchesSelector; module.exports = match; /** * Match `el` to `selector`. * * @param {Element} el * @param {String} selector * @return {Boolean} * @api public */ function match(el, selector) { if (vendor) return vendor.call(el, selector); var nodes = el.parentNode.querySelectorAll(selector); for (var i = 0; i < nodes.length; i++) { if (nodes[i] == el) return true; } return false; } /***/ }, /* 49 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor); } }return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function tryEvent(sink, scheduler, event) { try { sink.event(scheduler.now(), event); } catch (err) { sink.error(scheduler.now(), err); } } function tryEnd(sink, scheduler, event) { try { sink.end(scheduler.now(), event); } catch (err) { sink.error(scheduler.now(), err); } } var Observer = function () { function Observer() { var _this = this; _classCallCheck(this, Observer); this.run = function (sink, scheduler) { return _this._run(sink, scheduler); }; this.next = function (x) { return _this._next(x); }; this.error = function (err) { return _this._error(err); }; this.complete = function (x) { return _this._complete(x); }; } _createClass(Observer, [{ key: "_run", value: function _run(sink, scheduler) { this.sink = sink; this.scheduler = scheduler; this.active = true; return this; } }, { key: "dispose", value: function dispose() { this.active = false; } }, { key: "_next", value: function _next(value) { if (!this.active) { return; } tryEvent(this.sink, this.scheduler, value); } }, { key: "_error", value: function _error(err) { this.active = false; this.sink.error(this.scheduler.now(), err); } }, { key: "_complete", value: function _complete(value) { if (!this.active) { return; } this.active = false; tryEnd(this.sink, this.scheduler, value); } }]); return Observer; }(); exports.Observer = Observer; /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.replay = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor); } }return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor; }; }(); var _most = __webpack_require__(4); var _multicast = __webpack_require__(5); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function pushEvents(sink, buffer) { var i = 0; for (; i < buffer.length; ++i) { var item = buffer[i]; sink.event(item.time, item.value); } } function replayAdd(sink) { var length = this._replayAdd(sink); if (this._replay.buffer.length > 0) { pushEvents(sink, this._replay.buffer); } return length; } function addToBuffer(event, replay) { if (replay.buffer.length >= replay.bufferSize) { replay.buffer.shift(); } replay.buffer.push(event); } function replayEvent(time, value) { if (this._replay.bufferSize > 0) { addToBuffer({ time: time, value: value }, this._replay); } this._replayEvent(time, value); } var Replay = function () { function Replay(bufferSize, source) { _classCallCheck(this, Replay); this.source = source; this.bufferSize = bufferSize; this.buffer = []; } _createClass(Replay, [{ key: 'run', value: function run(sink, scheduler) { if (sink._replay !== this) { sink._replay = this; sink._replayAdd = sink.add; sink.add = replayAdd; sink._replayEvent = sink.event; sink.event = replayEvent; } return this.source.run(sink, scheduler); } }]); return Replay; }(); var replay = function replay(bufferSize, stream) { return new _most.Stream(new _multicast.MulticastSource(new Replay(bufferSize, stream.source))); }; exports.replay = replay; /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.holdSubject = exports.subject = undefined; var _most = __webpack_require__(4); var _multicast = __webpack_require__(5); var _Observer = __webpack_require__(49); var _Replay = __webpack_require__(50); function create(hold, bufferSize, initialValue) { var observer = new _Observer.Observer(); var stream = hold ? (0, _Replay.replay)(bufferSize, new _most.Stream(observer)) : new _most.Stream(new _multicast.MulticastSource(observer)); stream.drain(); if (typeof initialValue !== 'undefined') { observer.next(initialValue); } return { stream: stream, observer: observer }; } function subject() { return create(false, 0); } function holdSubject() { var bufferSize = arguments.length <= 0 || arguments[0] === undefined ? 1 : arguments[0]; var initialValue = arguments[1]; if (bufferSize < 1) { throw new Error('First argument to holdSubject is expected to be an ' + 'integer greater than or equal to 1'); } return create(true, bufferSize, initialValue); } exports.subject = subject; exports.holdSubject = holdSubject; /***/ }, /* 52 */ /***/ function(module, exports) { "use strict"; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ module.exports = LinkedList; /** * Doubly linked list * @constructor */ function LinkedList() { this.head = null; this.length = 0; } /** * Add a node to the end of the list * @param {{prev:Object|null, next:Object|null, dispose:function}} x node to add */ LinkedList.prototype.add = function (x) { if (this.head !== null) { this.head.prev = x; x.next = this.head; } this.head = x; ++this.length; }; /** * Remove the provided node from the list * @param {{prev:Object|null, next:Object|null, dispose:function}} x node to remove */ LinkedList.prototype.remove = function (x) { --this.length; if (x === this.head) { this.head = this.head.next; } if (x.next !== null) { x.next.prev = x.prev; x.next = null; } if (x.prev !== null) { x.prev.next = x.next; x.prev = null; } }; /** * @returns {boolean} true iff there are no nodes in the list */ LinkedList.prototype.isEmpty = function () { return this.length === 0; }; /** * Dispose all nodes * @returns {Promise} promise that fulfills when all nodes have been disposed, * or rejects if an error occurs while disposing */ LinkedList.prototype.dispose = function () { if (this.isEmpty()) { return Promise.resolve(); } var promises = []; var x = this.head; this.head = null; this.length = 0; while (x !== null) { promises.push(x.dispose()); x = x.next; } return Promise.all(promises); }; /***/ }, /* 53 */ /***/ function(module, exports) { "use strict"; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ // Based on https://github.com/petkaantonov/deque module.exports = Queue; function Queue(capPow2) { this._capacity = capPow2 || 32; this._length = 0; this._head = 0; } Queue.prototype.push = function (x) { var len = this._length; this._checkCapacity(len + 1); var i = this._head + len & this._capacity - 1; this[i] = x; this._length = len + 1; }; Queue.prototype.shift = function () { var head = this._head; var x = this[head]; this[head] = void 0; this._head = head + 1 & this._capacity - 1; this._length--; return x; }; Queue.prototype.isEmpty = function () { return this._length === 0; }; Queue.prototype.length = function () { return this._length; }; Queue.prototype._checkCapacity = function (size) { if (this._capacity < size) { this._ensureCapacity(this._capacity << 1); } }; Queue.prototype._ensureCapacity = function (capacity) { var oldCapacity = this._capacity; this._capacity = capacity; var last = this._head + this._length; if (last > oldCapacity) { copy(this, 0, this, oldCapacity, last & oldCapacity - 1); } }; function copy(src, srcIndex, dst, dstIndex, len) { for (var j = 0; j < len; ++j) { dst[j + dstIndex] = src[j + srcIndex]; src[j + srcIndex] = void 0; } } /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var Pipe = __webpack_require__(1); var runSource = __webpack_require__(32); var cons = __webpack_require__(23).cons; exports.scan = scan; exports.reduce = reduce; /** * Create a stream containing successive reduce results of applying f to * the previous reduce result and the current stream item. * @param {function(result:*, x:*):*} f reducer function * @param {*} initial initial value * @param {Stream} stream stream to scan * @returns {Stream} new stream containing successive reduce results */ function scan(f, initial, stream) { return cons(initial, new Stream(new Accumulate(ScanSink, f, initial, stream.source))); } function ScanSink(f, z, sink) { this.f = f; this.value = z; this.sink = sink; } ScanSink.prototype.event = function (t, x) { var f = this.f; this.value = f(this.value, x); this.sink.event(t, this.value); }; ScanSink.prototype.error = Pipe.prototype.error; ScanSink.prototype.end = Pipe.prototype.end; /** * Reduce a stream to produce a single result. Note that reducing an infinite * stream will return a Promise that never fulfills, but that may reject if an error * occurs. * @param {function(result:*, x:*):*} f reducer function * @param {*} initial initial value * @param {Stream} stream to reduce * @returns {Promise} promise for the file result of the reduce */ function reduce(f, initial, stream) { return runSource.withDefaultScheduler(noop, new Accumulate(AccumulateSink, f, initial, stream.source)); } function Accumulate(SinkType, f, z, source) { this.SinkType = SinkType; this.f = f; this.value = z; this.source = source; } Accumulate.prototype.run = function (sink, scheduler) { return this.source.run(new this.SinkType(this.f, this.value, sink), scheduler); }; function AccumulateSink(f, z, sink) { this.f = f; this.value = z; this.sink = sink; } AccumulateSink.prototype.event = function (t, x) { var f = this.f; this.value = f(this.value, x); this.sink.event(t, this.value); }; AccumulateSink.prototype.error = Pipe.prototype.error; AccumulateSink.prototype.end = function (t) { this.sink.end(t, this.value); }; function noop() {} /***/ }, /* 55 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var combine = __webpack_require__(24).combine; var apply = __webpack_require__(3).apply; exports.ap = ap; /** * Assume fs is a stream containing functions, and apply the latest function * in fs to the latest value in xs. * fs: --f---------g--------h------> * xs: -a-------b-------c-------d--> * ap(fs, xs): --fa-----fb-gb---gc--hc--hd-> * @param {Stream} fs stream of functions to apply to the latest x * @param {Stream} xs stream of values to which to apply all the latest f * @returns {Stream} stream containing all the applications of fs to xs */ function ap(fs, xs) { return combine(apply, fs, xs); } /***/ }, /* 56 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var mergeMapConcurrently = __webpack_require__(8).mergeMapConcurrently; exports.concatMap = concatMap; /** * Map each value in stream to a new stream, and concatenate them all * stream: -a---b---cX * f(a): 1-1-1-1X * f(b): -2-2-2-2X * f(c): -3-3-3-3X * stream.concatMap(f): -1-1-1-1-2-2-2-2-3-3-3-3X * @param {function(x:*):Stream} f function to map each value to a stream * @param {Stream} stream * @returns {Stream} new stream containing all events from each stream returned by f */ function concatMap(f, stream) { return mergeMapConcurrently(f, 1, stream); } /***/ }, /* 57 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var Sink = __webpack_require__(1); var dispose = __webpack_require__(2); var PropagateTask = __webpack_require__(6); exports.delay = delay; /** * @param {Number} delayTime milliseconds to delay each item * @param {Stream} stream * @returns {Stream} new stream containing the same items, but delayed by ms */ function delay(delayTime, stream) { return delayTime <= 0 ? stream : new Stream(new Delay(delayTime, stream.source)); } function Delay(dt, source) { this.dt = dt; this.source = source; } Delay.prototype.run = function (sink, scheduler) { var delaySink = new DelaySink(this.dt, sink, scheduler); return dispose.all([delaySink, this.source.run(delaySink, scheduler)]); }; function DelaySink(dt, sink, scheduler) { this.dt = dt; this.sink = sink; this.scheduler = scheduler; } DelaySink.prototype.dispose = function () { var self = this; this.scheduler.cancelAll(function (task) { return task.sink === self.sink; }); }; DelaySink.prototype.event = function (t, x) { this.scheduler.delay(this.dt, PropagateTask.event(x, this.sink)); }; DelaySink.prototype.end = function (t, x) { this.scheduler.delay(this.dt, PropagateTask.end(x, this.sink)); }; DelaySink.prototype.error = Sink.prototype.error; /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var ValueSource = __webpack_require__(34); var SafeSink = __webpack_require__(80); var Pipe = __webpack_require__(1); var dispose = __webpack_require__(2); var tryEvent = __webpack_require__(9); var isPromise = __webpack_require__(11).isPromise; exports.flatMapError = recoverWith; exports.recoverWith = recoverWith; exports.throwError = throwError; /** * If stream encounters an error, recover and continue with items from stream * returned by f. * @param {function(error:*):Stream} f function which returns a new stream * @param {Stream} stream * @returns {Stream} new stream which will recover from an error by calling f */ function recoverWith(f, stream) { return new Stream(new RecoverWith(f, stream.source)); } /** * Create a stream containing only an error * @param {*} e error value, preferably an Error or Error subtype * @returns {Stream} new stream containing only an error */ function throwError(e) { return new Stream(new ValueSource(error, e)); } function error(t, e, sink) { sink.error(t, e); } function RecoverWith(f, source) { this.f = f; this.source = source; } RecoverWith.prototype.run = function (sink, scheduler) { return new RecoverWithSink(this.f, this.source, sink, scheduler); }; function RecoverWithSink(f, source, sink, scheduler) { this.f = f; this.sink = new SafeSink(sink); this.scheduler = scheduler; this.disposable = source.run(this, scheduler); } RecoverWithSink.prototype.event = function (t, x) { tryEvent.tryEvent(t, x, this.sink); }; RecoverWithSink.prototype.end = function (t, x) { tryEvent.tryEnd(t, x, this.sink); }; RecoverWithSink.prototype.error = function (t, e) { var nextSink = this.sink.disable(); var result = dispose.tryDispose(t, this.disposable, nextSink); this.disposable = isPromise(result) ? dispose.promised(this._thenContinue(result, e, nextSink)) : this._continue(this.f, e, nextSink); }; RecoverWithSink.prototype._thenContinue = function (p, x, sink) { var self = this; return p.then(function () { return self._continue(self.f, x, sink); }); }; RecoverWithSink.prototype._continue = function (f, x, sink) { return f(x).source.run(sink, this.scheduler); }; RecoverWithSink.prototype.dispose = function () { return this.disposable.dispose(); }; /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var Sink = __webpack_require__(1); var Filter = __webpack_require__(29); exports.filter = filter; exports.skipRepeats = skipRepeats; exports.skipRepeatsWith = skipRepeatsWith; /** * Retain only items matching a predicate * @param {function(x:*):boolean} p filtering predicate called for each item * @param {Stream} stream stream to filter * @returns {Stream} stream containing only items for which predicate returns truthy */ function filter(p, stream) { return new Stream(Filter.create(p, stream.source)); } /** * Skip repeated events, using === to detect duplicates * @param {Stream} stream stream from which to omit repeated events * @returns {Stream} stream without repeated events */ function skipRepeats(stream) { return skipRepeatsWith(same, stream); } /** * Skip repeated events using the provided equals function to detect duplicates * @param {function(a:*, b:*):boolean} equals optional function to compare items * @param {Stream} stream stream from which to omit repeated events * @returns {Stream} stream without repeated events */ function skipRepeatsWith(equals, stream) { return new Stream(new SkipRepeats(equals, stream.source)); } function SkipRepeats(equals, source) { this.equals = equals; this.source = source; } SkipRepeats.prototype.run = function (sink, scheduler) { return this.source.run(new SkipRepeatsSink(this.equals, sink), scheduler); }; function SkipRepeatsSink(equals, sink) { this.equals = equals; this.sink = sink; this.value = void 0; this.init = true; } SkipRepeatsSink.prototype.end = Sink.prototype.end; SkipRepeatsSink.prototype.error = Sink.prototype.error; SkipRepeatsSink.prototype.event = function (t, x) { if (this.init) { this.init = false; this.value = x; this.sink.event(t, x); } else if (!this.equals(this.value, x)) { this.value = x; this.sink.event(t, x); } }; function same(a, b) { return a === b; } /***/ }, /* 60 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var Sink = __webpack_require__(1); var dispose = __webpack_require__(2); var PropagateTask = __webpack_require__(6); exports.throttle = throttle; exports.debounce = debounce; /** * Limit the rate of events by suppressing events that occur too often * @param {Number} period time to suppress events * @param {Stream} stream * @returns {Stream} */ function throttle(period, stream) { return new Stream(new Throttle(period, stream.source)); } function Throttle(period, source) { this.dt = period; this.source = source; } Throttle.prototype.run = function (sink, scheduler) { return this.source.run(new ThrottleSink(this.dt, sink), scheduler); }; function ThrottleSink(dt, sink) { this.time = 0; this.dt = dt; this.sink = sink; } ThrottleSink.prototype.event = function (t, x) { if (t >= this.time) { this.time = t + this.dt; this.sink.event(t, x); } }; ThrottleSink.prototype.end = Sink.prototype.end; ThrottleSink.prototype.error = Sink.prototype.error; /** * Wait for a burst of events to subside and emit only the last event in the burst * @param {Number} period events occuring more frequently than this * will be suppressed * @param {Stream} stream stream to debounce * @returns {Stream} new debounced stream */ function debounce(period, stream) { return new Stream(new Debounce(period, stream.source)); } function Debounce(dt, source) { this.dt = dt; this.source = source; } Debounce.prototype.run = function (sink, scheduler) { return new DebounceSink(this.dt, this.source, sink, scheduler); }; function DebounceSink(dt, source, sink, scheduler) { this.dt = dt; this.sink = sink; this.scheduler = scheduler; this.value = void 0; this.timer = null; var sourceDisposable = source.run(this, scheduler); this.disposable = dispose.all([this, sourceDisposable]); } DebounceSink.prototype.event = function (t, x) { this._clearTimer(); this.value = x; this.timer = this.scheduler.delay(this.dt, PropagateTask.event(x, this.sink)); }; DebounceSink.prototype.end = function (t, x) { if (this._clearTimer()) { this.sink.event(t, this.value); this.value = void 0; } this.sink.end(t, x); }; DebounceSink.prototype.error = function (t, x) { this._clearTimer(); this.sink.error(t, x); }; DebounceSink.prototype.dispose = function () { this._clearTimer(); }; DebounceSink.prototype._clearTimer = function () { if (this.timer === null) { return false; } this.timer.cancel(); this.timer = null; return true; }; /***/ }, /* 61 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var Pipe = __webpack_require__(1); exports.loop = loop; /** * Generalized feedback loop. Call a stepper function for each event. The stepper * will be called with 2 params: the current seed and the an event value. It must * return a new { seed, value } pair. The `seed` will be fed back into the next * invocation of stepper, and the `value` will be propagated as the event value. * @param {function(seed:*, value:*):{seed:*, value:*}} stepper loop step function * @param {*} seed initial seed value passed to first stepper call * @param {Stream} stream event stream * @returns {Stream} new stream whose values are the `value` field of the objects * returned by the stepper */ function loop(stepper, seed, stream) { return new Stream(new Loop(stepper, seed, stream.source)); } function Loop(stepper, seed, source) { this.step = stepper; this.seed = seed; this.source = source; } Loop.prototype.run = function (sink, scheduler) { return this.source.run(new LoopSink(this.step, this.seed, sink), scheduler); }; function LoopSink(stepper, seed, sink) { this.step = stepper; this.seed = seed; this.sink = sink; } LoopSink.prototype.error = Pipe.prototype.error; LoopSink.prototype.event = function (t, x) { var result = this.step(this.seed, x); this.seed = result.seed; this.sink.event(t, result.value); }; LoopSink.prototype.end = function (t) { this.sink.end(t, this.seed); }; /***/ }, /* 62 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var Pipe = __webpack_require__(1); var IndexSink = __webpack_require__(14); var empty = __webpack_require__(7).empty; var dispose = __webpack_require__(2); var base = __webpack_require__(3); var copy = base.copy; var reduce = base.reduce; exports.merge = merge; exports.mergeArray = mergeArray; /** * @returns {Stream} stream containing events from all streams in the argument * list in time order. If two events are simultaneous they will be merged in * arbitrary order. */ function merge() /*...streams*/{ return mergeArray(copy(arguments)); } /** * @param {Array} streams array of stream to merge * @returns {Stream} stream containing events from all input observables * in time order. If two events are simultaneous they will be merged in * arbitrary order. */ function mergeArray(streams) { var l = streams.length; return l === 0 ? empty() : l === 1 ? streams[0] : new Stream(mergeSources(streams)); } /** * This implements fusion/flattening for merge. It will * fuse adjacent merge operations. For example: * - a.merge(b).merge(c) effectively becomes merge(a, b, c) * - merge(a, merge(b, c)) effectively becomes merge(a, b, c) * It does this by concatenating the sources arrays of * any nested Merge sources, in effect "flattening" nested * merge operations into a single merge. */ function mergeSources(streams) { return new Merge(reduce(appendSources, [], streams)); } function appendSources(sources, stream) { var source = stream.source; return source instanceof Merge ? sources.concat(source.sources) : sources.concat(source); } function Merge(sources) { this.sources = sources; } Merge.prototype.run = function (sink, scheduler) { var l = this.sources.length; var disposables = new Array(l); var sinks = new Array(l); var mergeSink = new MergeSink(disposables, sinks, sink); for (var indexSink, i = 0; i < l; ++i) { indexSink = sinks[i] = new IndexSink(i, mergeSink); disposables[i] = this.sources[i].run(indexSink, scheduler); } return dispose.all(disposables); }; function MergeSink(disposables, sinks, sink) { this.sink = sink; this.disposables = disposables; this.activeCount = sinks.length; } MergeSink.prototype.error = Pipe.prototype.error; MergeSink.prototype.event = function (t, indexValue) { this.sink.event(t, indexValue.value); }; MergeSink.prototype.end = function (t, indexedValue) { dispose.tryDispose(t, this.disposables[indexedValue.index], this.sink); if (--this.activeCount === 0) { this.sink.end(t, indexedValue.value); } }; /***/ }, /* 63 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var runSource = __webpack_require__(32); exports.observe = observe; exports.drain = drain; /** * Observe all the event values in the stream in time order. The * provided function `f` will be called for each event value * @param {function(x:T):*} f function to call with each event value * @param {Stream<T>} stream stream to observe * @return {Promise} promise that fulfills after the stream ends without * an error, or rejects if the stream ends with an error. */ function observe(f, stream) { return runSource.withDefaultScheduler(f, stream.source); } /** * "Run" a stream by * @param stream * @return {*} */ function drain(stream) { return runSource.withDefaultScheduler(noop, stream.source); } function noop() {} /***/ }, /* 64 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var fatal = __webpack_require__(28); var just = __webpack_require__(7).of; exports.fromPromise = fromPromise; exports.awaitPromises = awaitPromises; /** * Create a stream containing only the promise's fulfillment * value at the time it fulfills. * @param {Promise<T>} p promise * @return {Stream<T>} stream containing promise's fulfillment value. * If the promise rejects, the stream will error */ function fromPromise(p) { return awaitPromises(just(p)); } /** * Turn a Stream<Promise<T>> into Stream<T> by awaiting each promise. * Event order is preserved. * @param {Stream<Promise<T>>} stream * @return {Stream<T>} stream of fulfillment values. The stream will * error if any promise rejects. */ function awaitPromises(stream) { return new Stream(new Await(stream.source)); } function Await(source) { this.source = source; } Await.prototype.run = function (sink, scheduler) { return this.source.run(new AwaitSink(sink, scheduler), scheduler); }; function AwaitSink(sink, scheduler) { this.sink = sink; this.scheduler = scheduler; this.queue = Promise.resolve(); var self = this; // Pre-create closures, to avoid creating them per event this._eventBound = function (x) { self.sink.event(self.scheduler.now(), x); }; this._endBound = function (x) { self.sink.end(self.scheduler.now(), x); }; this._errorBound = function (e) { self.sink.error(self.scheduler.now(), e); }; } AwaitSink.prototype.event = function (t, promise) { var self = this; this.queue = this.queue.then(function () { return self._event(promise); }).catch(this._errorBound); }; AwaitSink.prototype.end = function (t, x) { var self = this; this.queue = this.queue.then(function () { return self._end(x); }).catch(this._errorBound); }; AwaitSink.prototype.error = function (t, e) { var self = this; // Don't resolve error values, propagate directly this.queue = this.queue.then(function () { return self._errorBound(e); }).catch(fatal); }; AwaitSink.prototype._event = function (promise) { return promise.then(this._eventBound); }; AwaitSink.prototype._end = function (x) { return Promise.resolve(x).then(this._endBound); }; /***/ }, /* 65 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var Pipe = __webpack_require__(1); var dispose = __webpack_require__(2); var base = __webpack_require__(3); var invoke = __webpack_require__(13); exports.sample = sample; exports.sampleWith = sampleWith; exports.sampleArray = sampleArray; /** * When an event arrives on sampler, emit the result of calling f with the latest * values of all streams being sampled * @param {function(...values):*} f function to apply to each set of sampled values * @param {Stream} sampler streams will be sampled whenever an event arrives * on sampler * @returns {Stream} stream of sampled and transformed values */ function sample(f, sampler /*, ...streams */) { return sampleArray(f, sampler, base.drop(2, arguments)); } /** * When an event arrives on sampler, emit the latest event value from stream. * @param {Stream} sampler stream of events at whose arrival time * stream's latest value will be propagated * @param {Stream} stream stream of values * @returns {Stream} sampled stream of values */ function sampleWith(sampler, stream) { return new Stream(new Sampler(base.id, sampler.source, [stream.source])); } function sampleArray(f, sampler, streams) { return new Stream(new Sampler(f, sampler.source, base.map(getSource, streams))); } function getSource(stream) { return stream.source; } function Sampler(f, sampler, sources) { this.f = f; this.sampler = sampler; this.sources = sources; } Sampler.prototype.run = function (sink, scheduler) { var l = this.sources.length; var disposables = new Array(l + 1); var sinks = new Array(l); var sampleSink = new SampleSink(this.f, sinks, sink); for (var hold, i = 0; i < l; ++i) { hold = sinks[i] = new Hold(sampleSink); disposables[i] = this.sources[i].run(hold, scheduler); } disposables[i] = this.sampler.run(sampleSink, scheduler); return dispose.all(disposables); }; function Hold(sink) { this.sink = sink; this.hasValue = false; } Hold.prototype.event = function (t, x) { this.value = x; this.hasValue = true; this.sink._notify(this); }; Hold.prototype.end = function () {}; Hold.prototype.error = Pipe.prototype.error; function SampleSink(f, sinks, sink) { this.f = f; this.sinks = sinks; this.sink = sink; this.active = false; } SampleSink.prototype._notify = function () { if (!this.active) { this.active = this.sinks.every(hasValue); } }; SampleSink.prototype.event = function (t) { if (this.active) { this.sink.event(t, invoke(this.f, base.map(getValue, this.sinks))); } }; SampleSink.prototype.end = Pipe.prototype.end; SampleSink.prototype.error = Pipe.prototype.error; function hasValue(hold) { return hold.hasValue; } function getValue(hold) { return hold.value; } /***/ }, /* 66 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var Sink = __webpack_require__(1); var core = __webpack_require__(7); var dispose = __webpack_require__(2); var Map = __webpack_require__(30); exports.take = take; exports.skip = skip; exports.slice = slice; exports.takeWhile = takeWhile; exports.skipWhile = skipWhile; /** * @param {number} n * @param {Stream} stream * @returns {Stream} new stream containing only up to the first n items from stream */ function take(n, stream) { return slice(0, n, stream); } /** * @param {number} n * @param {Stream} stream * @returns {Stream} new stream with the first n items removed */ function skip(n, stream) { return slice(n, Infinity, stream); } /** * Slice a stream by index. Negative start/end indexes are not supported * @param {number} start * @param {number} end * @param {Stream} stream * @returns {Stream} stream containing items where start <= index < end */ function slice(start, end, stream) { return end <= start ? core.empty() : new Stream(sliceSource(start, end, stream.source)); } function sliceSource(start, end, source) { return source instanceof Map ? commuteMapSlice(start, end, source) : source instanceof Slice ? fuseSlice(start, end, source) : new Slice(start, end, source); } function commuteMapSlice(start, end, source) { return Map.create(source.f, sliceSource(start, end, source.source)); } function fuseSlice(start, end, source) { start += source.min; end = Math.min(end + source.min, source.max); return new Slice(start, end, source.source); } function Slice(min, max, source) { this.source = source; this.min = min; this.max = max; } Slice.prototype.run = function (sink, scheduler) { return new SliceSink(this.min, this.max - this.min, this.source, sink, scheduler); }; function SliceSink(skip, take, source, sink, scheduler) { this.sink = sink; this.skip = skip; this.take = take; this.disposable = dispose.once(source.run(this, scheduler)); } SliceSink.prototype.end = Sink.prototype.end; SliceSink.prototype.error = Sink.prototype.error; SliceSink.prototype.event = function (t, x) { if (this.skip > 0) { this.skip -= 1; return; } if (this.take === 0) { return; } this.take -= 1; this.sink.event(t, x); if (this.take === 0) { this.dispose(); this.sink.end(t, x); } }; SliceSink.prototype.dispose = function () { return this.disposable.dispose(); }; function takeWhile(p, stream) { return new Stream(new TakeWhile(p, stream.source)); } function TakeWhile(p, source) { this.p = p; this.source = source; } TakeWhile.prototype.run = function (sink, scheduler) { return new TakeWhileSink(this.p, this.source, sink, scheduler); }; function TakeWhileSink(p, source, sink, scheduler) { this.p = p; this.sink = sink; this.active = true; this.disposable = dispose.once(source.run(this, scheduler)); } TakeWhileSink.prototype.end = Sink.prototype.end; TakeWhileSink.prototype.error = Sink.prototype.error; TakeWhileSink.prototype.event = function (t, x) { if (!this.active) { return; } var p = this.p; this.active = p(x); if (this.active) { this.sink.event(t, x); } else { this.dispose(); this.sink.end(t, x); } }; TakeWhileSink.prototype.dispose = function () { return this.disposable.dispose(); }; function skipWhile(p, stream) { return new Stream(new SkipWhile(p, stream.source)); } function SkipWhile(p, source) { this.p = p; this.source = source; } SkipWhile.prototype.run = function (sink, scheduler) { return this.source.run(new SkipWhileSink(this.p, sink), scheduler); }; function SkipWhileSink(p, sink) { this.p = p; this.sink = sink; this.skipping = true; } SkipWhileSink.prototype.end = Sink.prototype.end; SkipWhileSink.prototype.error = Sink.prototype.error; SkipWhileSink.prototype.event = function (t, x) { if (this.skipping) { var p = this.p; this.skipping = p(x); if (this.skipping) { return; } } this.sink.event(t, x); }; /***/ }, /* 67 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var dispose = __webpack_require__(2); exports.switch = switchLatest; /** * Given a stream of streams, return a new stream that adopts the behavior * of the most recent inner stream. * @param {Stream} stream of streams on which to switch * @returns {Stream} switching stream */ function switchLatest(stream) { return new Stream(new Switch(stream.source)); } function Switch(source) { this.source = source; } Switch.prototype.run = function (sink, scheduler) { var switchSink = new SwitchSink(sink, scheduler); return dispose.all(switchSink, this.source.run(switchSink, scheduler)); }; function SwitchSink(sink, scheduler) { this.sink = sink; this.scheduler = scheduler; this.current = null; this.ended = false; } SwitchSink.prototype.event = function (t, stream) { this._disposeCurrent(t); // TODO: capture the result of this dispose this.current = new Segment(t, Infinity, this, this.sink); this.current.disposable = stream.source.run(this.current, this.scheduler); }; SwitchSink.prototype.end = function (t, x) { this.ended = true; this._checkEnd(t, x); }; SwitchSink.prototype.error = function (t, e) { this.ended = true; this.sink.error(t, e); }; SwitchSink.prototype.dispose = function () { return this._disposeCurrent(0); }; SwitchSink.prototype._disposeCurrent = function (t) { if (this.current !== null) { return this.current._dispose(t); } }; SwitchSink.prototype._disposeInner = function (t, inner) { inner._dispose(t); // TODO: capture the result of this dispose if (inner === this.current) { this.current = null; } }; SwitchSink.prototype._checkEnd = function (t, x) { if (this.ended && this.current === null) { this.sink.end(t, x); } }; SwitchSink.prototype._endInner = function (t, x, inner) { this._disposeInner(t, inner); this._checkEnd(t, x); }; SwitchSink.prototype._errorInner = function (t, e, inner) { this._disposeInner(t, inner); this.sink.error(t, e); }; function Segment(min, max, outer, sink) { this.min = min; this.max = max; this.outer = outer; this.sink = sink; this.disposable = dispose.empty(); } Segment.prototype.event = function (t, x) { if (t < this.max) { this.sink.event(Math.max(t, this.min), x); } }; Segment.prototype.end = function (t, x) { this.outer._endInner(Math.max(t, this.min), x, this); }; Segment.prototype.error = function (t, e) { this.outer._errorInner(Math.max(t, this.min), e, this); }; Segment.prototype._dispose = function (t) { this.max = t; dispose.tryDispose(t, this.disposable, this.sink); }; /***/ }, /* 68 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var Pipe = __webpack_require__(1); var dispose = __webpack_require__(2); var join = __webpack_require__(26).join; exports.during = during; exports.takeUntil = takeUntil; exports.skipUntil = skipUntil; function takeUntil(signal, stream) { return new Stream(new Until(signal.source, stream.source)); } function skipUntil(signal, stream) { return new Stream(new Since(signal.source, stream.source)); } function during(timeWindow, stream) { return takeUntil(join(timeWindow), skipUntil(timeWindow, stream)); } function Until(maxSignal, source) { this.maxSignal = maxSignal; this.source = source; } Until.prototype.run = function (sink, scheduler) { var min = new Bound(-Infinity, sink); var max = new UpperBound(this.maxSignal, sink, scheduler); var disposable = this.source.run(new TimeWindowSink(min, max, sink), scheduler); return dispose.all([min, max, disposable]); }; function Since(minSignal, source) { this.minSignal = minSignal; this.source = source; } Since.prototype.run = function (sink, scheduler) { var min = new LowerBound(this.minSignal, sink, scheduler); var max = new Bound(Infinity, sink); var disposable = this.source.run(new TimeWindowSink(min, max, sink), scheduler); return dispose.all([min, max, disposable]); }; function Bound(value, sink) { this.value = value; this.sink = sink; } Bound.prototype.error = Pipe.prototype.error; Bound.prototype.event = noop; Bound.prototype.end = noop; Bound.prototype.dispose = noop; function TimeWindowSink(min, max, sink) { this.min = min; this.max = max; this.sink = sink; } TimeWindowSink.prototype.event = function (t, x) { if (t >= this.min.value && t < this.max.value) { this.sink.event(t, x); } }; TimeWindowSink.prototype.error = Pipe.prototype.error; TimeWindowSink.prototype.end = Pipe.prototype.end; function LowerBound(signal, sink, scheduler) { this.value = Infinity; this.sink = sink; this.disposable = signal.run(this, scheduler); } LowerBound.prototype.event = function (t /*, x */) { if (t < this.value) { this.value = t; } }; LowerBound.prototype.end = noop; LowerBound.prototype.error = Pipe.prototype.error; LowerBound.prototype.dispose = function () { return this.disposable.dispose(); }; function UpperBound(signal, sink, scheduler) { this.value = Infinity; this.sink = sink; this.disposable = signal.run(this, scheduler); } UpperBound.prototype.event = function (t, x) { if (t < this.value) { this.value = t; this.sink.end(t, x); } }; UpperBound.prototype.end = noop; UpperBound.prototype.error = Pipe.prototype.error; UpperBound.prototype.dispose = function () { return this.disposable.dispose(); }; function noop() {} /***/ }, /* 69 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var Sink = __webpack_require__(1); exports.timestamp = timestamp; function timestamp(stream) { return new Stream(new Timestamp(stream.source)); } function Timestamp(source) { this.source = source; } Timestamp.prototype.run = function (sink, scheduler) { return this.source.run(new TimestampSink(sink), scheduler); }; function TimestampSink(sink) { this.sink = sink; } TimestampSink.prototype.end = Sink.prototype.end; TimestampSink.prototype.error = Sink.prototype.error; TimestampSink.prototype.event = function (t, x) { this.sink.event(t, { time: t, value: x }); }; /***/ }, /* 70 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); exports.transduce = transduce; /** * Transform a stream by passing its events through a transducer. * @param {function} transducer transducer function * @param {Stream} stream stream whose events will be passed through the * transducer * @return {Stream} stream of events transformed by the transducer */ function transduce(transducer, stream) { return new Stream(new Transduce(transducer, stream.source)); } function Transduce(transducer, source) { this.transducer = transducer; this.source = source; } Transduce.prototype.run = function (sink, scheduler) { var xf = this.transducer(new Transformer(sink)); return this.source.run(new TransduceSink(getTxHandler(xf), sink), scheduler); }; function TransduceSink(adapter, sink) { this.xf = adapter; this.sink = sink; } TransduceSink.prototype.event = function (t, x) { var next = this.xf.step(t, x); return this.xf.isReduced(next) ? this.sink.end(t, this.xf.getResult(next)) : next; }; TransduceSink.prototype.end = function (t, x) { return this.xf.result(x); }; TransduceSink.prototype.error = function (t, e) { return this.sink.error(t, e); }; function Transformer(sink) { this.time = -Infinity; this.sink = sink; } Transformer.prototype['@@transducer/init'] = Transformer.prototype.init = function () {}; Transformer.prototype['@@transducer/step'] = Transformer.prototype.step = function (t, x) { if (!isNaN(t)) { this.time = Math.max(t, this.time); } return this.sink.event(this.time, x); }; Transformer.prototype['@@transducer/result'] = Transformer.prototype.result = function (x) { return this.sink.end(this.time, x); }; /** * Given an object supporting the new or legacy transducer protocol, * create an adapter for it. * @param {object} tx transform * @returns {TxAdapter|LegacyTxAdapter} */ function getTxHandler(tx) { return typeof tx['@@transducer/step'] === 'function' ? new TxAdapter(tx) : new LegacyTxAdapter(tx); } /** * Adapter for new official transducer protocol * @param {object} tx transform * @constructor */ function TxAdapter(tx) { this.tx = tx; } TxAdapter.prototype.step = function (t, x) { return this.tx['@@transducer/step'](t, x); }; TxAdapter.prototype.result = function (x) { return this.tx['@@transducer/result'](x); }; TxAdapter.prototype.isReduced = function (x) { return x != null && x['@@transducer/reduced']; }; TxAdapter.prototype.getResult = function (x) { return x['@@transducer/value']; }; /** * Adapter for older transducer protocol * @param {object} tx transform * @constructor */ function LegacyTxAdapter(tx) { this.tx = tx; } LegacyTxAdapter.prototype.step = function (t, x) { return this.tx.step(t, x); }; LegacyTxAdapter.prototype.result = function (x) { return this.tx.result(x); }; LegacyTxAdapter.prototype.isReduced = function (x) { return x != null && x.__transducers_reduced__; }; LegacyTxAdapter.prototype.getResult = function (x) { return x.value; }; /***/ }, /* 71 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var transform = __webpack_require__(12); var core = __webpack_require__(7); var Sink = __webpack_require__(1); var IndexSink = __webpack_require__(14); var dispose = __webpack_require__(2); var base = __webpack_require__(3); var invoke = __webpack_require__(13); var Queue = __webpack_require__(53); var map = base.map; var tail = base.tail; exports.zip = zip; exports.zipArray = zipArray; /** * Combine streams pairwise (or tuple-wise) by index by applying f to values * at corresponding indices. The returned stream ends when any of the input * streams ends. * @param {function} f function to combine values * @returns {Stream} new stream with items at corresponding indices combined * using f */ function zip(f /*,...streams */) { return zipArray(f, tail(arguments)); } /** * Combine streams pairwise (or tuple-wise) by index by applying f to values * at corresponding indices. The returned stream ends when any of the input * streams ends. * @param {function} f function to combine values * @param {[Stream]} streams streams to zip using f * @returns {Stream} new stream with items at corresponding indices combined * using f */ function zipArray(f, streams) { return streams.length === 0 ? core.empty() : streams.length === 1 ? transform.map(f, streams[0]) : new Stream(new Zip(f, map(getSource, streams))); } function getSource(stream) { return stream.source; } function Zip(f, sources) { this.f = f; this.sources = sources; } Zip.prototype.run = function (sink, scheduler) { var l = this.sources.length; var disposables = new Array(l); var sinks = new Array(l); var buffers = new Array(l); var zipSink = new ZipSink(this.f, buffers, sinks, sink); for (var indexSink, i = 0; i < l; ++i) { buffers[i] = new Queue(); indexSink = sinks[i] = new IndexSink(i, zipSink); disposables[i] = this.sources[i].run(indexSink, scheduler); } return dispose.all(disposables); }; function ZipSink(f, buffers, sinks, sink) { this.f = f; this.sinks = sinks; this.sink = sink; this.buffers = buffers; } ZipSink.prototype.event = function (t, indexedValue) { var buffers = this.buffers; var buffer = buffers[indexedValue.index]; buffer.push(indexedValue.value); if (buffer.length() === 1) { if (!ready(this.buffers)) { return; } emitZipped(this.f, t, buffers, this.sink); if (ended(this.buffers, this.sinks)) { this.sink.end(t, void 0); } } }; ZipSink.prototype.end = function (t, indexedValue) { var buffer = this.buffers[indexedValue.index]; if (buffer.isEmpty()) { this.sink.end(t, indexedValue.value); } }; ZipSink.prototype.error = Sink.prototype.error; function emitZipped(f, t, buffers, sink) { sink.event(t, invoke(f, map(head, buffers))); } function head(buffer) { return buffer.shift(); } function ended(buffers, sinks) { for (var i = 0, l = buffers.length; i < l; ++i) { if (buffers[i].isEmpty() && !sinks[i].active) { return true; } } return false; } function ready(buffers) { for (var i = 0, l = buffers.length; i < l; ++i) { if (buffers[i].isEmpty()) { return false; } } return true; } /***/ }, /* 72 */ /***/ function(module, exports) { "use strict"; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ module.exports = Disposable; /** * Create a new Disposable which will dispose its underlying resource. * @param {function} dispose function * @param {*?} data any data to be passed to disposer function * @constructor */ function Disposable(dispose, data) { this._dispose = dispose; this._data = data; } Disposable.prototype.dispose = function () { return this._dispose(this._data); }; /***/ }, /* 73 */ /***/ function(module, exports) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ module.exports = SettableDisposable; function SettableDisposable() { this.disposable = void 0; this.disposed = false; this._resolve = void 0; var self = this; this.result = new Promise(function (resolve) { self._resolve = resolve; }); } SettableDisposable.prototype.setDisposable = function (disposable) { if (this.disposable !== void 0) { throw new Error('setDisposable called more than once'); } this.disposable = disposable; if (this.disposed) { this._resolve(disposable.dispose()); } }; SettableDisposable.prototype.dispose = function () { if (this.disposed) { return this.result; } this.disposed = true; if (this.disposable !== void 0) { this.result = this.disposable.dispose(); } return this.result; }; /***/ }, /* 74 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Pipe = __webpack_require__(1); module.exports = FilterMap; function FilterMap(p, f, source) { this.p = p; this.f = f; this.source = source; } FilterMap.prototype.run = function (sink, scheduler) { return this.source.run(new FilterMapSink(this.p, this.f, sink), scheduler); }; function FilterMapSink(p, f, sink) { this.p = p; this.f = f; this.sink = sink; } FilterMapSink.prototype.event = function (t, x) { var f = this.f; var p = this.p; p(x) && this.sink.event(t, f(x)); }; FilterMapSink.prototype.end = Pipe.prototype.end; FilterMapSink.prototype.error = Pipe.prototype.error; /***/ }, /* 75 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var base = __webpack_require__(3); module.exports = Scheduler; function ScheduledTask(delay, period, task, scheduler) { this.time = delay; this.period = period; this.task = task; this.scheduler = scheduler; this.active = true; } ScheduledTask.prototype.run = function () { return this.task.run(this.time); }; ScheduledTask.prototype.error = function (e) { return this.task.error(this.time, e); }; ScheduledTask.prototype.cancel = function () { this.scheduler.cancel(this); return this.task.dispose(); }; function runTask(task) { try { return task.run(); } catch (e) { return task.error(e); } } function Scheduler(timer) { this.timer = timer; this._timer = null; this._nextArrival = 0; this._tasks = []; var self = this; this._runReadyTasksBound = function () { self._runReadyTasks(self.now()); }; } Scheduler.prototype.now = function () { return this.timer.now(); }; Scheduler.prototype.asap = function (task) { return this.schedule(0, -1, task); }; Scheduler.prototype.delay = function (delay, task) { return this.schedule(delay, -1, task); }; Scheduler.prototype.periodic = function (period, task) { return this.schedule(0, period, task); }; Scheduler.prototype.schedule = function (delay, period, task) { var now = this.now(); var st = new ScheduledTask(now + Math.max(0, delay), period, task, this); insertByTime(st, this._tasks); this._scheduleNextRun(now); return st; }; Scheduler.prototype.cancel = function (task) { task.active = false; var i = binarySearch(task.time, this._tasks); if (i >= 0 && i < this._tasks.length) { var at = base.findIndex(task, this._tasks[i].events); if (at >= 0) { this._tasks[i].events.splice(at, 1); this._reschedule(); } } }; Scheduler.prototype.cancelAll = function (f) { for (var i = 0; i < this._tasks.length; ++i) { removeAllFrom(f, this._tasks[i]); } this._reschedule(); }; function removeAllFrom(f, timeslot) { timeslot.events = base.removeAll(f, timeslot.events); } Scheduler.prototype._reschedule = function () { if (this._tasks.length === 0) { this._unschedule(); } else { this._scheduleNextRun(this.now()); } }; Scheduler.prototype._unschedule = function () { this.timer.clearTimer(this._timer); this._timer = null; }; Scheduler.prototype._scheduleNextRun = function (now) { if (this._tasks.length === 0) { return; } var nextArrival = this._tasks[0].time; if (this._timer === null) { this._scheduleNextArrival(nextArrival, now); } else if (nextArrival < this._nextArrival) { this._unschedule(); this._scheduleNextArrival(nextArrival, now); } }; Scheduler.prototype._scheduleNextArrival = function (nextArrival, now) { this._nextArrival = nextArrival; var delay = Math.max(0, nextArrival - now); this._timer = this.timer.setTimer(this._runReadyTasksBound, delay); }; Scheduler.prototype._runReadyTasks = function (now) { this._timer = null; this._tasks = this._findAndRunTasks(now); this._scheduleNextRun(this.now()); }; Scheduler.prototype._findAndRunTasks = function (now) { var tasks = this._tasks; var l = tasks.length; var i = 0; while (i < l && tasks[i].time <= now) { ++i; } this._tasks = tasks.slice(i); // Run all ready tasks for (var j = 0; j < i; ++j) { this._tasks = runTasks(tasks[j], this._tasks); } return this._tasks; }; function runTasks(timeslot, tasks) { var events = timeslot.events; for (var i = 0; i < events.length; ++i) { var task = events[i]; if (task.active) { runTask(task); // Reschedule periodic repeating tasks // Check active again, since a task may have canceled itself if (task.period >= 0) { task.time = task.time + task.period; insertByTime(task, tasks); } } } return tasks; } function insertByTime(task, timeslots) { var l = timeslots.length; if (l === 0) { timeslots.push(newTimeslot(task.time, [task])); return; } var i = binarySearch(task.time, timeslots); if (i >= l) { timeslots.push(newTimeslot(task.time, [task])); } else if (task.time === timeslots[i].time) { timeslots[i].events.push(task); } else { timeslots.splice(i, 0, newTimeslot(task.time, [task])); } } function binarySearch(t, sortedArray) { var lo = 0; var hi = sortedArray.length; var mid, y; while (lo < hi) { mid = Math.floor((lo + hi) / 2); y = sortedArray[mid]; if (t === y.time) { return mid; } else if (t < y.time) { hi = mid; } else { lo = mid + 1; } } return hi; } function newTimeslot(t, events) { return { time: t, events: events }; } /***/ }, /* 76 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Scheduler = __webpack_require__(75); var setTimeoutTimer = __webpack_require__(78); var nodeTimer = __webpack_require__(77); var isNode = (typeof process === 'undefined' ? 'undefined' : _typeof(process)) === 'object' && typeof process.nextTick === 'function'; module.exports = new Scheduler(isNode ? nodeTimer : setTimeoutTimer); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(17))) /***/ }, /* 77 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var defer = __webpack_require__(27); /*global setTimeout, clearTimeout*/ function Task(f) { this.f = f; this.active = true; } Task.prototype.run = function () { if (!this.active) { return; } var f = this.f; return f(); }; Task.prototype.error = function (e) { throw e; }; Task.prototype.cancel = function () { this.active = false; }; function runAsTask(f) { var task = new Task(f); defer(task); return task; } module.exports = { now: Date.now, setTimer: function setTimer(f, dt) { return dt <= 0 ? runAsTask(f) : setTimeout(f, dt); }, clearTimer: function clearTimer(t) { return t instanceof Task ? t.cancel() : clearTimeout(t); } }; /***/ }, /* 78 */ /***/ function(module, exports) { "use strict"; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ /*global setTimeout, clearTimeout*/ module.exports = { now: Date.now, setTimer: function setTimer(f, dt) { return setTimeout(f, dt); }, clearTimer: function clearTimer(t) { return clearTimeout(t); } }; /***/ }, /* 79 */ /***/ function(module, exports) { "use strict"; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ module.exports = Observer; /** * Sink that accepts functions to apply to each event, and to end, and error * signals. * @constructor */ function Observer(event, end, error, disposable) { this._event = event; this._end = end; this._error = error; this._disposable = disposable; this.active = true; } Observer.prototype.event = function (t, x) { if (!this.active) { return; } this._event(x); }; Observer.prototype.end = function (t, x) { if (!this.active) { return; } this.active = false; disposeThen(this._end, this._error, this._disposable, x); }; Observer.prototype.error = function (t, e) { this.active = false; disposeThen(this._error, this._error, this._disposable, e); }; function disposeThen(end, error, disposable, x) { Promise.resolve(disposable.dispose()).then(function () { end(x); }, error); } /***/ }, /* 80 */ /***/ function(module, exports) { "use strict"; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ module.exports = SafeSink; function SafeSink(sink) { this.sink = sink; this.active = true; } SafeSink.prototype.event = function (t, x) { if (!this.active) { return; } this.sink.event(t, x); }; SafeSink.prototype.end = function (t, x) { if (!this.active) { return; } this.disable(); this.sink.end(t, x); }; SafeSink.prototype.error = function (t, e) { this.disable(); this.sink.error(t, e); }; SafeSink.prototype.disable = function () { this.active = false; return this.sink; }; /***/ }, /* 81 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var DeferredSink = __webpack_require__(33); var dispose = __webpack_require__(2); var tryEvent = __webpack_require__(9); module.exports = EventEmitterSource; function EventEmitterSource(event, source) { this.event = event; this.source = source; } EventEmitterSource.prototype.run = function (sink, scheduler) { // NOTE: Because EventEmitter allows events in the same call stack as // a listener is added, use a DeferredSink to buffer events // until the stack clears, then propagate. This maintains most.js's // invariant that no event will be delivered in the same call stack // as an observer begins observing. var dsink = new DeferredSink(sink); function addEventVariadic(a) { var l = arguments.length; if (l > 1) { var arr = new Array(l); for (var i = 0; i < l; ++i) { arr[i] = arguments[i]; } tryEvent.tryEvent(scheduler.now(), arr, dsink); } else { tryEvent.tryEvent(scheduler.now(), a, dsink); } } this.source.addListener(this.event, addEventVariadic); return dispose.create(disposeEventEmitter, { target: this, addEvent: addEventVariadic }); }; function disposeEventEmitter(info) { var target = info.target; target.source.removeListener(target.event, info.addEvent); } /***/ }, /* 82 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var dispose = __webpack_require__(2); var tryEvent = __webpack_require__(9); module.exports = EventTargetSource; function EventTargetSource(event, source, capture) { this.event = event; this.source = source; this.capture = capture; } EventTargetSource.prototype.run = function (sink, scheduler) { function addEvent(e) { tryEvent.tryEvent(scheduler.now(), e, sink); } this.source.addEventListener(this.event, addEvent, this.capture); return dispose.create(disposeEventTarget, { target: this, addEvent: addEvent }); }; function disposeEventTarget(info) { var target = info.target; target.source.removeEventListener(target.event, info.addEvent, target.capture); } /***/ }, /* 83 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var MulticastSource = __webpack_require__(5).MulticastSource; var DeferredSink = __webpack_require__(33); var tryEvent = __webpack_require__(9); exports.create = create; function create(run) { return new Stream(new MulticastSource(new SubscriberSource(run))); } function SubscriberSource(subscribe) { this._subscribe = subscribe; } SubscriberSource.prototype.run = function (sink, scheduler) { return new Subscription(new DeferredSink(sink), scheduler, this._subscribe); }; function Subscription(sink, scheduler, subscribe) { this.sink = sink; this.scheduler = scheduler; this.active = true; this._unsubscribe = this._init(subscribe); } Subscription.prototype._init = function (subscribe) { var s = this; try { return subscribe(add, end, error); } catch (e) { error(e); } function add(x) { s._add(x); } function end(x) { s._end(x); } function error(e) { s._error(e); } }; Subscription.prototype._add = function (x) { if (!this.active) { return; } tryEvent.tryEvent(this.scheduler.now(), x, this.sink); }; Subscription.prototype._end = function (x) { if (!this.active) { return; } this.active = false; tryEvent.tryEnd(this.scheduler.now(), x, this.sink); }; Subscription.prototype._error = function (x) { this.active = false; this.sink.error(this.scheduler.now(), x); }; Subscription.prototype.dispose = function () { this.active = false; if (typeof this._unsubscribe === 'function') { return this._unsubscribe.call(void 0); } }; /***/ }, /* 84 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var fromArray = __webpack_require__(85).fromArray; var isIterable = __webpack_require__(31).isIterable; var fromIterable = __webpack_require__(87).fromIterable; var isArrayLike = __webpack_require__(3).isArrayLike; exports.from = from; function from(a) { if (Array.isArray(a) || isArrayLike(a)) { return fromArray(a); } if (isIterable(a)) { return fromIterable(a); } throw new TypeError('not iterable: ' + a); } /***/ }, /* 85 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var PropagateTask = __webpack_require__(6); exports.fromArray = fromArray; function fromArray(a) { return new Stream(new ArraySource(a)); } function ArraySource(a) { this.array = a; } ArraySource.prototype.run = function (sink, scheduler) { return new ArrayProducer(this.array, sink, scheduler); }; function ArrayProducer(array, sink, scheduler) { this.scheduler = scheduler; this.task = new PropagateTask(runProducer, array, sink); scheduler.asap(this.task); } ArrayProducer.prototype.dispose = function () { return this.task.dispose(); }; function runProducer(t, array, sink) { produce(this, array, sink); } function produce(task, array, sink) { for (var i = 0, l = array.length; i < l && task.active; ++i) { sink.event(0, array[i]); } task.active && end(); function end() { sink.end(0); } } /***/ }, /* 86 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var MulticastSource = __webpack_require__(5).MulticastSource; var EventTargetSource = __webpack_require__(82); var EventEmitterSource = __webpack_require__(81); exports.fromEvent = fromEvent; /** * Create a stream from an EventTarget, such as a DOM Node, or EventEmitter. * @param {String} event event type name, e.g. 'click' * @param {EventTarget|EventEmitter} source EventTarget or EventEmitter * @param {boolean?} useCapture for DOM events, whether to use * capturing--passed as 3rd parameter to addEventListener. * @returns {Stream} stream containing all events of the specified type * from the source. */ function fromEvent(event, source /*, useCapture = false */) { var s; if (typeof source.addEventListener === 'function' && typeof source.removeEventListener === 'function') { var capture = arguments.length > 2 && !!arguments[2]; s = new MulticastSource(new EventTargetSource(event, source, capture)); } else if (typeof source.addListener === 'function' && typeof source.removeListener === 'function') { s = new EventEmitterSource(event, source); } else { throw new Error('source must support addEventListener/removeEventListener or addListener/removeListener'); } return new Stream(s); } /***/ }, /* 87 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var getIterator = __webpack_require__(31).getIterator; var PropagateTask = __webpack_require__(6); exports.fromIterable = fromIterable; function fromIterable(iterable) { return new Stream(new IterableSource(iterable)); } function IterableSource(iterable) { this.iterable = iterable; } IterableSource.prototype.run = function (sink, scheduler) { return new IteratorProducer(getIterator(this.iterable), sink, scheduler); }; function IteratorProducer(iterator, sink, scheduler) { this.scheduler = scheduler; this.iterator = iterator; this.task = new PropagateTask(runProducer, this, sink); scheduler.asap(this.task); } IteratorProducer.prototype.dispose = function () { return this.task.dispose(); }; function runProducer(t, producer, sink) { var x = producer.iterator.next(); if (x.done) { sink.end(t, x.value); } else { sink.event(t, x.value); } producer.scheduler.asap(producer.task); } /***/ }, /* 88 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var base = __webpack_require__(3); exports.generate = generate; /** * Compute a stream using an *async* generator, which yields promises * to control event times. * @param f * @returns {Stream} */ function generate(f /*, ...args */) { return new Stream(new GenerateSource(f, base.tail(arguments))); } function GenerateSource(f, args) { this.f = f; this.args = args; } GenerateSource.prototype.run = function (sink, scheduler) { return new Generate(this.f.apply(void 0, this.args), sink, scheduler); }; function Generate(iterator, sink, scheduler) { this.iterator = iterator; this.sink = sink; this.scheduler = scheduler; this.active = true; var self = this; function err(e) { self.sink.error(self.scheduler.now(), e); } Promise.resolve(this).then(next).catch(err); } function next(generate, x) { return generate.active ? handle(generate, generate.iterator.next(x)) : x; } function handle(generate, result) { if (result.done) { return generate.sink.end(generate.scheduler.now(), result.value); } return Promise.resolve(result.value).then(function (x) { return emit(generate, x); }, function (e) { return error(generate, e); }); } function emit(generate, x) { generate.sink.event(generate.scheduler.now(), x); return next(generate, x); } function error(generate, e) { return handle(generate, generate.iterator.throw(e)); } Generate.prototype.dispose = function () { this.active = false; }; /***/ }, /* 89 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); exports.iterate = iterate; /** * Compute a stream by iteratively calling f to produce values * Event times may be controlled by returning a Promise from f * @param {function(x:*):*|Promise<*>} f * @param {*} x initial value * @returns {Stream} */ function iterate(f, x) { return new Stream(new IterateSource(f, x)); } function IterateSource(f, x) { this.f = f; this.value = x; } IterateSource.prototype.run = function (sink, scheduler) { return new Iterate(this.f, this.value, sink, scheduler); }; function Iterate(f, initial, sink, scheduler) { this.f = f; this.sink = sink; this.scheduler = scheduler; this.active = true; var x = initial; var self = this; function err(e) { self.sink.error(self.scheduler.now(), e); } function start(iterate) { return stepIterate(iterate, x); } Promise.resolve(this).then(start).catch(err); } Iterate.prototype.dispose = function () { this.active = false; }; function stepIterate(iterate, x) { iterate.sink.event(iterate.scheduler.now(), x); if (!iterate.active) { return x; } var f = iterate.f; return Promise.resolve(f(x)).then(function (y) { return continueIterate(iterate, y); }); } function continueIterate(iterate, x) { return !iterate.active ? iterate.value : stepIterate(iterate, x); } /***/ }, /* 90 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); var dispose = __webpack_require__(2); var MulticastSource = __webpack_require__(5).MulticastSource; var PropagateTask = __webpack_require__(6); exports.periodic = periodic; /** * Create a stream that emits the current time periodically * @param {Number} period periodicity of events in millis * @param {*) value value to emit each period * @returns {Stream} new stream that emits the current time every period */ function periodic(period, value) { return new Stream(new MulticastSource(new Periodic(period, value))); } function Periodic(period, value) { this.period = period; this.value = value; } Periodic.prototype.run = function (sink, scheduler) { var task = scheduler.periodic(this.period, new PropagateTask(emit, this.value, sink)); return dispose.create(cancelTask, task); }; function cancelTask(task) { task.cancel(); } function emit(t, x, sink) { sink.event(t, x); } /***/ }, /* 91 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** @license MIT License (c) copyright 2010-2016 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ var Stream = __webpack_require__(0); exports.unfold = unfold; /** * Compute a stream by unfolding tuples of future values from a seed value * Event times may be controlled by returning a Promise from f * @param {function(seed:*):{value:*, seed:*, done:boolean}|Promise<{value:*, seed:*, done:boolean}>} f unfolding function accepts * a seed and returns a new tuple with a value, new seed, and boolean done flag. * If tuple.done is true, the stream will end. * @param {*} seed seed value * @returns {Stream} stream containing all value of all tuples produced by the * unfolding function. */ function unfold(f, seed) { return new Stream(new UnfoldSource(f, seed)); } function UnfoldSource(f, seed) { this.f = f; this.value = seed; } UnfoldSource.prototype.run = function (sink, scheduler) { return new Unfold(this.f, this.value, sink, scheduler); }; function Unfold(f, x, sink, scheduler) { this.f = f; this.sink = sink; this.scheduler = scheduler; this.active = true; var self = this; function err(e) { self.sink.error(self.scheduler.now(), e); } function start(unfold) { return stepUnfold(unfold, x); } Promise.resolve(this).then(start).catch(err); } Unfold.prototype.dispose = function () { this.active = false; }; function stepUnfold(unfold, x) { var f = unfold.f; return Promise.resolve(f(x)).then(function (tuple) { return continueUnfold(unfold, tuple); }); } function continueUnfold(unfold, tuple) { if (tuple.done) { unfold.sink.end(unfold.scheduler.now(), tuple.value); return tuple.value; } unfold.sink.event(unfold.scheduler.now(), tuple.value); if (!unfold.active) { return tuple.value; } return stepUnfold(unfold, tuple.seed); } /***/ }, /* 92 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = classNameFromVNode; var _selectorParser2 = __webpack_require__(35); var _selectorParser3 = _interopRequireDefault(_selectorParser2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function classNameFromVNode(vNode) { var _selectorParser = (0, _selectorParser3.default)(vNode.sel); var cn = _selectorParser.className; if (!vNode.data) { return cn; } var _vNode$data = vNode.data; var dataClass = _vNode$data.class; var props = _vNode$data.props; if (dataClass) { var c = Object.keys(vNode.data.class).filter(function (cl) { return vNode.data.class[cl]; }); cn += ' ' + c.join(' '); } if (props && props.className) { cn += ' ' + props.className; } return cn.trim(); } /***/ }, /* 93 */ /***/ function(module, exports) { "use strict"; function createElement(tagName) { return document.createElement(tagName); } function createElementNS(namespaceURI, qualifiedName) { return document.createElementNS(namespaceURI, qualifiedName); } function createTextNode(text) { return document.createTextNode(text); } function insertBefore(parentNode, newNode, referenceNode) { parentNode.insertBefore(newNode, referenceNode); } function removeChild(node, child) { node.removeChild(child); } function appendChild(node, child) { node.appendChild(child); } function parentNode(node) { return node.parentElement; } function nextSibling(node) { return node.nextSibling; } function tagName(node) { return node.tagName; } function setTextContent(node, text) { node.textContent = text; } module.exports = { createElement: createElement, createElementNS: createElementNS, createTextNode: createTextNode, appendChild: appendChild, removeChild: removeChild, insertBefore: insertBefore, parentNode: parentNode, nextSibling: nextSibling, tagName: tagName, setTextContent: setTextContent }; /***/ }, /* 94 */ /***/ function(module, exports) { "use strict"; var booleanAttrs = ["allowfullscreen", "async", "autofocus", "autoplay", "checked", "compact", "controls", "declare", "default", "defaultchecked", "defaultmuted", "defaultselected", "defer", "disabled", "draggable", "enabled", "formnovalidate", "hidden", "indeterminate", "inert", "ismap", "itemscope", "loop", "multiple", "muted", "nohref", "noresize", "noshade", "novalidate", "nowrap", "open", "pauseonexit", "readonly", "required", "reversed", "scoped", "seamless", "selected", "sortable", "spellcheck", "translate", "truespeed", "typemustmatch", "visible"]; var booleanAttrsDict = {}; for (var i = 0, len = booleanAttrs.length; i < len; i++) { booleanAttrsDict[booleanAttrs[i]] = true; } function updateAttrs(oldVnode, vnode) { var key, cur, old, elm = vnode.elm, oldAttrs = oldVnode.data.attrs || {}, attrs = vnode.data.attrs || {}; // update modified attributes, add new attributes for (key in attrs) { cur = attrs[key]; old = oldAttrs[key]; if (old !== cur) { // TODO: add support to namespaced attributes (setAttributeNS) if (!cur && booleanAttrsDict[key]) elm.removeAttribute(key);else elm.setAttribute(key, cur); } } //remove removed attributes // use `in` operator since the previous `for` iteration uses it (.i.e. add even attributes with undefined value) // the other option is to remove all attributes with value == undefined for (key in oldAttrs) { if (!(key in attrs)) { elm.removeAttribute(key); } } } module.exports = { create: updateAttrs, update: updateAttrs }; /***/ }, /* 95 */ /***/ function(module, exports) { 'use strict'; function updateClass(oldVnode, vnode) { var cur, name, elm = vnode.elm, oldClass = oldVnode.data.class || {}, klass = vnode.data.class || {}; for (name in oldClass) { if (!klass[name]) { elm.classList.remove(name); } } for (name in klass) { cur = klass[name]; if (cur !== oldClass[name]) { elm.classList[cur ? 'add' : 'remove'](name); } } } module.exports = { create: updateClass, update: updateClass }; /***/ }, /* 96 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var is = __webpack_require__(10); function arrInvoker(arr) { return function () { // Special case when length is two, for performance arr.length === 2 ? arr[0](arr[1]) : arr[0].apply(undefined, arr.slice(1)); }; } function fnInvoker(o) { return function (ev) { o.fn(ev); }; } function updateEventListeners(oldVnode, vnode) { var name, cur, old, elm = vnode.elm, oldOn = oldVnode.data.on || {}, on = vnode.data.on; if (!on) return; for (name in on) { cur = on[name]; old = oldOn[name]; if (old === undefined) { if (is.array(cur)) { elm.addEventListener(name, arrInvoker(cur)); } else { cur = { fn: cur }; on[name] = cur; elm.addEventListener(name, fnInvoker(cur)); } } else if (is.array(old)) { // Deliberately modify old array since it's captured in closure created with `arrInvoker` old.length = cur.length; for (var i = 0; i < old.length; ++i) { old[i] = cur[i]; }on[name] = old; } else { old.fn = cur; on[name] = old; } } } module.exports = { create: updateEventListeners, update: updateEventListeners }; /***/ }, /* 97 */ /***/ function(module, exports) { 'use strict'; var raf = typeof window !== 'undefined' && window.requestAnimationFrame || setTimeout; var nextFrame = function nextFrame(fn) { raf(function () { raf(fn); }); }; function setNextFrame(obj, prop, val) { nextFrame(function () { obj[prop] = val; }); } function getTextNodeRect(textNode) { var rect; if (document.createRange) { var range = document.createRange(); range.selectNodeContents(textNode); if (range.getBoundingClientRect) { rect = range.getBoundingClientRect(); } } return rect; } function calcTransformOrigin(isTextNode, textRect, boundingRect) { if (isTextNode) { if (textRect) { //calculate pixels to center of text from left edge of bounding box var relativeCenterX = textRect.left + textRect.width / 2 - boundingRect.left; var relativeCenterY = textRect.top + textRect.height / 2 - boundingRect.top; return relativeCenterX + 'px ' + relativeCenterY + 'px'; } } return '0 0'; //top left } function getTextDx(oldTextRect, newTextRect) { if (oldTextRect && newTextRect) { return oldTextRect.left + oldTextRect.width / 2 - (newTextRect.left + newTextRect.width / 2); } return 0; } function getTextDy(oldTextRect, newTextRect) { if (oldTextRect && newTextRect) { return oldTextRect.top + oldTextRect.height / 2 - (newTextRect.top + newTextRect.height / 2); } return 0; } function isTextElement(elm) { return elm.childNodes.length === 1 && elm.childNodes[0].nodeType === 3; } var removed, created; function pre(oldVnode, vnode) { removed = {}; created = []; } function create(oldVnode, vnode) { var hero = vnode.data.hero; if (hero && hero.id) { created.push(hero.id); created.push(vnode); } } function destroy(vnode) { var hero = vnode.data.hero; if (hero && hero.id) { var elm = vnode.elm; vnode.isTextNode = isTextElement(elm); //is this a text node? vnode.boundingRect = elm.getBoundingClientRect(); //save the bounding rectangle to a new property on the vnode vnode.textRect = vnode.isTextNode ? getTextNodeRect(elm.childNodes[0]) : null; //save bounding rect of inner text node var computedStyle = window.getComputedStyle(elm, null); //get current styles (includes inherited properties) vnode.savedStyle = JSON.parse(JSON.stringify(computedStyle)); //save a copy of computed style values removed[hero.id] = vnode; } } function post() { var i, id, newElm, oldVnode, oldElm, hRatio, wRatio, oldRect, newRect, dx, dy, origTransform, origTransition, newStyle, oldStyle, newComputedStyle, isTextNode, newTextRect, oldTextRect; for (i = 0; i < created.length; i += 2) { id = created[i]; newElm = created[i + 1].elm; oldVnode = removed[id]; if (oldVnode) { isTextNode = oldVnode.isTextNode && isTextElement(newElm); //Are old & new both text? newStyle = newElm.style; newComputedStyle = window.getComputedStyle(newElm, null); //get full computed style for new element oldElm = oldVnode.elm; oldStyle = oldElm.style; //Overall element bounding boxes newRect = newElm.getBoundingClientRect(); oldRect = oldVnode.boundingRect; //previously saved bounding rect //Text node bounding boxes & distances if (isTextNode) { newTextRect = getTextNodeRect(newElm.childNodes[0]); oldTextRect = oldVnode.textRect; dx = getTextDx(oldTextRect, newTextRect); dy = getTextDy(oldTextRect, newTextRect); } else { //Calculate distances between old & new positions dx = oldRect.left - newRect.left; dy = oldRect.top - newRect.top; } hRatio = newRect.height / Math.max(oldRect.height, 1); wRatio = isTextNode ? hRatio : newRect.width / Math.max(oldRect.width, 1); //text scales based on hRatio // Animate new element origTransform = newStyle.transform; origTransition = newStyle.transition; if (newComputedStyle.display === 'inline') //inline elements cannot be transformed newStyle.display = 'inline-block'; //this does not appear to have any negative side effects newStyle.transition = origTransition + 'transform 0s'; newStyle.transformOrigin = calcTransformOrigin(isTextNode, newTextRect, newRect); newStyle.opacity = '0'; newStyle.transform = origTransform + 'translate(' + dx + 'px, ' + dy + 'px) ' + 'scale(' + 1 / wRatio + ', ' + 1 / hRatio + ')'; setNextFrame(newStyle, 'transition', origTransition); setNextFrame(newStyle, 'transform', origTransform); setNextFrame(newStyle, 'opacity', '1'); // Animate old element for (var key in oldVnode.savedStyle) { //re-apply saved inherited properties if (parseInt(key) != key) { var ms = key.substring(0, 2) === 'ms'; var moz = key.substring(0, 3) === 'moz'; var webkit = key.substring(0, 6) === 'webkit'; if (!ms && !moz && !webkit) //ignore prefixed style properties oldStyle[key] = oldVnode.savedStyle[key]; } } oldStyle.position = 'absolute'; oldStyle.top = oldRect.top + 'px'; //start at existing position oldStyle.left = oldRect.left + 'px'; oldStyle.width = oldRect.width + 'px'; //Needed for elements who were sized relative to their parents oldStyle.height = oldRect.height + 'px'; //Needed for elements who were sized relative to their parents oldStyle.margin = 0; //Margin on hero element leads to incorrect positioning oldStyle.transformOrigin = calcTransformOrigin(isTextNode, oldTextRect, oldRect); oldStyle.transform = ''; oldStyle.opacity = '1'; document.body.appendChild(oldElm); setNextFrame(oldStyle, 'transform', 'translate(' + -dx + 'px, ' + -dy + 'px) scale(' + wRatio + ', ' + hRatio + ')'); //scale must be on far right for translate to be correct setNextFrame(oldStyle, 'opacity', '0'); oldElm.addEventListener('transitionend', function (ev) { if (ev.propertyName === 'transform') document.body.removeChild(ev.target); }); } } removed = created = undefined; } module.exports = { pre: pre, create: create, destroy: destroy, post: post }; /***/ }, /* 98 */ /***/ function(module, exports) { 'use strict'; function updateProps(oldVnode, vnode) { var key, cur, old, elm = vnode.elm, oldProps = oldVnode.data.props || {}, props = vnode.data.props || {}; for (key in oldProps) { if (!props[key]) { delete elm[key]; } } for (key in props) { cur = props[key]; old = oldProps[key]; if (old !== cur && (key !== 'value' || elm[key] !== cur)) { elm[key] = cur; } } } module.exports = { create: updateProps, update: updateProps }; /***/ }, /* 99 */ /***/ function(module, exports) { 'use strict'; var raf = typeof window !== 'undefined' && window.requestAnimationFrame || setTimeout; var nextFrame = function nextFrame(fn) { raf(function () { raf(fn); }); }; function setNextFrame(obj, prop, val) { nextFrame(function () { obj[prop] = val; }); } function updateStyle(oldVnode, vnode) { var cur, name, elm = vnode.elm, oldStyle = oldVnode.data.style || {}, style = vnode.data.style || {}, oldHasDel = 'delayed' in oldStyle; for (name in oldStyle) { if (!style[name]) { elm.style[name] = ''; } } for (name in style) { cur = style[name]; if (name === 'delayed') { for (name in style.delayed) { cur = style.delayed[name]; if (!oldHasDel || cur !== oldStyle.delayed[name]) { setNextFrame(elm.style, name, cur); } } } else if (name !== 'remove' && cur !== oldStyle[name]) { elm.style[name] = cur; } } } function applyDestroyStyle(vnode) { var style, name, elm = vnode.elm, s = vnode.data.style; if (!s || !(style = s.destroy)) return; for (name in style) { elm.style[name] = style[name]; } } function applyRemoveStyle(vnode, rm) { var s = vnode.data.style; if (!s || !s.remove) { rm(); return; } var name, elm = vnode.elm, idx, i = 0, maxDur = 0, compStyle, style = s.remove, amount = 0, applied = []; for (name in style) { applied.push(name); elm.style[name] = style[name]; } compStyle = getComputedStyle(elm); var props = compStyle['transition-property'].split(', '); for (; i < props.length; ++i) { if (applied.indexOf(props[i]) !== -1) amount++; } elm.addEventListener('transitionend', function (ev) { if (ev.target === elm) --amount; if (amount === 0) rm(); }); } module.exports = { create: updateStyle, update: updateStyle, destroy: applyDestroyStyle, remove: applyRemoveStyle }; /***/ }, /* 100 */ /***/ function(module, exports, __webpack_require__) { // jshint newcap: false /* global require, module, document, Node */ 'use strict'; var VNode = __webpack_require__(15); var is = __webpack_require__(10); var domApi = __webpack_require__(93); function isUndef(s) { return s === undefined; } function isDef(s) { return s !== undefined; } var emptyNode = VNode('', {}, [], undefined, undefined); function sameVnode(vnode1, vnode2) { return vnode1.key === vnode2.key && vnode1.sel === vnode2.sel; } function createKeyToOldIdx(children, beginIdx, endIdx) { var i, map = {}, key; for (i = beginIdx; i <= endIdx; ++i) { key = children[i].key; if (isDef(key)) map[key] = i; } return map; } var hooks = ['create', 'update', 'remove', 'destroy', 'pre', 'post']; function init(modules, api) { var i, j, cbs = {}; if (isUndef(api)) api = domApi; for (i = 0; i < hooks.length; ++i) { cbs[hooks[i]] = []; for (j = 0; j < modules.length; ++j) { if (modules[j][hooks[i]] !== undefined) cbs[hooks[i]].push(modules[j][hooks[i]]); } } function emptyNodeAt(elm) { return VNode(api.tagName(elm).toLowerCase(), {}, [], undefined, elm); } function createRmCb(childElm, listeners) { return function () { if (--listeners === 0) { var parent = api.parentNode(childElm); api.removeChild(parent, childElm); } }; } function createElm(vnode, insertedVnodeQueue) { var i, thunk, data = vnode.data; if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.init)) i(vnode); if (isDef(i = data.vnode)) { thunk = vnode; vnode = i; } } var elm, children = vnode.children, sel = vnode.sel; if (isDef(sel)) { // Parse selector var hashIdx = sel.indexOf('#'); var dotIdx = sel.indexOf('.', hashIdx); var hash = hashIdx > 0 ? hashIdx : sel.length; var dot = dotIdx > 0 ? dotIdx : sel.length; var tag = hashIdx !== -1 || dotIdx !== -1 ? sel.slice(0, Math.min(hash, dot)) : sel; elm = vnode.elm = isDef(data) && isDef(i = data.ns) ? api.createElementNS(i, tag) : api.createElement(tag); if (hash < dot) elm.id = sel.slice(hash + 1, dot); if (dotIdx > 0) elm.className = sel.slice(dot + 1).replace(/\./g, ' '); if (is.array(children)) { for (i = 0; i < children.length; ++i) { api.appendChild(elm, createElm(children[i], insertedVnodeQueue)); } } else if (is.primitive(vnode.text)) { api.appendChild(elm, api.createTextNode(vnode.text)); } for (i = 0; i < cbs.create.length; ++i) { cbs.create[i](emptyNode, vnode); }i = vnode.data.hook; // Reuse variable if (isDef(i)) { if (i.create) i.create(emptyNode, vnode); if (i.insert) insertedVnodeQueue.push(vnode); } } else { elm = vnode.elm = api.createTextNode(vnode.text); } if (isDef(thunk)) thunk.elm = vnode.elm; return vnode.elm; } function addVnodes(parentElm, before, vnodes, startIdx, endIdx, insertedVnodeQueue) { for (; startIdx <= endIdx; ++startIdx) { api.insertBefore(parentElm, createElm(vnodes[startIdx], insertedVnodeQueue), before); } } function invokeDestroyHook(vnode) { var i, j, data = vnode.data; if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.destroy)) i(vnode); for (i = 0; i < cbs.destroy.length; ++i) { cbs.destroy[i](vnode); }if (isDef(i = vnode.children)) { for (j = 0; j < vnode.children.length; ++j) { invokeDestroyHook(vnode.children[j]); } } if (isDef(i = data.vnode)) invokeDestroyHook(i); } } function removeVnodes(parentElm, vnodes, startIdx, endIdx) { for (; startIdx <= endIdx; ++startIdx) { var i, listeners, rm, ch = vnodes[startIdx]; if (isDef(ch)) { if (isDef(ch.sel)) { invokeDestroyHook(ch); listeners = cbs.remove.length + 1; rm = createRmCb(ch.elm, listeners); for (i = 0; i < cbs.remove.length; ++i) { cbs.remove[i](ch, rm); }if (isDef(i = ch.data) && isDef(i = i.hook) && isDef(i = i.remove)) { i(ch, rm); } else { rm(); } } else { // Text node api.removeChild(parentElm, ch.elm); } } } } function updateChildren(parentElm, oldCh, newCh, insertedVnodeQueue) { var oldStartIdx = 0, newStartIdx = 0; var oldEndIdx = oldCh.length - 1; var oldStartVnode = oldCh[0]; var oldEndVnode = oldCh[oldEndIdx]; var newEndIdx = newCh.length - 1; var newStartVnode = newCh[0]; var newEndVnode = newCh[newEndIdx]; var oldKeyToIdx, idxInOld, elmToMove, before; while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) { if (isUndef(oldStartVnode)) { oldStartVnode = oldCh[++oldStartIdx]; // Vnode has been moved left } else if (isUndef(oldEndVnode)) { oldEndVnode = oldCh[--oldEndIdx]; } else if (sameVnode(oldStartVnode, newStartVnode)) { patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue); oldStartVnode = oldCh[++oldStartIdx]; newStartVnode = newCh[++newStartIdx]; } else if (sameVnode(oldEndVnode, newEndVnode)) { patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue); oldEndVnode = oldCh[--oldEndIdx]; newEndVnode = newCh[--newEndIdx]; } else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue); api.insertBefore(parentElm, oldStartVnode.elm, api.nextSibling(oldEndVnode.elm)); oldStartVnode = oldCh[++oldStartIdx]; newEndVnode = newCh[--newEndIdx]; } else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue); api.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm); oldEndVnode = oldCh[--oldEndIdx]; newStartVnode = newCh[++newStartIdx]; } else { if (isUndef(oldKeyToIdx)) oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx); idxInOld = oldKeyToIdx[newStartVnode.key]; if (isUndef(idxInOld)) { // New element api.insertBefore(parentElm, createElm(newStartVnode, insertedVnodeQueue), oldStartVnode.elm); newStartVnode = newCh[++newStartIdx]; } else { elmToMove = oldCh[idxInOld]; patchVnode(elmToMove, newStartVnode, insertedVnodeQueue); oldCh[idxInOld] = undefined; api.insertBefore(parentElm, elmToMove.elm, oldStartVnode.elm); newStartVnode = newCh[++newStartIdx]; } } } if (oldStartIdx > oldEndIdx) { before = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm; addVnodes(parentElm, before, newCh, newStartIdx, newEndIdx, insertedVnodeQueue); } else if (newStartIdx > newEndIdx) { removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx); } } function patchVnode(oldVnode, vnode, insertedVnodeQueue) { var i, hook; if (isDef(i = vnode.data) && isDef(hook = i.hook) && isDef(i = hook.prepatch)) { i(oldVnode, vnode); } if (isDef(i = oldVnode.data) && isDef(i = i.vnode)) oldVnode = i; if (isDef(i = vnode.data) && isDef(i = i.vnode)) { patchVnode(oldVnode, i, insertedVnodeQueue); vnode.elm = i.elm; return; } var elm = vnode.elm = oldVnode.elm, oldCh = oldVnode.children, ch = vnode.children; if (oldVnode === vnode) return; if (!sameVnode(oldVnode, vnode)) { var parentElm = api.parentNode(oldVnode.elm); elm = createElm(vnode, insertedVnodeQueue); api.insertBefore(parentElm, elm, oldVnode.elm); removeVnodes(parentElm, [oldVnode], 0, 0); return; } if (isDef(vnode.data)) { for (i = 0; i < cbs.update.length; ++i) { cbs.update[i](oldVnode, vnode); }i = vnode.data.hook; if (isDef(i) && isDef(i = i.update)) i(oldVnode, vnode); } if (isUndef(vnode.text)) { if (isDef(oldCh) && isDef(ch)) { if (oldCh !== ch) updateChildren(elm, oldCh, ch, insertedVnodeQueue); } else if (isDef(ch)) { if (isDef(oldVnode.text)) api.setTextContent(elm, ''); addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue); } else if (isDef(oldCh)) { removeVnodes(elm, oldCh, 0, oldCh.length - 1); } else if (isDef(oldVnode.text)) { api.setTextContent(elm, ''); } } else if (oldVnode.text !== vnode.text) { api.setTextContent(elm, vnode.text); } if (isDef(hook) && isDef(i = hook.postpatch)) { i(oldVnode, vnode); } } return function (oldVnode, vnode) { var i, elm, parent; var insertedVnodeQueue = []; for (i = 0; i < cbs.pre.length; ++i) { cbs.pre[i](); }if (isUndef(oldVnode.sel)) { oldVnode = emptyNodeAt(oldVnode); } if (sameVnode(oldVnode, vnode)) { patchVnode(oldVnode, vnode, insertedVnodeQueue); } else { elm = oldVnode.elm; parent = api.parentNode(elm); createElm(vnode, insertedVnodeQueue); if (parent !== null) { api.insertBefore(parent, vnode.elm, api.nextSibling(elm)); removeVnodes(parent, [oldVnode], 0, 0); } } for (i = 0; i < insertedVnodeQueue.length; ++i) { insertedVnodeQueue[i].data.hook.insert(insertedVnodeQueue[i]); } for (i = 0; i < cbs.post.length; ++i) { cbs.post[i](); }return vnode; }; } module.exports = { init: init }; /***/ }, /* 101 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var h = __webpack_require__(36); function init(thunk) { var i, cur = thunk.data; cur.vnode = cur.fn.apply(undefined, cur.args); } function prepatch(oldThunk, thunk) { var i, old = oldThunk.data, cur = thunk.data; var oldArgs = old.args, args = cur.args; cur.vnode = old.vnode; if (old.fn !== cur.fn || oldArgs.length !== args.length) { cur.vnode = cur.fn.apply(undefined, args); return; } for (i = 0; i < args.length; ++i) { if (oldArgs[i] !== args[i]) { cur.vnode = cur.fn.apply(undefined, args); return; } } } module.exports = function (name, fn /* args */) { var i, args = []; for (i = 2; i < arguments.length; ++i) { args[i - 2] = arguments[i]; } return h('thunk' + name, { hook: { init: init, prepatch: prepatch }, fn: fn, args: args }); }; /***/ }, /* 102 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; var _core = __webpack_require__(37); var _core2 = _interopRequireDefault(_core); var _dom = __webpack_require__(16); var _most = __webpack_require__(4); var _code = __webpack_require__(38); var _code2 = _interopRequireDefault(_code); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function createWebSocket(path) { var host = window.location.hostname; if (host == '') host = 'localhost'; var uri = 'ws://' + host + ':3055' + path; var Socket = "MozWebSocket" in window ? MozWebSocket : WebSocket; return new Socket(uri); } var socket = createWebSocket('/'); var websocketsDriver = function websocketsDriver() { return (0, _most.create)(function (add) { socket.onmessage = function (msg) { return add(msg); }; }); }; function main(sources) { mMindex.ret(0); mMZ1.bnd(function (v) { return O.mMt1.bnd(add, v, mMt1).bnd(cube, mMt2).bnd(function () { return mMt3.ret(O.mMt1.x + ' cubed is ' + O.mMt2.x); }); }); mMZ2.bnd(function (v) { return cube(v).bnd(function (w) { return mMt3.ret(v + ' cubed is ' + w); }); }); var messages$ = sources.WS.map(function (e) { mMtem.ret(e.data.split(',')).bnd(function (v) { mMZ10.bnd(function () { return game([v[3], v[4], v[5], v[6]]); }); mMZ11.bnd(function () { return updateScoreboard(v[3]); }); mMZ12.bnd(function () { return mM6.ret(v[2] + ' successfully logged in.'); }); mMZ13.bnd(function () { return updateMessages(v); }); mMZ14.bnd(function () { return mMgoals2.ret('The winner is ' + v[2]); }); mMZ15.bnd(function () { return mMgoals2.ret('A player named ' + O.mMname.x + 'is currently logged in. Page will refresh in 4 seconds.').bnd(refresh); }); mMZ16.bnd(function () { if (O.mMname.x != v[2]) { mMgoals2.ret(v[2] + v[3]); } }); mMZ17.bnd(function () { if (v[3] == 'no file') { mMtaskList.ret([]); } else { process(e.data); } }); mMtemp.ret(e.data.split(',')[0]).bnd(next, 'CA#$42', mMZ10).bnd(next, 'CB#$42', mMZ11).bnd(next, 'CC#$42', mMZ12).bnd(next, 'CD#$42', mMZ13).bnd(next, 'CE#$42', mMZ14).bnd(next, 'EE#$42', mMZ15).bnd(next, 'DE#$42', mMZ16).bnd(next, 'DD#$42', mMZ17); }); }); var updateMessages = function updateMessages(ar) { var sender = ar[2]; mMhelper.ret(ar).bnd(splice, 0, 3, mMhelper).bnd(reduce).bnd(function (v) { return O.mMmsg.bnd(unshift, (0, _dom.h)('div', sender + ': ' + v), O.mMmsg); }); }; var loginPress$ = sources.DOM.select('input#login').events('keypress'); var loginPressAction$ = loginPress$.map(function (e) { var v = e.target.value; if (v == '') { return; } if (e.keyCode == 13) { socket.send("CC#$42" + v); mMname.ret(v.trim()); mM3.ret([]).bnd(mM2.ret); e.target.value = ''; document.getElementById('dice').style.display = 'block'; document.getElementById('rightPanel').style.display = 'block'; document.getElementById('log1').style.display = 'none'; document.getElementById('log2').style.display = 'block'; document.getElementById('gameDiv2').style.display = 'block'; } }); var groupPress$ = sources.DOM.select('input#group').events('keypress'); var groupPressAction$ = groupPress$.map(function (e) { var v = e.target.value; if (e.keyCode == 13) { mMgroup.ret(v); socket.send('CO#$42,' + v + ',' + O.mMname.x.trim() + ',' + v); mMgoals.ret(0); } }); var messagePress$ = sources.DOM.select('input.inputMessage').events('keydown'); var messagePressAction$ = messagePress$.map(function (e) { if (e.keyCode == 13) { socket.send('CD#$42,' + O.mMgroup.x.trim() + ',' + O.mMname.x.trim() + ',' + e.target.value); e.target.value = ''; } }); var task2 = function task(str) { console.log('In taskAction$. str is: ', str); socket.send('TD#$42' + ',' + O.mMgroup.x.trim() + ',' + O.mMname.x.trim() + ',' + '@' + str); }; var newTask$ = sources.DOM.select('input.newTask').events('keydown'); var newTaskAction$ = newTask$.map(function (e) { var ob = {}; var alert = ''; var task = ''; if (e.keyCode == 13) { var ar = e.target.value.split(','); if (ar.length < 3) { alert = 'You should enter "author, responsible party, task" separated by commas'; document.getElementById('alert').innerHTML = alert; } var ar2 = ar.slice(2); console.log('*************************************$$$$$$$$$$$_ar ', ar); if (ar2.length == 1) { task = ar[2]; } if (ar2.length > 1) { task = ar2.reduce(function (a, b) { return a + '$*$*$' + b; }); } if (O.mMar2.x.filter(function (v) { return v.task == task; }).length > 0) { document.getElementById('alert').innerHTML = task + " is already listed."; } else if (ar.length > 2) { O.mMcurrentList.bnd(addString, task + ',yellow, none, false,' + ar[0] + ',' + ar[1], mMtemp).bnd(function (v) { return task2(v); }); e.target.value = ''; document.getElementById('alert').innerHTML = ''; } } }); var process = function process(str) { var a = str.split(","); if (a == undefined) { return; }; if (a.length < 9) { return; }; var ob = {}; var ar = a.slice(3); var s = ar.reduce(function (a, b) { return a + ',' + b; }); console.log('In process. ar and s are: ', ar, s); var tempArray = []; if (ar.length < 6) { return; }; if (ar.length % 6 !== 0) { document.getElementById('alert').innerHTML = 'Error: array length is: ' + length; } mMcurrentList.ret(s); process3(ar); }; var process3 = function process3(a) { var ar5 = []; var keys = Array(a.length / 6).fill(1); keys.map(function (_) { ar5.push({ task: convertBack(a.shift()), color: a.shift(), textDecoration: a.shift(), checked: a.shift() === 'true', author: a.shift(), responsible: a.shift() }); }); mMar2.ret(ar5); process4(ar5); }; var process4 = function process4(a) { var tempArray = []; var keys = Object.keys(a); for (var k in keys) { tempArray.push((0, _dom.h)('div.todo', [(0, _dom.h)('span.task3', { style: { color: a[k].color, textDecoration: a[k].textDecoration } }, 'Task: ' + a[k].task), (0, _dom.h)('br'), (0, _dom.h)('button#edit1', 'Edit'), (0, _dom.h)('input#edit2', { props: { type: 'textarea', value: a[k].task }, style: { display: 'none' } }), (0, _dom.h)('span#author.tao', 'Author: ' + a[k].author + ' / ' + 'Responsibility: ' + a[k].responsible), (0, _dom.h)('br'), (0, _dom.h)('input#cb', { props: { type: 'checkbox', checked: a[k].checked }, style: { color: a[k].color, textDecoration: a[k].textDecoration } }), (0, _dom.h)('label.cbox', { props: { for: '#cb' } }, 'Completed'), (0, _dom.h)('button.delete', 'Delete'), (0, _dom.h)('br'), (0, _dom.h)('hr')])); } mMtaskList.ret(tempArray); }; var colorClick$ = sources.DOM.select('#cb').events('click'); var colorAction$ = colorClick$.map(function (e) { var index = getIndex(e); var s = O.mMcurrentList.x; var ar = s.split(','); var n = 6 * index + 3; var j = 6 * index + 2; var k = 6 * index + 1; var checked = ar[n]; if (checked == 'true') { ar[n] = 'false'; ar[k] = 'yellow'; ar[j] = 'none'; } else { ar[n] = 'true'; ar[k] = 'lightGreen'; ar[j] = 'line-through'; } task2(ar.reduce(function (a, b) { return a + ',' + b; })); }); var edit1$ = sources.DOM.select('#edit1').events('click'); var edit1Action$ = edit1$.map(function (e) { var index = getIndex2(e); O.mMtaskList.x[index].children[3].elm.style.display = 'block'; }); var edit2$ = sources.DOM.select('#edit2').events('keypress'); var edit2Action$ = edit2$.map(function (e) { var v = e.target.value; var index = getIndex2(e); if (e.keyCode == 13) { process2(v, index); O.mMtaskList.x[index].children[3].elm.style.display = 'none'; } }); var process2 = function process2(str, index) { var a = O.mMcurrentList.x; var ar = a.split(','); var task = str.split(',').reduce(function (a, b) { return ar + '$*$*$' + b; }); ar[index * 6] = task; var s = ar.reduce(function (a, b) { return a + ',' + b; }); task2(s); }; var deleteClick$ = sources.DOM.select('.delete').events('click'); var deleteAction$ = deleteClick$.map(function (e) { var index = getIndex(e); var s = O.mMcurrentList.x; var ar = s.split(','); var str = ''; ar.splice(index * 6, 6); if (ar.length > 0) { task2(ar.reduce(function (a, b) { return a + ',' + b; })); } else { socket.send('TX#$42' + ',' + O.mMgroup.x.trim() + ',' + O.mMname.x.trim()); mMtaskList.ret(''); } }); var chatClick$ = sources.DOM.select('#chat2').events('click'); var chatClickAction$ = chatClick$.map(function () { var el = document.getElementById('chatDiv'); el.style.display == 'none' ? el.style.display = 'inline' : el.style.display = 'none'; }); var captionClick$ = sources.DOM.select('#caption').events('click'); var captionClickAction$ = captionClick$.map(function () { var el = document.getElementById('captionDiv'); el.style.display == 'none' ? el.style.display = 'inline' : el.style.display = 'none'; }); var gameClick$ = sources.DOM.select('#game').events('click'); var gameClickAction$ = gameClick$.map(function () { var el = document.getElementById('gameDiv'); el.style.display == 'none' ? el.style.display = 'inline' : el.style.display = 'none'; var el2 = document.getElementById('gameDiv2'); el2.style.display == 'none' ? el2.style.display = 'inline' : el2.style.display = 'none'; }); var runTest$ = sources.DOM.select('#runTest').events('click'); var runTestAction$ = runTest$.map(function () { runTest(); }); var todoClick$ = sources.DOM.select('#todoButton').events('click'); var todoClickAction$ = todoClick$.map(function (e) { var el = document.getElementById('todoDiv'); el.style.display == 'none' ? el.style.display = 'inline' : el.style.display = 'none'; }); var rollClick$ = sources.DOM.select('.roll').events('click'); var rollClickAction$ = rollClick$.map(function (e) { mM13.ret(O.mM13.x - 1); mM8.ret(0); mM3.ret([]); socket.send('CG#$42,' + O.mMgroup.x.trim() + ',' + O.mMname.x.trim() + ',' + -1 + ',' + O.mMgoals.x); socket.send('CA#$42,' + O.mMgroup.x.trim() + ',' + O.mMname.x.trim() + ',6,6,12,20'); }); // ************************************************************************* Original Fibonacci enter var fib2 = function fib2(v) { if (v[2] > 1) { mM$fib.ret([v[1], v[0] + v[1], v[2] - 1]); } else { console.log(v[0]); mM19.ret(v[0]); } }; var fibPress$ = sources.DOM.select('input#code').events('keydown'); var fibPressAction$ = fibPress$.map(function (e) { if (e.target.value == '') { return; }; if (e.keyCode == 13 && Number.isInteger(e.target.value * 1)) { mM21.ret(e.target.value); fib2([0, 1, e.target.value]); } if (e.keyCode == 13 && !Number.isInteger(e.target.value * 1)) { mM19.ret("You didn't provide an integer"); } }); // ************************************************************************* END Original Fibonacci END // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> START PRIME FIB var fibKeyPress5$ = sources.DOM.select('input#fib92').events('keydown'); var primeFib$ = fibKeyPress5$.map(function (e) { if (e.keyCode == 13) { /* var bound; fibsMonad.run([0,1,e.target.value,[]]).bnd(s => bound = Math.ceil(Math.sqrt(s[3][s[3].length - 1]))); if (bound > primesMonad.a[primesMonad.a.length - 1] ) { primesMonad.run([primesMonad.s[0], "from the fibKeyPress5$ handler", bound, primesMonad.a]) } */ var res = fibsMonad.run([0, 1, e.target.value, []]).bnd(function (fibsState) { return fibsMonad.bnd(fpTransformer, primesMonad).bnd(function (primesState) { return tr3(fibsState[3], primesState[3]); }); }); document.getElementById('PF_9').innerHTML = res[0]; document.getElementById('PF_22').innerHTML = res[1]; document.getElementById('primeFibs').innerHTML = res[2]; } }); // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> END basic prime END // <>>><>><><><><>>>><><>< traversal ><><><><><><>>><><><><><><><><><><><>< START traversal window.onload = function (event) { console.log('onopen event: ', event); document.querySelector('input#login').focus(); mMitterfib5.release(200); // mM$prime5.ret([[2], 3, 3]); }; var forwardClick$ = sources.DOM.select('#forward').events('click'); var backClick$ = sources.DOM.select('#back').events('click'); var forwardAction$ = forwardClick$.map(function () { if (O.mMindex.x < O.mMhistorymM1.x.length - 1) { O.mMindex.bnd(add, 1, mMindex).bnd(function (v) { return trav(v); }); } }); var backAction$ = backClick$.map(function () { if (O.mMindex.x > 0) { O.mMindex.bnd(add, -1, mMindex).bnd(function (v) { return trav(v); }); socket.send('DE#$42,' + O.mMgroup.x.trim() + ',' + O.mMname.x.trim() + ', clicked the BACK button. '); } }); var numClick$ = sources.DOM.select('.num').events('click'); var numClickAction$ = numClick$.map(function (e) { console.log(e); if (O.mM3.x.length < 2) { O.mM3.bnd(push, e.target.innerHTML, O.mM3); mMtemp.ret(O.mMhistorymM1.x[O.mMindex.x].x).bnd(splice, e.target.id, 1, mMtemp).bnd(function (v) { return game(v); }); }; if (O.mM3.x.length === 2 && O.mM8.x !== 0) { updateCalc(); }; }).startWith([0, 0, 0, 0]); var opClick$ = sources.DOM.select('.op').events('click'); var opClickAction$ = opClick$.map(function (e) { mM8.ret(e.target.textContent); if (O.mM3.x.length === 2) { updateCalc(); } }); var game = function game(v) { mM1.ret(v); O.mMindex.bnd(add, 1, mMindex).bnd(function (i) { return O.mMhistorymM1.bnd(spliceAdd, i, O.mM1, O.mMhistorymM1); }); document.getElementById('0').innerHTML = O.mM1.x[0]; document.getElementById('1').innerHTML = O.mM1.x[1]; document.getElementById('2').innerHTML = O.mM1.x[2]; document.getElementById('3').innerHTML = O.mM1.x[3]; cleanup(); }; var trav = function trav(v) { document.getElementById('0').innerHTML = O.mMhistorymM1.x[v].x[0]; document.getElementById('1').innerHTML = O.mMhistorymM1.x[v].x[1]; document.getElementById('2').innerHTML = O.mMhistorymM1.x[v].x[2]; document.getElementById('3').innerHTML = O.mMhistorymM1.x[v].x[3]; cleanup(); }; function updateCalc() { O.mM3.bnd(function (x) { return mM7.ret(calc(x[0], O.mM8.x, x[1])).bnd(function (result) { O.mM1.bnd(push, result, mM1).bnd(function (z) { return game(z); }); if (result == 20) { score(O.mM13.x, 1); }; if (result == 18) { score(O.mM13.x, 3); }; }); }); reset(); }; // <>>><>><><><><>>>><><>< traversal ><><><><><><>>><><><><><><><><><><><>< END traversal var testZ = sources.DOM.select('#testZ').events('click'); var testZAction$ = testZ.map(function () { return mMZ1.release(1); }); var testQ = sources.DOM.select('#testQ').events('click'); var testQAction$ = testQ.map(function () { return mMt1.ret(-1).bnd(mM2.ret).bnd(function () { return mMZ1.release(1); }); }); var testW = sources.DOM.select('#testW').events('keypress'); var testWAction$ = testW.map(function (e) { if (e.keyCode == 13) { mMZ2.release(e.target.value); } }); var solve = function solve() { mMZ3.bnd(function (a) { return mMtemp.ret(a).bnd(innerHTML, '', 'quad6', mMtemp).bnd(innerHTML, a + " * x * x ", 'quad5', mMtemp).bnd(function (a) { return mMZ3.bnd(function (b) { return mMtemp.ret(b).bnd(innerHTML, " + " + b + " * x ", 'quad6', mMtemp).bnd(function (b) { return mMZ3.bnd(function (c) { var x = qS1(a, b, c); var y = qS2(a, b, c); document.getElementById('quad5').innerHTML = 'The results are: x = ' + x + ' and x ='; document.getElementById('quad6').innerHTML = y; solve(); }); }); }); }); }); }(); var quad$ = sources.DOM.select('#quad').events('keypress'); var quadAction$ = quad$.map(function (e) { if (e.keyCode == 13) { mMZ3.release(e.target.value); // Releases mMZ (below). document.getElementById('quad').value = ''; } }); var innerHTML = function innerHTML(x, v, u, m) { document.getElementById(u).innerHTML = v; return m.ret(x); }; var dummyClick$ = sources.DOM.select('#dummy').events('click'); var dummyAction$ = dummyClick$.map(function (e) { O.mMdummy.bnd(add, 1, mMdummy); console.log('<><><><><><><><><> In dummyAction$ e is: ', e); console.log(document.getElementById('dummy').click); console.log('<><><><><><><><><>'); var next = O.mM23.x[O.mM23.x.length - 1] * 1 + O.mM23.x[O.mM23.x.length - 2] * 1; O.mM23.bnd(push, next, mM23); document.getElementById('dummy2').innerHTML = O.mM23.x; }); var calcStream$ = (0, _most.merge)(forwardAction$, backAction$, dummyAction$, primeFib$, fibPressAction$, runTestAction$, quadAction$, testWAction$, testZAction$, testQAction$, edit1Action$, edit2Action$, colorAction$, deleteAction$, newTaskAction$, chatClickAction$, gameClickAction$, todoClickAction$, captionClickAction$, groupPressAction$, rollClickAction$, messagePressAction$, loginPressAction$, messages$, numClickAction$, opClickAction$); return { DOM: calcStream$.map(function () { return (0, _dom.h)('div.content', [(0, _dom.h)('div#rightPanel', { style: { display: 'none' } }, [(0, _dom.h)('span#tog', [(0, _dom.h)('button#game', { style: { fontSize: '16px' } }, 'TOGGLE GAME'), (0, _dom.h)('span.tao', ' '), (0, _dom.h)('button#todoButton', { style: { fontSize: '16px' } }, 'TOGGLE TODO LIST'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('button#chat2', { style: { fontSize: '16px' } }, 'TOGGLE CHAT'), (0, _dom.h)('span.tao', ' '), (0, _dom.h)('button#caption', { style: { fontSize: '16px' } }, 'TOGGLE CAPTION')]), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('div#gameDiv', [(0, _dom.h)('span', 'Group: ' + O.mMgroup.x), (0, _dom.h)('br'), (0, _dom.h)('span', 'Goals: ' + O.mMgoals.x), (0, _dom.h)('br'), (0, _dom.h)('span', 'Name: ' + O.mMname.x), (0, _dom.h)('br'), (0, _dom.h)('span', 'player[score][goals]'), (0, _dom.h)('div', O.mMscoreboard.x)]), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('div#todoDiv', [(0, _dom.h)('div#taskList', O.mMtaskList.x), (0, _dom.h)('span', 'Author, Responsible Person, Task: '), (0, _dom.h)('input.newTask')]), (0, _dom.h)('br'), (0, _dom.h)('span#alert'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('div#chatDiv', [(0, _dom.h)('div#messages', [(0, _dom.h)('span', 'Message: '), (0, _dom.h)('input.inputMessage'), (0, _dom.h)('div', O.mMmsg.x)])])]), (0, _dom.h)('div.leftPanel', { style: { width: '60%' } }, [(0, _dom.h)('br'), (0, _dom.h)('a.tao', { props: { href: '#common' } }, 'Common Patterns'), (0, _dom.h)('a.tao', { props: { href: '#tdList' } }, 'Todo List Explanation'), // h('a.tao', {props: {href: '#monads'}}, 'Why Call Them Monads' ), (0, _dom.h)('div#captionDiv', [(0, _dom.h)('h1', 'Motorcycle.js With JS-monads'), (0, _dom.h)('span.tao1', ' A shared, persistent todo list, '), (0, _dom.h)('br'), (0, _dom.h)('span.tao1', ' A websockets simulated dice game with a traversable history, '), (0, _dom.h)('br'), (0, _dom.h)('span.tao1', ' Group chat rooms and more demonstrations of efficient, '), (0, _dom.h)('br'), (0, _dom.h)('span.tao2', ' maintainable code using Motorcycle.js and JS-monads. ')]), (0, _dom.h)('br'), (0, _dom.h)('span.tao', 'This is a '), (0, _dom.h)('a', { props: { href: "https://github.com/motorcyclejs", target: "_blank" } }, 'Motorcycle.js'), (0, _dom.h)('span', ' application. Motorcycle.js is '), (0, _dom.h)('a', { props: { href: "https://github.com/cyclejs/core", target: "_blank" } }, 'Cycle.js'), (0, _dom.h)('span', ' using '), (0, _dom.h)('a', { props: { href: "https://github.com/cujojs/most", target: "_blank" } }, 'Most'), (0, _dom.h)('span', ' , '), (0, _dom.h)('span', ' and '), (0, _dom.h)('a', { props: { href: "https://github.com/paldepind/snabbdom", target: "_blank" } }, 'Snabbdom'), (0, _dom.h)('span', ' instead of RxJS and virtual-dom. The code for this repository is at '), (0, _dom.h)('a', { props: { href: "https://github.com/dschalk/JS-monads-stable", target: "_blank" } }, 'JS-monads-stable'), (0, _dom.h)('div#gameDiv2', { style: { display: 'none' } }, [(0, _dom.h)('br'), (0, _dom.h)('span', ' Here are the basic rules:'), (0, _dom.h)('p', 'RULES: If clicking two numbers and an operator (in any order) results in 20 or 18, the score increases by 1 or 3, respectively. If the score becomes 0 or is evenly divisible by 5, 5 points are added. A score of 25 results in one goal. That can only be achieved by arriving at a score of 20, which jumps the score to 25. Directly computing 25 results in a score of 30, and no goal. Each time ROLL is clicked, one point is deducted. Three goals wins the game. '), (0, _dom.h)('button#0.num'), (0, _dom.h)('button#1.num'), (0, _dom.h)('button#2.num'), (0, _dom.h)('button#3.num'), (0, _dom.h)('br'), (0, _dom.h)('button#4.op', 'add'), (0, _dom.h)('button#5.op', 'subtract'), (0, _dom.h)('button#5.op', 'mult'), (0, _dom.h)('button#5.op', 'div'), (0, _dom.h)('button#5.op', 'concat'), (0, _dom.h)('br'), (0, _dom.h)('div#dice', { style: { display: 'none' } }, [(0, _dom.h)('button.roll', 'ROLL'), (0, _dom.h)('br'), (0, _dom.h)('button#back', 'BACK'), (0, _dom.h)('button#forward', 'FORWARD')])]), (0, _dom.h)('div#log1', [(0, _dom.h)('p', 'IN ORDER TO SEE THE GAME, TODO LIST, AND CHAT DEMONSTRATIONS, YOU MUST ENTER SOMETHING BELOW.'), (0, _dom.h)('span', 'Name: '), (0, _dom.h)('input#login', { props: { placeholder: "focus on; start typing" } })]), (0, _dom.h)('p', O.mM6.x), (0, _dom.h)('div#log2', { style: { display: 'none' } }, [(0, _dom.h)('span', 'Change group: '), (0, _dom.h)('input#group')]), (0, _dom.h)('p', O.mMsoloAlert.x), (0, _dom.h)('p', 'People who are in the same group, other than solo, share the same todo list, messages, and simulated dice game. In order to see any of these, you must establish an identity on the server by logging in. The websockets connection terminates if the first message the server receives does not come from the sign in form. You can enter any random numbers or letters you like. The only check is to make sure someone hasn\t already signed in with whatever you have selected. '), (0, _dom.h)('hr'), (0, _dom.h)('h1', 'The Monads'), (0, _dom.h)('p', ' I call instances of the Monad and MonadState constructors "monads". Instances of Monad can probably be shown to be category theory monads in a restricted space where the bnd() method takes only a single argument, and that argument is a function mapping any Javascript value to some instance of Monad. But bnd() can take multiple arguments, and the return value doesn\'t have to be an instance of Monad. As you will see, I impose some restrictions on what I do with Monad instances for the sake of maintainability, predictability, and organization. If I had helpers on a project, I would ask them to do the same. I wouldn\'t modify the code to make it throw whenever someone attempted to deviate from the restrictions. Some would say that such a modification would be helpful, catching potential bugs before things went too far. I think it would be insulting; and who knows, there might be occasions when deviating would be the sensible thing to do. Anyway, here is Monad: '), (0, _dom.h)('h2', ' Monad '), _code2.default.monad, (0, _dom.h)('p', ' Monad\'s bnd() and ret() methods provide functionality similar to the Haskell ">>=" (pronounced "bind") operator and the Haskell "return" function. They even conform to the optional Haskell monad laws. The following equality expressions demonstrate how the monads work.Note that ret(v) creates a monad with m.id == "Anonymous" and x = v, and for any monad instance m with m.id == "m", and some Javascript value v, m.ret(v) creates or mutates O.m such that O.m.id = "m" and O.m.x == v. The Monad instance m remains unchanged. Let m be an instance of Monad and let v be any Javascript value (number, array, function, monad, ...), then the following expressions return true: '), (0, _dom.h)('pre', ' m.ret(v).x == m.ret(v).bnd(m.ret).x // m.ret(v) re-sets m.x to v so v is the same on both sides.\n m.ret(v).x == m.ret(v).ret(m.x).x\n m.ret(v).bnd(add, 3).bnd(cube).x == ret(v).bnd(v => add(v, 3).bnd(cube)).x // Associativity\n ret(v).x == ret(v).bnd(ret).x\n ret(v).x == ret(ret(v).x).x '), (0, _dom.h)('p', ' where '), _code2.default.ret_add_cube, (0, _dom.h)('p', ' If the values of Monad instances are updated only through the use of the Monad ret() method, then the current state of the Monad instances exists in the mutable, global object named "O". Keeping changing monad state in one place (on the object "O") makes applications easier to reason about and easier to maintain. I treat Monad instances as though they were immutable, updating them only through the use of their ret() methods. '), (0, _dom.h)('p', ' In the examples shown on this page, the initial values of instances of Monad remain unchaged. The ret() method places updated instances of the monad calling ret() on O. From the definition of ret() we know that for any monad m and value v, m.ret(v) updates O.m such that O.m.x = v. The ret() method does not mutate the instances of Monad referenced by the attributes of O. For any instance of Monad named "m" with id "m" and value v (i.e., m.x == v is true), m.ret(v2) creates a new attribute of O with key "m" or, if O.m already exists. m.ret(v2) mutates O by changing the value to which O.m refers. Before the change, O.m.x == v. After m.ret(v2), O.m.x == v2. For most practical purposes, it is as if O.m.x is the only thing that changed. But O.m is not mutated. If there is a reference to the original O.m, it will be preserved and calls to m.ret() will not affect it. Every time m.ret() is called, O.m refers to a newly created semi-clone of m with m.x referring to a (usually) different value. The traversable game display keeps replaced monads named "O.mM1" in an array named "O.mMhistorymM1". '), (0, _dom.h)('h3', 'Examples'), (0, _dom.h)('p', ' The convention "a == b" in this presentation signifies that a == b is true. I press f12 and the press CTRL-R to reboot and then select "console", I can cut and paste the following expressions into the browser console and verify that the are true. I have installed developer tools, so this might not work for you immediately. '), (0, _dom.h)('p', ' From the definition of Monad, you can see that m1.bnd(m2.ret) results in m2.ret(m1.x) being called. After that operation, O.m2.x == v where m1.x == v. And if O.m1.x == v2, O.m1.bnd(m2.ret) results in O.m2.x == v2. If these assertions are perplexing, just take another look at the definition of Monad and work through the transformations one step at a time. Here are some examples of the use of the Monad methods bnd() and ret(): '), (0, _dom.h)('span.red3', 'cube(3)'), (0, _dom.h)('span.td2', ' creates an anonymous monad with x == 27 and id == "anonymous". '), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('span.red3', 'm.ret(3).bnd(v => m.ret(v*v*v)).bnd(x => console.log(x)) '), (0, _dom.h)('span.td2', 'Returns 27'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('span.red3', 'cube(3).bnd(m.ret)'), (0, _dom.h)('span.td2', ' O.m.x == 27 and O.m.id == "m". '), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('span.red3', 'cube(10).ret(cube(3).x)'), (0, _dom.h)('span.td2', ' O.anonymous.x == 27 '), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('span.red3', 'cube(3).ret(cube(10).x)'), (0, _dom.h)('span.td2', ' O.anonymous.x == 1000 '), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('span.red3', 'cube(3).bnd(cube(10).ret)'), (0, _dom.h)('span.td2', ' O.anonymous.x == 27 '), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('span.red3', 'cube(5, m)'), (0, _dom.h)('span.td2', ' leaves the monad m unchanged, O.m.x == 125, and O.m.id == "m". '), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('span.red3', 'cube(5).bnd(m.ret)'), (0, _dom.h)('span.td2', ' is equivalent to the previous example. m is unchanged and O.m.x == 125. '), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('span.red3', 'ret(5).bnd(cube).bnd(m.ret)'), (0, _dom.h)('span.td2', ' is equivalent to the previous two examples. O.m.x == 125. '), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('span.red3', 'm.ret(4).bnd(cube)'), (0, _dom.h)('span.td2', 'causes O.m.x == 4, and creates an anonymous monad with x == 64. '), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('span.red3', 'm.ret(4).bnd(cube, m)'), (0, _dom.h)('span.td2', ' leaves m unchanged, O.m.x == 64, and O.m.id == "m". '), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('span.tao', ' By the way, If you want to mutate m, '), (0, _dom.h)('span.red3', 'ret(newVal, "m")'), (0, _dom.h)('span', ' will do the job. Now m.x == newVal and m.id = "m". I haven\'t found a need to do that sort of thing. I like to confine changing monad state to the mutable, global object "O", and leave the plain monads alone. That keeps the application tidy and manageable. '), (0, _dom.h)('p', ' Here are some examples using the function add(): '), (0, _dom.h)('span.red3', 'add(3, 4)'), (0, _dom.h)('span.td2', ' creates a useless anonymous monad with x == 7 and id == "anonymous". '), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('span.red3', 'add(3, 4).bnd(m.ret)'), (0, _dom.h)('span.td2', ' causes O.m.x == 7 and O.m.id == "m". '), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('span.red3', 'add(3, 4, m)'), (0, _dom.h)('span.td2', ' is equivalent to the prior example. The result is O.m.x == 7, and O.m.id == "m". '), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('span.red3', 'm.ret(0).bnd(add, 3).bnd(cube)'), (0, _dom.h)('span.td2', 'leaves m unchanged, O.m.x == 0, and creates an anonymous monad with x == 27. '), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('span.red3', 'ret(0).bnd(add, 3).bnd(cube).bnd(m.ret)'), (0, _dom.h)('span.td2', 'causes O.m.x == 27, and O.m.id = "m". '), (0, _dom.h)('br'), (0, _dom.h)('br#iterLink'), (0, _dom.h)('br'), (0, _dom.h)('span.red3', 'ret(0).bnd(add, 2, m).bnd(cube, m2)'), (0, _dom.h)('span.td2', ' causes O.m.x == 2, and O.m2.x == 8. '), (0, _dom.h)('br'), (0, _dom.h)('h2', 'MonadItter'), (0, _dom.h)('p', ' MonadItter instances do not have monadic properties. I will eventually change the name to "Itter". '), (0, _dom.h)('p', 'For any instance of MonadIter, say "m", the statement "m.bnd(func)" causes m.p == func to be true. The statement "m.release(...args) causes p(...args) to execute. Here is the definition: '), _code2.default.monadIt, (0, _dom.h)('p', ' As shown later on this page, MonadIter instances control the routing of incoming websockets messages and the flow of action in the simulated dice game. In the demonstrations below, they behave much like ES2016 itterators. I prefer them over ES2016 itterators. '), (0, _dom.h)('p', 'The following example illustrates the use of release() with an argument. It also shows lambda expressions being provided as arguments for bnd() and the release() method providing arguments to the expressions captured by bnd(). The initial values of mMt1, mMt2, and mMt3 are 0, 0, and "" respectively. When this page loads, the following code runs: '), _code2.default.testZ, (0, _dom.h)('p', ' add() and cube() are defined in the Monad section (above). If you click "mMZ1.release(1)" several times, the code (above) beginning with "mMZ1" will run several times, each time with v == 1. The result, O.mMt3.x, is shown below the button. mMZ1.p (bnd()\'s argument) remains constant while mMZ1.release(1) is repeatedly called, yielding a different result each time. '), (0, _dom.h)('button#testZ', 'mMZ1.release(1)'), (0, _dom.h)('p.code2', O.mMt3.x), (0, _dom.h)('span', 'Refresh button: '), (0, _dom.h)('button#testQ', 'mMt1.ret(0).bnd(mMt2.ret)'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('span.tao', ' You can call '), (0, _dom.h)('span.green', 'mMZ2.release(v)'), (0, _dom.h)('span', ' by entering a value for v below: '), (0, _dom.h)('br'), (0, _dom.h)('span', 'Please enter an integer here: '), (0, _dom.h)('input#testW'), (0, _dom.h)('p', ' Here is another example. It demonstrates lambda expressions passing values to a remote location for use in a computation. If you enter three numbers consecutively below, I\'ll call them a, b, and c, then the quadratic equation will be used to find solutions for a*x**2 + b*x + c = 0. The a, b, and c you select might not have a solution. If a and b are positive numbers, you are likely to see solutions if c is a negative number. For example, 12, 12, and -24 yields the solutions 1 and -2. '), (0, _dom.h)('p.#quad4.code2'), (0, _dom.h)('span#quad5.red2'), (0, _dom.h)('span#quad6.red8'), (0, _dom.h)('p', 'Run mMZ3.release(v) three times for three numbers. The numbers are a, b, and c in ax*x + b*x + c = 0: '), (0, _dom.h)('input#quad'), (0, _dom.h)('p', 'Here is the code:'), _code2.default.quad, (0, _dom.h)('span#tdList'), // ***************************************************************************************************** START MonadState (0, _dom.h)('h2', 'MonadState and MonadState Transformers'), (0, _dom.h)('p', ' An instance of MonadState holds the current state and value of a computation. For any instance of MonadState, say m, these can be accessed through m.s and m.a, respectively. '), _code2.default.MonadState, (0, _dom.h)('p', ' MonadState reproduces some of the functionality found in the Haskel Module "Control.Monad.State.Lazy", inspired by the paper "Functional Programming with Overloading and Higher-Order Polymorphism", Mark P Jones (http://web.cecs.pdx.edu/~mpj/) Advanced School of Functional Programming, 1995. The following demonstrations use the MonadState instances fibsMonad and primesMonad to create and store arrays of fibonacci numbers and arrays of prime numbers, respectively. fibsMonad and primesMonad provide a simple way to compute lists of prime fibonacci numbers. Because the results of computations are stored in the a and s attributes of MonadState instances, it was easy to make sure that no prime number is ever computed twice in the prime Fibonacci demonstration. '), (0, _dom.h)('p', ' Here is the definition of fibsMonad, along with the definition of the function that becomes fibsMonad.process. '), _code2.default.fibsMonad, (0, _dom.h)('p', ' The other MonadState instance used in this demonstration is primesMonad. Here is its definition along with the function that becomes primesMonad.process: '), _code2.default.primesMonad, (0, _dom.h)('h3', ' MonadState transformers '), (0, _dom.h)('p', ' Transformers take instances of MonadState and return different instances of MonadState, possibly in a modified state. The method call "fibsMonad.bnd(fpTransformer, primesMonad)" returns primesMonad. Here is the definition of fpTransformer: '), _code2.default.fpTransformer, (0, _dom.h)('p', ' If the largest number in primesMonad.a is less than the square root of the largest number in fibsMonad.a, primesMonad is updated so that the largest number in primesMonad.a is greater than the square root of the largest number in fibsMonad.a. Otherwise, primesMonad is returned unchanged. '), (0, _dom.h)('p', ' The final computation in the prime Fibonacci numbers demonstration occurs when "tr3(fibsState[3],primesState[3]" is called. tr3() takes an array of fibonacci numbers and an array of prime numbers and returns an array containing an array of Fibonacci numbrs, an array of prime numbers, and an array of prime Fibonacci numbers. Here is the definition of tr3: '), _code2.default.tr3, (0, _dom.h)('p', ' With these support functions in place, user input is processed by (possibly) updating primesMonad and then calling fibsMonad.bnd() three times; first to extract fibsMonad.s, second to run fpTransformer to modify and then obtain primesMonad, and third to obtain primesMonad.s and run tr3(fibsState[3],primesState[3]). Here is the code: '), _code2.default.primeFibInterface, (0, _dom.h)('p', 'Only 48 fibonacci numbers need to be generated in order to get the eleventh prime Fibonacci number. But 5546 prime numbers need to be generated to test for divisibility into 2971215073. Finding the next Fibonacci number is just a matter of adding the previous two. Getting the next prime number is a more elaborate and time-consuming procedure. In this context, the time needed to compute 48 Fibonacci numbers is insignificant, so I didn\'t bother to save previously computed Fibonacci numbers in the prime Fibonacci demonstration. When a user enters a number smaller than the current length of fibsMonad.a, fibsMonad is modified such that its length becomes exactly what the user entered.'), (0, _dom.h)('p', ' I entered 44 in my desktop Ubuntu Chrome and Firefox browsers and got the first ten prime Fibonacci numbers. I then entered 48 and all eleven prime Fibonacci numbers appeared. I tried gradually incrementing upwards, but when I got to 56 I stopped due to impatience with the lag time. The 56th Fibonacci number was computed to be 139583862445. No new prime Fibonacci numbers appeared.'), (0, _dom.h)('p', ' These are the first eleven proven prime Fibonacci numbers: '), (0, _dom.h)('pre', '2,3,5,13,89,\n233,1597,28657,514229,433494437,\n2971215073 '), (0, _dom.h)('p', ' The number you enter below is the length of the list of Fibonacci numbers you want to generate. '), (0, _dom.h)('p'), (0, _dom.h)('input#fib92'), (0, _dom.h)('br'), (0, _dom.h)('span#PF_7.red6', 'Fibonacci Numbers'), (0, _dom.h)('br'), (0, _dom.h)('span#PF_9.red7'), (0, _dom.h)('br'), (0, _dom.h)('span#PF_21.red6', 'Prime Numbers'), (0, _dom.h)('br'), (0, _dom.h)('span#PF_22.red7'), (0, _dom.h)('br'), (0, _dom.h)('span#PF_8.red6', 'Prime Fibonacci Numbers'), (0, _dom.h)('br'), (0, _dom.h)('span#primeFibs.red7'), //************************************************************************************************************* END MonadState (0, _dom.h)('h2', 'Immutable Data And The State Object "O" '), (0, _dom.h)('h3', ' Mutations '), (0, _dom.h)('p', ' Mutations in this application are confined to the global state object "O", MonadIter instances, and within function scope. Functions in this application do not have side effects. If a function argument is an array, say "ar", I make a clone by calling "ar = ar.slice()" before mutating ar. That way, the original ar is uneffected by whatever happens inside the function. '), (0, _dom.h)('p', ' Regarding mutations of MonadItter instances: In the MonadItter examples (above), bnd() is called only once on each instance of MonadItter. Essentially, the bnd() method defines the MonadItter instances. The definitions of MonadItter instances create generic templates waiting for their bnd() methods to give them meaning. The p attribute of a MonadItter instance starts out referencing "f () {}" and refers to something useful when an argument is provided to its bnd() method. In this case, mutation can\'t possibly cause any mischief. '), (0, _dom.h)('h3', ' Monad Updates '), (0, _dom.h)('p', 'All monad updates caused by the monad ret() method are stored in the object "O". When a monad m executes m.ret(v) for some value "v", m remains unchanged and the O attribute O.m is created or, if it already exists, is replaced by the update; i.e., O.m.x == v becomes true. Older versions of m are subject to garbage collection unless there is a reference to them or to an object (arrays are objects) containing m. This is illustrated in the score-keeping code below. All score changes are captured by mM13.ret(). Therefore, O.mM13.x is always the current score. Replacing monad attributes in O is vaguely analogous to swapping out ServerState in the Haskell server\'s state TMVar. Older versions of ServerState can be preserved in the server just as prior versions of O.mM13 can be preserved in the front end. '), (0, _dom.h)('h3', 'Storing Monads That Have Been Replaced In O'), (0, _dom.h)('p', ' The history of the number display in the game can be traversed in either direction until a player achieves a goal. After that, the traversable history builds up until another goal is achieves. Players can use historical displays, so to keep competition fair, group members are notified when another member clicks the BACK button. '), _code2.default.traverse, (0, _dom.h)('p', ' It would have been more efficient to just save the arrays rather than the monads that hold them. But this isn\'t about recommended practices right now. It is a demonstration of a use of the not-mutated monads on the mutable global object "O". I write "not-mutated" because the monads can be clobbered anytime you want. But if values are replaced using the Monad ret() method, as is the case in this demonstration, monads on "O" are replaced, not mutated. '), (0, _dom.h)('h2', 'Updating the DOM'), (0, _dom.h)('h3', 'Todo List DOM Updates'), (0, _dom.h)('br'), (0, _dom.h)('h3', 'Dice Game DOM updates'), (0, _dom.h)('p', ' mMcurrentRoll.ret() is called only when (1) a new dice roll comes in from the server, (2) when a player clicks a number, and (3) when clicking a number or operator results in a computation being performed. These are the three things that require a DOM update. When a player clicks a number, it disappears from number display. When a computation is performed, the result is added to the number display, unless the result is 18 or 20. A result of 18 or 20 results in a new roll coming in from the server '), (0, _dom.h)('p', ' I like the way Cycle.js and Motorcycle.js are unopinionated. DOM updates can be accomplished by permanently placing a mutating list of strings in the virtual DOM description, or by calling element.innerHTML = newValue. Either way, the actual DOM gets mutatated immediately, and mutating the DOM is what interactive applications are all about. Well, unless you load fresh pages every time something changes. I guess some people are still doing that. '), (0, _dom.h)('hr'), (0, _dom.h)('h2', 'Concise Code Blocks For Information Control'), (0, _dom.h)('p', ' Incoming websockets messages trigger updates to the game display, the chat display, and the todo list display. The members of a group see what other members are doing; and in the case of the todo list, they see the current list when they sign in to the group. When any member of a group adds a task, crosses it out as completed, edits its description, or removes it, the server updates the persistent file and all members of the group immediately see the revised list. '), (0, _dom.h)('p', 'The code below shows how incoming websockets messages are routed. For example, mMZ10.release() is called when a new dice roll (prefixed by CA#$42) comes in. '), _code2.default.messages, (0, _dom.h)('p', ' The "mMZ" prefix designates instances of MonadIter. The bnd() method assigns its argument to the "p" attribute. "p" runs if and when the release() method is called. The next() function releases a specified MonadIter instance when the calling monad\'s value matches the specified value. next2() releases the specified monad when the specified condition returns true. The release method in next() has no argument, but next does take arguments, as illustrated below.'), (0, _dom.h)('span.tao', ' The incoming messages block is just a syntactic variation of a switch block, but that isn\'t all that MonadIter instances can do. They can provide fine-grained control over the lazy evaluation of blocks of code. Calling release() after a function completes some task provides Promise-like behavior. Error handling is optional. The MonadInter release(...args) method facilitates sequential evaluation of code blocks, remeniscent of video and blog explanations of ES6 iterators and generators. I prefer doing it with MonadIter over "yield" and "next". For one thing, ES6 generator "yield" blocks must be evaluated in a predetermined order. This link takes you back to the MonadIter section with interactive examples of the use of release() with arguments. '), (0, _dom.h)('a#tdList2', { props: { href: '#iterLink' } }, 'release() with arguments'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('a', { props: { href: '#top' } }, 'Back To The Top'), (0, _dom.h)('br'), (0, _dom.h)('h3', 'The Todo List'), (0, _dom.h)('p', ' Next, I\'ll go over some features of the todo list application. This will show how Motorcycle.js and the monads work together.'), (0, _dom.h)('p', 'Creation Of A Task: If you enter something like Susan, Fred, Pay the water bill, the editable task will appear in your browser and in the browsers of any members a group you might have created or joined. If you have loaded this page in another tab and changed to the same group in both, you will see the task in both tabs, barring some malfunction. The task has a delete button, an edit button, and a "Completed" checkbox. It shows that Susan authorized the task and Fred is responsible for making sure it gets done. Instead of entering an authority and responsible person, you can just enter two commas before the task description. Without two commas, a message appears requesting more information. '), _code2.default.newTask, (0, _dom.h)('p', 'mM$taskList caries a string representing the task list. mMtaskList.x.split(",") produces an array whose length is a multiple of six. Commas in the task description are replaced by "$*$*$" so split(",") will put the entire task description in a single element. Commas are re-inserted when the list arrives from the server for rendering. Although a task list is a nested virtual DOM object (Snabbdom vnode), it can be conveniently passed back and forth to the server as a string without resorting to JSON.stringify. Its type is Text on the server and String in the front end, becomming a virtual DOM node only once, when it arrives from the server prefixed by "DD#$42" causing "process(e.data) to execute. Here is process(): '), _code2.default.process, (0, _dom.h)('span.tao', 'As you see, the string becomes a list of six-element objects, then those objects are used to create a Snabbdom vnode which is handed to mM$taskList.ret() leading to the update of O.mMtaskList. O.mMtaskList.x sits permanently in the main virtual DOM description. '), (0, _dom.h)('a', { props: { href: "https://github.com/dschalk/JS-monads-stable" } }, 'https://github.com/dschalk/JS-monads-stable'), (0, _dom.h)('br'), (0, _dom.h)('p', ' Clicking "Completed": When the "Completed" button is clicked, the following code runs: '), _code2.default.colorClick, (0, _dom.h)('p', 'O.mMtaskList is split into an array. Every sixth element is the start of a new task. colorAction$ toggles the second, third, and fourth element in the task pinpointed by "index" * 6. getIndex finds the index of the first and only the element whose task description matches the one that is being marked "Completed". I say "only" because users are prevented from adding duplicate tasks. After the changes are made, the array of strings is reduced to one string and sent to the server by task2(). '), (0, _dom.h)('p', ' This is the code involved in editing a task description: '), _code2.default.edit, (0, _dom.h)('p', 'Clicking "Edit" causes a text box to be displayed. Pressing <ENTER> causes it to diappear. edit2Action$ obtains the edited description of the task and the index of the task iten and provides them as arguments to process. Process exchanges $*$*$ for any commas in the edited version and assigns the amended task description to the variable "task". O.mMtaskList.x is copied and split into an array. "index * 6" is replaced with "task" and the list of strings is reduced back to a single string and sent to the server for distribution. This pattern, - (1) split the string representation of the todo list into an array of strings, (2) do something, (3) reduce the list of strings back to a single string - is repeated when the "Delete" button is clicked. If the last item gets deleted, the server is instructed to delete the persistent file bearing the name of the group whose member deleted the last task. '), (0, _dom.h)('p#common', 'Cycle.js has been criticized for not keeping state in a single location, the way React.js does. Motorcycle.js didn\'t do it for me, or try to force me to do it, but it so happens that the current state of all active monads is in the object "O". I have written applications in Node.js and React.js, and I can say without a doubt that Motorcycle.js provides the best reactive interface for my purposes. '), (0, _dom.h)('hr'), (0, _dom.h)('a', { props: { href: '#top' } }, 'Back To The Top'), (0, _dom.h)('h2', 'Common Patterns'), (0, _dom.h)('p', 'Anyone not yet familiar with functional programming can learn by studying the definition of the Monad bnd() method and considering the common patterns presented below. Often, we want to give a named monad the value of an anonymous monad returned by a monadic computation. Here are some ways to accomplish that: '), (0, _dom.h)('p', 'For any monads m1 and m2 with values a and b respectively (in other words, m1.x == a and m2.x == b return true), m1.bnd(m2.ret) provides m1\'s value to m2.ret() causing O.m2 to have m1\'s value. So, after m1.bnd(m2.ret), m1.x == a, m2.x == b, O.m2.x == a all return true. The definition of Monad\s bnd() method shows that the function m2.ret() operates on m1.x. m1.bnd(m2.ret) is equivalent to m2.ret(m1.x). The stand-alone ret() function can be used to alter the current value of m2, rather than altering the value of O.m2. Here is one way of accomplishing this: m1.bnd(x => ret(x,"m2"). These relationships are demonstrated in the following tests: '), (0, _dom.h)('pre', ' ret(\'m1Val\',\'m1\')\n m1.x === \'m1Val\' // true\n ret(\'m2Val\', \'m2\')\n m2.x === \'m2Val\' // true\n\n m1.bnd(m2.ret)\n O.m2.x === \'m1Val\' // true\n m2.x === \'m2Val\' // still true\n\n m1.ret(\'newVal\')\n O.m1.bnd(v => ret(v, \'m2\'))\n m2.x === \'newVal\' // true\n O.m2.x === \'m1Val\' // true still the same '), (0, _dom.h)('p', ' Here are two basic ways to create a monad named "m" with id = "m" and value v: '), (0, _dom.h)('pre', ' var m = new Monad(v, "m");\n ret(v, "m"); '), (0, _dom.h)('p', 'Let m be a monad with id == "m" and value v. Its bnd() method can return an anonymous monad, a new named monad, or a previously existing monad containing the computation result. To illustrate, here is the definition of "add" along with five uses of it: '), _code2.default.add, (0, _dom.h)('p'), (0, _dom.h)('hr'), (0, _dom.h)('hr'), (0, _dom.h)('a', { props: { href: '#top' } }, 'Back To The Top'), (0, _dom.h)('a', { props: { href: '#top' } }, 'Back To The Top'), (0, _dom.h)('p'), (0, _dom.h)('p'), (0, _dom.h)('p'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('br'), (0, _dom.h)('span#dummy2.red3'), (0, _dom.h)('hr'), (0, _dom.h)('button#dummy', O.mMdummy.x), (0, _dom.h)('p'), (0, _dom.h)('p'), (0, _dom.h)('p', '.'), (0, _dom.h)('p', '.'), (0, _dom.h)('p', '.'), (0, _dom.h)('p', '.'), (0, _dom.h)('p', '.'), (0, _dom.h)('p'), (0, _dom.h)('p'), (0, _dom.h)('p'), (0, _dom.h)('p'), (0, _dom.h)('p')])]); }) }; } function cleanup(x) { var target0 = document.getElementById('0'); var target1 = document.getElementById('1'); var target2 = document.getElementById('2'); var target3 = document.getElementById('3'); var targetAr = [target0, target1, target2, target3]; [0, 1, 2, 3].map(function (i) { if (targetAr[i].innerHTML == 'undefined') { targetAr[i].style.display = 'none'; } else { targetAr[i].style.display = 'inline'; } }); return ret(x); }; var score = function score(x, j) { if (x + j == 20) { mMgoals.ret(O.mMgoals.x == 2 ? 0 : O.mMgoals.x + 1); mM13.ret(0).bnd(mMindex.ret); mMhistorymM1.ret([ret([0, 0, 0, 0])]); socket.send('CG#$42,' + O.mMgroup.x + ',' + O.mMname.x + ',' + -x + ',' + O.mMgoals.x); if (O.mMgoals.x == 0) { socket.send('CE#$42,' + O.mMgroup.x + ',' + O.mMname.x + ',nothing '); } socket.send('CA#$42,' + O.mMgroup.x.trim() + ',' + O.mMname.x.trim() + ',6,6,12,20'); return; } if ((x + j) % 5 == 0) { socket.send('CG#$42,' + O.mMgroup.x + ',' + O.mMname.x + ',' + (j + 5) + ',' + O.mMgoals.x); mM13.ret(x + j + 5); socket.send('CA#$42,' + O.mMgroup.x.trim() + ',' + O.mMname.x.trim() + ',6,6,12,20'); return; } socket.send('CG#$42,' + O.mMgroup.x + ',' + O.mMname.x + ',' + j + ',' + O.mMgoals.x); mM13.ret(x + j); socket.send('CA#$42,' + O.mMgroup.x.trim() + ',' + O.mMname.x.trim() + ',6,6,12,20'); }; var reset = function reset() { mM3.ret([]).bnd(function () { return mM4.ret(0).bnd(mM8.ret).bnd(cleanup); }); }; var updateScoreboard = function updateScoreboard(v) { var ar2 = v.split("<br>"); var keys = Object.keys(ar2); var ar = []; keys.map(function (k) { ar.push((0, _dom.h)('div', ar2[k])); }); return mMscoreboard.ret(ar); }; var displayOff = function displayOff(x, a) { document.getElementById(a).style.display = 'none'; return ret(x); }; var displayInline = function displayInline(x, a) { if (document.getElementById(a)) document.getElementById(a).style.display = 'inline'; return ret(x); }; var newRoll = function newRoll(v) { socket.send('CA#$42,' + O.mMgroup.x.trim() + ',' + O.mMname.x.trim() + ',6,6,12,20'); return ret(v); }; var refresh = function refresh() { setTimeout(function () { document.location.reload(false); }, 4000); }; var sources = { DOM: (0, _dom.makeDOMDriver)('#main-container'), WS: websocketsDriver }; _core2.default.run(main, sources); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(17))) /***/ } /******/ ]);
Modified some code
client/dist/bundle.js
Modified some code
<ide><path>lient/dist/bundle.js <ide> <ide> var fibsMonad = (0, _dom.h)('pre', ' var fibsMonad = new MonadState(\'fibsMonad\', [0, 1, 3, [0,1]], [0,1], fibs_state ) \n\n var fibs_state = function fibs_state(ar) {\n var a = ar.slice();\n while (a[3].length < a[2]) {\n a = [a[1], a[0] + a[1], a[2], a[3].concat(a[0])];\n }\n return a\n } '); <ide> <del> var tr3 = (0, _dom.h)('pre', ' var tr3 = function tr (fibsArray, primesArray) {\n var ar = [];\n var primes = primesArray.slice();\n var fibs = fibsArray.slice();\n var fib = fibsArray.slice(3);\n var bound = Math.round(Math.sqrt(fibs[fibs.length - 1]));\n if (bound < primesArray[primesArray.length - 1]) {\n primes = primes.filter(v => v <= bound);\n }\n fib.map (f => {\n if ( f < 2 ) return;\n if ( primes.every(p => (f % p != 0 || f == p))) ar.push(f);\n })\n return [fibs, primes, ar]\n } '); <del> <del> var primeFibInterface = (0, _dom.h)('pre', ' const fibKeyPress5$ = sources.DOM\n .select(\'input#fib92\').events(\'keydown\');\n\n const primeFib$ = fibKeyPress5$.map(e => {\n if( e.keyCode == 13 ) {\n var bound;\n fibsMonad.run([0, 1, e.target.value, []])\n .bnd(s => bound = Math.round(Math.sqrt(s[0])));\n if (bound > primesMonad.a[primesMonad.a.length - 1] ) {\n primesMonad.run([primesMonad.s[0], "from the fibKeyPress5$ handler", bound, primesMonad.a])\n }\n var res = fibsMonad\n .bnd(fibsState => fibsMonad // Gets the current state of fibsMonad\n .bnd(fpTransformer, primesMonad) // Returnes the (possibly modified) state of primesMonad\n .bnd(primesState => tr3(fibsState[3],primesState[3]))) // Runs tr3 on fibsMonad.s and the new primesMonad\n document.getElementById(\'PF_9\').innerHTML = res[0]; // res is the return value of tr3 (above)\n document.getElementById(\'PF_22\').innerHTML = res[1];\n document.getElementById(\'primeFibs\').innerHTML = res[2];\n }\n }); '); <del> <del> var fpTransformer = (0, _dom.h)('pre', ' var fpTransformer = function fpTransformer (s, m) {\n let bound = Math.round(Math.sqrt(s[1]));\n if (bound <= m.a[m.a.length - 1]) {\n return m;\n }\n return m.run([m.s[0], "From fpTransformer", bound, m.a])\n } '); <add> var tr3 = (0, _dom.h)('pre', ' var tr3 = function tr (fibsArray, primesArray) {\n var bound = Math.ceil(Math.sqrt(fibsArray[fibsArray.length - 1]))\n var primes;\n if (primesArray[primesArray.length - 1] >= bound) {\n primes = primesArray.filter(v => v <= bound);\n } \n else {primes = primesArray.slice()};\n var ar = [];\n var fibs = fibsArray.slice(3);\n fibs.map (f => {\n if ( primesArray.every(p => (f % p != 0 || f == p))) ar.push(f);\n })\n return [fibsArray, primes, ar]\n } '); <add> <add> var primeFibInterface = (0, _dom.h)('pre', ' const fibKeyPress5$ = sources.DOM\n .select(\'input#fib92\').events(\'keydown\');\n\n const primeFib$ = fibKeyPress5$.map(e => {\n if( e.keyCode == 13 ) {\n var res = fibsMonad\n .run([0, 1, e.target.value, []])\n .bnd(fibsState => fibsMonad\n .bnd(fpTransformer, primesMonad)\n .bnd(primesState => tr3(fibsState[3],primesState[3])))\n document.getElementById(\'PF_9\').innerHTML = res[0];\n document.getElementById(\'PF_22\').innerHTML = res[1];\n document.getElementById(\'primeFibs\').innerHTML = res[2];\n }\n }); '); <add> <add> var fpTransformer = (0, _dom.h)('pre', ' var fpTransformer = function fpTransformer (s, m) {\n var bound = Math.ceil(Math.sqrt(s[3][s[3].length - 1]));\n if (bound > m.a[m.a.length - 1] ) {\n m.run([m.s[0], "from the fibKeyPress5$ handler", bound, primesMonad.a])\n }\n return m;\n } '); <ide> <ide> var innerHTML = (0, _dom.h)('pre', ' var innerHTML = function innerHTML (x, v, u, m) { \n document.getElementById(u).innerHTML = v;\n return m.ret(x);\n } '); <ide> <ide> <ide> var primeFib$ = fibKeyPress5$.map(function (e) { <ide> if (e.keyCode == 13) { <del> /* <del> var bound; <del> fibsMonad.run([0,1,e.target.value,[]]).bnd(s => bound = Math.ceil(Math.sqrt(s[3][s[3].length - 1]))); <del> if (bound > primesMonad.a[primesMonad.a.length - 1] ) { <del> primesMonad.run([primesMonad.s[0], "from the fibKeyPress5$ handler", bound, primesMonad.a]) <del> } <del> */ <ide> var res = fibsMonad.run([0, 1, e.target.value, []]).bnd(function (fibsState) { <ide> return fibsMonad.bnd(fpTransformer, primesMonad).bnd(function (primesState) { <ide> return tr3(fibsState[3], primesState[3]);
JavaScript
mit
5e03e932b2c4404de2fd8d17995a829801466acd
0
bcopeland/xwordjs,bcopeland/xwordjs
// @flow import React, { Component } from 'react'; import Modal from 'react-modal'; import FileInput from './FileInput.js'; import Server from './Server.js'; import Cell from './Cell.js'; import Clues from './Clues.js'; import Loading from './Loading.js'; import {TimerState, Timer} from './Timer.js'; import { Route, Switch, Link } from 'react-router-dom'; import { ButtonGroup, ButtonToolbar, DropdownButton, MenuItem, ProgressBar, Button } from 'react-bootstrap'; import scrollIntoViewIfNeeded from 'scroll-into-view-if-needed'; import { TextDecoder } from 'text-encoding'; import './Xword.css'; // TODO // . clue-only entry // . auto-pause // . port nav enhancements (no auto next, skip to first blank) var Xd = require("./xd.js"); var Puz = require("./puz.js"); var Xpf = require("./xpf.js"); class XwordClue { state: { index: number, direction: string, number: number, clue: string, answer: string, active: boolean, crossActive: boolean }; constructor(options) { this.state = { 'index': 0, 'direction': 'A', 'number': 0, 'clue': '', 'answer': '', 'active': false, 'crossActive': false, }; Object.assign(this.state, options); } setState(newstate) { Object.assign(this.state, newstate); } get(key) : any { return this.state[key]; } } class XwordCell { state: { fill: string, entry: string, active: boolean, focus: boolean, circled: boolean, incorrect: boolean, number: number, version: number, }; constructor(options) { this.state = { fill: '.', entry: ' ', active: false, focus: false, circled: false, incorrect: false, version: 0, number: 0, }; Object.assign(this.state, options); } setState(newstate) { Object.assign(this.state, newstate); } get(key) : any { return this.state[key]; } isBlack() : boolean { return this.state.fill === '#'; } } function Title(props) { var title = props.title; var author = props.author ? " by " + props.author : ""; return ( <div className={"xwordjs-title"}> <span className={"xwordjs-title-text"}>{title}</span> <span className={"xwordjs-author-text"}>{author}</span> </div> ); } function ClueBar(props) { var text = ''; for (var i=0; i < props.value.length; i++) { var clue = props.value[i]; if (clue.get('active')) { text = clue.get('number') + ". " + clue.get('clue'); } } return <div className={"xwordjs-clue-bar"}>{text}</div>; } class Grid extends Component { render() { var rows = []; for (var i=0; i < this.props.height; i++) { var row_cells = []; for (var j=0; j < this.props.width; j++) { var ind = i * this.props.width + j; var fill = this.props.cells[ind].get('fill'); var entry = this.props.cells[ind].get('entry'); var active = this.props.cells[ind].get('active'); var focus = this.props.cells[ind].get('focus'); var circled = this.props.cells[ind].get('circled'); var incorrect = this.props.cells[ind].get('incorrect'); var number = this.props.cells[ind].get('number') || ''; var black = fill === '#'; if (fill === '#' || fill === '.') { fill = ' '; } var cell = <Cell id={"cell_" + ind} value={entry} key={"cell_" + ind} isBlack={black} isActive={active} isFocus={focus} isCircled={circled} isIncorrect={incorrect} isTop={i===0} isLeft={j===0} number={number} onClick={(x)=>this.props.handleClick(parseInt(x.substring(5), 10))}/>; row_cells.push(cell); } rows[i] = <div className="xwordjs-grid-row" key={"row_" + i}>{row_cells}</div>; } return ( <div id="xwordjs-grid-inner">{rows}</div> ); } } function MobileKeyboardKey(props) { return <div className="xwordjs-keyboard-key" onClick={() => props.onClick(props.code)}>{props.value}</div>; } function MobileKeyboard(props) { var keys = ["qwertyuiop", "asdfghjkl", "␣zxcvbnm⌫"]; var rows = []; for (var i=0; i < keys.length; i++) { var rowstr = keys[i]; var row_keys = []; for (var j=0; j < rowstr.length; j++) { var ch = rowstr.charAt(j); var code; if (ch === '␣') { code = 0x20; } else if (ch === '⌫') { code = 0x8; } else { code = ch.charCodeAt(0); } var key = <MobileKeyboardKey key={ch} onClick={props.onClick} code={code} value={ch}/>; row_keys.push(key); } rows[i] = <div className="xwordjs-keyboard-row" key={i}>{row_keys}</div>; } return ( <div className="xwordjs-keyboard">{rows}</div> ); } class XwordSolver extends Component { state: { height: number, width: number, cells: Array<XwordCell>, clues: Array<XwordClue>, title: string, author: string, timer: TimerState, activecell: number, direction: string, cell_to_clue_table: Array<Array<number>>, clue_to_cell_table: Array<number>, version: number, solutionId: ?string, dismissed_modal: boolean, modified: boolean, rebus: boolean, server: ?Server }; closeModal: Function; revealAll: Function; serverUpdate: Function; constructor() { super(); this.state = { 'height': 15, 'width': 15, 'cells': [], 'clues': [], 'title': '', 'author': '', 'timer': new TimerState(), 'activecell': 0, 'direction': 'A', 'cell_to_clue_table': [], 'clue_to_cell_table': [], 'dismissed_modal': false, 'version': 1, 'modified': false, 'solutionId': null, rebus: false, 'server': null, } this.closeModal = this.closeModal.bind(this); this.revealAll = this.revealAll.bind(this); this.serverUpdate = this.serverUpdate.bind(this); } loadServerPuzzle(id: string) { if (!process.env.REACT_APP_HAS_SERVER) return; var self = this; var server = new Server({base_url: process.env.PUBLIC_URL}) server .getSolution(id) .then(function(obj) { return server.getPuzzle(obj.PuzzleId) }) .then(function(data) { var decoder = new TextDecoder('utf-8'); var puz = new Xpf(decoder.decode(data)); self.setState({solutionId: id, server: server}); self.puzzleLoaded(id, puz); server.connect(id, self.serverUpdate); var entries = []; for (var i=0; i < self.state.cells.length; i++) { entries.push({'Version': -1, 'Value': ''}); } server.sendSolution(id, -1, entries); }); } loadPuzzle(file: File, filename : ?string) { var self = this; if (process.env.REACT_APP_HAS_SERVER) { var server = new Server({base_url: process.env.PUBLIC_URL}) server.uploadPuzzle(file) .then(function(obj) { var id = obj.Id; return server.startSolution(id); }) .then(function(obj) { var solutionId = obj.Id; document.location.hash = "/s/" + solutionId; self.loadServerPuzzle(solutionId); }); } else { this.loadPuzzleURL(window.URL.createObjectURL(file), filename); } } loadPuzzleURL(url: string, filename : ?string) { var self = this; var request = new Request(url); fetch(request).then(function(response) { return response.arrayBuffer(); }).then(function(data) { var puz; var fn = filename || url; var decoder; if (fn.endsWith("xd")) { decoder = new TextDecoder('utf-8'); // $FlowFixMe puz = new Xd(decoder.decode(data)); self.puzzleLoaded(url, puz); } else if (fn.endsWith("xml") || url.match(/^http/)) { decoder = new TextDecoder('utf-8'); // $FlowFixMe puz = new Xpf(decoder.decode(data)); self.puzzleLoaded(url, puz); } else { puz = new Puz(data); self.puzzleLoaded(url, puz); } }); } cellPos(clue_id: number) { var y = Math.floor(clue_id / this.state.width); var x = clue_id % this.state.width; return [x, y]; } navRight() { var [x, y] = this.cellPos(this.state.activecell); while (x < this.state.width) { x += 1; if (x < this.state.width && this.state.cells[y * this.state.width + x].get('fill') !== '#') break; } if (x === this.state.width) return; var activecell = y * this.state.width + x; this.selectCell(activecell, this.state.direction); } navLeft() { var [x, y] = this.cellPos(this.state.activecell); while (x >= 0) { x -= 1; if (x >= 0 && this.state.cells[y * this.state.width + x].get('fill') !== '#') break; } if (x < 0) return; var activecell = y * this.state.width + x; this.selectCell(activecell, this.state.direction); } navUp() { var [x, y] = this.cellPos(this.state.activecell); while (y >= 0) { y -= 1; if (y >= 0 && this.state.cells[y * this.state.width + x].get('fill') !== '#') break; } if (y < 0) return; var activecell = y * this.state.width + x; this.selectCell(activecell, this.state.direction); } navDown() { var [x, y] = this.cellPos(this.state.activecell); while (y < this.state.height) { y += 1; if (y < this.state.height && this.state.cells[y * this.state.width + x].get('fill') !== '#') break; } if (y === this.state.height) return; var activecell = y * this.state.width + x; this.selectCell(activecell, this.state.direction); } navNextClue() { var dind = (this.state.direction === 'A') ? 0 : 1; var cur_cell_id = this.state.activecell; var clue_id = this.state.cell_to_clue_table[cur_cell_id][dind]; var next_clue_id = (clue_id + 1) % this.state.clues.length; this.selectClue(this.state.clues[next_clue_id]); } navPrevClue() { var dind = (this.state.direction === 'A') ? 0 : 1; var cur_cell_id = this.state.activecell; var clue_id = this.state.cell_to_clue_table[cur_cell_id][dind]; var next_clue_id = (clue_id - 1) % this.state.clues.length; this.selectClue(this.state.clues[next_clue_id]); } findNextEmptyCell(direction: string, start_x: number, start_y: number, end_x: ?number, end_y: ?number): ?number { var dind = (direction === 'A') ? 0 : 1; var [x_incr, y_incr] = [1 - dind, dind]; var [x, y] = [start_x, start_y]; if (end_x === null || end_x === undefined) end_x = this.state.width; if (end_y === null || end_y === undefined) end_y = this.state.height; var len = (!dind) ? end_x - start_x : end_y - start_y; for (let i = 0; i < len; i++) { var cell_id = y * this.state.width + x; var cell = this.state.cells[cell_id]; if (cell.isBlack()) break; if (cell.get('entry') === ' ') return cell_id; x += x_incr; y += y_incr; } return null; } navNext() { var dind = (this.state.direction === 'A') ? 0 : 1; var cur_cell_id = this.state.activecell; var clue_id = this.state.cell_to_clue_table[cur_cell_id][dind]; var start_cell_id = this.state.clue_to_cell_table[clue_id]; var clue = this.state.clues[clue_id]; var [x, y] = this.cellPos(cur_cell_id); var [start_x, start_y] = this.cellPos(start_cell_id); var alen = clue.get('answer').length; var empty_cell_id = this.findNextEmptyCell(this.state.direction, x, y); // wrap if (empty_cell_id === null || empty_cell_id === undefined) { empty_cell_id = this.findNextEmptyCell(this.state.direction, start_x, start_y, x, y); } if (empty_cell_id === null || empty_cell_id === undefined) { // no empty square. [x, y] = this.cellPos(cur_cell_id); // if end of word, go to next word if ((this.state.direction === 'A' && x === start_x + alen - 1) || (this.state.direction === 'D' && y === start_y + alen - 1)) { this.navNextClue(); return; } // go to next word if (this.state.direction === 'A') x += 1; else y += 1; empty_cell_id = y * this.state.width + x; } this.selectCell(empty_cell_id, this.state.direction); } navPrev() { var dind = (this.state.direction === 'A') ? 0 : 1; var cur_cell_id = this.state.activecell; var clue_id = this.state.cell_to_clue_table[cur_cell_id][dind]; var start_cell_id = this.state.clue_to_cell_table[clue_id]; var [x, y] = this.cellPos(cur_cell_id); var [start_x, start_y] = this.cellPos(start_cell_id); if (this.state.direction === 'A') x -= 1; else y -= 1; if (x < start_x) x = start_x; if (y < start_y) y = start_y; var activecell = y * this.state.width + x; this.selectCell(activecell, this.state.direction); } switchDir() { var dir = this.state.direction === 'A' ? 'D' : 'A'; this.selectCell(this.state.activecell, dir); } type(ch: string) { var cell = this.state.cells[this.state.activecell]; if (this.state.rebus) { var text = cell.get('entry'); cell.setState({entry: text + ch}); this.setState({modified: true}) } else { cell.setState({'entry': ch, 'version': cell.get('version') + 1}); this.setState({modified: true}) this.navNext(); } } del() { var cell = this.state.cells[this.state.activecell]; if (this.state.rebus) { var text = cell.get('entry'); text = text.substr(0, text.length - 1); cell.setState({entry: text}); this.setState({modified: true}) } else { cell.setState({'entry': ' ', 'version': cell.get('version') + 1}); this.setState({modified: true}) this.selectCell(this.state.activecell, this.state.direction); } } backspace() { var cell = this.state.cells[this.state.activecell]; if (this.state.rebus) { var text = cell.get('entry'); text = text.substr(0, text.length - 1); cell.setState({entry: text}); this.setState({modified: true}) } else { cell.setState({'entry': ' ', 'version': cell.get('version') + 1}); this.setState({modified: true}) this.navPrev(); } } isCorrect() { for (var i=0; i < this.state.cells.length; i++) { var cell = this.state.cells[i]; var fill = cell.get('fill'); var entry = cell.get('entry'); if (fill !== '#' && (entry !== fill && entry !== fill.charAt(0))) return false; } return true; } processKeyCode(keyCode: number, shift: boolean) { // A-Z if ((keyCode >= 0x41 && keyCode <= 0x5a) || (keyCode >= 0x61 && keyCode <= 0x7a)) { var ch = String.fromCharCode(keyCode) this.type(ch.toUpperCase()); return true; } switch (keyCode) { case 0x8: this.backspace(); return true; case 0x9: if (!shift) this.navNextClue(); else this.navPrevClue(); return true; case 0x20: this.switchDir(); return true; case 0x25: this.navLeft(); return true; case 0x26: this.navUp(); return true; case 0x27: this.navRight(); return true; case 0x28: this.navDown(); return true; case 0x2e: this.del(); return true; default: return false; } } handleKeyDown(e: KeyboardEvent) { if (e.ctrlKey || e.altKey) return; if (this.state.direction === 'A' && (e.keyCode === 0x26 || e.keyCode === 0x28)) { this.selectCell(this.state.activecell, 'D'); e.preventDefault(); return; } if (this.state.direction === 'D' && (e.keyCode === 0x25 || e.keyCode === 0x27)) { this.selectCell(this.state.activecell, 'A'); e.preventDefault(); return; } if (this.processKeyCode(e.keyCode, e.shiftKey)) { e.preventDefault(); } } handleClick(i: number) { if (this.state.activecell === i) { this.switchDir(); } else { this.selectCell(i, this.state.direction); } } puzzleLoaded(url: string, puz: Object) { var grid = puz.grid; var flags = puz.flags; var maxx = grid[0].length; var maxy = grid.length; var i; var title = 'Untitled'; var author = 'Unknown'; for (i=0; i < puz.headers.length; i++) { var [header, value] = puz.headers[i]; if (header === 'Title') { title = value; } else if (header === 'Creator' || header === 'Author') { author = value; } } var cells = Array(maxx * maxy).fill(null); var cell_to_clue_table = Array(maxx * maxy).fill(null); var number_index = []; for (var y = 0; y < maxy; y++) { for (var x = 0; x < maxx; x++) { var fill = grid[y][x]; var is_black = fill === '#'; var number = 0; var start_of_xslot = (!is_black && (x === 0 || grid[y][x-1] === '#') && (x + 1 < maxx && grid[y][x+1] !== '#')); var start_of_yslot = (!is_black && (y === 0 || grid[y-1][x] === '#') && (y + 1 < maxy && grid[y+1][x] !== '#')); if (start_of_xslot || start_of_yslot) { number_index.push([x,y]); number = number_index.length; } var circled = false; if (flags) { circled = !!(flags[y][x] & puz.FLAGS.CIRCLED); } cells[y * maxx + x] = new XwordCell({ 'fill': fill, 'number': number, 'active': false, 'circled': circled }); cell_to_clue_table[y * maxx + x] = [null, null]; } } var clues = []; var clue_to_cell_table = []; for (i=0; i < puz.clues.length; i++) { var [type, cluestr, answer] = puz.clues[i]; var [dir, num] = type; var clue = new XwordClue({ 'index': i, 'direction': dir, 'number': num, 'clue': cluestr, 'answer': answer}); clues.push(clue); // clue_to_cell table: index into clues[] has the corresponding // cell id var xy = number_index[num - 1]; clue_to_cell_table[i] = xy[1] * maxx + xy[0]; // set up cell_to_clue_table: indexed by cell id, each entry // has a two element array (across, down) which contains the // index into clues[]. Iterate over answer in the direction // of the clue to set all cells making up the answer var ind = 0, xincr = 0, yincr = 0; if (dir === 'A') { xincr = 1; } else { ind = 1; yincr = 1; } [x, y] = xy; for (var j = 0; y < maxy && x < maxx; j++) { var cell = y * maxx + x; if (grid[y][x] === '#') break; cell_to_clue_table[cell][ind] = i; x += xincr; y += yincr; } } this.setState({ 'title': title, 'author': author, 'width': maxx, 'height': maxy, 'cells': cells, 'clues': clues, 'clue_to_cell_table': clue_to_cell_table, 'cell_to_clue_table': cell_to_clue_table }); this.loadStoredData(); this.selectCell(0, 'A', true); // set cluelist to match grid height var gridelem = document.getElementById("xwordjs-grid-inner"); var cluediv = document.getElementById("xwordjs-cluelist-container"); var cluelist = document.getElementsByClassName("xwordjs-cluelist"); var gridHeight = window.getComputedStyle(gridelem).getPropertyValue("height"); if (cluediv) cluediv.style.height = gridHeight; for (i = 0; i < cluelist.length; i++) { var e = cluelist[i]; var newheight = String(parseInt(gridHeight, 10) - 60) + "px"; e.style.height = newheight; } } saveStoredData() { var key = this.state.cells.map((x) => x.state.fill).join(""); var data = { entries: this.state.cells.map((x) => x.state.entry), elapsed: this.state.timer.get('elapsed') }; // avoid a race condition when first starting up if (!data.elapsed) return; localStorage.setItem(key, JSON.stringify(data)); } readStoredData() { var key = this.state.cells.map((x) => x.state.fill).join(""); var data = localStorage.getItem(key); if (!data) return null; return JSON.parse(data); } loadStoredData() { var data = this.readStoredData() if (!data) return; var entries = data.entries; var elapsed = data.elapsed; for (var i=0; i < entries.length; i++) { this.state.cells[i].setState({entry: entries[i]}); } this.setState({modified: true}) this.state.timer.setState({elapsed: elapsed}); this.setState({cells: this.state.cells, timer: this.state.timer}); } highlightClue(clue: XwordClue, active: boolean) { var cluenum = clue.get('index'); var cind = this.state.clue_to_cell_table[cluenum]; var [x, y] = this.cellPos(cind); var x_incr = clue.get('direction') === 'A' ? 1 : 0; var y_incr = !x_incr; for (; x < this.state.width && y < this.state.height; ) { var cell = this.state.cells[this.state.width * y + x]; if (cell.isBlack()) break; cell.setState({"active": active}); x += x_incr; y += y_incr; } } selectCell(cell_id: number, direction: string, initial: ?boolean) { var cell = this.state.cells[cell_id]; if (cell.isBlack()) return; var newclues = this.state.clues.slice(); var newcells = this.state.cells.slice(); // unselect existing selected cell and crosses var oldcell_id = this.state.activecell; var old_dind = (this.state.direction === 'A') ? 0 : 1; var oldclue = this.state.clues[this.state.cell_to_clue_table[oldcell_id][old_dind]]; var oldcross = this.state.clues[this.state.cell_to_clue_table[oldcell_id][1 - old_dind]]; var oldcell = this.state.cells[oldcell_id]; var dind = (direction === 'A') ? 0 : 1; var clue = this.state.clues[this.state.cell_to_clue_table[cell_id][dind]]; var cross = this.state.clues[this.state.cell_to_clue_table[cell_id][1 - dind]]; var e; var cluediv = document.getElementById("xwordjs-cluelist-container"); var display = window.getComputedStyle(cluediv).getPropertyValue("display"); var hasClues = display !== "none"; if (initial || oldcross !== cross) { if (oldcross) oldcross.setState({"crossActive": false}); if (cross) { cross.setState({"crossActive": true}); e = document.getElementById("clue_" + cross.get('index')); if (e && hasClues) scrollIntoViewIfNeeded(e); } } if (initial || oldclue !== clue) { if (oldclue) { oldclue.setState({"active": false}); this.highlightClue(oldclue, false); } if (clue) { clue.setState({"active": true}); this.highlightClue(clue, true); e = document.getElementById("clue_" + clue.get('index')); if (e && hasClues) scrollIntoViewIfNeeded(e); } } if (initial || oldcell_id !== cell_id) { oldcell.setState({focus: false}); cell.setState({focus: true}); } e = document.getElementById("cell_" + cell_id); if (e) { var rect = e.getBoundingClientRect(); var container = document.getElementById("xwordjs-container"); var prect = container.getBoundingClientRect(); if (prect.left > rect.left || prect.right < rect.right || prect.top > rect.top || prect.bottom < rect.bottom) { scrollIntoViewIfNeeded(e); } } this.setState({'clues': newclues, 'cells': newcells, 'activecell': cell_id, 'direction': direction, rebus: false}); } revealCell() { var cell = this.state.cells[this.state.activecell]; cell.setState({'entry': cell.get('fill')}); this.setState({'cells': this.state.cells.slice()}); } revealClue() { var dind = (this.state.direction === 'A') ? 0 : 1; var cur_cell_id = this.state.activecell; var clue_id = this.state.cell_to_clue_table[cur_cell_id][dind]; var cind = this.state.clue_to_cell_table[clue_id]; var [x, y] = this.cellPos(cind); var x_incr = !dind; var y_incr = !x_incr; var cell; for (; x < this.state.width && y < this.state.height; ) { cell = this.state.cells[this.state.width * y + x]; if (cell.isBlack()) break; cell.setState({"entry": cell.get('fill')}); x += x_incr; y += y_incr; } cell = this.state.cells[this.state.activecell]; cell.setState({'entry': cell.get('fill')}); this.setState({'cells': this.state.cells.slice()}); } selectClue(clue: XwordClue) { var cluenum = clue.get('index'); // set first empty cell in this clue as active var cell = this.state.clue_to_cell_table[cluenum]; var [start_x, start_y] = this.cellPos(cell); var empty_cell = this.findNextEmptyCell(clue.get('direction'), start_x, start_y); if (empty_cell != null) cell = empty_cell; this.selectCell(cell, clue.get('direction')); } closeModal() { this.setState({'dismissed_modal': true}); } showErrors() { for (var i=0; i < this.state.cells.length; i++) { var cell = this.state.cells[i]; if (!cell.isBlack()) { if (cell.get('entry') !== ' ' && cell.get('entry') !== cell.get('fill')) { cell.setState({incorrect: true}); } else { cell.setState({incorrect: false}); } } } var newcells = this.state.cells.slice(); this.setState({'cells': newcells}); } revealAll() { this.setState({'dismissed_modal': true}); for (var i=0; i < this.state.cells.length; i++) { var cell = this.state.cells[i]; if (!cell.isBlack()) cell.setState({'entry': cell.get('fill')}); } var newcells = this.state.cells.slice(); this.setState({'cells': newcells}); } serverUpdate(json: Object) { console.log("a server update happened..."); for (var i = 0; i < json.Entries.length; i++) { var ch = json.Entries[i].Value; var version = json.Entries[i].Version; var cell = this.state.cells[i]; if (cell && !cell.isBlack() && version > cell.get('version')) { cell.setState({entry: ch, version: version}); } } this.setState({version: json.Version}); } updateTimer(state: Object) { if (state.stopped) return; if (this.isCorrect()) { state.stopped = true; } this.saveStoredData(); this.state.timer.setState(state); this.setState({'timer': this.state.timer}); if (!this.state.solutionId) return; var entries = []; for (var i=0; i < this.state.cells.length; i++) { var cell = this.state.cells[i]; entries.push({'Version': cell.get('version'), 'Value': cell.get('entry')}); } if (this.state.modified) { // $FlowFixMe this.state.server.sendSolution(this.state.solutionId, this.state.version, entries); this.setState({modified: false}); } } startRebus() { this.setState({rebus: true}); } componentDidMount() { var self = this; window.addEventListener("keydown", (e) => self.handleKeyDown(e)); if (this.props.filename) { self.loadPuzzleURL(process.env.PUBLIC_URL + this.props.filename); return; } if (this.props.serverId) { self.loadServerPuzzle(this.props.serverId); return; } // TODO move to XwordMain ? // old-style URLs: // #[^/][hash] -> /s/hash var puzzle = window.location.hash.substring(1); if (puzzle.length && puzzle[0] !== '/' && this.props.history) { this.props.history.push("/s/" + puzzle); return; } // ?filename -> /load/filename puzzle = window.location.search.substring(1); if (puzzle.length && this.props.history) { this.props.history.push("/file/" + puzzle); return; } } componentWillUnmount() { var self = this; window.removeEventListener("keydown", (e) => self.handleKeyDown(e)); } render() { if (this.state.cells.length === 0) { if (this.props.filename || this.props.serverId) { return <Loading/>; } if (process.env.REACT_APP_HAS_SERVER) { return ( <div className="XwordMain"> <div className="xwordjs-text-box"> <h1>Collaborative XwordJS</h1> <p> Upload a crossword puzzle here (.puz or .xpf format). Once loaded, you can copy the random URL string and share with someone else to play together. </p> <FileInput onChange={(x, filename) => this.loadPuzzle(x, filename)} /> </div> </div> ); } return ( <div className="XwordMain"> <div className="xwordjs-text-box"> <h1>XwordJS</h1> <p> Select a crossword puzzle here (.puz or .xpf format) and then you can solve it in your browser. The file will remain local and not uploaded anywhere else. </p> <FileInput onChange={(x, filename) => this.loadPuzzle(x, filename)} /> </div> </div> ); } return ( <div className="XwordMain"> <Modal isOpen={this.isCorrect() && !this.state.dismissed_modal}> <h1>Nice job!</h1> <p>You solved it. Sorry for the anticlimactic dialog.</p> <p>It took {this.state.timer.elapsedStr(true)}.</p> <button onClick={this.closeModal}>OK</button> </Modal> <div className="xwordjs-vertical-container"> <div className="xwordjs-topbar"> <Title title={this.state.title} author={this.state.author}/> </div> <div className="xwordjs-timer-bar"> <Timer value={this.state.timer} onChange={(x) => this.updateTimer(x)}/> <DropdownButton title="Reveal"> <MenuItem eventKey="1" onClick={() => this.showErrors()}>Show Errors</MenuItem> <MenuItem divider/> <MenuItem eventKey="2" onClick={() => this.revealCell()}>Reveal Cell</MenuItem> <MenuItem eventKey="3" onClick={() => this.revealClue()}>Reveal Clue</MenuItem> <MenuItem divider/> <MenuItem eventKey="4" onClick={() => this.revealAll()}>Reveal All</MenuItem> </DropdownButton> <ButtonSpacer/> <Button onClick={() => this.setState({rebus: !this.state.rebus})} active={this.state.rebus} bsSize="xsmall">Rebus</Button> </div> <ClueBar value={this.state.clues}/> <div className="xwordjs-container" id="xwordjs-container"> <div className="xwordjs-grid" id="xwordjs-grid"> <Grid height={this.state.height} width={this.state.width} cells={this.state.cells} handleClick={(x) => this.handleClick(x)}/> </div> <Clues selectClue={(i) => this.selectClue(i)} value={this.state.clues}/> </div> <BabyLink filename={this.props.filename}/> <MobileKeyboard onClick={(code) => this.processKeyCode(code, false)}/> </div> </div> ); } } function BabyLink(props) { var link = []; if (props.filename === "2017-11-13.xd") { link.push(<a href="/images/syc.jpg">55-Across: healthy 7 lbs, 1 oz</a>) } return ( <div>{link}</div> ); } function XwordLoadFile(props) { return ( <XwordSolver filename={props.match.params.name}/> ); } function XwordLoadServer(props) { return ( <XwordSolver serverId={props.match.params.hash}/> ); } class XwordPuzzleListLoader extends Component { state: { items: ?array }; constructor(options) { super(); this.state = { items: null } Object.assign(this.state, options); }; componentDidMount() { var self = this; var server = new Server({base_url: process.env.PUBLIC_URL}) server.listSolutions().then(function (data) { self.setState({items: data}); }); } render() { if (!this.state.items) { return <Loading/>; } return <XwordPuzzleList puzzles={this.state.items}/>; } } const ButtonSpacer = (props) => ( <ButtonGroup><span className="xwordjs-button-spacer"/></ButtonGroup> ); function XwordPuzzleList(props) { var items = []; for (var i = 0; i < props.puzzles.length; i++) { var p = props.puzzles[i]; items.push(<li key={i}><Link to={"/s/" + p.Id}>{p.Title + " " + p.Author}<ProgressBar now={p.Progress} label={`${p.Progress}%`}/></Link></li>); } return <ul>{items}</ul>; } function XwordMainPanel() { return ( <Switch> <Route exact path="/" component={XwordSolver}/> <Route path="/file/:name" component={XwordLoadFile}/> <Route path="/s/:hash" component={XwordLoadServer}/> <Route path="/list" component={XwordPuzzleListLoader}/> </Switch> ); } function XwordMain() { return ( <div> <XwordMainPanel /> </div> ); } export default XwordMain;
src/Xword.js
// @flow import React, { Component } from 'react'; import Modal from 'react-modal'; import FileInput from './FileInput.js'; import Server from './Server.js'; import Cell from './Cell.js'; import Clues from './Clues.js'; import Loading from './Loading.js'; import {TimerState, Timer} from './Timer.js'; import { Route, Switch, Link } from 'react-router-dom'; import { ButtonGroup, ButtonToolbar, DropdownButton, MenuItem, ProgressBar, Button } from 'react-bootstrap'; import scrollIntoViewIfNeeded from 'scroll-into-view-if-needed'; import { TextDecoder } from 'text-encoding'; import './Xword.css'; // TODO // . clue-only entry // . auto-pause // . port nav enhancements (no auto next, skip to first blank) var Xd = require("./xd.js"); var Puz = require("./puz.js"); var Xpf = require("./xpf.js"); class XwordClue { state: { index: number, direction: string, number: number, clue: string, answer: string, active: boolean, crossActive: boolean }; constructor(options) { this.state = { 'index': 0, 'direction': 'A', 'number': 0, 'clue': '', 'answer': '', 'active': false, 'crossActive': false, }; Object.assign(this.state, options); } setState(newstate) { Object.assign(this.state, newstate); } get(key) : any { return this.state[key]; } } class XwordCell { state: { fill: string, entry: string, active: boolean, focus: boolean, circled: boolean, incorrect: boolean, number: number, version: number, }; constructor(options) { this.state = { fill: '.', entry: ' ', active: false, focus: false, circled: false, incorrect: false, version: 0, number: 0, }; Object.assign(this.state, options); } setState(newstate) { Object.assign(this.state, newstate); } get(key) : any { return this.state[key]; } isBlack() : boolean { return this.state.fill === '#'; } } function Title(props) { var title = props.title; var author = props.author ? " by " + props.author : ""; return ( <div className={"xwordjs-title"}> <span className={"xwordjs-title-text"}>{title}</span> <span className={"xwordjs-author-text"}>{author}</span> </div> ); } function ClueBar(props) { var text = ''; for (var i=0; i < props.value.length; i++) { var clue = props.value[i]; if (clue.get('active')) { text = clue.get('number') + ". " + clue.get('clue'); } } return <div className={"xwordjs-clue-bar"}>{text}</div>; } class Grid extends Component { render() { var rows = []; for (var i=0; i < this.props.height; i++) { var row_cells = []; for (var j=0; j < this.props.width; j++) { var ind = i * this.props.width + j; var fill = this.props.cells[ind].get('fill'); var entry = this.props.cells[ind].get('entry'); var active = this.props.cells[ind].get('active'); var focus = this.props.cells[ind].get('focus'); var circled = this.props.cells[ind].get('circled'); var incorrect = this.props.cells[ind].get('incorrect'); var number = this.props.cells[ind].get('number') || ''; var black = fill === '#'; if (fill === '#' || fill === '.') { fill = ' '; } var cell = <Cell id={"cell_" + ind} value={entry} key={"cell_" + ind} isBlack={black} isActive={active} isFocus={focus} isCircled={circled} isIncorrect={incorrect} isTop={i===0} isLeft={j===0} number={number} onClick={(x)=>this.props.handleClick(parseInt(x.substring(5), 10))}/>; row_cells.push(cell); } rows[i] = <div className="xwordjs-grid-row" key={"row_" + i}>{row_cells}</div>; } return ( <div id="xwordjs-grid-inner">{rows}</div> ); } } function MobileKeyboardKey(props) { return <div className="xwordjs-keyboard-key" onClick={() => props.onClick(props.code)}>{props.value}</div>; } function MobileKeyboard(props) { var keys = ["qwertyuiop", "asdfghjkl", "␣zxcvbnm⌫"]; var rows = []; for (var i=0; i < keys.length; i++) { var rowstr = keys[i]; var row_keys = []; for (var j=0; j < rowstr.length; j++) { var ch = rowstr.charAt(j); var code; if (ch === '␣') { code = 0x20; } else if (ch === '⌫') { code = 0x8; } else { code = ch.charCodeAt(0); } var key = <MobileKeyboardKey key={ch} onClick={props.onClick} code={code} value={ch}/>; row_keys.push(key); } rows[i] = <div className="xwordjs-keyboard-row" key={i}>{row_keys}</div>; } return ( <div className="xwordjs-keyboard">{rows}</div> ); } class XwordSolver extends Component { state: { height: number, width: number, cells: Array<XwordCell>, clues: Array<XwordClue>, title: string, author: string, timer: TimerState, activecell: number, direction: string, cell_to_clue_table: Array<Array<number>>, clue_to_cell_table: Array<number>, version: number, solutionId: ?string, dismissed_modal: boolean, modified: boolean, rebus: boolean, server: ?Server }; closeModal: Function; revealAll: Function; serverUpdate: Function; constructor() { super(); this.state = { 'height': 15, 'width': 15, 'cells': [], 'clues': [], 'title': '', 'author': '', 'timer': new TimerState(), 'activecell': 0, 'direction': 'A', 'cell_to_clue_table': [], 'clue_to_cell_table': [], 'dismissed_modal': false, 'version': 1, 'modified': false, 'solutionId': null, rebus: false, 'server': null, } this.closeModal = this.closeModal.bind(this); this.revealAll = this.revealAll.bind(this); this.serverUpdate = this.serverUpdate.bind(this); } loadServerPuzzle(id: string) { if (!process.env.REACT_APP_HAS_SERVER) return; var self = this; var server = new Server({base_url: process.env.PUBLIC_URL}) server .getSolution(id) .then(function(obj) { return server.getPuzzle(obj.PuzzleId) }) .then(function(data) { var decoder = new TextDecoder('utf-8'); var puz = new Xpf(decoder.decode(data)); self.setState({solutionId: id, server: server}); self.puzzleLoaded(id, puz); server.connect(id, self.serverUpdate); var entries = []; for (var i=0; i < self.state.cells.length; i++) { entries.push({'Version': -1, 'Value': ''}); } server.sendSolution(id, -1, entries); }); } loadPuzzle(file: File, filename : ?string) { var self = this; if (process.env.REACT_APP_HAS_SERVER) { var server = new Server({base_url: process.env.PUBLIC_URL}) server.uploadPuzzle(file) .then(function(obj) { var id = obj.Id; return server.startSolution(id); }) .then(function(obj) { var solutionId = obj.Id; document.location.hash = "/s/" + solutionId; self.loadServerPuzzle(solutionId); }); } else { this.loadPuzzleURL(window.URL.createObjectURL(file), filename); } } loadPuzzleURL(url: string, filename : ?string) { var self = this; var request = new Request(url); fetch(request).then(function(response) { return response.arrayBuffer(); }).then(function(data) { var puz; var fn = filename || url; var decoder; if (fn.endsWith("xd")) { decoder = new TextDecoder('utf-8'); // $FlowFixMe puz = new Xd(decoder.decode(data)); self.puzzleLoaded(url, puz); } else if (fn.endsWith("xml") || url.match(/^http/)) { decoder = new TextDecoder('utf-8'); // $FlowFixMe puz = new Xpf(decoder.decode(data)); self.puzzleLoaded(url, puz); } else { puz = new Puz(data); self.puzzleLoaded(url, puz); } }); } cellPos(clue_id: number) { var y = Math.floor(clue_id / this.state.width); var x = clue_id % this.state.width; return [x, y]; } navRight() { var [x, y] = this.cellPos(this.state.activecell); while (x < this.state.width) { x += 1; if (x < this.state.width && this.state.cells[y * this.state.width + x].get('fill') !== '#') break; } if (x === this.state.width) return; var activecell = y * this.state.width + x; this.selectCell(activecell, this.state.direction); } navLeft() { var [x, y] = this.cellPos(this.state.activecell); while (x >= 0) { x -= 1; if (x >= 0 && this.state.cells[y * this.state.width + x].get('fill') !== '#') break; } if (x < 0) return; var activecell = y * this.state.width + x; this.selectCell(activecell, this.state.direction); } navUp() { var [x, y] = this.cellPos(this.state.activecell); while (y >= 0) { y -= 1; if (y >= 0 && this.state.cells[y * this.state.width + x].get('fill') !== '#') break; } if (y < 0) return; var activecell = y * this.state.width + x; this.selectCell(activecell, this.state.direction); } navDown() { var [x, y] = this.cellPos(this.state.activecell); while (y < this.state.height) { y += 1; if (y < this.state.height && this.state.cells[y * this.state.width + x].get('fill') !== '#') break; } if (y === this.state.height) return; var activecell = y * this.state.width + x; this.selectCell(activecell, this.state.direction); } navNextClue() { var dind = (this.state.direction === 'A') ? 0 : 1; var cur_cell_id = this.state.activecell; var clue_id = this.state.cell_to_clue_table[cur_cell_id][dind]; var next_clue_id = (clue_id + 1) % this.state.clues.length; this.selectClue(this.state.clues[next_clue_id]); } navPrevClue() { var dind = (this.state.direction === 'A') ? 0 : 1; var cur_cell_id = this.state.activecell; var clue_id = this.state.cell_to_clue_table[cur_cell_id][dind]; var next_clue_id = (clue_id - 1) % this.state.clues.length; this.selectClue(this.state.clues[next_clue_id]); } findNextEmptyCell(direction: string, start_x: number, start_y: number, end_x: ?number, end_y: ?number): ?number { var dind = (direction === 'A') ? 0 : 1; var [x_incr, y_incr] = [1 - dind, dind]; var [x, y] = [start_x, start_y]; if (end_x === null || end_x === undefined) end_x = this.state.width; if (end_y === null || end_y === undefined) end_y = this.state.height; var len = (!dind) ? end_x - start_x : end_y - start_y; for (let i = 0; i < len; i++) { var cell_id = y * this.state.width + x; var cell = this.state.cells[cell_id]; if (cell.isBlack()) break; if (cell.get('entry') === ' ') return cell_id; x += x_incr; y += y_incr; } return null; } navNext() { var dind = (this.state.direction === 'A') ? 0 : 1; var cur_cell_id = this.state.activecell; var clue_id = this.state.cell_to_clue_table[cur_cell_id][dind]; var start_cell_id = this.state.clue_to_cell_table[clue_id]; var clue = this.state.clues[clue_id]; var [x, y] = this.cellPos(cur_cell_id); var [start_x, start_y] = this.cellPos(start_cell_id); var alen = clue.get('answer').length; var empty_cell_id = this.findNextEmptyCell(this.state.direction, x, y); // wrap if (empty_cell_id === null || empty_cell_id === undefined) { empty_cell_id = this.findNextEmptyCell(this.state.direction, start_x, start_y, x, y); } if (empty_cell_id === null || empty_cell_id === undefined) { // no empty square. [x, y] = this.cellPos(cur_cell_id); // if end of word, go to next word if ((this.state.direction === 'A' && x === start_x + alen - 1) || (this.state.direction === 'D' && y === start_y + alen - 1)) { this.navNextClue(); return; } // go to next word if (this.state.direction === 'A') x += 1; else y += 1; empty_cell_id = y * this.state.width + x; } this.selectCell(empty_cell_id, this.state.direction); } navPrev() { var dind = (this.state.direction === 'A') ? 0 : 1; var cur_cell_id = this.state.activecell; var clue_id = this.state.cell_to_clue_table[cur_cell_id][dind]; var start_cell_id = this.state.clue_to_cell_table[clue_id]; var [x, y] = this.cellPos(cur_cell_id); var [start_x, start_y] = this.cellPos(start_cell_id); if (this.state.direction === 'A') x -= 1; else y -= 1; if (x < start_x) x = start_x; if (y < start_y) y = start_y; var activecell = y * this.state.width + x; this.selectCell(activecell, this.state.direction); } switchDir() { var dir = this.state.direction === 'A' ? 'D' : 'A'; this.selectCell(this.state.activecell, dir); } type(ch: string) { var cell = this.state.cells[this.state.activecell]; if (this.state.rebus) { var text = cell.get('entry'); cell.setState({entry: text + ch}); this.setState({modified: true}) } else { cell.setState({'entry': ch, 'version': cell.get('version') + 1}); this.setState({modified: true}) this.navNext(); } } del() { var cell = this.state.cells[this.state.activecell]; if (this.state.rebus) { var text = cell.get('entry'); text = text.substr(0, text.length - 1); cell.setState({entry: text}); this.setState({modified: true}) } else { cell.setState({'entry': ' ', 'version': cell.get('version') + 1}); this.setState({modified: true}) this.selectCell(this.state.activecell, this.state.direction); } } backspace() { var cell = this.state.cells[this.state.activecell]; if (this.state.rebus) { var text = cell.get('entry'); text = text.substr(0, text.length - 1); cell.setState({entry: text}); this.setState({modified: true}) } else { cell.setState({'entry': ' ', 'version': cell.get('version') + 1}); this.setState({modified: true}) this.navPrev(); } } isCorrect() { for (var i=0; i < this.state.cells.length; i++) { var cell = this.state.cells[i]; var fill = cell.get('fill'); var entry = cell.get('entry'); if (fill !== '#' && (entry !== fill && entry !== fill.charAt(0))) return false; } return true; } processKeyCode(keyCode: number, shift: boolean) { // A-Z if ((keyCode >= 0x41 && keyCode <= 0x5a) || (keyCode >= 0x61 && keyCode <= 0x7a)) { var ch = String.fromCharCode(keyCode) this.type(ch.toUpperCase()); return true; } switch (keyCode) { case 0x8: this.backspace(); return true; case 0x9: if (!shift) this.navNextClue(); else this.navPrevClue(); return true; case 0x20: this.switchDir(); return true; case 0x25: this.navLeft(); return true; case 0x26: this.navUp(); return true; case 0x27: this.navRight(); return true; case 0x28: this.navDown(); return true; case 0x2e: this.del(); return true; default: return false; } } handleKeyDown(e: KeyboardEvent) { if (e.ctrlKey || e.altKey) return; if (this.state.direction === 'A' && (e.keyCode === 0x26 || e.keyCode === 0x28)) { this.selectCell(this.state.activecell, 'D'); e.preventDefault(); return; } if (this.state.direction === 'D' && (e.keyCode === 0x25 || e.keyCode === 0x27)) { this.selectCell(this.state.activecell, 'A'); e.preventDefault(); return; } if (this.processKeyCode(e.keyCode, e.shiftKey)) { e.preventDefault(); } } handleClick(i: number) { if (this.state.activecell === i) { this.switchDir(); } else { this.selectCell(i, this.state.direction); } } puzzleLoaded(url: string, puz: Object) { var grid = puz.grid; var flags = puz.flags; var maxx = grid[0].length; var maxy = grid.length; var i; var title = 'Untitled'; var author = 'Unknown'; for (i=0; i < puz.headers.length; i++) { var [header, value] = puz.headers[i]; if (header === 'Title') { title = value; } else if (header === 'Creator' || header === 'Author') { author = value; } } var cells = Array(maxx * maxy).fill(null); var cell_to_clue_table = Array(maxx * maxy).fill(null); var number_index = []; for (var y = 0; y < maxy; y++) { for (var x = 0; x < maxx; x++) { var fill = grid[y][x]; var is_black = fill === '#'; var number = 0; var start_of_xslot = (!is_black && (x === 0 || grid[y][x-1] === '#') && (x + 1 < maxx && grid[y][x+1] !== '#')); var start_of_yslot = (!is_black && (y === 0 || grid[y-1][x] === '#') && (y + 1 < maxy && grid[y+1][x] !== '#')); if (start_of_xslot || start_of_yslot) { number_index.push([x,y]); number = number_index.length; } var circled = false; if (flags) { circled = !!(flags[y][x] & puz.FLAGS.CIRCLED); } cells[y * maxx + x] = new XwordCell({ 'fill': fill, 'number': number, 'active': false, 'circled': circled }); cell_to_clue_table[y * maxx + x] = [null, null]; } } var clues = []; var clue_to_cell_table = []; for (i=0; i < puz.clues.length; i++) { var [type, cluestr, answer] = puz.clues[i]; var [dir, num] = type; var clue = new XwordClue({ 'index': i, 'direction': dir, 'number': num, 'clue': cluestr, 'answer': answer}); clues.push(clue); // clue_to_cell table: index into clues[] has the corresponding // cell id var xy = number_index[num - 1]; clue_to_cell_table[i] = xy[1] * maxx + xy[0]; // set up cell_to_clue_table: indexed by cell id, each entry // has a two element array (across, down) which contains the // index into clues[]. Iterate over answer in the direction // of the clue to set all cells making up the answer var ind = 0, xincr = 0, yincr = 0; if (dir === 'A') { xincr = 1; } else { ind = 1; yincr = 1; } [x, y] = xy; for (var j = 0; y < maxy && x < maxx; j++) { var cell = y * maxx + x; if (grid[y][x] === '#') break; cell_to_clue_table[cell][ind] = i; x += xincr; y += yincr; } } this.setState({ 'title': title, 'author': author, 'width': maxx, 'height': maxy, 'cells': cells, 'clues': clues, 'clue_to_cell_table': clue_to_cell_table, 'cell_to_clue_table': cell_to_clue_table }); this.loadStoredData(); this.selectCell(0, 'A', true); // set cluelist to match grid height var gridelem = document.getElementById("xwordjs-grid-inner"); var cluediv = document.getElementById("xwordjs-cluelist-container"); var cluelist = document.getElementsByClassName("xwordjs-cluelist"); var gridHeight = window.getComputedStyle(gridelem).getPropertyValue("height"); if (cluediv) cluediv.style.height = gridHeight; for (i = 0; i < cluelist.length; i++) { var e = cluelist[i]; var newheight = String(parseInt(gridHeight, 10) - 60) + "px"; e.style.height = newheight; } } saveStoredData() { var key = this.state.cells.map((x) => x.state.fill).join(""); var data = { entries: this.state.cells.map((x) => x.state.entry), elapsed: this.state.timer.get('elapsed') }; // avoid a race condition when first starting up if (!data.elapsed) return; localStorage.setItem(key, JSON.stringify(data)); } readStoredData() { var key = this.state.cells.map((x) => x.state.fill).join(""); var data = localStorage.getItem(key); if (!data) return null; return JSON.parse(data); } loadStoredData() { var data = this.readStoredData() if (!data) return; var entries = data.entries; var elapsed = data.elapsed; for (var i=0; i < entries.length; i++) { this.state.cells[i].setState({entry: entries[i]}); } this.setState({modified: true}) this.state.timer.setState({elapsed: elapsed}); this.setState({cells: this.state.cells, timer: this.state.timer}); } highlightClue(clue: XwordClue, active: boolean) { var cluenum = clue.get('index'); var cind = this.state.clue_to_cell_table[cluenum]; var [x, y] = this.cellPos(cind); var x_incr = clue.get('direction') === 'A' ? 1 : 0; var y_incr = !x_incr; for (; x < this.state.width && y < this.state.height; ) { var cell = this.state.cells[this.state.width * y + x]; if (cell.isBlack()) break; cell.setState({"active": active}); x += x_incr; y += y_incr; } } selectCell(cell_id: number, direction: string, initial: ?boolean) { var cell = this.state.cells[cell_id]; if (cell.isBlack()) return; var newclues = this.state.clues.slice(); var newcells = this.state.cells.slice(); // unselect existing selected cell and crosses var oldcell_id = this.state.activecell; var old_dind = (this.state.direction === 'A') ? 0 : 1; var oldclue = this.state.clues[this.state.cell_to_clue_table[oldcell_id][old_dind]]; var oldcross = this.state.clues[this.state.cell_to_clue_table[oldcell_id][1 - old_dind]]; var oldcell = this.state.cells[oldcell_id]; var dind = (direction === 'A') ? 0 : 1; var clue = this.state.clues[this.state.cell_to_clue_table[cell_id][dind]]; var cross = this.state.clues[this.state.cell_to_clue_table[cell_id][1 - dind]]; var e; var cluediv = document.getElementById("xwordjs-cluelist-container"); var display = window.getComputedStyle(cluediv).getPropertyValue("display"); var hasClues = display !== "none"; if (initial || oldcross !== cross) { if (oldcross) oldcross.setState({"crossActive": false}); if (cross) { cross.setState({"crossActive": true}); e = document.getElementById("clue_" + cross.get('index')); if (e && hasClues) scrollIntoViewIfNeeded(e); } } if (initial || oldclue !== clue) { if (oldclue) { oldclue.setState({"active": false}); this.highlightClue(oldclue, false); } if (clue) { clue.setState({"active": true}); this.highlightClue(clue, true); e = document.getElementById("clue_" + clue.get('index')); if (e && hasClues) scrollIntoViewIfNeeded(e); } } if (initial || oldcell_id !== cell_id) { oldcell.setState({focus: false}); cell.setState({focus: true}); } e = document.getElementById("cell_" + cell_id); if (e) { var rect = e.getBoundingClientRect(); var pelem = e.parentElement; var needsScroll = false; while (pelem) { var prect = pelem.getBoundingClientRect(); if (prect.left > rect.left || prect.right < rect.right || prect.top > rect.top || prect.bottom < rect.bottom) { needsScroll = true; break; } pelem = pelem.parentElement; } if (needsScroll) scrollIntoViewIfNeeded(e); } this.setState({'clues': newclues, 'cells': newcells, 'activecell': cell_id, 'direction': direction, rebus: false}); } revealCell() { var cell = this.state.cells[this.state.activecell]; cell.setState({'entry': cell.get('fill')}); this.setState({'cells': this.state.cells.slice()}); } revealClue() { var dind = (this.state.direction === 'A') ? 0 : 1; var cur_cell_id = this.state.activecell; var clue_id = this.state.cell_to_clue_table[cur_cell_id][dind]; var cind = this.state.clue_to_cell_table[clue_id]; var [x, y] = this.cellPos(cind); var x_incr = !dind; var y_incr = !x_incr; var cell; for (; x < this.state.width && y < this.state.height; ) { cell = this.state.cells[this.state.width * y + x]; if (cell.isBlack()) break; cell.setState({"entry": cell.get('fill')}); x += x_incr; y += y_incr; } cell = this.state.cells[this.state.activecell]; cell.setState({'entry': cell.get('fill')}); this.setState({'cells': this.state.cells.slice()}); } selectClue(clue: XwordClue) { var cluenum = clue.get('index'); // set first empty cell in this clue as active var cell = this.state.clue_to_cell_table[cluenum]; var [start_x, start_y] = this.cellPos(cell); var empty_cell = this.findNextEmptyCell(clue.get('direction'), start_x, start_y); if (empty_cell != null) cell = empty_cell; this.selectCell(cell, clue.get('direction')); } closeModal() { this.setState({'dismissed_modal': true}); } showErrors() { for (var i=0; i < this.state.cells.length; i++) { var cell = this.state.cells[i]; if (!cell.isBlack()) { if (cell.get('entry') !== ' ' && cell.get('entry') !== cell.get('fill')) { cell.setState({incorrect: true}); } else { cell.setState({incorrect: false}); } } } var newcells = this.state.cells.slice(); this.setState({'cells': newcells}); } revealAll() { this.setState({'dismissed_modal': true}); for (var i=0; i < this.state.cells.length; i++) { var cell = this.state.cells[i]; if (!cell.isBlack()) cell.setState({'entry': cell.get('fill')}); } var newcells = this.state.cells.slice(); this.setState({'cells': newcells}); } serverUpdate(json: Object) { console.log("a server update happened..."); for (var i = 0; i < json.Entries.length; i++) { var ch = json.Entries[i].Value; var version = json.Entries[i].Version; var cell = this.state.cells[i]; if (cell && !cell.isBlack() && version > cell.get('version')) { cell.setState({entry: ch, version: version}); } } this.setState({version: json.Version}); } updateTimer(state: Object) { if (state.stopped) return; if (this.isCorrect()) { state.stopped = true; } this.saveStoredData(); this.state.timer.setState(state); this.setState({'timer': this.state.timer}); if (!this.state.solutionId) return; var entries = []; for (var i=0; i < this.state.cells.length; i++) { var cell = this.state.cells[i]; entries.push({'Version': cell.get('version'), 'Value': cell.get('entry')}); } if (this.state.modified) { // $FlowFixMe this.state.server.sendSolution(this.state.solutionId, this.state.version, entries); this.setState({modified: false}); } } startRebus() { this.setState({rebus: true}); } componentDidMount() { var self = this; window.addEventListener("keydown", (e) => self.handleKeyDown(e)); if (this.props.filename) { self.loadPuzzleURL(process.env.PUBLIC_URL + this.props.filename); return; } if (this.props.serverId) { self.loadServerPuzzle(this.props.serverId); return; } // TODO move to XwordMain ? // old-style URLs: // #[^/][hash] -> /s/hash var puzzle = window.location.hash.substring(1); if (puzzle.length && puzzle[0] !== '/' && this.props.history) { this.props.history.push("/s/" + puzzle); return; } // ?filename -> /load/filename puzzle = window.location.search.substring(1); if (puzzle.length && this.props.history) { this.props.history.push("/file/" + puzzle); return; } } componentWillUnmount() { var self = this; window.removeEventListener("keydown", (e) => self.handleKeyDown(e)); } render() { if (this.state.cells.length === 0) { if (this.props.filename || this.props.serverId) { return <Loading/>; } if (process.env.REACT_APP_HAS_SERVER) { return ( <div className="XwordMain"> <div className="xwordjs-text-box"> <h1>Collaborative XwordJS</h1> <p> Upload a crossword puzzle here (.puz or .xpf format). Once loaded, you can copy the random URL string and share with someone else to play together. </p> <FileInput onChange={(x, filename) => this.loadPuzzle(x, filename)} /> </div> </div> ); } return ( <div className="XwordMain"> <div className="xwordjs-text-box"> <h1>XwordJS</h1> <p> Select a crossword puzzle here (.puz or .xpf format) and then you can solve it in your browser. The file will remain local and not uploaded anywhere else. </p> <FileInput onChange={(x, filename) => this.loadPuzzle(x, filename)} /> </div> </div> ); } return ( <div className="XwordMain"> <Modal isOpen={this.isCorrect() && !this.state.dismissed_modal}> <h1>Nice job!</h1> <p>You solved it. Sorry for the anticlimactic dialog.</p> <p>It took {this.state.timer.elapsedStr(true)}.</p> <button onClick={this.closeModal}>OK</button> </Modal> <div className="xwordjs-vertical-container"> <div className="xwordjs-topbar"> <Title title={this.state.title} author={this.state.author}/> </div> <div className="xwordjs-timer-bar"> <Timer value={this.state.timer} onChange={(x) => this.updateTimer(x)}/> <DropdownButton title="Reveal"> <MenuItem eventKey="1" onClick={() => this.showErrors()}>Show Errors</MenuItem> <MenuItem divider/> <MenuItem eventKey="2" onClick={() => this.revealCell()}>Reveal Cell</MenuItem> <MenuItem eventKey="3" onClick={() => this.revealClue()}>Reveal Clue</MenuItem> <MenuItem divider/> <MenuItem eventKey="4" onClick={() => this.revealAll()}>Reveal All</MenuItem> </DropdownButton> <ButtonSpacer/> <Button onClick={() => this.setState({rebus: !this.state.rebus})} active={this.state.rebus} bsSize="xsmall">Rebus</Button> </div> <ClueBar value={this.state.clues}/> <div className="xwordjs-container"> <div className="xwordjs-grid"> <Grid height={this.state.height} width={this.state.width} cells={this.state.cells} handleClick={(x) => this.handleClick(x)}/> </div> <Clues selectClue={(i) => this.selectClue(i)} value={this.state.clues}/> </div> <BabyLink filename={this.props.filename}/> <MobileKeyboard onClick={(code) => this.processKeyCode(code, false)}/> </div> </div> ); } } function BabyLink(props) { var link = []; if (props.filename === "2017-11-13.xd") { link.push(<a href="/images/syc.jpg">55-Across: healthy 7 lbs, 1 oz</a>) } return ( <div>{link}</div> ); } function XwordLoadFile(props) { return ( <XwordSolver filename={props.match.params.name}/> ); } function XwordLoadServer(props) { return ( <XwordSolver serverId={props.match.params.hash}/> ); } class XwordPuzzleListLoader extends Component { state: { items: ?array }; constructor(options) { super(); this.state = { items: null } Object.assign(this.state, options); }; componentDidMount() { var self = this; var server = new Server({base_url: process.env.PUBLIC_URL}) server.listSolutions().then(function (data) { self.setState({items: data}); }); } render() { if (!this.state.items) { return <Loading/>; } return <XwordPuzzleList puzzles={this.state.items}/>; } } const ButtonSpacer = (props) => ( <ButtonGroup><span className="xwordjs-button-spacer"/></ButtonGroup> ); function XwordPuzzleList(props) { var items = []; for (var i = 0; i < props.puzzles.length; i++) { var p = props.puzzles[i]; items.push(<li key={i}><Link to={"/s/" + p.Id}>{p.Title + " " + p.Author}<ProgressBar now={p.Progress} label={`${p.Progress}%`}/></Link></li>); } return <ul>{items}</ul>; } function XwordMainPanel() { return ( <Switch> <Route exact path="/" component={XwordSolver}/> <Route path="/file/:name" component={XwordLoadFile}/> <Route path="/s/:hash" component={XwordLoadServer}/> <Route path="/list" component={XwordPuzzleListLoader}/> </Switch> ); } function XwordMain() { return ( <div> <XwordMainPanel /> </div> ); } export default XwordMain;
ui: check only against xwordjs container for scroll checks The xword-grid div never moves with the scrollpane so clipping against it doesn't work correctly. This fixes scroll jank except on the bottom-most row where the characters are slightly larger than the enclosing cell.
src/Xword.js
ui: check only against xwordjs container for scroll checks
<ide><path>rc/Xword.js <ide> e = document.getElementById("cell_" + cell_id); <ide> if (e) { <ide> var rect = e.getBoundingClientRect(); <del> var pelem = e.parentElement; <del> var needsScroll = false; <del> <del> while (pelem) { <del> var prect = pelem.getBoundingClientRect(); <del> if (prect.left > rect.left || prect.right < rect.right || <del> prect.top > rect.top || prect.bottom < rect.bottom) { <del> needsScroll = true; <del> break; <del> } <del> pelem = pelem.parentElement; <del> } <del> if (needsScroll) <add> var container = document.getElementById("xwordjs-container"); <add> var prect = container.getBoundingClientRect(); <add> if (prect.left > rect.left || prect.right < rect.right || <add> prect.top > rect.top || prect.bottom < rect.bottom) { <ide> scrollIntoViewIfNeeded(e); <add> } <ide> } <ide> <ide> this.setState({'clues': newclues, 'cells': newcells, 'activecell': cell_id, 'direction': direction, rebus: false}); <ide> <Button onClick={() => this.setState({rebus: !this.state.rebus})} active={this.state.rebus} bsSize="xsmall">Rebus</Button> <ide> </div> <ide> <ClueBar value={this.state.clues}/> <del> <div className="xwordjs-container"> <del> <div className="xwordjs-grid"> <add> <div className="xwordjs-container" id="xwordjs-container"> <add> <div className="xwordjs-grid" id="xwordjs-grid"> <ide> <Grid height={this.state.height} width={this.state.width} cells={this.state.cells} handleClick={(x) => this.handleClick(x)}/> <ide> </div> <ide> <Clues selectClue={(i) => this.selectClue(i)} value={this.state.clues}/>
Java
apache-2.0
cd728418c4e39a8f601b661dd5ebcca6e526d116
0
igniterealtime/Openfire,guusdk/Openfire,GregDThomas/Openfire,akrherz/Openfire,GregDThomas/Openfire,guusdk/Openfire,igniterealtime/Openfire,guusdk/Openfire,GregDThomas/Openfire,akrherz/Openfire,GregDThomas/Openfire,igniterealtime/Openfire,igniterealtime/Openfire,guusdk/Openfire,akrherz/Openfire,GregDThomas/Openfire,akrherz/Openfire,igniterealtime/Openfire,akrherz/Openfire,guusdk/Openfire
/* * Copyright (C) 2004-2008 Jive Software. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jivesoftware.openfire.sasl; import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.NoSuchElementException; import java.util.StringTokenizer; import java.io.IOException; import javax.security.sasl.Sasl; import javax.security.sasl.SaslServer; import javax.security.sasl.SaslException; import javax.security.sasl.AuthorizeCallback; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.NameCallback; import javax.security.auth.callback.UnsupportedCallbackException; /** * Implements the PLAIN server-side mechanism. * (<a href="http://www.ietf.org/rfc/rfc4616.txt">RFC 4616</a>)<br> * <p> * client ----- {authzid, authcid, password} -----&gt; server * </p> * Each paramater sent to the server is seperated by a null character * The authorization ID (authzid) may be empty. * * @author Jay Kline */ public class SaslServerPlainImpl implements SaslServer { private String principal; private String username; //requested authorization identity private String password; private CallbackHandler cbh; private boolean completed; private boolean aborted; private int counter; public SaslServerPlainImpl(String protocol, String serverFqdn, Map props, CallbackHandler cbh) throws SaslException { this.cbh = cbh; this.completed = false; this.counter = 0; } /** * Returns the IANA-registered mechanism name of this SASL server. * ("PLAIN"). * @return A non-null string representing the IANA-registered mechanism name. */ @Override public String getMechanismName() { return "PLAIN"; } /** * Evaluates the response data and generates a challenge. * * If a response is received from the client during the authentication * process, this method is called to prepare an appropriate next * challenge to submit to the client. The challenge is null if the * authentication has succeeded and no more challenge data is to be sent * to the client. It is non-null if the authentication must be continued * by sending a challenge to the client, or if the authentication has * succeeded but challenge data needs to be processed by the client. * {@code isComplete()} should be called * after each call to {@code evaluateResponse()},to determine if any further * response is needed from the client. * * @param response The non-null (but possibly empty) response sent * by the client. * * @return The possibly null challenge to send to the client. * It is null if the authentication has succeeded and there is * no more challenge data to be sent to the client. * @exception SaslException If an error occurred while processing * the response or generating a challenge. */ @Override public byte[] evaluateResponse(byte[] response) throws SaslException { if (completed) { throw new IllegalStateException("PLAIN authentication already completed"); } if (aborted) { throw new IllegalStateException("PLAIN authentication previously aborted due to error"); } try { if(response.length != 0) { String data = new String(response, StandardCharsets.UTF_8); StringTokenizer tokens = new StringTokenizer(data, "\0"); if (tokens.countTokens() > 2) { username = tokens.nextToken(); principal = tokens.nextToken(); } else { username = tokens.nextToken(); principal = username; } password = tokens.nextToken(); NameCallback ncb = new NameCallback("PLAIN authentication ID: ",principal); VerifyPasswordCallback vpcb = new VerifyPasswordCallback(password.toCharArray()); cbh.handle(new Callback[]{ncb,vpcb}); if (vpcb.getVerified()) { vpcb.clearPassword(); AuthorizeCallback acb = new AuthorizeCallback(principal,username); cbh.handle(new Callback[]{acb}); if(acb.isAuthorized()) { username = acb.getAuthorizedID(); completed = true; } else { completed = true; username = null; throw new SaslException("PLAIN: user not authorized: "+principal); } } else { throw new SaslException("PLAIN: user not authorized: "+principal); } } else { //Client gave no initial response if( counter++ > 1 ) { throw new SaslException("PLAIN expects a response"); } return null; } } catch (UnsupportedCallbackException | IOException | NoSuchElementException e) { aborted = true; throw new SaslException("PLAIN authentication failed for: "+username, e); } return null; } /** * Determines whether the authentication exchange has completed. * This method is typically called after each invocation of * {@code evaluateResponse()} to determine whether the * authentication has completed successfully or should be continued. * @return true if the authentication exchange has completed; false otherwise. */ @Override public boolean isComplete() { return completed; } /** * Reports the authorization ID in effect for the client of this * session. * This method can only be called if isComplete() returns true. * @return The authorization ID of the client. * @exception IllegalStateException if this authentication session has not completed */ @Override public String getAuthorizationID() { if(completed) { return username; } else { throw new IllegalStateException("PLAIN authentication not completed"); } } /** * Unwraps a byte array received from the client. PLAIN supports no security layer. * * @throws SaslException if attempted to use this method. */ @Override public byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException { if(completed) { throw new IllegalStateException("PLAIN does not support integrity or privacy"); } else { throw new IllegalStateException("PLAIN authentication not completed"); } } /** * Wraps a byte array to be sent to the client. PLAIN supports no security layer. * * @throws SaslException if attempted to use this method. */ @Override public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException { if(completed) { throw new IllegalStateException("PLAIN does not support integrity or privacy"); } else { throw new IllegalStateException("PLAIN authentication not completed"); } } /** * Retrieves the negotiated property. * This method can be called only after the authentication exchange has * completed (i.e., when {@code isComplete()} returns true); otherwise, an * {@code IllegalStateException} is thrown. * * @param propName the property * @return The value of the negotiated property. If null, the property was * not negotiated or is not applicable to this mechanism. * @exception IllegalStateException if this authentication exchange has not completed */ @Override public Object getNegotiatedProperty(String propName) { if (completed) { if (propName.equals(Sasl.QOP)) { return "auth"; } else { return null; } } else { throw new IllegalStateException("PLAIN authentication not completed"); } } /** * Disposes of any system resources or security-sensitive information * the SaslServer might be using. Invoking this method invalidates * the SaslServer instance. This method is idempotent. * @throws SaslException If a problem was encountered while disposing * the resources. */ @Override public void dispose() throws SaslException { password = null; username = null; principal = null; completed = false; } }
xmppserver/src/main/java/org/jivesoftware/openfire/sasl/SaslServerPlainImpl.java
/* * Copyright (C) 2004-2008 Jive Software. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jivesoftware.openfire.sasl; import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.StringTokenizer; import java.io.IOException; import javax.security.sasl.Sasl; import javax.security.sasl.SaslServer; import javax.security.sasl.SaslException; import javax.security.sasl.AuthorizeCallback; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.NameCallback; import javax.security.auth.callback.UnsupportedCallbackException; /** * Implements the PLAIN server-side mechanism. * (<a href="http://www.ietf.org/rfc/rfc4616.txt">RFC 4616</a>)<br> * <p> * client ----- {authzid, authcid, password} -----&gt; server * </p> * Each paramater sent to the server is seperated by a null character * The authorization ID (authzid) may be empty. * * @author Jay Kline */ public class SaslServerPlainImpl implements SaslServer { private String principal; private String username; //requested authorization identity private String password; private CallbackHandler cbh; private boolean completed; private boolean aborted; private int counter; public SaslServerPlainImpl(String protocol, String serverFqdn, Map props, CallbackHandler cbh) throws SaslException { this.cbh = cbh; this.completed = false; this.counter = 0; } /** * Returns the IANA-registered mechanism name of this SASL server. * ("PLAIN"). * @return A non-null string representing the IANA-registered mechanism name. */ @Override public String getMechanismName() { return "PLAIN"; } /** * Evaluates the response data and generates a challenge. * * If a response is received from the client during the authentication * process, this method is called to prepare an appropriate next * challenge to submit to the client. The challenge is null if the * authentication has succeeded and no more challenge data is to be sent * to the client. It is non-null if the authentication must be continued * by sending a challenge to the client, or if the authentication has * succeeded but challenge data needs to be processed by the client. * {@code isComplete()} should be called * after each call to {@code evaluateResponse()},to determine if any further * response is needed from the client. * * @param response The non-null (but possibly empty) response sent * by the client. * * @return The possibly null challenge to send to the client. * It is null if the authentication has succeeded and there is * no more challenge data to be sent to the client. * @exception SaslException If an error occurred while processing * the response or generating a challenge. */ @Override public byte[] evaluateResponse(byte[] response) throws SaslException { if (completed) { throw new IllegalStateException("PLAIN authentication already completed"); } if (aborted) { throw new IllegalStateException("PLAIN authentication previously aborted due to error"); } try { if(response.length != 0) { String data = new String(response, StandardCharsets.UTF_8); StringTokenizer tokens = new StringTokenizer(data, "\0"); if (tokens.countTokens() > 2) { username = tokens.nextToken(); principal = tokens.nextToken(); } else { username = tokens.nextToken(); principal = username; } password = tokens.nextToken(); NameCallback ncb = new NameCallback("PLAIN authentication ID: ",principal); VerifyPasswordCallback vpcb = new VerifyPasswordCallback(password.toCharArray()); cbh.handle(new Callback[]{ncb,vpcb}); if (vpcb.getVerified()) { vpcb.clearPassword(); AuthorizeCallback acb = new AuthorizeCallback(principal,username); cbh.handle(new Callback[]{acb}); if(acb.isAuthorized()) { username = acb.getAuthorizedID(); completed = true; } else { completed = true; username = null; throw new SaslException("PLAIN: user not authorized: "+principal); } } else { throw new SaslException("PLAIN: user not authorized: "+principal); } } else { //Client gave no initial response if( counter++ > 1 ) { throw new SaslException("PLAIN expects a response"); } return null; } } catch (UnsupportedCallbackException | IOException e) { aborted = true; throw new SaslException("PLAIN authentication failed for: "+username, e); } return null; } /** * Determines whether the authentication exchange has completed. * This method is typically called after each invocation of * {@code evaluateResponse()} to determine whether the * authentication has completed successfully or should be continued. * @return true if the authentication exchange has completed; false otherwise. */ @Override public boolean isComplete() { return completed; } /** * Reports the authorization ID in effect for the client of this * session. * This method can only be called if isComplete() returns true. * @return The authorization ID of the client. * @exception IllegalStateException if this authentication session has not completed */ @Override public String getAuthorizationID() { if(completed) { return username; } else { throw new IllegalStateException("PLAIN authentication not completed"); } } /** * Unwraps a byte array received from the client. PLAIN supports no security layer. * * @throws SaslException if attempted to use this method. */ @Override public byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException { if(completed) { throw new IllegalStateException("PLAIN does not support integrity or privacy"); } else { throw new IllegalStateException("PLAIN authentication not completed"); } } /** * Wraps a byte array to be sent to the client. PLAIN supports no security layer. * * @throws SaslException if attempted to use this method. */ @Override public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException { if(completed) { throw new IllegalStateException("PLAIN does not support integrity or privacy"); } else { throw new IllegalStateException("PLAIN authentication not completed"); } } /** * Retrieves the negotiated property. * This method can be called only after the authentication exchange has * completed (i.e., when {@code isComplete()} returns true); otherwise, an * {@code IllegalStateException} is thrown. * * @param propName the property * @return The value of the negotiated property. If null, the property was * not negotiated or is not applicable to this mechanism. * @exception IllegalStateException if this authentication exchange has not completed */ @Override public Object getNegotiatedProperty(String propName) { if (completed) { if (propName.equals(Sasl.QOP)) { return "auth"; } else { return null; } } else { throw new IllegalStateException("PLAIN authentication not completed"); } } /** * Disposes of any system resources or security-sensitive information * the SaslServer might be using. Invoking this method invalidates * the SaslServer instance. This method is idempotent. * @throws SaslException If a problem was encountered while disposing * the resources. */ @Override public void dispose() throws SaslException { password = null; username = null; principal = null; completed = false; } }
fix NPE (Line: password = tokens.nextToken(); - nextToken() will throw an Exception if no further element is available) - could happen if client will send wrong data or abort connection?
xmppserver/src/main/java/org/jivesoftware/openfire/sasl/SaslServerPlainImpl.java
fix NPE (Line: password = tokens.nextToken(); - nextToken() will throw an Exception if no further element is available) - could happen if client will send wrong data or abort connection?
<ide><path>mppserver/src/main/java/org/jivesoftware/openfire/sasl/SaslServerPlainImpl.java <ide> <ide> import java.nio.charset.StandardCharsets; <ide> import java.util.Map; <add>import java.util.NoSuchElementException; <ide> import java.util.StringTokenizer; <ide> import java.io.IOException; <ide> import javax.security.sasl.Sasl; <ide> } <ide> return null; <ide> } <del> } catch (UnsupportedCallbackException | IOException e) { <add> } catch (UnsupportedCallbackException | IOException | NoSuchElementException e) { <ide> aborted = true; <ide> throw new SaslException("PLAIN authentication failed for: "+username, e); <ide> }
Java
apache-2.0
6ba4e503fdf935e2e06556474069f1fd0af060d1
0
gxa/gxa,gxa/gxa,gxa/gxa,gxa/gxa,gxa/gxa
/* * Copyright 2008-2010 Microarray Informatics Team, EMBL-European Bioinformatics Institute * * 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. * * * For further details of the Gene Expression Atlas project, including source code, * downloads and documentation, please see: * * http://gxa.github.com/gxa */ package uk.ac.ebi.gxa.dao; import org.dbunit.DataSourceBasedDBTestCase; import org.dbunit.dataset.IDataSet; import org.dbunit.dataset.xml.FlatXmlDataSet; import org.hibernate.SessionFactory; import org.junit.After; import org.junit.Before; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.transaction.annotation.Transactional; import javax.sql.DataSource; import java.io.InputStream; import java.sql.*; /** * Abstract TestCase useful for setting up an in memory (hypersonic) database, and creating a DBUnit environment for * testing DAO methods and other stuff. * * @author Tony Burdett */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration @TransactionConfiguration(transactionManager = "atlasTxManager", defaultRollback = false) @Transactional public abstract class AtlasDAOTestCase extends DataSourceBasedDBTestCase { private static final String ATLAS_DATA_RESOURCE = "atlas-be-db.xml"; @Autowired(required = true) protected DataSource atlasDataSource; @Autowired protected AtlasDAO atlasDAO; @Autowired protected ArrayDesignDAO arrayDesignDAO; @Autowired protected BioEntityDAO bioEntityDAO; @Autowired protected ExperimentDAO experimentDAO; @Autowired protected SessionFactory sessionFactory; protected IDataSet getDataSet() throws Exception { InputStream in = this.getClass().getClassLoader().getResourceAsStream(ATLAS_DATA_RESOURCE); return new FlatXmlDataSet(in); } @Override protected DataSource getDataSource() { return atlasDataSource; } /** * This sets up an in-memory database using Hypersonic, and uses DBUnit to dump sample data form atlas-be-db.xml into * this in-memory database. It then configures a SingleConnectionDataSource from spring to provide access to the * underlying DB connection. Finally, it initialises a JdbcTemplate using this datasource, and an AtlasDAO using * this template. After setup, you should be able to use atlasDAO to test method calls against the data configured * in the sample dataset, or add to it and check the resulting data. */ @Before public void setUp() throws Exception { createDatabase(); super.setUp(); } @After public void tearDown() throws Exception { super.tearDown(); destroyDatabase(); } public void createDatabase() throws SQLException, ClassNotFoundException { // get a database connection, that will create the DB if it doesn't exist yet Connection conn = atlasDataSource.getConnection("sa", ""); System.out.print("Creating test database tables..."); runStatement(conn, "CREATE TABLE A2_ORGANISM " + "(ORGANISMID bigint not null, " + "NAME VARCHAR(255), " + "CONSTRAINT SYS_C008043 PRIMARY KEY (ORGANISMID)) ;"); runStatement(conn, "CREATE TABLE A2_EXPERIMENT " + "(EXPERIMENTID bigint NOT NULL, " + "ABSTRACT VARCHAR(2000), " + "ACCESSION VARCHAR(255), " + "DESCRIPTION VARCHAR(2000), " + "PERFORMER VARCHAR(2000), " + "LAB VARCHAR(2000), " + "LOADDATE timestamp, " + "PMID VARCHAR(255)," + "PRIVATE bit," + "CURATED bit, " + "CONSTRAINT SYS_C008053 PRIMARY KEY (EXPERIMENTID)) ;"); runStatement(conn, "CREATE TABLE A2_EXPERIMENTASSET " + "(EXPERIMENTASSETID bigint not null, " + "EXPERIMENTID bigint not null, " + "DESCRIPTION VARCHAR(2000), " + "FILENAME VARCHAR(255), " + "NAME VARCHAR(255), " + "CONSTRAINT SYS_C009999 PRIMARY KEY (EXPERIMENTASSETID)) ;"); runStatement(conn, "CREATE TABLE A2_ARRAYDESIGN " + "(ARRAYDESIGNID bigint not null, " + "ACCESSION VARCHAR(255), " + "TYPE VARCHAR(255), " + "NAME VARCHAR(255), " + "PROVIDER VARCHAR(255), " + "MAPPINGSWID bigint, " + "CONSTRAINT SYS_C008062 PRIMARY KEY (ARRAYDESIGNID))"); runStatement(conn, "CREATE TABLE A2_PROPERTY " + "(PROPERTYID bigint not null, " + "NAME VARCHAR(255), " + "ACCESSION VARCHAR(255), " + "CONSTRAINT SYS_C008064 PRIMARY KEY (PROPERTYID));"); runStatement(conn, "CREATE TABLE A2_PROPERTYVALUE " + "(PROPERTYVALUEID bigint not null, " + "PROPERTYID bigint, " + "NAME VARCHAR(255), " + "CONSTRAINT SYS_C008066 PRIMARY KEY (PROPERTYVALUEID));"); runStatement(conn, "CREATE TABLE A2_ASSAY " + "(ASSAYID bigint not null, " + "ACCESSION VARCHAR(255), " + "EXPERIMENTID bigint not null, " + "ARRAYDESIGNID bigint not null, " + "CONSTRAINT SYS_C008055 PRIMARY KEY (ASSAYID), " + "CONSTRAINT FKA2_ASSAY856724 FOREIGN KEY (ARRAYDESIGNID) " + "REFERENCES A2_ARRAYDESIGN (ARRAYDESIGNID), " + "CONSTRAINT FKA2_ASSAY169476 FOREIGN KEY (EXPERIMENTID) " + "REFERENCES A2_EXPERIMENT (EXPERIMENTID)) ;"); runStatement(conn, "CREATE TABLE A2_ASSAYPV " + "(ASSAYPVID bigint not null, " + "ASSAYID bigint, " + "PROPERTYVALUEID bigint, " + "CONSTRAINT SYS_C008058 PRIMARY KEY (ASSAYPVID));"); runStatement(conn, "CREATE TABLE A2_SAMPLE " + "(SAMPLEID bigint not null, " + "EXPERIMENTID bigint not null, " + "ACCESSION VARCHAR(255), " + "ORGANISMID bigint, " + "CHANNEL VARCHAR(255), " + "CONSTRAINT SYS_C008059 PRIMARY KEY (SAMPLEID)," + "CONSTRAINT FKA2_SAMPLE12345 FOREIGN KEY (ORGANISMID) " + "REFERENCES A2_ORGANISM (ORGANISMID));"); runStatement(conn, " CREATE TABLE A2_SAMPLEPV " + "(SAMPLEPVID bigint not null, " + "SAMPLEID bigint not null, " + "PROPERTYVALUEID bigint, " + "CONSTRAINT SYS_C008061 PRIMARY KEY (SAMPLEPVID)) ;"); runStatement(conn, "CREATE TABLE A2_ASSAYSAMPLE " + "(ASSAYSAMPLEID bigint not null, " + "ASSAYID bigint, " + "SAMPLEID bigint, " + "CONSTRAINT SYS_C008067 PRIMARY KEY (ASSAYSAMPLEID)) ;"); runStatement(conn, "CREATE TABLE A2_GENE " + "(GENEID bigint, " + "ORGANISMID bigint not null, " + "IDENTIFIER VARCHAR(255), " + "NAME VARCHAR(255)) ;"); runStatement(conn, "CREATE TABLE A2_GENEPROPERTY " + "(GENEPROPERTYID bigint not null, " + "NAME VARCHAR(255), " + "AE2TABLENAME VARCHAR(255), " + "CONSTRAINT SYS_C008045 PRIMARY KEY (GENEPROPERTYID)) ;"); runStatement(conn, " CREATE TABLE A2_GENEGPV " + "(GENEGPVID bigint not null," + "GENEID bigint, " + "GENEPROPERTYVALUEID bigint, " + "VALUE VARCHAR(255), " + "CONSTRAINT SYS_C008049 PRIMARY KEY (GENEGPVID)) ;"); runStatement(conn, " CREATE TABLE A2_GENEPROPERTYVALUE " + "(GENEPROPERTYVALUEID bigint, " + "GENEPROPERTYID bigint, " + "VALUE VARCHAR(255)," + "CONSTRAINT PK_GENEPROPERTYVALUE PRIMARY KEY (GENEPROPERTYVALUEID)) ;"); runStatement(conn, "CREATE TABLE A2_SOFTWARE " + "(SOFTWAREID bigint, " + "NAME VARCHAR(255) NOT NULL, " + "VERSION VARCHAR(255) NOT NULL) ;"); runStatement(conn, "CREATE TABLE A2_BIOENTITY " + "(BIOENTITYID bigint, " + "ORGANISMID bigint not null, " + "NAME VARCHAR(255), " + "BIOENTITYTYPEID bigint not null, " + "IDENTIFIER VARCHAR(255)) ;"); runStatement(conn, "CREATE TABLE A2_BIOENTITYPROPERTY " + "(BIOENTITYPROPERTYID bigint not null, " + "NAME VARCHAR(255), " + "CONSTRAINT SYS_C008070 PRIMARY KEY (BIOENTITYPROPERTYID)) ;"); runStatement(conn, " CREATE TABLE A2_BIOENTITYBEPV " + "(BIOENTITYBEPVID bigint not null," + "BIOENTITYID bigint, " + "BEPROPERTYVALUEID bigint, " + "SOFTWAREID bigint, " + "CONSTRAINT SYS_C008071 PRIMARY KEY (BIOENTITYBEPVID )) ;"); runStatement(conn, " CREATE TABLE A2_BIOENTITYPROPERTYVALUE " + "(BEPROPERTYVALUEID bigint, " + "BIOENTITYPROPERTYID bigint, " + "VALUE VARCHAR(255) );"); runStatement(conn, " CREATE TABLE A2_BIOENTITYTYPE " + "(BIOENTITYTYPEID bigint, " + "NAME VARCHAR(255), " + "ID_FOR_INDEX VARCHAR(1), " + "ID_FOR_ANALYTICS VARCHAR(1), " + "PROP_FOR_INDEX VARCHAR(1) );"); runStatement(conn, " CREATE TABLE A2_BERELATIONTYPE " + "(BERELATIONTYPEID bigint, " + "NAME VARCHAR(255));"); runStatement(conn, "CREATE TABLE A2_BIOENTITY2BIOENTITY " + "(BE2BEID bigint, " + "BIOENTITYIDFROM bigint not null, " + "BIOENTITYIDTO bigint not null, " + "SOFTWAREID bigint not null, " + "BERELATIONTYPEID bigint not null);"); runStatement(conn, "CREATE TABLE A2_DESIGNELTBIOENTITY " + "(DEBEID bigint, " + "DESIGNELEMENTID bigint not null, " + "SOFTWAREID bigint not null, " + "BIOENTITYID bigint not null);"); runStatement(conn, "CREATE TABLE VWDESIGNELEMENTGENELINKED " + "(designelementid bigint not null, " + "accession VARCHAR(255) NOT NULL, " + "name VARCHAR(255) NOT NULL, " + "arraydesignid bigint not null, " + "bioentityid bigint not null, " + "identifier VARCHAR(255) NOT NULL, " + "organismid bigint not null, " + "mappingswid bigint not null, " + "annotationswid bigint not null) "); runStatement(conn, "CREATE TABLE VWDESIGNELEMENTGENEDIRECT " + "(designelementid bigint not null, " + "accession VARCHAR(255) NOT NULL, " + "name VARCHAR(255) NOT NULL, " + "arraydesignid bigint not null, " + "bioentityid bigint not null, " + "identifier VARCHAR(255) NOT NULL, " + "organismid bigint not null) "); runStatement(conn, "CREATE TABLE A2_DESIGNELEMENT " + "(DESIGNELEMENTID bigint not null, " + "ARRAYDESIGNID bigint, " + "GENEID bigint not null, " + "ACCESSION VARCHAR(255), " + "NAME VARCHAR(255), " + "TYPE VARCHAR(255), " + "ISCONTROL INTEGER, " + "CONSTRAINT SYS_C008063 PRIMARY KEY (DESIGNELEMENTID)) ;"); runStatement(conn, "CREATE TABLE A2_ONTOLOGYMAPPING " + "(EXPERIMENTID bigint not null, " + "ACCESSION VARCHAR(255), " + "PROPERTY VARCHAR(255), " + "PROPERTYVALUE VARCHAR(255), " + "ONTOLOGYTERM VARCHAR(255), " + "ONTOLOGYTERMNAME VARCHAR(255), " + "ONTOLOGYTERMID bigint, " + "ONTOLOGYNAME VARCHAR(255), " + "ISSAMPLEPROPERTY BOOLEAN, " + "ISASSAYPROPERTY BOOLEAN);"); runStatement(conn, "CREATE TABLE A2_ONTOLOGYTERM (\n" + " ONTOLOGYTERMID bigint not null\n" + " , ONTOLOGYID bigint not null\n" + " , TERM VARCHAR(4000)\n" + " , ACCESSION VARCHAR(255) NOT NULL\n" + " , DESCRIPTION VARCHAR(4000))"); runStatement(conn, "CREATE TABLE A2_ONTOLOGY (\n" + " ONTOLOGYID bigint not null\n" + " , name VARCHAR(255) NOT NULL\n" + " , SOURCE_URI VARCHAR(255) NOT NULL\n" + " , version VARCHAR(255) NOT NULL\n" + " , DESCRIPTION VARCHAR(4000))"); runStatement(conn, " CREATE TABLE A2_ASSAYPVONTOLOGY (\n" + " ASSAYPVONTOLOGYID bigint not null\n" + " , ONTOLOGYTERMID bigint not null\n" + " , ASSAYPVID bigint not null)"); runStatement(conn, " CREATE TABLE A2_SAMPLEPVONTOLOGY (\n" + " SAMPLEPVONTOLOGYID bigint not null\n" + " , ONTOLOGYTERMID bigint not null\n" + " , SAMPLEPVID bigint not null)"); runStatement(conn, "CREATE SCHEMA ATLASLDR AUTHORIZATION sa"); runStatement(conn, "CREATE PROCEDURE A2_EXPERIMENTSET(" + " IN Accession VARCHAR(255), IN Description VARCHAR(255)," + " IN Performer VARCHAR(255), IN Lab VARCHAR(255)," + " IN PMID VARCHAR(255), IN Abstract VARCHAR(255))\n" + " MODIFIES SQL DATA\n" + " LANGUAGE JAVA\n" + " EXTERNAL NAME 'CLASSPATH:uk.ac.ebi.gxa.dao.AtlasDAOTestCase.a2ExperimentSet'"); runStatement(conn, "CREATE PROCEDURE A2_ASSAYSET(\n" + " IN Accession VARCHAR(255), IN ExperimentAccession VARCHAR(255),\n" + " IN ArrayDesignAccession VARCHAR(255),\n" + " IN Properties CHAR ARRAY)\n" + " MODIFIES SQL DATA\n" + " LANGUAGE JAVA\n" + " EXTERNAL NAME 'CLASSPATH:uk.ac.ebi.gxa.dao.AtlasDAOTestCase.assaySet'"); runStatement(conn, "CREATE PROCEDURE ATLASLDR.A2_SAMPLESET(\n" + " IN ExperimentAccession VARCHAR(255), IN SampleAccession VARCHAR(255), " + " IN Assays INT ARRAY, IN Properties INT ARRAY, IN Channel VARCHAR(255))\n" + " MODIFIES SQL DATA\n" + " LANGUAGE JAVA\n" + " EXTERNAL NAME 'CLASSPATH:uk.ac.ebi.gxa.dao.AtlasDAOTestCase.a2SampleSet'"); runStatement(conn, "CREATE PROCEDURE ATLASLDR.LOAD_PROGRESS(\n" + " IN experiment_accession VARCHAR(255), IN stage VARCHAR(255), " + " IN status VARCHAR(255), IN load_type VARCHAR(255))\n" + " NO SQL\n" + " LANGUAGE JAVA\n" + " EXTERNAL NAME 'CLASSPATH:uk.ac.ebi.gxa.dao.AtlasDAOTestCase.loadProgress'"); runStatement(conn, "CREATE AGGREGATE FUNCTION wm_concat(" + " IN val VARCHAR(255), IN flag BOOLEAN, " + " INOUT register VARCHAR(255), INOUT counter INT)\n" + " RETURNS VARCHAR(512)\n" + " NO SQL\n" + " LANGUAGE JAVA\n" + " EXTERNAL NAME 'CLASSPATH:uk.ac.ebi.gxa.dao.AtlasDAOTestCase.wmConcat'"); runStatement(conn, "CREATE SEQUENCE A2_ARRAYDESIGN_SEQ START WITH 10000000"); runStatement(conn, "CREATE SEQUENCE A2_ASSAY_SEQ START WITH 10000000"); runStatement(conn, "CREATE SEQUENCE A2_ASSAYPV_SEQ START WITH 10000000"); runStatement(conn, "CREATE SEQUENCE A2_ASSET_SEQ START WITH 10000000"); runStatement(conn, "CREATE SEQUENCE A2_EXPERIMENT_SEQ START WITH 10000000"); runStatement(conn, "CREATE SEQUENCE A2_ONTOLOGY_SEQ START WITH 10000000"); runStatement(conn, "CREATE SEQUENCE A2_ONTOLOGYTERM_SEQ START WITH 10000000"); runStatement(conn, "CREATE SEQUENCE A2_ORGANISM_SEQ START WITH 10000000"); runStatement(conn, "CREATE SEQUENCE A2_PROPERTY_SEQ START WITH 10000000"); runStatement(conn, "CREATE SEQUENCE A2_PROPERTYVALUE_SEQ START WITH 10000000"); runStatement(conn, "CREATE SEQUENCE A2_SAMPLE_SEQ START WITH 10000000"); runStatement(conn, "CREATE SEQUENCE A2_SAMPLEPV_SEQ START WITH 10000000"); System.out.println("...done!"); conn.close(); } @SuppressWarnings("unused") public static String a2SampleOrganism(int id) { return "Sample Organism Placeholder: " + id; } @SuppressWarnings("unused") public static void a2ExperimentSet(Connection conn, String accession, String description, String performer, String lab, String pmid, String anAbstract) throws SQLException { // this mimics the stored procedure A2_EXPERIMENTSET in the actual DB Statement stmt = conn.createStatement(); // create an experimentid - no oracle id generators here! long experimentid = System.currentTimeMillis(); stmt.executeUpdate( "INSERT INTO A2_EXPERIMENT(experimentid, accession, description, performer, lab) " + "values (" + experimentid + ", '" + accession + "', '" + description + "', '" + performer + "', '" + lab + "');"); } @SuppressWarnings("unused") public static void assaySet(String accession, String experimentAccession, String arrayDesignAccession, Array properties) throws SQLException { Connection con = DriverManager.getConnection("jdbc:default:connection"); // this mimics the stored procedure A2_ASSAYSET in the actual DB // lookup ids from accession first Statement stmt = con.createStatement(); long experimentID = -1; long arrayDesignID = -1; ResultSet rs = stmt.executeQuery("SELECT e.experimentid " + "FROM a2_experiment e " + "WHERE e.accession = '" + experimentAccession + "';"); while (rs.next()) { experimentID = rs.getLong(1); } rs.close(); rs = stmt.executeQuery("SELECT d.arraydesignid " + "FROM a2_arraydesign d " + "WHERE d.accession = '" + arrayDesignAccession + "';"); while (rs.next()) { arrayDesignID = rs.getLong(1); } rs.close(); // create an assayid - no oracle id generators here! long assayid = System.currentTimeMillis(); stmt.executeQuery( "INSERT INTO A2_ASSAY(assayid, accession, experimentid, arraydesignid) " + "values (" + assayid + ", '" + accession + "', '" + experimentID + "', '" + arrayDesignID + "');"); stmt.close(); } @SuppressWarnings("unused") public static void a2SampleSet(String experimentAccession, String sampleAccession, Array assays, Array properties, String channel) throws SQLException { Connection con = DriverManager.getConnection("jdbc:default:connection"); // this mimics the stored procedure A2_SAMPLESET in the actual DB Statement stmt = con.createStatement(); // create an sampleid - no oracle id generators here! long sampleid = System.currentTimeMillis(); stmt.executeQuery( "INSERT INTO A2_SAMPLE(sampleid, accession, channel) " + "values (" + sampleid + ", '" + sampleAccession + "', '" + channel + "');"); } @SuppressWarnings("unused") public static String wmConcat(String in, Boolean flag, String[] register, Integer[] counter) { if (flag) { if (register[0] == null) { return null; } return register[0]; } if (in == null) { return null; } if (register[0] == null) { register[0] = in; counter[0] = 1; } else { register[0] += "," + in; counter[0]++; } return null; } @SuppressWarnings("unused") public static void loadProgress(String accession, String stage, String status, String load_type) throws Exception { } public void destroyDatabase() throws SQLException, ClassNotFoundException { Connection conn = atlasDataSource.getConnection(); runStatement(conn, "SHUTDOWN"); conn.close(); } private static void runStatement(Connection conn, String sql) throws SQLException { // just using raw sql here, prior to any dao/jdbctemplate setup Statement st = conn.createStatement(); st.execute(sql); st.close(); } }
atlas-dao/src/test/java/uk/ac/ebi/gxa/dao/AtlasDAOTestCase.java
/* * Copyright 2008-2010 Microarray Informatics Team, EMBL-European Bioinformatics Institute * * 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. * * * For further details of the Gene Expression Atlas project, including source code, * downloads and documentation, please see: * * http://gxa.github.com/gxa */ package uk.ac.ebi.gxa.dao; import org.dbunit.DataSourceBasedDBTestCase; import org.dbunit.dataset.IDataSet; import org.dbunit.dataset.xml.FlatXmlDataSet; import org.hibernate.SessionFactory; import org.junit.After; import org.junit.Before; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.transaction.annotation.Transactional; import javax.sql.DataSource; import java.io.InputStream; import java.sql.*; /** * Abstract TestCase useful for setting up an in memory (hypersonic) database, and creating a DBUnit environment for * testing DAO methods and other stuff. * * @author Tony Burdett */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration @TransactionConfiguration(transactionManager = "atlasTxManager", defaultRollback = false) @Transactional public abstract class AtlasDAOTestCase extends DataSourceBasedDBTestCase { private static final String ATLAS_DATA_RESOURCE = "atlas-be-db.xml"; @Autowired(required = true) protected DataSource atlasDataSource; @Autowired protected AtlasDAO atlasDAO; @Autowired protected ArrayDesignDAO arrayDesignDAO; @Autowired protected BioEntityDAO bioEntityDAO; @Autowired protected ExperimentDAO experimentDAO; @Autowired protected SessionFactory sessionFactory; protected IDataSet getDataSet() throws Exception { InputStream in = this.getClass().getClassLoader().getResourceAsStream(ATLAS_DATA_RESOURCE); return new FlatXmlDataSet(in); } @Override protected DataSource getDataSource() { return atlasDataSource; } /** * This sets up an in-memory database using Hypersonic, and uses DBUnit to dump sample data form atlas-be-db.xml into * this in-memory database. It then configures a SingleConnectionDataSource from spring to provide access to the * underlying DB connection. Finally, it initialises a JdbcTemplate using this datasource, and an AtlasDAO using * this template. After setup, you should be able to use atlasDAO to test method calls against the data configured * in the sample dataset, or add to it and check the resulting data. */ @Before public void setUp() throws Exception { createDatabase(); super.setUp(); } @After public void tearDown() throws Exception { super.tearDown(); destroyDatabase(); } public void createDatabase() throws SQLException, ClassNotFoundException { // get a database connection, that will create the DB if it doesn't exist yet Connection conn = atlasDataSource.getConnection("sa", ""); System.out.print("Creating test database tables..."); runStatement(conn, "CREATE TABLE A2_ORGANISM " + "(ORGANISMID bigint not null, " + "NAME VARCHAR(255), " + "CONSTRAINT SYS_C008043 PRIMARY KEY (ORGANISMID)) ;"); runStatement(conn, "CREATE TABLE A2_EXPERIMENT " + "(EXPERIMENTID bigint NOT NULL, " + "ABSTRACT VARCHAR(2000), " + "ACCESSION VARCHAR(255), " + "DESCRIPTION VARCHAR(2000), " + "PERFORMER VARCHAR(2000), " + "LAB VARCHAR(2000), " + "LOADDATE timestamp, " + "PMID VARCHAR(255)," + "PRIVATE bit," + "CURATED bit, " + "CONSTRAINT SYS_C008053 PRIMARY KEY (EXPERIMENTID)) ;"); runStatement(conn, "CREATE TABLE A2_EXPERIMENTASSET " + "(EXPERIMENTASSETID bigint not null, " + "EXPERIMENTID bigint not null, " + "DESCRIPTION VARCHAR(2000), " + "FILENAME VARCHAR(255), " + "NAME VARCHAR(255), " + "CONSTRAINT SYS_C009999 PRIMARY KEY (EXPERIMENTASSETID)) ;"); runStatement(conn, "CREATE TABLE A2_ARRAYDESIGN " + "(ARRAYDESIGNID bigint not null, " + "ACCESSION VARCHAR(255), " + "TYPE VARCHAR(255), " + "NAME VARCHAR(255), " + "PROVIDER VARCHAR(255), " + "MAPPINGSWID bigint, " + "CONSTRAINT SYS_C008062 PRIMARY KEY (ARRAYDESIGNID))"); runStatement(conn, "CREATE TABLE A2_PROPERTY " + "(PROPERTYID bigint not null, " + "NAME VARCHAR(255), " + "ACCESSION VARCHAR(255), " + "CONSTRAINT SYS_C008064 PRIMARY KEY (PROPERTYID));"); runStatement(conn, "CREATE TABLE A2_PROPERTYVALUE " + "(PROPERTYVALUEID bigint not null, " + "PROPERTYID bigint, " + "NAME VARCHAR(255), " + "CONSTRAINT SYS_C008066 PRIMARY KEY (PROPERTYVALUEID));"); runStatement(conn, "CREATE TABLE A2_ASSAY " + "(ASSAYID bigint not null, " + "ACCESSION VARCHAR(255), " + "EXPERIMENTID bigint not null, " + "ARRAYDESIGNID bigint not null, " + "CONSTRAINT SYS_C008055 PRIMARY KEY (ASSAYID), " + "CONSTRAINT FKA2_ASSAY856724 FOREIGN KEY (ARRAYDESIGNID) " + "REFERENCES A2_ARRAYDESIGN (ARRAYDESIGNID), " + "CONSTRAINT FKA2_ASSAY169476 FOREIGN KEY (EXPERIMENTID) " + "REFERENCES A2_EXPERIMENT (EXPERIMENTID)) ;"); runStatement(conn, "CREATE TABLE A2_ASSAYPV " + "(ASSAYPVID bigint not null, " + "ASSAYID bigint, " + "PROPERTYVALUEID bigint, " + "CONSTRAINT SYS_C008058 PRIMARY KEY (ASSAYPVID));"); runStatement(conn, "CREATE TABLE A2_SAMPLE " + "(SAMPLEID bigint not null, " + "EXPERIMENTID bigint not null, " + "ACCESSION VARCHAR(255), " + "ORGANISMID bigint, " + "CHANNEL VARCHAR(255), " + "CONSTRAINT SYS_C008059 PRIMARY KEY (SAMPLEID)," + "CONSTRAINT FKA2_SAMPLE12345 FOREIGN KEY (ORGANISMID) " + "REFERENCES A2_ORGANISM (ORGANISMID));"); runStatement(conn, " CREATE TABLE A2_SAMPLEPV " + "(SAMPLEPVID bigint not null, " + "SAMPLEID bigint not null, " + "PROPERTYVALUEID bigint, " + "CONSTRAINT SYS_C008061 PRIMARY KEY (SAMPLEPVID)) ;"); runStatement(conn, "CREATE TABLE A2_ASSAYSAMPLE " + "(ASSAYSAMPLEID bigint not null, " + "ASSAYID bigint, " + "SAMPLEID bigint, " + "CONSTRAINT SYS_C008067 PRIMARY KEY (ASSAYSAMPLEID)) ;"); runStatement(conn, "CREATE TABLE A2_GENE " + "(GENEID bigint, " + "ORGANISMID bigint not null, " + "IDENTIFIER VARCHAR(255), " + "NAME VARCHAR(255)) ;"); runStatement(conn, "CREATE TABLE A2_GENEPROPERTY " + "(GENEPROPERTYID bigint not null, " + "NAME VARCHAR(255), " + "AE2TABLENAME VARCHAR(255), " + "CONSTRAINT SYS_C008045 PRIMARY KEY (GENEPROPERTYID)) ;"); runStatement(conn, " CREATE TABLE A2_GENEGPV " + "(GENEGPVID bigint not null," + "GENEID bigint, " + "GENEPROPERTYVALUEID bigint, " + "VALUE VARCHAR(255), " + "CONSTRAINT SYS_C008049 PRIMARY KEY (GENEGPVID)) ;"); runStatement(conn, " CREATE TABLE A2_GENEPROPERTYVALUE " + "(GENEPROPERTYVALUEID bigint, " + "GENEPROPERTYID bigint, " + "VALUE VARCHAR(255)," + "CONSTRAINT PK_GENEPROPERTYVALUE PRIMARY KEY (GENEPROPERTYVALUEID)) ;"); runStatement(conn, "CREATE TABLE A2_SOFTWARE " + "(SOFTWAREID bigint, " + "NAME VARCHAR(255) NOT NULL, " + "VERSION VARCHAR(255) NOT NULL) ;"); runStatement(conn, "CREATE TABLE A2_BIOENTITY " + "(BIOENTITYID bigint, " + "ORGANISMID bigint not null, " + "NAME VARCHAR(255), " + "BIOENTITYTYPEID bigint not null, " + "IDENTIFIER VARCHAR(255)) ;"); runStatement(conn, "CREATE TABLE A2_BIOENTITYPROPERTY " + "(BIOENTITYPROPERTYID bigint not null, " + "NAME VARCHAR(255), " + "CONSTRAINT SYS_C008070 PRIMARY KEY (BIOENTITYPROPERTYID)) ;"); runStatement(conn, " CREATE TABLE A2_BIOENTITYBEPV " + "(BIOENTITYBEPVID bigint not null," + "BIOENTITYID bigint, " + "BEPROPERTYVALUEID bigint, " + "SOFTWAREID bigint, " + "CONSTRAINT SYS_C008071 PRIMARY KEY (BIOENTITYBEPVID )) ;"); runStatement(conn, " CREATE TABLE A2_BIOENTITYPROPERTYVALUE " + "(BEPROPERTYVALUEID bigint, " + "BIOENTITYPROPERTYID bigint, " + "VALUE VARCHAR(255) );"); runStatement(conn, " CREATE TABLE A2_BIOENTITYTYPE " + "(BIOENTITYTYPEID bigint, " + "NAME VARCHAR(255), " + "ID_FOR_INDEX VARCHAR(1), " + "ID_FOR_ANALYTICS VARCHAR(1), " + "PROP_FOR_INDEX VARCHAR(1) );"); runStatement(conn, " CREATE TABLE A2_BERELATIONTYPE " + "(BERELATIONTYPEID bigint, " + "NAME VARCHAR(255));"); runStatement(conn, "CREATE TABLE A2_BIOENTITY2BIOENTITY " + "(BE2BEID bigint, " + "BIOENTITYIDFROM bigint not null, " + "BIOENTITYIDTO bigint not null, " + "SOFTWAREID bigint not null, " + "BERELATIONTYPEID bigint not null);"); runStatement(conn, "CREATE TABLE A2_DESIGNELTBIOENTITY " + "(DEBEID bigint, " + "DESIGNELEMENTID bigint not null, " + "SOFTWAREID bigint not null, " + "BIOENTITYID bigint not null);"); runStatement(conn, "CREATE TABLE VWDESIGNELEMENTGENELINKED " + "(designelementid bigint not null, " + "accession VARCHAR(255) NOT NULL, " + "name VARCHAR(255) NOT NULL, " + "arraydesignid bigint not null, " + "bioentityid bigint not null, " + "identifier VARCHAR(255) NOT NULL, " + "organismid bigint not null, " + "mappingswid bigint not null, " + "annotationswid bigint not null) "); runStatement(conn, "CREATE TABLE VWDESIGNELEMENTGENEDIRECT " + "(designelementid bigint not null, " + "accession VARCHAR(255) NOT NULL, " + "name VARCHAR(255) NOT NULL, " + "arraydesignid bigint not null, " + "bioentityid bigint not null, " + "identifier VARCHAR(255) NOT NULL, " + "organismid bigint not null) "); runStatement(conn, "CREATE TABLE A2_DESIGNELEMENT " + "(DESIGNELEMENTID bigint not null, " + "ARRAYDESIGNID bigint, " + "GENEID bigint not null, " + "ACCESSION VARCHAR(255), " + "NAME VARCHAR(255), " + "TYPE VARCHAR(255), " + "ISCONTROL INTEGER, " + "CONSTRAINT SYS_C008063 PRIMARY KEY (DESIGNELEMENTID)) ;"); runStatement(conn, "CREATE TABLE A2_ONTOLOGYMAPPING " + "(EXPERIMENTID bigint not null, " + "ACCESSION VARCHAR(255), " + "PROPERTY VARCHAR(255), " + "PROPERTYVALUE VARCHAR(255), " + "ONTOLOGYTERM VARCHAR(255), " + "ONTOLOGYTERMNAME VARCHAR(255), " + "ONTOLOGYTERMID bigint, " + "ONTOLOGYNAME VARCHAR(255), " + "ISSAMPLEPROPERTY BOOLEAN, " + "ISASSAYPROPERTY BOOLEAN);"); runStatement(conn, "CREATE TABLE A2_ONTOLOGYTERM (\n" + " ONTOLOGYTERMID bigint not null\n" + " , ONTOLOGYID bigint not null\n" + " , TERM VARCHAR(4000)\n" + " , ACCESSION VARCHAR(255) NOT NULL\n" + " , DESCRIPTION VARCHAR(4000))"); runStatement(conn, "CREATE TABLE A2_ONTOLOGY (\n" + " ONTOLOGYID bigint not null\n" + " , name VARCHAR(255) NOT NULL\n" + " , SOURCE_URI VARCHAR(255) NOT NULL\n" + " , version VARCHAR(255) NOT NULL\n" + " , DESCRIPTION VARCHAR(4000))"); runStatement(conn, " CREATE TABLE A2_ASSAYPVONTOLOGY (\n" + " ASSAYPVONTOLOGYID bigint not null\n" + " , ONTOLOGYTERMID bigint not null\n" + " , ASSAYPVID bigint not null)"); runStatement(conn, " CREATE TABLE A2_SAMPLEPVONTOLOGY (\n" + " SAMPLEPVONTOLOGYID bigint not null\n" + " , ONTOLOGYTERMID bigint not null\n" + " , SAMPLEPVID bigint not null)"); runStatement(conn, "CREATE SCHEMA ATLASLDR AUTHORIZATION sa"); runStatement(conn, "CREATE PROCEDURE A2_EXPERIMENTSET(" + " IN Accession VARCHAR(255), IN Description VARCHAR(255)," + " IN Performer VARCHAR(255), IN Lab VARCHAR(255)," + " IN PMID VARCHAR(255), IN Abstract VARCHAR(255))\n" + " MODIFIES SQL DATA\n" + " LANGUAGE JAVA\n" + " EXTERNAL NAME 'CLASSPATH:uk.ac.ebi.gxa.dao.AtlasDAOTestCase.a2ExperimentSet'"); runStatement(conn, "CREATE PROCEDURE A2_ASSAYSET(\n" + " IN Accession VARCHAR(255), IN ExperimentAccession VARCHAR(255),\n" + " IN ArrayDesignAccession VARCHAR(255),\n" + " IN Properties CHAR ARRAY)\n" + " MODIFIES SQL DATA\n" + " LANGUAGE JAVA\n" + " EXTERNAL NAME 'CLASSPATH:uk.ac.ebi.gxa.dao.AtlasDAOTestCase.assaySet'"); runStatement(conn, "CREATE PROCEDURE ATLASLDR.A2_SAMPLESET(\n" + " IN ExperimentAccession VARCHAR(255), IN SampleAccession VARCHAR(255), " + " IN Assays INT ARRAY, IN Properties INT ARRAY, IN Channel VARCHAR(255))\n" + " MODIFIES SQL DATA\n" + " LANGUAGE JAVA\n" + " EXTERNAL NAME 'CLASSPATH:uk.ac.ebi.gxa.dao.AtlasDAOTestCase.a2SampleSet'"); runStatement(conn, "CREATE PROCEDURE ATLASLDR.LOAD_PROGRESS(\n" + " IN experiment_accession VARCHAR(255), IN stage VARCHAR(255), " + " IN status VARCHAR(255), IN load_type VARCHAR(255))\n" + " NO SQL\n" + " LANGUAGE JAVA\n" + " EXTERNAL NAME 'CLASSPATH:uk.ac.ebi.gxa.dao.AtlasDAOTestCase.loadProgress'"); runStatement(conn, "CREATE AGGREGATE FUNCTION wm_concat(" + " IN val VARCHAR(255), IN flag BOOLEAN, " + " INOUT register VARCHAR(255), INOUT counter INT)\n" + " RETURNS VARCHAR(512)\n" + " NO SQL\n" + " LANGUAGE JAVA\n" + " EXTERNAL NAME 'CLASSPATH:uk.ac.ebi.gxa.dao.AtlasDAOTestCase.wmConcat'"); runStatement(conn, "CREATE SEQUENCE A2_ARRAYDESIGN_SEQ"); runStatement(conn, "CREATE SEQUENCE A2_ASSAY_SEQ"); runStatement(conn, "CREATE SEQUENCE A2_ASSAYPV_SEQ"); runStatement(conn, "CREATE SEQUENCE A2_ASSET_SEQ"); runStatement(conn, "CREATE SEQUENCE A2_EXPERIMENT_SEQ"); runStatement(conn, "CREATE SEQUENCE A2_ONTOLOGY_SEQ"); runStatement(conn, "CREATE SEQUENCE A2_ONTOLOGYTERM_SEQ"); runStatement(conn, "CREATE SEQUENCE A2_ORGANISM_SEQ"); runStatement(conn, "CREATE SEQUENCE A2_PROPERTY_SEQ"); runStatement(conn, "CREATE SEQUENCE A2_PROPERTYVALUE_SEQ"); runStatement(conn, "CREATE SEQUENCE A2_SAMPLE_SEQ"); runStatement(conn, "CREATE SEQUENCE A2_SAMPLEPV_SEQ"); System.out.println("...done!"); conn.close(); } @SuppressWarnings("unused") public static String a2SampleOrganism(int id) { return "Sample Organism Placeholder: " + id; } @SuppressWarnings("unused") public static void a2ExperimentSet(Connection conn, String accession, String description, String performer, String lab, String pmid, String anAbstract) throws SQLException { // this mimics the stored procedure A2_EXPERIMENTSET in the actual DB Statement stmt = conn.createStatement(); // create an experimentid - no oracle id generators here! long experimentid = System.currentTimeMillis(); stmt.executeUpdate( "INSERT INTO A2_EXPERIMENT(experimentid, accession, description, performer, lab) " + "values (" + experimentid + ", '" + accession + "', '" + description + "', '" + performer + "', '" + lab + "');"); } @SuppressWarnings("unused") public static void assaySet(String accession, String experimentAccession, String arrayDesignAccession, Array properties) throws SQLException { Connection con = DriverManager.getConnection("jdbc:default:connection"); // this mimics the stored procedure A2_ASSAYSET in the actual DB // lookup ids from accession first Statement stmt = con.createStatement(); long experimentID = -1; long arrayDesignID = -1; ResultSet rs = stmt.executeQuery("SELECT e.experimentid " + "FROM a2_experiment e " + "WHERE e.accession = '" + experimentAccession + "';"); while (rs.next()) { experimentID = rs.getLong(1); } rs.close(); rs = stmt.executeQuery("SELECT d.arraydesignid " + "FROM a2_arraydesign d " + "WHERE d.accession = '" + arrayDesignAccession + "';"); while (rs.next()) { arrayDesignID = rs.getLong(1); } rs.close(); // create an assayid - no oracle id generators here! long assayid = System.currentTimeMillis(); stmt.executeQuery( "INSERT INTO A2_ASSAY(assayid, accession, experimentid, arraydesignid) " + "values (" + assayid + ", '" + accession + "', '" + experimentID + "', '" + arrayDesignID + "');"); stmt.close(); } @SuppressWarnings("unused") public static void a2SampleSet(String experimentAccession, String sampleAccession, Array assays, Array properties, String channel) throws SQLException { Connection con = DriverManager.getConnection("jdbc:default:connection"); // this mimics the stored procedure A2_SAMPLESET in the actual DB Statement stmt = con.createStatement(); // create an sampleid - no oracle id generators here! long sampleid = System.currentTimeMillis(); stmt.executeQuery( "INSERT INTO A2_SAMPLE(sampleid, accession, channel) " + "values (" + sampleid + ", '" + sampleAccession + "', '" + channel + "');"); } @SuppressWarnings("unused") public static String wmConcat(String in, Boolean flag, String[] register, Integer[] counter) { if (flag) { if (register[0] == null) { return null; } return register[0]; } if (in == null) { return null; } if (register[0] == null) { register[0] = in; counter[0] = 1; } else { register[0] += "," + in; counter[0]++; } return null; } @SuppressWarnings("unused") public static void loadProgress(String accession, String stage, String status, String load_type) throws Exception { } public void destroyDatabase() throws SQLException, ClassNotFoundException { Connection conn = atlasDataSource.getConnection(); runStatement(conn, "SHUTDOWN"); conn.close(); } private static void runStatement(Connection conn, String sql) throws SQLException { // just using raw sql here, prior to any dao/jdbctemplate setup Statement st = conn.createStatement(); st.execute(sql); st.close(); } }
Adjusting HSQL sequences so that they would not clash with the existing data
atlas-dao/src/test/java/uk/ac/ebi/gxa/dao/AtlasDAOTestCase.java
Adjusting HSQL sequences so that they would not clash with the existing data
<ide><path>tlas-dao/src/test/java/uk/ac/ebi/gxa/dao/AtlasDAOTestCase.java <ide> " LANGUAGE JAVA\n" + <ide> " EXTERNAL NAME 'CLASSPATH:uk.ac.ebi.gxa.dao.AtlasDAOTestCase.wmConcat'"); <ide> <del> runStatement(conn, "CREATE SEQUENCE A2_ARRAYDESIGN_SEQ"); <del> runStatement(conn, "CREATE SEQUENCE A2_ASSAY_SEQ"); <del> runStatement(conn, "CREATE SEQUENCE A2_ASSAYPV_SEQ"); <del> runStatement(conn, "CREATE SEQUENCE A2_ASSET_SEQ"); <del> runStatement(conn, "CREATE SEQUENCE A2_EXPERIMENT_SEQ"); <del> runStatement(conn, "CREATE SEQUENCE A2_ONTOLOGY_SEQ"); <del> runStatement(conn, "CREATE SEQUENCE A2_ONTOLOGYTERM_SEQ"); <del> runStatement(conn, "CREATE SEQUENCE A2_ORGANISM_SEQ"); <del> runStatement(conn, "CREATE SEQUENCE A2_PROPERTY_SEQ"); <del> runStatement(conn, "CREATE SEQUENCE A2_PROPERTYVALUE_SEQ"); <del> runStatement(conn, "CREATE SEQUENCE A2_SAMPLE_SEQ"); <del> runStatement(conn, "CREATE SEQUENCE A2_SAMPLEPV_SEQ"); <add> runStatement(conn, "CREATE SEQUENCE A2_ARRAYDESIGN_SEQ START WITH 10000000"); <add> runStatement(conn, "CREATE SEQUENCE A2_ASSAY_SEQ START WITH 10000000"); <add> runStatement(conn, "CREATE SEQUENCE A2_ASSAYPV_SEQ START WITH 10000000"); <add> runStatement(conn, "CREATE SEQUENCE A2_ASSET_SEQ START WITH 10000000"); <add> runStatement(conn, "CREATE SEQUENCE A2_EXPERIMENT_SEQ START WITH 10000000"); <add> runStatement(conn, "CREATE SEQUENCE A2_ONTOLOGY_SEQ START WITH 10000000"); <add> runStatement(conn, "CREATE SEQUENCE A2_ONTOLOGYTERM_SEQ START WITH 10000000"); <add> runStatement(conn, "CREATE SEQUENCE A2_ORGANISM_SEQ START WITH 10000000"); <add> runStatement(conn, "CREATE SEQUENCE A2_PROPERTY_SEQ START WITH 10000000"); <add> runStatement(conn, "CREATE SEQUENCE A2_PROPERTYVALUE_SEQ START WITH 10000000"); <add> runStatement(conn, "CREATE SEQUENCE A2_SAMPLE_SEQ START WITH 10000000"); <add> runStatement(conn, "CREATE SEQUENCE A2_SAMPLEPV_SEQ START WITH 10000000"); <ide> <ide> System.out.println("...done!"); <ide> conn.close();
Java
apache-2.0
2f24d55e875d85536c6afec5cf2a3d52a06f3ad9
0
troels/nz-presto,troels/nz-presto,troels/nz-presto,troels/nz-presto,troels/nz-presto
/* * 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.facebook.presto.sql; import com.facebook.presto.metadata.FunctionRegistry; import com.facebook.presto.metadata.Signature; import com.facebook.presto.operator.scalar.ScalarFunctionImplementation; import com.facebook.presto.spi.ConnectorSession; import com.google.common.base.Defaults; import com.google.common.base.Throwables; import java.lang.invoke.MethodHandle; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import static java.lang.invoke.MethodHandleProxies.asInterfaceInstance; import static java.util.Objects.requireNonNull; public class FunctionInvoker { private final FunctionRegistry registry; public FunctionInvoker(FunctionRegistry registry) { this.registry = requireNonNull(registry, "registry is null"); } public Object invoke(Signature function, ConnectorSession session, Object... arguments) { return invoke(function, session, Arrays.asList(arguments)); } /** * Arguments must be the native container type for the corresponding SQL types. * * Returns a value in the native container type corresponding to the declared SQL return type */ public Object invoke(Signature function, ConnectorSession session, List<Object> arguments) { ScalarFunctionImplementation implementation = registry.getScalarFunctionImplementation(function); MethodHandle method = implementation.getMethodHandle(); // handle function on instance method, to allow use of fields method = bindInstanceFactory(method, implementation); if (method.type().parameterCount() > 0 && method.type().parameterType(0) == ConnectorSession.class) { method = method.bindTo(session); } List<Object> actualArguments = new ArrayList<>(); for (int i = 0; i < arguments.size(); i++) { Object argument = arguments.get(i); Optional<Class> lambdaArgument = implementation.getLambdaInterface().get(i); if (lambdaArgument.isPresent() && !MethodHandle.class.equals(lambdaArgument.get())) { argument = asInterfaceInstance(lambdaArgument.get(), (MethodHandle) argument); } if (implementation.getNullFlags().get(i)) { boolean isNull = argument == null; if (isNull) { argument = Defaults.defaultValue(method.type().parameterType(actualArguments.size())); } actualArguments.add(argument); actualArguments.add(isNull); } else { actualArguments.add(argument); } } try { return method.invokeWithArguments(actualArguments); } catch (Throwable throwable) { throw Throwables.propagate(throwable); } } private static MethodHandle bindInstanceFactory(MethodHandle method, ScalarFunctionImplementation implementation) { if (!implementation.getInstanceFactory().isPresent()) { return method; } try { return method.bindTo(implementation.getInstanceFactory().get().invoke()); } catch (Throwable throwable) { if (throwable instanceof InterruptedException) { Thread.currentThread().interrupt(); } throw Throwables.propagate(throwable); } } }
presto-main/src/main/java/com/facebook/presto/sql/FunctionInvoker.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.sql; import com.facebook.presto.metadata.FunctionRegistry; import com.facebook.presto.metadata.Signature; import com.facebook.presto.operator.scalar.ScalarFunctionImplementation; import com.facebook.presto.spi.ConnectorSession; import com.google.common.base.Defaults; import com.google.common.base.Throwables; import java.lang.invoke.MethodHandle; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Objects.requireNonNull; public class FunctionInvoker { private final FunctionRegistry registry; public FunctionInvoker(FunctionRegistry registry) { this.registry = requireNonNull(registry, "registry is null"); } public Object invoke(Signature function, ConnectorSession session, Object... arguments) { return invoke(function, session, Arrays.asList(arguments)); } /** * Arguments must be the native container type for the corresponding SQL types. * * Returns a value in the native container type corresponding to the declared SQL return type */ public Object invoke(Signature function, ConnectorSession session, List<Object> arguments) { ScalarFunctionImplementation implementation = registry.getScalarFunctionImplementation(function); MethodHandle method = implementation.getMethodHandle(); if (method.type().parameterCount() > 0 && method.type().parameterType(0) == ConnectorSession.class) { method = method.bindTo(session); } Iterator<Object> iterator = arguments.iterator(); List<Object> actualArguments = new ArrayList<>(); for (int i = 0; i < method.type().parameterCount(); i++) { Class<?> parameterType = method.type().parameterType(i); checkArgument(iterator.hasNext(), "Not enough arguments provided for method: %s", method.type()); Object argument = iterator.next(); if (implementation.getNullFlags().get(i)) { boolean isNull = argument == null; if (isNull) { argument = Defaults.defaultValue(parameterType); } actualArguments.add(argument); actualArguments.add(isNull); // Skip the next method parameter which is marked @IsNull i++; } else { actualArguments.add(argument); } } checkArgument(!iterator.hasNext(), "Too many arguments provided for method: %s", method.type()); try { return method.invokeWithArguments(actualArguments); } catch (Throwable throwable) { throw Throwables.propagate(throwable); } } }
Unify ExpressionInterpreter.invoke and FunctionInvoker code FunctionInvoker missed code handling InstanceFactory, as well as single-method interface needed for lambdas.
presto-main/src/main/java/com/facebook/presto/sql/FunctionInvoker.java
Unify ExpressionInterpreter.invoke and FunctionInvoker code
<ide><path>resto-main/src/main/java/com/facebook/presto/sql/FunctionInvoker.java <ide> import java.lang.invoke.MethodHandle; <ide> import java.util.ArrayList; <ide> import java.util.Arrays; <del>import java.util.Iterator; <ide> import java.util.List; <add>import java.util.Optional; <ide> <del>import static com.google.common.base.Preconditions.checkArgument; <add>import static java.lang.invoke.MethodHandleProxies.asInterfaceInstance; <ide> import static java.util.Objects.requireNonNull; <ide> <ide> public class FunctionInvoker <ide> ScalarFunctionImplementation implementation = registry.getScalarFunctionImplementation(function); <ide> MethodHandle method = implementation.getMethodHandle(); <ide> <add> // handle function on instance method, to allow use of fields <add> method = bindInstanceFactory(method, implementation); <add> <ide> if (method.type().parameterCount() > 0 && method.type().parameterType(0) == ConnectorSession.class) { <ide> method = method.bindTo(session); <ide> } <del> Iterator<Object> iterator = arguments.iterator(); <ide> List<Object> actualArguments = new ArrayList<>(); <del> for (int i = 0; i < method.type().parameterCount(); i++) { <del> Class<?> parameterType = method.type().parameterType(i); <del> checkArgument(iterator.hasNext(), "Not enough arguments provided for method: %s", method.type()); <del> Object argument = iterator.next(); <add> for (int i = 0; i < arguments.size(); i++) { <add> Object argument = arguments.get(i); <add> Optional<Class> lambdaArgument = implementation.getLambdaInterface().get(i); <add> if (lambdaArgument.isPresent() && !MethodHandle.class.equals(lambdaArgument.get())) { <add> argument = asInterfaceInstance(lambdaArgument.get(), (MethodHandle) argument); <add> } <ide> if (implementation.getNullFlags().get(i)) { <ide> boolean isNull = argument == null; <ide> if (isNull) { <del> argument = Defaults.defaultValue(parameterType); <add> argument = Defaults.defaultValue(method.type().parameterType(actualArguments.size())); <ide> } <ide> actualArguments.add(argument); <ide> actualArguments.add(isNull); <del> // Skip the next method parameter which is marked @IsNull <del> i++; <ide> } <ide> else { <ide> actualArguments.add(argument); <ide> } <ide> } <del> <del> checkArgument(!iterator.hasNext(), "Too many arguments provided for method: %s", method.type()); <ide> <ide> try { <ide> return method.invokeWithArguments(actualArguments); <ide> throw Throwables.propagate(throwable); <ide> } <ide> } <add> <add> private static MethodHandle bindInstanceFactory(MethodHandle method, ScalarFunctionImplementation implementation) <add> { <add> if (!implementation.getInstanceFactory().isPresent()) { <add> return method; <add> } <add> <add> try { <add> return method.bindTo(implementation.getInstanceFactory().get().invoke()); <add> } <add> catch (Throwable throwable) { <add> if (throwable instanceof InterruptedException) { <add> Thread.currentThread().interrupt(); <add> } <add> throw Throwables.propagate(throwable); <add> } <add> } <ide> }
Java
mit
51d31b3d7bca19b0099a8f8058149a9a445339b6
0
t28hub/DraggableView
package com.t28.draggableview; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.view.Menu; import android.view.MenuItem; import android.view.View; import com.t28.draggablelistview.DraggableListView; import java.util.Arrays; import java.util.List; public class MainActivity extends ActionBarActivity implements ItemAdapter.OnItemClickListener { private DraggableListView mListView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mListView = (DraggableListView) findViewById(R.id.main_container); mListView.setHasFixedSize(true); mListView.setLayoutManager(new GridLayoutManager(this, 2, LinearLayoutManager.HORIZONTAL, false)); final List<String> dataSet = Arrays.asList(getResources().getStringArray(R.array.lineups)); final ItemAdapter adapter = new ItemAdapter(dataSet); adapter.setOnItemClickListener(this); mListView.setAdapter(adapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onItemClick(View view, int position) { } @Override public void onItemLongClick(View view, int position) { if (mListView.isDragging()) { return; } mListView.startDrag(view, new DraggableListView.ShadowBuilder(view)); } }
example/src/main/java/com/t28/draggableview/MainActivity.java
package com.t28.draggableview; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.GridLayoutManager; import android.view.Menu; import android.view.MenuItem; import android.view.View; import com.t28.draggablelistview.DraggableListView; import java.util.Arrays; import java.util.List; public class MainActivity extends ActionBarActivity implements ItemAdapter.OnItemClickListener { private DraggableListView mListView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mListView = (DraggableListView) findViewById(R.id.main_container); mListView.setHasFixedSize(true); mListView.setLayoutManager(new GridLayoutManager(this, 2)); final List<String> dataSet = Arrays.asList(getResources().getStringArray(R.array.lineups)); final ItemAdapter adapter = new ItemAdapter(dataSet); adapter.setOnItemClickListener(this); mListView.setAdapter(adapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onItemClick(View view, int position) { } @Override public void onItemLongClick(View view, int position) { if (mListView.isDragging()) { return; } mListView.startDrag(view, new DraggableListView.ShadowBuilder(view)); } }
水平方向のグリッドに変更
example/src/main/java/com/t28/draggableview/MainActivity.java
水平方向のグリッドに変更
<ide><path>xample/src/main/java/com/t28/draggableview/MainActivity.java <ide> import android.os.Bundle; <ide> import android.support.v7.app.ActionBarActivity; <ide> import android.support.v7.widget.GridLayoutManager; <add>import android.support.v7.widget.LinearLayoutManager; <ide> import android.view.Menu; <ide> import android.view.MenuItem; <ide> import android.view.View; <ide> <ide> mListView = (DraggableListView) findViewById(R.id.main_container); <ide> mListView.setHasFixedSize(true); <del> mListView.setLayoutManager(new GridLayoutManager(this, 2)); <add> mListView.setLayoutManager(new GridLayoutManager(this, 2, LinearLayoutManager.HORIZONTAL, false)); <ide> <ide> final List<String> dataSet = Arrays.asList(getResources().getStringArray(R.array.lineups)); <ide> final ItemAdapter adapter = new ItemAdapter(dataSet);
Java
apache-2.0
83f1e1ff08d7d910b7d34d1f954a28aca6caea9e
0
cloudiator/lance,cloudiator/lance
/* * Copyright (c) 2014-2015 University of Ulm * * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. 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. */ /* * Copyright (c) 2014-2015 University of Ulm * * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. 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 de.uniulm.omi.cloudiator.lance.client; import com.google.common.collect.Maps; import de.uniulm.omi.cloudiator.lance.LcaConstants; import de.uniulm.omi.cloudiator.lance.application.ApplicationId; import de.uniulm.omi.cloudiator.lance.application.ApplicationInstanceId; import de.uniulm.omi.cloudiator.lance.application.DeploymentContext; import de.uniulm.omi.cloudiator.lance.application.component.ComponentId; import de.uniulm.omi.cloudiator.lance.application.component.DeployableComponent; import de.uniulm.omi.cloudiator.lance.container.spec.os.OperatingSystem; import de.uniulm.omi.cloudiator.lance.lca.DeploymentException; import de.uniulm.omi.cloudiator.lance.lca.LcaException; import de.uniulm.omi.cloudiator.lance.lca.LcaRegistry; import de.uniulm.omi.cloudiator.lance.lca.LifecycleAgent; import de.uniulm.omi.cloudiator.lance.lca.container.ComponentInstanceId; import de.uniulm.omi.cloudiator.lance.lca.container.ContainerException; import de.uniulm.omi.cloudiator.lance.lca.container.ContainerStatus; import de.uniulm.omi.cloudiator.lance.lca.container.ContainerType; import de.uniulm.omi.cloudiator.lance.lca.registry.RegistrationException; import de.uniulm.omi.cloudiator.lance.lca.registry.RegistryFactory; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.RMISocketFactory; import java.util.Map; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; public final class LifecycleClient { private static Map<String, CacheEntry> lifecycleAgentCache = Maps.newConcurrentMap(); private static class CacheEntry { private final Registry registry; private final LifecycleAgent lifecycleAgent; private CacheEntry(Registry registry, LifecycleAgent lifecycleAgent) { checkNotNull(registry, "registry is null."); checkNotNull(lifecycleAgent, "lifecycleAgent is null"); this.registry = registry; this.lifecycleAgent = lifecycleAgent; } public Registry registry() { return registry; } public LifecycleAgent lifecycleAgent() { return lifecycleAgent; } } public static LifecycleClient getClient(String serverIp) throws RemoteException, NotBoundException { checkNotNull(serverIp); checkArgument(!serverIp.isEmpty()); return new LifecycleClient(serverIp); } private static final LcaRegistry currentRegistry; private final LifecycleAgent lifecycleAgent; private LifecycleClient(String serverIp) throws RemoteException, NotBoundException { this.lifecycleAgent = findLifecycleAgent(serverIp); } static { try { RMISocketFactory.setSocketFactory(new RMISocketFactory() { private final RMISocketFactory delegate = RMISocketFactory.getDefaultSocketFactory(); @Override public Socket createSocket(String host, int port) throws IOException { final Socket socket = delegate.createSocket(host, port); socket.setSoTimeout(30000); socket.setKeepAlive(true); return socket; } @Override public ServerSocket createServerSocket(int i) throws IOException { return delegate.createServerSocket(i); } }); } catch (IOException e) { throw new ExceptionInInitializerError(e); } try { currentRegistry = RegistryFactory.createRegistry(); } catch (RegistrationException e) { throw new ExceptionInInitializerError(e); } } public final ComponentInstanceId deploy(final DeploymentContext ctx, final DeployableComponent comp, final OperatingSystem os, final ContainerType containerType) throws DeploymentException { try { return lifecycleAgent.deployComponent(ctx, comp, os, containerType); } catch (RemoteException re) { throw new DeploymentException(handleRemoteException(re)); } catch (LcaException | ContainerException | RegistrationException e) { throw new DeploymentException(e); } } public ContainerStatus getComponentContainerStatus(ComponentInstanceId cid, String serverIp) throws DeploymentException { try { final LifecycleAgent lifecycleAgent = findLifecycleAgent(serverIp); return lifecycleAgent.getComponentContainerStatus(cid); } catch (RemoteException e) { throw new DeploymentException(handleRemoteException(e)); } catch (NotBoundException e) { throw new DeploymentException(new RegistrationException("bad registry handling.", e)); } } public void waitForDeployment(ComponentInstanceId cid) { try { while (!Thread.currentThread().isInterrupted()) { final ContainerStatus componentContainerStatus = lifecycleAgent.getComponentContainerStatus(cid); if (ContainerStatus.READY.equals(componentContainerStatus)) { return; } if (ContainerStatus.errorStates().contains(componentContainerStatus)) { throw new IllegalStateException(String .format("Container reached illegal state %s while waiting for state %s", componentContainerStatus, ContainerStatus.READY)); } Thread.sleep(10000); } } catch (RemoteException e) { throw new RuntimeException( String.format("Error while waiting for container %s to be ready.", cid), e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException("Got interrupted while waiting for container to be ready."); } } public final boolean undeploy(ComponentInstanceId componentInstanceId, ContainerType containerType) throws DeploymentException { try { return lifecycleAgent.stopComponentInstance(containerType, componentInstanceId); } catch (RemoteException e) { throw new DeploymentException(handleRemoteException(e)); } catch (LcaException | ContainerException e) { throw new DeploymentException(e); } } private static Exception handleRemoteException(RemoteException re) { Throwable t = re.getCause(); if (t == null) return new LcaException("network exception occurred"); if (t instanceof LcaException) return (LcaException) t; if (t instanceof RegistrationException) return (RegistrationException) t; return new LcaException("downstream exception occurred.", re); } private static synchronized LifecycleAgent findLifecycleAgent(String serverIp) throws RemoteException, NotBoundException { if (!lifecycleAgentCache.containsKey(serverIp)) { Registry reg = LocateRegistry.getRegistry(serverIp); Object o = reg.lookup(LcaConstants.AGENT_REGISTRY_KEY); lifecycleAgentCache.put(serverIp, new CacheEntry(reg, (LifecycleAgent) o)); } checkState(lifecycleAgentCache.containsKey(serverIp)); return lifecycleAgentCache.get(serverIp).lifecycleAgent(); } /** * @param myInstanceId the instance id * @param lsyAppId the aplication id * @return true if this application instance has been added successfully. false if it was already contained * in the registry. * @throws RegistrationException when an registration error occurs */ public boolean registerApplicationInstance(ApplicationInstanceId myInstanceId, ApplicationId lsyAppId) throws RegistrationException { return currentRegistry.addApplicationInstance(myInstanceId, lsyAppId, "<unknown name>"); } public void registerApplicationInstance(ApplicationInstanceId myInstanceId, ApplicationId lsyAppId, String name) throws RegistrationException { currentRegistry.addApplicationInstance(myInstanceId, lsyAppId, name); } public void registerComponentForApplicationInstance(ApplicationInstanceId myInstanceId, ComponentId zookeeperComponentId) throws RegistrationException { currentRegistry.addComponent(myInstanceId, zookeeperComponentId, "<unknown name>"); } public void registerComponentForApplicationInstance(ApplicationInstanceId myInstanceId, ComponentId zookeeperComponentId, String componentName) throws RegistrationException { currentRegistry.addComponent(myInstanceId, zookeeperComponentId, componentName); } public DeploymentContext initDeploymentContext(ApplicationId appId, ApplicationInstanceId appInstanceId) { return new DeploymentContext(appId, appInstanceId, currentRegistry); } }
client/src/main/java/de/uniulm/omi/cloudiator/lance/client/LifecycleClient.java
/* * Copyright (c) 2014-2015 University of Ulm * * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. 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. */ /* * Copyright (c) 2014-2015 University of Ulm * * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. 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 de.uniulm.omi.cloudiator.lance.client; import com.google.common.collect.Maps; import de.uniulm.omi.cloudiator.lance.LcaConstants; import de.uniulm.omi.cloudiator.lance.application.ApplicationId; import de.uniulm.omi.cloudiator.lance.application.ApplicationInstanceId; import de.uniulm.omi.cloudiator.lance.application.DeploymentContext; import de.uniulm.omi.cloudiator.lance.application.component.ComponentId; import de.uniulm.omi.cloudiator.lance.application.component.DeployableComponent; import de.uniulm.omi.cloudiator.lance.container.spec.os.OperatingSystem; import de.uniulm.omi.cloudiator.lance.lca.DeploymentException; import de.uniulm.omi.cloudiator.lance.lca.LcaException; import de.uniulm.omi.cloudiator.lance.lca.LcaRegistry; import de.uniulm.omi.cloudiator.lance.lca.LifecycleAgent; import de.uniulm.omi.cloudiator.lance.lca.container.ComponentInstanceId; import de.uniulm.omi.cloudiator.lance.lca.container.ContainerException; import de.uniulm.omi.cloudiator.lance.lca.container.ContainerStatus; import de.uniulm.omi.cloudiator.lance.lca.container.ContainerType; import de.uniulm.omi.cloudiator.lance.lca.registry.RegistrationException; import de.uniulm.omi.cloudiator.lance.lca.registry.RegistryFactory; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.util.Map; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; public final class LifecycleClient { private static Map<String, CacheEntry> lifecycleAgentCache = Maps.newConcurrentMap(); private static class CacheEntry { private final Registry registry; private final LifecycleAgent lifecycleAgent; private CacheEntry(Registry registry, LifecycleAgent lifecycleAgent) { checkNotNull(registry, "registry is null."); checkNotNull(lifecycleAgent, "lifecycleAgent is null"); this.registry = registry; this.lifecycleAgent = lifecycleAgent; } public Registry registry() { return registry; } public LifecycleAgent lifecycleAgent() { return lifecycleAgent; } } public static LifecycleClient getClient(String serverIp) throws RemoteException, NotBoundException { checkNotNull(serverIp); checkArgument(!serverIp.isEmpty()); return new LifecycleClient(serverIp); } private static final LcaRegistry currentRegistry; private final LifecycleAgent lifecycleAgent; private LifecycleClient(String serverIp) throws RemoteException, NotBoundException { this.lifecycleAgent = findLifecycleAgent(serverIp); } static { try { currentRegistry = RegistryFactory.createRegistry(); } catch (RegistrationException e) { throw new ExceptionInInitializerError(e); } } public final ComponentInstanceId deploy(final DeploymentContext ctx, final DeployableComponent comp, final OperatingSystem os, final ContainerType containerType) throws DeploymentException { try { return lifecycleAgent.deployComponent(ctx, comp, os, containerType); } catch (RemoteException re) { throw new DeploymentException(handleRemoteException(re)); } catch (LcaException | ContainerException | RegistrationException e) { throw new DeploymentException(e); } } public ContainerStatus getComponentContainerStatus(ComponentInstanceId cid, String serverIp) throws DeploymentException { try { final LifecycleAgent lifecycleAgent = findLifecycleAgent(serverIp); return lifecycleAgent.getComponentContainerStatus(cid); } catch (RemoteException e) { throw new DeploymentException(handleRemoteException(e)); } catch (NotBoundException e) { throw new DeploymentException(new RegistrationException("bad registry handling.", e)); } } public void waitForDeployment(ComponentInstanceId cid) { try { while (!Thread.currentThread().isInterrupted()) { final ContainerStatus componentContainerStatus = lifecycleAgent.getComponentContainerStatus(cid); if (ContainerStatus.READY.equals(componentContainerStatus)) { return; } if (ContainerStatus.errorStates().contains(componentContainerStatus)) { throw new IllegalStateException(String .format("Container reached illegal state %s while waiting for state %s", componentContainerStatus, ContainerStatus.READY)); } Thread.sleep(10000); } } catch (RemoteException e) { throw new RuntimeException( String.format("Error while waiting for container %s to be ready.", cid), e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException("Got interrupted while waiting for container to be ready."); } } public final boolean undeploy(ComponentInstanceId componentInstanceId, ContainerType containerType) throws DeploymentException { try { return lifecycleAgent.stopComponentInstance(containerType, componentInstanceId); } catch (RemoteException e) { throw new DeploymentException(handleRemoteException(e)); } catch (LcaException | ContainerException e) { throw new DeploymentException(e); } } private static Exception handleRemoteException(RemoteException re) { Throwable t = re.getCause(); if (t == null) return new LcaException("network exception occurred"); if (t instanceof LcaException) return (LcaException) t; if (t instanceof RegistrationException) return (RegistrationException) t; return new LcaException("downstream exception occurred.", re); } private static synchronized LifecycleAgent findLifecycleAgent(String serverIp) throws RemoteException, NotBoundException { if (!lifecycleAgentCache.containsKey(serverIp)) { Registry reg = LocateRegistry.getRegistry(serverIp); Object o = reg.lookup(LcaConstants.AGENT_REGISTRY_KEY); lifecycleAgentCache.put(serverIp, new CacheEntry(reg, (LifecycleAgent) o)); } checkState(lifecycleAgentCache.containsKey(serverIp)); return lifecycleAgentCache.get(serverIp).lifecycleAgent(); } /** * @param myInstanceId the instance id * @param lsyAppId the aplication id * @return true if this application instance has been added successfully. false if it was already contained * in the registry. * @throws RegistrationException when an registration error occurs */ public boolean registerApplicationInstance(ApplicationInstanceId myInstanceId, ApplicationId lsyAppId) throws RegistrationException { return currentRegistry.addApplicationInstance(myInstanceId, lsyAppId, "<unknown name>"); } public void registerApplicationInstance(ApplicationInstanceId myInstanceId, ApplicationId lsyAppId, String name) throws RegistrationException { currentRegistry.addApplicationInstance(myInstanceId, lsyAppId, name); } public void registerComponentForApplicationInstance(ApplicationInstanceId myInstanceId, ComponentId zookeeperComponentId) throws RegistrationException { currentRegistry.addComponent(myInstanceId, zookeeperComponentId, "<unknown name>"); } public void registerComponentForApplicationInstance(ApplicationInstanceId myInstanceId, ComponentId zookeeperComponentId, String componentName) throws RegistrationException { currentRegistry.addComponent(myInstanceId, zookeeperComponentId, componentName); } public DeploymentContext initDeploymentContext(ApplicationId appId, ApplicationInstanceId appInstanceId) { return new DeploymentContext(appId, appInstanceId, currentRegistry); } }
Set socket timeout for RMI
client/src/main/java/de/uniulm/omi/cloudiator/lance/client/LifecycleClient.java
Set socket timeout for RMI
<ide><path>lient/src/main/java/de/uniulm/omi/cloudiator/lance/client/LifecycleClient.java <ide> import de.uniulm.omi.cloudiator.lance.lca.registry.RegistrationException; <ide> import de.uniulm.omi.cloudiator.lance.lca.registry.RegistryFactory; <ide> <add>import java.io.IOException; <add>import java.net.ServerSocket; <add>import java.net.Socket; <ide> import java.rmi.NotBoundException; <ide> import java.rmi.RemoteException; <ide> import java.rmi.registry.LocateRegistry; <ide> import java.rmi.registry.Registry; <add>import java.rmi.server.RMISocketFactory; <ide> import java.util.Map; <ide> <ide> import static com.google.common.base.Preconditions.checkArgument; <ide> } <ide> <ide> static { <add> try { <add> RMISocketFactory.setSocketFactory(new RMISocketFactory() { <add> <add> private final RMISocketFactory delegate = RMISocketFactory.getDefaultSocketFactory(); <add> <add> @Override public Socket createSocket(String host, int port) throws IOException { <add> final Socket socket = delegate.createSocket(host, port); <add> socket.setSoTimeout(30000); <add> socket.setKeepAlive(true); <add> return socket; <add> } <add> <add> @Override public ServerSocket createServerSocket(int i) throws IOException { <add> return delegate.createServerSocket(i); <add> } <add> }); <add> } catch (IOException e) { <add> throw new ExceptionInInitializerError(e); <add> } <ide> try { <ide> currentRegistry = RegistryFactory.createRegistry(); <ide> } catch (RegistrationException e) {
Java
mit
992f596d9f65dc89e6b7f4756d082d9a87b63824
0
mevdschee/tqdev-metrics
package com.tqdev.metrics.jdbc; import static org.assertj.core.api.Assertions.assertThat; import java.sql.PreparedStatement; import java.sql.SQLException; import org.junit.Before; import org.junit.Test; public class InstrumentedDataSourceTest extends InstrumentedDataSourceTestBase { @Before public void initialize() { registry.reset(); } @Test public void shouldMeasureSelectSingleUserOnceWithPreparedStatement() throws SQLException { String sql = "select * from users where id = ?"; PreparedStatement statement = dataSource.getConnection().prepareStatement(sql); statement.setInt(1, 1); assertThat(statement.executeQuery()).isNotNull(); assertThat(registry.get("jdbc.Statement.Invocations", sql)).isEqualTo(1); assertThat(registry.get("jdbc.Statement.Durations", sql)).isEqualTo(123456789); } @Test public void shouldMeasureSelectSingleUserTwiceWithPreparedStatement() throws SQLException { String sql = "select * from users where id = ?"; PreparedStatement statement = dataSource.getConnection().prepareStatement(sql); statement.setInt(1, 1); assertThat(statement.executeQuery()).isNotNull(); assertThat(statement.executeQuery()).isNotNull(); assertThat(registry.get("jdbc.Statement.Invocations", sql)).isEqualTo(2); assertThat(registry.get("jdbc.Statement.Durations", sql)).isEqualTo(246913578); } }
metrics-jdbc/src/test/java/com/tqdev/metrics/jdbc/InstrumentedDataSourceTest.java
package com.tqdev.metrics.jdbc; import static org.assertj.core.api.Assertions.assertThat; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.junit.Before; import org.junit.Test; public class InstrumentedDataSourceTest extends InstrumentedDataSourceTestBase { @Before public void initialize() { registry.reset(); } @Test public void shouldMeasureSelectSingleUserOnceWithPreparedStatement() throws SQLException { String sql = "select * from users where id = ?"; PreparedStatement statement = dataSource.getConnection().prepareStatement(sql); statement.setInt(1, 1); ResultSet resultSet = statement.executeQuery(); assertThat(resultSet).isInstanceOf(ResultSet.class); assertThat(registry.get("jdbc.Statement.Invocations", sql)).isEqualTo(1); assertThat(registry.get("jdbc.Statement.Durations", sql)).isEqualTo(123456789); } @Test public void shouldMeasureSelectSingleUserTwiceWithPreparedStatement() throws SQLException { String sql = "select * from users where id = ?"; PreparedStatement statement = dataSource.getConnection().prepareStatement(sql); statement.setInt(1, 1); statement.executeQuery(); statement.executeQuery(); assertThat(registry.get("jdbc.Statement.Invocations", sql)).isEqualTo(2); assertThat(registry.get("jdbc.Statement.Durations", sql)).isEqualTo(246913578); } }
Improve tests
metrics-jdbc/src/test/java/com/tqdev/metrics/jdbc/InstrumentedDataSourceTest.java
Improve tests
<ide><path>etrics-jdbc/src/test/java/com/tqdev/metrics/jdbc/InstrumentedDataSourceTest.java <ide> import static org.assertj.core.api.Assertions.assertThat; <ide> <ide> import java.sql.PreparedStatement; <del>import java.sql.ResultSet; <ide> import java.sql.SQLException; <ide> <ide> import org.junit.Before; <ide> String sql = "select * from users where id = ?"; <ide> PreparedStatement statement = dataSource.getConnection().prepareStatement(sql); <ide> statement.setInt(1, 1); <del> ResultSet resultSet = statement.executeQuery(); <del> assertThat(resultSet).isInstanceOf(ResultSet.class); <add> assertThat(statement.executeQuery()).isNotNull(); <ide> assertThat(registry.get("jdbc.Statement.Invocations", sql)).isEqualTo(1); <ide> assertThat(registry.get("jdbc.Statement.Durations", sql)).isEqualTo(123456789); <ide> } <ide> String sql = "select * from users where id = ?"; <ide> PreparedStatement statement = dataSource.getConnection().prepareStatement(sql); <ide> statement.setInt(1, 1); <del> statement.executeQuery(); <del> statement.executeQuery(); <add> assertThat(statement.executeQuery()).isNotNull(); <add> assertThat(statement.executeQuery()).isNotNull(); <ide> assertThat(registry.get("jdbc.Statement.Invocations", sql)).isEqualTo(2); <ide> assertThat(registry.get("jdbc.Statement.Durations", sql)).isEqualTo(246913578); <ide> }
Java
agpl-3.0
25a17271bdb2a8aa91e481eaf804a4e15e436388
0
chris-dvdb/dvdb.de
package de.dvdb.infrastructure.amazon; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.xml.namespace.QName; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jboss.seam.annotations.AutoCreate; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Name; import com.amazon.soap.ecs.AWSECommerceService; import com.amazon.soap.ecs.AWSECommerceServicePortType; import com.amazon.soap.ecs.BrowseNode; import com.amazon.soap.ecs.BrowseNodes; import com.amazon.soap.ecs.Errors; import com.amazon.soap.ecs.Item; import com.amazon.soap.ecs.ItemLookup; import com.amazon.soap.ecs.ItemLookupRequest; import com.amazon.soap.ecs.ItemLookupResponse; import com.amazon.soap.ecs.Items; import com.amazon.soap.ecs.Offer; import com.amazon.soap.ecs.Request; import com.sun.xml.ws.api.message.Header; import com.sun.xml.ws.api.message.Headers; import com.sun.xml.ws.developer.WSBindingProvider; import de.dvdb.application.ApplicationSettings; import de.dvdb.domain.model.item.type.AmazonDVDItem; import de.dvdb.domain.model.pricing.Price; import de.dvdb.domain.service.AmazonService; @Stateless @TransactionAttribute(TransactionAttributeType.REQUIRED) @Name("amazonBridge") @AutoCreate public class AmazonServiceImpl implements AmazonService, Serializable { private static final long serialVersionUID = 965755125849259771L; @In ApplicationSettings applicationSettings; @PersistenceContext(unitName = "dvdb") EntityManager entityManager; private static Log log = LogFactory.getLog(AmazonServiceImpl.class .getName()); /** * Gets the current Amazon Price for an Amazon item. */ public Price getCurrentPriceForItem( de.dvdb.domain.model.item.type.Item amazonItem) { try { SignatureHelper sigo = new SignatureHelper(applicationSettings .getAmazonSecret()); String time = sigo.getTimestamp(); String sig = sigo.sign("ItemLookup" + time); AWSECommerceService service = new AWSECommerceService(); AWSECommerceServicePortType port = service .getAWSECommerceServicePort(); ItemLookup lookup = new ItemLookup(); ItemLookupRequest request = new ItemLookupRequest(); request.getResponseGroup().add("Offers"); request.getResponseGroup().add("SalesRank"); request.getResponseGroup().add("ItemIds"); request.getItemId().add(amazonItem.getAsin()); request.setIdType("ASIN"); lookup.getRequest().add(request); WSBindingProvider bp = (WSBindingProvider) port; Header h1 = Headers .create(new QName( "http://security.amazonaws.com/doc/2007-01-01/", "AWSAccessKeyId"), applicationSettings .getAmazonAccessKey()); Header h2 = Headers.create(new QName( "http://security.amazonaws.com/doc/2007-01-01/", "Timestamp"), time); Header h3 = Headers.create(new QName( "http://security.amazonaws.com/doc/2007-01-01/", "Signature"), sig); bp.setOutboundHeaders(h1, h2, h3); ItemLookupResponse response = port.itemLookup(lookup); List<Items> itemsArray = response.getItems(); handleErrors(itemsArray.get(0).getRequest()); List<Item> items = itemsArray.get(0).getItem(); if (items == null || items.size() != 1 || items.get(0) == null) return null; Item item = items.get(0); if (item.getOffers() == null) return null; // no offers for item List<Offer> offers = item.getOffers().getOffer(); // get offers Offer amaOff = getAmazonItem(offers); // what offers amazon? if (amaOff == null || amaOff.getOfferListing() == null || amaOff.getOfferListing().get(0) == null || amaOff.getOfferListing().get(0).getPrice() == null || amaOff.getOfferListing().get(0).getPrice().getAmount() == null) return null; int priceInCent = amaOff.getOfferListing().get(0).getPrice() .getAmount().intValue(); Double price = new Double(priceInCent) / 100; String availability = amaOff.getOfferListing().get(0) .getAvailability(); String productUrl = applicationSettings.getAmazonProduktUrl() .replaceAll("#ASIN#", item.getASIN()); Price p = new Price(); p.setItem(amazonItem); p.setAvailability(availability); p.setPrice(price); p.setUrl(productUrl); return p; } catch (Exception e) { log.error("Error accessing Amazon Webservice for fetching a price " + e); e.printStackTrace(); } return null; } /** * Creates a new AmazonItem based on the retrieved item attributes for an * ASIN. */ public AmazonDVDItem getAmazonDVDItemFull(String asin) { try { SignatureHelper sigo = new SignatureHelper(applicationSettings .getAmazonSecret()); String time = sigo.getTimestamp(); String sig = sigo.sign("ItemLookup" + time); log.info("Getting item details for asin " + asin + ". Sig " + sig); // Set the service: AWSECommerceService service = new AWSECommerceService(); AWSECommerceServicePortType port = service .getAWSECommerceServicePort(); ItemLookup lookup = new ItemLookup(); ItemLookupRequest request = new ItemLookupRequest(); request.getResponseGroup().add("Large"); request.getResponseGroup().add("Images"); request.getResponseGroup().add("SalesRank"); request.getResponseGroup().add("ItemIds"); request.getResponseGroup().add("ItemAttributes"); request.getResponseGroup().add("BrowseNodes"); request.getItemId().add(asin); request.setIdType("ASIN"); lookup.getRequest().add(request); WSBindingProvider bp = (WSBindingProvider) port; Header h1 = Headers .create(new QName( "http://security.amazonaws.com/doc/2007-01-01/", "AWSAccessKeyId"), applicationSettings .getAmazonAccessKey()); Header h2 = Headers.create(new QName( "http://security.amazonaws.com/doc/2007-01-01/", "Timestamp"), time); Header h3 = Headers.create(new QName( "http://security.amazonaws.com/doc/2007-01-01/", "Signature"), sig); bp.setOutboundHeaders(h1, h2, h3); ItemLookupResponse response = port.itemLookup(lookup); List<Items> itemsArray = response.getItems(); handleErrors(itemsArray.get(0).getRequest()); List<Item> items = itemsArray.get(0).getItem(); if (items == null || items.size() != 1 || items.get(0) == null) return null; Item item = items.get(0); AmazonDVDItem amazonItem = null; amazonItem = new AmazonDVDItem(item); log.info("Got details for asin " + asin + " " + amazonItem); return amazonItem; } catch (Exception e) { e.printStackTrace(); log.error("Error accessing Amazon Webservice " + e); } return null; } /** * Creates a new AmazonItem based on the retrieved item attributes for an * ASIN. */ public AmazonDVDItem getAmazonDVDItemLight(String asin) { try { SignatureHelper sigo = new SignatureHelper(applicationSettings .getAmazonSecret()); String time = sigo.getTimestamp(); String sig = sigo.sign("ItemLookup" + time); log.info("Getting item details for asin " + asin); AWSECommerceService service = new AWSECommerceService(); AWSECommerceServicePortType port = service .getAWSECommerceServicePort(); ItemLookup lookup = new ItemLookup(); ItemLookupRequest request = new ItemLookupRequest(); request.getResponseGroup().add("Images"); request.getResponseGroup().add("SalesRank"); request.getResponseGroup().add("ItemIds"); request.getResponseGroup().add("ItemAttributes"); request.getResponseGroup().add("BrowseNodes"); request.getItemId().add(asin); request.setIdType("ASIN"); lookup.getRequest().add(request); WSBindingProvider bp = (WSBindingProvider) port; Header h1 = Headers .create(new QName( "http://security.amazonaws.com/doc/2007-01-01/", "AWSAccessKeyId"), applicationSettings .getAmazonAccessKey()); Header h2 = Headers.create(new QName( "http://security.amazonaws.com/doc/2007-01-01/", "Timestamp"), time); Header h3 = Headers.create(new QName( "http://security.amazonaws.com/doc/2007-01-01/", "Signature"), sig); bp.setOutboundHeaders(h1, h2, h3); ItemLookupResponse response = port.itemLookup(lookup); List<Items> itemsArray = response.getItems(); handleErrors(itemsArray.get(0).getRequest()); List<Item> items = itemsArray.get(0).getItem(); if (items == null || items.size() != 1 || items.get(0) == null) return null; Item item = items.get(0); // browsenodes holen BrowseNodes bns = item.getBrowseNodes(); List<BrowseNode> nods = bns.getBrowseNode(); Set<String> allBrowseNodes = new HashSet<String>(); for (BrowseNode browseNode : nods) { addNodes(allBrowseNodes, browseNode); } AmazonDVDItem amazonItem = null; if (AmazonDVDItem.isDVD(allBrowseNodes)) { amazonItem = new AmazonDVDItem(); } // else if (AmazonGame.isGame(allBrowseNodes)) { // amazonItem = new AmazonGame(); // String pf = ""; // String[] pfs = item.getItemAttributes().getPlatform(); // for (String string : pfs) { // pf = pf + "<li>" + string + "</li>"; // } // ((AmazonGame) amazonItem).setPlattform(pf); // } // // else // amazonItem = new AmazonDVDItem(); amazonItem.setEan(item.getItemAttributes().getEAN()); amazonItem.setTitle(item.getItemAttributes().getTitle()); amazonItem.setAsin(item.getASIN()); amazonItem.setUrl(applicationSettings.getAmazonProduktUrl() .replaceAll("#ASIN#", item.getASIN())); if (item.getLargeImage() != null) amazonItem.setUrlImageLarge(item.getLargeImage().getURL()); if (item.getMediumImage() != null) amazonItem.setUrlImageMedium(item.getMediumImage().getURL()); if (item.getSmallImage() != null) amazonItem.setUrlImageSmall(item.getSmallImage().getURL()); if (item.getSalesRank() != null) { try { int salesRank = Integer.parseInt(item.getSalesRank() .replaceAll("\\.", "").replaceAll(",", "")); amazonItem.setSalesRank(salesRank); } catch (Exception e) { log.warn("Unable to parse sales rank " + item.getSalesRank().replaceAll("\\.", "") .replaceAll(",", "")); } } String releaseDateString = item.getItemAttributes() .getReleaseDate(); if (releaseDateString != null) { try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date releaseDate = sdf.parse(releaseDateString); amazonItem.setReleaseDateAmazon(releaseDate); } catch (Exception e) { log.warn("Unable to parse release date " + releaseDateString + ". " + e.getMessage()); } } // amazonItem.setBrowseNodes(allBrowseNodes.toArray(new String[0])); log.info("Got details for asin " + asin + " " + amazonItem); return amazonItem; } catch (Exception e) { log.error("Error accessing Amazon Webservice " + e); e.printStackTrace(); } return null; } // --- private helpers --------------------------------------------------- private void addNodes(Set<String> cats, BrowseNode node) { cats.add(node.getBrowseNodeId()); if (node.getAncestors() != null && node.getAncestors().getBrowseNode().size() > 0) { for (BrowseNode bn : node.getAncestors().getBrowseNode()) { addNodes(cats, bn); } } } private Offer getAmazonItem(List<Offer> offers) { if (offers == null) return null; for (int i = 0; i < offers.size(); i++) { if (offers.get(i).getMerchant() == null) continue; if (offers.get((i)).getMerchant().getMerchantId() == null) continue; if (!offers .get((i)) .getMerchant() .getMerchantId() .equalsIgnoreCase(applicationSettings.getAmazonMerchantId())) continue; else return offers.get(i); } return null; } private List<de.dvdb.domain.model.item.type.Item> replaceWithExistingItems( List<de.dvdb.domain.model.item.type.Item> items) { Map<String, de.dvdb.domain.model.item.type.Item> asins = new HashMap<String, de.dvdb.domain.model.item.type.Item>(); for (de.dvdb.domain.model.item.type.Item item : items) { asins.put(item.getAsin(), item); } List<de.dvdb.domain.model.item.type.Item> dbItems = entityManager .createQuery("from Item i where i.asin in (:asins)") .setParameter("asins", asins.keySet()).getResultList(); for (de.dvdb.domain.model.item.type.Item item : dbItems) { if (item.getAsin() != null) asins.put(item.getAsin(), item); } log.info("Found " + dbItems.size() + " in db " + dbItems); for (int i = 0; i < items.size(); i++) { items.set(i, asins.get(items.get(i).getAsin())); } return items; } private void handleErrors(Request request) { Errors errors = request.getErrors(); if (errors != null) { for (Errors.Error error : errors.getError()) { log.warn("Error while retrieving item: " + error.getMessage()); } } } }
dvdb-ejb/src/main/java/de/dvdb/infrastructure/amazon/AmazonServiceImpl.java
package de.dvdb.infrastructure.amazon; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.xml.namespace.QName; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jboss.seam.annotations.AutoCreate; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Name; import com.amazon.soap.ecs.AWSECommerceService; import com.amazon.soap.ecs.AWSECommerceServicePortType; import com.amazon.soap.ecs.BrowseNode; import com.amazon.soap.ecs.BrowseNodes; import com.amazon.soap.ecs.Errors; import com.amazon.soap.ecs.Item; import com.amazon.soap.ecs.ItemLookup; import com.amazon.soap.ecs.ItemLookupRequest; import com.amazon.soap.ecs.ItemLookupResponse; import com.amazon.soap.ecs.Items; import com.amazon.soap.ecs.Offer; import com.amazon.soap.ecs.Request; import com.sun.xml.ws.api.message.Header; import com.sun.xml.ws.api.message.Headers; import com.sun.xml.ws.developer.WSBindingProvider; import de.dvdb.application.ApplicationSettings; import de.dvdb.domain.model.item.type.AmazonDVDItem; import de.dvdb.domain.model.pricing.Price; import de.dvdb.domain.service.AmazonService; @Stateless @TransactionAttribute(TransactionAttributeType.REQUIRED) @Name("amazonBridge") @AutoCreate public class AmazonServiceImpl implements AmazonService, Serializable { private static final long serialVersionUID = 965755125849259771L; @In ApplicationSettings applicationSettings; @PersistenceContext(unitName = "dvdb") EntityManager entityManager; private static Log log = LogFactory.getLog(AmazonServiceImpl.class .getName()); /** * Gets the current Amazon Price for an Amazon item. */ public Price getCurrentPriceForItem( de.dvdb.domain.model.item.type.Item amazonItem) { try { SignatureHelper sigo = new SignatureHelper(applicationSettings .getAmazonSecret()); String time = sigo.getTimestamp(); String sig = sigo.sign("ItemLookup" + time); AWSECommerceService service = new AWSECommerceService(); AWSECommerceServicePortType port = service .getAWSECommerceServicePort(); ItemLookup lookup = new ItemLookup(); ItemLookupRequest request = new ItemLookupRequest(); request.getResponseGroup().add("Offers"); request.getResponseGroup().add("SalesRank"); request.getResponseGroup().add("ItemIds"); request.getItemId().add(amazonItem.getAsin()); request.setIdType("ASIN"); lookup.getRequest().add(request); WSBindingProvider bp = (WSBindingProvider) port; Header h1 = Headers .create(new QName( "http://security.amazonaws.com/doc/2007-01-01/", "AWSAccessKeyId"), applicationSettings .getAmazonAccessKey()); Header h2 = Headers.create(new QName( "http://security.amazonaws.com/doc/2007-01-01/", "Timestamp"), time); Header h3 = Headers.create(new QName( "http://security.amazonaws.com/doc/2007-01-01/", "Signature"), sig); bp.setOutboundHeaders(h1, h2, h3); ItemLookupResponse response = port.itemLookup(lookup); List<Items> itemsArray = response.getItems(); handleErrors(itemsArray.get(0).getRequest()); List<Item> items = itemsArray.get(0).getItem(); if (items == null || items.size() != 1 || items.get(0) == null) return null; Item item = items.get(0); if (item.getOffers() == null) return null; // no offers for item List<Offer> offers = item.getOffers().getOffer(); // get offers Offer amaOff = getAmazonItem(offers); // what offers amazon? if (amaOff == null || amaOff.getOfferListing() == null || amaOff.getOfferListing().get(0) == null || amaOff.getOfferListing().get(0).getPrice() == null || amaOff.getOfferListing().get(0).getPrice().getAmount() == null) return null; int priceInCent = amaOff.getOfferListing().get(0).getPrice() .getAmount().intValue(); Double price = new Double(priceInCent) / 100; String availability = amaOff.getOfferListing().get(0) .getAvailability(); String productUrl = applicationSettings.getAmazonProduktUrl() .replaceAll("#ASIN#", item.getASIN()); Price p = new Price(); p.setItem(amazonItem); p.setAvailability(availability); p.setPrice(price); p.setUrl(productUrl); return p; } catch (Exception e) { log.error("Error accessing Amazon Webservice for fetching a price " + e); } return null; } /** * Creates a new AmazonItem based on the retrieved item attributes for an * ASIN. */ public AmazonDVDItem getAmazonDVDItemFull(String asin) { try { SignatureHelper sigo = new SignatureHelper(applicationSettings .getAmazonSecret()); String time = sigo.getTimestamp(); String sig = sigo.sign("ItemLookup" + time); log.info("Getting item details for asin " + asin + ". Sig " + sig); // Set the service: AWSECommerceService service = new AWSECommerceService(); AWSECommerceServicePortType port = service .getAWSECommerceServicePort(); ItemLookup lookup = new ItemLookup(); ItemLookupRequest request = new ItemLookupRequest(); request.getResponseGroup().add("Large"); request.getResponseGroup().add("Images"); request.getResponseGroup().add("SalesRank"); request.getResponseGroup().add("ItemIds"); request.getResponseGroup().add("ItemAttributes"); request.getResponseGroup().add("BrowseNodes"); request.getItemId().add(asin); request.setIdType("ASIN"); lookup.getRequest().add(request); WSBindingProvider bp = (WSBindingProvider) port; Header h1 = Headers .create(new QName( "http://security.amazonaws.com/doc/2007-01-01/", "AWSAccessKeyId"), applicationSettings .getAmazonAccessKey()); Header h2 = Headers.create(new QName( "http://security.amazonaws.com/doc/2007-01-01/", "Timestamp"), time); Header h3 = Headers.create(new QName( "http://security.amazonaws.com/doc/2007-01-01/", "Signature"), sig); bp.setOutboundHeaders(h1, h2, h3); ItemLookupResponse response = port.itemLookup(lookup); List<Items> itemsArray = response.getItems(); handleErrors(itemsArray.get(0).getRequest()); List<Item> items = itemsArray.get(0).getItem(); if (items == null || items.size() != 1 || items.get(0) == null) return null; Item item = items.get(0); AmazonDVDItem amazonItem = null; amazonItem = new AmazonDVDItem(item); log.info("Got details for asin " + asin + " " + amazonItem); return amazonItem; } catch (Exception e) { e.printStackTrace(); log.error("Error accessing Amazon Webservice " + e); } return null; } /** * Creates a new AmazonItem based on the retrieved item attributes for an * ASIN. */ public AmazonDVDItem getAmazonDVDItemLight(String asin) { try { SignatureHelper sigo = new SignatureHelper(applicationSettings .getAmazonSecret()); String time = sigo.getTimestamp(); String sig = sigo.sign("ItemLookup" + time); log.info("Getting item details for asin " + asin); AWSECommerceService service = new AWSECommerceService(); AWSECommerceServicePortType port = service .getAWSECommerceServicePort(); ItemLookup lookup = new ItemLookup(); ItemLookupRequest request = new ItemLookupRequest(); request.getResponseGroup().add("Images"); request.getResponseGroup().add("SalesRank"); request.getResponseGroup().add("ItemIds"); request.getResponseGroup().add("ItemAttributes"); request.getResponseGroup().add("BrowseNodes"); request.getItemId().add(asin); request.setIdType("ASIN"); lookup.getRequest().add(request); WSBindingProvider bp = (WSBindingProvider) port; Header h1 = Headers .create(new QName( "http://security.amazonaws.com/doc/2007-01-01/", "AWSAccessKeyId"), applicationSettings .getAmazonAccessKey()); Header h2 = Headers.create(new QName( "http://security.amazonaws.com/doc/2007-01-01/", "Timestamp"), time); Header h3 = Headers.create(new QName( "http://security.amazonaws.com/doc/2007-01-01/", "Signature"), sig); bp.setOutboundHeaders(h1, h2, h3); ItemLookupResponse response = port.itemLookup(lookup); List<Items> itemsArray = response.getItems(); handleErrors(itemsArray.get(0).getRequest()); List<Item> items = itemsArray.get(0).getItem(); if (items == null || items.size() != 1 || items.get(0) == null) return null; Item item = items.get(0); // browsenodes holen BrowseNodes bns = item.getBrowseNodes(); List<BrowseNode> nods = bns.getBrowseNode(); Set<String> allBrowseNodes = new HashSet<String>(); for (BrowseNode browseNode : nods) { addNodes(allBrowseNodes, browseNode); } AmazonDVDItem amazonItem = null; if (AmazonDVDItem.isDVD(allBrowseNodes)) { amazonItem = new AmazonDVDItem(); } // else if (AmazonGame.isGame(allBrowseNodes)) { // amazonItem = new AmazonGame(); // String pf = ""; // String[] pfs = item.getItemAttributes().getPlatform(); // for (String string : pfs) { // pf = pf + "<li>" + string + "</li>"; // } // ((AmazonGame) amazonItem).setPlattform(pf); // } // // else // amazonItem = new AmazonDVDItem(); amazonItem.setEan(item.getItemAttributes().getEAN()); amazonItem.setTitle(item.getItemAttributes().getTitle()); amazonItem.setAsin(item.getASIN()); amazonItem.setUrl(applicationSettings.getAmazonProduktUrl() .replaceAll("#ASIN#", item.getASIN())); if (item.getLargeImage() != null) amazonItem.setUrlImageLarge(item.getLargeImage().getURL()); if (item.getMediumImage() != null) amazonItem.setUrlImageMedium(item.getMediumImage().getURL()); if (item.getSmallImage() != null) amazonItem.setUrlImageSmall(item.getSmallImage().getURL()); if (item.getSalesRank() != null) { try { int salesRank = Integer.parseInt(item.getSalesRank() .replaceAll("\\.", "").replaceAll(",", "")); amazonItem.setSalesRank(salesRank); } catch (Exception e) { log.warn("Unable to parse sales rank " + item.getSalesRank().replaceAll("\\.", "") .replaceAll(",", "")); } } String releaseDateString = item.getItemAttributes() .getReleaseDate(); if (releaseDateString != null) { try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date releaseDate = sdf.parse(releaseDateString); amazonItem.setReleaseDateAmazon(releaseDate); } catch (Exception e) { log.warn("Unable to parse release date " + releaseDateString + ". " + e.getMessage()); } } // amazonItem.setBrowseNodes(allBrowseNodes.toArray(new String[0])); log.info("Got details for asin " + asin + " " + amazonItem); return amazonItem; } catch (Exception e) { log.error("Error accessing Amazon Webservice " + e); e.printStackTrace(); } return null; } // --- private helpers --------------------------------------------------- private void addNodes(Set<String> cats, BrowseNode node) { cats.add(node.getBrowseNodeId()); if (node.getAncestors() != null && node.getAncestors().getBrowseNode().size() > 0) { for (BrowseNode bn : node.getAncestors().getBrowseNode()) { addNodes(cats, bn); } } } private Offer getAmazonItem(List<Offer> offers) { if (offers == null) return null; for (int i = 0; i < offers.size(); i++) { if (offers.get(i).getMerchant() == null) continue; if (offers.get((i)).getMerchant().getMerchantId() == null) continue; if (!offers .get((i)) .getMerchant() .getMerchantId() .equalsIgnoreCase(applicationSettings.getAmazonMerchantId())) continue; else return offers.get(i); } return null; } private List<de.dvdb.domain.model.item.type.Item> replaceWithExistingItems( List<de.dvdb.domain.model.item.type.Item> items) { Map<String, de.dvdb.domain.model.item.type.Item> asins = new HashMap<String, de.dvdb.domain.model.item.type.Item>(); for (de.dvdb.domain.model.item.type.Item item : items) { asins.put(item.getAsin(), item); } List<de.dvdb.domain.model.item.type.Item> dbItems = entityManager .createQuery("from Item i where i.asin in (:asins)") .setParameter("asins", asins.keySet()).getResultList(); for (de.dvdb.domain.model.item.type.Item item : dbItems) { if (item.getAsin() != null) asins.put(item.getAsin(), item); } log.info("Found " + dbItems.size() + " in db " + dbItems); for (int i = 0; i < items.size(); i++) { items.set(i, asins.get(items.get(i).getAsin())); } return items; } private void handleErrors(Request request) { Errors errors = request.getErrors(); if (errors != null) { for (Errors.Error error : errors.getError()) { log.warn("Error while retrieving item: " + error.getMessage()); } } } }
more fixes
dvdb-ejb/src/main/java/de/dvdb/infrastructure/amazon/AmazonServiceImpl.java
more fixes
<ide><path>vdb-ejb/src/main/java/de/dvdb/infrastructure/amazon/AmazonServiceImpl.java <ide> } catch (Exception e) { <ide> log.error("Error accessing Amazon Webservice for fetching a price " <ide> + e); <add> e.printStackTrace(); <ide> } <ide> return null; <ide> }
JavaScript
apache-2.0
c91f74755d5d64370bdfe1dbef8736a6bc68c0ff
0
pattisdr/osf.io,felliott/osf.io,icereval/osf.io,binoculars/osf.io,chennan47/osf.io,sloria/osf.io,felliott/osf.io,brianjgeiger/osf.io,saradbowman/osf.io,baylee-d/osf.io,CenterForOpenScience/osf.io,leb2dg/osf.io,chennan47/osf.io,CenterForOpenScience/osf.io,leb2dg/osf.io,pattisdr/osf.io,aaxelb/osf.io,TomBaxter/osf.io,icereval/osf.io,cslzchen/osf.io,TomBaxter/osf.io,chennan47/osf.io,erinspace/osf.io,adlius/osf.io,sloria/osf.io,binoculars/osf.io,laurenrevere/osf.io,brianjgeiger/osf.io,crcresearch/osf.io,adlius/osf.io,felliott/osf.io,HalcyonChimera/osf.io,mfraezz/osf.io,leb2dg/osf.io,saradbowman/osf.io,aaxelb/osf.io,brianjgeiger/osf.io,Johnetordoff/osf.io,adlius/osf.io,mattclark/osf.io,caseyrollins/osf.io,mfraezz/osf.io,caseyrollins/osf.io,Johnetordoff/osf.io,erinspace/osf.io,mattclark/osf.io,CenterForOpenScience/osf.io,crcresearch/osf.io,cslzchen/osf.io,icereval/osf.io,aaxelb/osf.io,adlius/osf.io,brianjgeiger/osf.io,baylee-d/osf.io,erinspace/osf.io,laurenrevere/osf.io,sloria/osf.io,cslzchen/osf.io,Johnetordoff/osf.io,binoculars/osf.io,HalcyonChimera/osf.io,caseyrollins/osf.io,CenterForOpenScience/osf.io,mfraezz/osf.io,pattisdr/osf.io,crcresearch/osf.io,mfraezz/osf.io,HalcyonChimera/osf.io,TomBaxter/osf.io,aaxelb/osf.io,laurenrevere/osf.io,Johnetordoff/osf.io,mattclark/osf.io,felliott/osf.io,HalcyonChimera/osf.io,baylee-d/osf.io,cslzchen/osf.io,leb2dg/osf.io
/** * Fangorn: Defining Treebeard options for OSF. * For Treebeard and _item API's check: https://github.com/caneruguz/treebeard/wiki */ 'use strict'; var $ = require('jquery'); var m = require('mithril'); var URI = require('URIjs'); var Raven = require('raven-js'); var Treebeard = require('treebeard'); var moment = require('moment'); var Dropzone = require('dropzone'); var lodashGet = require('lodash.get'); var $osf = require('js/osfHelpers'); var waterbutler = require('js/waterbutler'); var iconmap = require('js/iconmap'); var storageAddons = require('json!storageAddons.json'); // CSS require('css/fangorn.css'); var tbOptions; var noop = function () { }; var tempCounter = 1; var STATE_MAP = { upload: { display: 'Upload pending...' }, copy: { display: 'Copying ' }, delete: { display: 'Deleting ' }, move: { display: 'Moving ' }, rename: { display: 'Renaming ' } }; var SYNC_UPLOAD_ADDONS = ['github', 'dataverse']; var READ_ONLY_ADDONS = ['bitbucket', 'gitlab', 'onedrive']; var CONFLICT_INFO = { skip: { passed: 'Skipped' }, replace: { passed: 'Replaced old version' }, keep: { passed: 'Kept both versions' } }; var OPERATIONS = { RENAME: { verb: 'Rename', status: 'rename', passed: 'renamed', action: 'Renaming' }, MOVE: { verb: 'Move', status: 'move', passed: 'moved', action: 'Moving' }, COPY: { verb: 'Copy', status: 'copy', passed: 'copied', action: 'Copying' } }; // Cross browser key codes for the Command key var COMMAND_KEYS = [224, 17, 91, 93]; var ESCAPE_KEY = 27; var ENTER_KEY = 13; function findByTempID(parent, tmpID) { var child; var item; for (var i = 0; i < parent.children.length; i++) { child = parent.children[i]; if (!child.data.tmpID) { continue; } if (child.data.tmpID === tmpID) { item = child; } } return item; } /** * Cancel a pending upload * @this Treebeard.controller * @param {Object} row Treebeard row containing the file to cancel. */ function cancelUpload(row) { var tb = this; var cancelableStatuses = [Dropzone.UPLOADING, Dropzone.QUEUED]; // Select files that are uploading, queued, or rejected (!accepted) var filesArr = tb.dropzone.files.filter(function(file) { return cancelableStatuses.indexOf(file.status) > -1 || !file.accepted; }); var handled = false; // Search for and remove specified file from queue if (SYNC_UPLOAD_ADDONS.indexOf(row.data.provider) !== -1) { // Provider is handled in sync handled = tb.dropzone.syncFileCache[row.data.provider].some(function(file, index) { if (file.tmpID === row.data.tmpID) { tb.deleteNode(row.parentID, row.id); return tb.dropzone.syncFileCache[row.data.provider].splice(index, 1); } }); } if (!handled) { // File is currently being uploaded/managed by dropzone handled = filesArr.some(function(file) { if (file.tmpID === row.data.tmpID) { tb.deleteNode(row.parentID, row.id); tb.dropzone.removeFile(file); return true; } }); } tb.isUploading(handled && filesArr.length > 1); } /** * Cancel all pending uploads * @this Treebeard.controller */ function cancelAllUploads() { var tb = this; var cancelableStatuses = [Dropzone.UPLOADING, Dropzone.QUEUED]; // Select files that are uploading, queued, or rejected (!accepted) var filesArr = tb.dropzone.files.filter(function(file) { return cancelableStatuses.indexOf(file.status) > -1 || !file.accepted; }); // Remove all queued files var removeFromUI = function(file) { var parent = file.treebeardParent || tb.dropzoneItemCache; var item = findByTempID(parent, file.tmpID); tb.deleteNode(parent.id, item.id); }; // Clear all synchronous uploads if (tb.dropzone.syncFileCache !== undefined) { SYNC_UPLOAD_ADDONS.forEach(function(provider) { if (tb.dropzone.syncFileCache[provider] !== undefined) { // Remove cached provider files from UI tb.dropzone.syncFileCache[provider].forEach(removeFromUI); // Clear provider cache tb.dropzone.syncFileCache[provider].length = 0; } }); } // Clear all ongoing uploads filesArr.forEach(function(file, index) { // Ignore completed files if (file.upload.progress === 100) return; removeFromUI(file); // Cancel currently uploading file tb.dropzone.removeFile(file); }); tb.isUploading(false); } var uploadRowTemplate = function(item) { var tb = this; var padding; if (tb.filterOn) { padding = 20; } else { padding = (item.depth - 1) * 20; } var columns = [{ data : '', // Data field name css : '', custom : function(){ var uploadColumns = [ m('.col-xs-7', {style: 'overflow: hidden;text-overflow: ellipsis;'}, [ m('span', { style : 'padding-left:' + padding + 'px;'}, tb.options.resolveIcon.call(tb, item)), m('span', { style : 'margin-left: 9px;'}, item.data.name) ]), m('.col-xs-3', m('.progress', [ m('.progress-bar.progress-bar-info.progress-bar-striped.active', { role : 'progressbar', 'aria-valuenow' : item.data.progress, 'aria-valuemin' : '0', 'aria-valuemax': '100', 'style' : 'width: ' + item.data.progress + '%' }, m('span.sr-only', item.data.progress + '% Complete')) ]) ) ]; if (item.data.progress < 100) { uploadColumns.push(m('.col-xs-2', [ m('span', m('.fangorn-toolbar-icon.m-l-sm', { style : 'padding: 0px 6px 2px 2px;font-size: 16px;display: inline;', config : function() { reapplyTooltips(); }, 'onclick' : function (e) { e.stopImmediatePropagation(); cancelUpload.call(tb, item); }}, m('span.text-muted', '×') )) ])); } return m('row.text-muted', uploadColumns); } }]; if(tb.options.placement === 'files'){ columns.push({ data : '', // Data field name custom : function(){ return '';} }); } return columns; }; /** * Returns custom icons for OSF depending on the type of item. Used for non-file icons. * @param {Object} item A Treebeard _item object. Node information is inside item.data * @this Treebeard.controller * @returns {Object} Returns a mithril template with the m() function. */ function resolveIconView(item) { var icons = iconmap.projectComponentIcons; function returnView(type, category) { var iconType = icons[type]; if(type === 'project' || type === 'component' || type === 'registeredProject' || type === 'registeredComponent') { if (item.data.permissions.view) { iconType = icons[category]; } else { return null; } } if (type === 'registeredComponent' || type === 'registeredProject') { iconType += ' po-icon-registered'; } else { iconType += ' po-icon'; } var template = m('span', { 'class' : iconType}); return template; } if (item.data.permissions){ if (!item.data.permissions.view) { return m('span', { 'class' : iconmap.private }); } } if (item.data.isDashboard) { return returnView('collection'); } if (item.data.isSmartFolder) { return returnView('smartCollection'); } if ((item.data.nodeType === 'pointer' && item.parent().data.nodeType !== 'folder') || (item.data.isPointer && !item.parent().data.isFolder)) { return returnView('link'); } if (item.data.nodeType === 'project') { if (item.data.parentIsFolder && item.data.isFolder) { return returnView('collection'); } if (item.data.isRegistration) { return returnView('registeredProject', item.data.category); } else { return returnView('project', item.data.category); } } if (item.data.nodeType === 'component') { if (item.data.isRegistration) { return returnView('registeredComponent', item.data.category); } return returnView('component', item.data.category); } if (item.data.nodeType === 'pointer') { return returnView('link'); } return null; } /** * Returns custom icons for OSF depending on the type of item * @param {Object} item A Treebeard _item object. Node information is inside item.data * @this Treebeard.controller * @returns {Object} Returns a mithril template with the m() function. * @private */ function _fangornResolveIcon(item) { if (item.data.unavailable) return m('div', {style: {width:'16px', height:'16px', background:'url(' + item.data.iconUrl+ ')', display:'inline-block', opacity: 0.4}}, ''); var privateFolder = m('i.fa.fa-lock', ' '), pointerFolder = m('i.fa.fa-link', ' '), openFolder = m('i.fa.fa-folder-open', ' '), closedFolder = m('i.fa.fa-folder', ' '), configOption = item.data.provider ? resolveconfigOption.call(this, item, 'folderIcon', [item]) : undefined, // jshint ignore:line icon; var newIcon = resolveIconView(item); if ( newIcon === null) { if (item.kind === 'folder') { if (item.data.iconUrl) { return m('div', {style: {width:'16px', height:'16px', background:'url(' + item.data.iconUrl+ ')', display:'inline-block'}}, ''); } if (!item.data.permissions.view) { return privateFolder; } if (item.data.isPointer) { return pointerFolder; } if (item.open) { return configOption || openFolder; } return configOption || closedFolder; } if (item.data.icon) { return m('i.fa.' + item.data.icon, ' '); } return m('div.file-extension', { 'class': '_' + item.data.name.split('.').pop().toLowerCase() }); } return newIcon; } // Addon config registry. this will be populated with add on specific items if any. Fangorn.config = {}; /** * Returns add on specific configurations * @param {Object} item A Treebeard _item object. Node information is inside item.data * @param {String} key What the option is called in the add on object * @this Treebeard.controller * @returns {*} Returns the configuration, can be string, number, array, or function; */ function getconfig(item, key) { if (item && item.data.provider && Fangorn.config[item.data.provider]) { return Fangorn.config[item.data.provider][key]; } return undefined; } /** * Gets a Fangorn config option if it is defined by an addon dev. * Calls it with `args` if it's a function otherwise returns the value. * If the config option is not defined, returns null * @param {Object} item A Treebeard _item object. Node information is inside item.data * @param {String} option What the option is called in the add on object * @param {Array} args An Array of whatever arguments will be sent with the .apply() * @this Treebeard.controller * @returns {*} Returns if its a property, runs the function if function, returns null if no option is defined. */ function resolveconfigOption(item, option, args) { var self = this, // jshint ignore:line prop = getconfig(item, option); if (prop) { return typeof prop === 'function' ? prop.apply(self, args) : prop; } return null; } /** * Inherits a list of data fields from one item (parent) to another. * @param {Object} item A Treebeard _item object. Node information is inside item.data * @param {Object} parent A Treebeard _item object. Node information is inside item.data * @this Treebeard.controller */ var inheritedFields = ['nodeId', 'nodeUrl', 'nodeApiUrl', 'permissions', 'provider', 'accept']; function inheritFromParent(item, parent, fields) { inheritedFields.concat(fields || []).forEach(function(field) { item.data[field] = item.data[field] || parent.data[field]; }); if(item.data.provider === 'github' || item.data.provider === 'bitbucket' || item.data.provider === 'gitlab'){ item.data.branch = parent.data.branch; } } /** * Returns custom folder toggle icons for OSF * @param {Object} item A Treebeard _item object. Node information is inside item.data * @this Treebeard.controller * @returns {string} Returns a mithril template with m() function, or empty string. * @private */ function _fangornResolveToggle(item) { var toggleMinus = m('i.fa.fa-minus', ' '), togglePlus = m('i.fa.fa-plus', ' '), // padding added so that this overlaps the toggle-icon div and prevent cursor change into pointer for checkout icons. checkedByUser = m('i.fa.fa-sign-out.text-muted[style="font-size: 120%; cursor: default; padding-top: 10px; padding-bottom: 10px; padding-right: 4px;"]', ''), checkedByOther = m('i.fa.fa-sign-out[style="color: #d9534f; font-size: 120%; cursor: default; padding-top: 10px; padding-bottom: 10px; padding-right: 4px;"]', ''); // check if folder has children whether it's lazyloaded or not. if (item.kind === 'folder' && item.depth > 1) { if(!item.data.permissions.view){ return ''; } if (item.open) { return toggleMinus; } return togglePlus; } if (item.data.provider === 'osfstorage' && item.kind === 'file') { if (item.data.extra && item.data.extra.checkout) { if (item.data.extra.checkout._id === window.contextVars.currentUser.id){ return checkedByUser; } return checkedByOther; } } return ''; } /** * Checks if folder toggle is permitted (i.e. contents are private) * @param {Object} item A Treebeard _item object. Node information is inside item.data * @this Treebeard.controller * @returns {boolean} * @private */ function _fangornToggleCheck(item) { if (item.data.permissions.view) { return true; } item.notify.update('Not allowed: Private folder', 'warning', 1, undefined); return false; } function checkConflicts(items, folder){ var children = { 'names': [], 'ids': [] }; var ret = { 'conflicts' : [], 'ready': [] }; folder.children.forEach(function(child){ children.names.push(child.data.name); children.ids.push(child.id); }); items.forEach(function(item) { if (children.names.includes(item.data.name) && !children.ids.includes(item.id)){ ret.conflicts.push(item); } else { ret.ready.push(item); } }); return ret; } function handleCancel(tb, provider, mode, item){ if (mode === 'stop') { tb.syncFileMoveCache[provider].conflicts.length = 0; tb.modal.dismiss(); } else { addFileStatus(tb, item, false, '', '', 'skip'); doSyncMove(tb, provider); } } function displayConflict(tb, item, folder, cb) { var mithrilContent = m('', [ m('p', 'An item named "' + item.data.name + '" already exists in this location.'), m('h5.replace-file', '"Keep Both" will retain both files (and their version histories) in this location.'), m('h5.replace-file', '"Replace" will overwrite the existing file in this location. ' + 'You will lose previous versions of the overwritten file. ' + 'You will keep previous versions of the moved file.'), m('h5.replace-file', '"Skip" will skip the current file.'), m('h5.replace-file', '"Stop" will only move files with no conflicts.') ]); var mithrilButtons = [ m('span.btn.btn-primary.btn-sm', {onclick: cb.bind(tb, 'keep')}, 'Keep Both'), m('span.btn.btn-primary.btn-sm', {onclick: cb.bind(tb, 'replace')}, 'Replace'), m('span.btn.btn-default.btn-sm', {onclick: function() {handleCancel(tb, folder.data.provider, 'skip', item);}}, 'Skip'), m('span.btn.btn-danger.btn-sm', {onclick: function() {handleCancel(tb, folder.data.provider, 'stop');}}, 'Stop') ]; var header = m('h3.break-word.modal-title', 'Replace "' + item.data.name + '"?'); tb.modal.update(mithrilContent, mithrilButtons, header); } function checkConflictsRename(tb, item, name, cb) { var messageArray = []; var parent = item.parent(); for(var i = 0; i < parent.children.length; i++) { var child = parent.children[i]; if (child.data.name === name && child.id !== item.id) { messageArray.push([ m('p', 'An item named "' + child.data.name + '" already exists in this location.'), m('h5.replace-file', '"Keep Both" will retain both files (and their version histories) in this location.'), m('h5.replace-file', '"Replace" will overwrite the existing file in this location. ' + 'You will lose previous versions of the overwritten file. ' + 'You will keep previous versions of the moved file.'), m('h5.replace-file', '"Cancel" will cancel the move.') ]); if (window.contextVars.node.preprintFileId === child.data.path.replace('/', '')) { messageArray = messageArray.concat([ m('p', 'The file "' + child.data.name + '" is the primary file for a preprint, so it should not be replaced.'), m('strong', 'Replacing this file will remove this preprint from circulation.') ]); } tb.modal.update( m('', messageArray), [ m('span.btn.btn-default', {onclick: function() {tb.modal.dismiss();}}, 'Cancel'), //jshint ignore:line m('span.btn.btn-primary', {onclick: cb.bind(tb, 'keep')}, 'Keep Both'), m('span.btn.btn-primary', {onclick: cb.bind(tb, 'replace')}, 'Replace') ], m('h3.break-word.modal-title', 'Replace "' + child.data.name + '"?') ); return; } } cb('replace'); } function doItemOp(operation, to, from, rename, conflict) { var tb = this; var inReadyQueue; var filesRemaining; var inConflictsQueue; var syncMoves; var notRenameOp = typeof rename === 'undefined'; if (notRenameOp) { filesRemaining = tb.syncFileMoveCache && tb.syncFileMoveCache[to.data.provider]; inConflictsQueue = filesRemaining.conflicts && filesRemaining.conflicts.length > 0; syncMoves = SYNC_UPLOAD_ADDONS.indexOf(from.data.provider) !== -1; if (syncMoves) { inReadyQueue = filesRemaining && filesRemaining.ready && filesRemaining.ready.length > 0; } if (inConflictsQueue) { var s = filesRemaining.conflicts.length > 1 ? 's' : ''; var mithrilContent = m('div', { className: 'text-center' }, [ m('p.h4', filesRemaining.conflicts.length + ' conflict' + s + ' left to resolve.'), m('div', {className: 'ball-pulse ball-scale-blue text-center'}, [ m('div',''), m('div',''), m('div',''), ]) ]); var header = m('h3.break-word.modal-title', operation.action + ' "' + from.data.name +'"'); tb.modal.update(mithrilContent, m('', []), header); } } var ogParent = from.parentID; if (to.id === ogParent && (!rename || rename === from.data.name)){ return; } if (operation === OPERATIONS.COPY) { from = tb.createItem($.extend(true, {status: operation.status}, from.data), to.id); } else { from.data.status = operation.status; from.move(to.id); } if (to.data.provider === from.provider) { tb.pendingFileOps.push(from.id); } orderFolder.call(tb, from.parent()); var moveSpec; if (operation === OPERATIONS.RENAME) { moveSpec = { action: 'rename', rename: rename, conflict: conflict }; } else if (operation === OPERATIONS.COPY) { moveSpec = { action: 'copy', path: to.data.path || '/', conflict: conflict, resource: to.data.nodeId, provider: to.data.provider }; } else if (operation === OPERATIONS.MOVE) { moveSpec = { action: 'move', path: to.data.path || '/', conflict: conflict, resource: to.data.nodeId, provider: to.data.provider }; } var options = {}; if(from.data.provider === 'github' || from.data.provider === 'bitbucket' || from.data.provider === 'gitlab'){ options.branch = from.data.branch; moveSpec.branch = from.data.branch; } from.inProgress = true; tb.clearMultiselect(); $.ajax({ type: 'POST', beforeSend: $osf.setXHRAuthorization, url: waterbutler.buildTreeBeardFileOp(from, options), contentType: 'application/json', data: JSON.stringify(moveSpec) }).done(function(resp, _, xhr) { if (to.data.provider === from.provider) { tb.pendingFileOps.pop(); } if (xhr.status === 202) { var mithrilContent = m('div', [ m('h3.break-word', operation.action + ' "' + (from.data.materialized || '/') + '" to "' + (to.data.materialized || '/') + '" is taking a bit longer than expected.'), m('p', 'We\'ll send you an email when it has finished.'), m('p', 'In the mean time you can leave this page; your ' + operation.status + ' will still be completed.') ]); var mithrilButtons = m('div', [ m('span.tb-modal-btn', { 'class' : 'text-default', onclick : function() { tb.modal.dismiss(); }}, 'Close') ]); var header = m('h3.modal-title.break-word', 'Operation Information'); tb.modal.update(mithrilContent, mithrilButtons, header); return; } from.data = tb.options.lazyLoadPreprocess.call(this, resp).data; from.data.status = undefined; from.notify.update('Successfully ' + operation.passed + '.', 'success', null, 1000); if (xhr.status === 200) { to.children.forEach(function(child) { if (child.data.name === from.data.name && child.id !== from.id) { child.removeSelf(); } }); } inheritFromParent(from, from.parent()); if (from.data.kind === 'folder' && from.data.children) { from.children = []; var child; from.data.children.forEach(function(item) { child = tb.buildTree(item, from); inheritFromParent(child, from); from.add(child); }); from.open = true; from.load = true; } var url = from.data.nodeUrl + 'files/' + from.data.provider + from.data.path; if (notRenameOp) { addFileStatus(tb, from, true, '', url, conflict); } // no need to redraw because fangornOrderFolder does it orderFolder.call(tb, from.parent()); }).fail(function(xhr, textStatus) { if (to.data.provider === from.provider) { tb.pendingFileOps.pop(); } if (operation === OPERATIONS.COPY) { from.removeSelf(); } else { from.move(ogParent); from.data.status = undefined; } var message; if (xhr.status !== 500 && xhr.responseJSON && (xhr.responseJSON.message || xhr.responseJSON.message_long)) { message = xhr.responseJSON.message || xhr.responseJSON.message_long; } else if (xhr.status === 503) { message = textStatus; } else { message = 'Please refresh the page or contact ' + $osf.osfSupportLink() + ' if the problem persists.'; } $osf.growl(operation.verb + ' failed.', message); Raven.captureMessage('Failed to move or copy file', { extra: { xhr: xhr, requestData: moveSpec } }); if (notRenameOp) { addFileStatus(tb, from, false, '', '', conflict); } orderFolder.call(tb, from.parent()); }).always(function(){ from.inProgress = false; if (notRenameOp && (typeof inConflictsQueue !== 'undefined' || syncMoves)) { doSyncMove(tb, to.data.provider); } }); } /** * Find out what the upload URL is for each item * Because we use add ons each item will have something different. This needs to be in the json data. * @param {Object} item A Treebeard _item object. Node information is inside item.data * @this Treebeard.controller * @returns {String} Returns the url string from data or resolved through add on settings. * @private */ function _fangornResolveUploadUrl(item, file) { // WB v1 update syntax is PUT <file_path>?kind=file // WB v1 upload syntax is PUT <parent_path>/?kind=file&name=<filename> // If upload target file name already exists don't pass file.name. WB v1 rejects updates that // include a filename. var configOption = resolveconfigOption.call(this, item, 'uploadUrl', [item, file]); // jshint ignore:line if (configOption) { return configOption; } var updateUrl; $.each(item.children, function( index, value ) { if (file.name === value.data.name) { updateUrl = waterbutler.buildTreeBeardUpload(value); return false; } }); return updateUrl || waterbutler.buildTreeBeardUpload(item, {name: file.name}); } /** * Event to fire when mouse is hovering over row. Currently used for hover effect. * @param {Object} item A Treebeard _item object. Node information is inside item.data * @param event The mouseover event from the browser * @this Treebeard.controller * @private */ function _fangornMouseOverRow(item, event) { $('.fg-hover-hide').hide(); $(event.target).closest('.tb-row').find('.fg-hover-hide').show(); } /** * Runs when dropzone uploadprogress is running, used for updating upload progress in view and models. * @param {Object} treebeard The treebeard instance currently being run, check Treebeard API * @param {Object} file File object that dropzone passes * @param {Number} progress Progress number between 0 and 100 * @this Dropzone * @private */ function _fangornUploadProgress(treebeard, file, progress) { var parent = file.treebeardParent; progress = Math.ceil(progress); for(var i = 0; i < parent.children.length; i++) { if (parent.children[i].data.tmpID !== file.tmpID) continue; if (parent.children[i].data.progress !== progress) { parent.children[i].data.progress = progress; m.redraw(); } return; } } /** * Runs when dropzone sending method is running, used for updating the view while file is being sent. * @param {Object} treebeard The treebeard instance currently being run, check Treebeard API * @param {Object} file File object that dropzone passes * @param xhr xhr information being sent * @param formData Dropzone's formdata information * @this Dropzone * @returns {*|null} Return isn't really used here by anything else. * @private */ function _fangornSending(treebeard, file, xhr, formData) { treebeard.options.uploadInProgress = true; var parent = file.treebeardParent || treebeard.dropzoneItemCache; xhr = $osf.setXHRAuthorization(xhr); var _send = xhr.send; xhr.send = function() { _send.call(xhr, file); }; var configOption = resolveconfigOption.call(treebeard, parent, 'uploadSending', [file, xhr, formData]); return configOption || null; } /** * Runs when Dropzone's addedfile hook is run. * @param {Object} treebeard The treebeard instance currently being run, check Treebeard API * @param {Object} file File object that dropzone passes * @this Dropzone * @returns {*|null} * @private */ function _fangornAddedFile(treebeard, file) { var item = file.treebeardParent; if (!_fangornCanDrop(treebeard, item)) { return; } if (SYNC_UPLOAD_ADDONS.indexOf(item.data.provider) !== -1) { this.syncFileCache = this.syncFileCache || {}; this.syncFileCache[item.data.provider] = this.syncFileCache[item.data.provider] || []; var files = this.getActiveFiles().filter(function(f) {return f.isSync;}); if (files.length > 0) { this.syncFileCache[item.data.provider].push(file); this.files.splice(this.files.indexOf(files), 1); } file.isSync = true; } var configOption = resolveconfigOption.call(treebeard, item, 'uploadAdd', [file, item]); var tmpID = tempCounter++; file.tmpID = tmpID; file.url = _fangornResolveUploadUrl(item, file); file.method = _fangornUploadMethod(item); var blankItem = { // create a blank item that will refill when upload is finished. name: file.name, kind: 'file', provider: item.data.provider, children: [], permissions: { view: false, edit: false }, tmpID: tmpID, progress: 0, uploadState : m.prop('uploading'), }; var newitem = treebeard.createItem(blankItem, item.id); return configOption || null; } function _fangornCanDrop(treebeard, item) { var canDrop = resolveconfigOption.call(treebeard, item, 'canDrop', [item]); if (canDrop === null) { canDrop = item.data.provider && item.kind === 'folder' && item.data.permissions.edit; } return canDrop; } /** * Runs when Dropzone's dragover event hook is run. * @param {Object} treebeard The treebeard instance currently being run, check Treebeard API * @param event DOM event object * @this Dropzone * @private */ function _fangornDragOver(treebeard, event) { var dropzoneHoverClass = 'fangorn-dz-hover', closestTarget = $(event.target).closest('.tb-row'), itemID = parseInt(closestTarget.attr('data-id')), item = treebeard.find(itemID); treebeard.select('.tb-row').removeClass(dropzoneHoverClass).removeClass(treebeard.options.hoverClass); if (item !== undefined) { if (_fangornCanDrop(treebeard, item)) { closestTarget.addClass(dropzoneHoverClass); } } } /** * Runs when Dropzone's drop event hook is run. * @param {Object} treebeard The treebeard instance currently being run, check Treebeard API * @param event DOM event object * @this Dropzone * @private */ function _fangornDropzoneDrop(treebeard, event) { var dropzoneHoverClass = 'fangorn-dz-hover'; treebeard.select('.tb-row').removeClass(dropzoneHoverClass); } /** * Runs when Dropzone's complete hook is run after upload is completed. * @param {Object} treebeard The treebeard instance currently being run, check Treebeard API * @param {Object} file File object that dropzone passes * @this Dropzone * @private */ function _fangornComplete(treebeard, file) { var item = file.treebeardParent; resolveconfigOption.call(treebeard, item, 'onUploadComplete', [item]); orderFolder.call(treebeard, item); if (file.isSync) { if (this.syncFileCache[item.data.provider].length > 0) { var nextFile = this.syncFileCache[item.data.provider].pop(); this.files.push(nextFile); this.processFile(nextFile); } } } /** * Runs when Dropzone's success hook is run. * @param {Object} treebeard The treebeard instance currently being run, check Treebeard API * @param {Object} file File object that dropzone passes * @param {Object} response JSON response from the server * @this Dropzone * @private */ function _fangornDropzoneSuccess(treebeard, file, response) { treebeard.options.uploadInProgress = false; var parent = file.treebeardParent, item, revisedItem, child; for (var i = 0; i < parent.children.length; i++) { child = parent.children[i]; if (!child.data.tmpID){ continue; } if (child.data.tmpID === file.tmpID) { item = child; } } // RESPONSES // OSF : Object with actionTake : "file_added" // DROPBOX : Object; addon : 'dropbox' // S3 : Nothing // GITHUB : Object; addon : 'github' // Dataverse : Object, actionTaken : file_uploaded revisedItem = resolveconfigOption.call(treebeard, item.parent(), 'uploadSuccess', [file, item, response]); if (!revisedItem && response) { item.data = treebeard.options.lazyLoadPreprocess.call(this, response).data; inheritFromParent(item, item.parent()); } if (item.data.tmpID) { item.data.tmpID = null; item.data.uploadState('completed'); } // Remove duplicates if file was updated var status = file.xhr.status; if (status === 200) { parent.children.forEach(function(child) { if (child.data.name === item.data.name && child.id !== item.id) { child.removeSelf(); } }); } var url = item.data.nodeUrl + 'files/' + item.data.provider + item.data.path; addFileStatus(treebeard, file, true, '', url); if (item.data.provider === 'dataverse') { item.parent().data.datasetDraftModified = true; } treebeard.redraw(); } function _fangornDropzoneRemovedFile(treebeard, file, message, xhr) { addFileStatus(treebeard, file, false, 'Upload Canceled.', ''); } /** * runs when Dropzone's error hook runs. Notifies user with error. * @param {Object} treebeard The treebeard instance currently being run, check Treebeard API * @param {Object} file File object that dropzone passes * @param message Error message returned * @private */ var DEFAULT_ERROR_MESSAGE = 'Could not upload file. The file may be invalid ' + 'or the file folder has been deleted.'; function _fangornDropzoneError(treebeard, file, message, xhr) { var tb = treebeard; var msgText; // Unpatched Dropzone silently does nothing when folders are uploaded on Windows IE // Patched Dropzone.prototype.drop to emit error with file = 'None' to catch the error if (file === 'None'){ $osf.growl('Error', 'Cannot upload folders.'); return; } if (file.isDirectory) { msgText = 'Cannot upload folders.'; } else if (xhr && xhr.status === 507) { msgText = 'Cannot upload file due to insufficient storage.'; } else if (xhr && xhr.status === 0) { // There is no way for Safari to know if it was a folder at present msgText = ''; if ($osf.isSafari()) { msgText += 'Could not upload file. Possible reasons: <br>'; msgText += '1. Cannot upload folders. <br>2. '; } msgText += 'Unable to reach the provider, please try again later. '; msgText += 'If the problem persists, please contact ' + $osf.osfSupportEmail() + '.'; } else { //Osfstorage and most providers store message in {Object}message.{string}message, //but some, like Dataverse, have it in {string} message. if (message){ msgText = message.message ? message.message : (typeof message === 'string' ? message : DEFAULT_ERROR_MESSAGE); } else { msgText = DEFAULT_ERROR_MESSAGE; } } if (typeof file.isDirectory === 'undefined') { var parent = file.treebeardParent || treebeardParent.dropzoneItemCache; // jshint ignore:line var item; var child; var destroyItem = false; for (var i = 0; i < parent.children.length; i++) { child = parent.children[i]; if (!child.data.tmpID) { continue; } if (child.data.tmpID === file.tmpID) { child.removeSelf(); } } } console.error(file); treebeard.options.uploadInProgress = false; if (msgText !== 'Upload canceled.') { addFileStatus(treebeard, file, false, msgText, ''); } treebeard.dropzone.options.queuecomplete(file); } /** * Click event for when upload buttonin Action Column, it essentially runs the hiddenFileInput.click * @param event DOM event object for click * @param {Object} item A Treebeard _item object for the row involved. Node information is inside item.data * @param {Object} col Information pertinent to that column where this upload event is run from * @private */ function _uploadEvent(event, item, col) { var self = this; // jshint ignore:line try { event.stopPropagation(); } catch (e) { window.event.cancelBubble = true; } self.dropzoneItemCache = item; self.dropzone.hiddenFileInput.click(); if (!item.open) { self.updateFolder(null, item); } } /** * Download button in Action Column * @param event DOM event object for click * @param {Object} item A Treebeard _item object for the row involved. Node information is inside item.data * @param {Object} col Information pertinent to that column where this upload event is run from * @private */ function _downloadEvent (event, item, col) { try { event.stopPropagation(); } catch (e) { window.event.cancelBubble = true; } window.location = waterbutler.buildTreeBeardDownload(item); } function _downloadZipEvent (event, item, col) { try { event.stopPropagation(); } catch (e) { window.event.cancelBubble = true; } window.location = waterbutler.buildTreeBeardDownloadZip(item); } function _createFolder(event, dismissCallback, helpText) { var tb = this; helpText(''); var val = $.trim(tb.select('#createFolderInput').val()); var parent = tb.multiselected()[0]; if (!parent.open) { tb.updateFolder(null, parent); } if (val.length < 1) { helpText('Please enter a folder name.'); return; } if (val.indexOf('/') !== -1) { helpText('Folder name contains illegal characters.'); return; } var extra = {}; var path = parent.data.path || '/'; var options = {name: val, kind: 'folder'}; if ((parent.data.provider === 'github') || (parent.data.provider === 'gitlab')) { extra.branch = parent.data.branch; options.branch = parent.data.branch; } m.request({ method: 'PUT', background: true, config: $osf.setXHRAuthorization, url: waterbutler.buildCreateFolderUrl(path, parent.data.provider, parent.data.nodeId, options, extra) }).then(function(item) { item = tb.options.lazyLoadPreprocess.call(this, item).data; inheritFromParent({data: item}, parent, ['branch']); item = tb.createItem(item, parent.id); orderFolder.call(tb, parent); item.notify.update('New folder created!', 'success', undefined, 1000); if(dismissCallback) { dismissCallback(); } }, function(data) { if (data && data.code === 409) { helpText(data.message); m.redraw(); } else { helpText('Folder creation failed.'); } }); } /** * Deletes the item, only appears for items * @param event DOM event object for click * @param {Object} item A Treebeard _item object for the row involved. Node information is inside item.data * @param {Object} col Information pertinent to that column where this upload event is run from * @private */ function _removeEvent (event, items, col) { var tb = this; function cancelDelete() { tb.modal.dismiss(); } function runDelete(item) { tb.select('.modal-footer .btn-danger').html('<i> Deleting...</i>').removeClass('btn-danger').addClass('btn-default disabled'); // delete from server, if successful delete from view var url = resolveconfigOption.call(this, item, 'resolveDeleteUrl', [item]); url = url || waterbutler.buildTreeBeardDelete(item); $.ajax({ url: url, type: 'DELETE', beforeSend: $osf.setXHRAuthorization }) .done(function(data) { // delete view tb.deleteNode(item.parentID, item.id); tb.modal.dismiss(); tb.clearMultiselect(); if (item.data.provider === 'dataverse') { item.parent().data.datasetDraftModified = true; } }) .fail(function(data){ tb.modal.dismiss(); tb.clearMultiselect(); if (data.responseJSON.message_long.indexOf('preprint') !== -1) { $osf.growl('Delete failed', data.responseJSON.message_long); } item.notify.update('Delete failed.', 'danger', undefined, 3000); }); } function runDeleteMultiple(items){ items.forEach(function(item){ runDelete(item); }); } function doDelete() { var folder = items[0]; if (folder.data.permissions.edit) { var mithrilContent = m('div', [ m('p.text-danger', 'This folder and ALL its contents will be deleted. This action is irreversible.') ]); var mithrilButtons = m('div', [ m('span.btn.btn-default', { onclick : function() { cancelDelete.call(tb); } }, 'Cancel'), m('span.btn.btn-danger', { onclick : function() { runDelete(folder); } }, 'Delete') ]); tb.modal.update(mithrilContent, mithrilButtons, m('h3.break-word.modal-title', 'Delete "' + folder.data.name+ '"?')); } else { folder.notify.update('You don\'t have permission to delete this file.', 'info', undefined, 3000); } } // If there is only one item being deleted, don't complicate the issue: if(items.length === 1) { var detail = 'This action is irreversible.'; if(items[0].kind !== 'folder'){ var mithrilContentSingle = m('div', [ m('p', detail) ]); var mithrilButtonsSingle = m('div', [ m('span.btn.btn-default', { onclick : function() { cancelDelete(); } }, 'Cancel'), m('span.btn.btn-danger', { onclick : function() { runDelete(items[0]); } }, 'Delete') ]); // This is already being checked before this step but will keep this edit permission check if(items[0].data.permissions.edit){ tb.modal.update(mithrilContentSingle, mithrilButtonsSingle, m('h3.break-word.modal-title', 'Delete "' + items[0].data.name + '"?')); } } if(items[0].kind === 'folder') { if (!items[0].open) { tb.updateFolder(null, items[0], doDelete); } else { doDelete(); } } } else { // Check if all items can be deleted var canDelete = true; var deleteList = []; var noDeleteList = []; var deleteMessage = [m('p', 'This action is irreversible.')]; var mithrilContentMultiple; var mithrilButtonsMultiple; items.forEach(function(item, index, arr){ if(!item.data.permissions.edit){ canDelete = false; noDeleteList.push(item); } else { deleteList.push(item); } if(item.kind === 'folder' && deleteMessage.length === 1) { deleteMessage.push(m('p.text-danger', 'Some of the selected items are folders. This will delete the folder(s) and ALL of their content.')); } }); // If all items can be deleted if(canDelete){ mithrilContentMultiple = m('div', [ deleteMessage, deleteList.map(function(n){ if(n.kind === 'folder'){ return m('.fangorn-canDelete.text-success.break-word', [ m('i.fa.fa-folder'), m('b', ' ' + n.data.name) ]); } return m('.fangorn-canDelete.text-success.break-word', n.data.name); }) ]); mithrilButtonsMultiple = m('div', [ m('span.btn.btn-default', { onclick : function() { tb.modal.dismiss(); } }, 'Cancel'), m('span.btn.btn-danger', { onclick : function() { runDeleteMultiple.call(tb, deleteList); } }, 'Delete All') ]); } else { mithrilContentMultiple = m('div', [ m('p', 'Some of these files can\'t be deleted but you can delete the ones highlighted with green. This action is irreversible.'), deleteList.map(function(n){ if(n.kind === 'folder'){ return m('.fangorn-canDelete.text-success.break-word', [ m('i.fa.fa-folder'), m('b', ' ' + n.data.name) ]); } return m('.fangorn-canDelete.text-success.break-word', n.data.name); }), noDeleteList.map(function(n){ return m('.fangorn-noDelete.text-warning.break-word', n.data.name); }) ]); mithrilButtonsMultiple = m('div', [ m('span.btn.btn-default', { 'class' : 'text-default', onclick : function() { tb.modal.dismiss(); } }, 'Cancel'), m('span.btn.btn-danger', { 'class' : 'text-danger', onclick : function() { runDeleteMultiple.call(tb, deleteList); } }, 'Delete Some') ]); } tb.modal.update(mithrilContentMultiple, mithrilButtonsMultiple, m('h3.break-word.modal-title', 'Delete multiple files?')); } } function doCheckout(item, checkout, showError) { return $osf.ajaxJSON( 'PUT', window.contextVars.apiV2Prefix + 'files' + item.data.path + '/', { isCors: true, data: { data: { id: item.data.path.replace('/', ''), type: 'files', attributes: { checkout: checkout } } } } ).done(function(xhr) { if (showError) { window.location.reload(); } }).fail(function(xhr) { if (showError) { $osf.growl('Error', 'Unable to check out file. This is most likely due to the file being already checked-out' + ' by another user.'); } }); } /** * Resolves lazy load url for fetching children * @param {Object} item A Treebeard _item object for the row involved. Node information is inside item.data * @this Treebeard.controller * @returns {String|Boolean} Returns the fetch URL in string or false if there is no url. * @private */ function _fangornResolveLazyLoad(item) { item.connected = true; var configOption = resolveconfigOption.call(this, item, 'lazyload', [item]); if (configOption) { return configOption; } if (item.data.provider === undefined) { return false; } return waterbutler.buildTreeBeardMetadata(item); } /** * Handles errors in lazyload fetching of items, usually link is wrong * @param {Object} item A Treebeard _item object for the row involved. Node information is inside item.data * @this Treebeard.controller * @private */ function _fangornLazyLoadError (item) { item.connected = false; var configOption = resolveconfigOption.call(this, item, 'lazyLoadError', [item]); } /** * Applies the positionining and initialization of tooltips for file names * @private */ function reapplyTooltips () { $('[data-toggle="tooltip"]').tooltip({container: 'body', 'animation' : false}); } /** * Called when new object data has arrived to be loaded. * @param {Object} tree A Treebeard _item object for the row involved. Node information is inside item.data * @this Treebeard.controller * @private */ function _fangornLazyLoadOnLoad (tree, event) { tree.children.forEach(function(item) { inheritFromParent(item, tree); }); resolveconfigOption.call(this, tree, 'lazyLoadOnLoad', [tree, event]); reapplyTooltips(); if (tree.depth > 1) { orderFolder.call(this, tree); } } /** * Order contents of a folder without an entire sorting of all the table * @param {Object} tree A Treebeard _item object for the row involved. Node information is inside item.data * @this Treebeard.controller * @private */ function orderFolder(tree) { var sortColumn; var sortDirection; if(typeof this.isSorted !== 'undefined' && typeof this.isSorted[0] !== 'undefined'){ sortColumn = Object.keys(this.isSorted)[0]; // default to whatever column is first for (var column in this.isSorted){ sortColumn = this.isSorted[column].asc || this.isSorted[column].desc ? column : sortColumn; } sortDirection = this.isSorted[sortColumn].desc ? 'desc' : 'asc'; // default to ascending }else{ sortColumn = 0; sortDirection = 'asc'; } tree.sortChildren(this, sortDirection, 'text', sortColumn, 1); this.redraw(); } /** * Changes the upload method based on what the add ons need. Default is POST, S3 needs PUT * @param {Object} item A Treebeard _item object for the row involved. Node information is inside item.data * @this Treebeard.controller * @returns {string} Must return string that is a legitimate method like POST, PUT * @private */ function _fangornUploadMethod(item) { var configOption = resolveconfigOption.call(this, item, 'uploadMethod', [item]); return configOption || 'PUT'; } function gotoFileEvent (item, toUrl) { if(toUrl === undefined) toUrl = '/'; var tb = this; var redir = new URI(item.data.nodeUrl); redir.segment('files').segment(item.data.provider).segmentCoded(item.data.path.substring(1)); var fileurl = redir.toString() + toUrl; // construct view only link into file url as it gets removed from url params in IE if ($osf.isIE()) { var viewOnly = $osf.urlParams().view_only; if (viewOnly) { if (fileurl.indexOf('?') !== -1) { fileurl += '&view_only=' + viewOnly; }else { fileurl += '?view_only=' + viewOnly; } } } if (COMMAND_KEYS.indexOf(tb.pressedKey) !== -1) { window.open(fileurl, '_blank'); } else { window.open(fileurl, '_self'); } } /** * Defines the contents of the title column (does not include the toggle and folder sections * @param {Object} item A Treebeard _item object for the row involved. Node information is inside item.data * @param {Object} col Options for this particulat column * @this Treebeard.controller * @returns {Array} Returns an array of mithril template objects using m() * @private */ function _fangornTitleColumnHelper(tb, item, col, nameTitle, toUrl, classNameOption){ if (typeof tb.options.links === 'undefined') { tb.options.links = true; } // as opposed to undefined, avoids unnecessary setting of this value if (item.data.isAddonRoot && item.connected === false) { return _connectCheckTemplate.call(this, item); } if (item.kind === 'file' && item.data.permissions.view) { var attrs = {}; if (tb.options.links) { attrs = { className: classNameOption, onclick: function(event) { event.stopImmediatePropagation(); gotoFileEvent.call(tb, item, toUrl); } }; } return m('span', attrs, nameTitle); } if ((item.data.nodeType === 'project' || item.data.nodeType ==='component') && item.data.permissions.view) { return m('a.' + classNameOption, {href: '/' + item.data.nodeID.toString() + toUrl}, nameTitle); } return m('span', nameTitle); } function _fangornTitleColumn(item, col) { var tb = this; return _fangornTitleColumnHelper(tb, item, col, item.data.name, '/', 'fg-file-links'); } function _fangornVersionColumn(item, col) { var tb = this; if (item.kind !== 'folder' && item.data.provider === 'osfstorage'){ return _fangornTitleColumnHelper(tb, item, col, String(item.data.extra.version), '/?show=revision', 'fg-version-links'); } return; } /** * Defines the contents of the modified column (does not include the toggle and folder sections * @param {Object} item A Treebeard _item object for the row involved. Node information is inside item.data * @param {Object} col Options for this particular column * @this Treebeard.controller * @returns {Array} Returns an array of mithril template objects using m() * @private */ function _fangornModifiedColumn(item, col) { var tb = this; if (item.data.isAddonRoot && item.connected === false) { // as opposed to undefined, avoids unnecessary setting of this value return _connectCheckTemplate.call(this, item); } if (item.kind === 'file' && item.data.permissions.view && item.data.modified_utc) { item.data.modified = new moment(moment.utc(item.data.modified_utc,'YYYY-MM-DD hh:mm A', 'en').toDate()).format('YYYY-MM-DD hh:mm A'); return m( 'span', item.data.modified ); } return m('span', ''); } /** * Returns a reusable template for column titles when there is no connection * @param {Object} item A Treebeard _item object for the row involved. Node information is inside item.data * @this Treebeard.controller * @private */ function _connectCheckTemplate(item){ var tb = this; return m('span.text-danger', [ m('span', item.data.name), m('em', ' couldn\'t load.' ), m('button.btn.btn-xs.btn-default.m-l-xs', { onclick : function(e){ e.stopImmediatePropagation(); if (tb.options.togglecheck.call(tb, item)) { var index = tb.returnIndex(item.id); tb.toggleFolder(index, e); } } }, [m('i.fa.fa-refresh'), ' Retry']) ]); } /** * Parent function for resolving rows, all columns are sub methods within this function * @param {Object} item A Treebeard _item object for the row involved. Node information is inside item.data * @this Treebeard.controller * @returns {Array} An array of columns that get iterated through in Treebeard * @private */ function _fangornResolveRows(item) { var tb = this; var defaultColumns = []; var configOption; item.css = ''; if(tb.isMultiselected(item.id)){ item.css = 'fangorn-selected'; } if(item.data.permissions && !item.data.permissions.view){ item.css += ' tb-private-row'; } if(item.data.uploadState && (item.data.uploadState() === 'pending' || item.data.uploadState() === 'uploading')){ return uploadRowTemplate.call(tb, item); } if (item.data.status) { return [{ data : '', // Data field name css : 't-a-c', custom : function(){ return m('span.text-muted', [STATE_MAP[item.data.status].display, item.data.name, '...']); } }, { data : '', // Data field name custom : function(){ return '';} }]; } if (item.parentID) { item.data.permissions = item.data.permissions || item.parent().data.permissions; if (item.data.kind === 'folder') { item.data.accept = item.data.accept || item.parent().data.accept; } } defaultColumns.push({ data : 'name', // Data field name folderIcons : true, filter : true, custom : _fangornTitleColumn }); defaultColumns.push({ data : 'size', // Data field name sortInclude : false, filter : false, custom : function() {return item.data.size ? $osf.humanFileSize(item.data.size, true) : '';} }); defaultColumns.push({ data: 'version', filter: false, sortInclude : false, custom: _fangornVersionColumn }); if (item.data.provider === 'osfstorage') { defaultColumns.push({ data : 'downloads', sortInclude : false, filter : false, custom: function() { return lodashGet(item, 'data.extra.downloads', '').toString(); } }); } else { defaultColumns.push({ data : 'downloads', sortInclude : false, filter : false, custom : function() { return m(''); } }); } defaultColumns.push({ data : 'modified', // Data field name filter : false, custom : _fangornModifiedColumn }); configOption = resolveconfigOption.call(this, item, 'resolveRows', [item]); return configOption || defaultColumns; } /** * Defines Column Titles separately since content and css may be different, allows more flexibility * @returns {Array} an Array of column information that gets templated inside Treebeard * @this Treebeard.controller * @private */ function _fangornColumnTitles () { var columns = []; columns.push({ title : 'Name', width : '54%', sort : true, sortType : 'text' }, { title : 'Size', width : '8%', sort : false }, { title : 'Version', width : '10%', sort : false }, { title : 'Downloads', width : '8%', sort : false }, { title : 'Modified', width : '20%', sort : true, sortType : 'text' }); return columns; } /** * When fangorn loads the top level needs to be open so we load the children on load * @this Treebeard.controller * @private */ function _loadTopLevelChildren() { var i; for (i = 0; i < this.treeData.children.length; i++) { this.updateFolder(null, this.treeData.children[i]); } } /** * Expand major addons on load * @param {Object} item A Treebeard _item object for the row involved. Node information is inside item.data * @this Treebeard.controller * @private */ var NO_AUTO_EXPAND_PROJECTS = ['ezcuj', 'ecmz4', 'w4wvg', 'sn64d']; function expandStateLoad(item) { var tb = this, icon = $('.tb-row[data-id="' + item.id + '"]').find('.tb-toggle-icon'), toggleIcon = tbOptions.resolveToggle(item), addonList = [], i; if (item.children.length > 0 && item.depth === 1) { // NOTE: On the RPP and a few select projects *only*: Load the top-level project's OSF Storage // but do NOT lazy-load children in order to save hundreds of requests. // TODO: We might want to do this for every project, but that's TBD. // /sloria if (window.contextVars && window.contextVars.node && NO_AUTO_EXPAND_PROJECTS.indexOf(window.contextVars.node.id) > -1) { var osfsItems = item.children.filter(function(child) { return child.data.isAddonRoot && child.data.provider === 'osfstorage'; }); if (osfsItems.length) { var osfsItem = osfsItems[0]; tb.updateFolder(null, osfsItem); } } else { for (i = 0; i < item.children.length; i++) { tb.updateFolder(null, item.children[i]); } } } if (item.children.length > 0 && item.depth === 2) { for (i = 0; i < item.children.length; i++) { if (item.children[i].data.isAddonRoot || item.children[i].data.addonFullName === 'OSF Storage' ) { tb.updateFolder(null, item.children[i]); } } } if (item.depth > 2 && !item.data.isAddonRoot && !item.data.type && item.children.length === 0 && item.open) { // Displays loading indicator until request below completes // Copied from toggleFolder() in Treebeard if (icon.get(0)) { m.render(icon.get(0), tbOptions.resolveRefreshIcon()); } $osf.ajaxJSON( 'GET', '/api/v1/project/' + item.data.nodeID + '/files/grid/' ).done(function(response) { var data = response.data[0].children; tb.updateFolder(data, item); tb.redraw(); }).fail(function(xhr) { item.notify.update('Unable to retrieve components.', 'danger', undefined, 3000); item.open = false; Raven.captureMessage('Unable to retrieve components for node ' + item.data.nodeID, { extra: { xhr: xhr } }); }); } $('.fangorn-toolbar-icon').tooltip(); } /** * @param tree A Treebeard _item object for the row * @param nodeID Current node._id * @param file window.contextVars.file object */ function setCurrentFileID(tree, nodeID, file) { var tb = this; if(!file){ return; } var child; var i; if (file.provider === 'figshare') { for (i = 0; i < tree.children.length; i++) { child = tree.children[i]; if (nodeID === child.data.nodeId && child.data.provider === file.provider && child.data.path === file.path) { tb.currentFileID = child.id; } } } else if (file.provider === 'dataverse') { // Only highlight file in correct dataset version, since paths persist across versions for (i = 0; i < tree.children.length; i++) { child = tree.children[i]; var urlParams = $osf.urlParams(); if (nodeID === child.data.nodeId && child.data.provider === file.provider && child.data.path === file.path && child.data.extra.datasetVersion === urlParams.version) { tb.currentFileID = child.id; } } } else if (tb.fangornFolderIndex !== undefined && tb.fangornFolderArray !== undefined && tb.fangornFolderIndex < tb.fangornFolderArray.length) { for (var j = 0; j < tree.children.length; j++) { child = tree.children[j]; if (nodeID === child.data.nodeId && child.data.provider === file.provider && child.data.name === tb.fangornFolderArray[tb.fangornFolderIndex]) { tb.fangornFolderIndex++; if (child.data.kind === 'folder') { tb.updateFolder(null, child); tree = child; } else { tb.currentFileID = child.id; } } } } } /** * Scroll to the Treebeard item corresponding to the given ID * @param fileID id of a Treebeard _item object */ function scrollToFile(fileID) { var tb = this; if (fileID !== undefined) { var index = tb.returnIndex(fileID); var visibleIndex = tb.visibleIndexes.indexOf(index); var scrollTo = visibleIndex * tb.options.rowHeight; this.select('#tb-tbody').scrollTop(scrollTo); } } function _renameEvent () { var tb = this; var item = tb.multiselected()[0]; var val = $.trim($('#renameInput').val()); var folder = item.parent(); //TODO Error message? if (val === item.name) { return; } checkConflictsRename(tb, item, val, doItemOp.bind(tb, OPERATIONS.RENAME, folder, item, val)); tb.toolbarMode(toolbarModes.DEFAULT); } var toolbarModes = { 'DEFAULT' : 'bar', 'FILTER' : 'filter', 'ADDFOLDER' : 'addFolder', 'RENAME' : 'rename', 'ADDPROJECT' : 'addProject' }; // A fangorn-styled button; addons can reuse this var FGButton = { view: function(ctrl, args, children) { var extraCSS = args.className || ''; var tooltipText = args.tooltip || ''; var iconCSS = args.icon || ''; var onclick = args.onclick || noop; var opts = { className: 'fangorn-toolbar-icon ' + extraCSS, onclick: onclick }; // Add tooltip if applicable if (args.tooltip) { opts['data-toggle'] = 'tooltip'; opts['data-placement'] = 'bottom'; opts.title = args.tooltip; } var childrenElements = []; childrenElements.push(m('i', {className: iconCSS})); if(children) { childrenElements.push(m('span', children)); } return m('div', opts, childrenElements); } }; var FGInput = { view : function(ctrl, args, helpText) { var extraCSS = args.className || ''; var tooltipText = args.tooltip || ''; var placeholder = args.placeholder || ''; var id = args.id || ''; var helpTextId = args.helpTextId || ''; var oninput = args.oninput || noop; var onkeypress = args.onkeypress || noop; return m('span', [ m('input', { 'id' : id, className: 'pull-right form-control' + extraCSS, oninput: oninput, onkeypress: onkeypress, 'value': args.value || '', 'data-toggle': tooltipText ? 'tooltip' : '', 'title': tooltipText, 'data-placement' : 'bottom', 'placeholder' : placeholder }), m('.text-danger', { 'id' : helpTextId }, helpText) ]); } }; var FGDropdown = { view : function(ctrl, args, children) { var extraCSS = args.className || ''; var tooltipText = args.tooltip || ''; var id = args.id || ''; var name = args.name || ''; var label = args.label || ''; var onchange = args.onchange || noop; return m('span.fangorn-dropdown', { className: extraCSS }, [ m('span.hidden-xs', label), m('select.no-border', { 'name' : name, 'id' : id, onchange: onchange, 'data-toggle': tooltipText ? 'tooltip' : '', 'title': tooltipText, 'data-placement' : 'bottom' }, children) ]); } }; var FGItemButtons = { view : function(ctrl, args, children) { var tb = args.treebeard; var item = args.item; var rowButtons = []; var mode = args.mode; var preprintPath = getPreprintPath(window.contextVars.node.preprintFileId); if (tb.options.placement !== 'fileview') { if (window.File && window.FileReader && item.kind === 'folder' && item.data.provider && item.data.permissions && item.data.permissions.edit) { rowButtons.push( m.component(FGButton, { onclick: function(event) {_uploadEvent.call(tb, event, item); }, icon: 'fa fa-upload', className : 'text-success' }, 'Upload'), m.component(FGButton, { onclick: function () { mode(toolbarModes.ADDFOLDER); }, icon: 'fa fa-plus', className: 'text-success' }, 'Create Folder')); if (item.data.path) { if (preprintPath && folderContainsPreprint(item, preprintPath)) { rowButtons.push( m.component(FGButton, { icon: 'fa fa-trash', tooltip: 'This folder contains a Preprint. You cannot delete Preprints, but you can upload a new version.', className: 'tb-disabled' }, 'Delete Folder')); reapplyTooltips(); } else { rowButtons.push( m.component(FGButton, { onclick: function(event) {_removeEvent.call(tb, event, [item]); }, icon: 'fa fa-trash', className : 'text-danger' }, 'Delete Folder')); } } } if (item.kind === 'file') { rowButtons.push( m.component(FGButton, { onclick: function (event) { _downloadEvent.call(tb, event, item); }, icon: 'fa fa-download', className: 'text-primary' }, 'Download') ); if (item.data.permissions && item.data.permissions.view) { rowButtons.push( m.component(FGButton, { onclick: function (event) { gotoFileEvent.call(tb, item, '/'); }, icon: 'fa fa-file-o', className: 'text-info' }, 'View')); } if (item.data.permissions && item.data.permissions.edit) { if (item.data.provider === 'osfstorage') { if (!item.data.extra.checkout){ if (preprintPath && preprintPath === item.data.path) { // Block delete for preprint files rowButtons.push( m.component(FGButton, { icon: 'fa fa-trash', tooltip: 'This file is a Preprint. You cannot delete Preprints, but you can upload a new version.', className: 'tb-disabled' }, 'Delete')); // Tooltips don't seem to auto reapply, this forces them. reapplyTooltips(); } else { rowButtons.push( m.component(FGButton, { onclick: function(event) { _removeEvent.call(tb, event, [item]); }, icon: 'fa fa-trash', className: 'text-danger' }, 'Delete')); } rowButtons.push( m.component(FGButton, { onclick: function(event) { tb.modal.update(m('', [ m('p', 'This would mean ' + 'other contributors cannot edit, delete or upload new versions of this file ' + 'as long as it is checked-out. You can check it back in at anytime.') ]), m('', [ m('a.btn.btn-default', {onclick: function() {tb.modal.dismiss();}}, 'Cancel'), //jshint ignore:line m('a.btn.btn-warning', {onclick: function() { doCheckout(item, window.contextVars.currentUser.id, true); }}, 'Check out file') ]), m('h3.break-word.modal-title', 'Confirm file check-out?')); }, icon: 'fa fa-sign-out', className : 'text-warning' }, 'Check out file')); } else if (item.data.extra.checkout && item.data.extra.checkout._id === window.contextVars.currentUser.id) { rowButtons.push( m.component(FGButton, { onclick: function(event) { doCheckout(item, null, true); }, icon: 'fa fa-sign-in', className : 'text-warning' }, 'Check in file') ); } } else { rowButtons.push( m.component(FGButton, { onclick: function (event) { _removeEvent.call(tb, event, [item]); }, icon: 'fa fa-trash', className: 'text-danger' }, 'Delete')); } } if(storageAddons[item.data.provider].externalView) { var providerFullName = storageAddons[item.data.provider].fullName; rowButtons.push( m('a.text-info.fangorn-toolbar-icon', {href: item.data.extra.webView}, [ m('i.fa.fa-external-link'), m('span', 'View on ' + providerFullName) ]) ); } } else if (item.data.provider) { rowButtons.push( m.component(FGButton, { onclick: function (event) { _downloadZipEvent.call(tb, event, item); }, icon: 'fa fa-download', className: 'text-primary' }, 'Download as zip') ); } if (item.data.provider && !item.data.isAddonRoot && item.data.permissions && item.data.permissions.edit && (item.data.provider !== 'osfstorage' || !item.data.extra.checkout)) { rowButtons.push( m.component(FGButton, { onclick: function () { mode(toolbarModes.RENAME); }, icon: 'fa fa-pencil', className: 'text-info' }, 'Rename') ); } return m('span', rowButtons); } } }; var dismissToolbar = function(helpText){ var tb = this; if (tb.toolbarMode() === toolbarModes.FILTER){ tb.resetFilter(); } tb.toolbarMode(toolbarModes.DEFAULT); tb.filterText(''); if(typeof helpText === 'function'){ helpText(''); } m.redraw(); }; var FGToolbar = { controller : function(args) { var self = this; self.tb = args.treebeard; self.tb.toolbarMode = m.prop(toolbarModes.DEFAULT); self.items = args.treebeard.multiselected; self.mode = self.tb.toolbarMode; self.isUploading = args.treebeard.isUploading; self.helpText = m.prop(''); self.dismissToolbar = dismissToolbar.bind(self.tb, self.helpText); self.createFolder = function(event){ _createFolder.call(self.tb, event, self.dismissToolbar, self.helpText); }; self.nameData = m.prop(''); self.renameId = m.prop(''); self.renameData = m.prop(''); }, view : function(ctrl) { var templates = {}; var generalButtons = []; var finalRowButtons = []; var items = ctrl.items(); var item = items[0]; var dismissIcon = m.component(FGButton, { onclick: ctrl.dismissToolbar, icon : 'fa fa-times' }, ''); templates[toolbarModes.FILTER] = [ m('.col-xs-9', [ ctrl.tb.options.filterTemplate.call(ctrl.tb) ]), m('.col-xs-3.tb-buttons-col', m('.fangorn-toolbar.pull-right', [dismissIcon]) ) ]; $('.tb-row').click(function(){ ctrl.helpText(''); }); if (ctrl.tb.toolbarMode() === toolbarModes.DEFAULT) { ctrl.nameData(''); ctrl.renameId(''); } if(typeof item !== 'undefined' && item.id !== ctrl.renameId()){ ctrl.renameData(item.data.name); ctrl.renameId(item.id); } if (ctrl.tb.options.placement !== 'fileview') { templates[toolbarModes.ADDFOLDER] = [ m('.col-xs-9', [ m.component(FGInput, { oninput: m.withAttr('value', ctrl.nameData), onkeypress: function (event) { if (ctrl.tb.pressedKey === ENTER_KEY) { ctrl.createFolder.call(ctrl.tb, event, ctrl.dismissToolbar); } }, id: 'createFolderInput', value: ctrl.nameData(), helpTextId: 'createFolderHelp', placeholder: 'New folder name', }, ctrl.helpText()) ]), m('.col-xs-3.tb-buttons-col', m('.fangorn-toolbar.pull-right', [ m.component(FGButton, { onclick: ctrl.createFolder, icon: 'fa fa-plus', className: 'text-success' }), dismissIcon ] ) ) ]; templates[toolbarModes.RENAME] = [ m('.col-xs-9', m.component(FGInput, { oninput: m.withAttr('value', ctrl.renameData), onkeypress: function (event) { if (ctrl.tb.pressedKey === ENTER_KEY) { _renameEvent.call(ctrl.tb); } }, id: 'renameInput', value: ctrl.renameData(), helpTextId: 'renameHelpText', placeholder: 'Enter name', }, ctrl.helpText()) ), m('.col-xs-3.tb-buttons-col', m('.fangorn-toolbar.pull-right', [ m.component(FGButton, { onclick: function () { _renameEvent.call(ctrl.tb); }, icon: 'fa fa-pencil', className: 'text-info' }), dismissIcon ] ) ) ]; } // Bar mode // Which buttons should show? if(items.length === 1){ var addonButtons = resolveconfigOption.call(ctrl.tb, item, 'itemButtons', [item]); if (addonButtons) { finalRowButtons = m.component(addonButtons, {treebeard : ctrl.tb, item : item }); // jshint ignore:line } else if (ctrl.tb.options.placement !== 'fileview') { finalRowButtons = m.component(FGItemButtons, {treebeard : ctrl.tb, mode : ctrl.mode, item : item }); // jshint ignore:line } } if(ctrl.isUploading() && ctrl.tb.options.placement !== 'fileview') { generalButtons.push( m.component(FGButton, { onclick: function() { cancelAllUploads.call(ctrl.tb); }, icon: 'fa fa-time-circle', className : 'text-danger' }, 'Cancel Pending Uploads') ); } // multiple selection icons // Special cased to not show 'delete multiple' for github or published dataverses if( (items.length > 1) && (ctrl.tb.multiselected()[0].data.provider !== 'github') && (ctrl.tb.multiselected()[0].data.provider !== 'onedrive') && (ctrl.tb.options.placement !== 'fileview') && !( (ctrl.tb.multiselected()[0].data.provider === 'dataverse') && (ctrl.tb.multiselected()[0].parent().data.version === 'latest-published') ) ) { if (showDeleteMultiple(items)) { var preprintPath = getPreprintPath(window.contextVars.node.preprintFileId); if (preprintPath && multiselectContainsPreprint(items, preprintPath)) { generalButtons.push( m.component(FGButton, { icon: 'fa fa-trash', tooltip: 'One of these items is a Preprint or contains a Preprint. You cannot delete Preprints, but you can upload a new version.', className: 'tb-disabled' }, 'Delete Multiple') ); } else { generalButtons.push( m.component(FGButton, { onclick: function(event) { var configOption = resolveconfigOption.call(ctrl.tb, item, 'removeEvent', [event, items]); // jshint ignore:line if(!configOption){ _removeEvent.call(ctrl.tb, null, items); } }, icon: 'fa fa-trash', className : 'text-danger' }, 'Delete Multiple') ); } } } generalButtons.push( m.component(FGButton, { onclick: function(event){ ctrl.mode(toolbarModes.FILTER); }, icon: 'fa fa-search', className : 'text-primary' }, 'Filter')); if (ctrl.tb.options.placement !== 'fileview') { generalButtons.push(m.component(FGButton, { onclick: function(event){ var mithrilContent = m('div', [ m('p', [ m('b', 'Select rows:'), m('span', ' Click on a row (outside the add-on, file, or folder name) to show further actions in the toolbar. Use Command or Shift keys to select multiple files.')]), m('p', [ m('b', 'Open files:'), m('span', ' Click a file name to go to view the file in the OSF.')]), m('p', [ m('b', 'Open files in new tab:'), m('span', ' Press Command (Ctrl in Windows) and click a file name to open it in a new tab.')]), m('p', [ m('b', 'Download as zip:'), m('span', ' Click on the row of an add-on or folder and click the Download as Zip button in the toolbar.'), m('i', ' Not available for all storage add-ons.')]), m('p', [ m('b', 'Copy files:'), m('span', ' Press Option (Alt in Windows) while dragging a file to a new folder or component.'), m('i', ' Only for contributors with write access.')]) ]); var mithrilButtons = m('button', { 'type':'button', 'class' : 'btn btn-default', onclick : function(event) { ctrl.tb.modal.dismiss(); } }, 'Close'); ctrl.tb.modal.update(mithrilContent, mithrilButtons, m('h3.modal-title.break-word', 'How to Use the File Browser')); }, icon: 'fa fa-info', className : 'text-info' }, '')); } if (ctrl.tb.options.placement === 'fileview') { generalButtons.push(m.component(FGButton, { onclick: function(event){ var panelToggle = $('.panel-toggle'); var panelExpand = $('.panel-expand'); var panelVisible = panelToggle.find('.osf-panel-hide'); var panelHidden = panelToggle.find('.osf-panel-show'); panelVisible.hide(); panelHidden.show(); }, icon: 'fa fa-angle-up' }, '')); } if (item && item.connected !== false){ // as opposed to undefined, avoids unnecessary setting of this value templates[toolbarModes.DEFAULT] = m('.col-xs-12', m('.pull-right', [finalRowButtons, m('span', generalButtons)])); } else { templates[toolbarModes.DEFAULT] = m('.col-xs-12', m('.pull-right', m('span', generalButtons))); } return m('.row.tb-header-row', [ m('#folderRow', { config : function () { $('#folderRow input').focus(); }}, [ templates[ctrl.mode()] ]) ]); } }; /** * When multiple rows are selected remove those that are not valid * @param {Array} rows List of item objects * @returns {Array} newRows Returns the revised list of rows */ function filterRows(rows) { if(rows.length === 0){ return; } var tb = this; var i, newRows = [], originalRow = tb.find(tb.multiselected()[0].id), originalParent, currentItem; function changeColor() { $(this).css('background-color', ''); } if (originalRow !== undefined) { originalParent = originalRow.parentID; for (i = 0; i < rows.length; i++) { currentItem = rows[i]; // Filter rows that are no in the parent var inParent = currentItem.parentID === originalParent && currentItem.id !== -1; var inProgress = typeof currentItem.inProgress !== 'undefined' && currentItem.inProgress; if (inParent && !inProgress) { newRows.push(rows[i]); } else { $('.tb-row[data-id="' + rows[i].id + '"]').stop().css('background-color', '#D18C93') .animate({ backgroundColor: '#fff'}, 500, changeColor); if (inProgress) { $osf.growl('Error', 'Please wait for current action to complete'); } } } } tb.multiselected(newRows); tb.highlightMultiselect(); return newRows; } /** * Helper function that turns parent open values to true to respective redraws can open the folder * @this Treebeard.controller * @param {Object} item A Treebeard _item object. * @private */ function openParentFolders (item) { var tb = this; // does it have a parent? If so change open var parent = item.parent(); if (parent) { if (!parent.open) { var index = tb.returnIndex(parent.id); parent.load = true; tb.toggleFolder(index); } openParentFolders.call(tb, parent); } } /** * Handles multiselect conditions and actions * @this Treebeard.controller * @param {Object} event jQuery click event. * @param {Object} row A Treebeard _item object. * @private */ function _fangornMultiselect (event, row) { var tb = this; var scrollToItem = false; if (tb.toolbarMode() === 'filter') { scrollToItem = true; // recursively open parents of the selected item but do not lazyload; openParentFolders.call(tb, row); } dismissToolbar.call(tb); filterRows.call(tb, tb.multiselected()); if (tb.multiselected().length === 1){ tb.select('#tb-tbody').removeClass('unselectable'); if(scrollToItem) { scrollToFile.call(tb, tb.multiselected()[0].id); } } else if (tb.multiselected().length > 1) { tb.select('#tb-tbody').addClass('unselectable'); } m.redraw(); reapplyTooltips(); } /* BEGIN MOVE */ // copyMode can be 'copy', 'move', 'forbidden', or null. // This is set at draglogic and is used as global within this module var copyMode = null; // Set altkey global to fangorn var altKey = false; $(document).keydown(function (e) { if (e.altKey) { altKey = true; } }); $(document).keyup(function (e) { if (!e.altKey) { altKey = false; } }); /** * Hook for the drag start event on jquery * @param event jQuery UI drggable event object * @param ui jQuery UI draggable ui object * @private */ function _fangornDragStart(event, ui) { // Sync up the toolbar in case item was drag-clicked and not released m.redraw(); var itemID = $(event.target).attr('data-id'), item = this.find(itemID); if (this.multiselected().length < 2) { this.multiselected([item]); } } /** * Hook for the drop event of jQuery UI droppable * @param event jQuery UI droppable event object * @param ui jQuery UI droppable ui object * @private */ function _fangornDrop(event, ui) { var tb = this; var items = tb.multiselected().length === 0 ? [tb.find(tb.selected)] : tb.multiselected(), folder = tb.find($(event.target).attr('data-id')); // Run drop logic here _dropLogic.call(tb, event, items, folder); } /** * Hook for the over event of jQuery UI droppable * @param event jQuery UI droppable event object * @param ui jQuery UI droppable ui object * @private */ function _fangornOver(event, ui) { var tb = this; var items = tb.multiselected().length === 0 ? [tb.find(tb.selected)] : tb.multiselected(), folder = tb.find($(event.target).attr('data-id')), dragState = _dragLogic.call(tb, event, items, ui); $('.tb-row').removeClass('tb-h-success fangorn-hover'); if (dragState !== 'forbidden') { $('.tb-row[data-id="' + folder.id + '"]').addClass('tb-h-success'); } else { $('.tb-row[data-id="' + folder.id + '"]').addClass('fangorn-hover'); } } /** * Log the success or failure of a file action (upload, etc.) in treebeard * @param {Object} treebeard The treebeard instance currently being run, check Treebeard API * @param {Object} file File object that dropzone passes * @param success Boolean on whether upload actually happened * @param message String failure reason message, '' if success === true * @param link String with url to file, '' if success === false * @param op String specifying type of move conflict resolution; ['keep', 'skip', 'replace'] * @private */ function addFileStatus(treebeard, file, success, message, link, op){ if (typeof op !== 'undefined'){ treebeard.moveStates.push( {'name': file.data.name, 'success': success, 'link': link, 'op': op} ); } else { treebeard.uploadStates.push( {'name': file.name, 'success': success, 'link': link, 'message': message} ); } } /** * Triggers file status modal or growlboxes after upload queue is empty * @param {Object} treebeard The treebeard instance currently being run, check Treebeard API * @private */ var UPLOAD_MODAL_MIN_FILE_QUANTITY = 4; function _fangornQueueComplete(treebeard) { var fileStatuses = treebeard.uploadStates; treebeard.uploadStates = []; var total = fileStatuses.length; var failed = 0; if (total >= UPLOAD_MODAL_MIN_FILE_QUANTITY) { treebeard.modal.update(m('', [ m('', [ fileStatuses.map(function(status){ if (!status.success){ failed++; } return m('', [ m('.row', [ m((status.success ? 'a[href="' + status.link + '"]' : '') + '.col-sm-10', status.name), m('.col-sm-1', m(status.success ? '.fa.fa-check[style="color: green"]' : '.fa.fa-times[style="color: red"]')), m('.col-sm-1', m(!status.success ? '.fa.fa-info[data-toggle="tooltip"][data-placement="top"][title="'+ status.message +'"]' : '')) ]), m('hr') ] ); }) ]) ]), m('', [ m('a.btn.btn-primary', {onclick: function() {treebeard.modal.dismiss();}}, 'Done'), //jshint ignore:line ]), m('', [m('h3.break-word.modal-title', 'Upload Status'), m('p', total - failed + '/' + total + ' files succeeded.')])); $('[data-toggle="tooltip"]').tooltip(); } else { fileStatuses.map(function(status) { if (!status.success) { if (status.message !== 'Upload canceled.') { $osf.growl( 'Error', status.message ); } } }); } } /** * Where the drop actions happen * @param event jQuery UI drop event * @param {Array} items List of items being dragged at the time. Each item is a _item object * @param {Object} folder Folder information as _item object */ function _dropLogic(event, items, folder) { var tb = this; if (items.length < 1 || items.indexOf(folder) > -1 || copyMode === 'forbidden' ) { return; } if (folder.data.kind === 'file') { folder = folder.parent(); } if (!folder.open) { return tb.updateFolder(null, folder, _dropLogic.bind(tb, event, items, folder)); } var toMove = checkConflicts(items, folder); tb.syncFileMoveCache = tb.syncFileMoveCache || {}; tb.syncFileMoveCache[folder.data.provider] = tb.syncFileMoveCache[folder.data.provider] || {}; tb.moveStates = []; if (toMove.ready.length > 0) { tb.syncFileMoveCache[folder.data.provider].ready = tb.syncFileMoveCache[folder.data.provider].ready || []; if (SYNC_UPLOAD_ADDONS.indexOf(folder.data.provider) !== -1) { toMove.ready.forEach(function(item) { tb.syncFileMoveCache[folder.data.provider].ready.push({'item' : item, 'folder' : folder}); }); } else { toMove.ready.forEach(function(item) { doItemOp.call(tb, copyMode === 'move' ? OPERATIONS.MOVE : OPERATIONS.COPY, folder, item, undefined, 'replace'); }); } } if (toMove.conflicts.length > 0) { tb.syncFileMoveCache[folder.data.provider].conflicts = tb.syncFileMoveCache[folder.data.provider].conflicts || []; toMove.conflicts.forEach(function(item) { tb.syncFileMoveCache[folder.data.provider].conflicts.push({'item' : item, 'folder' : folder}); }); } if (tb.syncFileMoveCache[folder.data.provider].conflicts || tb.syncFileMoveCache[folder.data.provider].ready) { doSyncMove(tb, folder.data.provider); } } function displayMoveStats(tb) { var moveStatuses = tb.moveStates; var total = moveStatuses && moveStatuses.length; if (moveStatuses.length) { tb.moveStates = []; var failed = 0; var skipped = 0; tb.modal.update(m('', [ m('', [ moveStatuses.map(function(status){ if (!status.success){ failed++; } if (status.op === 'skip'){ skipped++; } return m('', [ m('.row', [ m((status.success ? 'a[href="' + status.link + '"]' : '') + '.col-sm-7', status.name), m('.col-sm-1', m(status.success ? '.fa.fa-check.text-success' : '.fa.fa-times.text-danger')), m('.col-sm-4' + (status.success ? '.text-info' : '.text-danger'), CONFLICT_INFO[status.op].passed) ]), m('hr') ] ); }) ]) ]), m('', [ m('a.btn.btn-primary', {onclick: function() {tb.modal.dismiss();}}, 'Done'), //jshint ignore:line ]), m('', [ m('h3.break-word.modal-title', 'Move Status'), m('p', [ m('span', failed !== total ? total - failed + '/' + total + ' files successfully moved.': ''), m('span', skipped ? ' Skipped ' + skipped + '/' + total + ' files.': '') ]) ])); } else { tb.modal.dismiss(); } } function doSyncMove(tb, provider){ var cache = tb.syncFileMoveCache && tb.syncFileMoveCache[provider]; var itemData; if (cache.conflicts && cache.conflicts.length > 0) { itemData = cache.conflicts.pop(); displayConflict(tb, itemData.item, itemData.folder, doItemOp.bind(tb, copyMode === 'move' ? OPERATIONS.MOVE : OPERATIONS.COPY, itemData.folder, itemData.item, undefined)); } else if (cache.ready && cache.ready.length > 0) { itemData = cache.ready.pop(); doItemOp.call(tb, copyMode === 'move' ? OPERATIONS.MOVE : OPERATIONS.COPY, itemData.folder, itemData.item, undefined, 'replace'); } else { displayMoveStats(tb); } } /** * Sets the copy state based on which item is being dragged on which other item * @param {Object} event Browser drag event * @param {Array} items List of items being dragged at the time. Each item is a _item object * @param {Object} ui jQuery UI draggable drag ui object * @returns {String} copyMode One of the copy states, from 'copy', 'move', 'forbidden' */ function _dragLogic(event, items, ui) { var tb = this; var canMove = true, folder = this.find($(event.target).attr('data-id')), dragGhost = $('.tb-drag-ghost'); // Set the cursor to match the appropriate copy mode copyMode = getCopyMode(folder, items); switch (copyMode) { case 'forbidden': dragGhost.css('cursor', 'not-allowed'); break; case 'copy': dragGhost.css('cursor', 'copy'); break; case 'move': dragGhost.css('cursor', 'move'); break; default: dragGhost.css('cursor', 'default'); } return copyMode; } function getAllChildren(item) { var c; var current; var children = []; var remaining = []; for (c in item.children) { remaining.push(item.children[c]); } while (remaining.length > 0) { current = remaining.pop(); children.push(current); for (c in current.children) { remaining.push(current.children[c]); } } return children; } function isInvalidDropFolder(folder) { if ( // cannot drop on root line folder.parentID === 0 || // don't drop if changed folder.inProgress || // cannot drop on files folder.data.nodeType || folder.data.kind !== 'folder' || // must have permission !folder.data.permissions.edit || // must have a provider !folder.data.provider || folder.data.status || // cannot add to published dataverse (folder.data.provider === 'dataverse' && folder.data.dataverseIsPublished) || // no dropping into read-only providers (READ_ONLY_ADDONS.indexOf(folder.data.provider) !== -1) ) { return true; } return false; } function isInvalidDropItem(folder, item, cannotBeFolder, mustBeIntra) { if ( // not a valid drop if is a node item.data.nodeType || // cannot drop on roots item.data.isAddonRoot || // no self drops item.id === folder.id || // no dropping on direct parent item.parentID === folder.id || // no moving published items from dataverse (item.data.provider === 'dataverse' && item.data.extra.hasPublishedVersion) || // no moving folders into dataverse (folder.data.provider === 'dataverse' && item.data.kind === 'folder') || // no dropping if waiting on waterbutler ajax item.inProgress || (cannotBeFolder && item.data.kind === 'folder') || (mustBeIntra && item.data.provider !== folder.data.provider) ) { return true; } return false; } function allowedToMove(folder, item, mustBeIntra) { return ( item.data.permissions.edit && (!mustBeIntra || (item.data.provider === folder.data.provider && item.data.nodeId === folder.data.nodeId)) && !(item.data.provider === 'figshare' && item.data.extra && item.data.extra.status === 'public') && (READ_ONLY_ADDONS.indexOf(item.data.provider) === -1) && (READ_ONLY_ADDONS.indexOf(folder.data.provider) === -1) ); } function folderContainsPreprint(item, preprintPath) { // TODO This will only get children of open folders -ajs var children = getAllChildren(item); for (var c = 0; c < children.length; c++) { if (children[c].data.path === preprintPath) { return true; } } return false; } function showDeleteMultiple(items) { // Only show delete button if user has edit permissions on at least one selected file for (var i = 0; i < items.length; i++) { var each = items[i].data; if (typeof each.permissions !== 'undefined' && each.permissions.edit && !each.isAddonRoot && !each.nodeType) { return true; } } return false; } function multiselectContainsPreprint(items, preprintPath) { for (var i = 0; i < items.length; i++) { var each = items[i]; if (each.data.kind === 'folder') { if (folderContainsPreprint(each, preprintPath)) { return true; } } else if (each.data.path === preprintPath) { return true; } } return false; } function getPreprintPath(preprintFileId) { if (preprintFileId) { return '/' + preprintFileId; } return null; } function getCopyMode(folder, items) { var tb = this; // Prevents side effects from rare instance where folders not fully populated if (typeof folder === 'undefined' || typeof folder.data === 'undefined') { return 'forbidden'; } var preprintPath = getPreprintPath(window.contextVars.node.preprintFileId); var canMove = true; var mustBeIntra = (folder.data.provider === 'github'); // Folders cannot be copied to dataverse at all. Folders may only be copied to figshare // if the target is the addon root and the root is a project (not a fileset) var cannotBeFolder = ( folder.data.provider === 'dataverse' || (folder.data.provider === 'figshare' && !(folder.data.isAddonRoot && folder.data.rootFolderType === 'project')) ); if (isInvalidDropFolder(folder)) { return 'forbidden'; } for (var i = 0; i < items.length; i++) { var item = items[i]; if (isInvalidDropItem(folder, item, cannotBeFolder, mustBeIntra)) { return 'forbidden'; } var children = getAllChildren(item); for (var c = 0; c < children.length; c++) { if (children[c].inProgress || children[c].id === folder.id) { return 'forbidden'; } if (children[c].data.path === preprintPath){ mustBeIntra = true; } } if (canMove) { mustBeIntra = mustBeIntra || item.data.provider === 'github' || preprintPath === item.data.path; canMove = allowedToMove(folder, item, mustBeIntra); } } if (folder.data.isPointer || altKey || !canMove) { return 'copy'; } return 'move'; } /* END MOVE */ function _resizeHeight () { var tb = this; var tbody = tb.select('#tb-tbody'); var windowHeight = $(window).height(); var topBuffer = tbody.offset().top + 50; var availableSpace = windowHeight - topBuffer; if(availableSpace > 0) { // Set a minimum height tbody.height(availableSpace < 300 ? 300 : availableSpace); } } /** * OSF-specific Treebeard options common to all addons. * Check Treebeard API for more information */ tbOptions = { rowHeight : 35, // user can override or get from .tb-row height showTotal : 15, // Actually this is calculated with div height, not needed. NEEDS CHECKING paginate : false, // Whether the applet starts with pagination or not. paginateToggle : false, // Show the buttons that allow users to switch between scroll and paginate. uploads : true, // Turns dropzone on/off. columnTitles : _fangornColumnTitles, resolveRows : _fangornResolveRows, lazyLoadPreprocess: waterbutler.wbLazyLoadPreprocess, hoverClassMultiselect : 'fangorn-selected', multiselect : true, placement : 'files', title : function() { //TODO Add disk saving mode message // if(window.contextVars.diskSavingMode) { // // If File and FileRead are not defined dropzone is not supported and neither is uploads // if (window.File && window.FileReader) { // return m('p', { // }, [ // m('span', 'To Upload: Drag files into a folder OR click the '), // m('i.btn.btn-default.btn-xs', { disabled : 'disabled'}, [ m('i.fa.fa-upload')]), // m('span', ' below.') // ]); // } // return m('p', { // class: 'text-danger' // }, [ // m('span', 'Your browser does not support file uploads, ', [ // m('a', { href: 'http://browsehappy.com' }, 'learn more'), // '.' // ]) // ]); // } return undefined; }, showFilter : true, // Gives the option to filter by showing the filter box. allowMove : true, // Turn moving on or off. hoverClass : 'fangorn-hover', togglecheck : _fangornToggleCheck, sortButtonSelector : { up : 'i.fa.fa-chevron-up', down : 'i.fa.fa-chevron-down' }, ondataload: function() { _loadTopLevelChildren.call(this); }, onload : function () { var tb = this; tb.options.onload = null; // Make sure we don't get called again tb.uploadStates = []; tb.pendingFileOps = []; tb.select('#tb-tbody, .tb-tbody-inner').on('click', function(event){ if(event.target !== this) { var item = tb.multiselected()[0]; if (item) { if (item.data.isAddonRoot || item.data.nodeType === 'project' || item.data.nodeType === 'component') { tb.toolbarMode(toolbarModes.DEFAULT); } return; } } tb.clearMultiselect(); m.redraw(); dismissToolbar.call(tb); }); $(window).on('beforeunload', function() { if(tb.dropzone && tb.dropzone.getUploadingFiles().length) { return 'You have pending uploads, if you leave this page they may not complete.'; } if(tb.pendingFileOps.length > 0) { return 'You have pending file operations, if you leave this page they may not complete.'; } }); if(tb.options.placement === 'project-files') { _resizeHeight.call(tb); $(window).resize(function(){ _resizeHeight.call(tb); }); } $(window).on('keydown', function(event){ if (event.keyCode === ESCAPE_KEY) { dismissToolbar.call(tb); } }); }, movecheck : function (to, from) { //This method gives the users an option to do checks and define their return return true; }, movefail : function (to, from) { //This method gives the users an option to do checks and define their return return true; }, addcheck : function (treebeard, item, file) { var size; var maxSize; var displaySize; var msgText; if (_fangornCanDrop(treebeard, item)) { if (item.data.accept && item.data.accept.maxSize) { size = file.size / 1000000; maxSize = item.data.accept.maxSize; if (size > maxSize) { displaySize = Math.round(file.size / 10000) / 100; msgText = 'One of the files is too large (' + displaySize + ' MB). Max file size is ' + item.data.accept.maxSize + ' MB.'; item.notify.update(msgText, 'warning', undefined, 3000); addFileStatus(treebeard, file, false, 'File is too large. Max file size is ' + item.data.accept.maxSize + ' MB.', ''); return false; } } return true; } return false; }, onscrollcomplete : function(){ reapplyTooltips(); }, onmultiselect : _fangornMultiselect, filterPlaceholder : 'Filter', onmouseoverrow : _fangornMouseOverRow, sortDepth : 2, dropzone : { // All dropzone options. maxFilesize: 10000000, url: function(files) {return files[0].url;}, clickable : '#treeGrid', addRemoveLinks : false, previewTemplate : '<div></div>', parallelUploads : 5, acceptDirectories : false, createImageThumbnails : false, fallback: function(){}, }, resolveIcon : _fangornResolveIcon, resolveToggle : _fangornResolveToggle, // Pass ``null`` to avoid overwriting Dropzone URL resolver resolveUploadUrl: function() {return null;}, resolveLazyloadUrl : _fangornResolveLazyLoad, resolveUploadMethod : _fangornUploadMethod, lazyLoadError : _fangornLazyLoadError, lazyLoadOnLoad : _fangornLazyLoadOnLoad, ontogglefolder : expandStateLoad, dropzoneEvents : { uploadprogress : _fangornUploadProgress, sending : _fangornSending, complete : _fangornComplete, success : _fangornDropzoneSuccess, removedfile: _fangornDropzoneRemovedFile, error : _fangornDropzoneError, dragover : _fangornDragOver, addedfile : _fangornAddedFile, drop : _fangornDropzoneDrop, queuecomplete : _fangornQueueComplete }, resolveRefreshIcon : function() { return m('i.fa.fa-refresh.fa-spin'); }, removeIcon : function(){ return m.trust('&times;'); }, toolbarComponent : FGToolbar, // DRAG AND DROP RELATED OPTIONS dragOptions : {}, dropOptions : {}, dragEvents : { start : _fangornDragStart }, dropEvents : { drop : _fangornDrop, over : _fangornOver }, onafterselectwitharrow : function(row, direction) { var tb = this; var item = tb.find(row.id); _fangornMultiselect.call(tb, null, item); }, hScroll : null, naturalScrollLimit : 0 }; /** * Loads Fangorn with options * @param {Object} options The options to be extended with Treebeard options * @constructor */ function Fangorn(options) { this.options = $.extend({}, tbOptions, options); this.grid = null; // Set by _initGrid this.init(); } /** * Initialize Fangorn methods that connect it to Treebeard * @type {{constructor: Fangorn, init: Function, _initGrid: Function}} */ Fangorn.prototype = { constructor: Fangorn, init: function () { this._initGrid(); }, // Create the Treebeard once all addons have been configured _initGrid: function () { this.grid = new Treebeard(this.options); return this.grid; } }; Fangorn.Components = { button : FGButton, input : FGInput, toolbar : FGToolbar, dropdown : FGDropdown, toolbarModes : toolbarModes }; Fangorn.ButtonEvents = { _downloadEvent : _downloadEvent, _downloadZipEvent: _downloadZipEvent, _uploadEvent : _uploadEvent, _removeEvent : _removeEvent, createFolder : _createFolder, _gotoFileEvent : gotoFileEvent, }; Fangorn.DefaultColumns = { _fangornTitleColumn : _fangornTitleColumn, _fangornVersionColumn : _fangornVersionColumn, _fangornModifiedColumn : _fangornModifiedColumn }; Fangorn.Utils = { inheritFromParent : inheritFromParent, resolveconfigOption: resolveconfigOption, reapplyTooltips : reapplyTooltips, setCurrentFileID: setCurrentFileID, scrollToFile: scrollToFile, openParentFolders : openParentFolders, dismissToolbar : dismissToolbar, uploadRowTemplate : uploadRowTemplate, resolveIconView : resolveIconView, orderFolder : orderFolder, connectCheckTemplate : _connectCheckTemplate }; Fangorn.DefaultOptions = tbOptions; module.exports = { Fangorn : Fangorn, allowedToMove : allowedToMove, folderContainsPreprint : folderContainsPreprint, getAllChildren : getAllChildren, isInvalidDropFolder : isInvalidDropFolder, isInvalidDropItem : isInvalidDropItem, getCopyMode : getCopyMode, multiselectContainsPreprint : multiselectContainsPreprint, showDeleteMultiple : showDeleteMultiple, checkConflicts : checkConflicts };
website/static/js/fangorn.js
/** * Fangorn: Defining Treebeard options for OSF. * For Treebeard and _item API's check: https://github.com/caneruguz/treebeard/wiki */ 'use strict'; var $ = require('jquery'); var m = require('mithril'); var URI = require('URIjs'); var Raven = require('raven-js'); var Treebeard = require('treebeard'); var moment = require('moment'); var Dropzone = require('dropzone'); var lodashGet = require('lodash.get'); var $osf = require('js/osfHelpers'); var waterbutler = require('js/waterbutler'); var iconmap = require('js/iconmap'); var storageAddons = require('json!storageAddons.json'); // CSS require('css/fangorn.css'); var tbOptions; var noop = function () { }; var tempCounter = 1; var STATE_MAP = { upload: { display: 'Upload pending...' }, copy: { display: 'Copying ' }, delete: { display: 'Deleting ' }, move: { display: 'Moving ' }, rename: { display: 'Renaming ' } }; var SYNC_UPLOAD_ADDONS = ['github', 'dataverse']; var READ_ONLY_ADDONS = ['bitbucket', 'gitlab', 'onedrive']; var CONFLICT_INFO = { skip: { passed: 'Skipped' }, replace: { passed: 'Replaced old version' }, keep: { passed: 'Kept both versions' } }; var OPERATIONS = { RENAME: { verb: 'Rename', status: 'rename', passed: 'renamed', action: 'Renaming' }, MOVE: { verb: 'Move', status: 'move', passed: 'moved', action: 'Moving' }, COPY: { verb: 'Copy', status: 'copy', passed: 'copied', action: 'Copying' } }; // Cross browser key codes for the Command key var COMMAND_KEYS = [224, 17, 91, 93]; var ESCAPE_KEY = 27; var ENTER_KEY = 13; function findByTempID(parent, tmpID) { var child; var item; for (var i = 0; i < parent.children.length; i++) { child = parent.children[i]; if (!child.data.tmpID) { continue; } if (child.data.tmpID === tmpID) { item = child; } } return item; } /** * Cancel a pending upload * @this Treebeard.controller * @param {Object} row Treebeard row containing the file to cancel. */ function cancelUpload(row) { var tb = this; var cancelableStatuses = [Dropzone.UPLOADING, Dropzone.QUEUED]; // Select files that are uploading, queued, or rejected (!accepted) var filesArr = tb.dropzone.files.filter(function(file) { return cancelableStatuses.indexOf(file.status) > -1 || !file.accepted; }); var handled = false; // Search for and remove specified file from queue if (SYNC_UPLOAD_ADDONS.indexOf(row.data.provider) !== -1) { // Provider is handled in sync handled = tb.dropzone.syncFileCache[row.data.provider].some(function(file, index) { if (file.tmpID === row.data.tmpID) { tb.deleteNode(row.parentID, row.id); return tb.dropzone.syncFileCache[row.data.provider].splice(index, 1); } }); } if (!handled) { // File is currently being uploaded/managed by dropzone handled = filesArr.some(function(file) { if (file.tmpID === row.data.tmpID) { tb.deleteNode(row.parentID, row.id); tb.dropzone.removeFile(file); return true; } }); } tb.isUploading(handled && filesArr.length > 1); } /** * Cancel all pending uploads * @this Treebeard.controller */ function cancelAllUploads() { var tb = this; var cancelableStatuses = [Dropzone.UPLOADING, Dropzone.QUEUED]; // Select files that are uploading, queued, or rejected (!accepted) var filesArr = tb.dropzone.files.filter(function(file) { return cancelableStatuses.indexOf(file.status) > -1 || !file.accepted; }); // Remove all queued files var removeFromUI = function(file) { var parent = file.treebeardParent || tb.dropzoneItemCache; var item = findByTempID(parent, file.tmpID); tb.deleteNode(parent.id, item.id); }; // Clear all synchronous uploads if (tb.dropzone.syncFileCache !== undefined) { SYNC_UPLOAD_ADDONS.forEach(function(provider) { if (tb.dropzone.syncFileCache[provider] !== undefined) { // Remove cached provider files from UI tb.dropzone.syncFileCache[provider].forEach(removeFromUI); // Clear provider cache tb.dropzone.syncFileCache[provider].length = 0; } }); } // Clear all ongoing uploads filesArr.forEach(function(file, index) { // Ignore completed files if (file.upload.progress === 100) return; removeFromUI(file); // Cancel currently uploading file tb.dropzone.removeFile(file); }); tb.isUploading(false); } var uploadRowTemplate = function(item) { var tb = this; var padding; if (tb.filterOn) { padding = 20; } else { padding = (item.depth - 1) * 20; } var columns = [{ data : '', // Data field name css : '', custom : function(){ var uploadColumns = [ m('.col-xs-7', {style: 'overflow: hidden;text-overflow: ellipsis;'}, [ m('span', { style : 'padding-left:' + padding + 'px;'}, tb.options.resolveIcon.call(tb, item)), m('span', { style : 'margin-left: 9px;'}, item.data.name) ]), m('.col-xs-3', m('.progress', [ m('.progress-bar.progress-bar-info.progress-bar-striped.active', { role : 'progressbar', 'aria-valuenow' : item.data.progress, 'aria-valuemin' : '0', 'aria-valuemax': '100', 'style' : 'width: ' + item.data.progress + '%' }, m('span.sr-only', item.data.progress + '% Complete')) ]) ) ]; if (item.data.progress < 100) { uploadColumns.push(m('.col-xs-2', [ m('span', m('.fangorn-toolbar-icon.m-l-sm', { style : 'padding: 0px 6px 2px 2px;font-size: 16px;display: inline;', config : function() { reapplyTooltips(); }, 'onclick' : function (e) { e.stopImmediatePropagation(); cancelUpload.call(tb, item); }}, m('span.text-muted', '×') )) ])); } return m('row.text-muted', uploadColumns); } }]; if(tb.options.placement === 'files'){ columns.push({ data : '', // Data field name custom : function(){ return '';} }); } return columns; }; /** * Returns custom icons for OSF depending on the type of item. Used for non-file icons. * @param {Object} item A Treebeard _item object. Node information is inside item.data * @this Treebeard.controller * @returns {Object} Returns a mithril template with the m() function. */ function resolveIconView(item) { var icons = iconmap.projectComponentIcons; function returnView(type, category) { var iconType = icons[type]; if(type === 'project' || type === 'component' || type === 'registeredProject' || type === 'registeredComponent') { if (item.data.permissions.view) { iconType = icons[category]; } else { return null; } } if (type === 'registeredComponent' || type === 'registeredProject') { iconType += ' po-icon-registered'; } else { iconType += ' po-icon'; } var template = m('span', { 'class' : iconType}); return template; } if (item.data.permissions){ if (!item.data.permissions.view) { return m('span', { 'class' : iconmap.private }); } } if (item.data.isDashboard) { return returnView('collection'); } if (item.data.isSmartFolder) { return returnView('smartCollection'); } if ((item.data.nodeType === 'pointer' && item.parent().data.nodeType !== 'folder') || (item.data.isPointer && !item.parent().data.isFolder)) { return returnView('link'); } if (item.data.nodeType === 'project') { if (item.data.parentIsFolder && item.data.isFolder) { return returnView('collection'); } if (item.data.isRegistration) { return returnView('registeredProject', item.data.category); } else { return returnView('project', item.data.category); } } if (item.data.nodeType === 'component') { if (item.data.isRegistration) { return returnView('registeredComponent', item.data.category); } return returnView('component', item.data.category); } if (item.data.nodeType === 'pointer') { return returnView('link'); } return null; } /** * Returns custom icons for OSF depending on the type of item * @param {Object} item A Treebeard _item object. Node information is inside item.data * @this Treebeard.controller * @returns {Object} Returns a mithril template with the m() function. * @private */ function _fangornResolveIcon(item) { if (item.data.unavailable) return m('div', {style: {width:'16px', height:'16px', background:'url(' + item.data.iconUrl+ ')', display:'inline-block', opacity: 0.4}}, ''); var privateFolder = m('i.fa.fa-lock', ' '), pointerFolder = m('i.fa.fa-link', ' '), openFolder = m('i.fa.fa-folder-open', ' '), closedFolder = m('i.fa.fa-folder', ' '), configOption = item.data.provider ? resolveconfigOption.call(this, item, 'folderIcon', [item]) : undefined, // jshint ignore:line icon; var newIcon = resolveIconView(item); if ( newIcon === null) { if (item.kind === 'folder') { if (item.data.iconUrl) { return m('div', {style: {width:'16px', height:'16px', background:'url(' + item.data.iconUrl+ ')', display:'inline-block'}}, ''); } if (!item.data.permissions.view) { return privateFolder; } if (item.data.isPointer) { return pointerFolder; } if (item.open) { return configOption || openFolder; } return configOption || closedFolder; } if (item.data.icon) { return m('i.fa.' + item.data.icon, ' '); } return m('div.file-extension', { 'class': '_' + item.data.name.split('.').pop().toLowerCase() }); } return newIcon; } // Addon config registry. this will be populated with add on specific items if any. Fangorn.config = {}; /** * Returns add on specific configurations * @param {Object} item A Treebeard _item object. Node information is inside item.data * @param {String} key What the option is called in the add on object * @this Treebeard.controller * @returns {*} Returns the configuration, can be string, number, array, or function; */ function getconfig(item, key) { if (item && item.data.provider && Fangorn.config[item.data.provider]) { return Fangorn.config[item.data.provider][key]; } return undefined; } /** * Gets a Fangorn config option if it is defined by an addon dev. * Calls it with `args` if it's a function otherwise returns the value. * If the config option is not defined, returns null * @param {Object} item A Treebeard _item object. Node information is inside item.data * @param {String} option What the option is called in the add on object * @param {Array} args An Array of whatever arguments will be sent with the .apply() * @this Treebeard.controller * @returns {*} Returns if its a property, runs the function if function, returns null if no option is defined. */ function resolveconfigOption(item, option, args) { var self = this, // jshint ignore:line prop = getconfig(item, option); if (prop) { return typeof prop === 'function' ? prop.apply(self, args) : prop; } return null; } /** * Inherits a list of data fields from one item (parent) to another. * @param {Object} item A Treebeard _item object. Node information is inside item.data * @param {Object} parent A Treebeard _item object. Node information is inside item.data * @this Treebeard.controller */ var inheritedFields = ['nodeId', 'nodeUrl', 'nodeApiUrl', 'permissions', 'provider', 'accept']; function inheritFromParent(item, parent, fields) { inheritedFields.concat(fields || []).forEach(function(field) { item.data[field] = item.data[field] || parent.data[field]; }); if(item.data.provider === 'github' || item.data.provider === 'bitbucket' || item.data.provider === 'gitlab'){ item.data.branch = parent.data.branch; } } /** * Returns custom folder toggle icons for OSF * @param {Object} item A Treebeard _item object. Node information is inside item.data * @this Treebeard.controller * @returns {string} Returns a mithril template with m() function, or empty string. * @private */ function _fangornResolveToggle(item) { var toggleMinus = m('i.fa.fa-minus', ' '), togglePlus = m('i.fa.fa-plus', ' '), // padding added so that this overlaps the toggle-icon div and prevent cursor change into pointer for checkout icons. checkedByUser = m('i.fa.fa-sign-out.text-muted[style="font-size: 120%; cursor: default; padding-top: 10px; padding-bottom: 10px; padding-right: 4px;"]', ''), checkedByOther = m('i.fa.fa-sign-out[style="color: #d9534f; font-size: 120%; cursor: default; padding-top: 10px; padding-bottom: 10px; padding-right: 4px;"]', ''); // check if folder has children whether it's lazyloaded or not. if (item.kind === 'folder' && item.depth > 1) { if(!item.data.permissions.view){ return ''; } if (item.open) { return toggleMinus; } return togglePlus; } if (item.data.provider === 'osfstorage' && item.kind === 'file') { if (item.data.extra && item.data.extra.checkout) { if (item.data.extra.checkout._id === window.contextVars.currentUser.id){ return checkedByUser; } return checkedByOther; } } return ''; } /** * Checks if folder toggle is permitted (i.e. contents are private) * @param {Object} item A Treebeard _item object. Node information is inside item.data * @this Treebeard.controller * @returns {boolean} * @private */ function _fangornToggleCheck(item) { if (item.data.permissions.view) { return true; } item.notify.update('Not allowed: Private folder', 'warning', 1, undefined); return false; } function checkConflicts(items, folder){ var children = { 'names': [], 'ids': [] }; var ret = { 'conflicts' : [], 'ready': [] }; folder.children.forEach(function(child){ children.names.push(child.data.name); children.ids.push(child.id); }); items.forEach(function(item) { if (children.names.includes(item.data.name) && !children.ids.includes(item.id)){ ret.conflicts.push(item); } else { ret.ready.push(item); } }); return ret; } function handleCancel(tb, provider, mode, item){ if (mode === 'stop') { tb.syncFileMoveCache[provider].conflicts.length = 0; tb.modal.dismiss(); } else { addFileStatus(tb, item, false, '', '', 'skip'); doSyncMove(tb, provider); } } function displayConflict(tb, item, folder, cb) { var mithrilContent = m('', [ m('p', 'An item named "' + item.data.name + '" already exists in this location.'), m('h5.replace-file', '"Keep Both" will retain both files (and their version histories) in this location.'), m('h5.replace-file', '"Replace" will overwrite the existing file in this location. ' + 'You will lose previous versions of the overwritten file. ' + 'You will keep previous versions of the moved file.'), m('h5.replace-file', '"Skip" will skip the current file.'), m('h5.replace-file', '"Stop" will only move files with no conflicts.') ]); var mithrilButtons = [ m('span.btn.btn-primary.btn-sm', {onclick: cb.bind(tb, 'keep')}, 'Keep Both'), m('span.btn.btn-primary.btn-sm', {onclick: cb.bind(tb, 'replace')}, 'Replace'), m('span.btn.btn-default.btn-sm', {onclick: function() {handleCancel(tb, folder.data.provider, 'skip', item);}}, 'Skip'), m('span.btn.btn-danger.btn-sm', {onclick: function() {handleCancel(tb, folder.data.provider, 'stop');}}, 'Stop') ]; var header = m('h3.break-word.modal-title', 'Replace "' + item.data.name + '"?'); tb.modal.update(mithrilContent, mithrilButtons, header); } function checkConflictsRename(tb, item, name, cb) { var messageArray = []; var parent = item.parent(); for(var i = 0; i < parent.children.length; i++) { var child = parent.children[i]; if (child.data.name === name && child.id !== item.id) { messageArray.push([ m('p', 'An item named "' + child.data.name + '" already exists in this location.'), m('h5.replace-file', '"Keep Both" will retain both files (and their version histories) in this location.'), m('h5.replace-file', '"Replace" will overwrite the existing file in this location. ' + 'You will lose previous versions of the overwritten file. ' + 'You will keep previous versions of the moved file.'), m('h5.replace-file', '"Cancel" will cancel the move.') ]); if (window.contextVars.node.preprintFileId === child.data.path.replace('/', '')) { messageArray = messageArray.concat([ m('p', 'The file "' + child.data.name + '" is the primary file for a preprint, so it should not be replaced.'), m('strong', 'Replacing this file will remove this preprint from circulation.') ]); } tb.modal.update( m('', messageArray), [ m('span.btn.btn-default', {onclick: function() {tb.modal.dismiss();}}, 'Cancel'), //jshint ignore:line m('span.btn.btn-primary', {onclick: cb.bind(tb, 'keep')}, 'Keep Both'), m('span.btn.btn-primary', {onclick: cb.bind(tb, 'replace')}, 'Replace') ], m('h3.break-word.modal-title', 'Replace "' + child.data.name + '"?') ); return; } } cb('replace'); } function doItemOp(operation, to, from, rename, conflict) { var tb = this; var inReadyQueue; var filesRemaining; var inConflictsQueue; var syncMoves; var notRenameOp = typeof rename === 'undefined'; if (notRenameOp) { filesRemaining = tb.syncFileMoveCache && tb.syncFileMoveCache[to.data.provider]; inConflictsQueue = filesRemaining.conflicts && filesRemaining.conflicts.length > 0; syncMoves = SYNC_UPLOAD_ADDONS.indexOf(from.data.provider) !== -1; if (syncMoves) { inReadyQueue = filesRemaining && filesRemaining.ready && filesRemaining.ready.length > 0; } if (inConflictsQueue) { var s = filesRemaining.conflicts.length > 1 ? 's' : ''; var mithrilContent = m('div', { className: 'text-center' }, [ m('p.h4', filesRemaining.conflicts.length + ' conflict' + s + ' left to resolve.'), m('div', {className: 'ball-pulse ball-scale-blue text-center'}, [ m('div',''), m('div',''), m('div',''), ]) ]); var header = m('h3.break-word.modal-title', operation.action + ' "' + from.data.name +'"'); tb.modal.update(mithrilContent, m('', []), header); } } var ogParent = from.parentID; if (to.id === ogParent && (!rename || rename === from.data.name)){ return; } if (operation === OPERATIONS.COPY) { from = tb.createItem($.extend(true, {status: operation.status}, from.data), to.id); } else { from.data.status = operation.status; from.move(to.id); } if (to.data.provider === from.provider) { tb.pendingFileOps.push(from.id); } orderFolder.call(tb, from.parent()); var moveSpec; if (operation === OPERATIONS.RENAME) { moveSpec = { action: 'rename', rename: rename, conflict: conflict }; } else if (operation === OPERATIONS.COPY) { moveSpec = { action: 'copy', path: to.data.path || '/', conflict: conflict, resource: to.data.nodeId, provider: to.data.provider }; } else if (operation === OPERATIONS.MOVE) { moveSpec = { action: 'move', path: to.data.path || '/', conflict: conflict, resource: to.data.nodeId, provider: to.data.provider }; } var options = {}; if(from.data.provider === 'github' || from.data.provider === 'bitbucket' || from.data.provider === 'gitlab'){ options.branch = from.data.branch; moveSpec.branch = from.data.branch; } from.inProgress = true; tb.clearMultiselect(); $.ajax({ type: 'POST', beforeSend: $osf.setXHRAuthorization, url: waterbutler.buildTreeBeardFileOp(from, options), contentType: 'application/json', data: JSON.stringify(moveSpec) }).done(function(resp, _, xhr) { if (to.data.provider === from.provider) { tb.pendingFileOps.pop(); } if (xhr.status === 202) { var mithrilContent = m('div', [ m('h3.break-word', operation.action + ' "' + (from.data.materialized || '/') + '" to "' + (to.data.materialized || '/') + '" is taking a bit longer than expected.'), m('p', 'We\'ll send you an email when it has finished.'), m('p', 'In the mean time you can leave this page; your ' + operation.status + ' will still be completed.') ]); var mithrilButtons = m('div', [ m('span.tb-modal-btn', { 'class' : 'text-default', onclick : function() { tb.modal.dismiss(); }}, 'Close') ]); var header = m('h3.modal-title.break-word', 'Operation Information'); tb.modal.update(mithrilContent, mithrilButtons, header); return; } from.data = tb.options.lazyLoadPreprocess.call(this, resp).data; from.data.status = undefined; from.notify.update('Successfully ' + operation.passed + '.', 'success', null, 1000); if (xhr.status === 200) { to.children.forEach(function(child) { if (child.data.name === from.data.name && child.id !== from.id) { child.removeSelf(); } }); } inheritFromParent(from, from.parent()); if (from.data.kind === 'folder' && from.data.children) { from.children = []; var child; from.data.children.forEach(function(item) { child = tb.buildTree(item, from); inheritFromParent(child, from); from.add(child); }); from.open = true; from.load = true; } var url = from.data.nodeUrl + 'files/' + from.data.provider + from.data.path; if (notRenameOp) { addFileStatus(tb, from, true, '', url, conflict); } // no need to redraw because fangornOrderFolder does it orderFolder.call(tb, from.parent()); }).fail(function(xhr, textStatus) { if (to.data.provider === from.provider) { tb.pendingFileOps.pop(); } if (operation === OPERATIONS.COPY) { from.removeSelf(); } else { from.move(ogParent); from.data.status = undefined; } var message; if (xhr.status !== 500 && xhr.responseJSON && (xhr.responseJSON.message || xhr.responseJSON.message_long)) { message = xhr.responseJSON.message || xhr.responseJSON.message_long; } else if (xhr.status === 503) { message = textStatus; } else { message = 'Please refresh the page or contact ' + $osf.osfSupportLink() + ' if the problem persists.'; } $osf.growl(operation.verb + ' failed.', message); Raven.captureMessage('Failed to move or copy file', { extra: { xhr: xhr, requestData: moveSpec } }); if (notRenameOp) { addFileStatus(tb, from, false, '', '', conflict); } orderFolder.call(tb, from.parent()); }).always(function(){ from.inProgress = false; if (notRenameOp && (typeof inConflictsQueue !== 'undefined' || syncMoves)) { doSyncMove(tb, to.data.provider); } }); } /** * Find out what the upload URL is for each item * Because we use add ons each item will have something different. This needs to be in the json data. * @param {Object} item A Treebeard _item object. Node information is inside item.data * @this Treebeard.controller * @returns {String} Returns the url string from data or resolved through add on settings. * @private */ function _fangornResolveUploadUrl(item, file) { // WB v1 update syntax is PUT <file_path>?kind=file // WB v1 upload syntax is PUT <parent_path>/?kind=file&name=<filename> // If upload target file name already exists don't pass file.name. WB v1 rejects updates that // include a filename. var configOption = resolveconfigOption.call(this, item, 'uploadUrl', [item, file]); // jshint ignore:line if (configOption) { return configOption; } var updateUrl; $.each(item.children, function( index, value ) { if (file.name === value.data.name) { updateUrl = waterbutler.buildTreeBeardUpload(value); return false; } }); return updateUrl || waterbutler.buildTreeBeardUpload(item, {name: file.name}); } /** * Event to fire when mouse is hovering over row. Currently used for hover effect. * @param {Object} item A Treebeard _item object. Node information is inside item.data * @param event The mouseover event from the browser * @this Treebeard.controller * @private */ function _fangornMouseOverRow(item, event) { $('.fg-hover-hide').hide(); $(event.target).closest('.tb-row').find('.fg-hover-hide').show(); } /** * Runs when dropzone uploadprogress is running, used for updating upload progress in view and models. * @param {Object} treebeard The treebeard instance currently being run, check Treebeard API * @param {Object} file File object that dropzone passes * @param {Number} progress Progress number between 0 and 100 * @this Dropzone * @private */ function _fangornUploadProgress(treebeard, file, progress) { var parent = file.treebeardParent; progress = Math.ceil(progress); for(var i = 0; i < parent.children.length; i++) { if (parent.children[i].data.tmpID !== file.tmpID) continue; if (parent.children[i].data.progress !== progress) { parent.children[i].data.progress = progress; m.redraw(); } return; } } /** * Runs when dropzone sending method is running, used for updating the view while file is being sent. * @param {Object} treebeard The treebeard instance currently being run, check Treebeard API * @param {Object} file File object that dropzone passes * @param xhr xhr information being sent * @param formData Dropzone's formdata information * @this Dropzone * @returns {*|null} Return isn't really used here by anything else. * @private */ function _fangornSending(treebeard, file, xhr, formData) { treebeard.options.uploadInProgress = true; var parent = file.treebeardParent || treebeard.dropzoneItemCache; xhr = $osf.setXHRAuthorization(xhr); var _send = xhr.send; xhr.send = function() { _send.call(xhr, file); }; var configOption = resolveconfigOption.call(treebeard, parent, 'uploadSending', [file, xhr, formData]); return configOption || null; } /** * Runs when Dropzone's addedfile hook is run. * @param {Object} treebeard The treebeard instance currently being run, check Treebeard API * @param {Object} file File object that dropzone passes * @this Dropzone * @returns {*|null} * @private */ function _fangornAddedFile(treebeard, file) { var item = file.treebeardParent; if (!_fangornCanDrop(treebeard, item)) { return; } if (SYNC_UPLOAD_ADDONS.indexOf(item.data.provider) !== -1) { this.syncFileCache = this.syncFileCache || {}; this.syncFileCache[item.data.provider] = this.syncFileCache[item.data.provider] || []; var files = this.getActiveFiles().filter(function(f) {return f.isSync;}); if (files.length > 0) { this.syncFileCache[item.data.provider].push(file); this.files.splice(this.files.indexOf(files), 1); } file.isSync = true; } var configOption = resolveconfigOption.call(treebeard, item, 'uploadAdd', [file, item]); var tmpID = tempCounter++; file.tmpID = tmpID; file.url = _fangornResolveUploadUrl(item, file); file.method = _fangornUploadMethod(item); var blankItem = { // create a blank item that will refill when upload is finished. name: file.name, kind: 'file', provider: item.data.provider, children: [], permissions: { view: false, edit: false }, tmpID: tmpID, progress: 0, uploadState : m.prop('uploading'), }; var newitem = treebeard.createItem(blankItem, item.id); return configOption || null; } function _fangornCanDrop(treebeard, item) { var canDrop = resolveconfigOption.call(treebeard, item, 'canDrop', [item]); if (canDrop === null) { canDrop = item.data.provider && item.kind === 'folder' && item.data.permissions.edit; } return canDrop; } /** * Runs when Dropzone's dragover event hook is run. * @param {Object} treebeard The treebeard instance currently being run, check Treebeard API * @param event DOM event object * @this Dropzone * @private */ function _fangornDragOver(treebeard, event) { var dropzoneHoverClass = 'fangorn-dz-hover', closestTarget = $(event.target).closest('.tb-row'), itemID = parseInt(closestTarget.attr('data-id')), item = treebeard.find(itemID); treebeard.select('.tb-row').removeClass(dropzoneHoverClass).removeClass(treebeard.options.hoverClass); if (item !== undefined) { if (_fangornCanDrop(treebeard, item)) { closestTarget.addClass(dropzoneHoverClass); } } } /** * Runs when Dropzone's drop event hook is run. * @param {Object} treebeard The treebeard instance currently being run, check Treebeard API * @param event DOM event object * @this Dropzone * @private */ function _fangornDropzoneDrop(treebeard, event) { var dropzoneHoverClass = 'fangorn-dz-hover'; treebeard.select('.tb-row').removeClass(dropzoneHoverClass); } /** * Runs when Dropzone's complete hook is run after upload is completed. * @param {Object} treebeard The treebeard instance currently being run, check Treebeard API * @param {Object} file File object that dropzone passes * @this Dropzone * @private */ function _fangornComplete(treebeard, file) { var item = file.treebeardParent; resolveconfigOption.call(treebeard, item, 'onUploadComplete', [item]); orderFolder.call(treebeard, item); if (file.isSync) { if (this.syncFileCache[item.data.provider].length > 0) { var nextFile = this.syncFileCache[item.data.provider].pop(); this.files.push(nextFile); this.processFile(nextFile); } } } /** * Runs when Dropzone's success hook is run. * @param {Object} treebeard The treebeard instance currently being run, check Treebeard API * @param {Object} file File object that dropzone passes * @param {Object} response JSON response from the server * @this Dropzone * @private */ function _fangornDropzoneSuccess(treebeard, file, response) { treebeard.options.uploadInProgress = false; var parent = file.treebeardParent, item, revisedItem, child; for (var i = 0; i < parent.children.length; i++) { child = parent.children[i]; if (!child.data.tmpID){ continue; } if (child.data.tmpID === file.tmpID) { item = child; } } // RESPONSES // OSF : Object with actionTake : "file_added" // DROPBOX : Object; addon : 'dropbox' // S3 : Nothing // GITHUB : Object; addon : 'github' // Dataverse : Object, actionTaken : file_uploaded revisedItem = resolveconfigOption.call(treebeard, item.parent(), 'uploadSuccess', [file, item, response]); if (!revisedItem && response) { item.data = treebeard.options.lazyLoadPreprocess.call(this, response).data; inheritFromParent(item, item.parent()); } if (item.data.tmpID) { item.data.tmpID = null; item.data.uploadState('completed'); } // Remove duplicates if file was updated var status = file.xhr.status; if (status === 200) { parent.children.forEach(function(child) { if (child.data.name === item.data.name && child.id !== item.id) { child.removeSelf(); } }); } var url = item.data.nodeUrl + 'files/' + item.data.provider + item.data.path; addFileStatus(treebeard, file, true, '', url); if (item.data.provider === 'dataverse') { item.parent().data.datasetDraftModified = true; } treebeard.redraw(); } function _fangornDropzoneRemovedFile(treebeard, file, message, xhr) { addFileStatus(treebeard, file, false, 'Upload Canceled.', ''); } /** * runs when Dropzone's error hook runs. Notifies user with error. * @param {Object} treebeard The treebeard instance currently being run, check Treebeard API * @param {Object} file File object that dropzone passes * @param message Error message returned * @private */ var DEFAULT_ERROR_MESSAGE = 'Could not upload file. The file may be invalid ' + 'or the file folder has been deleted.'; function _fangornDropzoneError(treebeard, file, message, xhr) { var tb = treebeard; var msgText; // Unpatched Dropzone silently does nothing when folders are uploaded on Windows IE // Patched Dropzone.prototype.drop to emit error with file = 'None' to catch the error if (file === 'None'){ $osf.growl('Error', 'Cannot upload folders.'); return; } if (file.isDirectory) { msgText = 'Cannot upload folders.'; } else if (xhr && xhr.status === 507) { msgText = 'Cannot upload file due to insufficient storage.'; } else if (xhr && xhr.status === 0) { // There is no way for Safari to know if it was a folder at present msgText = ''; if ($osf.isSafari()) { msgText += 'Could not upload file. Possible reasons: <br>'; msgText += '1. Cannot upload folders. <br>2. '; } msgText += 'Unable to reach the provider, please try again later. '; msgText += 'If the problem persists, please contact ' + $osf.osfSupportEmail() + '.'; } else { //Osfstorage and most providers store message in {Object}message.{string}message, //but some, like Dataverse, have it in {string} message. if (message){ msgText = message.message ? message.message : (typeof message === 'string' ? message : DEFAULT_ERROR_MESSAGE); } else { msgText = DEFAULT_ERROR_MESSAGE; } } if (typeof file.isDirectory === 'undefined') { var parent = file.treebeardParent || treebeardParent.dropzoneItemCache; // jshint ignore:line var item; var child; var destroyItem = false; for (var i = 0; i < parent.children.length; i++) { child = parent.children[i]; if (!child.data.tmpID) { continue; } if (child.data.tmpID === file.tmpID) { child.removeSelf(); } } } console.error(file); treebeard.options.uploadInProgress = false; if (msgText !== 'Upload canceled.') { addFileStatus(treebeard, file, false, msgText, ''); } treebeard.dropzone.options.queuecomplete(file); } /** * Click event for when upload buttonin Action Column, it essentially runs the hiddenFileInput.click * @param event DOM event object for click * @param {Object} item A Treebeard _item object for the row involved. Node information is inside item.data * @param {Object} col Information pertinent to that column where this upload event is run from * @private */ function _uploadEvent(event, item, col) { var self = this; // jshint ignore:line try { event.stopPropagation(); } catch (e) { window.event.cancelBubble = true; } self.dropzoneItemCache = item; self.dropzone.hiddenFileInput.click(); if (!item.open) { self.updateFolder(null, item); } } /** * Download button in Action Column * @param event DOM event object for click * @param {Object} item A Treebeard _item object for the row involved. Node information is inside item.data * @param {Object} col Information pertinent to that column where this upload event is run from * @private */ function _downloadEvent (event, item, col) { try { event.stopPropagation(); } catch (e) { window.event.cancelBubble = true; } window.location = waterbutler.buildTreeBeardDownload(item); } function _downloadZipEvent (event, item, col) { try { event.stopPropagation(); } catch (e) { window.event.cancelBubble = true; } window.location = waterbutler.buildTreeBeardDownloadZip(item); } function _createFolder(event, dismissCallback, helpText) { var tb = this; helpText(''); var val = $.trim(tb.select('#createFolderInput').val()); var parent = tb.multiselected()[0]; if (!parent.open) { tb.updateFolder(null, parent); } if (val.length < 1) { helpText('Please enter a folder name.'); return; } if (val.indexOf('/') !== -1) { helpText('Folder name contains illegal characters.'); return; } var extra = {}; var path = parent.data.path || '/'; var options = {name: val, kind: 'folder'}; if ((parent.data.provider === 'github') || (parent.data.provider === 'gitlab')) { extra.branch = parent.data.branch; options.branch = parent.data.branch; } m.request({ method: 'PUT', background: true, config: $osf.setXHRAuthorization, url: waterbutler.buildCreateFolderUrl(path, parent.data.provider, parent.data.nodeId, options, extra) }).then(function(item) { item = tb.options.lazyLoadPreprocess.call(this, item).data; inheritFromParent({data: item}, parent, ['branch']); item = tb.createItem(item, parent.id); orderFolder.call(tb, parent); item.notify.update('New folder created!', 'success', undefined, 1000); if(dismissCallback) { dismissCallback(); } }, function(data) { if (data && data.code === 409) { helpText(data.message); m.redraw(); } else { helpText('Folder creation failed.'); } }); } /** * Deletes the item, only appears for items * @param event DOM event object for click * @param {Object} item A Treebeard _item object for the row involved. Node information is inside item.data * @param {Object} col Information pertinent to that column where this upload event is run from * @private */ function _removeEvent (event, items, col) { var tb = this; function cancelDelete() { tb.modal.dismiss(); } function runDelete(item) { tb.select('.modal-footer .btn-danger').html('<i> Deleting...</i>').removeClass('btn-danger').addClass('btn-default disabled'); // delete from server, if successful delete from view var url = resolveconfigOption.call(this, item, 'resolveDeleteUrl', [item]); url = url || waterbutler.buildTreeBeardDelete(item); $.ajax({ url: url, type: 'DELETE', beforeSend: $osf.setXHRAuthorization }) .done(function(data) { // delete view tb.deleteNode(item.parentID, item.id); tb.modal.dismiss(); tb.clearMultiselect(); if (item.data.provider === 'dataverse') { item.parent().data.datasetDraftModified = true; } }) .fail(function(data){ tb.modal.dismiss(); tb.clearMultiselect(); if (data.responseJSON.message_long.indexOf('preprint') !== -1) { $osf.growl('Delete failed', data.responseJSON.message_long); } item.notify.update('Delete failed.', 'danger', undefined, 3000); }); } function runDeleteMultiple(items){ items.forEach(function(item){ runDelete(item); }); } function doDelete() { var folder = items[0]; if (folder.data.permissions.edit) { var mithrilContent = m('div', [ m('p.text-danger', 'This folder and ALL its contents will be deleted. This action is irreversible.') ]); var mithrilButtons = m('div', [ m('span.btn.btn-default', { onclick : function() { cancelDelete.call(tb); } }, 'Cancel'), m('span.btn.btn-danger', { onclick : function() { runDelete(folder); } }, 'Delete') ]); tb.modal.update(mithrilContent, mithrilButtons, m('h3.break-word.modal-title', 'Delete "' + folder.data.name+ '"?')); } else { folder.notify.update('You don\'t have permission to delete this file.', 'info', undefined, 3000); } } // If there is only one item being deleted, don't complicate the issue: if(items.length === 1) { var detail = 'This action is irreversible.'; if(items[0].kind !== 'folder'){ var mithrilContentSingle = m('div', [ m('p', detail) ]); var mithrilButtonsSingle = m('div', [ m('span.btn.btn-default', { onclick : function() { cancelDelete(); } }, 'Cancel'), m('span.btn.btn-danger', { onclick : function() { runDelete(items[0]); } }, 'Delete') ]); // This is already being checked before this step but will keep this edit permission check if(items[0].data.permissions.edit){ tb.modal.update(mithrilContentSingle, mithrilButtonsSingle, m('h3.break-word.modal-title', 'Delete "' + items[0].data.name + '"?')); } } if(items[0].kind === 'folder') { if (!items[0].open) { tb.updateFolder(null, items[0], doDelete); } else { doDelete(); } } } else { // Check if all items can be deleted var canDelete = true; var deleteList = []; var noDeleteList = []; var deleteMessage = [m('p', 'This action is irreversible.')]; var mithrilContentMultiple; var mithrilButtonsMultiple; items.forEach(function(item, index, arr){ if(!item.data.permissions.edit){ canDelete = false; noDeleteList.push(item); } else { deleteList.push(item); } if(item.kind === 'folder' && deleteMessage.length === 1) { deleteMessage.push(m('p.text-danger', 'Some of the selected items are folders. This will delete the folder(s) and ALL of their content.')); } }); // If all items can be deleted if(canDelete){ mithrilContentMultiple = m('div', [ deleteMessage, deleteList.map(function(n){ if(n.kind === 'folder'){ return m('.fangorn-canDelete.text-success.break-word', [ m('i.fa.fa-folder'), m('b', ' ' + n.data.name) ]); } return m('.fangorn-canDelete.text-success.break-word', n.data.name); }) ]); mithrilButtonsMultiple = m('div', [ m('span.btn.btn-default', { onclick : function() { tb.modal.dismiss(); } }, 'Cancel'), m('span.btn.btn-danger', { onclick : function() { runDeleteMultiple.call(tb, deleteList); } }, 'Delete All') ]); } else { mithrilContentMultiple = m('div', [ m('p', 'Some of these files can\'t be deleted but you can delete the ones highlighted with green. This action is irreversible.'), deleteList.map(function(n){ if(n.kind === 'folder'){ return m('.fangorn-canDelete.text-success.break-word', [ m('i.fa.fa-folder'), m('b', ' ' + n.data.name) ]); } return m('.fangorn-canDelete.text-success.break-word', n.data.name); }), noDeleteList.map(function(n){ return m('.fangorn-noDelete.text-warning.break-word', n.data.name); }) ]); mithrilButtonsMultiple = m('div', [ m('span.btn.btn-default', { 'class' : 'text-default', onclick : function() { tb.modal.dismiss(); } }, 'Cancel'), m('span.btn.btn-danger', { 'class' : 'text-danger', onclick : function() { runDeleteMultiple.call(tb, deleteList); } }, 'Delete Some') ]); } tb.modal.update(mithrilContentMultiple, mithrilButtonsMultiple, m('h3.break-word.modal-title', 'Delete multiple files?')); } } function doCheckout(item, checkout, showError) { return $osf.ajaxJSON( 'PUT', window.contextVars.apiV2Prefix + 'files' + item.data.path + '/', { isCors: true, data: { data: { id: item.data.path.replace('/', ''), type: 'files', attributes: { checkout: checkout } } } } ).done(function(xhr) { if (showError) { window.location.reload(); } }).fail(function(xhr) { if (showError) { $osf.growl('Error', 'Unable to check out file. This is most likely due to the file being already checked-out' + ' by another user.'); } }); } /** * Resolves lazy load url for fetching children * @param {Object} item A Treebeard _item object for the row involved. Node information is inside item.data * @this Treebeard.controller * @returns {String|Boolean} Returns the fetch URL in string or false if there is no url. * @private */ function _fangornResolveLazyLoad(item) { item.connected = true; var configOption = resolveconfigOption.call(this, item, 'lazyload', [item]); if (configOption) { return configOption; } if (item.data.provider === undefined) { return false; } return waterbutler.buildTreeBeardMetadata(item); } /** * Handles errors in lazyload fetching of items, usually link is wrong * @param {Object} item A Treebeard _item object for the row involved. Node information is inside item.data * @this Treebeard.controller * @private */ function _fangornLazyLoadError (item) { item.connected = false; var configOption = resolveconfigOption.call(this, item, 'lazyLoadError', [item]); } /** * Applies the positionining and initialization of tooltips for file names * @private */ function reapplyTooltips () { $('[data-toggle="tooltip"]').tooltip({container: 'body', 'animation' : false}); } /** * Called when new object data has arrived to be loaded. * @param {Object} tree A Treebeard _item object for the row involved. Node information is inside item.data * @this Treebeard.controller * @private */ function _fangornLazyLoadOnLoad (tree, event) { tree.children.forEach(function(item) { inheritFromParent(item, tree); }); resolveconfigOption.call(this, tree, 'lazyLoadOnLoad', [tree, event]); reapplyTooltips(); if (tree.depth > 1) { orderFolder.call(this, tree); } } /** * Order contents of a folder without an entire sorting of all the table * @param {Object} tree A Treebeard _item object for the row involved. Node information is inside item.data * @this Treebeard.controller * @private */ function orderFolder(tree) { var sortColumn; var sortDirection; if(typeof this.isSorted !== 'undefined' && typeof this.isSorted[0] !== 'undefined'){ sortColumn = Object.keys(this.isSorted)[0]; // default to whatever column is first for (var column in this.isSorted){ sortColumn = this.isSorted[column].asc || this.isSorted[column].desc ? column : sortColumn; } sortDirection = this.isSorted[sortColumn].desc ? 'desc' : 'asc'; // default to ascending }else{ sortColumn = 0; sortDirection = 'asc'; } tree.sortChildren(this, sortDirection, 'text', sortColumn, 1); this.redraw(); } /** * Changes the upload method based on what the add ons need. Default is POST, S3 needs PUT * @param {Object} item A Treebeard _item object for the row involved. Node information is inside item.data * @this Treebeard.controller * @returns {string} Must return string that is a legitimate method like POST, PUT * @private */ function _fangornUploadMethod(item) { var configOption = resolveconfigOption.call(this, item, 'uploadMethod', [item]); return configOption || 'PUT'; } function gotoFileEvent (item, toUrl) { if(toUrl === undefined) toUrl = '/'; var tb = this; var redir = new URI(item.data.nodeUrl); redir.segment('files').segment(item.data.provider).segmentCoded(item.data.path.substring(1)); var fileurl = redir.toString() + toUrl; // construct view only link into file url as it gets removed from url params in IE if ($osf.isIE()) { var viewOnly = $osf.urlParams().view_only; if (viewOnly) { if (fileurl.indexOf('?') !== -1) { fileurl += '&view_only=' + viewOnly; }else { fileurl += '?view_only=' + viewOnly; } } } if (COMMAND_KEYS.indexOf(tb.pressedKey) !== -1) { window.open(fileurl, '_blank'); } else { window.open(fileurl, '_self'); } } /** * Defines the contents of the title column (does not include the toggle and folder sections * @param {Object} item A Treebeard _item object for the row involved. Node information is inside item.data * @param {Object} col Options for this particulat column * @this Treebeard.controller * @returns {Array} Returns an array of mithril template objects using m() * @private */ function _fangornTitleColumnHelper(tb, item, col, nameTitle, toUrl, classNameOption){ if (typeof tb.options.links === 'undefined') { tb.options.links = true; } // as opposed to undefined, avoids unnecessary setting of this value if (item.data.isAddonRoot && item.connected === false) { return _connectCheckTemplate.call(this, item); } if (item.kind === 'file' && item.data.permissions.view) { var attrs = {}; if (tb.options.links) { attrs = { className: classNameOption, onclick: function(event) { event.stopImmediatePropagation(); gotoFileEvent.call(tb, item, toUrl); } }; } return m('span', attrs, nameTitle); } if ((item.data.nodeType === 'project' || item.data.nodeType ==='component') && item.data.permissions.view) { return m('a.' + classNameOption, {href: '/' + item.data.nodeID.toString() + toUrl}, nameTitle); } return m('span', nameTitle); } function _fangornTitleColumn(item, col) { var tb = this; return _fangornTitleColumnHelper(tb, item, col, item.data.name, '/', 'fg-file-links'); } function _fangornVersionColumn(item, col) { var tb = this; if (item.kind !== 'folder' && item.data.provider === 'osfstorage'){ return _fangornTitleColumnHelper(tb, item, col, String(item.data.extra.version), '/?show=revision', 'fg-version-links'); } return; } /** * Defines the contents of the modified column (does not include the toggle and folder sections * @param {Object} item A Treebeard _item object for the row involved. Node information is inside item.data * @param {Object} col Options for this particular column * @this Treebeard.controller * @returns {Array} Returns an array of mithril template objects using m() * @private */ function _fangornModifiedColumn(item, col) { var tb = this; if (item.data.isAddonRoot && item.connected === false) { // as opposed to undefined, avoids unnecessary setting of this value return _connectCheckTemplate.call(this, item); } if (item.kind === 'file' && item.data.permissions.view && item.data.modified_utc) { item.data.modified = new moment(moment.utc(item.data.modified_utc,'YYYY-MM-DD hh:mm A', 'en').toDate()).format('YYYY-MM-DD hh:mm A'); return m( 'span', item.data.modified ); } return m('span', ''); } /** * Returns a reusable template for column titles when there is no connection * @param {Object} item A Treebeard _item object for the row involved. Node information is inside item.data * @this Treebeard.controller * @private */ function _connectCheckTemplate(item){ var tb = this; return m('span.text-danger', [ m('span', item.data.name), m('em', ' couldn\'t load.' ), m('button.btn.btn-xs.btn-default.m-l-xs', { onclick : function(e){ e.stopImmediatePropagation(); if (tb.options.togglecheck.call(tb, item)) { var index = tb.returnIndex(item.id); tb.toggleFolder(index, e); } } }, [m('i.fa.fa-refresh'), ' Retry']) ]); } /** * Parent function for resolving rows, all columns are sub methods within this function * @param {Object} item A Treebeard _item object for the row involved. Node information is inside item.data * @this Treebeard.controller * @returns {Array} An array of columns that get iterated through in Treebeard * @private */ function _fangornResolveRows(item) { var tb = this; var defaultColumns = []; var configOption; item.css = ''; if(tb.isMultiselected(item.id)){ item.css = 'fangorn-selected'; } if(item.data.permissions && !item.data.permissions.view){ item.css += ' tb-private-row'; } if(item.data.uploadState && (item.data.uploadState() === 'pending' || item.data.uploadState() === 'uploading')){ return uploadRowTemplate.call(tb, item); } if (item.data.status) { return [{ data : '', // Data field name css : 't-a-c', custom : function(){ return m('span.text-muted', [STATE_MAP[item.data.status].display, item.data.name, '...']); } }, { data : '', // Data field name custom : function(){ return '';} }]; } if (item.parentID) { item.data.permissions = item.data.permissions || item.parent().data.permissions; if (item.data.kind === 'folder') { item.data.accept = item.data.accept || item.parent().data.accept; } } defaultColumns.push({ data : 'name', // Data field name folderIcons : true, filter : true, custom : _fangornTitleColumn }); defaultColumns.push({ data : 'size', // Data field name sortInclude : false, filter : false, custom : function() {return item.data.size ? $osf.humanFileSize(item.data.size, true) : '';} }); defaultColumns.push({ data: 'version', filter: false, sortInclude : false, custom: _fangornVersionColumn }); if (item.data.provider === 'osfstorage') { defaultColumns.push({ data : 'downloads', sortInclude : false, filter : false, custom: function() { return lodashGet(item, 'data.extra.downloads', '').toString(); } }); } else { defaultColumns.push({ data : 'downloads', sortInclude : false, filter : false, custom : function() { return m(''); } }); } defaultColumns.push({ data : 'modified', // Data field name filter : false, custom : _fangornModifiedColumn }); configOption = resolveconfigOption.call(this, item, 'resolveRows', [item]); return configOption || defaultColumns; } /** * Defines Column Titles separately since content and css may be different, allows more flexibility * @returns {Array} an Array of column information that gets templated inside Treebeard * @this Treebeard.controller * @private */ function _fangornColumnTitles () { var columns = []; columns.push({ title : 'Name', width : '54%', sort : true, sortType : 'text' }, { title : 'Size', width : '8%', sort : false }, { title : 'Version', width : '10%', sort : false }, { title : 'Downloads', width : '8%', sort : false }, { title : 'Modified', width : '20%', sort : true, sortType : 'text' }); return columns; } /** * When fangorn loads the top level needs to be open so we load the children on load * @this Treebeard.controller * @private */ function _loadTopLevelChildren() { var i; for (i = 0; i < this.treeData.children.length; i++) { this.updateFolder(null, this.treeData.children[i]); } } /** * Expand major addons on load * @param {Object} item A Treebeard _item object for the row involved. Node information is inside item.data * @this Treebeard.controller * @private */ var NO_AUTO_EXPAND_PROJECTS = ['ezcuj', 'ecmz4', 'w4wvg', 'sn64d']; function expandStateLoad(item) { var tb = this, icon = $('.tb-row[data-id="' + item.id + '"]').find('.tb-toggle-icon'), toggleIcon = tbOptions.resolveToggle(item), addonList = [], i; if (item.children.length > 0 && item.depth === 1) { // NOTE: On the RPP and a few select projects *only*: Load the top-level project's OSF Storage // but do NOT lazy-load children in order to save hundreds of requests. // TODO: We might want to do this for every project, but that's TBD. // /sloria if (window.contextVars && window.contextVars.node && NO_AUTO_EXPAND_PROJECTS.indexOf(window.contextVars.node.id) > -1) { var osfsItems = item.children.filter(function(child) { return child.data.isAddonRoot && child.data.provider === 'osfstorage'; }); if (osfsItems.length) { var osfsItem = osfsItems[0]; tb.updateFolder(null, osfsItem); } } else { for (i = 0; i < item.children.length; i++) { tb.updateFolder(null, item.children[i]); } } } if (item.children.length > 0 && item.depth === 2) { for (i = 0; i < item.children.length; i++) { if (item.children[i].data.isAddonRoot || item.children[i].data.addonFullName === 'OSF Storage' ) { tb.updateFolder(null, item.children[i]); } } } if (item.depth > 2 && !item.data.isAddonRoot && !item.data.type && item.children.length === 0 && item.open) { // Displays loading indicator until request below completes // Copied from toggleFolder() in Treebeard if (icon.get(0)) { m.render(icon.get(0), tbOptions.resolveRefreshIcon()); } $osf.ajaxJSON( 'GET', '/api/v1/project/' + item.data.nodeID + '/files/grid/' ).done(function(response) { var data = response.data[0].children; tb.updateFolder(data, item); tb.redraw(); }).fail(function(xhr) { item.notify.update('Unable to retrieve components.', 'danger', undefined, 3000); item.open = false; Raven.captureMessage('Unable to retrieve components for node ' + item.data.nodeID, { extra: { xhr: xhr } }); }); } $('.fangorn-toolbar-icon').tooltip(); } /** * @param tree A Treebeard _item object for the row * @param nodeID Current node._id * @param file window.contextVars.file object */ function setCurrentFileID(tree, nodeID, file) { var tb = this; if(!file){ return; } var child; var i; if (file.provider === 'figshare') { for (i = 0; i < tree.children.length; i++) { child = tree.children[i]; if (nodeID === child.data.nodeId && child.data.provider === file.provider && child.data.path === file.path) { tb.currentFileID = child.id; } } } else if (file.provider === 'dataverse') { // Only highlight file in correct dataset version, since paths persist across versions for (i = 0; i < tree.children.length; i++) { child = tree.children[i]; var urlParams = $osf.urlParams(); if (nodeID === child.data.nodeId && child.data.provider === file.provider && child.data.path === file.path && child.data.extra.datasetVersion === urlParams.version) { tb.currentFileID = child.id; } } } else if (tb.fangornFolderIndex !== undefined && tb.fangornFolderArray !== undefined && tb.fangornFolderIndex < tb.fangornFolderArray.length) { for (var j = 0; j < tree.children.length; j++) { child = tree.children[j]; if (nodeID === child.data.nodeId && child.data.provider === file.provider && child.data.name === tb.fangornFolderArray[tb.fangornFolderIndex]) { tb.fangornFolderIndex++; if (child.data.kind === 'folder') { tb.updateFolder(null, child); tree = child; } else { tb.currentFileID = child.id; } } } } } /** * Scroll to the Treebeard item corresponding to the given ID * @param fileID id of a Treebeard _item object */ function scrollToFile(fileID) { var tb = this; if (fileID !== undefined) { var index = tb.returnIndex(fileID); var visibleIndex = tb.visibleIndexes.indexOf(index); var scrollTo = visibleIndex * tb.options.rowHeight; this.select('#tb-tbody').scrollTop(scrollTo); } } function _renameEvent () { var tb = this; var item = tb.multiselected()[0]; var val = $.trim($('#renameInput').val()); var folder = item.parent(); //TODO Error message? if (val === item.name) { return; } checkConflictsRename(tb, item, val, doItemOp.bind(tb, OPERATIONS.RENAME, folder, item, val)); tb.toolbarMode(toolbarModes.DEFAULT); } var toolbarModes = { 'DEFAULT' : 'bar', 'FILTER' : 'filter', 'ADDFOLDER' : 'addFolder', 'RENAME' : 'rename', 'ADDPROJECT' : 'addProject' }; // A fangorn-styled button; addons can reuse this var FGButton = { view: function(ctrl, args, children) { var extraCSS = args.className || ''; var tooltipText = args.tooltip || ''; var iconCSS = args.icon || ''; var onclick = args.onclick || noop; var opts = { className: 'fangorn-toolbar-icon ' + extraCSS, onclick: onclick }; // Add tooltip if applicable if (args.tooltip) { opts['data-toggle'] = 'tooltip'; opts['data-placement'] = 'bottom'; opts.title = args.tooltip; } var childrenElements = []; childrenElements.push(m('i', {className: iconCSS})); if(children) { childrenElements.push(m('span', children)); } return m('div', opts, childrenElements); } }; var FGInput = { view : function(ctrl, args, helpText) { var extraCSS = args.className || ''; var tooltipText = args.tooltip || ''; var placeholder = args.placeholder || ''; var id = args.id || ''; var helpTextId = args.helpTextId || ''; var oninput = args.oninput || noop; var onkeypress = args.onkeypress || noop; return m('span', [ m('input', { 'id' : id, className: 'pull-right form-control' + extraCSS, oninput: oninput, onkeypress: onkeypress, 'value': args.value || '', 'data-toggle': tooltipText ? 'tooltip' : '', 'title': tooltipText, 'data-placement' : 'bottom', 'placeholder' : placeholder }), m('.text-danger', { 'id' : helpTextId }, helpText) ]); } }; var FGDropdown = { view : function(ctrl, args, children) { var extraCSS = args.className || ''; var tooltipText = args.tooltip || ''; var id = args.id || ''; var name = args.name || ''; var label = args.label || ''; var onchange = args.onchange || noop; return m('span.fangorn-dropdown', { className: extraCSS }, [ m('span.hidden-xs', label), m('select.no-border', { 'name' : name, 'id' : id, onchange: onchange, 'data-toggle': tooltipText ? 'tooltip' : '', 'title': tooltipText, 'data-placement' : 'bottom' }, children) ]); } }; var FGItemButtons = { view : function(ctrl, args, children) { var tb = args.treebeard; var item = args.item; var rowButtons = []; var mode = args.mode; var preprintPath = getPreprintPath(window.contextVars.node.preprintFileId); if (tb.options.placement !== 'fileview') { if (window.File && window.FileReader && item.kind === 'folder' && item.data.provider && item.data.permissions && item.data.permissions.edit) { rowButtons.push( m.component(FGButton, { onclick: function(event) {_uploadEvent.call(tb, event, item); }, icon: 'fa fa-upload', className : 'text-success' }, 'Upload'), m.component(FGButton, { onclick: function () { mode(toolbarModes.ADDFOLDER); }, icon: 'fa fa-plus', className: 'text-success' }, 'Create Folder')); if (item.data.path) { if (preprintPath && folderContainsPreprint(item, preprintPath)) { rowButtons.push( m.component(FGButton, { icon: 'fa fa-trash', tooltip: 'This folder contains a Preprint. You cannot delete Preprints, but you can upload a new version.', className: 'tb-disabled' }, 'Delete Folder')); reapplyTooltips(); } else { rowButtons.push( m.component(FGButton, { onclick: function(event) {_removeEvent.call(tb, event, [item]); }, icon: 'fa fa-trash', className : 'text-danger' }, 'Delete Folder')); } } } if (item.kind === 'file') { rowButtons.push( m.component(FGButton, { onclick: function (event) { _downloadEvent.call(tb, event, item); }, icon: 'fa fa-download', className: 'text-primary' }, 'Download') ); if (item.data.permissions && item.data.permissions.view) { rowButtons.push( m.component(FGButton, { onclick: function (event) { gotoFileEvent.call(tb, item, '/'); }, icon: 'fa fa-file-o', className: 'text-info' }, 'View')); } if (item.data.permissions && item.data.permissions.edit) { if (item.data.provider === 'osfstorage') { if (!item.data.extra.checkout){ if (preprintPath && preprintPath === item.data.path) { // Block delete for preprint files rowButtons.push( m.component(FGButton, { icon: 'fa fa-trash', tooltip: 'This file is a Preprint. You cannot delete Preprints, but you can upload a new version.', className: 'tb-disabled' }, 'Delete')); // Tooltips don't seem to auto reapply, this forces them. reapplyTooltips(); } else { rowButtons.push( m.component(FGButton, { onclick: function(event) { _removeEvent.call(tb, event, [item]); }, icon: 'fa fa-trash', className: 'text-danger' }, 'Delete')); } rowButtons.push( m.component(FGButton, { onclick: function(event) { tb.modal.update(m('', [ m('p', 'This would mean ' + 'other contributors cannot edit, delete or upload new versions of this file ' + 'as long as it is checked-out. You can check it back in at anytime.') ]), m('', [ m('a.btn.btn-default', {onclick: function() {tb.modal.dismiss();}}, 'Cancel'), //jshint ignore:line m('a.btn.btn-warning', {onclick: function() { doCheckout(item, window.contextVars.currentUser.id, true); }}, 'Check out file') ]), m('h3.break-word.modal-title', 'Confirm file check-out?')); }, icon: 'fa fa-sign-out', className : 'text-warning' }, 'Check out file')); } else if (item.data.extra.checkout && item.data.extra.checkout._id === window.contextVars.currentUser.id) { rowButtons.push( m.component(FGButton, { onclick: function(event) { doCheckout(item, null, true); }, icon: 'fa fa-sign-in', className : 'text-warning' }, 'Check in file') ); } } else { rowButtons.push( m.component(FGButton, { onclick: function (event) { _removeEvent.call(tb, event, [item]); }, icon: 'fa fa-trash', className: 'text-danger' }, 'Delete')); } } if(storageAddons[item.data.provider].externalView) { var providerFullName = storageAddons[item.data.provider].fullName; rowButtons.push( m('a.text-info.fangorn-toolbar-icon', {href: item.data.extra.webView}, [ m('i.fa.fa-external-link'), m('span', 'View on ' + providerFullName) ]) ); } } else if (item.data.provider) { rowButtons.push( m.component(FGButton, { onclick: function (event) { _downloadZipEvent.call(tb, event, item); }, icon: 'fa fa-download', className: 'text-primary' }, 'Download as zip') ); } if (item.data.provider && !item.data.isAddonRoot && item.data.permissions && item.data.permissions.edit && (item.data.provider !== 'osfstorage' || !item.data.extra.checkout)) { rowButtons.push( m.component(FGButton, { onclick: function () { mode(toolbarModes.RENAME); }, icon: 'fa fa-pencil', className: 'text-info' }, 'Rename') ); } return m('span', rowButtons); } } }; var dismissToolbar = function(helpText){ var tb = this; if (tb.toolbarMode() === toolbarModes.FILTER){ tb.resetFilter(); } tb.toolbarMode(toolbarModes.DEFAULT); tb.filterText(''); if(typeof helpText === 'function'){ helpText(''); } m.redraw(); }; var FGToolbar = { controller : function(args) { var self = this; self.tb = args.treebeard; self.tb.toolbarMode = m.prop(toolbarModes.DEFAULT); self.items = args.treebeard.multiselected; self.mode = self.tb.toolbarMode; self.isUploading = args.treebeard.isUploading; self.helpText = m.prop(''); self.dismissToolbar = dismissToolbar.bind(self.tb, self.helpText); self.createFolder = function(event){ _createFolder.call(self.tb, event, self.dismissToolbar, self.helpText); }; self.nameData = m.prop(''); self.renameId = m.prop(''); self.renameData = m.prop(''); }, view : function(ctrl) { var templates = {}; var generalButtons = []; var finalRowButtons = []; var items = ctrl.items(); var item = items[0]; var dismissIcon = m.component(FGButton, { onclick: ctrl.dismissToolbar, icon : 'fa fa-times' }, ''); templates[toolbarModes.FILTER] = [ m('.col-xs-9', [ ctrl.tb.options.filterTemplate.call(ctrl.tb) ]), m('.col-xs-3.tb-buttons-col', m('.fangorn-toolbar.pull-right', [dismissIcon]) ) ]; $('.tb-row').click(function(){ ctrl.helpText(''); }); if (ctrl.tb.toolbarMode() === toolbarModes.DEFAULT) { ctrl.nameData(''); ctrl.renameId(''); } if(typeof item !== 'undefined' && item.id !== ctrl.renameId()){ ctrl.renameData(item.data.name); ctrl.renameId(item.id); } if (ctrl.tb.options.placement !== 'fileview') { templates[toolbarModes.ADDFOLDER] = [ m('.col-xs-9', [ m.component(FGInput, { oninput: m.withAttr('value', ctrl.nameData), onkeypress: function (event) { if (ctrl.tb.pressedKey === ENTER_KEY) { ctrl.createFolder.call(ctrl.tb, event, ctrl.dismissToolbar); } }, id: 'createFolderInput', value: ctrl.nameData(), helpTextId: 'createFolderHelp', placeholder: 'New folder name', }, ctrl.helpText()) ]), m('.col-xs-3.tb-buttons-col', m('.fangorn-toolbar.pull-right', [ m.component(FGButton, { onclick: ctrl.createFolder, icon: 'fa fa-plus', className: 'text-success' }), dismissIcon ] ) ) ]; templates[toolbarModes.RENAME] = [ m('.col-xs-9', m.component(FGInput, { oninput: m.withAttr('value', ctrl.renameData), onkeypress: function (event) { if (ctrl.tb.pressedKey === ENTER_KEY) { _renameEvent.call(ctrl.tb); } }, id: 'renameInput', value: ctrl.renameData(), helpTextId: 'renameHelpText', placeholder: 'Enter name', }, ctrl.helpText()) ), m('.col-xs-3.tb-buttons-col', m('.fangorn-toolbar.pull-right', [ m.component(FGButton, { onclick: function () { _renameEvent.call(ctrl.tb); }, icon: 'fa fa-pencil', className: 'text-info' }), dismissIcon ] ) ) ]; } // Bar mode // Which buttons should show? if(items.length === 1){ var addonButtons = resolveconfigOption.call(ctrl.tb, item, 'itemButtons', [item]); if (addonButtons) { finalRowButtons = m.component(addonButtons, {treebeard : ctrl.tb, item : item }); // jshint ignore:line } else if (ctrl.tb.options.placement !== 'fileview') { finalRowButtons = m.component(FGItemButtons, {treebeard : ctrl.tb, mode : ctrl.mode, item : item }); // jshint ignore:line } } if(ctrl.isUploading() && ctrl.tb.options.placement !== 'fileview') { generalButtons.push( m.component(FGButton, { onclick: function() { cancelAllUploads.call(ctrl.tb); }, icon: 'fa fa-time-circle', className : 'text-danger' }, 'Cancel Pending Uploads') ); } // multiple selection icons // Special cased to not show 'delete multiple' for github or published dataverses if( (items.length > 1) && (ctrl.tb.multiselected()[0].data.provider !== 'github') && (ctrl.tb.multiselected()[0].data.provider !== 'onedrive') && (ctrl.tb.options.placement !== 'fileview') && !( (ctrl.tb.multiselected()[0].data.provider === 'dataverse') && (ctrl.tb.multiselected()[0].parent().data.version === 'latest-published') ) ) { if (showDeleteMultiple(items)) { var preprintPath = getPreprintPath(window.contextVars.node.preprintFileId); if (preprintPath && multiselectContainsPreprint(items, preprintPath)) { generalButtons.push( m.component(FGButton, { icon: 'fa fa-trash', tooltip: 'One of these items is a Preprint or contains a Preprint. You cannot delete Preprints, but you can upload a new version.', className: 'tb-disabled' }, 'Delete Multiple') ); } else { generalButtons.push( m.component(FGButton, { onclick: function(event) { var configOption = resolveconfigOption.call(ctrl.tb, item, 'removeEvent', [event, items]); // jshint ignore:line if(!configOption){ _removeEvent.call(ctrl.tb, null, items); } }, icon: 'fa fa-trash', className : 'text-danger' }, 'Delete Multiple') ); } } } generalButtons.push( m.component(FGButton, { onclick: function(event){ ctrl.mode(toolbarModes.FILTER); }, icon: 'fa fa-search', className : 'text-primary' }, 'Filter')); if (ctrl.tb.options.placement !== 'fileview') { generalButtons.push(m.component(FGButton, { onclick: function(event){ var mithrilContent = m('div', [ m('p', [ m('b', 'Select rows:'), m('span', ' Click on a row (outside the add-on, file, or folder name) to show further actions in the toolbar. Use Command or Shift keys to select multiple files.')]), m('p', [ m('b', 'Open files:'), m('span', ' Click a file name to go to view the file in the OSF.')]), m('p', [ m('b', 'Open files in new tab:'), m('span', ' Press Command (Ctrl in Windows) and click a file name to open it in a new tab.')]), m('p', [ m('b', 'Download as zip:'), m('span', ' Click on the row of an add-on or folder and click the Download as Zip button in the toolbar.'), m('i', ' Not available for all storage add-ons.')]), m('p', [ m('b', 'Copy files:'), m('span', ' Press Option (Alt in Windows) while dragging a file to a new folder or component.'), m('i', ' Only for contributors with write access.')]) ]); var mithrilButtons = m('button', { 'type':'button', 'class' : 'btn btn-default', onclick : function(event) { ctrl.tb.modal.dismiss(); } }, 'Close'); ctrl.tb.modal.update(mithrilContent, mithrilButtons, m('h3.modal-title.break-word', 'How to Use the File Browser')); }, icon: 'fa fa-info', className : 'text-info' }, '')); } if (ctrl.tb.options.placement === 'fileview') { generalButtons.push(m.component(FGButton, { onclick: function(event){ var panelToggle = $('.panel-toggle'); var panelExpand = $('.panel-expand'); var panelVisible = panelToggle.find('.osf-panel-hide'); var panelHidden = panelToggle.find('.osf-panel-show'); panelVisible.hide(); panelHidden.show(); }, icon: 'fa fa-angle-up' }, '')); } if (item && item.connected !== false){ // as opposed to undefined, avoids unnecessary setting of this value templates[toolbarModes.DEFAULT] = m('.col-xs-12', m('.pull-right', [finalRowButtons, m('span', generalButtons)])); } else { templates[toolbarModes.DEFAULT] = m('.col-xs-12', m('.pull-right', m('span', generalButtons))); } return m('.row.tb-header-row', [ m('#folderRow', { config : function () { $('#folderRow input').focus(); }}, [ templates[ctrl.mode()] ]) ]); } }; /** * When multiple rows are selected remove those that are not valid * @param {Array} rows List of item objects * @returns {Array} newRows Returns the revised list of rows */ function filterRows(rows) { if(rows.length === 0){ return; } var tb = this; var i, newRows = [], originalRow = tb.find(tb.multiselected()[0].id), originalParent, currentItem; function changeColor() { $(this).css('background-color', ''); } if (originalRow !== undefined) { originalParent = originalRow.parentID; for (i = 0; i < rows.length; i++) { currentItem = rows[i]; // Filter rows that are no in the parent var inParent = currentItem.parentID === originalParent && currentItem.id !== -1; var inProgress = typeof currentItem.inProgress !== 'undefined' && currentItem.inProgress; if (inParent && !inProgress) { newRows.push(rows[i]); } else { $('.tb-row[data-id="' + rows[i].id + '"]').stop().css('background-color', '#D18C93') .animate({ backgroundColor: '#fff'}, 500, changeColor); if (inProgress) { $osf.growl('Error', 'Please wait for current action to complete'); } } } } tb.multiselected(newRows); tb.highlightMultiselect(); return newRows; } /** * Helper function that turns parent open values to true to respective redraws can open the folder * @this Treebeard.controller * @param {Object} item A Treebeard _item object. * @private */ function openParentFolders (item) { var tb = this; // does it have a parent? If so change open var parent = item.parent(); if (parent) { if (!parent.open) { var index = tb.returnIndex(parent.id); parent.load = true; tb.toggleFolder(index); } openParentFolders.call(tb, parent); } } /** * Handles multiselect conditions and actions * @this Treebeard.controller * @param {Object} event jQuery click event. * @param {Object} row A Treebeard _item object. * @private */ function _fangornMultiselect (event, row) { var tb = this; var scrollToItem = false; if (tb.toolbarMode() === 'filter') { scrollToItem = true; // recursively open parents of the selected item but do not lazyload; openParentFolders.call(tb, row); } dismissToolbar.call(tb); filterRows.call(tb, tb.multiselected()); if (tb.multiselected().length === 1){ tb.select('#tb-tbody').removeClass('unselectable'); if(scrollToItem) { scrollToFile.call(tb, tb.multiselected()[0].id); } } else if (tb.multiselected().length > 1) { tb.select('#tb-tbody').addClass('unselectable'); } m.redraw(); reapplyTooltips(); } /* BEGIN MOVE */ // copyMode can be 'copy', 'move', 'forbidden', or null. // This is set at draglogic and is used as global within this module var copyMode = null; // Set altkey global to fangorn var altKey = false; $(document).keydown(function (e) { if (e.altKey) { altKey = true; } }); $(document).keyup(function (e) { if (!e.altKey) { altKey = false; } }); /** * Hook for the drag start event on jquery * @param event jQuery UI drggable event object * @param ui jQuery UI draggable ui object * @private */ function _fangornDragStart(event, ui) { // Sync up the toolbar in case item was drag-clicked and not released m.redraw(); var itemID = $(event.target).attr('data-id'), item = this.find(itemID); if (this.multiselected().length < 2) { this.multiselected([item]); } } /** * Hook for the drop event of jQuery UI droppable * @param event jQuery UI droppable event object * @param ui jQuery UI droppable ui object * @private */ function _fangornDrop(event, ui) { var tb = this; var items = tb.multiselected().length === 0 ? [tb.find(tb.selected)] : tb.multiselected(), folder = tb.find($(event.target).attr('data-id')); // Run drop logic here _dropLogic.call(tb, event, items, folder); } /** * Hook for the over event of jQuery UI droppable * @param event jQuery UI droppable event object * @param ui jQuery UI droppable ui object * @private */ function _fangornOver(event, ui) { var tb = this; var items = tb.multiselected().length === 0 ? [tb.find(tb.selected)] : tb.multiselected(), folder = tb.find($(event.target).attr('data-id')), dragState = _dragLogic.call(tb, event, items, ui); $('.tb-row').removeClass('tb-h-success fangorn-hover'); if (dragState !== 'forbidden') { $('.tb-row[data-id="' + folder.id + '"]').addClass('tb-h-success'); } else { $('.tb-row[data-id="' + folder.id + '"]').addClass('fangorn-hover'); } } /** * Log the success or failure of a file action (upload, etc.) in treebeard * @param {Object} treebeard The treebeard instance currently being run, check Treebeard API * @param {Object} file File object that dropzone passes * @param success Boolean on whether upload actually happened * @param message String failure reason message, '' if success === true * @param link String with url to file, '' if success === false * @param op String specifying type of move conflict resolution; ['keep', 'skip', 'replace'] * @private */ function addFileStatus(treebeard, file, success, message, link, op){ if (typeof op !== 'undefined'){ treebeard.moveStates.push( {'name': file.data.name, 'success': success, 'link': link, 'op': op} ); } else { treebeard.uploadStates.push( {'name': file.name, 'success': success, 'link': link, 'message': message} ); } } /** * Triggers file status modal or growlboxes after upload queue is empty * @param {Object} treebeard The treebeard instance currently being run, check Treebeard API * @private */ var UPLOAD_MODAL_MIN_FILE_QUANTITY = 4; function _fangornQueueComplete(treebeard) { var fileStatuses = treebeard.uploadStates; treebeard.uploadStates = []; var total = fileStatuses.length; var failed = 0; if (total >= UPLOAD_MODAL_MIN_FILE_QUANTITY) { treebeard.modal.update(m('', [ m('', [ fileStatuses.map(function(status){ if (!status.success){ failed++; } return m('', [ m('.row', [ m((status.success ? 'a[href="' + status.link + '"]' : '') + '.col-sm-10', status.name), m('.col-sm-1', m(status.success ? '.fa.fa-check[style="color: green"]' : '.fa.fa-times[style="color: red"]')), m('.col-sm-1', m(!status.success ? '.fa.fa-info[data-toggle="tooltip"][data-placement="top"][title="'+ status.message +'"]' : '')) ]), m('hr') ] ); }) ]) ]), m('', [ m('a.btn.btn-primary', {onclick: function() {treebeard.modal.dismiss();}}, 'Done'), //jshint ignore:line ]), m('', [m('h3.break-word.modal-title', 'Upload Status'), m('p', total - failed + '/' + total + ' files succeeded.')])); $('[data-toggle="tooltip"]').tooltip(); } else { fileStatuses.map(function(status) { if (!status.success) { if (status.message !== 'Upload canceled.') { $osf.growl( 'Error', status.message ); } } }); } } /** * Where the drop actions happen * @param event jQuery UI drop event * @param {Array} items List of items being dragged at the time. Each item is a _item object * @param {Object} folder Folder information as _item object */ function _dropLogic(event, items, folder) { var tb = this; if (items.length < 1 || items.indexOf(folder) > -1 || copyMode === 'forbidden' ) { return; } if (folder.data.kind === 'file') { folder = folder.parent(); } if (!folder.open) { return tb.updateFolder(null, folder, _dropLogic.bind(tb, event, items, folder)); } var toMove = checkConflicts(items, folder); tb.syncFileMoveCache = tb.syncFileMoveCache || {}; tb.syncFileMoveCache[folder.data.provider] = tb.syncFileMoveCache[folder.data.provider] || {}; tb.moveStates = tb.moveStates || []; if (toMove.ready.length > 0) { tb.syncFileMoveCache[folder.data.provider].ready = tb.syncFileMoveCache[folder.data.provider].ready || []; if (SYNC_UPLOAD_ADDONS.indexOf(folder.data.provider) !== -1) { toMove.ready.forEach(function(item) { tb.syncFileMoveCache[folder.data.provider].ready.push({'item' : item, 'folder' : folder}); }); } else { toMove.ready.forEach(function(item) { doItemOp.call(tb, copyMode === 'move' ? OPERATIONS.MOVE : OPERATIONS.COPY, folder, item, undefined, 'replace'); }); } } if (toMove.conflicts.length > 0) { tb.syncFileMoveCache[folder.data.provider].conflicts = tb.syncFileMoveCache[folder.data.provider].conflicts || []; toMove.conflicts.forEach(function(item) { tb.syncFileMoveCache[folder.data.provider].conflicts.push({'item' : item, 'folder' : folder}); }); } if (tb.syncFileMoveCache[folder.data.provider].conflicts || tb.syncFileMoveCache[folder.data.provider].ready) { doSyncMove(tb, folder.data.provider); } } function displayMoveStats(tb) { var moveStatuses = tb.moveStates; var total = moveStatuses && moveStatuses.length; if (moveStatuses.length) { tb.moveStates = []; var failed = 0; var skipped = 0; tb.modal.update(m('', [ m('', [ moveStatuses.map(function(status){ if (!status.success){ failed++; } if (status.op === 'skip'){ skipped++; } return m('', [ m('.row', [ m((status.success ? 'a[href="' + status.link + '"]' : '') + '.col-sm-7', status.name), m('.col-sm-1', m(status.success ? '.fa.fa-check.text-success' : '.fa.fa-times.text-danger')), m('.col-sm-4' + (status.success ? '.text-info' : '.text-danger'), CONFLICT_INFO[status.op].passed) ]), m('hr') ] ); }) ]) ]), m('', [ m('a.btn.btn-primary', {onclick: function() {tb.modal.dismiss();}}, 'Done'), //jshint ignore:line ]), m('', [ m('h3.break-word.modal-title', 'Move Status'), m('p', [ m('span', failed !== total ? total - failed + '/' + total + ' files successfully moved.': ''), m('span', skipped ? ' Skipped ' + skipped + '/' + total + ' files.': '') ]) ])); } else { tb.modal.dismiss(); } } function doSyncMove(tb, provider){ var cache = tb.syncFileMoveCache && tb.syncFileMoveCache[provider]; var itemData; if (cache.conflicts && cache.conflicts.length > 0) { itemData = cache.conflicts.pop(); displayConflict(tb, itemData.item, itemData.folder, doItemOp.bind(tb, copyMode === 'move' ? OPERATIONS.MOVE : OPERATIONS.COPY, itemData.folder, itemData.item, undefined)); } else if (cache.ready && cache.ready.length > 0) { itemData = cache.ready.pop(); doItemOp.call(tb, copyMode === 'move' ? OPERATIONS.MOVE : OPERATIONS.COPY, itemData.folder, itemData.item, undefined, 'replace'); } else { displayMoveStats(tb); } } /** * Sets the copy state based on which item is being dragged on which other item * @param {Object} event Browser drag event * @param {Array} items List of items being dragged at the time. Each item is a _item object * @param {Object} ui jQuery UI draggable drag ui object * @returns {String} copyMode One of the copy states, from 'copy', 'move', 'forbidden' */ function _dragLogic(event, items, ui) { var tb = this; var canMove = true, folder = this.find($(event.target).attr('data-id')), dragGhost = $('.tb-drag-ghost'); // Set the cursor to match the appropriate copy mode copyMode = getCopyMode(folder, items); switch (copyMode) { case 'forbidden': dragGhost.css('cursor', 'not-allowed'); break; case 'copy': dragGhost.css('cursor', 'copy'); break; case 'move': dragGhost.css('cursor', 'move'); break; default: dragGhost.css('cursor', 'default'); } return copyMode; } function getAllChildren(item) { var c; var current; var children = []; var remaining = []; for (c in item.children) { remaining.push(item.children[c]); } while (remaining.length > 0) { current = remaining.pop(); children.push(current); for (c in current.children) { remaining.push(current.children[c]); } } return children; } function isInvalidDropFolder(folder) { if ( // cannot drop on root line folder.parentID === 0 || // don't drop if changed folder.inProgress || // cannot drop on files folder.data.nodeType || folder.data.kind !== 'folder' || // must have permission !folder.data.permissions.edit || // must have a provider !folder.data.provider || folder.data.status || // cannot add to published dataverse (folder.data.provider === 'dataverse' && folder.data.dataverseIsPublished) || // no dropping into read-only providers (READ_ONLY_ADDONS.indexOf(folder.data.provider) !== -1) ) { return true; } return false; } function isInvalidDropItem(folder, item, cannotBeFolder, mustBeIntra) { if ( // not a valid drop if is a node item.data.nodeType || // cannot drop on roots item.data.isAddonRoot || // no self drops item.id === folder.id || // no dropping on direct parent item.parentID === folder.id || // no moving published items from dataverse (item.data.provider === 'dataverse' && item.data.extra.hasPublishedVersion) || // no moving folders into dataverse (folder.data.provider === 'dataverse' && item.data.kind === 'folder') || // no dropping if waiting on waterbutler ajax item.inProgress || (cannotBeFolder && item.data.kind === 'folder') || (mustBeIntra && item.data.provider !== folder.data.provider) ) { return true; } return false; } function allowedToMove(folder, item, mustBeIntra) { return ( item.data.permissions.edit && (!mustBeIntra || (item.data.provider === folder.data.provider && item.data.nodeId === folder.data.nodeId)) && !(item.data.provider === 'figshare' && item.data.extra && item.data.extra.status === 'public') && (READ_ONLY_ADDONS.indexOf(item.data.provider) === -1) && (READ_ONLY_ADDONS.indexOf(folder.data.provider) === -1) ); } function folderContainsPreprint(item, preprintPath) { // TODO This will only get children of open folders -ajs var children = getAllChildren(item); for (var c = 0; c < children.length; c++) { if (children[c].data.path === preprintPath) { return true; } } return false; } function showDeleteMultiple(items) { // Only show delete button if user has edit permissions on at least one selected file for (var i = 0; i < items.length; i++) { var each = items[i].data; if (typeof each.permissions !== 'undefined' && each.permissions.edit && !each.isAddonRoot && !each.nodeType) { return true; } } return false; } function multiselectContainsPreprint(items, preprintPath) { for (var i = 0; i < items.length; i++) { var each = items[i]; if (each.data.kind === 'folder') { if (folderContainsPreprint(each, preprintPath)) { return true; } } else if (each.data.path === preprintPath) { return true; } } return false; } function getPreprintPath(preprintFileId) { if (preprintFileId) { return '/' + preprintFileId; } return null; } function getCopyMode(folder, items) { var tb = this; // Prevents side effects from rare instance where folders not fully populated if (typeof folder === 'undefined' || typeof folder.data === 'undefined') { return 'forbidden'; } var preprintPath = getPreprintPath(window.contextVars.node.preprintFileId); var canMove = true; var mustBeIntra = (folder.data.provider === 'github'); // Folders cannot be copied to dataverse at all. Folders may only be copied to figshare // if the target is the addon root and the root is a project (not a fileset) var cannotBeFolder = ( folder.data.provider === 'dataverse' || (folder.data.provider === 'figshare' && !(folder.data.isAddonRoot && folder.data.rootFolderType === 'project')) ); if (isInvalidDropFolder(folder)) { return 'forbidden'; } for (var i = 0; i < items.length; i++) { var item = items[i]; if (isInvalidDropItem(folder, item, cannotBeFolder, mustBeIntra)) { return 'forbidden'; } var children = getAllChildren(item); for (var c = 0; c < children.length; c++) { if (children[c].inProgress || children[c].id === folder.id) { return 'forbidden'; } if (children[c].data.path === preprintPath){ mustBeIntra = true; } } if (canMove) { mustBeIntra = mustBeIntra || item.data.provider === 'github' || preprintPath === item.data.path; canMove = allowedToMove(folder, item, mustBeIntra); } } if (folder.data.isPointer || altKey || !canMove) { return 'copy'; } return 'move'; } /* END MOVE */ function _resizeHeight () { var tb = this; var tbody = tb.select('#tb-tbody'); var windowHeight = $(window).height(); var topBuffer = tbody.offset().top + 50; var availableSpace = windowHeight - topBuffer; if(availableSpace > 0) { // Set a minimum height tbody.height(availableSpace < 300 ? 300 : availableSpace); } } /** * OSF-specific Treebeard options common to all addons. * Check Treebeard API for more information */ tbOptions = { rowHeight : 35, // user can override or get from .tb-row height showTotal : 15, // Actually this is calculated with div height, not needed. NEEDS CHECKING paginate : false, // Whether the applet starts with pagination or not. paginateToggle : false, // Show the buttons that allow users to switch between scroll and paginate. uploads : true, // Turns dropzone on/off. columnTitles : _fangornColumnTitles, resolveRows : _fangornResolveRows, lazyLoadPreprocess: waterbutler.wbLazyLoadPreprocess, hoverClassMultiselect : 'fangorn-selected', multiselect : true, placement : 'files', title : function() { //TODO Add disk saving mode message // if(window.contextVars.diskSavingMode) { // // If File and FileRead are not defined dropzone is not supported and neither is uploads // if (window.File && window.FileReader) { // return m('p', { // }, [ // m('span', 'To Upload: Drag files into a folder OR click the '), // m('i.btn.btn-default.btn-xs', { disabled : 'disabled'}, [ m('i.fa.fa-upload')]), // m('span', ' below.') // ]); // } // return m('p', { // class: 'text-danger' // }, [ // m('span', 'Your browser does not support file uploads, ', [ // m('a', { href: 'http://browsehappy.com' }, 'learn more'), // '.' // ]) // ]); // } return undefined; }, showFilter : true, // Gives the option to filter by showing the filter box. allowMove : true, // Turn moving on or off. hoverClass : 'fangorn-hover', togglecheck : _fangornToggleCheck, sortButtonSelector : { up : 'i.fa.fa-chevron-up', down : 'i.fa.fa-chevron-down' }, ondataload: function() { _loadTopLevelChildren.call(this); }, onload : function () { var tb = this; tb.options.onload = null; // Make sure we don't get called again tb.uploadStates = []; tb.pendingFileOps = []; tb.select('#tb-tbody, .tb-tbody-inner').on('click', function(event){ if(event.target !== this) { var item = tb.multiselected()[0]; if (item) { if (item.data.isAddonRoot || item.data.nodeType === 'project' || item.data.nodeType === 'component') { tb.toolbarMode(toolbarModes.DEFAULT); } return; } } tb.clearMultiselect(); m.redraw(); dismissToolbar.call(tb); }); $(window).on('beforeunload', function() { if(tb.dropzone && tb.dropzone.getUploadingFiles().length) { return 'You have pending uploads, if you leave this page they may not complete.'; } if(tb.pendingFileOps.length > 0) { return 'You have pending file operations, if you leave this page they may not complete.'; } }); if(tb.options.placement === 'project-files') { _resizeHeight.call(tb); $(window).resize(function(){ _resizeHeight.call(tb); }); } $(window).on('keydown', function(event){ if (event.keyCode === ESCAPE_KEY) { dismissToolbar.call(tb); } }); }, movecheck : function (to, from) { //This method gives the users an option to do checks and define their return return true; }, movefail : function (to, from) { //This method gives the users an option to do checks and define their return return true; }, addcheck : function (treebeard, item, file) { var size; var maxSize; var displaySize; var msgText; if (_fangornCanDrop(treebeard, item)) { if (item.data.accept && item.data.accept.maxSize) { size = file.size / 1000000; maxSize = item.data.accept.maxSize; if (size > maxSize) { displaySize = Math.round(file.size / 10000) / 100; msgText = 'One of the files is too large (' + displaySize + ' MB). Max file size is ' + item.data.accept.maxSize + ' MB.'; item.notify.update(msgText, 'warning', undefined, 3000); addFileStatus(treebeard, file, false, 'File is too large. Max file size is ' + item.data.accept.maxSize + ' MB.', ''); return false; } } return true; } return false; }, onscrollcomplete : function(){ reapplyTooltips(); }, onmultiselect : _fangornMultiselect, filterPlaceholder : 'Filter', onmouseoverrow : _fangornMouseOverRow, sortDepth : 2, dropzone : { // All dropzone options. maxFilesize: 10000000, url: function(files) {return files[0].url;}, clickable : '#treeGrid', addRemoveLinks : false, previewTemplate : '<div></div>', parallelUploads : 5, acceptDirectories : false, createImageThumbnails : false, fallback: function(){}, }, resolveIcon : _fangornResolveIcon, resolveToggle : _fangornResolveToggle, // Pass ``null`` to avoid overwriting Dropzone URL resolver resolveUploadUrl: function() {return null;}, resolveLazyloadUrl : _fangornResolveLazyLoad, resolveUploadMethod : _fangornUploadMethod, lazyLoadError : _fangornLazyLoadError, lazyLoadOnLoad : _fangornLazyLoadOnLoad, ontogglefolder : expandStateLoad, dropzoneEvents : { uploadprogress : _fangornUploadProgress, sending : _fangornSending, complete : _fangornComplete, success : _fangornDropzoneSuccess, removedfile: _fangornDropzoneRemovedFile, error : _fangornDropzoneError, dragover : _fangornDragOver, addedfile : _fangornAddedFile, drop : _fangornDropzoneDrop, queuecomplete : _fangornQueueComplete }, resolveRefreshIcon : function() { return m('i.fa.fa-refresh.fa-spin'); }, removeIcon : function(){ return m.trust('&times;'); }, toolbarComponent : FGToolbar, // DRAG AND DROP RELATED OPTIONS dragOptions : {}, dropOptions : {}, dragEvents : { start : _fangornDragStart }, dropEvents : { drop : _fangornDrop, over : _fangornOver }, onafterselectwitharrow : function(row, direction) { var tb = this; var item = tb.find(row.id); _fangornMultiselect.call(tb, null, item); }, hScroll : null, naturalScrollLimit : 0 }; /** * Loads Fangorn with options * @param {Object} options The options to be extended with Treebeard options * @constructor */ function Fangorn(options) { this.options = $.extend({}, tbOptions, options); this.grid = null; // Set by _initGrid this.init(); } /** * Initialize Fangorn methods that connect it to Treebeard * @type {{constructor: Fangorn, init: Function, _initGrid: Function}} */ Fangorn.prototype = { constructor: Fangorn, init: function () { this._initGrid(); }, // Create the Treebeard once all addons have been configured _initGrid: function () { this.grid = new Treebeard(this.options); return this.grid; } }; Fangorn.Components = { button : FGButton, input : FGInput, toolbar : FGToolbar, dropdown : FGDropdown, toolbarModes : toolbarModes }; Fangorn.ButtonEvents = { _downloadEvent : _downloadEvent, _downloadZipEvent: _downloadZipEvent, _uploadEvent : _uploadEvent, _removeEvent : _removeEvent, createFolder : _createFolder, _gotoFileEvent : gotoFileEvent, }; Fangorn.DefaultColumns = { _fangornTitleColumn : _fangornTitleColumn, _fangornVersionColumn : _fangornVersionColumn, _fangornModifiedColumn : _fangornModifiedColumn }; Fangorn.Utils = { inheritFromParent : inheritFromParent, resolveconfigOption: resolveconfigOption, reapplyTooltips : reapplyTooltips, setCurrentFileID: setCurrentFileID, scrollToFile: scrollToFile, openParentFolders : openParentFolders, dismissToolbar : dismissToolbar, uploadRowTemplate : uploadRowTemplate, resolveIconView : resolveIconView, orderFolder : orderFolder, connectCheckTemplate : _connectCheckTemplate }; Fangorn.DefaultOptions = tbOptions; module.exports = { Fangorn : Fangorn, allowedToMove : allowedToMove, folderContainsPreprint : folderContainsPreprint, getAllChildren : getAllChildren, isInvalidDropFolder : isInvalidDropFolder, isInvalidDropItem : isInvalidDropItem, getCopyMode : getCopyMode, multiselectContainsPreprint : multiselectContainsPreprint, showDeleteMultiple : showDeleteMultiple, checkConflicts : checkConflicts };
Do not inherit previous move statuses
website/static/js/fangorn.js
Do not inherit previous move statuses
<ide><path>ebsite/static/js/fangorn.js <ide> <ide> tb.syncFileMoveCache = tb.syncFileMoveCache || {}; <ide> tb.syncFileMoveCache[folder.data.provider] = tb.syncFileMoveCache[folder.data.provider] || {}; <del> tb.moveStates = tb.moveStates || []; <add> tb.moveStates = []; <ide> <ide> if (toMove.ready.length > 0) { <ide> tb.syncFileMoveCache[folder.data.provider].ready = tb.syncFileMoveCache[folder.data.provider].ready || [];