repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
tharindum/opennms_dashboard
opennms-services/src/main/java/org/opennms/netmgt/trapd/jmx/TrapdMBean.java
1408
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2006-2011 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2011 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.trapd.jmx; import org.opennms.netmgt.daemon.BaseOnmsMBean; /** * <p>TrapdMBean interface.</p> * * @author ranger * @version $Id: $ */ public interface TrapdMBean extends BaseOnmsMBean { }
gpl-2.0
blazegraph/database
bigdata-core/bigdata-rdf/src/java/com/bigdata/rdf/store/BDS.java
14054
/* Copyright (C) SYSTAP, LLC DBA Blazegraph 2006-2016. All rights reserved. Contact: SYSTAP, LLC DBA Blazegraph 2501 Calvert ST NW #106 Washington, DC 20008 licenses@blazegraph.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * Created on Apr 12, 2008 */ package com.bigdata.rdf.store; import org.openrdf.model.URI; import org.openrdf.model.impl.URIImpl; import com.bigdata.rdf.sparql.ast.eval.SliceServiceFactory; /** * A vocabulary for the bigdata full text search facility. Full text search may * be used to combine text search and graph search. Low-latency, user facing * search applications may be created by slicing the full text search results * and feeding them incrementally into SPARQL queries. This approach allows the * application to manage the cost of the SPARQL query by bounding the input. If * necessary, additional results can be feed into the query. * * @see SliceServiceFactory * * @see <a * href="http://sourceforge.net/apps/mediawiki/bigdata/index.php?title=FullTextSearch"> * Free Text Index </a> * * @author <a href="mailto:thompsonbry@users.sourceforge.net">Bryan Thompson</a> * @version $Id: BD.java 6786 2012-12-19 18:43:27Z thompsonbry $ */ public interface BDS { /** * The namespace used for magic search predicates. * <p> * @see #SEARCH * @see #RELEVANCE * @see #RANK * @see #NUM_MATCHED_TOKENS */ final String NAMESPACE = "http://www.bigdata.com/rdf/search#"; /** * The name of a magic predicate recognized in SPARQL queries when it occurs * in statement patterns such as: * * <pre> * * ( s?, bigdata:search, &quot;scale-out RDF triplestore&quot; ) * * </pre> * * The value MUST be bound and MUST be a literal. The * <code>languageCode</code> attribute is permitted. When specified, the * <code>languageCode</code> attribute will be used to determine how the * literal is tokenized - it does not filter for matches marked with that * <code>languageCode</code> attribute. The <code>datatype</code> attribute * is not allowed. * <p> * The subject MUST NOT be bound. * <p> * * This expression will evaluate to a set of bindings for the subject * position corresponding to the indexed literals matching any of the terms * obtained when the literal was tokenized. * * <p> * Note: The context position should be unbound when using statement * identifiers. */ final URI SEARCH = new URIImpl(NAMESPACE + "search"); /** * Magic predicate used to query for free text search metadata, reporting * the relevance of the search result to the search query. Use in * conjunction with {@link #SEARCH} as follows: * <p> * * <pre> * * select ?s ?relevance * where { * ?s bds:search &quot;scale-out RDF triplestore&quot; . * ?s bds:relevance ?relevance . * } * * </pre> * * Relevance is the cosine of the angle between the query vector (search * terms) and the document vector (terms in the indexed literals). The * minimum relevance is ZERO (0.0). The maximum relevance is ONE (1.0). * * @see #MIN_RELEVANCE * @see #MAX_RELEVANCE */ final URI RELEVANCE = new URIImpl(NAMESPACE + "relevance"); /** * Magic predicate used to query for free text search metadata, reporting * the rank (origin ONE (1)) of the search result amoung the search results * obtained for the search query. The rank is from ONE to N, where N is the * number of search results from the full text index. {@link #MIN_RANK} and * {@link #MAX_RANK} may be used to "slice" the full text index search * results. Use this query hint conjunction with {@link #SEARCH} as follows: * <p> * * <pre> * * select ?s ?rank * where { * ?s bds:search &quot;scale-out RDF triplestore&quot; . * ?s bds:rank ?rank . * } * * </pre> * * @see #MIN_RANK * @see #MAX_RANK */ final URI RANK = new URIImpl(NAMESPACE + "rank"); /** * Magic predicate used to limit the maximum rank of the free text search * results to the specified value (default {@value #DEFAULT_MAX_RANK)}. Use * in conjunction with {@link #SEARCH} as follows: * <p> * * <pre> * * select ?s * where { * ?s bds:search &quot;scale-out RDF triplestore&quot; . * ?s bds:maxRank "5"^^xsd:int . * } * * </pre> * * You can use {@link #MIN_RANK} and {@link #MAX_RANK} together to page * through the search results. This is often key to achieving low latency * graph search. By limiting the number of results that are fed into the * remained of the SPARQL query, you can ensure that the SPARQL query runs * quickly. If you do not get enough results from the SPARQL query, you can * feed the next "page" of free text results by changing the values for the * {@link #MIN_RANK} AND {@link #MAX_RANK} query hints. */ final URI MAX_RANK = new URIImpl(NAMESPACE + "maxRank"); /** * The default for {@link #MAX_RANK}. */ final int DEFAULT_MAX_RANK = Integer.MAX_VALUE; /** * Magic predicate used to limit the minimum rank of the free text search * results to the specified value (default {@value #DEFAULT_MIN_RANK}). Use * in conjunction with {@link #SEARCH} as follows: * <p> * * <pre> * * select ?s * where { * ?s bds:search &quot;scale-out RDF triplestore&quot; . * ?s bds:minRank "5"^^xsd:int . * } * * </pre> * * The default is {@value #DEFAULT_MIN_RANK}. */ final URI MIN_RANK = new URIImpl(NAMESPACE + "minRank"); /** * The default for {@link #MIN_RANK} is 1, full text search results will * start with the #1 most relevant hit by default. */ final int DEFAULT_MIN_RANK = 1; /** * Magic predicate used to query for free text search metadata. Use in * conjunction with {@link #SEARCH} as follows: * <p> * * <pre> * * select ?s * where { * ?s bds:search &quot;scale-out RDF triplestore&quot; . * ?s bds:minRelevance "0.5"^^xsd:double . * } * * </pre> * * The relevance scores are in [0.0:1.0], where 0.0 is the minimum possible * relevance and 1.0 is the maximum possible relevance. You should NOT * specify a minimum relevance of ZERO (0.0) as this can drag in way too * many unrelated results. The default is {@value #DEFAULT_MIN_RELEVANCE}. */ final URI MIN_RELEVANCE = new URIImpl(NAMESPACE + "minRelevance"); final double DEFAULT_MIN_RELEVANCE = 0.0d; /** * Magic predicate used to query for free text search metadata. Use in * conjunction with {@link #SEARCH} as follows: * <p> * * <pre> * * select ?s * where { * ?s bds:search &quot;scale-out RDF triplestore&quot; . * ?s bds:maxRelevance "0.9"^^xsd:double . * } * * </pre> * * The relevance scores are in [0.0:1.0], where 0.0 is the minimum possible * relevance and 1.0 is the maximum possible relevance. You should NOT * specify a minimum relevance of ZERO (0.0) as this can drag in way too * many unrelated results. The default maximum relevance is * {@value #DEFAULT_MAX_RELEVANCE}. */ final URI MAX_RELEVANCE = new URIImpl(NAMESPACE + "maxRelevance"); /** * The default value for {@link #MAX_RELEVANCE} unless overridden. */ final double DEFAULT_MAX_RELEVANCE = 1.0d; /** * Magic predicate used to query for free text search metadata indicates * that all terms in the query must be found within a given literal in order * for that literal to "match" the query (default * {@value #DEFAULT_MATCH_ALL_TERMS}). Use in conjunction with * {@link #SEARCH} as follows: * <p> * * <pre> * * select ?s * where { * ?s bds:search &quot;scale-out RDF triplestore&quot; . * ?s bds:matchAllTerms "true" . * } * * </pre> */ final URI MATCH_ALL_TERMS = new URIImpl(NAMESPACE + "matchAllTerms"); final boolean DEFAULT_MATCH_ALL_TERMS = false; /** * Magic predicate used to query for free text search metadata indicates * that only exact string matches will be reported (the literal must contain * the search string). Use in conjunction with {@link #SEARCH} as follows: * <p> * * <pre> * * select ?s * where { * ?s bds:search &quot;scale-out RDF triplestore&quot; . * ?s bds:matchExact "true" . * } * * </pre> * <p> * This operation will be rather expensive as it will require materializing * all the hits to check their values. */ final URI MATCH_EXACT = new URIImpl(NAMESPACE + "matchExact"); final boolean DEFAULT_MATCH_EXACT = false; /** * Magic predicate used to query for free text search metadata indicates * that only search results that also pass the specified REGEX filter will * be reported. Use in conjunction with {@link #SEARCH} as follows: * <p> * * <pre> * * select ?s * where { * ?s bds:search &quot;scale-out RDF triplestore&quot; . * ?s bds:matchRegex &quot;regex to apply to ?s bindings&quot; . * } * * </pre> * <p> * This operation will be rather expensive as it will require materializing * all the hits to check their values. */ final URI MATCH_REGEX = new URIImpl(NAMESPACE + "matchRegex"); final String DEFAULT_MATCH_REGEX = null; /** * * <strong>Prefix matching is now indicated using a wildcard</strong> * * <pre> * PREFIX bds: <http://www.bigdata.com/rdf/search#> * * SELECT ?subj ?label * WHERE { * ?label bds:search "mi*" . * ?label bds:relevance ?cosine . * ?subj ?p ?label . * } * </pre> * * <strong>The following approach is no longer supported. </strong> * * Magic predicate used to query for free text search metadata to turn on * prefix matching. Prefix matching will match all full text index tokens * that begin with the specified token(s) (default * {@value #DEFAULT_PREFIX_MATCH}). Use in conjunction with {@link #SEARCH} * as follows: * <p> * * <pre> * * select ?s * where { * ?s bds:search &quot;scale-out RDF triplestore&quot; . * ?s bds:prefixMatch &quot;true&quot; . * } * * </pre> * <p> * This will turn on prefix matching. * * @deprecated Prefix matching is now invoked using a wildcard. * * @see <a href="https://sourceforge.net/apps/trac/bigdata/ticket/803" > * prefixMatch does not work in full text search </a> */ @Deprecated final URI PREFIX_MATCH = new URIImpl(NAMESPACE + "prefixMatch"); /** * @deprecated This option is now invoked using a wildcard. */ final boolean DEFAULT_PREFIX_MATCH = false; /** * Magic predicate used to query for free text search metadata. Use in * conjunction with {@link #SEARCH} as follows: * <p> * * <pre> * * select ?s * where { * ?s bds:search &quot;scale-out RDF triplestore&quot; . * ?s bds:subjectSearch "true" . * } * * </pre> * <p> * The subject-centric search index must be enabled via * {@link AbstractTripleStore.Options#SUBJECT_CENTRIC_TEXT_INDEX}. * * @deprecated Feature was never completed due to scalability issues. See * BZLG-1548, BLZG-563. */ @Deprecated final URI SUBJECT_SEARCH = new URIImpl(NAMESPACE + "subjectSearch"); @Deprecated final boolean DEFAULT_SUBJECT_SEARCH = false; /** * Magic predicate used for the "search in search" service. Also serves as * the identifier for the service itself. */ final URI SEARCH_IN_SEARCH = new URIImpl(NAMESPACE + "searchInSearch"); /** * Magic predicate used to query for free text search metadata to set a * deadline in milliseconds on the full text index search ( * {@value #DEFAULT_TIMEOUT}). Use in conjunction with {@link #SEARCH} as * follows: * <p> * * <pre> * * select ?s * where { * ?s bds:search &quot;scale-out RDF triplestore&quot; . * ?s bds:searchTimeout "5000" . * } * * </pre> * <p> * Timeout specified in milliseconds. */ final URI SEARCH_TIMEOUT = new URIImpl(NAMESPACE + "searchTimeout"); /** * The default timeout for a free text search (milliseconds). */ final long DEFAULT_TIMEOUT = Long.MAX_VALUE; /** * Magic predicate to specify that we want a range count done on the search. * Bind the range count to the variable in the object position. Will * attempt to do a fast range count on the index rather than materializing * the hits into an array. This is only possible if matchExact == false * and matchRegex == null. */ final URI RANGE_COUNT = new URIImpl(NAMESPACE + "rangeCount"); }
gpl-2.0
aubelix/liferay-samples
wip-portlet/src/main/java/fr/ippon/wip/ltpa/providers/CredentialProvider.java
1407
/* * Copyright 2010,2011 Ippon Technologies * * This file is part of Web Integration Portlet (WIP). * Web Integration Portlet (WIP) is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Web Integration Portlet (WIP) 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 Web Integration Portlet (WIP). If not, see <http://www.gnu.org/licenses/>. */ package fr.ippon.wip.ltpa.providers; import javax.portlet.PortletRequest; /** * The interface CredentialProvider must be implemented * by the external class that supply the credential. */ public interface CredentialProvider { /** * This method returns the user credential. The "request" parameter * is used to send data needed by the implementing method (ex: a user ID) * * @param request PortletRequest object to transmit data * @return a String tuple {domain, ltpaSecret} */ public String getCredentials(PortletRequest request); }
gpl-2.0
sdvf/itba-pod-2010
src/main/java/ar/edu/itba/pod/simul/communication/ClusterCommunication.java
1588
package ar.edu.itba.pod.simul.communication; import java.rmi.Remote; import java.rmi.RemoteException; /** * Medium used for all the necessary communications for the cluster. Each node must have one implementation of this * interface in order to communicate with the rest of the nodes in the cluster. */ public interface ClusterCommunication extends Remote { /** * A broadcast message is created and the nodes are informed of the message. The sender node sends the message to N * random nodes. In each iteration, the node is informed if this message is new or not. This information is used to * determine whether to continue or not with the broadcast. * * @param message * The message to send to the cluster */ public void broadcast(Message message) throws RemoteException; /** * A point to point communication is established between the two nodes and the message is sent. In case that the * destination node has already received the message, false is returned. Otherwise, true is returned. The receiver * must determine if the new messages has to be send in broadcast to the rest of the nodes or not. * * @param message * The message to send to the cluster * @param node * The destination node * @return True if it is a new message */ public boolean send(Message message, String nodeId) throws RemoteException; /** * @return The message listener of the current node. * @throws RemoteException */ public MessageListener getListener() throws RemoteException; }
gpl-2.0
skyHALud/codenameone
Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/classlib/modules/nio/src/main/java/common/org/apache/harmony/nio/internal/LockManager.java
2964
/* 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.harmony.nio.internal; import java.nio.channels.FileLock; import java.nio.channels.OverlappingFileLockException; import java.util.Comparator; import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; /** * The lock manager is responsible for tracking acquired and pending locks on * the underlying file channel. * */ final class LockManager { // The set of acquired and pending locks. private final Comparator<FileLock> lockComparator = new Comparator<FileLock>() { public int compare(FileLock lock1, FileLock lock2) { long position1 = lock1.position(); long position2 = lock2.position(); return position1 > position2 ? 1 : (position1 < position2 ? -1 : 0); } }; private final SortedSet<FileLock> locks = new TreeSet<FileLock>( lockComparator); /* * Default Constructor. */ protected LockManager() { super(); } /* * Add a new pending lock to the manager. Throws an exception if the lock * would overlap an existing lock. Once the lock is acquired it remains in * this set as an acquired lock. */ synchronized void addLock(FileLock lock) throws OverlappingFileLockException { long lockEnd = lock.position() + lock.size(); for (Iterator<FileLock> keyItr = locks.iterator(); keyItr.hasNext();) { FileLock existingLock = keyItr.next(); if (existingLock.position() > lockEnd) { // This, and all remaining locks, start beyond our end (so // cannot overlap). break; } if (existingLock.overlaps(lock.position(), lock.size())) { throw new OverlappingFileLockException(); } } locks.add(lock); } /* * Removes an acquired lock from the lock manager. If the lock did not exist * in the lock manager the operation is a no-op. */ synchronized void removeLock(FileLock lock) { locks.remove(lock); } }
gpl-2.0
gxwangdi/practice
grpc-java/core/src/main/java/io/grpc/internal/AtomicBackoff.java
3398
/* * Copyright 2017, Google Inc. 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 Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.grpc.internal; import com.google.common.base.Preconditions; import java.util.concurrent.atomic.AtomicLong; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.concurrent.ThreadSafe; /** * A {@code long} atomically updated due to errors caused by the value being too small. */ @ThreadSafe public final class AtomicBackoff { private static final Logger log = Logger.getLogger(AtomicBackoff.class.getName()); private final String name; private final AtomicLong value = new AtomicLong(); /** Construct an atomic with initial value {@code value}. {@code name} is used for logging. */ public AtomicBackoff(String name, long value) { Preconditions.checkArgument(value > 0, "value must be positive"); this.name = name; this.value.set(value); } /** Returns the current state. The state instance's value does not change of time. */ public State getState() { return new State(value.get()); } @ThreadSafe public final class State { private final long savedValue; private State(long value) { this.savedValue = value; } public long get() { return savedValue; } /** * Causes future invocations of {@link AtomicBackoff#getState} to have a value at least double * this state's value. Subsequent calls to this method will not increase the value further. */ public void backoff() { // Use max to handle overflow long newValue = Math.max(savedValue * 2, savedValue); boolean swapped = value.compareAndSet(savedValue, newValue); // Even if swapped is false, the current value should be at least as large as newValue assert value.get() >= newValue; if (swapped) { log.log(Level.WARNING, "Increased {0} to {1}", new Object[] {name, newValue}); } } } }
gpl-2.0
tybor/MoSync
tools/android/dx/src/com/android/dx/cf/iface/StdMethod.java
1983
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.dx.cf.iface; import com.android.dx.rop.code.AccessFlags; import com.android.dx.rop.cst.CstNat; import com.android.dx.rop.cst.CstType; import com.android.dx.rop.type.Prototype; /** * Standard implementation of {@link Method}, which directly stores * all the associated data. */ public final class StdMethod extends StdMember implements Method { /** {@code non-null;} the effective method descriptor */ private final Prototype effectiveDescriptor; /** * Constructs an instance. * * @param definingClass {@code non-null;} the defining class * @param accessFlags access flags * @param nat {@code non-null;} member name and type (descriptor) * @param attributes {@code non-null;} list of associated attributes */ public StdMethod(CstType definingClass, int accessFlags, CstNat nat, AttributeList attributes) { super(definingClass, accessFlags, nat, attributes); String descStr = getDescriptor().getString(); effectiveDescriptor = Prototype.intern(descStr, definingClass.getClassType(), AccessFlags.isStatic(accessFlags), nat.isInstanceInit()); } /** {@inheritDoc} */ public Prototype getEffectiveDescriptor() { return effectiveDescriptor; } }
gpl-2.0
gernoteger/RemInD
remind-core/src/main/java/at/jit/remind/core/model/UserInput.java
1020
package at.jit.remind.core.model; public class UserInput { private int lowerTestCycleNumber; private int upperTestCycleNumber; private String environment; public UserInput() { this(Integer.MIN_VALUE, Integer.MAX_VALUE, ""); } public UserInput(int lowerTestCycleNumber, int upperTestCycleNumber, String environment) { this.lowerTestCycleNumber = lowerTestCycleNumber; this.upperTestCycleNumber = upperTestCycleNumber; this.environment = environment; } public int getLowerTestCycleNumber() { return lowerTestCycleNumber; } public void setLowerTestCycleNumber(int lowerTestCycleNumber) { this.lowerTestCycleNumber = lowerTestCycleNumber; } public int getUpperTestCycleNumber() { return upperTestCycleNumber; } public void setUpperTestCycleNumber(int upperTestCycleNumber) { this.upperTestCycleNumber = upperTestCycleNumber; } public String getEnvironment() { return environment; } public void setEnvironment(String environment) { this.environment = environment; } }
gpl-2.0
smarr/Truffle
compiler/src/org.graalvm.compiler.lir/src/org/graalvm/compiler/lir/dfa/LocationMarker.java
7673
/* * Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.graalvm.compiler.lir.dfa; import static jdk.vm.ci.code.ValueUtil.isIllegal; import java.util.ArrayList; import java.util.EnumSet; import org.graalvm.compiler.core.common.LIRKind; import org.graalvm.compiler.core.common.cfg.AbstractBlockBase; import org.graalvm.compiler.core.common.cfg.BlockMap; import org.graalvm.compiler.debug.DebugContext; import org.graalvm.compiler.debug.Indent; import org.graalvm.compiler.lir.InstructionStateProcedure; import org.graalvm.compiler.lir.LIR; import org.graalvm.compiler.lir.LIRFrameState; import org.graalvm.compiler.lir.LIRInstruction; import org.graalvm.compiler.lir.LIRInstruction.OperandFlag; import org.graalvm.compiler.lir.LIRInstruction.OperandMode; import org.graalvm.compiler.lir.ValueConsumer; import org.graalvm.compiler.lir.framemap.FrameMap; import org.graalvm.compiler.lir.util.ValueSet; import jdk.vm.ci.code.Register; import jdk.vm.ci.meta.PlatformKind; import jdk.vm.ci.meta.Value; public abstract class LocationMarker<S extends ValueSet<S>> { private final LIR lir; private final BlockMap<S> liveInMap; private final BlockMap<S> liveOutMap; protected final FrameMap frameMap; protected LocationMarker(LIR lir, FrameMap frameMap) { this.lir = lir; this.frameMap = frameMap; liveInMap = new BlockMap<>(lir.getControlFlowGraph()); liveOutMap = new BlockMap<>(lir.getControlFlowGraph()); } protected abstract S newLiveValueSet(); protected abstract boolean shouldProcessValue(Value operand); protected abstract void processState(LIRInstruction op, LIRFrameState info, S values); void build() { AbstractBlockBase<?>[] blocks = lir.getControlFlowGraph().getBlocks(); UniqueWorkList worklist = new UniqueWorkList(blocks.length); for (int i = blocks.length - 1; i >= 0; i--) { worklist.add(blocks[i]); } for (AbstractBlockBase<?> block : lir.getControlFlowGraph().getBlocks()) { liveInMap.put(block, newLiveValueSet()); } while (!worklist.isEmpty()) { AbstractBlockBase<?> block = worklist.poll(); processBlock(block, worklist); } } /** * Merge outSet with in-set of successors. */ private boolean updateOutBlock(AbstractBlockBase<?> block) { S union = newLiveValueSet(); for (AbstractBlockBase<?> succ : block.getSuccessors()) { union.putAll(liveInMap.get(succ)); } S outSet = liveOutMap.get(block); // check if changed if (outSet == null || !union.equals(outSet)) { liveOutMap.put(block, union); return true; } return false; } @SuppressWarnings("try") private void processBlock(AbstractBlockBase<?> block, UniqueWorkList worklist) { if (updateOutBlock(block)) { DebugContext debug = lir.getDebug(); try (Indent indent = debug.logAndIndent("handle block %s", block)) { currentSet = liveOutMap.get(block).copy(); ArrayList<LIRInstruction> instructions = lir.getLIRforBlock(block); for (int i = instructions.size() - 1; i >= 0; i--) { LIRInstruction inst = instructions.get(i); processInstructionBottomUp(inst); } liveInMap.put(block, currentSet); currentSet = null; for (AbstractBlockBase<?> b : block.getPredecessors()) { worklist.add(b); } } } } private static final EnumSet<OperandFlag> REGISTER_FLAG_SET = EnumSet.of(OperandFlag.REG); private S currentSet; /** * Process all values of an instruction bottom-up, i.e. definitions before usages. Values that * start or end at the current operation are not included. */ @SuppressWarnings("try") private void processInstructionBottomUp(LIRInstruction op) { DebugContext debug = lir.getDebug(); try (Indent indent = debug.logAndIndent("handle op %d, %s", op.id(), op)) { // kills op.visitEachTemp(defConsumer); op.visitEachOutput(defConsumer); if (frameMap != null && op.destroysCallerSavedRegisters()) { for (Register reg : frameMap.getRegisterConfig().getCallerSaveRegisters()) { PlatformKind kind = frameMap.getTarget().arch.getLargestStorableKind(reg.getRegisterCategory()); defConsumer.visitValue(reg.asValue(LIRKind.value(kind)), OperandMode.TEMP, REGISTER_FLAG_SET); } } // gen - values that are considered alive for this state op.visitEachAlive(useConsumer); op.visitEachState(useConsumer); // mark locations op.forEachState(stateConsumer); // gen op.visitEachInput(useConsumer); } } InstructionStateProcedure stateConsumer = new InstructionStateProcedure() { @Override public void doState(LIRInstruction inst, LIRFrameState info) { processState(inst, info, currentSet); } }; ValueConsumer useConsumer = new ValueConsumer() { @Override public void visitValue(Value operand, OperandMode mode, EnumSet<OperandFlag> flags) { if (shouldProcessValue(operand)) { // no need to insert values and derived reference DebugContext debug = lir.getDebug(); if (debug.isLogEnabled()) { debug.log("set operand: %s", operand); } currentSet.put(operand); } } }; ValueConsumer defConsumer = new ValueConsumer() { @Override public void visitValue(Value operand, OperandMode mode, EnumSet<OperandFlag> flags) { if (shouldProcessValue(operand)) { DebugContext debug = lir.getDebug(); if (debug.isLogEnabled()) { debug.log("clear operand: %s", operand); } currentSet.remove(operand); } else { assert isIllegal(operand) || !operand.getValueKind().equals(LIRKind.Illegal) || mode == OperandMode.TEMP : String.format("Illegal PlatformKind is only allowed for TEMP mode: %s, %s", operand, mode); } } }; }
gpl-2.0
amilner42/projectEuler
src/problems/Problem81.java
2282
package problems; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; //Question ----------------------------------------------------------------------------------------------------------------------- // // Refer to: https://projecteuler.net/problem=81 // //--------------------------------------------------------------------------------------------------------------------------------- // Solution correct public class Problem81 { public static void main(String[] args) throws IOException { // Read 80 by 80 board from input file as integers int[][] board = new int[80][80]; BufferedReader inputStream = new BufferedReader(new FileReader("Problem81InputFile")); try { int index = 0; String line; while((line = inputStream.readLine()) != null) { String[] temp = line.split(","); int[] result = new int[temp.length]; for(int i = 0; i < temp.length; i++) { result[i] = Integer.valueOf(temp[i]); } board[index] = result; index++; } } finally { // this finally block making sure that the inputStream closes no matter what if(inputStream != null){ inputStream.close(); } } // Go through the board updating each value for(int i = 0; i < board.length; i++) { for(int j = 0; j < board[i].length; j++) { updateValue(board , i , j); } } // Value of the bottom right number is the minimum path System.out.println(board[79][79]); } // Update the value at position [i][j] in the board by adding the minimum of the value above/left of current position // if those values exists on the board. Eg. Top row has nothing above it. private static void updateValue(int[][] board, int i, int j) { if(j == 0 && i == 0) { return; } else if(j == 0) { board[i][j] += board[i-1][j]; } else if(i == 0) { board[i][j] += board[i][j-1]; } else { board[i][j] += Math.min(board[i][j-1] , board[i-1][j]); } } }
gpl-2.0
SpoonLabs/astor
examples/math_20/src/main/java/org/apache/commons/math3/optimization/BaseMultivariateSimpleBoundsOptimizer.java
2970
/* * 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.math3.optimization; import org.apache.commons.math3.analysis.MultivariateFunction; /** * This interface is mainly intended to enforce the internal coherence of * Commons-FastMath. Users of the API are advised to base their code on * the following interfaces: * <ul> * <li>{@link org.apache.commons.math3.optimization.MultivariateOptimizer}</li> * <li>{@link org.apache.commons.math3.optimization.MultivariateDifferentiableOptimizer}</li> * </ul> * * @param <FUNC> Type of the objective function to be optimized. * * @version $Id$ * @since 3.0 */ public interface BaseMultivariateSimpleBoundsOptimizer<FUNC extends MultivariateFunction> extends BaseMultivariateOptimizer<FUNC> { /** * Optimize an objective function. * * @param f Objective function. * @param goalType Type of optimization goal: either * {@link GoalType#MAXIMIZE} or {@link GoalType#MINIMIZE}. * @param startPoint Start point for optimization. * @param maxEval Maximum number of function evaluations. * @param lowerBound Lower bound for each of the parameters. * @param upperBound Upper bound for each of the parameters. * @return the point/value pair giving the optimal value for objective * function. * @throws org.apache.commons.math3.exception.DimensionMismatchException * if the array sizes are wrong. * @throws org.apache.commons.math3.exception.TooManyEvaluationsException * if the maximal number of evaluations is exceeded. * @throws org.apache.commons.math3.exception.NullArgumentException if * {@code f}, {@code goalType} or {@code startPoint} is {@code null}. * @throws org.apache.commons.math3.exception.NumberIsTooSmallException if any * of the initial values is less than its lower bound. * @throws org.apache.commons.math3.exception.NumberIsTooLargeException if any * of the initial values is greater than its upper bound. */ PointValuePair optimize(int maxEval, FUNC f, GoalType goalType, double[] startPoint, double[] lowerBound, double[] upperBound); }
gpl-2.0
FauxFaux/jdk9-jdk
src/java.desktop/share/classes/sun/awt/NullComponentPeer.java
7790
/* * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.awt; import java.awt.AWTException; import java.awt.BufferCapabilities; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.GraphicsConfiguration; import java.awt.Image; import java.awt.Insets; import java.awt.event.FocusEvent.Cause; import java.awt.Point; import java.awt.Event; import java.awt.event.PaintEvent; import java.awt.image.ColorModel; import java.awt.image.ImageObserver; import java.awt.image.ImageProducer; import java.awt.image.VolatileImage; import java.awt.peer.CanvasPeer; import java.awt.peer.LightweightPeer; import java.awt.peer.PanelPeer; import java.awt.peer.ComponentPeer; import java.awt.peer.ContainerPeer; import java.awt.Rectangle; import sun.java2d.pipe.Region; /** * Implements the LightweightPeer interface for use in lightweight components * that have no native window associated with them. This gets created by * default in Component so that Component and Container can be directly * extended to create useful components written entirely in java. These * components must be hosted somewhere higher up in the component tree by a * native container (such as a Frame). * * This implementation provides no useful semantics and serves only as a * marker. One could provide alternative implementations in java that do * something useful for some of the other peer interfaces to minimize the * native code. * * This was renamed from java.awt.LightweightPeer (a horrible and confusing * name) and moved from java.awt.Toolkit into sun.awt as a public class in * its own file. * * @author Timothy Prinzing * @author Michael Martak */ public class NullComponentPeer implements LightweightPeer, CanvasPeer, PanelPeer { public boolean isObscured() { return false; } public boolean canDetermineObscurity() { return false; } public boolean isFocusable() { return false; } public void setVisible(boolean b) { } public void show() { } public void hide() { } public void setEnabled(boolean b) { } public void enable() { } public void disable() { } public void paint(Graphics g) { } public void repaint(long tm, int x, int y, int width, int height) { } public void print(Graphics g) { } public void setBounds(int x, int y, int width, int height, int op) { } public void reshape(int x, int y, int width, int height) { } public void coalescePaintEvent(PaintEvent e) { } public boolean handleEvent(Event e) { return false; } public void handleEvent(java.awt.AWTEvent arg0) { } public Dimension getPreferredSize() { return new Dimension(1,1); } public Dimension getMinimumSize() { return new Dimension(1,1); } public ColorModel getColorModel() { return null; } public Graphics getGraphics() { return null; } public GraphicsConfiguration getGraphicsConfiguration() { return null; } public FontMetrics getFontMetrics(Font font) { return null; } public void dispose() { // no native code } public void setForeground(Color c) { } public void setBackground(Color c) { } public void setFont(Font f) { } public void updateCursorImmediately() { } public void setCursor(Cursor cursor) { } public boolean requestFocus (Component lightweightChild, boolean temporary, boolean focusedWindowChangeAllowed, long time, Cause cause) { return false; } public Image createImage(ImageProducer producer) { return null; } public Image createImage(int width, int height) { return null; } public boolean prepareImage(Image img, int w, int h, ImageObserver o) { return false; } public int checkImage(Image img, int w, int h, ImageObserver o) { return 0; } public Dimension preferredSize() { return getPreferredSize(); } public Dimension minimumSize() { return getMinimumSize(); } public Point getLocationOnScreen() { return new Point(0,0); } public Insets getInsets() { return insets(); } public void beginValidate() { } public void endValidate() { } public Insets insets() { return new Insets(0, 0, 0, 0); } public boolean isPaintPending() { return false; } public boolean handlesWheelScrolling() { return false; } public VolatileImage createVolatileImage(int width, int height) { return null; } public void beginLayout() { } public void endLayout() { } public void createBuffers(int numBuffers, BufferCapabilities caps) throws AWTException { throw new AWTException( "Page-flipping is not allowed on a lightweight component"); } public Image getBackBuffer() { throw new IllegalStateException( "Page-flipping is not allowed on a lightweight component"); } public void flip(int x1, int y1, int x2, int y2, BufferCapabilities.FlipContents flipAction) { throw new IllegalStateException( "Page-flipping is not allowed on a lightweight component"); } public void destroyBuffers() { } /** * @see java.awt.peer.ComponentPeer#isReparentSupported */ public boolean isReparentSupported() { return false; } /** * @see java.awt.peer.ComponentPeer#reparent */ public void reparent(ContainerPeer newNativeParent) { throw new UnsupportedOperationException(); } public void layout() { } public Rectangle getBounds() { return new Rectangle(0, 0, 0, 0); } /** * Applies the shape to the native component window. * @since 1.7 */ public void applyShape(Region shape) { } /** * Lowers this component at the bottom of the above HW peer. If the above parameter * is null then the method places this component at the top of the Z-order. */ public void setZOrder(ComponentPeer above) { } public boolean updateGraphicsData(GraphicsConfiguration gc) { return false; } public GraphicsConfiguration getAppropriateGraphicsConfiguration( GraphicsConfiguration gc) { return gc; } }
gpl-2.0
nickhargreaves/CitizenReporter
WordPress/src/main/java/org/codeforafrica/citizenreporter/starreports/ui/stats/models/CommentFollowersModel.java
1886
package org.codeforafrica.citizenreporter.starreports.ui.stats.models; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class CommentFollowersModel implements Serializable { private String mBlogID; private int mPage; private int mPages; private int mTotal; private List<SingleItemModel> mPosts; public CommentFollowersModel(String blogID, JSONObject response) throws JSONException { this.mBlogID = blogID; this.mPage = response.getInt("page"); this.mPages = response.getInt("pages"); this.mTotal = response.getInt("total"); JSONArray postsJSONArray = response.optJSONArray("posts"); if (postsJSONArray != null) { mPosts = new ArrayList<>(postsJSONArray.length()); for (int i = 0; i < postsJSONArray.length(); i++) { JSONObject currentPostJSON = postsJSONArray.getJSONObject(i); String postId = String.valueOf(currentPostJSON.getInt("id")); String title = currentPostJSON.getString("title"); int followers = currentPostJSON.getInt("followers"); String url = currentPostJSON.getString("url"); SingleItemModel currentPost = new SingleItemModel(blogID, null, postId, title, followers, url, null); mPosts.add(currentPost); } } } public String getBlogID() { return mBlogID; } public void setBlogID(String blogID) { this.mBlogID = blogID; } public List<SingleItemModel> getPosts() { return this.mPosts; } public int getTotal() { return mTotal; } public int getPage() { return mPage; } public int getPages() { return mPages; } }
gpl-2.0
rfdrake/opennms
opennms-webapp/src/main/java/org/opennms/web/rest/NotificationRestService.java
6661
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2008-2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.web.rest; import java.util.Date; import javax.ws.rs.Consumes; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.core.UriInfo; import org.opennms.core.criteria.CriteriaBuilder; import org.opennms.netmgt.dao.api.NotificationDao; import org.opennms.netmgt.model.OnmsNotification; import org.opennms.netmgt.model.OnmsNotificationCollection; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import com.sun.jersey.spi.resource.PerRequest; @Component /** * <p>NotificationRestService class.</p> * * @author ranger * @version $Id: $ * @since 1.8.1 */ @PerRequest @Scope("prototype") @Path("notifications") public class NotificationRestService extends OnmsRestService { @Autowired private NotificationDao m_notifDao; @Context UriInfo m_uriInfo; @Context SecurityContext m_securityContext; /** * <p>getNotification</p> * * @param notifId a {@link java.lang.String} object. * @return a {@link org.opennms.netmgt.model.OnmsNotification} object. */ @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Path("{notifId}") @Transactional public OnmsNotification getNotification(@PathParam("notifId") String notifId) { readLock(); try { OnmsNotification result= m_notifDao.get(new Integer(notifId)); return result; } finally { readUnlock(); } } /** * <p>getCount</p> * * @return a {@link java.lang.String} object. */ @GET @Produces(MediaType.TEXT_PLAIN) @Path("count") @Transactional public String getCount() { readLock(); try { return Integer.toString(m_notifDao.countAll()); } finally { readUnlock(); } } /** * <p>getNotifications</p> * * @return a {@link org.opennms.netmgt.model.OnmsNotificationCollection} object. */ @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Transactional public OnmsNotificationCollection getNotifications() { readLock(); try { final CriteriaBuilder builder = new CriteriaBuilder(OnmsNotification.class); applyQueryFilters(m_uriInfo.getQueryParameters(), builder); builder.orderBy("notifyId").desc(); OnmsNotificationCollection coll = new OnmsNotificationCollection(m_notifDao.findMatching(builder.toCriteria())); coll.setTotalCount(m_notifDao.countMatching(builder.count().toCriteria())); return coll; } finally { readUnlock(); } } /** * <p>updateNotification</p> * * @param notifId a {@link java.lang.String} object. * @param ack a {@link java.lang.Boolean} object. */ @PUT @Path("{notifId}") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Transactional public Response updateNotification(@PathParam("notifId") String notifId, @FormParam("ack") Boolean ack) { writeLock(); try { OnmsNotification notif=m_notifDao.get(new Integer(notifId)); if(ack==null) { throw new IllegalArgumentException("Must supply the 'ack' parameter, set to either 'true' or 'false'"); } processNotifAck(notif,ack); return Response.seeOther(m_uriInfo.getBaseUriBuilder().path(this.getClass()).path(this.getClass(), "getNotification").build(notifId)).build(); } finally { writeUnlock(); } } /** * <p>updateNotifications</p> * * @param params a {@link org.opennms.web.rest.MultivaluedMapImpl} object. */ @PUT @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Transactional public Response updateNotifications(final MultivaluedMapImpl params) { writeLock(); try { Boolean ack=false; if(params.containsKey("ack")) { ack="true".equals(params.getFirst("ack")); params.remove("ack"); } final CriteriaBuilder builder = new CriteriaBuilder(OnmsNotification.class); applyQueryFilters(params, builder); for (final OnmsNotification notif : m_notifDao.findMatching(builder.toCriteria())) { processNotifAck(notif, ack); } return Response.seeOther(m_uriInfo.getBaseUriBuilder().path(this.getClass()).path(this.getClass(), "getNotifications").build()).build(); } finally { writeUnlock(); } } private void processNotifAck(final OnmsNotification notif, final Boolean ack) { if(ack) { notif.setRespondTime(new Date()); notif.setAnsweredBy(m_securityContext.getUserPrincipal().getName()); } else { notif.setRespondTime(null); notif.setAnsweredBy(null); } m_notifDao.save(notif); } }
gpl-2.0
CharlesZ-Chen/checker-framework
checker/tests/src/tests/IndexTest.java
641
package tests; import java.io.File; import java.util.List; import org.checkerframework.framework.test.CheckerFrameworkPerDirectoryTest; import org.junit.runners.Parameterized.Parameters; /** JUnit tests for the Index Checker. */ public class IndexTest extends CheckerFrameworkPerDirectoryTest { public IndexTest(List<File> testFiles) { super( testFiles, org.checkerframework.checker.index.IndexChecker.class, "index", "-Anomsgtext"); } @Parameters public static String[] getTestDirs() { return new String[] {"index", "all-systems"}; } }
gpl-2.0
xlee00/Telegram
TMessagesProj/src/main/java/org/telegram/messenger/SecretChatHelper.java
104602
/* * This is the source code of Telegram for Android v. 2.0.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2016. */ package org.telegram.messenger; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import org.telegram.tgnet.AbstractSerializedData; import org.telegram.tgnet.ConnectionsManager; import org.telegram.tgnet.NativeByteBuffer; import org.telegram.tgnet.RequestDelegate; import org.telegram.tgnet.TLClassStore; import org.telegram.tgnet.TLObject; import org.telegram.tgnet.TLRPC; import java.io.File; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.concurrent.ConcurrentHashMap; public class SecretChatHelper { public static class TL_decryptedMessageHolder extends TLObject { public static int constructor = 0x555555F9; public long random_id; public int date; public TLRPC.TL_decryptedMessageLayer layer; public TLRPC.EncryptedFile file; public boolean new_key_used; public void readParams(AbstractSerializedData stream, boolean exception) { random_id = stream.readInt64(exception); date = stream.readInt32(exception); layer = TLRPC.TL_decryptedMessageLayer.TLdeserialize(stream, stream.readInt32(exception), exception); if (stream.readBool(exception)) { file = TLRPC.EncryptedFile.TLdeserialize(stream, stream.readInt32(exception), exception); } new_key_used = stream.readBool(exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt64(random_id); stream.writeInt32(date); layer.serializeToStream(stream); stream.writeBool(file != null); if (file != null) { file.serializeToStream(stream); } stream.writeBool(new_key_used); } } public static final int CURRENT_SECRET_CHAT_LAYER = 46; private ArrayList<Integer> sendingNotifyLayer = new ArrayList<>(); private HashMap<Integer, ArrayList<TL_decryptedMessageHolder>> secretHolesQueue = new HashMap<>(); private HashMap<Integer, TLRPC.EncryptedChat> acceptingChats = new HashMap<>(); public ArrayList<TLRPC.Update> delayedEncryptedChatUpdates = new ArrayList<>(); private ArrayList<Long> pendingEncMessagesToDelete = new ArrayList<>(); private boolean startingSecretChat = false; private static volatile SecretChatHelper Instance = null; public static SecretChatHelper getInstance() { SecretChatHelper localInstance = Instance; if (localInstance == null) { synchronized (SecretChatHelper.class) { localInstance = Instance; if (localInstance == null) { Instance = localInstance = new SecretChatHelper(); } } } return localInstance; } public void cleanUp() { sendingNotifyLayer.clear(); acceptingChats.clear(); secretHolesQueue.clear(); delayedEncryptedChatUpdates.clear(); pendingEncMessagesToDelete.clear(); startingSecretChat = false; } protected void processPendingEncMessages() { if (!pendingEncMessagesToDelete.isEmpty()) { final ArrayList<Long> pendingEncMessagesToDeleteCopy = new ArrayList<>(pendingEncMessagesToDelete); AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { for (int a = 0; a < pendingEncMessagesToDeleteCopy.size(); a++) { MessageObject messageObject = MessagesController.getInstance().dialogMessagesByRandomIds.get(pendingEncMessagesToDeleteCopy.get(a)); if (messageObject != null) { messageObject.deleted = true; } } } }); ArrayList<Long> arr = new ArrayList<>(pendingEncMessagesToDelete); MessagesStorage.getInstance().markMessagesAsDeletedByRandoms(arr); pendingEncMessagesToDelete.clear(); } } private TLRPC.TL_messageService createServiceSecretMessage(final TLRPC.EncryptedChat encryptedChat, TLRPC.DecryptedMessageAction decryptedMessage) { TLRPC.TL_messageService newMsg = new TLRPC.TL_messageService(); newMsg.action = new TLRPC.TL_messageEncryptedAction(); newMsg.action.encryptedAction = decryptedMessage; newMsg.local_id = newMsg.id = UserConfig.getNewMessageId(); newMsg.from_id = UserConfig.getClientUserId(); newMsg.unread = true; newMsg.out = true; newMsg.flags = TLRPC.MESSAGE_FLAG_HAS_FROM_ID; newMsg.dialog_id = ((long) encryptedChat.id) << 32; newMsg.to_id = new TLRPC.TL_peerUser(); newMsg.send_state = MessageObject.MESSAGE_SEND_STATE_SENDING; if (encryptedChat.participant_id == UserConfig.getClientUserId()) { newMsg.to_id.user_id = encryptedChat.admin_id; } else { newMsg.to_id.user_id = encryptedChat.participant_id; } if (decryptedMessage instanceof TLRPC.TL_decryptedMessageActionScreenshotMessages || decryptedMessage instanceof TLRPC.TL_decryptedMessageActionSetMessageTTL) { newMsg.date = ConnectionsManager.getInstance().getCurrentTime(); } else { newMsg.date = 0; } newMsg.random_id = SendMessagesHelper.getInstance().getNextRandomId(); UserConfig.saveConfig(false); ArrayList<TLRPC.Message> arr = new ArrayList<>(); arr.add(newMsg); MessagesStorage.getInstance().putMessages(arr, false, true, true, 0); return newMsg; } public void sendMessagesReadMessage(TLRPC.EncryptedChat encryptedChat, ArrayList<Long> random_ids, TLRPC.Message resendMessage) { if (!(encryptedChat instanceof TLRPC.TL_encryptedChat)) { return; } TLRPC.TL_decryptedMessageService reqSend; if (AndroidUtilities.getPeerLayerVersion(encryptedChat.layer) >= 17) { reqSend = new TLRPC.TL_decryptedMessageService(); } else { reqSend = new TLRPC.TL_decryptedMessageService_layer8(); reqSend.random_bytes = new byte[15]; Utilities.random.nextBytes(reqSend.random_bytes); } TLRPC.Message message; if (resendMessage != null) { message = resendMessage; reqSend.action = message.action.encryptedAction; } else { reqSend.action = new TLRPC.TL_decryptedMessageActionReadMessages(); reqSend.action.random_ids = random_ids; message = createServiceSecretMessage(encryptedChat, reqSend.action); } reqSend.random_id = message.random_id; performSendEncryptedRequest(reqSend, message, encryptedChat, null, null, null); } protected void processUpdateEncryption(TLRPC.TL_updateEncryption update, ConcurrentHashMap<Integer, TLRPC.User> usersDict) { final TLRPC.EncryptedChat newChat = update.chat; long dialog_id = ((long) newChat.id) << 32; TLRPC.EncryptedChat existingChat = MessagesController.getInstance().getEncryptedChatDB(newChat.id); if (newChat instanceof TLRPC.TL_encryptedChatRequested && existingChat == null) { int user_id = newChat.participant_id; if (user_id == UserConfig.getClientUserId()) { user_id = newChat.admin_id; } TLRPC.User user = MessagesController.getInstance().getUser(user_id); if (user == null) { user = usersDict.get(user_id); } newChat.user_id = user_id; final TLRPC.Dialog dialog = new TLRPC.TL_dialog(); dialog.id = dialog_id; dialog.unread_count = 0; dialog.top_message = 0; dialog.last_message_date = update.date; AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { MessagesController.getInstance().dialogs_dict.put(dialog.id, dialog); MessagesController.getInstance().dialogs.add(dialog); MessagesController.getInstance().putEncryptedChat(newChat, false); Collections.sort(MessagesController.getInstance().dialogs, new Comparator<TLRPC.Dialog>() { @Override public int compare(TLRPC.Dialog tl_dialog, TLRPC.Dialog tl_dialog2) { if (tl_dialog.last_message_date == tl_dialog2.last_message_date) { return 0; } else if (tl_dialog.last_message_date < tl_dialog2.last_message_date) { return 1; } else { return -1; } } }); NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); } }); MessagesStorage.getInstance().putEncryptedChat(newChat, user, dialog); SecretChatHelper.getInstance().acceptSecretChat(newChat); } else if (newChat instanceof TLRPC.TL_encryptedChat) { if (existingChat != null && existingChat instanceof TLRPC.TL_encryptedChatWaiting && (existingChat.auth_key == null || existingChat.auth_key.length == 1)) { newChat.a_or_b = existingChat.a_or_b; newChat.user_id = existingChat.user_id; SecretChatHelper.getInstance().processAcceptedSecretChat(newChat); } else if (existingChat == null && startingSecretChat) { delayedEncryptedChatUpdates.add(update); } } else { final TLRPC.EncryptedChat exist = existingChat; if (exist != null) { newChat.user_id = exist.user_id; newChat.auth_key = exist.auth_key; newChat.key_create_date = exist.key_create_date; newChat.key_use_count_in = exist.key_use_count_in; newChat.key_use_count_out = exist.key_use_count_out; newChat.ttl = exist.ttl; newChat.seq_in = exist.seq_in; newChat.seq_out = exist.seq_out; } AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { if (exist != null) { MessagesController.getInstance().putEncryptedChat(newChat, false); } MessagesStorage.getInstance().updateEncryptedChat(newChat); NotificationCenter.getInstance().postNotificationName(NotificationCenter.encryptedChatUpdated, newChat); } }); } } public void sendMessagesDeleteMessage(TLRPC.EncryptedChat encryptedChat, ArrayList<Long> random_ids, TLRPC.Message resendMessage) { if (!(encryptedChat instanceof TLRPC.TL_encryptedChat)) { return; } TLRPC.TL_decryptedMessageService reqSend; if (AndroidUtilities.getPeerLayerVersion(encryptedChat.layer) >= 17) { reqSend = new TLRPC.TL_decryptedMessageService(); } else { reqSend = new TLRPC.TL_decryptedMessageService_layer8(); reqSend.random_bytes = new byte[15]; Utilities.random.nextBytes(reqSend.random_bytes); } TLRPC.Message message; if (resendMessage != null) { message = resendMessage; reqSend.action = message.action.encryptedAction; } else { reqSend.action = new TLRPC.TL_decryptedMessageActionDeleteMessages(); reqSend.action.random_ids = random_ids; message = createServiceSecretMessage(encryptedChat, reqSend.action); } reqSend.random_id = message.random_id; performSendEncryptedRequest(reqSend, message, encryptedChat, null, null, null); } public void sendClearHistoryMessage(TLRPC.EncryptedChat encryptedChat, TLRPC.Message resendMessage) { if (!(encryptedChat instanceof TLRPC.TL_encryptedChat)) { return; } TLRPC.TL_decryptedMessageService reqSend; if (AndroidUtilities.getPeerLayerVersion(encryptedChat.layer) >= 17) { reqSend = new TLRPC.TL_decryptedMessageService(); } else { reqSend = new TLRPC.TL_decryptedMessageService_layer8(); reqSend.random_bytes = new byte[15]; Utilities.random.nextBytes(reqSend.random_bytes); } TLRPC.Message message; if (resendMessage != null) { message = resendMessage; reqSend.action = message.action.encryptedAction; } else { reqSend.action = new TLRPC.TL_decryptedMessageActionFlushHistory(); message = createServiceSecretMessage(encryptedChat, reqSend.action); } reqSend.random_id = message.random_id; performSendEncryptedRequest(reqSend, message, encryptedChat, null, null, null); } public void sendNotifyLayerMessage(final TLRPC.EncryptedChat encryptedChat, TLRPC.Message resendMessage) { if (!(encryptedChat instanceof TLRPC.TL_encryptedChat)) { return; } if (sendingNotifyLayer.contains(encryptedChat.id)) { return; } sendingNotifyLayer.add(encryptedChat.id); TLRPC.TL_decryptedMessageService reqSend; if (AndroidUtilities.getPeerLayerVersion(encryptedChat.layer) >= 17) { reqSend = new TLRPC.TL_decryptedMessageService(); } else { reqSend = new TLRPC.TL_decryptedMessageService_layer8(); reqSend.random_bytes = new byte[15]; Utilities.random.nextBytes(reqSend.random_bytes); } TLRPC.Message message; if (resendMessage != null) { message = resendMessage; reqSend.action = message.action.encryptedAction; } else { reqSend.action = new TLRPC.TL_decryptedMessageActionNotifyLayer(); reqSend.action.layer = CURRENT_SECRET_CHAT_LAYER; message = createServiceSecretMessage(encryptedChat, reqSend.action); } reqSend.random_id = message.random_id; performSendEncryptedRequest(reqSend, message, encryptedChat, null, null, null); } public void sendRequestKeyMessage(final TLRPC.EncryptedChat encryptedChat, TLRPC.Message resendMessage) { if (!(encryptedChat instanceof TLRPC.TL_encryptedChat)) { return; } TLRPC.TL_decryptedMessageService reqSend; if (AndroidUtilities.getPeerLayerVersion(encryptedChat.layer) >= 17) { reqSend = new TLRPC.TL_decryptedMessageService(); } else { reqSend = new TLRPC.TL_decryptedMessageService_layer8(); reqSend.random_bytes = new byte[15]; Utilities.random.nextBytes(reqSend.random_bytes); } TLRPC.Message message; if (resendMessage != null) { message = resendMessage; reqSend.action = message.action.encryptedAction; } else { reqSend.action = new TLRPC.TL_decryptedMessageActionRequestKey(); reqSend.action.exchange_id = encryptedChat.exchange_id; reqSend.action.g_a = encryptedChat.g_a; message = createServiceSecretMessage(encryptedChat, reqSend.action); } reqSend.random_id = message.random_id; performSendEncryptedRequest(reqSend, message, encryptedChat, null, null, null); } public void sendAcceptKeyMessage(final TLRPC.EncryptedChat encryptedChat, TLRPC.Message resendMessage) { if (!(encryptedChat instanceof TLRPC.TL_encryptedChat)) { return; } TLRPC.TL_decryptedMessageService reqSend; if (AndroidUtilities.getPeerLayerVersion(encryptedChat.layer) >= 17) { reqSend = new TLRPC.TL_decryptedMessageService(); } else { reqSend = new TLRPC.TL_decryptedMessageService_layer8(); reqSend.random_bytes = new byte[15]; Utilities.random.nextBytes(reqSend.random_bytes); } TLRPC.Message message; if (resendMessage != null) { message = resendMessage; reqSend.action = message.action.encryptedAction; } else { reqSend.action = new TLRPC.TL_decryptedMessageActionAcceptKey(); reqSend.action.exchange_id = encryptedChat.exchange_id; reqSend.action.key_fingerprint = encryptedChat.future_key_fingerprint; reqSend.action.g_b = encryptedChat.g_a_or_b; message = createServiceSecretMessage(encryptedChat, reqSend.action); } reqSend.random_id = message.random_id; performSendEncryptedRequest(reqSend, message, encryptedChat, null, null, null); } public void sendCommitKeyMessage(final TLRPC.EncryptedChat encryptedChat, TLRPC.Message resendMessage) { if (!(encryptedChat instanceof TLRPC.TL_encryptedChat)) { return; } TLRPC.TL_decryptedMessageService reqSend; if (AndroidUtilities.getPeerLayerVersion(encryptedChat.layer) >= 17) { reqSend = new TLRPC.TL_decryptedMessageService(); } else { reqSend = new TLRPC.TL_decryptedMessageService_layer8(); reqSend.random_bytes = new byte[15]; Utilities.random.nextBytes(reqSend.random_bytes); } TLRPC.Message message; if (resendMessage != null) { message = resendMessage; reqSend.action = message.action.encryptedAction; } else { reqSend.action = new TLRPC.TL_decryptedMessageActionCommitKey(); reqSend.action.exchange_id = encryptedChat.exchange_id; reqSend.action.key_fingerprint = encryptedChat.future_key_fingerprint; message = createServiceSecretMessage(encryptedChat, reqSend.action); } reqSend.random_id = message.random_id; performSendEncryptedRequest(reqSend, message, encryptedChat, null, null, null); } public void sendAbortKeyMessage(final TLRPC.EncryptedChat encryptedChat, TLRPC.Message resendMessage, long excange_id) { if (!(encryptedChat instanceof TLRPC.TL_encryptedChat)) { return; } TLRPC.TL_decryptedMessageService reqSend; if (AndroidUtilities.getPeerLayerVersion(encryptedChat.layer) >= 17) { reqSend = new TLRPC.TL_decryptedMessageService(); } else { reqSend = new TLRPC.TL_decryptedMessageService_layer8(); reqSend.random_bytes = new byte[15]; Utilities.random.nextBytes(reqSend.random_bytes); } TLRPC.Message message; if (resendMessage != null) { message = resendMessage; reqSend.action = message.action.encryptedAction; } else { reqSend.action = new TLRPC.TL_decryptedMessageActionAbortKey(); reqSend.action.exchange_id = excange_id; message = createServiceSecretMessage(encryptedChat, reqSend.action); } reqSend.random_id = message.random_id; performSendEncryptedRequest(reqSend, message, encryptedChat, null, null, null); } public void sendNoopMessage(final TLRPC.EncryptedChat encryptedChat, TLRPC.Message resendMessage) { if (!(encryptedChat instanceof TLRPC.TL_encryptedChat)) { return; } TLRPC.TL_decryptedMessageService reqSend; if (AndroidUtilities.getPeerLayerVersion(encryptedChat.layer) >= 17) { reqSend = new TLRPC.TL_decryptedMessageService(); } else { reqSend = new TLRPC.TL_decryptedMessageService_layer8(); reqSend.random_bytes = new byte[15]; Utilities.random.nextBytes(reqSend.random_bytes); } TLRPC.Message message; if (resendMessage != null) { message = resendMessage; reqSend.action = message.action.encryptedAction; } else { reqSend.action = new TLRPC.TL_decryptedMessageActionNoop(); message = createServiceSecretMessage(encryptedChat, reqSend.action); } reqSend.random_id = message.random_id; performSendEncryptedRequest(reqSend, message, encryptedChat, null, null, null); } public void sendTTLMessage(TLRPC.EncryptedChat encryptedChat, TLRPC.Message resendMessage) { if (!(encryptedChat instanceof TLRPC.TL_encryptedChat)) { return; } TLRPC.TL_decryptedMessageService reqSend; if (AndroidUtilities.getPeerLayerVersion(encryptedChat.layer) >= 17) { reqSend = new TLRPC.TL_decryptedMessageService(); } else { reqSend = new TLRPC.TL_decryptedMessageService_layer8(); reqSend.random_bytes = new byte[15]; Utilities.random.nextBytes(reqSend.random_bytes); } TLRPC.Message message; if (resendMessage != null) { message = resendMessage; reqSend.action = message.action.encryptedAction; } else { reqSend.action = new TLRPC.TL_decryptedMessageActionSetMessageTTL(); reqSend.action.ttl_seconds = encryptedChat.ttl; message = createServiceSecretMessage(encryptedChat, reqSend.action); MessageObject newMsgObj = new MessageObject(message, null, false); newMsgObj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SENDING; ArrayList<MessageObject> objArr = new ArrayList<>(); objArr.add(newMsgObj); MessagesController.getInstance().updateInterfaceWithMessages(message.dialog_id, objArr); NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); } reqSend.random_id = message.random_id; performSendEncryptedRequest(reqSend, message, encryptedChat, null, null, null); } public void sendScreenshotMessage(TLRPC.EncryptedChat encryptedChat, ArrayList<Long> random_ids, TLRPC.Message resendMessage) { if (!(encryptedChat instanceof TLRPC.TL_encryptedChat)) { return; } TLRPC.TL_decryptedMessageService reqSend; if (AndroidUtilities.getPeerLayerVersion(encryptedChat.layer) >= 17) { reqSend = new TLRPC.TL_decryptedMessageService(); } else { reqSend = new TLRPC.TL_decryptedMessageService_layer8(); reqSend.random_bytes = new byte[15]; Utilities.random.nextBytes(reqSend.random_bytes); } TLRPC.Message message; if (resendMessage != null) { message = resendMessage; reqSend.action = message.action.encryptedAction; } else { reqSend.action = new TLRPC.TL_decryptedMessageActionScreenshotMessages(); reqSend.action.random_ids = random_ids; message = createServiceSecretMessage(encryptedChat, reqSend.action); MessageObject newMsgObj = new MessageObject(message, null, false); newMsgObj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SENDING; ArrayList<MessageObject> objArr = new ArrayList<>(); objArr.add(newMsgObj); MessagesController.getInstance().updateInterfaceWithMessages(message.dialog_id, objArr); NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); } reqSend.random_id = message.random_id; performSendEncryptedRequest(reqSend, message, encryptedChat, null, null, null); } private void updateMediaPaths(MessageObject newMsgObj, TLRPC.EncryptedFile file, TLRPC.DecryptedMessage decryptedMessage, String originalPath) { TLRPC.Message newMsg = newMsgObj.messageOwner; if (file != null) { if (newMsg.media instanceof TLRPC.TL_messageMediaPhoto && newMsg.media.photo != null) { TLRPC.PhotoSize size = newMsg.media.photo.sizes.get(newMsg.media.photo.sizes.size() - 1); String fileName = size.location.volume_id + "_" + size.location.local_id; size.location = new TLRPC.TL_fileEncryptedLocation(); size.location.key = decryptedMessage.media.key; size.location.iv = decryptedMessage.media.iv; size.location.dc_id = file.dc_id; size.location.volume_id = file.id; size.location.secret = file.access_hash; size.location.local_id = file.key_fingerprint; String fileName2 = size.location.volume_id + "_" + size.location.local_id; File cacheFile = new File(FileLoader.getInstance().getDirectory(FileLoader.MEDIA_DIR_CACHE), fileName + ".jpg"); File cacheFile2 = FileLoader.getPathToAttach(size); cacheFile.renameTo(cacheFile2); ImageLoader.getInstance().replaceImageInCache(fileName, fileName2, size.location, true); ArrayList<TLRPC.Message> arr = new ArrayList<>(); arr.add(newMsg); MessagesStorage.getInstance().putMessages(arr, false, true, false, 0); //MessagesStorage.getInstance().putSentFile(originalPath, newMsg.media.photo, 3); } else if (newMsg.media instanceof TLRPC.TL_messageMediaDocument && newMsg.media.document != null) { TLRPC.Document document = newMsg.media.document; newMsg.media.document = new TLRPC.TL_documentEncrypted(); newMsg.media.document.id = file.id; newMsg.media.document.access_hash = file.access_hash; newMsg.media.document.date = document.date; newMsg.media.document.attributes = document.attributes; newMsg.media.document.mime_type = document.mime_type; newMsg.media.document.size = file.size; newMsg.media.document.key = decryptedMessage.media.key; newMsg.media.document.iv = decryptedMessage.media.iv; newMsg.media.document.thumb = document.thumb; newMsg.media.document.dc_id = file.dc_id; newMsg.media.document.caption = document.caption != null ? document.caption : ""; if (newMsg.attachPath != null && newMsg.attachPath.startsWith(FileLoader.getInstance().getDirectory(FileLoader.MEDIA_DIR_CACHE).getAbsolutePath())) { File cacheFile = new File(newMsg.attachPath); File cacheFile2 = FileLoader.getPathToAttach(newMsg.media.document); if (cacheFile.renameTo(cacheFile2)) { newMsgObj.mediaExists = newMsgObj.attachPathExists; newMsgObj.attachPathExists = false; newMsg.attachPath = ""; } } /*String fileName = audio.dc_id + "_" + audio.id + ".ogg"; TODO check String fileName2 = newMsg.media.audio.dc_id + "_" + newMsg.media.audio.id + ".ogg"; if (!fileName.equals(fileName2)) { File cacheFile = new File(FileLoader.getInstance().getDirectory(FileLoader.MEDIA_DIR_CACHE), fileName); File cacheFile2 = FileLoader.getPathToAttach(newMsg.media.audio); if (cacheFile.renameTo(cacheFile2)) { newMsg.attachPath = ""; } }*/ ArrayList<TLRPC.Message> arr = new ArrayList<>(); arr.add(newMsg); MessagesStorage.getInstance().putMessages(arr, false, true, false, 0); //MessagesStorage.getInstance().putSentFile(originalPath, newMsg.media.document, 4); document //MessagesStorage.getInstance().putSentFile(originalPath, newMsg.media.video, 5); video } } } public static boolean isSecretVisibleMessage(TLRPC.Message message) { return message.action instanceof TLRPC.TL_messageEncryptedAction && (message.action.encryptedAction instanceof TLRPC.TL_decryptedMessageActionScreenshotMessages || message.action.encryptedAction instanceof TLRPC.TL_decryptedMessageActionSetMessageTTL); } public static boolean isSecretInvisibleMessage(TLRPC.Message message) { return message.action instanceof TLRPC.TL_messageEncryptedAction && !(message.action.encryptedAction instanceof TLRPC.TL_decryptedMessageActionScreenshotMessages || message.action.encryptedAction instanceof TLRPC.TL_decryptedMessageActionSetMessageTTL); } protected void performSendEncryptedRequest(final TLRPC.DecryptedMessage req, final TLRPC.Message newMsgObj, final TLRPC.EncryptedChat chat, final TLRPC.InputEncryptedFile encryptedFile, final String originalPath, final MessageObject newMsg) { if (req == null || chat.auth_key == null || chat instanceof TLRPC.TL_encryptedChatRequested || chat instanceof TLRPC.TL_encryptedChatWaiting) { return; } SendMessagesHelper.getInstance().putToSendingMessages(newMsgObj); Utilities.stageQueue.postRunnable(new Runnable() { @Override public void run() { try { TLObject toEncryptObject; if (AndroidUtilities.getPeerLayerVersion(chat.layer) >= 17) { TLRPC.TL_decryptedMessageLayer layer = new TLRPC.TL_decryptedMessageLayer(); int myLayer = Math.max(17, AndroidUtilities.getMyLayerVersion(chat.layer)); layer.layer = Math.min(myLayer, AndroidUtilities.getPeerLayerVersion(chat.layer)); layer.message = req; layer.random_bytes = new byte[15]; Utilities.random.nextBytes(layer.random_bytes); toEncryptObject = layer; if (chat.seq_in == 0 && chat.seq_out == 0) { if (chat.admin_id == UserConfig.getClientUserId()) { chat.seq_out = 1; } else { chat.seq_in = 1; } } if (newMsgObj.seq_in == 0 && newMsgObj.seq_out == 0) { layer.in_seq_no = chat.seq_in; layer.out_seq_no = chat.seq_out; chat.seq_out += 2; if (AndroidUtilities.getPeerLayerVersion(chat.layer) >= 20) { if (chat.key_create_date == 0) { chat.key_create_date = ConnectionsManager.getInstance().getCurrentTime(); } chat.key_use_count_out++; if ((chat.key_use_count_out >= 100 || chat.key_create_date < ConnectionsManager.getInstance().getCurrentTime() - 60 * 60 * 24 * 7) && chat.exchange_id == 0 && chat.future_key_fingerprint == 0) { requestNewSecretChatKey(chat); } } MessagesStorage.getInstance().updateEncryptedChatSeq(chat); if (newMsgObj != null) { newMsgObj.seq_in = layer.in_seq_no; newMsgObj.seq_out = layer.out_seq_no; MessagesStorage.getInstance().setMessageSeq(newMsgObj.id, newMsgObj.seq_in, newMsgObj.seq_out); } } else { layer.in_seq_no = newMsgObj.seq_in; layer.out_seq_no = newMsgObj.seq_out; } FileLog.e("tmessages", req + " send message with in_seq = " + layer.in_seq_no + " out_seq = " + layer.out_seq_no); } else { toEncryptObject = req; } int len = toEncryptObject.getObjectSize(); NativeByteBuffer toEncrypt = new NativeByteBuffer(4 + len); toEncrypt.writeInt32(len); toEncryptObject.serializeToStream(toEncrypt); byte[] messageKeyFull = Utilities.computeSHA1(toEncrypt.buffer); byte[] messageKey = new byte[16]; if (messageKeyFull.length != 0) { System.arraycopy(messageKeyFull, messageKeyFull.length - 16, messageKey, 0, 16); } MessageKeyData keyData = MessageKeyData.generateMessageKeyData(chat.auth_key, messageKey, false); len = toEncrypt.length(); int extraLen = len % 16 != 0 ? 16 - len % 16 : 0; NativeByteBuffer dataForEncryption = new NativeByteBuffer(len + extraLen); toEncrypt.position(0); dataForEncryption.writeBytes(toEncrypt); if (extraLen != 0) { byte[] b = new byte[extraLen]; Utilities.random.nextBytes(b); dataForEncryption.writeBytes(b); } toEncrypt.reuse(); Utilities.aesIgeEncryption(dataForEncryption.buffer, keyData.aesKey, keyData.aesIv, true, false, 0, dataForEncryption.limit()); NativeByteBuffer data = new NativeByteBuffer(8 + messageKey.length + dataForEncryption.length()); dataForEncryption.position(0); data.writeInt64(chat.key_fingerprint); data.writeBytes(messageKey); data.writeBytes(dataForEncryption); dataForEncryption.reuse(); data.position(0); TLObject reqToSend; if (encryptedFile == null) { if (req instanceof TLRPC.TL_decryptedMessageService) { TLRPC.TL_messages_sendEncryptedService req2 = new TLRPC.TL_messages_sendEncryptedService(); req2.data = data; req2.random_id = req.random_id; req2.peer = new TLRPC.TL_inputEncryptedChat(); req2.peer.chat_id = chat.id; req2.peer.access_hash = chat.access_hash; reqToSend = req2; } else { TLRPC.TL_messages_sendEncrypted req2 = new TLRPC.TL_messages_sendEncrypted(); req2.data = data; req2.random_id = req.random_id; req2.peer = new TLRPC.TL_inputEncryptedChat(); req2.peer.chat_id = chat.id; req2.peer.access_hash = chat.access_hash; reqToSend = req2; } } else { TLRPC.TL_messages_sendEncryptedFile req2 = new TLRPC.TL_messages_sendEncryptedFile(); req2.data = data; req2.random_id = req.random_id; req2.peer = new TLRPC.TL_inputEncryptedChat(); req2.peer.chat_id = chat.id; req2.peer.access_hash = chat.access_hash; req2.file = encryptedFile; reqToSend = req2; } ConnectionsManager.getInstance().sendRequest(reqToSend, new RequestDelegate() { @Override public void run(TLObject response, TLRPC.TL_error error) { if (error == null) { if (req.action instanceof TLRPC.TL_decryptedMessageActionNotifyLayer) { TLRPC.EncryptedChat currentChat = MessagesController.getInstance().getEncryptedChat(chat.id); if (currentChat == null) { currentChat = chat; } if (currentChat.key_hash == null) { currentChat.key_hash = AndroidUtilities.calcAuthKeyHash(currentChat.auth_key); } if (AndroidUtilities.getPeerLayerVersion(currentChat.layer) >= 46 && currentChat.key_hash.length == 16) { try { byte[] sha256 = Utilities.computeSHA256(chat.auth_key, 0, chat.auth_key.length); byte[] key_hash = new byte[36]; System.arraycopy(chat.key_hash, 0, key_hash, 0, 16); System.arraycopy(sha256, 0, key_hash, 16, 20); currentChat.key_hash = key_hash; MessagesStorage.getInstance().updateEncryptedChat(currentChat); } catch (Throwable e) { FileLog.e("tmessages", e); } } sendingNotifyLayer.remove((Integer) currentChat.id); currentChat.layer = AndroidUtilities.setMyLayerVersion(currentChat.layer, CURRENT_SECRET_CHAT_LAYER); MessagesStorage.getInstance().updateEncryptedChatLayer(currentChat); } } if (newMsgObj != null) { if (error == null) { final String attachPath = newMsgObj.attachPath; final TLRPC.messages_SentEncryptedMessage res = (TLRPC.messages_SentEncryptedMessage) response; if (isSecretVisibleMessage(newMsgObj)) { newMsgObj.date = res.date; } if (newMsg != null && res.file instanceof TLRPC.TL_encryptedFile) { updateMediaPaths(newMsg, res.file, req, originalPath); } MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() { @Override public void run() { if (isSecretInvisibleMessage(newMsgObj)) { res.date = 0; } MessagesStorage.getInstance().updateMessageStateAndId(newMsgObj.random_id, newMsgObj.id, newMsgObj.id, res.date, false, 0); AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { newMsgObj.send_state = MessageObject.MESSAGE_SEND_STATE_SENT; NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageReceivedByServer, newMsgObj.id, newMsgObj.id, newMsgObj, newMsgObj.dialog_id); SendMessagesHelper.getInstance().processSentMessage(newMsgObj.id); if (MessageObject.isVideoMessage(newMsgObj)) { SendMessagesHelper.getInstance().stopVideoService(attachPath); } SendMessagesHelper.getInstance().removeFromSendingMessages(newMsgObj.id); } }); } }); } else { MessagesStorage.getInstance().markMessageAsSendError(newMsgObj); AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { newMsgObj.send_state = MessageObject.MESSAGE_SEND_STATE_SEND_ERROR; NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageSendError, newMsgObj.id); SendMessagesHelper.getInstance().processSentMessage(newMsgObj.id); if (MessageObject.isVideoMessage(newMsgObj)) { SendMessagesHelper.getInstance().stopVideoService(newMsgObj.attachPath); } SendMessagesHelper.getInstance().removeFromSendingMessages(newMsgObj.id); } }); } } } }, ConnectionsManager.RequestFlagInvokeAfter); } catch (Exception e) { FileLog.e("tmessages", e); } } }); } private void applyPeerLayer(final TLRPC.EncryptedChat chat, int newPeerLayer) { int currentPeerLayer = AndroidUtilities.getPeerLayerVersion(chat.layer); if (newPeerLayer <= currentPeerLayer) { return; } if (chat.key_hash.length == 16 && currentPeerLayer >= 46) { try { byte[] sha256 = Utilities.computeSHA256(chat.auth_key, 0, chat.auth_key.length); byte[] key_hash = new byte[36]; System.arraycopy(chat.key_hash, 0, key_hash, 0, 16); System.arraycopy(sha256, 0, key_hash, 16, 20); chat.key_hash = key_hash; MessagesStorage.getInstance().updateEncryptedChat(chat); } catch (Throwable e) { FileLog.e("tmessages", e); } } chat.layer = AndroidUtilities.setPeerLayerVersion(chat.layer, newPeerLayer); MessagesStorage.getInstance().updateEncryptedChatLayer(chat); if (currentPeerLayer < CURRENT_SECRET_CHAT_LAYER) { sendNotifyLayerMessage(chat, null); } AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { NotificationCenter.getInstance().postNotificationName(NotificationCenter.encryptedChatUpdated, chat); } }); } public TLRPC.Message processDecryptedObject(final TLRPC.EncryptedChat chat, final TLRPC.EncryptedFile file, int date, long random_id, TLObject object, boolean new_key_used) { if (object != null) { int from_id = chat.admin_id; if (from_id == UserConfig.getClientUserId()) { from_id = chat.participant_id; } if (AndroidUtilities.getPeerLayerVersion(chat.layer) >= 20 && chat.exchange_id == 0 && chat.future_key_fingerprint == 0 && chat.key_use_count_in >= 120) { requestNewSecretChatKey(chat); } if (chat.exchange_id == 0 && chat.future_key_fingerprint != 0 && !new_key_used) { chat.future_auth_key = new byte[256]; chat.future_key_fingerprint = 0; MessagesStorage.getInstance().updateEncryptedChat(chat); } else if (chat.exchange_id != 0 && new_key_used) { chat.key_fingerprint = chat.future_key_fingerprint; chat.auth_key = chat.future_auth_key; chat.key_create_date = ConnectionsManager.getInstance().getCurrentTime(); chat.future_auth_key = new byte[256]; chat.future_key_fingerprint = 0; chat.key_use_count_in = 0; chat.key_use_count_out = 0; chat.exchange_id = 0; MessagesStorage.getInstance().updateEncryptedChat(chat); } if (object instanceof TLRPC.TL_decryptedMessage) { TLRPC.TL_decryptedMessage decryptedMessage = (TLRPC.TL_decryptedMessage) object; TLRPC.TL_message newMessage; if (AndroidUtilities.getPeerLayerVersion(chat.layer) >= 17) { newMessage = new TLRPC.TL_message_secret(); newMessage.ttl = decryptedMessage.ttl; newMessage.entities = decryptedMessage.entities; } else { newMessage = new TLRPC.TL_message(); newMessage.ttl = chat.ttl; } newMessage.message = decryptedMessage.message; newMessage.date = date; newMessage.local_id = newMessage.id = UserConfig.getNewMessageId(); UserConfig.saveConfig(false); newMessage.from_id = from_id; newMessage.to_id = new TLRPC.TL_peerUser(); newMessage.random_id = random_id; newMessage.to_id.user_id = UserConfig.getClientUserId(); newMessage.unread = true; newMessage.flags = TLRPC.MESSAGE_FLAG_HAS_MEDIA | TLRPC.MESSAGE_FLAG_HAS_FROM_ID; if (decryptedMessage.via_bot_name != null && decryptedMessage.via_bot_name.length() > 0) { newMessage.via_bot_name = decryptedMessage.via_bot_name; newMessage.flags |= TLRPC.MESSAGE_FLAG_HAS_BOT_ID; } newMessage.dialog_id = ((long) chat.id) << 32; if (decryptedMessage.reply_to_random_id != 0) { newMessage.reply_to_random_id = decryptedMessage.reply_to_random_id; newMessage.flags |= TLRPC.MESSAGE_FLAG_REPLY; } if (decryptedMessage.media == null || decryptedMessage.media instanceof TLRPC.TL_decryptedMessageMediaEmpty) { newMessage.media = new TLRPC.TL_messageMediaEmpty(); } else if (decryptedMessage.media instanceof TLRPC.TL_decryptedMessageMediaWebPage) { newMessage.media = new TLRPC.TL_messageMediaWebPage(); newMessage.media.webpage = new TLRPC.TL_webPageUrlPending(); newMessage.media.webpage.url = decryptedMessage.media.url; } else if (decryptedMessage.media instanceof TLRPC.TL_decryptedMessageMediaContact) { newMessage.media = new TLRPC.TL_messageMediaContact(); newMessage.media.last_name = decryptedMessage.media.last_name; newMessage.media.first_name = decryptedMessage.media.first_name; newMessage.media.phone_number = decryptedMessage.media.phone_number; newMessage.media.user_id = decryptedMessage.media.user_id; } else if (decryptedMessage.media instanceof TLRPC.TL_decryptedMessageMediaGeoPoint) { newMessage.media = new TLRPC.TL_messageMediaGeo(); newMessage.media.geo = new TLRPC.TL_geoPoint(); newMessage.media.geo.lat = decryptedMessage.media.lat; newMessage.media.geo._long = decryptedMessage.media._long; } else if (decryptedMessage.media instanceof TLRPC.TL_decryptedMessageMediaPhoto) { if (decryptedMessage.media.key == null || decryptedMessage.media.key.length != 32 || decryptedMessage.media.iv == null || decryptedMessage.media.iv.length != 32) { return null; } newMessage.media = new TLRPC.TL_messageMediaPhoto(); newMessage.media.caption = decryptedMessage.media.caption != null ? decryptedMessage.media.caption : ""; newMessage.media.photo = new TLRPC.TL_photo(); newMessage.media.photo.date = newMessage.date; byte[] thumb = ((TLRPC.TL_decryptedMessageMediaPhoto) decryptedMessage.media).thumb; if (thumb != null && thumb.length != 0 && thumb.length <= 6000 && decryptedMessage.media.thumb_w <= 100 && decryptedMessage.media.thumb_h <= 100) { TLRPC.TL_photoCachedSize small = new TLRPC.TL_photoCachedSize(); small.w = decryptedMessage.media.thumb_w; small.h = decryptedMessage.media.thumb_h; small.bytes = thumb; small.type = "s"; small.location = new TLRPC.TL_fileLocationUnavailable(); newMessage.media.photo.sizes.add(small); } TLRPC.TL_photoSize big = new TLRPC.TL_photoSize(); big.w = decryptedMessage.media.w; big.h = decryptedMessage.media.h; big.type = "x"; big.size = file.size; big.location = new TLRPC.TL_fileEncryptedLocation(); big.location.key = decryptedMessage.media.key; big.location.iv = decryptedMessage.media.iv; big.location.dc_id = file.dc_id; big.location.volume_id = file.id; big.location.secret = file.access_hash; big.location.local_id = file.key_fingerprint; newMessage.media.photo.sizes.add(big); } else if (decryptedMessage.media instanceof TLRPC.TL_decryptedMessageMediaVideo) { if (decryptedMessage.media.key == null || decryptedMessage.media.key.length != 32 || decryptedMessage.media.iv == null || decryptedMessage.media.iv.length != 32) { return null; } newMessage.media = new TLRPC.TL_messageMediaDocument(); newMessage.media.document = new TLRPC.TL_documentEncrypted(); newMessage.media.document.key = decryptedMessage.media.key; newMessage.media.document.iv = decryptedMessage.media.iv; newMessage.media.document.dc_id = file.dc_id; newMessage.media.caption = decryptedMessage.media.caption != null ? decryptedMessage.media.caption : ""; newMessage.media.document.date = date; newMessage.media.document.size = file.size; newMessage.media.document.id = file.id; newMessage.media.document.access_hash = file.access_hash; newMessage.media.document.mime_type = decryptedMessage.media.mime_type; if (newMessage.media.document.mime_type == null) { newMessage.media.document.mime_type = "video/mp4"; } byte[] thumb = ((TLRPC.TL_decryptedMessageMediaVideo) decryptedMessage.media).thumb; if (thumb != null && thumb.length != 0 && thumb.length <= 6000 && decryptedMessage.media.thumb_w <= 100 && decryptedMessage.media.thumb_h <= 100) { newMessage.media.document.thumb = new TLRPC.TL_photoCachedSize(); newMessage.media.document.thumb.bytes = thumb; newMessage.media.document.thumb.w = decryptedMessage.media.thumb_w; newMessage.media.document.thumb.h = decryptedMessage.media.thumb_h; newMessage.media.document.thumb.type = "s"; newMessage.media.document.thumb.location = new TLRPC.TL_fileLocationUnavailable(); } else { newMessage.media.document.thumb = new TLRPC.TL_photoSizeEmpty(); newMessage.media.document.thumb.type = "s"; } TLRPC.TL_documentAttributeVideo attributeVideo = new TLRPC.TL_documentAttributeVideo(); attributeVideo.w = decryptedMessage.media.w; attributeVideo.h = decryptedMessage.media.h; attributeVideo.duration = decryptedMessage.media.duration; newMessage.media.document.attributes.add(attributeVideo); if (newMessage.ttl != 0) { newMessage.ttl = Math.max(decryptedMessage.media.duration + 2, newMessage.ttl); } } else if (decryptedMessage.media instanceof TLRPC.TL_decryptedMessageMediaDocument) { if (decryptedMessage.media.key == null || decryptedMessage.media.key.length != 32 || decryptedMessage.media.iv == null || decryptedMessage.media.iv.length != 32) { return null; } newMessage.media = new TLRPC.TL_messageMediaDocument(); newMessage.media.caption = decryptedMessage.media.caption != null ? decryptedMessage.media.caption : ""; newMessage.media.document = new TLRPC.TL_documentEncrypted(); newMessage.media.document.id = file.id; newMessage.media.document.access_hash = file.access_hash; newMessage.media.document.date = date; if (decryptedMessage.media instanceof TLRPC.TL_decryptedMessageMediaDocument_layer8) { TLRPC.TL_documentAttributeFilename fileName = new TLRPC.TL_documentAttributeFilename(); fileName.file_name = decryptedMessage.media.file_name; newMessage.media.document.attributes.add(fileName); } else { newMessage.media.document.attributes = decryptedMessage.media.attributes; } newMessage.media.document.mime_type = decryptedMessage.media.mime_type; newMessage.media.document.size = decryptedMessage.media.size != 0 ? Math.min(decryptedMessage.media.size, file.size) : file.size; newMessage.media.document.key = decryptedMessage.media.key; newMessage.media.document.iv = decryptedMessage.media.iv; if (newMessage.media.document.mime_type == null) { newMessage.media.document.mime_type = ""; } byte[] thumb = ((TLRPC.TL_decryptedMessageMediaDocument) decryptedMessage.media).thumb; if (thumb != null && thumb.length != 0 && thumb.length <= 6000 && decryptedMessage.media.thumb_w <= 100 && decryptedMessage.media.thumb_h <= 100) { newMessage.media.document.thumb = new TLRPC.TL_photoCachedSize(); newMessage.media.document.thumb.bytes = thumb; newMessage.media.document.thumb.w = decryptedMessage.media.thumb_w; newMessage.media.document.thumb.h = decryptedMessage.media.thumb_h; newMessage.media.document.thumb.type = "s"; newMessage.media.document.thumb.location = new TLRPC.TL_fileLocationUnavailable(); } else { newMessage.media.document.thumb = new TLRPC.TL_photoSizeEmpty(); newMessage.media.document.thumb.type = "s"; } newMessage.media.document.dc_id = file.dc_id; if (MessageObject.isVoiceMessage(newMessage)) { newMessage.media_unread = true; } } else if (decryptedMessage.media instanceof TLRPC.TL_decryptedMessageMediaExternalDocument) { newMessage.media = new TLRPC.TL_messageMediaDocument(); newMessage.media.caption = ""; newMessage.media.document = new TLRPC.TL_document(); newMessage.media.document.id = decryptedMessage.media.id; newMessage.media.document.access_hash = decryptedMessage.media.access_hash; newMessage.media.document.date = decryptedMessage.media.date; newMessage.media.document.attributes = decryptedMessage.media.attributes; newMessage.media.document.mime_type = decryptedMessage.media.mime_type; newMessage.media.document.dc_id = decryptedMessage.media.dc_id; newMessage.media.document.size = decryptedMessage.media.size; newMessage.media.document.thumb = ((TLRPC.TL_decryptedMessageMediaExternalDocument) decryptedMessage.media).thumb; if (newMessage.media.document.mime_type == null) { newMessage.media.document.mime_type = ""; } } else if (decryptedMessage.media instanceof TLRPC.TL_decryptedMessageMediaAudio) { if (decryptedMessage.media.key == null || decryptedMessage.media.key.length != 32 || decryptedMessage.media.iv == null || decryptedMessage.media.iv.length != 32) { return null; } newMessage.media = new TLRPC.TL_messageMediaDocument(); newMessage.media.document = new TLRPC.TL_documentEncrypted(); newMessage.media.document.key = decryptedMessage.media.key; newMessage.media.document.iv = decryptedMessage.media.iv; newMessage.media.document.id = file.id; newMessage.media.document.access_hash = file.access_hash; newMessage.media.document.date = date; newMessage.media.document.size = file.size; newMessage.media.document.dc_id = file.dc_id; newMessage.media.document.mime_type = decryptedMessage.media.mime_type; newMessage.media.document.thumb = new TLRPC.TL_photoSizeEmpty(); newMessage.media.document.thumb.type = "s"; newMessage.media.caption = decryptedMessage.media.caption != null ? decryptedMessage.media.caption : ""; if (newMessage.media.document.mime_type == null) { newMessage.media.document.mime_type = "audio/ogg"; } TLRPC.TL_documentAttributeAudio attributeAudio = new TLRPC.TL_documentAttributeAudio(); attributeAudio.duration = decryptedMessage.media.duration; attributeAudio.voice = true; newMessage.media.document.attributes.add(attributeAudio); if (newMessage.ttl != 0) { newMessage.ttl = Math.max(decryptedMessage.media.duration + 1, newMessage.ttl); } } else if (decryptedMessage.media instanceof TLRPC.TL_decryptedMessageMediaVenue) { newMessage.media = new TLRPC.TL_messageMediaVenue(); newMessage.media.geo = new TLRPC.TL_geoPoint(); newMessage.media.geo.lat = decryptedMessage.media.lat; newMessage.media.geo._long = decryptedMessage.media._long; newMessage.media.title = decryptedMessage.media.title; newMessage.media.address = decryptedMessage.media.address; newMessage.media.provider = decryptedMessage.media.provider; newMessage.media.venue_id = decryptedMessage.media.venue_id; } else { return null; } return newMessage; } else if (object instanceof TLRPC.TL_decryptedMessageService) { final TLRPC.TL_decryptedMessageService serviceMessage = (TLRPC.TL_decryptedMessageService) object; if (serviceMessage.action instanceof TLRPC.TL_decryptedMessageActionSetMessageTTL || serviceMessage.action instanceof TLRPC.TL_decryptedMessageActionScreenshotMessages) { TLRPC.TL_messageService newMessage = new TLRPC.TL_messageService(); if (serviceMessage.action instanceof TLRPC.TL_decryptedMessageActionSetMessageTTL) { newMessage.action = new TLRPC.TL_messageEncryptedAction(); if (serviceMessage.action.ttl_seconds < 0 || serviceMessage.action.ttl_seconds > 60 * 60 * 24 * 365) { serviceMessage.action.ttl_seconds = 60 * 60 * 24 * 365; } chat.ttl = serviceMessage.action.ttl_seconds; newMessage.action.encryptedAction = serviceMessage.action; MessagesStorage.getInstance().updateEncryptedChatTTL(chat); } else if (serviceMessage.action instanceof TLRPC.TL_decryptedMessageActionScreenshotMessages) { newMessage.action = new TLRPC.TL_messageEncryptedAction(); newMessage.action.encryptedAction = serviceMessage.action; } newMessage.local_id = newMessage.id = UserConfig.getNewMessageId(); UserConfig.saveConfig(false); newMessage.unread = true; newMessage.flags = TLRPC.MESSAGE_FLAG_HAS_FROM_ID; newMessage.date = date; newMessage.from_id = from_id; newMessage.to_id = new TLRPC.TL_peerUser(); newMessage.to_id.user_id = UserConfig.getClientUserId(); newMessage.dialog_id = ((long) chat.id) << 32; return newMessage; } else if (serviceMessage.action instanceof TLRPC.TL_decryptedMessageActionFlushHistory) { final long did = ((long) chat.id) << 32; AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { TLRPC.Dialog dialog = MessagesController.getInstance().dialogs_dict.get(did); if (dialog != null) { dialog.unread_count = 0; MessagesController.getInstance().dialogMessage.remove(dialog.id); } MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() { @Override public void run() { AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { NotificationsController.getInstance().processReadMessages(null, did, 0, Integer.MAX_VALUE, false); HashMap<Long, Integer> dialogsToUpdate = new HashMap<>(); dialogsToUpdate.put(did, 0); NotificationsController.getInstance().processDialogsUpdateRead(dialogsToUpdate); } }); } }); MessagesStorage.getInstance().deleteDialog(did, 1); NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); NotificationCenter.getInstance().postNotificationName(NotificationCenter.removeAllMessagesFromDialog, did, false); } }); return null; } else if (serviceMessage.action instanceof TLRPC.TL_decryptedMessageActionDeleteMessages) { if (!serviceMessage.action.random_ids.isEmpty()) { pendingEncMessagesToDelete.addAll(serviceMessage.action.random_ids); } return null; } else if (serviceMessage.action instanceof TLRPC.TL_decryptedMessageActionReadMessages) { if (!serviceMessage.action.random_ids.isEmpty()) { int time = ConnectionsManager.getInstance().getCurrentTime(); MessagesStorage.getInstance().createTaskForSecretChat(chat.id, time, time, 1, serviceMessage.action.random_ids); } } else if (serviceMessage.action instanceof TLRPC.TL_decryptedMessageActionNotifyLayer) { applyPeerLayer(chat, serviceMessage.action.layer); } else if (serviceMessage.action instanceof TLRPC.TL_decryptedMessageActionRequestKey) { if (chat.exchange_id != 0) { if (chat.exchange_id > serviceMessage.action.exchange_id) { FileLog.e("tmessages", "we already have request key with higher exchange_id"); return null; } else { sendAbortKeyMessage(chat, null, chat.exchange_id); } } byte[] salt = new byte[256]; Utilities.random.nextBytes(salt); BigInteger p = new BigInteger(1, MessagesStorage.secretPBytes); BigInteger g_b = BigInteger.valueOf(MessagesStorage.secretG); g_b = g_b.modPow(new BigInteger(1, salt), p); BigInteger g_a = new BigInteger(1, serviceMessage.action.g_a); if (!Utilities.isGoodGaAndGb(g_a, p)) { sendAbortKeyMessage(chat, null, serviceMessage.action.exchange_id); return null; } byte[] g_b_bytes = g_b.toByteArray(); if (g_b_bytes.length > 256) { byte[] correctedAuth = new byte[256]; System.arraycopy(g_b_bytes, 1, correctedAuth, 0, 256); g_b_bytes = correctedAuth; } g_a = g_a.modPow(new BigInteger(1, salt), p); byte[] authKey = g_a.toByteArray(); if (authKey.length > 256) { byte[] correctedAuth = new byte[256]; System.arraycopy(authKey, authKey.length - 256, correctedAuth, 0, 256); authKey = correctedAuth; } else if (authKey.length < 256) { byte[] correctedAuth = new byte[256]; System.arraycopy(authKey, 0, correctedAuth, 256 - authKey.length, authKey.length); for (int a = 0; a < 256 - authKey.length; a++) { authKey[a] = 0; } authKey = correctedAuth; } byte[] authKeyHash = Utilities.computeSHA1(authKey); byte[] authKeyId = new byte[8]; System.arraycopy(authKeyHash, authKeyHash.length - 8, authKeyId, 0, 8); chat.exchange_id = serviceMessage.action.exchange_id; chat.future_auth_key = authKey; chat.future_key_fingerprint = Utilities.bytesToLong(authKeyId); chat.g_a_or_b = g_b_bytes; MessagesStorage.getInstance().updateEncryptedChat(chat); sendAcceptKeyMessage(chat, null); } else if (serviceMessage.action instanceof TLRPC.TL_decryptedMessageActionAcceptKey) { if (chat.exchange_id == serviceMessage.action.exchange_id) { BigInteger p = new BigInteger(1, MessagesStorage.secretPBytes); BigInteger i_authKey = new BigInteger(1, serviceMessage.action.g_b); if (!Utilities.isGoodGaAndGb(i_authKey, p)) { chat.future_auth_key = new byte[256]; chat.future_key_fingerprint = 0; chat.exchange_id = 0; MessagesStorage.getInstance().updateEncryptedChat(chat); sendAbortKeyMessage(chat, null, serviceMessage.action.exchange_id); return null; } i_authKey = i_authKey.modPow(new BigInteger(1, chat.a_or_b), p); byte[] authKey = i_authKey.toByteArray(); if (authKey.length > 256) { byte[] correctedAuth = new byte[256]; System.arraycopy(authKey, authKey.length - 256, correctedAuth, 0, 256); authKey = correctedAuth; } else if (authKey.length < 256) { byte[] correctedAuth = new byte[256]; System.arraycopy(authKey, 0, correctedAuth, 256 - authKey.length, authKey.length); for (int a = 0; a < 256 - authKey.length; a++) { authKey[a] = 0; } authKey = correctedAuth; } byte[] authKeyHash = Utilities.computeSHA1(authKey); byte[] authKeyId = new byte[8]; System.arraycopy(authKeyHash, authKeyHash.length - 8, authKeyId, 0, 8); long fingerprint = Utilities.bytesToLong(authKeyId); if (serviceMessage.action.key_fingerprint == fingerprint) { chat.future_auth_key = authKey; chat.future_key_fingerprint = fingerprint; MessagesStorage.getInstance().updateEncryptedChat(chat); sendCommitKeyMessage(chat, null); } else { chat.future_auth_key = new byte[256]; chat.future_key_fingerprint = 0; chat.exchange_id = 0; MessagesStorage.getInstance().updateEncryptedChat(chat); sendAbortKeyMessage(chat, null, serviceMessage.action.exchange_id); } } else { chat.future_auth_key = new byte[256]; chat.future_key_fingerprint = 0; chat.exchange_id = 0; MessagesStorage.getInstance().updateEncryptedChat(chat); sendAbortKeyMessage(chat, null, serviceMessage.action.exchange_id); } } else if (serviceMessage.action instanceof TLRPC.TL_decryptedMessageActionCommitKey) { if (chat.exchange_id == serviceMessage.action.exchange_id && chat.future_key_fingerprint == serviceMessage.action.key_fingerprint) { long old_fingerpring = chat.key_fingerprint; byte[] old_key = chat.auth_key; chat.key_fingerprint = chat.future_key_fingerprint; chat.auth_key = chat.future_auth_key; chat.key_create_date = ConnectionsManager.getInstance().getCurrentTime(); chat.future_auth_key = old_key; chat.future_key_fingerprint = old_fingerpring; chat.key_use_count_in = 0; chat.key_use_count_out = 0; chat.exchange_id = 0; MessagesStorage.getInstance().updateEncryptedChat(chat); sendNoopMessage(chat, null); } else { chat.future_auth_key = new byte[256]; chat.future_key_fingerprint = 0; chat.exchange_id = 0; MessagesStorage.getInstance().updateEncryptedChat(chat); sendAbortKeyMessage(chat, null, serviceMessage.action.exchange_id); } } else if (serviceMessage.action instanceof TLRPC.TL_decryptedMessageActionAbortKey) { if (chat.exchange_id == serviceMessage.action.exchange_id) { chat.future_auth_key = new byte[256]; chat.future_key_fingerprint = 0; chat.exchange_id = 0; MessagesStorage.getInstance().updateEncryptedChat(chat); } } else if (serviceMessage.action instanceof TLRPC.TL_decryptedMessageActionNoop) { //do nothing } else if (serviceMessage.action instanceof TLRPC.TL_decryptedMessageActionResend) { final TLRPC.TL_encryptedChatDiscarded newChat = new TLRPC.TL_encryptedChatDiscarded(); newChat.id = chat.id; newChat.user_id = chat.user_id; newChat.auth_key = chat.auth_key; newChat.key_create_date = chat.key_create_date; newChat.key_use_count_in = chat.key_use_count_in; newChat.key_use_count_out = chat.key_use_count_out; newChat.seq_in = chat.seq_in; newChat.seq_out = chat.seq_out; MessagesStorage.getInstance().updateEncryptedChat(newChat); AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { MessagesController.getInstance().putEncryptedChat(newChat, false); NotificationCenter.getInstance().postNotificationName(NotificationCenter.encryptedChatUpdated, newChat); } }); declineSecretChat(chat.id); } else { return null; } } else { FileLog.e("tmessages", "unknown message " + object); } } else { FileLog.e("tmessages", "unknown TLObject"); } return null; } public void checkSecretHoles(TLRPC.EncryptedChat chat, ArrayList<TLRPC.Message> messages) { ArrayList<TL_decryptedMessageHolder> holes = secretHolesQueue.get(chat.id); if (holes == null) { return; } Collections.sort(holes, new Comparator<TL_decryptedMessageHolder>() { @Override public int compare(TL_decryptedMessageHolder lhs, TL_decryptedMessageHolder rhs) { if (lhs.layer.out_seq_no > rhs.layer.out_seq_no) { return 1; } else if (lhs.layer.out_seq_no < rhs.layer.out_seq_no) { return -1; } return 0; } }); boolean update = false; for (int a = 0; a < holes.size(); a++) { TL_decryptedMessageHolder holder = holes.get(a); if (holder.layer.out_seq_no == chat.seq_in || chat.seq_in == holder.layer.out_seq_no - 2) { applyPeerLayer(chat, holder.layer.layer); chat.seq_in = holder.layer.out_seq_no; holes.remove(a); a--; update = true; TLRPC.Message message = processDecryptedObject(chat, holder.file, holder.date, holder.random_id, holder.layer.message, holder.new_key_used); if (message != null) { messages.add(message); } } else { break; } } if (holes.isEmpty()) { secretHolesQueue.remove(chat.id); } if (update) { MessagesStorage.getInstance().updateEncryptedChatSeq(chat); } } protected ArrayList<TLRPC.Message> decryptMessage(TLRPC.EncryptedMessage message) { final TLRPC.EncryptedChat chat = MessagesController.getInstance().getEncryptedChatDB(message.chat_id); if (chat == null || chat instanceof TLRPC.TL_encryptedChatDiscarded) { return null; } try { NativeByteBuffer is = new NativeByteBuffer(message.bytes.length); is.writeBytes(message.bytes); is.position(0); long fingerprint = is.readInt64(false); byte[] keyToDecrypt = null; boolean new_key_used = false; if (chat.key_fingerprint == fingerprint) { keyToDecrypt = chat.auth_key; } else if (chat.future_key_fingerprint != 0 && chat.future_key_fingerprint == fingerprint) { keyToDecrypt = chat.future_auth_key; new_key_used = true; } if (keyToDecrypt != null) { byte[] messageKey = is.readData(16, false); MessageKeyData keyData = MessageKeyData.generateMessageKeyData(keyToDecrypt, messageKey, false); Utilities.aesIgeEncryption(is.buffer, keyData.aesKey, keyData.aesIv, false, false, 24, is.limit() - 24); int len = is.readInt32(false); if (len < 0 || len > is.limit() - 28) { return null; } byte[] messageKeyFull = Utilities.computeSHA1(is.buffer, 24, Math.min(len + 4 + 24, is.buffer.limit())); if (!Utilities.arraysEquals(messageKey, 0, messageKeyFull, messageKeyFull.length - 16)) { return null; } TLObject object = TLClassStore.Instance().TLdeserialize(is, is.readInt32(false), false); is.reuse(); if (!new_key_used && AndroidUtilities.getPeerLayerVersion(chat.layer) >= 20) { chat.key_use_count_in++; } if (object instanceof TLRPC.TL_decryptedMessageLayer) { final TLRPC.TL_decryptedMessageLayer layer = (TLRPC.TL_decryptedMessageLayer) object; if (chat.seq_in == 0 && chat.seq_out == 0) { if (chat.admin_id == UserConfig.getClientUserId()) { chat.seq_out = 1; } else { chat.seq_in = 1; } } if (layer.random_bytes.length < 15) { FileLog.e("tmessages", "got random bytes less than needed"); return null; } FileLog.e("tmessages", "current chat in_seq = " + chat.seq_in + " out_seq = " + chat.seq_out); FileLog.e("tmessages", "got message with in_seq = " + layer.in_seq_no + " out_seq = " + layer.out_seq_no); if (layer.out_seq_no < chat.seq_in) { return null; } if (chat.seq_in != layer.out_seq_no && chat.seq_in != layer.out_seq_no - 2) { FileLog.e("tmessages", "got hole"); ArrayList<TL_decryptedMessageHolder> arr = secretHolesQueue.get(chat.id); if (arr == null) { arr = new ArrayList<>(); secretHolesQueue.put(chat.id, arr); } if (arr.size() >= 4) { secretHolesQueue.remove(chat.id); final TLRPC.TL_encryptedChatDiscarded newChat = new TLRPC.TL_encryptedChatDiscarded(); newChat.id = chat.id; newChat.user_id = chat.user_id; newChat.auth_key = chat.auth_key; newChat.key_create_date = chat.key_create_date; newChat.key_use_count_in = chat.key_use_count_in; newChat.key_use_count_out = chat.key_use_count_out; newChat.seq_in = chat.seq_in; newChat.seq_out = chat.seq_out; AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { MessagesController.getInstance().putEncryptedChat(newChat, false); MessagesStorage.getInstance().updateEncryptedChat(newChat); NotificationCenter.getInstance().postNotificationName(NotificationCenter.encryptedChatUpdated, newChat); } }); declineSecretChat(chat.id); return null; } TL_decryptedMessageHolder holder = new TL_decryptedMessageHolder(); holder.layer = layer; holder.file = message.file; holder.random_id = message.random_id; holder.date = message.date; holder.new_key_used = new_key_used; arr.add(holder); return null; } applyPeerLayer(chat, layer.layer); chat.seq_in = layer.out_seq_no; MessagesStorage.getInstance().updateEncryptedChatSeq(chat); object = layer.message; } ArrayList<TLRPC.Message> messages = new ArrayList<>(); TLRPC.Message decryptedMessage = processDecryptedObject(chat, message.file, message.date, message.random_id, object, new_key_used); if (decryptedMessage != null) { messages.add(decryptedMessage); } checkSecretHoles(chat, messages); return messages; } else { is.reuse(); FileLog.e("tmessages", "fingerprint mismatch " + fingerprint); } } catch (Exception e) { FileLog.e("tmessages", e); } return null; } public void requestNewSecretChatKey(final TLRPC.EncryptedChat encryptedChat) { if (AndroidUtilities.getPeerLayerVersion(encryptedChat.layer) < 20) { return; } final byte[] salt = new byte[256]; Utilities.random.nextBytes(salt); BigInteger i_g_a = BigInteger.valueOf(MessagesStorage.secretG); i_g_a = i_g_a.modPow(new BigInteger(1, salt), new BigInteger(1, MessagesStorage.secretPBytes)); byte[] g_a = i_g_a.toByteArray(); if (g_a.length > 256) { byte[] correctedAuth = new byte[256]; System.arraycopy(g_a, 1, correctedAuth, 0, 256); g_a = correctedAuth; } encryptedChat.exchange_id = SendMessagesHelper.getInstance().getNextRandomId(); encryptedChat.a_or_b = salt; encryptedChat.g_a = g_a; MessagesStorage.getInstance().updateEncryptedChat(encryptedChat); sendRequestKeyMessage(encryptedChat, null); } public void processAcceptedSecretChat(final TLRPC.EncryptedChat encryptedChat) { BigInteger p = new BigInteger(1, MessagesStorage.secretPBytes); BigInteger i_authKey = new BigInteger(1, encryptedChat.g_a_or_b); if (!Utilities.isGoodGaAndGb(i_authKey, p)) { declineSecretChat(encryptedChat.id); return; } i_authKey = i_authKey.modPow(new BigInteger(1, encryptedChat.a_or_b), p); byte[] authKey = i_authKey.toByteArray(); if (authKey.length > 256) { byte[] correctedAuth = new byte[256]; System.arraycopy(authKey, authKey.length - 256, correctedAuth, 0, 256); authKey = correctedAuth; } else if (authKey.length < 256) { byte[] correctedAuth = new byte[256]; System.arraycopy(authKey, 0, correctedAuth, 256 - authKey.length, authKey.length); for (int a = 0; a < 256 - authKey.length; a++) { authKey[a] = 0; } authKey = correctedAuth; } byte[] authKeyHash = Utilities.computeSHA1(authKey); byte[] authKeyId = new byte[8]; System.arraycopy(authKeyHash, authKeyHash.length - 8, authKeyId, 0, 8); long fingerprint = Utilities.bytesToLong(authKeyId); if (encryptedChat.key_fingerprint == fingerprint) { encryptedChat.auth_key = authKey; encryptedChat.key_create_date = ConnectionsManager.getInstance().getCurrentTime(); encryptedChat.seq_in = 0; encryptedChat.seq_out = 1; MessagesStorage.getInstance().updateEncryptedChat(encryptedChat); AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { MessagesController.getInstance().putEncryptedChat(encryptedChat, false); NotificationCenter.getInstance().postNotificationName(NotificationCenter.encryptedChatUpdated, encryptedChat); sendNotifyLayerMessage(encryptedChat, null); } }); } else { final TLRPC.TL_encryptedChatDiscarded newChat = new TLRPC.TL_encryptedChatDiscarded(); newChat.id = encryptedChat.id; newChat.user_id = encryptedChat.user_id; newChat.auth_key = encryptedChat.auth_key; newChat.key_create_date = encryptedChat.key_create_date; newChat.key_use_count_in = encryptedChat.key_use_count_in; newChat.key_use_count_out = encryptedChat.key_use_count_out; newChat.seq_in = encryptedChat.seq_in; newChat.seq_out = encryptedChat.seq_out; MessagesStorage.getInstance().updateEncryptedChat(newChat); AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { MessagesController.getInstance().putEncryptedChat(newChat, false); NotificationCenter.getInstance().postNotificationName(NotificationCenter.encryptedChatUpdated, newChat); } }); declineSecretChat(encryptedChat.id); } } public void declineSecretChat(int chat_id) { TLRPC.TL_messages_discardEncryption req = new TLRPC.TL_messages_discardEncryption(); req.chat_id = chat_id; ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(TLObject response, TLRPC.TL_error error) { } }); } public void acceptSecretChat(final TLRPC.EncryptedChat encryptedChat) { if (acceptingChats.get(encryptedChat.id) != null) { return; } acceptingChats.put(encryptedChat.id, encryptedChat); TLRPC.TL_messages_getDhConfig req = new TLRPC.TL_messages_getDhConfig(); req.random_length = 256; req.version = MessagesStorage.lastSecretVersion; ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(TLObject response, TLRPC.TL_error error) { if (error == null) { TLRPC.messages_DhConfig res = (TLRPC.messages_DhConfig) response; if (response instanceof TLRPC.TL_messages_dhConfig) { if (!Utilities.isGoodPrime(res.p, res.g)) { acceptingChats.remove(encryptedChat.id); declineSecretChat(encryptedChat.id); return; } MessagesStorage.secretPBytes = res.p; MessagesStorage.secretG = res.g; MessagesStorage.lastSecretVersion = res.version; MessagesStorage.getInstance().saveSecretParams(MessagesStorage.lastSecretVersion, MessagesStorage.secretG, MessagesStorage.secretPBytes); } byte[] salt = new byte[256]; for (int a = 0; a < 256; a++) { salt[a] = (byte) ((byte) (Utilities.random.nextDouble() * 256) ^ res.random[a]); } encryptedChat.a_or_b = salt; encryptedChat.seq_in = 1; encryptedChat.seq_out = 0; BigInteger p = new BigInteger(1, MessagesStorage.secretPBytes); BigInteger g_b = BigInteger.valueOf(MessagesStorage.secretG); g_b = g_b.modPow(new BigInteger(1, salt), p); BigInteger g_a = new BigInteger(1, encryptedChat.g_a); if (!Utilities.isGoodGaAndGb(g_a, p)) { acceptingChats.remove(encryptedChat.id); declineSecretChat(encryptedChat.id); return; } byte[] g_b_bytes = g_b.toByteArray(); if (g_b_bytes.length > 256) { byte[] correctedAuth = new byte[256]; System.arraycopy(g_b_bytes, 1, correctedAuth, 0, 256); g_b_bytes = correctedAuth; } g_a = g_a.modPow(new BigInteger(1, salt), p); byte[] authKey = g_a.toByteArray(); if (authKey.length > 256) { byte[] correctedAuth = new byte[256]; System.arraycopy(authKey, authKey.length - 256, correctedAuth, 0, 256); authKey = correctedAuth; } else if (authKey.length < 256) { byte[] correctedAuth = new byte[256]; System.arraycopy(authKey, 0, correctedAuth, 256 - authKey.length, authKey.length); for (int a = 0; a < 256 - authKey.length; a++) { authKey[a] = 0; } authKey = correctedAuth; } byte[] authKeyHash = Utilities.computeSHA1(authKey); byte[] authKeyId = new byte[8]; System.arraycopy(authKeyHash, authKeyHash.length - 8, authKeyId, 0, 8); encryptedChat.auth_key = authKey; encryptedChat.key_create_date = ConnectionsManager.getInstance().getCurrentTime(); TLRPC.TL_messages_acceptEncryption req2 = new TLRPC.TL_messages_acceptEncryption(); req2.g_b = g_b_bytes; req2.peer = new TLRPC.TL_inputEncryptedChat(); req2.peer.chat_id = encryptedChat.id; req2.peer.access_hash = encryptedChat.access_hash; req2.key_fingerprint = Utilities.bytesToLong(authKeyId); ConnectionsManager.getInstance().sendRequest(req2, new RequestDelegate() { @Override public void run(TLObject response, TLRPC.TL_error error) { acceptingChats.remove(encryptedChat.id); if (error == null) { final TLRPC.EncryptedChat newChat = (TLRPC.EncryptedChat) response; newChat.auth_key = encryptedChat.auth_key; newChat.user_id = encryptedChat.user_id; newChat.seq_in = encryptedChat.seq_in; newChat.seq_out = encryptedChat.seq_out; newChat.key_create_date = encryptedChat.key_create_date; newChat.key_use_count_in = encryptedChat.key_use_count_in; newChat.key_use_count_out = encryptedChat.key_use_count_out; MessagesStorage.getInstance().updateEncryptedChat(newChat); AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { MessagesController.getInstance().putEncryptedChat(newChat, false); NotificationCenter.getInstance().postNotificationName(NotificationCenter.encryptedChatUpdated, newChat); sendNotifyLayerMessage(newChat, null); } }); } } }); } else { acceptingChats.remove(encryptedChat.id); } } }); } public void startSecretChat(final Context context, final TLRPC.User user) { if (user == null || context == null) { return; } startingSecretChat = true; final ProgressDialog progressDialog = new ProgressDialog(context); progressDialog.setMessage(LocaleController.getString("Loading", R.string.Loading)); progressDialog.setCanceledOnTouchOutside(false); progressDialog.setCancelable(false); TLRPC.TL_messages_getDhConfig req = new TLRPC.TL_messages_getDhConfig(); req.random_length = 256; req.version = MessagesStorage.lastSecretVersion; final int reqId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(TLObject response, TLRPC.TL_error error) { if (error == null) { TLRPC.messages_DhConfig res = (TLRPC.messages_DhConfig) response; if (response instanceof TLRPC.TL_messages_dhConfig) { if (!Utilities.isGoodPrime(res.p, res.g)) { AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { try { if (!((Activity) context).isFinishing()) { progressDialog.dismiss(); } } catch (Exception e) { FileLog.e("tmessages", e); } } }); return; } MessagesStorage.secretPBytes = res.p; MessagesStorage.secretG = res.g; MessagesStorage.lastSecretVersion = res.version; MessagesStorage.getInstance().saveSecretParams(MessagesStorage.lastSecretVersion, MessagesStorage.secretG, MessagesStorage.secretPBytes); } final byte[] salt = new byte[256]; for (int a = 0; a < 256; a++) { salt[a] = (byte) ((byte) (Utilities.random.nextDouble() * 256) ^ res.random[a]); } BigInteger i_g_a = BigInteger.valueOf(MessagesStorage.secretG); i_g_a = i_g_a.modPow(new BigInteger(1, salt), new BigInteger(1, MessagesStorage.secretPBytes)); byte[] g_a = i_g_a.toByteArray(); if (g_a.length > 256) { byte[] correctedAuth = new byte[256]; System.arraycopy(g_a, 1, correctedAuth, 0, 256); g_a = correctedAuth; } TLRPC.TL_messages_requestEncryption req2 = new TLRPC.TL_messages_requestEncryption(); req2.g_a = g_a; req2.user_id = MessagesController.getInputUser(user); req2.random_id = Utilities.random.nextInt(); ConnectionsManager.getInstance().sendRequest(req2, new RequestDelegate() { @Override public void run(final TLObject response, TLRPC.TL_error error) { if (error == null) { AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { startingSecretChat = false; if (!((Activity) context).isFinishing()) { try { progressDialog.dismiss(); } catch (Exception e) { FileLog.e("tmessages", e); } } TLRPC.EncryptedChat chat = (TLRPC.EncryptedChat) response; chat.user_id = chat.participant_id; chat.seq_in = 0; chat.seq_out = 1; chat.a_or_b = salt; MessagesController.getInstance().putEncryptedChat(chat, false); TLRPC.Dialog dialog = new TLRPC.TL_dialog(); dialog.id = ((long) chat.id) << 32; dialog.unread_count = 0; dialog.top_message = 0; dialog.last_message_date = ConnectionsManager.getInstance().getCurrentTime(); MessagesController.getInstance().dialogs_dict.put(dialog.id, dialog); MessagesController.getInstance().dialogs.add(dialog); Collections.sort(MessagesController.getInstance().dialogs, new Comparator<TLRPC.Dialog>() { @Override public int compare(TLRPC.Dialog tl_dialog, TLRPC.Dialog tl_dialog2) { if (tl_dialog.last_message_date == tl_dialog2.last_message_date) { return 0; } else if (tl_dialog.last_message_date < tl_dialog2.last_message_date) { return 1; } else { return -1; } } }); MessagesStorage.getInstance().putEncryptedChat(chat, user, dialog); NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); NotificationCenter.getInstance().postNotificationName(NotificationCenter.encryptedChatCreated, chat); Utilities.stageQueue.postRunnable(new Runnable() { @Override public void run() { if (!delayedEncryptedChatUpdates.isEmpty()) { MessagesController.getInstance().processUpdateArray(delayedEncryptedChatUpdates, null, null); delayedEncryptedChatUpdates.clear(); } } }); } }); } else { delayedEncryptedChatUpdates.clear(); AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { if (!((Activity) context).isFinishing()) { startingSecretChat = false; try { progressDialog.dismiss(); } catch (Exception e) { FileLog.e("tmessages", e); } AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setMessage(LocaleController.getString("CreateEncryptedChatError", R.string.CreateEncryptedChatError)); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null); builder.show().setCanceledOnTouchOutside(true); } } }); } } }, ConnectionsManager.RequestFlagFailOnServerErrors); } else { delayedEncryptedChatUpdates.clear(); AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { startingSecretChat = false; if (!((Activity) context).isFinishing()) { try { progressDialog.dismiss(); } catch (Exception e) { FileLog.e("tmessages", e); } } } }); } } }, ConnectionsManager.RequestFlagFailOnServerErrors); progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, LocaleController.getString("Cancel", R.string.Cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ConnectionsManager.getInstance().cancelRequest(reqId, true); try { dialog.dismiss(); } catch (Exception e) { FileLog.e("tmessages", e); } } }); try { progressDialog.show(); } catch (Exception e) { //don't promt } } }
gpl-2.0
smarr/graal
graal/com.oracle.graal.compiler.hsail.test/src/com/oracle/graal/compiler/hsail/test/EscapingNewBase.java
2628
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.compiler.hsail.test; import com.oracle.graal.compiler.hsail.test.infra.GraalKernelTester; import java.util.Arrays; /** * Base Class for tests that allocate escaping objects. */ public class EscapingNewBase extends GraalKernelTester { final int num = getRange(); int getRange() { return 24; } @Result public Object[] outArray = new Object[num]; public Object[] savedOutArray; @Result public boolean savedOutArrayMatch1; @Result public boolean savedOutArrayMatch2; @Result public boolean savedOutArrayMatch3; void setupArrays() { for (int i = 0; i < num; i++) { outArray[i] = null; } } int getDispatches() { return 1; } @Override protected boolean supportsRequiredCapabilities() { return canHandleObjectAllocation(); } @Override public void runTest() { setupArrays(); dispatchMethodKernel(num); // use System.gc() to ensure new objects are in form that gc likes System.gc(); savedOutArray = Arrays.copyOf(outArray, num); savedOutArrayMatch1 = Arrays.equals(outArray, savedOutArray); if (getDispatches() > 1) { // redispatch kernel without gc dispatchMethodKernel(num); savedOutArrayMatch2 = Arrays.equals(outArray, savedOutArray); // and one more time with gc dispatchMethodKernel(num); savedOutArrayMatch3 = Arrays.equals(outArray, savedOutArray); System.gc(); } } }
gpl-2.0
marylinh/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest01991.java
2061
/** * OWASP Benchmark Project v1.2beta * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The OWASP Benchmark is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, version 2. * * The OWASP Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest01991") public class BenchmarkTest01991 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String param = request.getHeader("vector"); if (param == null) param = ""; String bar = doSomething(param); response.getWriter().write("Parameter value: " + bar); } // end doPost private static String doSomething(String param) throws ServletException, IOException { String bar; // Simple if statement that assigns param to bar on true condition int num = 196; if ( (500/42) + num > 200 ) bar = param; else bar = "This should never happen"; return bar; } }
gpl-2.0
gstreamer-java/gir2java
generated-src/generated/gstreamer10/gst/GstAllocatorClass.java
1209
package generated.gstreamer10.gst; import org.bridj.BridJ; import org.bridj.Pointer; import org.bridj.StructObject; import org.bridj.ann.Field; import org.bridj.ann.Library; @Library("gstreamer-1.0") public class GstAllocatorClass extends StructObject { static { BridJ.register(); } public GstAllocatorClass() { super(); } public GstAllocatorClass(Pointer pointer) { super(pointer); } @Field(0) public GstObjectClass gstallocatorclass_field_object_class() { return this.io.getNativeObjectField(this, 0); } @Field(0) public GstAllocatorClass gstallocatorclass_field_object_class(GstObjectClass gstallocatorclass_field_object_class) { this.io.setNativeObjectField(this, 0, gstallocatorclass_field_object_class); return this; } @Field(1) private Pointer gstallocatorclass_field__gst_reserved() { return this.io.getPointerField(this, 1); } @Field(1) private GstAllocatorClass gstallocatorclass_field__gst_reserved(Pointer gstallocatorclass_field__gst_reserved) { this.io.setPointerField(this, 1, gstallocatorclass_field__gst_reserved); return this; } }
gpl-3.0
rexut/jkcemu
src/jkcemu/emusys/SLC1.java
13812
/* * (c) 2009-2016 Jens Mueller * * Kleincomputer-Emulator * * Emulation des Schach- und Lerncomputers SLC1 */ package jkcemu.emusys; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.event.KeyEvent; import java.lang.*; import java.util.Arrays; import java.util.Properties; import jkcemu.base.AbstractKeyboardFld; import jkcemu.base.EmuSys; import jkcemu.base.EmuThread; import jkcemu.base.EmuUtil; import jkcemu.emusys.etc.SLC1KeyboardFld; import z80emu.Z80CPU; import z80emu.Z80PCListener; public class SLC1 extends EmuSys implements Z80PCListener { public static final String SYSNAME = "SLC1"; public static final String PROP_PREFIX = "jkcemu.slc1."; private static byte[] rom = null; private SLC1KeyboardFld keyboardFld; private int[] keyboardMatrix; private int[] digitStatus; private int[] digitValues; private byte[] ram; private int displayTStates; private int curKeyCol; private int curSegValue; private long curDisplayTStates; private int ledStatus; private boolean ledValue; private boolean chessMode; public SLC1( EmuThread emuThread, Properties props ) { super( emuThread, props, PROP_PREFIX ); if( rom == null ) { rom = readResource( "/rom/slc1/slc1_0000.bin" ); } this.keyboardFld = null; this.keyboardMatrix = new int[ 3 ]; this.digitStatus = new int[ 6 ]; this.digitValues = new int[ 6 ]; this.ram = new byte[ 0x0400 ]; this.ledStatus = 0; this.ledValue = false; this.chessMode = true; Z80CPU cpu = emuThread.getZ80CPU(); cpu.addMaxSpeedListener( this ); cpu.addPCListener( this, 0x0000, 0x0615 ); cpu.addTStatesListener( this ); z80MaxSpeedChanged( cpu ); } public static int getDefaultSpeedKHz() { return 2500; } public boolean isChessMode() { return this.chessMode; } public void updKeyboardMatrix( int[] kbMatrix ) { synchronized( this.keyboardMatrix ) { int n = Math.min( kbMatrix.length, this.keyboardMatrix.length ); int i = 0; while( i < n ) { this.keyboardMatrix[ i ] = kbMatrix[ i ]; i++; } while( i < this.keyboardMatrix.length ) { this.keyboardMatrix[ i ] = 0; i++; } } } /* --- Z80PCListener --- */ @Override public void z80PCChanged( Z80CPU cpu, int pc ) { switch( pc ) { case 0x0000: setChessMode( true ); break; case 0x0615: setChessMode( false ); break; } } /* --- ueberschriebene Methoden --- */ @Override public boolean canApplySettings( Properties props ) { return EmuUtil.getProperty( props, EmuThread.PROP_SYSNAME ).equals( SYSNAME ); } @Override public AbstractKeyboardFld createKeyboardFld() { this.keyboardFld = new SLC1KeyboardFld( this ); return this.keyboardFld; } @Override public void die() { Z80CPU cpu = this.emuThread.getZ80CPU(); cpu.removeTStatesListener( this ); cpu.removePCListener( this ); cpu.removeMaxSpeedListener( this ); super.die(); } @Override public Chessman getChessman( int row, int col ) { Chessman rv = null; if( this.chessMode && (row >= 0) && (row < 8) && (col >= 0) && (col < 8) ) { switch( getMemByte( 0x5000 + (row * 16) + col, false ) ) { case 1: rv = Chessman.WHITE_PAWN; break; case 2: rv = Chessman.WHITE_KNIGHT; break; case 3: rv = Chessman.WHITE_BISHOP; break; case 4: rv = Chessman.WHITE_ROOK; break; case 5: rv = Chessman.WHITE_QUEEN; break; case 6: rv = Chessman.WHITE_KING; break; case 0xFF: rv = Chessman.BLACK_PAWN; break; case 0xFE: rv = Chessman.BLACK_KNIGHT; break; case 0xFD: rv = Chessman.BLACK_BISHOP; break; case 0xFC: rv = Chessman.BLACK_ROOK; break; case 0xFB: rv = Chessman.BLACK_QUEEN; break; case 0xFA: rv = Chessman.BLACK_KING; break; } } return rv; } @Override public Color getColor( int colorIdx ) { Color color = Color.black; switch( colorIdx ) { case 1: color = this.colorGreenDark; break; case 2: color = this.colorGreenLight; break; } return color; } @Override public int getColorCount() { return 3; } @Override public String getHelpPage() { return "/help/slc1.htm"; } @Override public int getMemByte( int addr, boolean m1 ) { int rv = 0xFF; if( (addr & 0x4000) != 0 ) { // A14=0: ROM, A14=1: RAM int idx = addr & 0x03FF; if( idx < this.ram.length ) { rv = (int) this.ram[ idx ] & 0xFF; } } else { addr &= 0x0FFF; if( addr < rom.length ) { rv = (int) rom[ addr ] & 0xFF; } } return rv; } @Override public int getScreenHeight() { return 110; } @Override public int getScreenWidth() { return 70 + (this.digitValues.length * 50); } @Override public String getTitle() { return SYSNAME; } @Override public boolean keyPressed( int keyCode, boolean ctrlDown, boolean shiftDown ) { boolean rv = false; synchronized( this.keyboardMatrix ) { if( this.chessMode ) { switch( keyCode ) { case KeyEvent.VK_ESCAPE: // Rueckstellen this.keyboardMatrix[ 2 ] = 0x10; rv = true; break; case KeyEvent.VK_ENTER: // Figurenwahl, Zug quittieren this.keyboardMatrix[ 2 ] = 0x80; rv = true; break; case KeyEvent.VK_F1: // Spielstaerke this.keyboardMatrix[ 2 ] = 0x20; rv = true; break; case KeyEvent.VK_F2: // in Spielmode wechseln this.keyboardMatrix[ 2 ] = 0x40; rv = true; break; } } else { switch( keyCode ) { case KeyEvent.VK_F1: // ADR this.keyboardMatrix[ 2 ] = 0x80; rv = true; break; case KeyEvent.VK_F2: // Fu this.keyboardMatrix[ 2 ] = 0x40; rv = true; break; } } } if( rv ) { updKeyboardFld(); } return rv; } @Override public void keyReleased() { synchronized( this.keyboardMatrix ) { Arrays.fill( this.keyboardMatrix, 0 ); } updKeyboardFld(); } @Override public boolean keyTyped( char keyChar ) { boolean rv = false; synchronized( this.keyboardMatrix ) { keyChar = Character.toUpperCase( keyChar ); if( this.chessMode ) { switch( keyChar ) { case 'S': // in Spielmode wechseln this.keyboardMatrix[ 2 ] = 0x40; rv = true; break; case 'Z': // Figurenwahl, Zug quittieren this.keyboardMatrix[ 2 ] = 0x80; rv = true; break; case 'A': // Spalte A bzw. Zeile 1 case '1': this.keyboardMatrix[ 0 ] = 0x80; rv = true; break; case 'B': // Spalte B bzw. Zeile 2 case '2': this.keyboardMatrix[ 0 ] = 0x40; rv = true; break; case 'C': // Spalte C bzw. Zeile 3 case '3': this.keyboardMatrix[ 0 ] = 0x20; rv = true; break; case 'D': // Spalte D bzw. Zeile 4 case '4': this.keyboardMatrix[ 0 ] = 0x10; rv = true; break; case 'E': // Spalte E bzw. Zeile 5 case '5': this.keyboardMatrix[ 1 ] = 0x10; rv = true; break; case 'F': // Spalte F bzw. Zeile 6 case '6': this.keyboardMatrix[ 1 ] = 0x20; rv = true; break; case 'G': // Spalte G bzw. Zeile 7 case '7': this.keyboardMatrix[ 1 ] = 0x40; rv = true; break; case 'H': // Spalte H bzw. Zeile 8 case '8': this.keyboardMatrix[ 1 ] = 0x80; rv = true; break; } } else { switch( keyChar ) { case '0': // 0 bzw. 8 case '8': this.keyboardMatrix[ 0 ] = 0x80; rv = true; break; case '1': // 1 bzw. 9 case '9': this.keyboardMatrix[ 0 ] = 0x40; rv = true; break; case '2': // 2 bzw. A case 'A': this.keyboardMatrix[ 0 ] = 0x20; rv = true; break; case '3': // 3 bzw. B case 'B': this.keyboardMatrix[ 0 ] = 0x10; rv = true; break; case '4': // 4 bzw. C case 'C': this.keyboardMatrix[ 1 ] = 0x10; rv = true; break; case '5': // 5 bzw. D case 'D': this.keyboardMatrix[ 1 ] = 0x20; rv = true; break; case '6': // 6 bzw. E case 'E': this.keyboardMatrix[ 1 ] = 0x40; rv = true; break; case '7': // 7 bzw. F case 'F': this.keyboardMatrix[ 1 ] = 0x80; rv = true; break; case 'S': // Shift this.keyboardMatrix[ 2 ] = 0x10; rv = true; break; case '+': // +/- 1 case '-': this.keyboardMatrix[ 2 ] = 0x20; rv = true; break; } } } if( rv ) { updKeyboardFld(); } return rv; } @Override public boolean paintScreen( Graphics g, int x, int y, int screenScale ) { synchronized( this.digitStatus ) { // LED Busy g.setFont( new Font( "SansSerif", Font.BOLD, 18 * screenScale ) ); g.setColor( this.ledValue || (this.ledStatus > 0) ? this.colorGreenLight : this.colorGreenDark ); g.drawString( "Busy", x, y + (110 * screenScale) ); // 7-Segment-Anzeige for( int i = this.digitValues.length - 1; i >= 0; --i ) { paint7SegDigit( g, x, y, this.digitValues[ i ], this.colorGreenDark, this.colorGreenLight, screenScale ); x += (65 * screenScale); } } return true; } @Override public int readIOByte( int port, int tStates ) { int rv = 0xFF; synchronized( this.keyboardMatrix ) { if( (this.curKeyCol >= 0) && (this.curKeyCol < this.keyboardMatrix.length) ) { rv = ~this.keyboardMatrix[ this.curKeyCol ] & 0xFF; } } return rv; } @Override public void reset( EmuThread.ResetLevel resetLevel, Properties props ) { super.reset( resetLevel, props ); if( resetLevel == EmuThread.ResetLevel.POWER_ON ) { initSRAM( this.ram, props ); } synchronized( this.keyboardMatrix ) { Arrays.fill( this.keyboardMatrix, 0 ); this.curKeyCol = 0; } synchronized( this.digitStatus ) { Arrays.fill( this.digitStatus, 0 ); Arrays.fill( this.digitValues, 0 ); this.ledStatus = 0; this.ledValue = false; } this.curSegValue = 0; this.curDisplayTStates = 0; setChessMode( true ); } @Override public boolean setMemByte( int addr, int value ) { boolean rv = false; if( (addr & 0x4000) != 0 ) { // A14=1: RAM int idx = addr & 0x03FF; if( idx < this.ram.length ) { this.ram[ idx ] = (byte) value; if( this.chessMode && (idx < 0x78) && ((idx % 16) < 8) ) { this.screenFrm.setChessboardDirty( true ); } rv = true; } } return rv; } @Override public boolean supportsChessboard() { return true; } @Override public boolean supportsKeyboardFld() { return true; } @Override public boolean supportsSoundOutMono() { return true; } @Override public void writeIOByte( int port, int value, int tStates ) { // Tastaturspalten int col = value & 0x0F; synchronized( this.keyboardMatrix ) { this.curKeyCol = col - 3; } // Tonausgabe this.soundOutPhase = (col == 9); // Anzeige boolean dirty = false; int segMask = 0x01; int segNum = port & 0x07; if( segNum > 0 ) { segMask <<= segNum; } if( (value & 0x80) != 0 ) { this.curSegValue |= segMask; } else { this.curSegValue &= ~segMask; } if( col == 2 ) { col = -1; } else if( col > 2 ) { --col; } synchronized( this.digitStatus ) { if( (col >= 0) && (col < this.digitValues.length) ) { this.curSegValue &= 0x7F; if( this.curSegValue != this.digitValues[ col ] ) { this.digitValues[ col ] = this.curSegValue; dirty = true; } this.digitStatus[ col ] = 3; } int ledStatus = 0; boolean ledValue = ((value & 0x10) != 0); if( ledValue ) { ledStatus = 3; if( !this.ledValue && (this.ledStatus == 0) ) { dirty = true; } } else { if( this.ledValue || (this.ledStatus > 0) ) { dirty = true; } } this.ledStatus = ledStatus; this.ledValue = ledValue; } if( dirty ) { this.screenFrm.setScreenDirty( true ); } } @Override public void z80MaxSpeedChanged( Z80CPU cpu ) { super.z80MaxSpeedChanged( cpu ); this.displayTStates = cpu.getMaxSpeedKHz() * 50; } @Override public void z80TStatesProcessed( Z80CPU cpu, int tStates ) { super.z80TStatesProcessed( cpu, tStates ); // Anzeige if( this.displayTStates > 0 ) { this.curDisplayTStates += tStates; if( this.curDisplayTStates > this.displayTStates ) { boolean dirty = false; synchronized( this.digitStatus ) { for( int i = 0; i < this.digitStatus.length; i++ ) { if( this.digitStatus[ i ] > 0 ) { --this.digitStatus[ i ]; } else { if( this.digitValues[ i ] != 0 ) { this.digitValues[ i ] = 0; dirty = true; } } } if( !this.ledValue && (this.ledStatus > 0) ) { --this.ledStatus; if( this.ledStatus == 0 ) { dirty = true; } } } if( dirty ) { this.screenFrm.setScreenDirty( true ); } this.curDisplayTStates = 0; } } } /* --- privated Methoden --- */ private void setChessMode( boolean state ) { if( state != this.chessMode ) { this.chessMode = state; if( this.keyboardFld != null ) { this.keyboardFld.repaint(); } } } private void updKeyboardFld() { if( this.keyboardFld != null ) this.keyboardFld.updKeySelection( this.keyboardMatrix ); } }
gpl-3.0
GilCol/TextSecure
src/org/thoughtcrime/securesms/ConversationListItem.java
9802
/** * Copyright (C) 2011 Whisper Systems * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.thoughtcrime.securesms; import android.annotation.TargetApi; import android.content.Context; import android.content.res.ColorStateList; import android.graphics.Typeface; import android.graphics.drawable.RippleDrawable; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.os.Handler; import android.support.annotation.DrawableRes; import android.support.annotation.NonNull; import android.util.AttributeSet; import android.view.View; import android.widget.RelativeLayout; import android.widget.TextView; import org.thoughtcrime.securesms.components.AvatarImageView; import org.thoughtcrime.securesms.components.DeliveryStatusView; import org.thoughtcrime.securesms.components.AlertView; import org.thoughtcrime.securesms.components.FromTextView; import org.thoughtcrime.securesms.components.ThumbnailView; import org.thoughtcrime.securesms.crypto.MasterSecret; import org.thoughtcrime.securesms.database.model.ThreadRecord; import org.thoughtcrime.securesms.recipients.Recipients; import org.thoughtcrime.securesms.util.DateUtils; import org.thoughtcrime.securesms.util.ResUtil; import org.thoughtcrime.securesms.util.ViewUtil; import java.util.Locale; import java.util.Set; import static org.thoughtcrime.securesms.util.SpanUtil.color; /** * A view that displays the element in a list of multiple conversation threads. * Used by SecureSMS's ListActivity via a ConversationListAdapter. * * @author Moxie Marlinspike */ public class ConversationListItem extends RelativeLayout implements Recipients.RecipientsModifiedListener, BindableConversationListItem, Unbindable { private final static String TAG = ConversationListItem.class.getSimpleName(); private final static Typeface BOLD_TYPEFACE = Typeface.create("sans-serif", Typeface.BOLD); private final static Typeface LIGHT_TYPEFACE = Typeface.create("sans-serif-light", Typeface.NORMAL); private Set<Long> selectedThreads; private Recipients recipients; private long threadId; private TextView subjectView; private FromTextView fromView; private TextView dateView; private TextView archivedView; private DeliveryStatusView deliveryStatusIndicator; private AlertView alertView; private boolean read; private AvatarImageView contactPhotoImage; private ThumbnailView thumbnailView; private final @DrawableRes int readBackground; private final @DrawableRes int unreadBackround; private final Handler handler = new Handler(); private int distributionType; public ConversationListItem(Context context) { this(context, null); } public ConversationListItem(Context context, AttributeSet attrs) { super(context, attrs); readBackground = ResUtil.getDrawableRes(context, R.attr.conversation_list_item_background_read); unreadBackround = ResUtil.getDrawableRes(context, R.attr.conversation_list_item_background_unread); } @Override protected void onFinishInflate() { super.onFinishInflate(); this.subjectView = (TextView) findViewById(R.id.subject); this.fromView = (FromTextView) findViewById(R.id.from); this.dateView = (TextView) findViewById(R.id.date); this.deliveryStatusIndicator = (DeliveryStatusView) findViewById(R.id.delivery_status); this.alertView = (AlertView) findViewById(R.id.indicators_parent); this.contactPhotoImage = (AvatarImageView) findViewById(R.id.contact_photo_image); this.thumbnailView = (ThumbnailView) findViewById(R.id.thumbnail); this.archivedView = ViewUtil.findById(this, R.id.archived); thumbnailView.setClickable(false); } public void bind(@NonNull MasterSecret masterSecret, @NonNull ThreadRecord thread, @NonNull Locale locale, @NonNull Set<Long> selectedThreads, boolean batchMode) { this.selectedThreads = selectedThreads; this.recipients = thread.getRecipients(); this.threadId = thread.getThreadId(); this.read = thread.isRead(); this.distributionType = thread.getDistributionType(); this.recipients.addListener(this); this.fromView.setText(recipients, read); this.subjectView.setText(thread.getDisplayBody()); this.subjectView.setTypeface(read ? LIGHT_TYPEFACE : BOLD_TYPEFACE); if (thread.getDate() > 0) { CharSequence date = DateUtils.getBriefRelativeTimeSpanString(getContext(), locale, thread.getDate()); dateView.setText(read ? date : color(getResources().getColor(R.color.textsecure_primary), date)); dateView.setTypeface(read ? LIGHT_TYPEFACE : BOLD_TYPEFACE); } if (thread.isArchived()) { this.archivedView.setVisibility(View.VISIBLE); } else { this.archivedView.setVisibility(View.GONE); } setStatusIcons(thread); setThumbnailSnippet(masterSecret, thread); setBatchState(batchMode); setBackground(thread); setRippleColor(recipients); this.contactPhotoImage.setAvatar(recipients, true); } @Override public void unbind() { if (this.recipients != null) this.recipients.removeListener(this); } private void setBatchState(boolean batch) { setSelected(batch && selectedThreads.contains(threadId)); } public Recipients getRecipients() { return recipients; } public long getThreadId() { return threadId; } public boolean getRead() { return read; } public int getDistributionType() { return distributionType; } private void setThumbnailSnippet(MasterSecret masterSecret, ThreadRecord thread) { if (thread.getSnippetUri() != null) { this.thumbnailView.setVisibility(View.VISIBLE); this.thumbnailView.setImageResource(masterSecret, thread.getSnippetUri()); LayoutParams subjectParams = (RelativeLayout.LayoutParams)this.subjectView.getLayoutParams(); subjectParams.addRule(RelativeLayout.LEFT_OF, R.id.thumbnail); this.subjectView.setLayoutParams(subjectParams); this.post(new ThumbnailPositioner(thumbnailView, archivedView, deliveryStatusIndicator, dateView)); } else { this.thumbnailView.setVisibility(View.GONE); LayoutParams subjectParams = (RelativeLayout.LayoutParams)this.subjectView.getLayoutParams(); subjectParams.addRule(RelativeLayout.LEFT_OF, R.id.delivery_status); this.subjectView.setLayoutParams(subjectParams); } } private void setStatusIcons(ThreadRecord thread) { if (!thread.isOutgoing()) { deliveryStatusIndicator.setNone(); alertView.setNone(); } else if (thread.isFailed()) { deliveryStatusIndicator.setNone(); alertView.setFailed(); } else if (thread.isPendingInsecureSmsFallback()) { deliveryStatusIndicator.setNone(); alertView.setPendingApproval(); } else { alertView.setNone(); if (thread.isPending()) deliveryStatusIndicator.setPending(); else if (thread.isDelivered()) deliveryStatusIndicator.setDelivered(); else deliveryStatusIndicator.setSent(); } } private void setBackground(ThreadRecord thread) { if (thread.isRead()) setBackgroundResource(readBackground); else setBackgroundResource(unreadBackround); } @TargetApi(VERSION_CODES.LOLLIPOP) private void setRippleColor(Recipients recipients) { if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { ((RippleDrawable)(getBackground()).mutate()) .setColor(ColorStateList.valueOf(recipients.getColor().toConversationColor(getContext()))); } } @Override public void onModified(final Recipients recipients) { handler.post(new Runnable() { @Override public void run() { fromView.setText(recipients, read); contactPhotoImage.setAvatar(recipients, true); setRippleColor(recipients); } }); } private static class ThumbnailPositioner implements Runnable { private final View thumbnailView; private final View archivedView; private final View deliveryStatusView; private final View dateView; public ThumbnailPositioner(View thumbnailView, View archivedView, View deliveryStatusView, View dateView) { this.thumbnailView = thumbnailView; this.archivedView = archivedView; this.deliveryStatusView = deliveryStatusView; this.dateView = dateView; } @Override public void run() { LayoutParams thumbnailParams = (RelativeLayout.LayoutParams)thumbnailView.getLayoutParams(); if (archivedView.getVisibility() == View.VISIBLE && (archivedView.getWidth() + deliveryStatusView.getWidth()) > dateView.getWidth()) { thumbnailParams.addRule(RelativeLayout.LEFT_OF, R.id.delivery_status); } else { thumbnailParams.addRule(RelativeLayout.LEFT_OF, R.id.date); } thumbnailView.setLayoutParams(thumbnailParams); } } }
gpl-3.0
aelred/grakn
grakn-test/src/test/java/ai/grakn/graphs/DiagonalGraph.java
3254
/* * Grakn - A Distributed Semantic Database * Copyright (C) 2016 Grakn Labs Limited * * Grakn is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Grakn is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Grakn. If not, see <http://www.gnu.org/licenses/gpl.txt>. */ package ai.grakn.graphs; import ai.grakn.GraknGraph; import ai.grakn.concept.ConceptId; import ai.grakn.concept.EntityType; import ai.grakn.concept.RelationType; import ai.grakn.concept.RoleType; import ai.grakn.concept.TypeName; import java.util.function.Consumer; public class DiagonalGraph extends TestGraph { private final static TypeName key = TypeName.of("name"); private final static String gqlFile = "diagonal-test.gql"; private final int n; private final int m; public DiagonalGraph(int n, int m){ this.m = m; this.n = n; } public static Consumer<GraknGraph> get(int n, int m) { return new DiagonalGraph(n, m).build(); } @Override public Consumer<GraknGraph> build(){ return (GraknGraph graph) -> { loadFromFile(graph, gqlFile); buildExtensionalDB(graph, n, m); }; } private void buildExtensionalDB(GraknGraph graph, int n, int m) { RoleType relFrom = graph.getRoleType("rel-from"); RoleType relTo = graph.getRoleType("rel-to"); EntityType entity1 = graph.getEntityType("entity1"); RelationType horizontal = graph.getRelationType("horizontal"); RelationType vertical = graph.getRelationType("vertical"); ConceptId[][] instanceIds = new ConceptId[n][m]; long inserts = 0; for(int i = 0 ; i < n ;i++) for(int j = 0 ; j < m ;j++) { instanceIds[i][j] = putEntity(graph, "a" + i + "," + j, entity1, key).getId(); inserts++; if (inserts % 100 == 0) System.out.println("inst inserts: " + inserts); } for(int i = 0 ; i < n ; i++) { for (int j = 0; j < m; j++) { if ( i < n - 1 ) { horizontal.addRelation() .putRolePlayer(relFrom, graph.getConcept(instanceIds[i][j])) .putRolePlayer(relTo, graph.getConcept(instanceIds[i+1][j])); inserts++; } if ( j < m - 1){ vertical.addRelation() .putRolePlayer(relFrom, graph.getConcept(instanceIds[i][j])) .putRolePlayer(relTo, graph.getConcept(instanceIds[i][j+1])); inserts++; } if (inserts % 100 == 0) System.out.println("rel inserts: " + inserts); } } System.out.println("Extensional DB loaded."); } }
gpl-3.0
nhahtdh/opentsdb
src/tsd/client/QueryUi.java
51641
// This file is part of OpenTSDB. // Copyright (C) 2010-2012 The OpenTSDB Authors. // // This program is free software: you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 2.1 of the License, or (at your // option) any later version. This program is distributed in the hope that it // will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser // General Public License for more details. You should have received a copy // of the GNU Lesser General Public License along with this program. If not, // see <http://www.gnu.org/licenses/>. package tsd.client; /* * DISCLAIMER * This my first GWT code ever, so it's most likely horribly wrong as I've had * virtually no exposure to the technology except through the tutorial. --tsuna */ import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.dom.client.Style; import com.google.gwt.dom.client.Style.Cursor; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.DomEvent; import com.google.gwt.event.dom.client.ErrorEvent; import com.google.gwt.event.dom.client.ErrorHandler; import com.google.gwt.event.dom.client.LoadEvent; import com.google.gwt.event.dom.client.LoadHandler; import com.google.gwt.event.dom.client.MouseDownEvent; import com.google.gwt.event.dom.client.MouseDownHandler; import com.google.gwt.event.dom.client.MouseEvent; import com.google.gwt.event.dom.client.MouseMoveEvent; import com.google.gwt.event.dom.client.MouseMoveHandler; import com.google.gwt.event.dom.client.MouseOutEvent; import com.google.gwt.event.dom.client.MouseOutHandler; import com.google.gwt.event.dom.client.MouseOverEvent; import com.google.gwt.event.dom.client.MouseOverHandler; import com.google.gwt.event.dom.client.MouseUpEvent; import com.google.gwt.event.dom.client.MouseUpHandler; import com.google.gwt.event.logical.shared.BeforeSelectionEvent; import com.google.gwt.event.logical.shared.BeforeSelectionHandler; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.event.shared.EventHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestBuilder; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.http.client.RequestException; import com.google.gwt.http.client.Response; import com.google.gwt.http.client.URL; import com.google.gwt.i18n.client.DateTimeFormat; import com.google.gwt.json.client.JSONArray; import com.google.gwt.json.client.JSONNumber; import com.google.gwt.json.client.JSONObject; import com.google.gwt.json.client.JSONParser; import com.google.gwt.json.client.JSONString; import com.google.gwt.json.client.JSONValue; import com.google.gwt.user.client.Element; import com.google.gwt.user.client.History; import com.google.gwt.user.client.HistoryListener; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.AbsolutePanel; import com.google.gwt.user.client.ui.Anchor; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.DecoratedTabPanel; import com.google.gwt.user.client.ui.DecoratorPanel; import com.google.gwt.user.client.ui.DisclosurePanel; import com.google.gwt.user.client.ui.FlexTable; import com.google.gwt.user.client.ui.Grid; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.InlineLabel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.RadioButton; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; /** * Root class for the 'query UI'. * Manages the entire UI, forms to query the TSDB and other misc panels. */ public class QueryUi implements EntryPoint, HistoryListener { // Some URLs we use to fetch data from the TSD. private static final String AGGREGATORS_URL = "/aggregators"; private static final String LOGS_URL = "/logs?json"; private static final String STATS_URL = "/stats?json"; private static final String VERSION_URL = "/version?json"; private static final DateTimeFormat FULLDATE = DateTimeFormat.getFormat("yyyy/MM/dd-HH:mm:ss"); private final Label current_error = new Label(); private final DateTimeBox start_datebox = new DateTimeBox(); private final DateTimeBox end_datebox = new DateTimeBox(); private final CheckBox autoreload = new CheckBox("Autoreload"); private final ValidatedTextBox autoreoload_interval = new ValidatedTextBox(); private Timer autoreoload_timer; private final ValidatedTextBox yrange = new ValidatedTextBox(); private final ValidatedTextBox y2range = new ValidatedTextBox(); private final CheckBox ylog = new CheckBox(); private final CheckBox y2log = new CheckBox(); private final TextBox ylabel = new TextBox(); private final TextBox y2label = new TextBox(); private final ValidatedTextBox yformat = new ValidatedTextBox(); private final ValidatedTextBox y2format = new ValidatedTextBox(); private final ValidatedTextBox wxh = new ValidatedTextBox(); private String keypos = ""; // Position of the key on the graph. private final CheckBox horizontalkey = new CheckBox("Horizontal layout"); private final CheckBox keybox = new CheckBox("Box"); private final CheckBox nokey = new CheckBox("No key (overrides others)"); // Styling options. private final CheckBox smooth = new CheckBox(); /** * Handles every change to the query form and gets a new graph. * Whenever the user changes one of the parameters of the graph, we want * to automatically get a new graph. */ private final EventsHandler refreshgraph = new EventsHandler() { protected <H extends EventHandler> void onEvent(final DomEvent<H> event) { refreshGraph(); } }; final MetricForm.MetricChangeHandler metric_change_handler = new MetricForm.MetricChangeHandler() { public void onMetricChange(final MetricForm metric) { final int index = metrics.getWidgetIndex(metric); metrics.getTabBar().setTabText(index, getTabTitle(metric)); } private String getTabTitle(final MetricForm metric) { final String metrictext = metric.getMetric(); final int last_period = metrictext.lastIndexOf('.'); if (last_period < 0) { return metrictext; } return metrictext.substring(last_period + 1); } }; final EventsHandler updatey2range = new EventsHandler() { protected <H extends EventHandler> void onEvent(final DomEvent<H> event) { for (final Widget metric : metrics) { if (!(metric instanceof MetricForm)) { continue; } if (((MetricForm) metric).x1y2().getValue()) { y2range.setEnabled(true); y2log.setEnabled(true); y2label.setEnabled(true); y2format.setEnabled(true); return; } } y2range.setEnabled(false); y2log.setEnabled(false); y2label.setEnabled(false); y2format.setEnabled(false); } }; /** List of known aggregation functions. Fetched once from the server. */ private final ArrayList<String> aggregators = new ArrayList<String>(); private final DecoratedTabPanel metrics = new DecoratedTabPanel(); /** Panel to place generated graphs and a box for zoom highlighting. */ private final AbsolutePanel graphbox = new AbsolutePanel(); private final Image graph = new Image(); private final ZoomBox zoom_box = new ZoomBox(); private final Label graphstatus = new Label(); /** Remember the last URI requested to avoid requesting twice the same. */ private String lastgraphuri; /** * We only send one request at a time, how many have we not sent yet?. * Note that we don't buffer pending requests. When there are multiple * ones pending, we will only execute the last one and discard the other * intermediate ones, since the user is no longer interested in them. */ private int pending_requests = 0; /** How many graph requests we make. */ private int nrequests = 0; // Other misc panels. private final FlexTable logs = new FlexTable(); private final FlexTable stats_table = new FlexTable(); private final HTML build_data = new HTML("Loading..."); /** * This is the entry point method. */ public void onModuleLoad() { asyncGetJson(AGGREGATORS_URL, new GotJsonCallback() { public void got(final JSONValue json) { // Do we need more manual type checking? Not sure what will happen // in the browser if something other than an array is returned. final JSONArray aggs = json.isArray(); for (int i = 0; i < aggs.size(); i++) { aggregators.add(aggs.get(i).isString().stringValue()); } ((MetricForm) metrics.getWidget(0)).setAggregators(aggregators); refreshFromQueryString(); refreshGraph(); } }); // All UI elements need to regenerate the graph when changed. { final ValueChangeHandler<Date> vch = new ValueChangeHandler<Date>() { public void onValueChange(final ValueChangeEvent<Date> event) { refreshGraph(); } }; TextBox tb = start_datebox.getTextBox(); tb.addBlurHandler(refreshgraph); tb.addKeyPressHandler(refreshgraph); start_datebox.addValueChangeHandler(vch); tb = end_datebox.getTextBox(); tb.addBlurHandler(refreshgraph); tb.addKeyPressHandler(refreshgraph); end_datebox.addValueChangeHandler(vch); } autoreoload_interval.addBlurHandler(refreshgraph); autoreoload_interval.addKeyPressHandler(refreshgraph); yrange.addBlurHandler(refreshgraph); yrange.addKeyPressHandler(refreshgraph); y2range.addBlurHandler(refreshgraph); y2range.addKeyPressHandler(refreshgraph); ylog.addClickHandler(new AdjustYRangeCheckOnClick(ylog, yrange)); y2log.addClickHandler(new AdjustYRangeCheckOnClick(y2log, y2range)); ylog.addClickHandler(refreshgraph); y2log.addClickHandler(refreshgraph); ylabel.addBlurHandler(refreshgraph); ylabel.addKeyPressHandler(refreshgraph); y2label.addBlurHandler(refreshgraph); y2label.addKeyPressHandler(refreshgraph); yformat.addBlurHandler(refreshgraph); yformat.addKeyPressHandler(refreshgraph); y2format.addBlurHandler(refreshgraph); y2format.addKeyPressHandler(refreshgraph); wxh.addBlurHandler(refreshgraph); wxh.addKeyPressHandler(refreshgraph); horizontalkey.addClickHandler(refreshgraph); keybox.addClickHandler(refreshgraph); nokey.addClickHandler(refreshgraph); smooth.addClickHandler(refreshgraph); yrange.setValidationRegexp("^(" // Nothing or + "|\\[([-+.0-9eE]+|\\*)?" // "[start + ":([-+.0-9eE]+|\\*)?\\])$"); // :end]" yrange.setVisibleLength(5); yrange.setMaxLength(44); // MAX=2^26=20 chars: "[-$MAX:$MAX]" yrange.setText("[0:]"); y2range.setValidationRegexp("^(" // Nothing or + "|\\[([-+.0-9eE]+|\\*)?" // "[start + ":([-+.0-9eE]+|\\*)?\\])$"); // :end]" y2range.setVisibleLength(5); y2range.setMaxLength(44); // MAX=2^26=20 chars: "[-$MAX:$MAX]" y2range.setText("[0:]"); y2range.setEnabled(false); y2log.setEnabled(false); ylabel.setVisibleLength(10); ylabel.setMaxLength(50); // Arbitrary limit. y2label.setVisibleLength(10); y2label.setMaxLength(50); // Arbitrary limit. y2label.setEnabled(false); yformat.setValidationRegexp("^(|.*%..*)$"); // Nothing or at least one %? yformat.setVisibleLength(10); yformat.setMaxLength(16); // Arbitrary limit. y2format.setValidationRegexp("^(|.*%..*)$"); // Nothing or at least one %? y2format.setVisibleLength(10); y2format.setMaxLength(16); // Arbitrary limit. y2format.setEnabled(false); wxh.setValidationRegexp("^[1-9][0-9]{2,}x[1-9][0-9]{2,}$"); // 100x100 wxh.setVisibleLength(9); wxh.setMaxLength(11); // 99999x99999 wxh.setText((Window.getClientWidth() - 20) + "x" + (Window.getClientHeight() * 4 / 5)); final FlexTable table = new FlexTable(); table.setText(0, 0, "From"); { final HorizontalPanel hbox = new HorizontalPanel(); hbox.add(new InlineLabel("To")); final Anchor now = new Anchor("(now)"); now.addClickHandler(new ClickHandler() { public void onClick(final ClickEvent event) { end_datebox.setValue(new Date()); refreshGraph(); } }); hbox.add(now); hbox.add(autoreload); hbox.setWidth("100%"); table.setWidget(0, 1, hbox); } autoreload.addValueChangeHandler(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(final ValueChangeEvent<Boolean> event) { if (autoreload.getValue()) { final HorizontalPanel hbox = new HorizontalPanel(); hbox.setWidth("100%"); hbox.add(new InlineLabel("Every:")); hbox.add(autoreoload_interval); hbox.add(new InlineLabel("seconds")); table.setWidget(1, 1, hbox); if (autoreoload_interval.getValue().isEmpty()) { autoreoload_interval.setValue("15"); } autoreoload_interval.setFocus(true); lastgraphuri = ""; // Force refreshGraph. refreshGraph(); // Trigger the 1st auto-reload } else { table.setWidget(1, 1, end_datebox); } } }); autoreoload_interval.setValidationRegexp("^([5-9]|[1-9][0-9]+)$"); // >=5s autoreoload_interval.setMaxLength(4); autoreoload_interval.setVisibleLength(8); table.setWidget(1, 0, start_datebox); table.setWidget(1, 1, end_datebox); { final HorizontalPanel hbox = new HorizontalPanel(); hbox.add(new InlineLabel("WxH:")); hbox.add(wxh); table.setWidget(0, 3, hbox); } { addMetricForm("metric 1", 0); metrics.selectTab(0); metrics.add(new InlineLabel("Loading..."), "+"); metrics.addBeforeSelectionHandler(new BeforeSelectionHandler<Integer>() { public void onBeforeSelection(final BeforeSelectionEvent<Integer> event) { final int item = event.getItem(); final int nitems = metrics.getWidgetCount(); if (item == nitems - 1) { // Last item: the "+" was clicked. event.cancel(); final MetricForm metric = addMetricForm("metric " + nitems, item); metrics.selectTab(item); metric.setFocus(true); } } }); table.setWidget(2, 0, metrics); } table.getFlexCellFormatter().setColSpan(2, 0, 2); table.getFlexCellFormatter().setRowSpan(1, 3, 2); final DecoratedTabPanel optpanel = new DecoratedTabPanel(); optpanel.add(makeAxesPanel(), "Axes"); optpanel.add(makeKeyPanel(), "Key"); optpanel.add(makeStylePanel(), "Style"); optpanel.selectTab(0); table.setWidget(1, 3, optpanel); final DecoratorPanel decorator = new DecoratorPanel(); decorator.setWidget(table); final VerticalPanel graphpanel = new VerticalPanel(); graphpanel.add(decorator); { final VerticalPanel graphvbox = new VerticalPanel(); graphvbox.add(graphstatus); graph.setVisible(false); // Put the graph image element and the zoombox elements inside the absolute panel graphbox.add(graph, 0, 0); zoom_box.setVisible(false); graphbox.add(zoom_box, 0, 0); graph.addMouseOverHandler(new MouseOverHandler() { public void onMouseOver(final MouseOverEvent event) { final Style style = graphbox.getElement().getStyle(); style.setCursor(Cursor.CROSSHAIR); } }); graph.addMouseOutHandler(new MouseOutHandler() { public void onMouseOut(final MouseOutEvent event) { final Style style = graphbox.getElement().getStyle(); style.setCursor(Cursor.AUTO); } }); graphvbox.add(graphbox); graph.addErrorHandler(new ErrorHandler() { public void onError(final ErrorEvent event) { graphstatus.setText("Oops, failed to load the graph."); } }); graph.addLoadHandler(new LoadHandler() { public void onLoad(final LoadEvent event) { graphbox.setWidth(graph.getWidth() + "px"); graphbox.setHeight(graph.getHeight() + "px"); } }); graphpanel.add(graphvbox); } final DecoratedTabPanel mainpanel = new DecoratedTabPanel(); mainpanel.setWidth("100%"); mainpanel.add(graphpanel, "Graph"); mainpanel.add(stats_table, "Stats"); mainpanel.add(logs, "Logs"); mainpanel.add(build_data, "Version"); mainpanel.selectTab(0); mainpanel.addBeforeSelectionHandler(new BeforeSelectionHandler<Integer>() { public void onBeforeSelection(final BeforeSelectionEvent<Integer> event) { clearError(); final int item = event.getItem(); switch (item) { case 1: refreshStats(); return; case 2: refreshLogs(); return; case 3: refreshVersion(); return; } } }); final VerticalPanel root = new VerticalPanel(); root.setWidth("100%"); root.add(current_error); current_error.setVisible(false); current_error.addStyleName("dateBoxFormatError"); root.add(mainpanel); RootPanel.get("queryuimain").add(root); // Must be done at the end, once all the widgets are attached. ensureSameWidgetSize(optpanel); History.addHistoryListener(this); } @Override public void onHistoryChanged(String historyToken) { refreshFromQueryString(); refreshGraph(); } /** Additional styling options. */ private Grid makeStylePanel() { final Grid grid = new Grid(5, 3); grid.setText(0, 1, "Smooth"); grid.setWidget(0, 2, smooth); return grid; } /** * Builds the panel containing customizations for the axes of the graph. */ private Grid makeAxesPanel() { final Grid grid = new Grid(5, 3); grid.setText(0, 1, "Y"); grid.setText(0, 2, "Y2"); setTextAlignCenter(grid.getRowFormatter().getElement(0)); grid.setText(1, 0, "Label"); grid.setWidget(1, 1, ylabel); grid.setWidget(1, 2, y2label); grid.setText(2, 0, "Format"); grid.setWidget(2, 1, yformat); grid.setWidget(2, 2, y2format); grid.setText(3, 0, "Range"); grid.setWidget(3, 1, yrange); grid.setWidget(3, 2, y2range); grid.setText(4, 0, "Log scale"); grid.setWidget(4, 1, ylog); grid.setWidget(4, 2, y2log); setTextAlignCenter(grid.getCellFormatter().getElement(4, 1)); setTextAlignCenter(grid.getCellFormatter().getElement(4, 2)); return grid; } private MetricForm addMetricForm(final String label, final int item) { final MetricForm metric = new MetricForm(refreshgraph); metric.x1y2().addClickHandler(updatey2range); metric.setMetricChangeHandler(metric_change_handler); metric.setAggregators(aggregators); metrics.insert(metric, label, item); return metric; } private final HashMap<String, RadioButton> keypos_map = new HashMap<String, RadioButton>(17); /** * Small helper to build a radio button used to change the position of the * key of the graph. */ private RadioButton addKeyRadioButton(final Grid grid, final int row, final int col, final String pos) { final RadioButton rb = new RadioButton("keypos"); rb.addClickHandler(new ClickHandler() { public void onClick(final ClickEvent event) { keypos = pos; } }); rb.addClickHandler(refreshgraph); grid.setWidget(row, col, rb); keypos_map.put(pos, rb); return rb; } /** * Builds the panel containing the customizations for the key of the graph. */ private Widget makeKeyPanel() { final Grid grid = new Grid(5, 5); addKeyRadioButton(grid, 0, 0, "out left top"); addKeyRadioButton(grid, 0, 2, "out center top"); addKeyRadioButton(grid, 0, 4, "out right top"); addKeyRadioButton(grid, 1, 1, "top left"); addKeyRadioButton(grid, 1, 2, "top center"); addKeyRadioButton(grid, 1, 3, "top right").setValue(true); addKeyRadioButton(grid, 2, 0, "out center left"); addKeyRadioButton(grid, 2, 1, "center left"); addKeyRadioButton(grid, 2, 2, "center"); addKeyRadioButton(grid, 2, 3, "center right"); addKeyRadioButton(grid, 2, 4, "out center right"); addKeyRadioButton(grid, 3, 1, "bottom left"); addKeyRadioButton(grid, 3, 2, "bottom center"); addKeyRadioButton(grid, 3, 3, "bottom right"); addKeyRadioButton(grid, 4, 0, "out bottom left"); addKeyRadioButton(grid, 4, 2, "out bottom center"); addKeyRadioButton(grid, 4, 4, "out bottom right"); final Grid.CellFormatter cf = grid.getCellFormatter(); cf.getElement(1, 1).getStyle().setProperty("borderLeft", "1px solid #000"); cf.getElement(1, 1).getStyle().setProperty("borderTop", "1px solid #000"); cf.getElement(1, 2).getStyle().setProperty("borderTop", "1px solid #000"); cf.getElement(1, 3).getStyle().setProperty("borderTop", "1px solid #000"); cf.getElement(1, 3).getStyle().setProperty("borderRight", "1px solid #000"); cf.getElement(2, 1).getStyle().setProperty("borderLeft", "1px solid #000"); cf.getElement(2, 3).getStyle().setProperty("borderRight", "1px solid #000"); cf.getElement(3, 1).getStyle().setProperty("borderLeft", "1px solid #000"); cf.getElement(3, 1).getStyle().setProperty("borderBottom", "1px solid #000"); cf.getElement(3, 2).getStyle().setProperty("borderBottom", "1px solid #000"); cf.getElement(3, 3).getStyle().setProperty("borderBottom", "1px solid #000"); cf.getElement(3, 3).getStyle().setProperty("borderRight", "1px solid #000"); final VerticalPanel vbox = new VerticalPanel(); vbox.add(new InlineLabel("Key location:")); vbox.add(grid); vbox.add(horizontalkey); keybox.setValue(true); vbox.add(keybox); vbox.add(nokey); return vbox; } private void refreshStats() { asyncGetJson(STATS_URL, new GotJsonCallback() { public void got(final JSONValue json) { final JSONArray stats = json.isArray(); final int nstats = stats.size(); for (int i = 0; i < nstats; i++) { final String stat = stats.get(i).isString().stringValue(); String part = stat.substring(0, stat.indexOf(' ')); stats_table.setText(i, 0, part); // metric int pos = part.length() + 1; part = stat.substring(pos, stat.indexOf(' ', pos)); stats_table.setText(i, 1, part); // timestamp pos += part.length() + 1; part = stat.substring(pos, stat.indexOf(' ', pos)); stats_table.setText(i, 2, part); // value pos += part.length() + 1; stats_table.setText(i, 3, stat.substring(pos)); // tags } } }); } private void refreshVersion() { asyncGetJson(VERSION_URL, new GotJsonCallback() { public void got(final JSONValue json) { final JSONObject bd = json.isObject(); final JSONString shortrev = bd.get("short_revision").isString(); final JSONString status = bd.get("repo_status").isString(); final JSONString stamp = bd.get("timestamp").isString(); final JSONString user = bd.get("user").isString(); final JSONString host = bd.get("host").isString(); final JSONString repo = bd.get("repo").isString(); final JSONString version = bd.get("version").isString(); build_data.setHTML( "OpenTSDB version [" + version.stringValue() + "] built from revision " + shortrev.stringValue() + " in a " + status.stringValue() + " state<br/>" + "Built on " + new Date((Long.parseLong(stamp.stringValue()) * 1000)) + " by " + user.stringValue() + '@' + host.stringValue() + ':' + repo.stringValue()); } }); } private void refreshLogs() { asyncGetJson(LOGS_URL, new GotJsonCallback() { public void got(final JSONValue json) { final JSONArray logmsgs = json.isArray(); final int nmsgs = logmsgs.size(); final FlexTable.FlexCellFormatter fcf = logs.getFlexCellFormatter(); final FlexTable.RowFormatter rf = logs.getRowFormatter(); for (int i = 0; i < nmsgs; i++) { final String msg = logmsgs.get(i).isString().stringValue(); String part = msg.substring(0, msg.indexOf('\t')); logs.setText(i * 2, 0, new Date(Integer.valueOf(part) * 1000L).toString()); logs.setText(i * 2 + 1, 0, ""); // So we can change the style ahead. int pos = part.length() + 1; part = msg.substring(pos, msg.indexOf('\t', pos)); if ("WARN".equals(part)) { rf.getElement(i * 2).getStyle().setBackgroundColor("#FCC"); rf.getElement(i * 2 + 1).getStyle().setBackgroundColor("#FCC"); } else if ("ERROR".equals(part)) { rf.getElement(i * 2).getStyle().setBackgroundColor("#F99"); rf.getElement(i * 2 + 1).getStyle().setBackgroundColor("#F99"); } else { rf.getElement(i * 2).getStyle().clearBackgroundColor(); rf.getElement(i * 2 + 1).getStyle().clearBackgroundColor(); if ((i % 2) == 0) { rf.addStyleName(i * 2, "subg"); rf.addStyleName(i * 2 + 1, "subg"); } } pos += part.length() + 1; logs.setText(i * 2, 1, part); // level part = msg.substring(pos, msg.indexOf('\t', pos)); pos += part.length() + 1; logs.setText(i * 2, 2, part); // thread part = msg.substring(pos, msg.indexOf('\t', pos)); pos += part.length() + 1; if (part.startsWith("net.opentsdb.")) { part = part.substring(13); } else if (part.startsWith("org.hbase.")) { part = part.substring(10); } logs.setText(i * 2, 3, part); // logger logs.setText(i * 2 + 1, 0, msg.substring(pos)); // message fcf.setColSpan(i * 2 + 1, 0, 4); rf.addStyleName(i * 2, "fwf"); rf.addStyleName(i * 2 + 1, "fwf"); } } }); } private void addLabels(final StringBuilder url) { final String ylabel = this.ylabel.getText(); if (!ylabel.isEmpty()) { url.append("&ylabel=").append(ylabel); } if (y2label.isEnabled()) { final String y2label = this.y2label.getText(); if (!y2label.isEmpty()) { url.append("&y2label=").append(y2label); } } } private void addFormats(final StringBuilder url) { final String yformat = this.yformat.getText(); if (!yformat.isEmpty()) { url.append("&yformat=").append(yformat); } if (y2format.isEnabled()) { final String y2format = this.y2format.getText(); if (!y2format.isEmpty()) { url.append("&y2format=").append(y2format); } } } private void addYRanges(final StringBuilder url) { final String yrange = this.yrange.getText(); if (!yrange.isEmpty()) { url.append("&yrange=").append(yrange); } if (y2range.isEnabled()) { final String y2range = this.y2range.getText(); if (!y2range.isEmpty()) { url.append("&y2range=").append(y2range); } } } private void addLogscales(final StringBuilder url) { if (ylog.getValue()) { url.append("&ylog"); } if (y2log.isEnabled() && y2log.getValue()) { url.append("&y2log"); } } /** * Maybe sets the text of a {@link TextBox} from a query string parameter. * @param qs A parsed query string. * @param key Name of the query string parameter. * If this parameter wasn't passed, the {@link TextBox} will be emptied. * @param tb The {@link TextBox} to change. */ private static void maybeSetTextbox(final QueryString qs, final String key, final TextBox tb) { final ArrayList<String> values = qs.get(key); if (values == null) { tb.setText(""); return; } tb.setText(values.get(0)); } /** * Sets the text of a {@link TextBox} from a query string parameter. * @param qs A parsed query string. * @param key Name of the query string parameter. * @param tb The {@link TextBox} to change. */ private static void setTextbox(final QueryString qs, final String key, final TextBox tb) { final ArrayList<String> values = qs.get(key); if (values != null) { tb.setText(values.get(0)); } } private static QueryString getQueryString(final String qs) { return qs.isEmpty() ? new QueryString() : QueryString.decode(qs); } private void refreshFromQueryString() { final QueryString qs = getQueryString(URL.decode(History.getToken())); maybeSetTextbox(qs, "start", start_datebox.getTextBox()); maybeSetTextbox(qs, "end", end_datebox.getTextBox()); setTextbox(qs, "wxh", wxh); autoreload.setValue(qs.containsKey("autoreload"), true); maybeSetTextbox(qs, "autoreload", autoreoload_interval); final ArrayList<String> newmetrics = qs.get("m"); if (newmetrics == null) { // Clear all metric forms. final int toremove = metrics.getWidgetCount() - 1; addMetricForm("metric 1", 0); metrics.selectTab(0); for (int i = 0; i < toremove; i++) { metrics.remove(1); } return; } final int n = newmetrics.size(); // We want this many metrics. ArrayList<String> options = qs.get("o"); if (options == null) { options = new ArrayList<String>(n); } for (int i = options.size(); i < n; i++) { // Make both arrays equal size. options.add(""); // Add missing o's. } for (int i = 0; i < newmetrics.size(); ++i) { if (i == metrics.getWidgetCount() - 1) { addMetricForm("", i); } final MetricForm metric = (MetricForm) metrics.getWidget(i); metric.updateFromQueryString(newmetrics.get(i), options.get(i)); } // Remove extra metric forms. final int m = metrics.getWidgetCount() - 1; // We have this many metrics. int showing = metrics.getTabBar().getSelectedTab(); // Currently selected. for (int i = m - 1; i >= n; i--) { if (showing == i) { // If we're about to remove the currently selected, metrics.selectTab(--showing); // fix focus to not wind up nowhere. } metrics.remove(i); } updatey2range.onEvent(null); maybeSetTextbox(qs, "ylabel", ylabel); maybeSetTextbox(qs, "y2label", y2label); maybeSetTextbox(qs, "yformat", yformat); maybeSetTextbox(qs, "y2format", y2format); maybeSetTextbox(qs, "yrange", yrange); maybeSetTextbox(qs, "y2range", y2range); ylog.setValue(qs.containsKey("ylog")); y2log.setValue(qs.containsKey("y2log")); if (qs.containsKey("key")) { final String key = qs.getFirst("key"); keybox.setValue(key.contains(" box")); horizontalkey.setValue(key.contains(" horiz")); keypos = key.replaceAll(" (box|horiz\\w*)", ""); keypos_map.get(keypos).setChecked(true); } else { keybox.setValue(false); horizontalkey.setValue(false); keypos_map.get("top right").setChecked(true); keypos = ""; } nokey.setValue(qs.containsKey("nokey")); smooth.setValue(qs.containsKey("smooth")); } private void refreshGraph() { final Date start = start_datebox.getValue(); if (start == null) { graphstatus.setText("Please specify a start time."); return; } final Date end = end_datebox.getValue(); if (end != null && !autoreload.getValue()) { if (end.getTime() <= start.getTime()) { end_datebox.addStyleName("dateBoxFormatError"); graphstatus.setText("End time must be after start time!"); return; } } final StringBuilder url = new StringBuilder(); url.append("/q?start="); final String start_text = start_datebox.getTextBox().getText(); if (start_text.endsWith(" ago") || start_text.endsWith("-ago")) { url.append(start_text); } else { url.append(FULLDATE.format(start)); } if (end != null && !autoreload.getValue()) { url.append("&end="); final String end_text = end_datebox.getTextBox().getText(); if (end_text.endsWith(" ago") || end_text.endsWith("-ago")) { url.append(end_text); } else { url.append(FULLDATE.format(end)); } } else { // If there's no end-time, the graph may change while the URL remains // the same. No browser seems to re-fetch an image once it's been // fetched, even if we destroy the DOM object and re-created it with the // same src attribute. This has nothing to do with caching headers sent // by the server. The browsers simply won't retrieve the same URL again // through JavaScript manipulations, period. So as a workaround, we add // a special parameter that the server will delete from the query. url.append("&ignore=" + nrequests++); } if (!addAllMetrics(url)) { return; } addLabels(url); addFormats(url); addYRanges(url); addLogscales(url); if (nokey.getValue()) { url.append("&nokey"); } else if (!keypos.isEmpty() || horizontalkey.getValue()) { url.append("&key="); if (!keypos.isEmpty()) { url.append(keypos); } if (horizontalkey.getValue()) { url.append(" horiz"); } if (keybox.getValue()) { url.append(" box"); } } url.append("&wxh=").append(wxh.getText()); if (smooth.getValue()) { url.append("&smooth=csplines"); } final String unencodedUri = url.toString(); final String uri = URL.encode(unencodedUri); if (uri.equals(lastgraphuri)) { return; // Don't re-request the same graph. } else if (pending_requests++ > 0) { return; } lastgraphuri = uri; graphstatus.setText("Loading graph..."); asyncGetJson(uri + "&json", new GotJsonCallback() { public void got(final JSONValue json) { if (autoreoload_timer != null) { autoreoload_timer.cancel(); autoreoload_timer = null; } final JSONObject result = json.isObject(); final JSONValue err = result.get("err"); String msg = ""; if (err != null) { displayError("An error occurred while generating the graph: " + err.isString().stringValue()); graphstatus.setText("Please correct the error above."); } else { clearError(); String history = unencodedUri.substring(3) // Remove "/q?". .replaceFirst("ignore=[^&]*&", ""); // Unnecessary cruft. if (autoreload.getValue()) { history += "&autoreload=" + autoreoload_interval.getText(); } if (!history.equals(URL.decode(History.getToken()))) { History.newItem(history, false); } final JSONValue nplotted = result.get("plotted"); final JSONValue cachehit = result.get("cachehit"); if (cachehit != null) { msg += "Cache hit (" + cachehit.isString().stringValue() + "). "; } if (nplotted != null && nplotted.isNumber().doubleValue() > 0) { graph.setUrl(uri + "&png"); graph.setVisible(true); msg += result.get("points").isNumber() + " points retrieved, " + nplotted + " points plotted"; } else { graph.setVisible(false); msg += "Your query didn't return anything"; } final JSONValue timing = result.get("timing"); if (timing != null) { msg += " in " + timing + "ms."; } else { msg += '.'; } } final JSONValue info = result.get("info"); if (info != null) { if (!msg.isEmpty()) { msg += ' '; } msg += info.isString().stringValue(); } graphstatus.setText(msg); if (result.get("etags") != null) { final JSONArray etags = result.get("etags").isArray(); final int netags = etags.size(); for (int i = 0; i < netags; i++) { if (i >= metrics.getWidgetCount()) { break; } final Widget widget = metrics.getWidget(i); if (!(widget instanceof MetricForm)) { break; } final MetricForm metric = (MetricForm) widget; final JSONArray tags = etags.get(i).isArray(); // Skip if no tags were associated with the query. if (null != tags) { for (int j = 0; j < tags.size(); j++) { metric.autoSuggestTag(tags.get(j).isString().stringValue()); } } } } if (autoreload.getValue()) { final int reload_in = Integer.parseInt(autoreoload_interval.getValue()); if (reload_in >= 5) { autoreoload_timer = new Timer() { public void run() { // Verify that we still want auto reload and that the graph // hasn't been updated in the mean time. if (autoreload.getValue() && lastgraphuri == uri) { // Force refreshGraph to believe that we want a new graph. lastgraphuri = ""; refreshGraph(); } } }; autoreoload_timer.schedule(reload_in * 1000); } } if (--pending_requests > 0) { pending_requests = 0; refreshGraph(); } } }); } private boolean addAllMetrics(final StringBuilder url) { boolean found_metric = false; for (final Widget widget : metrics) { if (!(widget instanceof MetricForm)) { continue; } final MetricForm metric = (MetricForm) widget; found_metric |= metric.buildQueryString(url); } if (!found_metric) { graphstatus.setText("Please specify a metric."); } return found_metric; } private void asyncGetJson(final String url, final GotJsonCallback callback) { final RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url); try { builder.sendRequest(null, new RequestCallback() { public void onError(final Request request, final Throwable e) { displayError("Failed to get " + url + ": " + e.getMessage()); // Since we don't call the callback we've been given, reset this // bit of state as we're not going to retry anything right now. pending_requests = 0; } public void onResponseReceived(final Request request, final Response response) { final int code = response.getStatusCode(); if (code == Response.SC_OK) { clearError(); callback.got(JSONParser.parse(response.getText())); return; } else if (code >= Response.SC_BAD_REQUEST) { // 400+ => Oops. // Since we don't call the callback we've been given, reset this // bit of state as we're not going to retry anything right now. pending_requests = 0; String err = response.getText(); // If the response looks like a JSON object, it probably contains // an error message. if (!err.isEmpty() && err.charAt(0) == '{') { final JSONValue json = JSONParser.parse(err); final JSONObject result = json == null ? null : json.isObject(); final JSONValue jerr = result == null ? null : result.get("err"); final JSONString serr = jerr == null ? null : jerr.isString(); err = serr.stringValue(); // If the error message has multiple lines (which is common if // it contains a stack trace), show only the first line and // hide the rest in a panel users can expand. final int newline = err.indexOf('\n', 1); final String msg = "Request failed: " + response.getStatusText(); if (newline < 0) { displayError(msg + ": " + err); } else { displayError(msg); final DisclosurePanel dp = new DisclosurePanel(err.substring(0, newline)); RootPanel.get("queryuimain").add(dp); // Attach the widget. final InlineLabel content = new InlineLabel(err.substring(newline, err.length())); content.addStyleName("fwf"); // For readable stack traces. dp.setContent(content); current_error.getElement().appendChild(dp.getElement()); } } else { displayError("Request failed while getting " + url + ": " + response.getStatusText()); // Since we don't call the callback we've been given, reset this // bit of state as we're not going to retry anything right now. pending_requests = 0; } graphstatus.setText(""); } } }); } catch (RequestException e) { displayError("Failed to get " + url + ": " + e.getMessage()); } } private void displayError(final String errmsg) { current_error.setText(errmsg); current_error.setVisible(true); } private void clearError() { current_error.setVisible(false); } static void setTextAlignCenter(final Element element) { element.getStyle().setProperty("textAlign", "center"); } /** Zoom box and associated event handlers. */ private final class ZoomBox extends HTML implements MouseUpHandler, MouseMoveHandler, MouseDownHandler { /** "Fudge factor" to account for the axes present on the image. */ private static final int OFFSET_WITH_AXIS = 45; private static final int OFFSET_WITHOUT_AXIS = 15; private boolean zoom_selection_active = false; /** Rectangle of the selection. */ private int start_x; private int end_x; private int start_y; private int end_y; private HandlerRegistration graph_move_handler; private HandlerRegistration box_move_handler; ZoomBox() { // Set ourselves up as the event handler for all mouse-draggable events. graph.addMouseDownHandler(this); graph.addMouseUpHandler(this); // Also add the handlers on the actual zoom highlight box (this is in // case the cursor gets on the zoombox, so that it keeps responding // correctly). super.addMouseUpHandler(this); final Style style = super.getElement().getStyle(); style.setProperty("background", "red"); style.setProperty("filter", "alpha(opacity=50)"); style.setProperty("opacity", "0.4"); // Needed to make this object focusable. super.getElement().setAttribute("tabindex", "-1"); } @Override public void onMouseDown(final MouseDownEvent event) { event.preventDefault(); // Check if the zoom selection is active, if so, it's possible that the // mouse left the browser mid-selection and got stuck enabled even // though the mouse isn't still pressed. If that's the case, do a similar // operation to the onMouseUp event. if (zoom_selection_active) { endSelection(event); return; } final Element image = graph.getElement(); zoom_selection_active = true; start_x = event.getRelativeX(image); start_y = event.getRelativeY(image); end_x = 0; end_y = 0; graphbox.setWidgetPosition(this, start_x, start_y); super.setWidth("0px"); super.setHeight("0px"); super.setVisible(true); // Workaround to steal the focus from whatever had it previously, // which may cause the graph to reload as a side effect. super.getElement().focus(); graph_move_handler = graph.addMouseMoveHandler(this); box_move_handler = super.addMouseMoveHandler(this); } @Override public void onMouseMove(final MouseMoveEvent event) { event.preventDefault(); final int x = event.getRelativeX(graph.getElement()); final int y = event.getRelativeY(graph.getElement()); int left; int top; int width; int height; // Figure out the top, left, height, and width of the box based // on current cursor location. if (x < start_x) { left = x; width = start_x - x; } else { left = start_x; width = x - start_x; } if (y < start_y) { top = y; height = start_y - y; } else { top = start_y; height = y - start_y; } // Resize / move the box as needed based on cursor location. super.setVisible(false); graphbox.setWidgetPosition(this, left, top); super.setWidth(width + "px"); super.setHeight(height + "px"); super.setVisible(true); } @Override public void onMouseUp(final MouseUpEvent event) { if (zoom_selection_active) { endSelection(event); } } /** * Perform operations for when a user completes their selection. * This involves removing the highlight box and kicking off the * zoom in operation. * @param event The event that triggered the end of the selection. */ private <H extends EventHandler> void endSelection(final MouseEvent<H> event) { zoom_selection_active = false; // Stop tracking cursor movements to improve performance. graph_move_handler.removeHandler(); graph_move_handler = null; box_move_handler.removeHandler(); box_move_handler = null; final Element image = graph.getElement(); end_x = event.getRelativeX(image); end_y = event.getRelativeY(image); // Hide the zoom box super.setVisible(false); super.setWidth("0px"); super.setHeight("0px"); // Calculate the true start/end points of the zoom area selected by // mouse. If the mouse was dragged left on the graph before being // let up, then start_x is the right-most edge of the zoomable area. // If the mouse was dragged right on the graph before being let up, // then start_x is the left-most edge of the zoomable area. if (start_x < end_x) { start_x = start_x - OFFSET_WITH_AXIS; end_x = end_x - OFFSET_WITH_AXIS; } else { final int saved_start = start_x; start_x = end_x - OFFSET_WITH_AXIS; end_x = saved_start - OFFSET_WITH_AXIS; } int actual_width = graph.getWidth() - OFFSET_WITH_AXIS; if (y2range.isEnabled()) { // If we have a second Y axis. actual_width -= OFFSET_WITH_AXIS; } else { actual_width -= OFFSET_WITHOUT_AXIS; } // Prevent division by zero if image is pathologically small. // or: Prevent changing anything if the distance the cursor traveled was // too small (as happens during a simple click or unintentional click). if (actual_width < 1 || end_x - start_x <= 5) { return; } // Total span of time represented between the start and end times. final long duration; final long start = start_datebox.getValue().getTime(); { final long end; final Date end_date = end_datebox.getValue(); if (end_date != null) { end = end_date.getTime(); } else { end = new Date().getTime(); } duration = end - start; } // Get the start and end positions of the mouse drag operation on the // image as a percentage of the image size. final long start_change = start_x * duration / actual_width; final long end_change = end_x * duration / actual_width; start_datebox.setValue(new Date(start + start_change)); end_datebox.setValue(new Date(start + end_change)); refreshGraph(); } }; private final class AdjustYRangeCheckOnClick implements ClickHandler { private final CheckBox box; private final ValidatedTextBox range; public AdjustYRangeCheckOnClick(final CheckBox box, final ValidatedTextBox range) { this.box = box; this.range = range; } public void onClick(final ClickEvent event) { if (box.isEnabled() && box.getValue() && "[0:]".equals(range.getValue())) { range.setValue("[1:]"); } else if (box.isEnabled() && !box.getValue() && "[1:]".equals(range.getValue())) { range.setValue("[0:]"); } } }; /** * Ensures all the widgets in the given panel have the same size. * Otherwise by default the panel will automatically resize itself to the * contents of the currently active panel's widget, which is annoying * because it makes a number of things move around in the UI. * @param panel The panel containing the widgets to resize. */ private static void ensureSameWidgetSize(final DecoratedTabPanel panel) { if (!panel.isAttached()) { throw new IllegalArgumentException("panel not attached: " + panel); } int maxw = 0; int maxh = 0; for (final Widget widget : panel) { final int w = widget.getOffsetWidth(); final int h = widget.getOffsetHeight(); if (w > maxw) { maxw = w; } if (h > maxh) { maxh = h; } } if (maxw == 0 || maxh == 0) { throw new IllegalArgumentException("maxw=" + maxw + " maxh=" + maxh); } for (final Widget widget : panel) { setOffsetWidth(widget, maxw); setOffsetHeight(widget, maxh); } } /** * Properly sets the total width of a widget. * This takes into account decorations such as border, margin, and padding. */ private static void setOffsetWidth(final Widget widget, int width) { widget.setWidth(width + "px"); final int offset = widget.getOffsetWidth(); if (offset > 0) { width -= offset - width; if (width > 0) { widget.setWidth(width + "px"); } } } /** * Properly sets the total height of a widget. * This takes into account decorations such as border, margin, and padding. */ private static void setOffsetHeight(final Widget widget, int height) { widget.setHeight(height + "px"); final int offset = widget.getOffsetHeight(); if (offset > 0) { height -= offset - height; if (height > 0) { widget.setHeight(height + "px"); } } } }
gpl-3.0
LeoTremblay/activityinfo
server/src/main/java/org/activityinfo/server/command/handler/sync/AdminLocalState.java
1945
package org.activityinfo.server.command.handler.sync; /* * #%L * ActivityInfo Server * %% * Copyright (C) 2009 - 2013 UNICEF * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ public class AdminLocalState { private int version = 0; private boolean complete = false; private int lastId; public AdminLocalState(String localState) { if (localState != null) { String[] tokens = localState.split(","); setVersion(Integer.parseInt(tokens[0])); if (tokens.length == 1) { setComplete(true); } else { setComplete(false); setLastId(Integer.parseInt(tokens[1])); } } } @Override public String toString() { if (isComplete()) { return Integer.toString(getVersion()); } else { return getVersion() + "," + getLastId(); } } void setVersion(int version) { this.version = version; } int getVersion() { return version; } void setComplete(boolean complete) { this.complete = complete; } boolean isComplete() { return complete; } void setLastId(int lastId) { this.lastId = lastId; } int getLastId() { return lastId; } }
gpl-3.0
arraydev/snap-engine
snap-core/src/main/java/org/esa/snap/util/geotiff/IIOUtils.java
11554
/* * Copyright (C) 2010 Brockmann Consult GmbH (info@brockmann-consult.de) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.util.geotiff; import org.jdom.Element; import org.jdom.input.DOMBuilder; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import javax.imageio.IIOException; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageReadParam; import javax.imageio.ImageReader; import javax.imageio.ImageTypeSpecifier; import javax.imageio.ImageWriter; import javax.imageio.metadata.IIOMetadata; import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.ImageOutputStream; import java.io.File; import java.io.IOException; import java.util.Iterator; public class IIOUtils { /** * Returns a <code>BufferedImage</code> as the result of decoding a supplied <code>File</code> with an * <code>ImageReader</code> chosen automatically from among those currently registered. The <code>File</code> is * wrapped in an <code>ImageInputStream</code>. If no registered <code>ImageReader</code> claims to be able to * readImage the resulting stream, <code>null</code> is returned. * <p> The current cache settings from <code>getUseCache</code>and <code>getCacheDirectory</code> will be used to * control caching in the <code>ImageInputStream</code> that is created. * <p> Note that there is no <code>readImage</code> method that takes a filename as a <code>String</code>; use this * method instead after creating a <code>File</code> from the filename. * <p> This methods does not attempt to locate <code>ImageReader</code>s that can readImage directly from a * <code>File</code>; that may be accomplished using <code>IIORegistry</code> and <code>ImageReaderSpi</code>. * * @param input a <code>File</code> to readImage from. * * @return a <code>BufferedImage</code> containing the decoded contents of the input, or <code>null</code>. * * @throws IllegalArgumentException if <code>input</code> is <code>null</code>. * @throws java.io.IOException if an error occurs during reading. */ public static IIOImage readImage(File input) throws IOException { if (input == null) { throw new IllegalArgumentException("input == null!"); } if (!input.canRead()) { throw new IIOException("Can't readImage input file!"); } ImageInputStream stream = ImageIO.createImageInputStream(input); if (stream == null) { throw new IIOException("Can't create an ImageInputStream!"); } return readImage(stream); } /** * Returns a <code>BufferedImage</code> as the result of decoding a supplied <code>ImageInputStream</code> with an * <code>ImageReader</code> chosen automatically from among those currently registered. If no registered * <code>ImageReader</code> claims to be able to readImage the stream, <code>null</code> is returned. * * @param stream an <code>ImageInputStream</code> to readImage from. * * @return a <code>BufferedImage</code> containing the decoded contents of the input, or <code>null</code>. * * @throws IllegalArgumentException if <code>stream</code> is <code>null</code>. * @throws IOException if an error occurs during reading. */ public static IIOImage readImage(ImageInputStream stream) throws IOException { if (stream == null) { throw new IllegalArgumentException("stream == null!"); } Iterator iter = ImageIO.getImageReaders(stream); if (!iter.hasNext()) { return null; } ImageReader reader = (ImageReader) iter.next(); ImageReadParam param = reader.getDefaultReadParam(); reader.setInput(stream, true, true); IIOImage iioImage = reader.readAll(0, param); stream.close(); reader.dispose(); return iioImage; } /** * Writes an image using an arbitrary <code>ImageWriter</code> that supports the given format to a * <code>File</code>. If there is already a <code>File</code> present, its contents are discarded. * * @param iioImage the image data to be written. * @param formatName a <code>String</code> containg the informal name of the format. * @param output a <code>File</code> to be written to. * * @return <code>false</code> if no appropriate writer is found. * * @throws IllegalArgumentException if any parameter is <code>null</code>. * @throws IOException if an error occurs during writing. */ public static boolean writeImage(IIOImage iioImage, String formatName, File output) throws IOException { if (output == null) { throw new IllegalArgumentException("output == null!"); } ImageOutputStream stream = null; try { output.delete(); stream = ImageIO.createImageOutputStream(output); } catch (IOException e) { throw new IIOException("Can't create output stream!", e); } boolean val = writeImage(iioImage, formatName, stream); stream.close(); return val; } /** * Writes an image using the an arbitrary <code>ImageWriter</code> that supports the given format to an * <code>ImageOutputStream</code>. The image is written to the <code>ImageOutputStream</code> starting at the * current stream pointer, overwriting existing stream data from that point forward, if present. * * @param iioImage the image data to be written. * @param formatName a <code>String</code> containg the informal name of the format. * @param output an <code>ImageOutputStream</code> to be written to. * * @return <code>false</code> if no appropriate writer is found. * * @throws IllegalArgumentException if any parameter is <code>null</code>. * @throws IOException if an error occurs during writing. */ public static boolean writeImage(IIOImage iioImage, String formatName, ImageOutputStream output) throws IOException { if (iioImage == null) { throw new IllegalArgumentException("iioImage == null!"); } if (formatName == null) { throw new IllegalArgumentException("formatName == null!"); } if (output == null) { throw new IllegalArgumentException("output == null!"); } ImageTypeSpecifier type = ImageTypeSpecifier.createFromRenderedImage(iioImage.getRenderedImage()); ImageWriter writer = getImageWriter(type, formatName); if (writer == null) { return false; } writer.setOutput(output); writer.write(iioImage); output.flush(); writer.dispose(); return true; } /** * Gets an image writer suitable to be used for the given image type and image format. * * @param imageType the type of the image to be written later * @param imageFormatName the image format name, e.g. "TIFF" * * @return a suitable image writer, or <code>null</code> if no writer is found */ public static ImageWriter getImageWriter(ImageTypeSpecifier imageType, String imageFormatName) { return getImageWriter(imageType, imageFormatName, null); } /** * Gets an image writer suitable to be used for the given image type, image format and metadata format. * * @param imageType the type of the image to be written later * @param imageFormatName the image format name, e.g. "TIFF" * @param metadataFormatName the metadata format name, e.g. "com_sun_media_imageio_plugins_tiff_image_1.0", or * <code>null</code> * * @return a suitable image writer, or <code>null</code> if no writer is found */ public static ImageWriter getImageWriter(ImageTypeSpecifier imageType, String imageFormatName, String metadataFormatName) { Iterator writers = ImageIO.getImageWriters(imageType, imageFormatName); while (writers.hasNext()) { final ImageWriter writer = (ImageWriter) writers.next(); if (metadataFormatName == null) { return writer; } final String nativeImageMetadataFormatName = writer.getOriginatingProvider().getNativeImageMetadataFormatName(); if (metadataFormatName.equals(nativeImageMetadataFormatName)) { return writer; } } writers = ImageIO.getImageWriters(imageType, imageFormatName); while (writers.hasNext()) { final ImageWriter writer = (ImageWriter) writers.next(); final String[] extraImageMetadataFormatNames = writer.getOriginatingProvider().getExtraImageMetadataFormatNames(); for (int i = 0; i < extraImageMetadataFormatNames.length; i++) { final String extraImageMetadataFormatName = extraImageMetadataFormatNames[i]; if (metadataFormatName.equals(extraImageMetadataFormatName)) { return writer; } } } return null; } public static String getXML(final IIOMetadata metadata) { final String metadataFormatName = metadata.getNativeMetadataFormatName(); return getXML((org.w3c.dom.Element) metadata.getAsTree(metadataFormatName)); } private static String getXML(final org.w3c.dom.Element metadataElement) { return getXML(convertToJDOM(metadataElement)); } private static String getXML(Element metadataElement) { // following lines uses the old JDOM jar // xmlOutputter.setIndent(true); // xmlOutputter.setIndent(" "); // xmlOutputter.setNewlines(true); // xmlOutputter.setExpandEmptyElements(false); // xmlOutputter.setOmitEncoding(true); // xmlOutputter.setOmitDeclaration(true); // xmlOutputter.setTextNormalize(false); final Format prettyFormat = Format.getPrettyFormat(); prettyFormat.setExpandEmptyElements(false); prettyFormat.setOmitEncoding(true); prettyFormat.setOmitDeclaration(true); prettyFormat.setTextMode(Format.TextMode.PRESERVE); final XMLOutputter xmlOutputter = new XMLOutputter(prettyFormat); final String xml = xmlOutputter.outputString(metadataElement); return xml; } private static Element convertToJDOM(final org.w3c.dom.Element metadataElement) { return new DOMBuilder().build(metadataElement); } private IIOUtils() { } }
gpl-3.0
abocz/darcy-ui
src/test/java/com/redhat/darcy/ui/AbstractViewIsLoadedTest.java
15407
/* Copyright 2014 Red Hat, Inc. and/or its affiliates. This file is part of darcy-ui. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.redhat.darcy.ui; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.redhat.darcy.ui.annotations.Context; import com.redhat.darcy.ui.annotations.NotRequired; import com.redhat.darcy.ui.annotations.Require; import com.redhat.darcy.ui.annotations.RequireAll; import com.redhat.darcy.ui.api.Locator; import com.redhat.darcy.ui.api.View; import com.redhat.darcy.ui.api.elements.Element; import com.redhat.darcy.ui.api.elements.Findable; import com.redhat.darcy.ui.testing.doubles.AlwaysDisplayedLabel; import com.redhat.darcy.ui.testing.doubles.NeverDisplayedElement; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import java.util.ArrayList; import java.util.List; @SuppressWarnings("unused") @RunWith(JUnit4.class) public class AbstractViewIsLoadedTest { @Test(expected = NoRequiredElementsException.class) public void shouldThrowNoRequiredElementsExceptionIfCalledWithoutAnyAnnotatedElements() { View testView = new AbstractView() { Element element = new AlwaysDisplayedLabel(); }; testView.isLoaded(); } @Test public void shouldReturnTrueIfAllRequiredElementsAreDisplayed() { View testView = new AbstractView() { @Require private Element test = new AlwaysDisplayedLabel(); }; assertTrue("isLoaded should return true if all required elements are displayed.", testView.isLoaded()); } @Test public void shouldReturnFalseIfNotAllRequiredElementsAreDisplayed() { View testView = new AbstractView() { @Require private Element displayed = new AlwaysDisplayedLabel(); @Require private Element notDisplayed = new NeverDisplayedElement(); }; assertFalse("isLoaded should return false if not all required elements are displayed.", testView.isLoaded()); } @Test public void shouldReturnTrueIfRequireAllIsUsedAndAllElementsAreDisplayed() { @RequireAll class TestView extends AbstractView { private Element displayed = new AlwaysDisplayedLabel(); private Element displayed2 = new AlwaysDisplayedLabel(); } View testView = new TestView(); assertTrue("isLoaded should return true if all required elements are displayed and " + "RequireAll annotation is used.", testView.isLoaded()); } @Test public void shouldReturnFalseIfRequireAllIsUsedAndNotAllElementsAreDisplayed() { @RequireAll class TestView extends AbstractView { private Element displayed = new AlwaysDisplayedLabel(); private Element notDisplayed = new NeverDisplayedElement(); } View testView = new TestView(); assertFalse("isLoaded should return false if not all required elements are displayed and " + "RequireAll annotation is used.", testView.isLoaded()); } @Test public void shouldReturnTrueIfOnlyElementNotDisplayedIsNotRequired() { @RequireAll class TestView extends AbstractView { private Element displayed = new AlwaysDisplayedLabel(); @NotRequired private Element notDisplayed = new NeverDisplayedElement(); } View testView = new TestView(); assertTrue("isLoaded should return true if only element not displayed is not required when " + "RequireAll annotation is used.", testView.isLoaded()); } @Test public void shouldReturnFalseIfOnlyElementDisplayedIsNotRequired() { @RequireAll class TestView extends AbstractView { @NotRequired private Element displayed = new AlwaysDisplayedLabel(); private Element notDisplayed = new NeverDisplayedElement(); } View testView = new TestView(); assertFalse("isLoaded should return false if only element actually displayed is not required" + " when RequireAll annotation is used.", testView.isLoaded()); } @Test public void shouldReturnTrueIfRequireIsSpecifiedForAListWithASingleElementLoaded() { class TestView extends AbstractView { @Require private List<Element> elements; public TestView() { elements = new ArrayList<Element>(); elements.add(new AlwaysDisplayedLabel()); } } TestView view = new TestView(); assertTrue("isLoaded should return true if no specific requirement limit is specified for" + " for a list that has at least a single element loaded.", view.isLoaded()); } @Test public void shouldReturnFalseIfRequireIsSpecifiedForAListWithNoElementsLoaded() { class TestView extends AbstractView { @Require private List<Element> elements; public TestView() { elements = new ArrayList<Element>(); } } TestView view = new TestView(); assertFalse("isLoaded should return false if a list with no elements loaded is specified" + " required with no requirement limit.", view.isLoaded()); } @Test public void shouldReturnTrueIfExactNumberOfElementsSpecifiedInListAreLoaded() { class TestView extends AbstractView { @Require(exactly = 5) private List<Element> elements; public TestView() { elements = new ArrayList<Element>(); while (elements.size() < 5) { elements.add(new AlwaysDisplayedLabel()); } } } TestView view = new TestView(); assertTrue("Should return true if an exact number of elements in a list are loaded.", view.isLoaded()); } @Test public void shouldReturnFalseIfExactNumberOfElementsSpecifiedInAListAreNotLoaded() { class TestView extends AbstractView { @Require(exactly = 5) private List<Element> elements; public TestView() { elements = new ArrayList<Element>(); while (elements.size() < 4) { elements.add(new AlwaysDisplayedLabel()); } elements.add(new NeverDisplayedElement()); } } TestView view = new TestView(); assertFalse("isLoaded should return false if all required elements are not loaded.", view.isLoaded()); } @Test public void shouldReturnTrueIfAtLeastAsManyElementsNeededAreLoaded() { class TestView extends AbstractView { @Require(atLeast = 5) private List<Element> elements; public TestView() { elements = new ArrayList<Element>(); while (elements.size() < 6) { elements.add(new AlwaysDisplayedLabel()); } while (elements.size() < 10) { elements.add(new NeverDisplayedElement()); } } } TestView view = new TestView(); assertTrue("Should return true if at least 5 elements are loaded in the list.", view.isLoaded()); } @Test public void shouldReturnTrueIfAsManyElementsNeededAreLoaded() { class TestView extends AbstractView { @Require(atLeast = 5) private List<Element> elements; public TestView() { elements = new ArrayList<Element>(); while (elements.size() < 5) { elements.add(new AlwaysDisplayedLabel()); } while (elements.size() < 10) { elements.add(new NeverDisplayedElement()); } } } TestView view = new TestView(); assertTrue("Should return true if at least 5 elements are loaded in the list.", view.isLoaded()); } @Test public void shouldReturnFalseIfLessElementsThanSpecifiedAreLoaded() { class TestView extends AbstractView { @Require(atLeast = 5) private List<Element> elements; public TestView() { elements = new ArrayList<Element>(); while (elements.size() < 4) { elements.add(new AlwaysDisplayedLabel()); } while (elements.size() < 10) { elements.add(new NeverDisplayedElement()); } elements.add(new NeverDisplayedElement()); } } TestView view = new TestView(); assertFalse("isLoaded should return false if atLeast was specified and not enough elements" + " are loaded.", view.isLoaded()); } @Test public void shouldReturnTrueIfAtMostAsManyElementsNeededAreLoaded() { class TestView extends AbstractView { @Require(atMost = 5) private List<Element> elements; public TestView() { elements = new ArrayList<Element>(); while (elements.size() < 4) { elements.add(new AlwaysDisplayedLabel()); } } } TestView view = new TestView(); assertTrue("Should return true if at most 4 elements are loaded in the list.", view.isLoaded()); } @Test public void shouldReturnTrueIfExactlyAsManyElementsNeededSpecifiedWithAtMostAreLoaded() { class TestView extends AbstractView { @Require(atMost = 5) private List<Element> elements; public TestView() { elements = new ArrayList<Element>(); while (elements.size() < 5) { elements.add(new AlwaysDisplayedLabel()); } } } TestView view = new TestView(); assertTrue("Should return true if at most 5 elements are loaded in the list.", view.isLoaded()); } @Test public void shouldReturnFalseIfMoreElementsThanSpecifiedWithAtMostAreLoaded() { class TestView extends AbstractView { @Require(atMost = 5) private List<Element> elements; public TestView() { elements = new ArrayList<Element>(); while (elements.size() < 6) { elements.add(new AlwaysDisplayedLabel()); } } } TestView view = new TestView(); assertFalse("Should return false if 6 elements are loaded in the list.", view.isLoaded()); } @Test public void shouldAllowBeingOverridden() { View testView = new AbstractView() { @Require private Element displayed = new AlwaysDisplayedLabel(); @Override public boolean isLoaded() { return super.isLoaded(); } }; assertTrue(testView.isLoaded()); } @Test(expected = TestException.class) public void shouldPropagateUncheckedExceptions() { Element throwsExceptionOnIsDisplayed = mock(Element.class); when(throwsExceptionOnIsDisplayed.isDisplayed()).thenThrow(TestException.class); View testView = new AbstractView() { @Require Element element = throwsExceptionOnIsDisplayed; }; testView.isLoaded(); } @Test public void shouldReturnTrueIfRequiredFieldIsAViewThatIsLoaded() { View mockView = mock(View.class); when(mockView.isLoaded()).thenReturn(true); View testView = new AbstractView() { @Require View view = mockView; }; assertTrue("isLoaded should check View fields for isLoaded.", testView.isLoaded()); verify(mockView).isLoaded(); } @Test public void shouldReturnFalseIfRequiredFieldIsAViewThatIsNotLoaded() { View mockView = mock(View.class); when(mockView.isLoaded()).thenReturn(false); View testView = new AbstractView() { @Require View view = mockView; }; assertFalse("isLoaded should check View fields for isLoaded.", testView.isLoaded()); verify(mockView).isLoaded(); } @Test public void shouldReturnTrueIfRequiredFieldIsAFindableThatIsPresent() { Findable mockFindable = mock(Findable.class); when(mockFindable.isPresent()).thenReturn(true); View testView = new AbstractView() { @Require Findable findable = mockFindable; }; assertTrue("isLoaded should check Findable fields for isPresent if they do not implement " + "View or Element.", testView.isLoaded()); } @Test public void shouldReturnFalseIfRequiredFieldIsAFindableThatIsNotPresent() { Findable mockFindable = mock(Findable.class); when(mockFindable.isPresent()).thenReturn(false); View testView = new AbstractView() { @Require Findable findable = mockFindable; }; assertFalse("isLoaded should check Findable fields for isPresent if they do not implement" + "View or Element.", testView.isLoaded()); } @Test(expected = NoRequiredElementsException.class) public void shouldIgnoreFieldsAnnotatedWithContext() { @RequireAll class TestView extends AbstractView { @Context Element element = mock(Element.class); }; TestView testView = new TestView(); testView.isLoaded(); } @Test(expected = NoRequiredElementsException.class) public void shouldNotConsiderIrrelevantFieldsAsAbleToBeRequired() { @RequireAll class TestView extends AbstractView { String aString; } TestView testView = new TestView(); testView.isLoaded(); } @Test(expected = NoRequiredElementsException.class) public void shouldReconsiderEmptyConditionsListIfFieldIsAmbiguous() { @RequireAll class TestView extends AbstractView { List<String> stringList; }; TestView testView = new TestView(); testView.isLoaded(); } class TestException extends RuntimeException {} }
gpl-3.0
TheComputerGeek2/MobArena
src/main/java/com/garbagemule/MobArena/things/Thing.java
1328
package com.garbagemule.MobArena.things; import org.bukkit.entity.Player; /** * A thing is something that can be given to a player, taken from a player, * or something that a player can have or be in possession of. Things may have * any number of these three properties, which means that just because a thing * can be given to a player, it doesn't mean that it can also be taken away, * or that the player is in possession of it. * <p> * The interface exposes three methods that are all optional operations. An * operation returns false if it fails or if it isn't applicable to the given * thing (which is the same as failing). */ public interface Thing { /** * Give this thing to the given player. * * @param player a player, non-null * @return true, if this thing was given to the player, false otherwise */ boolean giveTo(Player player); /** * Take this thing from the given player. * * @param player a player, non-null * @return true, if this thing was taken from the player, false otherwise */ boolean takeFrom(Player player); /** * Check if the given player has this thing. * * @param player a player, non-null * @return true, if the player has this thing, false otherwise */ boolean heldBy(Player player); }
gpl-3.0
TGMP/ModularArmour
src/main/java/com/badlogic/gdx/utils/IntMap.java
29406
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.utils; import java.util.Iterator; import java.util.NoSuchElementException; import chbachman.api.util.Array; import com.badlogic.gdx.math.MathUtils; /** * An unordered map that uses int keys. This implementation is a cuckoo hash map * using 3 hashes, random walking, and a small stash for problematic keys. Null * values are allowed. No allocation is done except when growing the table size. * <br> * <br> * This map performs very fast get, containsKey, and remove (typically O(1), * worst case O(log(n))). Put may be a bit slower, depending on hash collisions. * Load factors greater than 0.91 greatly increase the chances the map will have * to rehash to the next higher POT size. * * @author Nathan Sweet */ public class IntMap<V> implements Iterable<IntMap.Entry<V>> { private static final int PRIME1 = 0xbe1f14b1; private static final int PRIME2 = 0xb4b82e39; private static final int PRIME3 = 0xced1c241; private static final int EMPTY = 0; public int size; int[] keyTable; V[] valueTable; int capacity, stashSize; V zeroValue; boolean hasZeroValue; private float loadFactor; private int hashShift, mask, threshold; private int stashCapacity; private int pushIterations; private Entries entries1, entries2; private Values values1, values2; private Keys keys1, keys2; /** * Creates a new map with an initial capacity of 32 and a load factor of * 0.8. This map will hold 25 items before growing the backing table. */ public IntMap() { this(32, 0.8f); } /** * Creates a new map with a load factor of 0.8. This map will hold * initialCapacity * 0.8 items before growing the backing table. */ public IntMap(int initialCapacity) { this(initialCapacity, 0.8f); } /** * Creates a new map with the specified initial capacity and load factor. * This map will hold initialCapacity * loadFactor items before growing the * backing table. */ public IntMap(int initialCapacity, float loadFactor) { if (initialCapacity < 0) throw new IllegalArgumentException("initialCapacity must be >= 0: " + initialCapacity); if (initialCapacity > 1 << 30) throw new IllegalArgumentException("initialCapacity is too large: " + initialCapacity); capacity = MathUtils.nextPowerOfTwo(initialCapacity); if (loadFactor <= 0) throw new IllegalArgumentException("loadFactor must be > 0: " + loadFactor); this.loadFactor = loadFactor; threshold = (int) (capacity * loadFactor); mask = capacity - 1; hashShift = 31 - Integer.numberOfTrailingZeros(capacity); stashCapacity = Math.max(3, (int) Math.ceil(Math.log(capacity)) * 2); pushIterations = Math.max(Math.min(capacity, 8), (int) Math.sqrt(capacity) / 8); keyTable = new int[capacity + stashCapacity]; valueTable = (V[]) new Object[keyTable.length]; } /** Creates a new map identical to the specified map. */ public IntMap(IntMap<? extends V> map) { this(map.capacity, map.loadFactor); stashSize = map.stashSize; System.arraycopy(map.keyTable, 0, keyTable, 0, map.keyTable.length); System.arraycopy(map.valueTable, 0, valueTable, 0, map.valueTable.length); size = map.size; zeroValue = map.zeroValue; hasZeroValue = map.hasZeroValue; } public V put(int key, V value) { if (key == 0) { V oldValue = zeroValue; zeroValue = value; if (!hasZeroValue) { hasZeroValue = true; size++; } return oldValue; } int[] keyTable = this.keyTable; // Check for existing keys. int index1 = key & mask; int key1 = keyTable[index1]; if (key1 == key) { V oldValue = valueTable[index1]; valueTable[index1] = value; return oldValue; } int index2 = hash2(key); int key2 = keyTable[index2]; if (key2 == key) { V oldValue = valueTable[index2]; valueTable[index2] = value; return oldValue; } int index3 = hash3(key); int key3 = keyTable[index3]; if (key3 == key) { V oldValue = valueTable[index3]; valueTable[index3] = value; return oldValue; } // Update key in the stash. for (int i = capacity, n = i + stashSize; i < n; i++) { if (keyTable[i] == key) { V oldValue = valueTable[i]; valueTable[i] = value; return oldValue; } } // Check for empty buckets. if (key1 == EMPTY) { keyTable[index1] = key; valueTable[index1] = value; if (size++ >= threshold) resize(capacity << 1); return null; } if (key2 == EMPTY) { keyTable[index2] = key; valueTable[index2] = value; if (size++ >= threshold) resize(capacity << 1); return null; } if (key3 == EMPTY) { keyTable[index3] = key; valueTable[index3] = value; if (size++ >= threshold) resize(capacity << 1); return null; } push(key, value, index1, key1, index2, key2, index3, key3); return null; } public void putAll(IntMap<V> map) { for (Entry<V> entry : map.entries()) put(entry.key, entry.value); } /** Skips checks for existing keys. */ private void putResize(int key, V value) { if (key == 0) { zeroValue = value; hasZeroValue = true; return; } // Check for empty buckets. int index1 = key & mask; int key1 = keyTable[index1]; if (key1 == EMPTY) { keyTable[index1] = key; valueTable[index1] = value; if (size++ >= threshold) resize(capacity << 1); return; } int index2 = hash2(key); int key2 = keyTable[index2]; if (key2 == EMPTY) { keyTable[index2] = key; valueTable[index2] = value; if (size++ >= threshold) resize(capacity << 1); return; } int index3 = hash3(key); int key3 = keyTable[index3]; if (key3 == EMPTY) { keyTable[index3] = key; valueTable[index3] = value; if (size++ >= threshold) resize(capacity << 1); return; } push(key, value, index1, key1, index2, key2, index3, key3); } private void push(int insertKey, V insertValue, int index1, int key1, int index2, int key2, int index3, int key3) { int[] keyTable = this.keyTable; V[] valueTable = this.valueTable; int mask = this.mask; // Push keys until an empty bucket is found. int evictedKey; V evictedValue; int i = 0, pushIterations = this.pushIterations; do { // Replace the key and value for one of the hashes. switch (MathUtils.random(2)) { case 0: evictedKey = key1; evictedValue = valueTable[index1]; keyTable[index1] = insertKey; valueTable[index1] = insertValue; break; case 1: evictedKey = key2; evictedValue = valueTable[index2]; keyTable[index2] = insertKey; valueTable[index2] = insertValue; break; default: evictedKey = key3; evictedValue = valueTable[index3]; keyTable[index3] = insertKey; valueTable[index3] = insertValue; break; } // If the evicted key hashes to an empty bucket, put it there and // stop. index1 = evictedKey & mask; key1 = keyTable[index1]; if (key1 == EMPTY) { keyTable[index1] = evictedKey; valueTable[index1] = evictedValue; if (size++ >= threshold) resize(capacity << 1); return; } index2 = hash2(evictedKey); key2 = keyTable[index2]; if (key2 == EMPTY) { keyTable[index2] = evictedKey; valueTable[index2] = evictedValue; if (size++ >= threshold) resize(capacity << 1); return; } index3 = hash3(evictedKey); key3 = keyTable[index3]; if (key3 == EMPTY) { keyTable[index3] = evictedKey; valueTable[index3] = evictedValue; if (size++ >= threshold) resize(capacity << 1); return; } if (++i == pushIterations) break; insertKey = evictedKey; insertValue = evictedValue; } while (true); putStash(evictedKey, evictedValue); } private void putStash(int key, V value) { if (stashSize == stashCapacity) { // Too many pushes occurred and the stash is full, increase the // table size. resize(capacity << 1); put(key, value); return; } // Store key in the stash. int index = capacity + stashSize; keyTable[index] = key; valueTable[index] = value; stashSize++; size++; } public V get(int key) { if (key == 0) { if (!hasZeroValue) return null; return zeroValue; } int index = key & mask; if (keyTable[index] != key) { index = hash2(key); if (keyTable[index] != key) { index = hash3(key); if (keyTable[index] != key) return getStash(key, null); } } return valueTable[index]; } public V get(int key, V defaultValue) { if (key == 0) { if (!hasZeroValue) return defaultValue; return zeroValue; } int index = key & mask; if (keyTable[index] != key) { index = hash2(key); if (keyTable[index] != key) { index = hash3(key); if (keyTable[index] != key) return getStash(key, defaultValue); } } return valueTable[index]; } private V getStash(int key, V defaultValue) { int[] keyTable = this.keyTable; for (int i = capacity, n = i + stashSize; i < n; i++) if (keyTable[i] == key) return valueTable[i]; return defaultValue; } public V remove(int key) { if (key == 0) { if (!hasZeroValue) return null; V oldValue = zeroValue; zeroValue = null; hasZeroValue = false; size--; return oldValue; } int index = key & mask; if (keyTable[index] == key) { keyTable[index] = EMPTY; V oldValue = valueTable[index]; valueTable[index] = null; size--; return oldValue; } index = hash2(key); if (keyTable[index] == key) { keyTable[index] = EMPTY; V oldValue = valueTable[index]; valueTable[index] = null; size--; return oldValue; } index = hash3(key); if (keyTable[index] == key) { keyTable[index] = EMPTY; V oldValue = valueTable[index]; valueTable[index] = null; size--; return oldValue; } return removeStash(key); } V removeStash(int key) { int[] keyTable = this.keyTable; for (int i = capacity, n = i + stashSize; i < n; i++) { if (keyTable[i] == key) { V oldValue = valueTable[i]; removeStashIndex(i); size--; return oldValue; } } return null; } void removeStashIndex(int index) { // If the removed location was not last, move the last tuple to the // removed location. stashSize--; int lastIndex = capacity + stashSize; if (index < lastIndex) { keyTable[index] = keyTable[lastIndex]; valueTable[index] = valueTable[lastIndex]; valueTable[lastIndex] = null; } else valueTable[index] = null; } /** * Reduces the size of the backing arrays to be the specified capacity or * less. If the capacity is already less, nothing is done. If the map * contains more items than the specified capacity, the next highest power * of two capacity is used instead. */ public void shrink(int maximumCapacity) { if (maximumCapacity < 0) throw new IllegalArgumentException("maximumCapacity must be >= 0: " + maximumCapacity); if (size > maximumCapacity) maximumCapacity = size; if (capacity <= maximumCapacity) return; maximumCapacity = MathUtils.nextPowerOfTwo(maximumCapacity); resize(maximumCapacity); } /** * Clears the map and reduces the size of the backing arrays to be the * specified capacity if they are larger. */ public void clear(int maximumCapacity) { if (capacity <= maximumCapacity) { clear(); return; } zeroValue = null; hasZeroValue = false; size = 0; resize(maximumCapacity); } public void clear() { if (size == 0) return; int[] keyTable = this.keyTable; V[] valueTable = this.valueTable; for (int i = capacity + stashSize; i-- > 0;) { keyTable[i] = EMPTY; valueTable[i] = null; } size = 0; stashSize = 0; zeroValue = null; hasZeroValue = false; } /** * Returns true if the specified value is in the map. Note this traverses * the entire map and compares every value, which may be an expensive * operation. * * @param identity * If true, uses == to compare the specified value with values in * the map. If false, uses {@link #equals(Object)}. */ public boolean containsValue(Object value, boolean identity) { V[] valueTable = this.valueTable; if (value == null) { if (hasZeroValue && zeroValue == null) return true; int[] keyTable = this.keyTable; for (int i = capacity + stashSize; i-- > 0;) if (keyTable[i] != EMPTY && valueTable[i] == null) return true; } else if (identity) { if (value == zeroValue) return true; for (int i = capacity + stashSize; i-- > 0;) if (valueTable[i] == value) return true; } else { if (hasZeroValue && value.equals(zeroValue)) return true; for (int i = capacity + stashSize; i-- > 0;) if (value.equals(valueTable[i])) return true; } return false; } public boolean containsKey(int key) { if (key == 0) return hasZeroValue; int index = key & mask; if (keyTable[index] != key) { index = hash2(key); if (keyTable[index] != key) { index = hash3(key); if (keyTable[index] != key) return containsKeyStash(key); } } return true; } private boolean containsKeyStash(int key) { int[] keyTable = this.keyTable; for (int i = capacity, n = i + stashSize; i < n; i++) if (keyTable[i] == key) return true; return false; } /** * Returns the key for the specified value, or <tt>notFound</tt> if it is * not in the map. Note this traverses the entire map and compares every * value, which may be an expensive operation. * * @param identity * If true, uses == to compare the specified value with values in * the map. If false, uses {@link #equals(Object)}. */ public int findKey(Object value, boolean identity, int notFound) { V[] valueTable = this.valueTable; if (value == null) { if (hasZeroValue && zeroValue == null) return 0; int[] keyTable = this.keyTable; for (int i = capacity + stashSize; i-- > 0;) if (keyTable[i] != EMPTY && valueTable[i] == null) return keyTable[i]; } else if (identity) { if (value == zeroValue) return 0; for (int i = capacity + stashSize; i-- > 0;) if (valueTable[i] == value) return keyTable[i]; } else { if (hasZeroValue && value.equals(zeroValue)) return 0; for (int i = capacity + stashSize; i-- > 0;) if (value.equals(valueTable[i])) return keyTable[i]; } return notFound; } /** * Increases the size of the backing array to accommodate the specified * number of additional items. Useful before adding many items to avoid * multiple backing array resizes. */ public void ensureCapacity(int additionalCapacity) { int sizeNeeded = size + additionalCapacity; if (sizeNeeded >= threshold) resize(MathUtils.nextPowerOfTwo((int) (sizeNeeded / loadFactor))); } private void resize(int newSize) { int oldEndIndex = capacity + stashSize; capacity = newSize; threshold = (int) (newSize * loadFactor); mask = newSize - 1; hashShift = 31 - Integer.numberOfTrailingZeros(newSize); stashCapacity = Math.max(3, (int) Math.ceil(Math.log(newSize)) * 2); pushIterations = Math.max(Math.min(newSize, 8), (int) Math.sqrt(newSize) / 8); int[] oldKeyTable = keyTable; V[] oldValueTable = valueTable; keyTable = new int[newSize + stashCapacity]; valueTable = (V[]) new Object[newSize + stashCapacity]; int oldSize = size; size = hasZeroValue ? 1 : 0; stashSize = 0; if (oldSize > 0) { for (int i = 0; i < oldEndIndex; i++) { int key = oldKeyTable[i]; if (key != EMPTY) putResize(key, oldValueTable[i]); } } } private int hash2(int h) { h *= PRIME2; return (h ^ h >>> hashShift) & mask; } private int hash3(int h) { h *= PRIME3; return (h ^ h >>> hashShift) & mask; } public String toString() { if (size == 0) return "[]"; StringBuilder buffer = new StringBuilder(32); buffer.append('['); int[] keyTable = this.keyTable; V[] valueTable = this.valueTable; int i = keyTable.length; if (hasZeroValue) { buffer.append("0="); buffer.append(zeroValue); } else { while (i-- > 0) { int key = keyTable[i]; if (key == EMPTY) continue; buffer.append(key); buffer.append('='); buffer.append(valueTable[i]); break; } } while (i-- > 0) { int key = keyTable[i]; if (key == EMPTY) continue; buffer.append(", "); buffer.append(key); buffer.append('='); buffer.append(valueTable[i]); } buffer.append(']'); return buffer.toString(); } public Iterator<Entry<V>> iterator() { return entries(); } /** * Returns an iterator for the entries in the map. Remove is supported. Note * that the same iterator instance is returned each time this method is * called. Use the {@link Entries} constructor for nested or multithreaded * iteration. */ public Entries<V> entries() { if (entries1 == null) { entries1 = new Entries(this); entries2 = new Entries(this); } if (!entries1.valid) { entries1.reset(); entries1.valid = true; entries2.valid = false; return entries1; } entries2.reset(); entries2.valid = true; entries1.valid = false; return entries2; } /** * Returns an iterator for the values in the map. Remove is supported. Note * that the same iterator instance is returned each time this method is * called. Use the {@link Entries} constructor for nested or multithreaded * iteration. */ public Values<V> values() { if (values1 == null) { values1 = new Values(this); values2 = new Values(this); } if (!values1.valid) { values1.reset(); values1.valid = true; values2.valid = false; return values1; } values2.reset(); values2.valid = true; values1.valid = false; return values2; } /** * Returns an iterator for the keys in the map. Remove is supported. Note * that the same iterator instance is returned each time this method is * called. Use the {@link Entries} constructor for nested or multithreaded * iteration. */ public Keys keys() { if (keys1 == null) { keys1 = new Keys(this); keys2 = new Keys(this); } if (!keys1.valid) { keys1.reset(); keys1.valid = true; keys2.valid = false; return keys1; } keys2.reset(); keys2.valid = true; keys1.valid = false; return keys2; } static public class Entry<V> { public int key; public V value; public String toString() { return key + "=" + value; } } static private class MapIterator<V> { static final int INDEX_ILLEGAL = -2; static final int INDEX_ZERO = -1; public boolean hasNext; final IntMap<V> map; int nextIndex, currentIndex; boolean valid = true; public MapIterator(IntMap<V> map) { this.map = map; reset(); } public void reset() { currentIndex = INDEX_ILLEGAL; nextIndex = INDEX_ZERO; if (map.hasZeroValue) hasNext = true; else findNextIndex(); } void findNextIndex() { hasNext = false; int[] keyTable = map.keyTable; for (int n = map.capacity + map.stashSize; ++nextIndex < n;) { if (keyTable[nextIndex] != EMPTY) { hasNext = true; break; } } } public void remove() { if (currentIndex == INDEX_ZERO && map.hasZeroValue) { map.zeroValue = null; map.hasZeroValue = false; } else if (currentIndex < 0) { throw new IllegalStateException("next must be called before remove."); } else if (currentIndex >= map.capacity) { map.removeStashIndex(currentIndex); nextIndex = currentIndex - 1; findNextIndex(); } else { map.keyTable[currentIndex] = EMPTY; map.valueTable[currentIndex] = null; } currentIndex = INDEX_ILLEGAL; map.size--; } } static public class Entries<V> extends MapIterator<V>implements Iterable<Entry<V>>, Iterator<Entry<V>> { private Entry<V> entry = new Entry(); public Entries(IntMap map) { super(map); } /** * Note the same entry instance is returned each time this method is * called. */ public Entry<V> next() { if (!hasNext) throw new NoSuchElementException(); if (!valid) throw new GdxRuntimeException("#iterator() cannot be used nested."); int[] keyTable = map.keyTable; if (nextIndex == INDEX_ZERO) { entry.key = 0; entry.value = map.zeroValue; } else { entry.key = keyTable[nextIndex]; entry.value = map.valueTable[nextIndex]; } currentIndex = nextIndex; findNextIndex(); return entry; } public boolean hasNext() { if (!valid) throw new GdxRuntimeException("#iterator() cannot be used nested."); return hasNext; } public Iterator<Entry<V>> iterator() { return this; } public void remove() { super.remove(); } } static public class Values<V> extends MapIterator<V>implements Iterable<V>, Iterator<V> { public Values(IntMap<V> map) { super(map); } public boolean hasNext() { if (!valid) throw new GdxRuntimeException("#iterator() cannot be used nested."); return hasNext; } public V next() { if (!hasNext) throw new NoSuchElementException(); if (!valid) throw new GdxRuntimeException("#iterator() cannot be used nested."); V value; if (nextIndex == INDEX_ZERO) value = map.zeroValue; else value = map.valueTable[nextIndex]; currentIndex = nextIndex; findNextIndex(); return value; } public Iterator<V> iterator() { return this; } /** Returns a new array containing the remaining values. */ public Array<V> toArray() { Array array = new Array(true, map.size); while (hasNext) array.add(next()); return array; } public void remove() { super.remove(); } } static public class Keys extends MapIterator { public Keys(IntMap map) { super(map); } public int next() { if (!hasNext) throw new NoSuchElementException(); if (!valid) throw new GdxRuntimeException("#iterator() cannot be used nested."); int key = nextIndex == INDEX_ZERO ? 0 : map.keyTable[nextIndex]; currentIndex = nextIndex; findNextIndex(); return key; } /** Returns a new array containing the remaining keys. */ public IntArray toArray() { IntArray array = new IntArray(true, map.size); while (hasNext) array.add(next()); return array; } } }
gpl-3.0
mlohbihler/BACnet4J
src/main/java/com/serotonin/bacnet4j/service/acknowledgement/AtomicWriteFileAck.java
3391
/* * ============================================================================ * GNU General Public License * ============================================================================ * * Copyright (C) 2015 Infinite Automation Software. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * When signing a commercial license with Infinite Automation Software, * the following extension to GPL is made. A special exception to the GPL is * included to allow you to distribute a combined work that includes BAcnet4J * without being obliged to provide the source code for any proprietary components. * * See www.infiniteautomation.com for commercial license options. * * @author Matthew Lohbihler */ package com.serotonin.bacnet4j.service.acknowledgement; import com.serotonin.bacnet4j.exception.BACnetException; import com.serotonin.bacnet4j.type.primitive.SignedInteger; import com.serotonin.bacnet4j.util.sero.ByteQueue; public class AtomicWriteFileAck extends AcknowledgementService { private static final long serialVersionUID = -3122331020521995628L; public static final byte TYPE_ID = 7; private final boolean recordAccess; private final SignedInteger fileStart; public AtomicWriteFileAck(boolean recordAccess, SignedInteger fileStart) { this.recordAccess = recordAccess; this.fileStart = fileStart; } @Override public byte getChoiceId() { return TYPE_ID; } @Override public void write(ByteQueue queue) { write(queue, fileStart, recordAccess ? 1 : 0); } AtomicWriteFileAck(ByteQueue queue) throws BACnetException { recordAccess = peekTagNumber(queue) == 1; fileStart = read(queue, SignedInteger.class, recordAccess ? 1 : 0); } public boolean isRecordAccess() { return recordAccess; } public SignedInteger getFileStart() { return fileStart; } @Override public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + ((fileStart == null) ? 0 : fileStart.hashCode()); result = PRIME * result + (recordAccess ? 1231 : 1237); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final AtomicWriteFileAck other = (AtomicWriteFileAck) obj; if (fileStart == null) { if (other.fileStart != null) return false; } else if (!fileStart.equals(other.fileStart)) return false; if (recordAccess != other.recordAccess) return false; return true; } }
gpl-3.0
intel-analytics/InformationExtraction
src/main/java/com/intel/ie/analytics/ModelWeight.java
929
package com.intel.ie.analytics; import edu.stanford.nlp.ie.KBPSemgrexExtractor; import edu.stanford.nlp.ie.KBPTokensregexExtractor; import java.io.IOException; public class ModelWeight { static Double KBPStatisticalWeightIntel = 0.5289; static Double KBPStatisticalWeightDefault = 0.4474; static Double KBPTokenWeight = 0.6218; static Double KBPSemgrexWeight = 0.3653; static Double getWeight(IntelKBPRelationExtractor extractor) { if (extractor.getClass().equals(IntelKBPStatisticalExtractor.class)) return KBPStatisticalWeightIntel; else if (extractor.getClass().equals(DefaultKBPStatisticalExtractor.class)) return KBPStatisticalWeightDefault; else if (extractor.getClass().equals(IntelKBPSemgrexExtractor.class)) return KBPSemgrexWeight; else if (extractor.getClass().equals(IntelKBPTokensregexExtractor.class)) return KBPTokenWeight; else return 1.0; } }
gpl-3.0
PLRI/arden2bytecode
src/arden/compiler/InMemoryClassLoader.java
2323
// arden2bytecode // Copyright (c) 2010, Daniel Grunwald // 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 owner 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 arden.compiler; /** * ClassLoader used for loading the compiled classes without having to save them * to disk. * * @author Daniel Grunwald */ final class InMemoryClassLoader extends ClassLoader { String className; byte[] data; Class<?> loadedClass; public InMemoryClassLoader(String className, byte[] data) { super(Thread.currentThread().getContextClassLoader()); this.className = className; this.data = data; } protected synchronized Class<?> findClass(String name) throws ClassNotFoundException { if (className.equals(name)) { if (loadedClass == null) { loadedClass = defineClass(name, data, 0, data.length); data = null; } return loadedClass; } else { throw new ClassNotFoundException(); } } }
gpl-3.0
schwabdidier/GazePlay
gazeplay-games/src/main/java/net/gazeplay/games/blocs/BlocsGamesStats.java
275
package net.gazeplay.games.blocs; import javafx.scene.Scene; import net.gazeplay.stats.HiddenItemsGamesStats; public class BlocsGamesStats extends HiddenItemsGamesStats { public BlocsGamesStats(Scene scene) { super(scene); gameName = "blocs"; } }
gpl-3.0
Pante/XMC-Toolkit
commons/src/test/java/com/karuslabs/commons/command/tree/MapperTest.java
3723
/* * The MIT License * * Copyright 2019 Karus Labs. * * 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.karuslabs.commons.command.tree; import com.karuslabs.commons.command.tree.nodes.Argument; import com.karuslabs.commons.command.tree.nodes.Literal; import com.mojang.brigadier.arguments.StringArgumentType; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.tree.*; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class MapperTest { Mapper<String, String> mapper = new Mapper<>(); @Test void mapper_map_argument() { var unmapped = Argument.<String, String>builder("b", StringArgumentType.word()).build(); var argument = (ArgumentCommandNode<String, String>) mapper.map(unmapped); assertEquals("b", argument.getName()); assertSame(unmapped.getType(), argument.getType()); assertSame(Mapper.NONE, argument.getCommand()); assertSame(Mapper.TRUE, argument.getRequirement()); assertNull(argument.getCustomSuggestions()); } @Test void mapper_map_literal() { var literal = mapper.map(Literal.<String>builder("a").build()); assertTrue(literal instanceof LiteralCommandNode<?>); assertEquals("a", literal.getName()); assertSame(Mapper.NONE, literal.getCommand()); assertSame(Mapper.TRUE, literal.getRequirement()); } @Test void mapper_map_root() { assertEquals(RootCommandNode.class, mapper.map(new RootCommandNode<>()).getClass()); } @Test void mapper_map_otherwise() { var command = mock(CommandNode.class); assertEquals( "Unsupported command, '" + command.getName() + "' of type: " + command.getClass().getName(), assertThrows(UnsupportedOperationException.class, () -> mapper.map(command)).getMessage() ); } @Test void type() { var argument = Argument.<String, String>builder("", StringArgumentType.word()).build(); assertEquals(argument.getType(), mapper.type(argument)); } @Test void execution() throws CommandSyntaxException { assertEquals(0, mapper.execution(null).run(null)); } @Test void predicate() { assertTrue(mapper.requirement(null).test(null)); } @Test void suggestions() { assertNull(mapper.suggestions(null)); } }
gpl-3.0
AuthMe/AuthMeReloaded
src/main/java/fr/xephi/authme/security/crypts/Pbkdf2Django.java
1893
package fr.xephi.authme.security.crypts; import com.google.common.primitives.Ints; import de.rtner.security.auth.spi.PBKDF2Engine; import de.rtner.security.auth.spi.PBKDF2Parameters; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.security.crypts.description.AsciiRestricted; import java.util.Base64; @AsciiRestricted public class Pbkdf2Django extends HexSaltedMethod { private static final int DEFAULT_ITERATIONS = 24000; private final ConsoleLogger logger = ConsoleLoggerFactory.get(Pbkdf2Django.class); @Override public String computeHash(String password, String salt, String name) { String result = "pbkdf2_sha256$" + DEFAULT_ITERATIONS + "$" + salt + "$"; PBKDF2Parameters params = new PBKDF2Parameters("HmacSHA256", "ASCII", salt.getBytes(), DEFAULT_ITERATIONS); PBKDF2Engine engine = new PBKDF2Engine(params); return result + Base64.getEncoder().encodeToString(engine.deriveKey(password, 32)); } @Override public boolean comparePassword(String password, HashedPassword hashedPassword, String unusedName) { String[] line = hashedPassword.getHash().split("\\$"); if (line.length != 4) { return false; } Integer iterations = Ints.tryParse(line[1]); if (iterations == null) { logger.warning("Cannot read number of rounds for Pbkdf2Django: '" + line[1] + "'"); return false; } String salt = line[2]; byte[] derivedKey = Base64.getDecoder().decode(line[3]); PBKDF2Parameters params = new PBKDF2Parameters("HmacSHA256", "ASCII", salt.getBytes(), iterations, derivedKey); PBKDF2Engine engine = new PBKDF2Engine(params); return engine.verifyKey(password); } @Override public int getSaltLength() { return 12; } }
gpl-3.0
ggonzales/ksl
src/com/dotmarketing/factories/WebAssetFactory.java
79551
package com.dotmarketing.factories; import static com.dotmarketing.business.PermissionAPI.PERMISSION_WRITE; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import com.dotmarketing.beans.Host; import com.dotmarketing.beans.Identifier; import com.dotmarketing.beans.Inode; import com.dotmarketing.beans.MultiTree; import com.dotmarketing.beans.PermissionAsset; import com.dotmarketing.beans.Tree; import com.dotmarketing.beans.WebAsset; import com.dotmarketing.business.APILocator; import com.dotmarketing.business.CacheLocator; import com.dotmarketing.business.DotIdentifierStateException; import com.dotmarketing.business.DotStateException; import com.dotmarketing.business.NoSuchUserException; import com.dotmarketing.business.PermissionAPI; import com.dotmarketing.business.Permissionable; import com.dotmarketing.business.Role; import com.dotmarketing.business.Versionable; import com.dotmarketing.cache.LiveCache; import com.dotmarketing.cache.WorkingCache; import com.dotmarketing.common.db.DotConnect; import com.dotmarketing.db.HibernateUtil; import com.dotmarketing.exception.DotDataException; import com.dotmarketing.exception.DotHibernateException; import com.dotmarketing.exception.DotSecurityException; import com.dotmarketing.exception.WebAssetException; import com.dotmarketing.menubuilders.RefreshMenus; import com.dotmarketing.portlets.containers.business.ContainerAPI; import com.dotmarketing.portlets.containers.model.Container; import com.dotmarketing.portlets.contentlet.business.ContentletAPI; import com.dotmarketing.portlets.contentlet.business.HostAPI; import com.dotmarketing.portlets.contentlet.model.Contentlet; import com.dotmarketing.portlets.files.business.FileAPI; import com.dotmarketing.portlets.files.model.File; import com.dotmarketing.portlets.folders.business.FolderAPI; import com.dotmarketing.portlets.folders.model.Folder; import com.dotmarketing.portlets.htmlpages.business.HTMLPageAPI; import com.dotmarketing.portlets.htmlpages.model.HTMLPage; import com.dotmarketing.portlets.links.business.MenuLinkAPI; import com.dotmarketing.portlets.links.model.Link; import com.dotmarketing.portlets.structure.factories.StructureFactory; import com.dotmarketing.portlets.structure.model.Structure; import com.dotmarketing.portlets.templates.business.TemplateAPI; import com.dotmarketing.portlets.templates.model.Template; import com.dotmarketing.services.ContainerServices; import com.dotmarketing.services.PageServices; import com.dotmarketing.services.TemplateServices; import com.dotmarketing.util.InodeUtils; import com.dotmarketing.util.Logger; import com.dotmarketing.util.PaginatedArrayList; import com.dotmarketing.util.UtilMethods; import com.dotmarketing.util.WebKeys; import com.liferay.portal.model.User; import com.liferay.portal.struts.ActionException; import edu.emory.mathcs.backport.java.util.Collections; /** * * @author maria, david(2005) */ public class WebAssetFactory { public enum Direction { PREVIOUS, NEXT }; public enum AssetType { HTMLPAGE("HTMLPAGE"), FILE_ASSET("FILE_ASSET"), CONTAINER("CONTAINER"), TEMPLATE("TEMPLATE"), LINK("LINK") ; private String value; AssetType (String value) { this.value = value; } public String toString () { return value; } public static AssetType getObject (String value) { AssetType[] ojs = AssetType.values(); for (AssetType oj : ojs) { if (oj.value.equals(value)) return oj; } return null; } } private static PermissionAPI permissionAPI = APILocator.getPermissionAPI(); private static HTMLPageAPI htmlPageAPI = APILocator.getHTMLPageAPI(); private static FileAPI fileAPI = APILocator.getFileAPI(); private static ContainerAPI containerAPI = APILocator.getContainerAPI(); private static TemplateAPI templateAPI = APILocator.getTemplateAPI(); private static MenuLinkAPI linksAPI = APILocator.getMenuLinkAPI(); private static final int ITERATION_LIMIT = 500; private final static int MAX_LIMIT_COUNT = 100; /** * @param permissionAPI the permissionAPI to set */ public static void setPermissionAPI(PermissionAPI permissionAPIRef) { permissionAPI = permissionAPIRef; } public static void createAsset(WebAsset webasset, String userId, Inode parent) throws DotDataException, DotStateException, DotSecurityException { webasset.setModDate(new java.util.Date()); webasset.setModUser(userId); // persists the webasset HibernateUtil.saveOrUpdate(webasset); // adds the webasset as child of the folder or parent inode if(!parent.getType().equalsIgnoreCase("folder")) parent.addChild(webasset); // create new identifier, with the URI Identifier id = APILocator.getIdentifierAPI().createNew(webasset, (Folder) parent); id.setOwner(userId); // set the identifier on the inode for future reference. // and for when we get rid of identifiers all together //HibernateUtil.saveOrUpdate(id); APILocator.getIdentifierAPI().save(id); webasset.setIdentifier(id.getId()); APILocator.getVersionableAPI().setWorking(webasset); } public static void createAsset(WebAsset webasset, String userId, Host host) throws DotDataException, DotStateException, DotSecurityException { webasset.setModDate(new java.util.Date()); webasset.setModUser(userId); // persists the webasset HibernateUtil.saveOrUpdate(webasset); // create new identifier, without URI Identifier id = APILocator.getIdentifierAPI().createNew(webasset, host); id.setOwner(userId); APILocator.getIdentifierAPI().save(id); webasset.setIdentifier(id.getId()); HibernateUtil.saveOrUpdate(webasset); APILocator.getVersionableAPI().setWorking(webasset); } public static void createAsset(WebAsset webasset, String userId, Inode parent, Identifier identifier) throws DotDataException, DotStateException, DotSecurityException { webasset.setModDate(new java.util.Date()); webasset.setModUser(userId); // set the identifier on the inode for future reference. // and for when we get rid of identifiers all together webasset.setIdentifier(identifier.getInode()); // persists the webasset HibernateUtil.saveOrUpdate(webasset); APILocator.getVersionableAPI().setWorking(webasset); // adds the webasset as child of the folder or parent inode if(!parent.getType().equalsIgnoreCase("folder")) parent.addChild(webasset); // adds asset to the existing identifier //identifier.addChild(webasset); } public static void createAsset(WebAsset webasset, String userId, Identifier identifier) throws DotDataException, DotStateException, DotSecurityException { webasset.setModDate(new java.util.Date()); webasset.setModUser(userId); // set the identifier on the inode for future reference. // and for when we get rid of identifiers all together webasset.setIdentifier(identifier.getInode()); // persists the webasset HibernateUtil.saveOrUpdate(webasset); APILocator.getVersionableAPI().setWorking(webasset); // adds asset to the existing identifier //identifier.addChild(webasset); } public static void createAsset(WebAsset webasset, String userId, Inode parent, Identifier identifier, boolean working) throws DotDataException, DotStateException, DotSecurityException { webasset.setModDate(new java.util.Date()); webasset.setModUser(userId); // persists the webasset HibernateUtil.saveOrUpdate(webasset); // adds the webasset as child of the folder or parent inode if(!parent.getType().equalsIgnoreCase("folder")) parent.addChild(webasset); // adds asset to the existing identifier //identifier.addChild(webasset); //webasset.addParent(identifier); webasset.setIdentifier(identifier.getInode()); HibernateUtil.saveOrUpdate(webasset); if(working) APILocator.getVersionableAPI().setWorking(webasset); } public static void createAsset(WebAsset webasset, String userId, Inode parent, Identifier identifier, boolean working, boolean isLive) throws DotDataException, DotStateException, DotSecurityException { webasset.setModDate(new java.util.Date()); webasset.setModUser(userId); // persists the webasset HibernateUtil.saveOrUpdate(webasset); // adds the webasset as child of the folder or parent inode if(!parent.getType().equalsIgnoreCase("folder")) parent.addChild(webasset); // adds asset to the existing identifier //identifier.addChild(webasset); //webasset.addParent(identifier); webasset.setIdentifier(identifier.getInode()); HibernateUtil.saveOrUpdate(webasset); if(working) APILocator.getVersionableAPI().setWorking(webasset); if(isLive) APILocator.getVersionableAPI().setLive(webasset); } public static void createAsset(WebAsset webasset, String userId, Identifier identifier, boolean working) throws DotDataException, DotStateException, DotSecurityException { webasset.setModDate(new java.util.Date()); webasset.setModUser(userId); // persists the webasset //HibernateUtil.saveOrUpdate(webasset); // adds asset to the existing identifier //identifier.addChild(webasset); //webasset.addParent(identifier); webasset.setIdentifier(identifier.getInode()); HibernateUtil.saveOrUpdate(webasset); if(working) APILocator.getVersionableAPI().setWorking(webasset); } public static void createAsset(WebAsset webasset, String userId, Inode parent, boolean isLive) throws DotDataException, DotStateException, DotSecurityException { webasset.setModDate(new java.util.Date()); webasset.setModUser(userId); // persists the webasset HibernateUtil.saveOrUpdate(webasset); // adds the webasset as child of the folder or parent inode if(!parent.getType().equalsIgnoreCase("folder")) parent.addChild(webasset); // create new identifier, with the URI Identifier id = APILocator.getIdentifierAPI().createNew(webasset, (Folder) parent); id.setOwner(userId); // set the identifier on the inode for future reference. // and for when we get rid of identifiers all together APILocator.getIdentifierAPI().save(id); webasset.setIdentifier(id.getId()); APILocator.getVersionableAPI().setWorking(webasset); if(isLive) APILocator.getVersionableAPI().setLive(webasset); } public static WebAsset getParentWebAsset(Inode i) { HibernateUtil dh = new HibernateUtil(WebAsset.class); WebAsset webAsset = null ; try { dh.setQuery("from inode in class " + WebAsset.class.getName() + " where ? in inode.children.elements"); dh.setParam(i.getInode()); webAsset = (WebAsset) dh.load(); } catch (DotHibernateException e) { Logger.error(WebAssetFactory.class,"getParentWebAsset failed:" + e,e); } return webAsset; } public static void renameAsset(WebAsset webasset) throws DotStateException, DotDataException, DotSecurityException { List versions = getAssetVersionsandLive(webasset); Iterator versIter = versions.iterator(); while (versIter.hasNext()) { WebAsset currWebAsset = (WebAsset) versIter.next(); currWebAsset.setFriendlyName(webasset.getFriendlyName()); } } public static boolean editAsset(WebAsset currWebAsset, String userId) throws DotStateException, DotDataException, DotSecurityException { if (!currWebAsset.isLocked()) { // sets lock true User proxyuser=new User(userId); APILocator.getVersionableAPI().setLocked(currWebAsset, true, proxyuser); return true; } // if it is locked then we compare lockedBy with userId from the user that wants to edit the asset String currUserId=APILocator.getVersionableAPI().getLockedBy(currWebAsset); return currUserId.equals(userId); } public static WebAsset getBackAssetVersion(WebAsset versionWebAsset) throws Exception { Identifier id = (Identifier) APILocator.getIdentifierAPI().find(versionWebAsset); if (!InodeUtils.isSet(id.getInode())) { throw new Exception("Web asset Identifier not found!"); } WebAsset working = (WebAsset) APILocator.getVersionableAPI().findWorkingVersion(id, APILocator.getUserAPI().getSystemUser(), false); if (!InodeUtils.isSet(working.getInode())) { throw new Exception("Working copy not found!"); } APILocator.getVersionableAPI().setWorking(versionWebAsset); return versionWebAsset; } /** * This method is odd. You send it an asset, but that may not be the one * that get published. The method will get the identifer of the asset you * send it and find the working version of the asset and make that the live * version. * * @param currWebAsset * This asset's identifier will be used to find the "working" * asset. * @return This method returns the OLD live asset or null. Wierd. * @throws DotSecurityException * @throws DotDataException */ @SuppressWarnings("unchecked") public static WebAsset publishAsset(WebAsset currWebAsset) throws DotStateException, DotDataException, DotSecurityException { Logger.debug(WebAssetFactory.class, "Publishing asset!!!!"); // gets the identifier for this asset Identifier identifier = APILocator.getIdentifierAPI().find(currWebAsset); // gets the current working asset WebAsset workingwebasset = null; // gets the current working asset workingwebasset = (WebAsset) APILocator.getVersionableAPI().findWorkingVersion(identifier, APILocator.getUserAPI().getSystemUser(), false); if (!InodeUtils.isSet(workingwebasset.getInode())) { workingwebasset = currWebAsset; } Logger.debug(WebAssetFactory.class, "workingwebasset=" + workingwebasset.getInode()); WebAsset livewebasset = null; // gets the current working asset livewebasset = (WebAsset) APILocator.getVersionableAPI().findLiveVersion(identifier, APILocator.getUserAPI().getSystemUser(), false); if(workingwebasset.isDeleted()){ throw new DotStateException("You may not publish deleted assets!!!"); } /*if ((livewebasset != null) && (InodeUtils.isSet(livewebasset.getInode())) && (livewebasset.getInode() != workingwebasset.getInode())) { Logger.debug(WebAssetFactory.class, "livewebasset.getInode()=" + livewebasset.getInode()); // sets previous live to false livewebasset.setLive(false); livewebasset.setModDate(new java.util.Date()); // persists it HibernateUtil.saveOrUpdate(livewebasset); }*/ // sets new working to live APILocator.getVersionableAPI().setLive(workingwebasset); workingwebasset.setModDate(new java.util.Date()); // persists the webasset HibernateUtil.saveOrUpdate(workingwebasset); Logger.debug(WebAssetFactory.class, "HibernateUtil.saveOrUpdate(workingwebasset)"); return livewebasset; } /** * This method is odd. You send it an asset, but that may not be the one * that get published. The method will get the identifer of the asset you * send it and find the working version of the asset and make that the live * version. * * @param currWebAsset * This asset's identifier will be used to find the "working" * asset. * @param user * @return This method returns the OLD live asset or null. Wierd. * @throws DotSecurityException * @throws DotDataException * @throws DotStateException */ @SuppressWarnings("unchecked") public static WebAsset publishAsset(WebAsset currWebAsset, User user) throws WebAssetException, DotStateException, DotDataException, DotSecurityException { return publishAsset(currWebAsset,user,true); } /** * This method is odd. You send it an asset, but that may not be the one * that get published. The method will get the identifer of the asset you * send it and find the working version of the asset and make that the live * version. * * @param currWebAsset * This asset's identifier will be used to find the "working" * asset. * @param user * @param isNewVersion - if passed false then the webasset's mod user and mod date will NOT be altered. @see {@link ContentletAPI#checkinWithoutVersioning(Contentlet, java.util.Map, List, List, User, boolean)}checkinWithoutVersioning. * @return This method returns the OLD live asset or null. Wierd. * @throws DotDataException * @throws DotStateException * @throws DotSecurityException */ @SuppressWarnings("unchecked") public static WebAsset publishAsset(WebAsset currWebAsset, User user, boolean isNewVersion) throws WebAssetException, DotStateException, DotDataException, DotSecurityException { Logger.debug(WebAssetFactory.class, "Publishing asset!!!!"); // gets the identifier for this asset Identifier identifier = APILocator.getIdentifierAPI().find(currWebAsset); // gets the current working asset WebAsset workingwebasset = null; // gets the current working asset workingwebasset = (WebAsset) APILocator.getVersionableAPI().findWorkingVersion(identifier, APILocator.getUserAPI().getSystemUser(), false); if (!InodeUtils.isSet(workingwebasset.getInode())) { workingwebasset = currWebAsset; } Logger.debug(WebAssetFactory.class, "workingwebasset=" + workingwebasset.getInode()); WebAsset livewebasset = null; try { // gets the current working asset livewebasset = (WebAsset) APILocator.getVersionableAPI().findLiveVersion(identifier, APILocator.getUserAPI().getSystemUser(), false); } catch (Exception e) { } if(workingwebasset.isDeleted()){ throw new WebAssetException("You may not publish deleted assets!!!"); } boolean localTransaction = false; try { localTransaction = HibernateUtil.startLocalTransactionIfNeeded(); // sets new working to live APILocator.getVersionableAPI().setLive(workingwebasset); if(isNewVersion){ workingwebasset.setModDate(new java.util.Date()); workingwebasset.setModUser(user.getUserId()); } // persists the webasset HibernateUtil.saveOrUpdate(workingwebasset); }catch(Exception e){ Logger.error(WebAssetFactory.class, e.getMessage(), e); if(localTransaction){ HibernateUtil.rollbackTransaction(); } } finally{ if(localTransaction){ HibernateUtil.commitTransaction(); } } Logger.debug(WebAssetFactory.class, "HibernateUtil.saveOrUpdate(workingwebasset)"); return livewebasset; } public static WebAsset getLiveAsset(WebAsset currWebAsset) throws Exception { Logger.debug(WebAssetFactory.class, "Publishing asset!!!!"); // gets the identifier for this asset Identifier identifier = APILocator.getIdentifierAPI().find(currWebAsset); WebAsset livewebasset = null; // gets the current working asset livewebasset = (WebAsset) APILocator.getVersionableAPI().findLiveVersion(identifier, APILocator.getUserAPI().getSystemUser(), false); return livewebasset; } public static boolean archiveAsset(WebAsset currWebAsset) throws DotDataException, DotStateException, DotSecurityException { return archiveAsset(currWebAsset, (String)null); } public static boolean archiveAsset(WebAsset currWebAsset, User user) throws DotDataException, DotStateException, DotSecurityException { return archiveAsset(currWebAsset, user.getUserId()); } public static boolean archiveAsset(WebAsset currWebAsset, String userId) throws DotDataException, DotStateException, DotSecurityException { // gets the identifier for this asset Identifier identifier = APILocator.getIdentifierAPI().find(currWebAsset); WebAsset workingwebasset = null; // gets the current working asset workingwebasset = (WebAsset) APILocator.getVersionableAPI().findWorkingVersion(identifier, APILocator.getUserAPI().getSystemUser(), false); WebAsset live = (WebAsset) APILocator.getVersionableAPI().findLiveVersion(identifier, APILocator.getUserAPI().getSystemUser(), false); //Delete the HTML Page from the Structure Detail if(currWebAsset instanceof HTMLPage) { List<Structure> structures = (List<Structure>) StructureFactory.getStructures(); for(Structure structure : structures) { if(structure.getDetailPage() == identifier.getInode()) { structure.setDetailPage(""); StructureFactory.saveStructure(structure); } } } else if (currWebAsset instanceof File) { RefreshMenus.deleteMenu(currWebAsset); Identifier ident=APILocator.getIdentifierAPI().find(currWebAsset); CacheLocator.getNavToolCache().removeNavByPath(ident.getHostId(), ident.getParentPath()); } User userMod = null; try{ userMod = APILocator.getUserAPI().loadUserById(workingwebasset.getModUser(),APILocator.getUserAPI().getSystemUser(),false); }catch(Exception ex){ if(ex instanceof NoSuchUserException){ try { userMod = APILocator.getUserAPI().getSystemUser(); } catch (DotDataException e) { Logger.error(WebAssetFactory.class,e.getMessage(),e); } } } if(userMod!=null){ workingwebasset.setModUser(userMod.getUserId()); } if (userId == null || !workingwebasset.isLocked() || workingwebasset.getModUser().equals(userId)) { if (live!=null && InodeUtils.isSet(live.getInode())) { APILocator.getVersionableAPI().removeLive(live.getIdentifier()); } //Reset the mod date workingwebasset.setModDate(new Date ()); // sets deleted to true APILocator.getVersionableAPI().setDeleted(workingwebasset, true); // persists the webasset HibernateUtil.saveOrUpdate(workingwebasset); return true; } return false; } public static boolean deleteAssetVersion(WebAsset currWebAsset) throws DotStateException, DotDataException, DotSecurityException { if (!currWebAsset.isLive() && !currWebAsset.isWorking()) { // it's a version so delete from database InodeFactory.deleteInode(currWebAsset); return true; } return false; } public static void unLockAsset(WebAsset currWebAsset) throws DotDataException, DotStateException, DotSecurityException { // unlocks current asset APILocator.getVersionableAPI().setLocked(currWebAsset, false, null); } public static void unArchiveAsset(WebAsset currWebAsset) throws DotDataException, DotStateException, DotSecurityException { RefreshMenus.deleteMenu(currWebAsset); Identifier ident=APILocator.getIdentifierAPI().find(currWebAsset); CacheLocator.getNavToolCache().removeNavByPath(ident.getHostId(), ident.getParentPath()); // gets the identifier for this asset APILocator.getVersionableAPI().setDeleted(currWebAsset, false); } public static boolean unPublishAsset(WebAsset currWebAsset, String userId, Inode parent) throws DotStateException, DotDataException, DotSecurityException { ContentletAPI conAPI = APILocator.getContentletAPI(); HostAPI hostAPI = APILocator.getHostAPI(); // gets the identifier for this asset Identifier identifier = APILocator.getIdentifierAPI().find(currWebAsset); WebAsset workingwebasset = null; // gets the current working asset workingwebasset = (WebAsset) APILocator.getVersionableAPI().findWorkingVersion(identifier, APILocator.getUserAPI().getSystemUser(), false); WebAsset livewebasset = null; User modUser = null; try{ modUser = APILocator.getUserAPI().loadUserById(workingwebasset.getModUser(),APILocator.getUserAPI().getSystemUser(),false); }catch(Exception ex){ if(ex instanceof NoSuchUserException){ try { modUser = APILocator.getUserAPI().getSystemUser(); } catch (DotDataException e) { Logger.error(WebAssetFactory.class,e.getMessage(),e); } } } if(modUser!=null){ workingwebasset.setModUser(modUser.getUserId()); } if (!workingwebasset.isLocked() || workingwebasset.getModUser().equals(userId)) { try { // gets the current working asset livewebasset = (WebAsset) APILocator.getVersionableAPI().findLiveVersion(identifier, APILocator.getUserAPI().getSystemUser(), false); APILocator.getVersionableAPI().removeLive(identifier.getId()); livewebasset.setModDate(new java.util.Date()); livewebasset.setModUser(userId); HibernateUtil.saveOrUpdate(livewebasset); if ((livewebasset.getInode() != workingwebasset.getInode())) { APILocator.getVersionableAPI().setLocked(workingwebasset, false, null); // removes from folder or parent inode if(parent != null) parent.deleteChild(workingwebasset); } if (currWebAsset instanceof HTMLPage) { //remove page from the live directory PageServices.unpublishPageFile((HTMLPage)currWebAsset); //Refreshing the menues //RefreshMenus.deleteMenus(); RefreshMenus.deleteMenu(currWebAsset); CacheLocator.getNavToolCache().removeNavByPath(identifier.getHostId(), identifier.getParentPath()); } else if (currWebAsset instanceof Container) { //remove container from the live directory ContainerServices.unpublishContainerFile((Container)currWebAsset); } else if (currWebAsset instanceof Template) { //remove template from the live directory TemplateServices.unpublishTemplateFile((Template)currWebAsset); } else if( currWebAsset instanceof Link ) { // Removes static menues to provoke all possible dependencies be generated. if( parent instanceof Folder ) { Folder parentFolder = (Folder)parent; Host host = hostAPI.findParentHost(parentFolder, APILocator.getUserAPI().getSystemUser(), false); RefreshMenus.deleteMenu(host); CacheLocator.getNavToolCache().removeNav(host.getIdentifier(), FolderAPI.SYSTEM_FOLDER); } } else if (currWebAsset instanceof File) { RefreshMenus.deleteMenu(currWebAsset); CacheLocator.getNavToolCache().removeNavByPath(identifier.getHostId(), identifier.getParentPath()); } LiveCache.removeAssetFromCache(currWebAsset); return true; } catch (Exception e) { return false; } } return false; } // TO-DO // Do this one with a language condition... public static java.util.List getAssetVersions(WebAsset currWebAsset) throws DotStateException, DotDataException, DotSecurityException { // gets the identifier for this asset if (currWebAsset.isWorking()) { Identifier identifier = APILocator.getIdentifierAPI().find(currWebAsset); return APILocator.getVersionableAPI().findAllVersions(identifier, APILocator.getUserAPI().getSystemUser(), false); } return new java.util.ArrayList(); } /* * public static java.util.List getWorkingAssetsOfClass(Class c) { return * IdentifierFactory.getLiveOfClass(c); } */ // TO-DO // Do this one with a language condition. public static java.util.List getAssetVersionsandLive(WebAsset currWebAsset) throws DotStateException, DotDataException, DotSecurityException { // gets the identifier for this asset if (currWebAsset.isWorking()) { Identifier identifier = APILocator.getIdentifierAPI().find(currWebAsset); return APILocator.getVersionableAPI().findAllVersions(identifier, APILocator.getUserAPI().getSystemUser(), false); } return new java.util.ArrayList(); } // Do this one with a language condition. public static java.util.List getAssetVersionsandLiveandWorking(WebAsset currWebAsset) throws DotStateException, DotDataException, DotSecurityException { // gets the identifier for this asset if (currWebAsset.isWorking()) { Identifier identifier = APILocator.getIdentifierAPI().find(currWebAsset); return APILocator.getVersionableAPI().findAllVersions(identifier, APILocator.getUserAPI().getSystemUser(), false); } return new java.util.ArrayList(); } // Swap assets properties and tree relationships to convert the newAsset // into the workingAsset // This method don�t swap the multitree relationships and correctly set the // working/live and parent folder // relationships and properties /* @SuppressWarnings("deprecation") private static WebAsset swapAssets(WebAsset workingAsset, WebAsset newAsset) throws Exception { Folder parentFolder = null; if (!isAbstractAsset(workingAsset)){ parentFolder = (Folder) APILocator.getFolderAPI().findParentFolder(workingAsset,APILocator.getUserAPI().getSystemUser(),false); } Identifier identifier = (Identifier) APILocator.getIdentifierAPI().find(workingAsset); // Retrieving assets properties excluding (inode, children, parents and // parent) Map workingAssetProps = PropertyUtils.describe(workingAsset); workingAssetProps.remove("class"); workingAssetProps.remove("inode"); workingAssetProps.remove("children"); workingAssetProps.remove("parents"); workingAssetProps.remove("parent"); Map newAssetProps = PropertyUtils.describe(newAsset); newAssetProps.remove("class"); newAssetProps.remove("inode"); newAssetProps.remove("children"); newAssetProps.remove("parents"); newAssetProps.remove("parent"); boolean newAssetLive = newAsset.isLive(); // Swaping props Iterator keys = workingAssetProps.keySet().iterator(); while (keys.hasNext()) { try { String key = (String) keys.next(); Object x = workingAssetProps.get(key); if(x != null && !key.equalsIgnoreCase("working")&& !key.equalsIgnoreCase("live")){ PropertyUtils.setProperty(newAsset, key, x); } } catch (NoSuchMethodException e) { } catch (InvocationTargetException e) { } } keys = newAssetProps.keySet().iterator(); while (keys.hasNext()) { try { String key = (String) keys.next(); Object x = newAssetProps.get(key); if(x!=null && !key.equalsIgnoreCase("working")&& !key.equalsIgnoreCase("live")){ PropertyUtils.setProperty(workingAsset, key, x); } } catch (NoSuchMethodException e) { } catch (InvocationTargetException e) { } } // Setting working/live/locked/date/user properties APILocator.getVersionableAPI().setWorking(workingAsset); if(newAssetLive) APILocator.getVersionableAPI().setWorking(workingAsset); workingAsset.setModDate(new java.util.Date()); APILocator.getVersionableAPI().setLocked(newAsset.getIdentifier(), false, null); if (!isAbstractAsset(workingAsset)) { // Removing the folder for the new version parentFolder.deleteChild(newAsset); } // Saving changes HibernateUtil.saveOrUpdate(workingAsset); HibernateUtil.saveOrUpdate(newAsset); // Swaping tree relationships //TreeFactory.swapTrees(workingAsset, newAsset); if (!isAbstractAsset(workingAsset)) { // Setting folders and identifiers //parentFolder.addChild(workingAsset); //parentFolder.deleteChild(newAsset); } //identifier.addChild(workingAsset); //identifier.addChild(newAsset); if (!isAbstractAsset(workingAsset)) { if (newAsset.isLive()) { //parentFolder.addChild(newAsset); } } HibernateUtil.flush(); HibernateUtil.getSession().refresh(workingAsset); HibernateUtil.getSession().refresh(newAsset); return workingAsset; } */ /** * This method save the new asset as the new working version and change the * current working as an old version. * * @param newWebAsset * New webasset version to be converted as the working asset. * @return The current working webasset (The new version), after the method * execution is must use this class as the working asset instead the * class you give as parameter. * @throws Exception * The method throw an exception when the new asset identifier * or the working folder cannot be found. */ public static WebAsset saveAsset(WebAsset newWebAsset, Identifier id) throws Exception { if (!InodeUtils.isSet(id.getInode())) { throw new Exception("Web asset Identifier not found!"); } WebAsset currWebAsset = null; // gets the current working asset currWebAsset = (WebAsset) APILocator.getVersionableAPI().findWorkingVersion(id, APILocator.getUserAPI().getSystemUser(), false); //http://jira.dotmarketing.net/browse/DOTCMS-5927 if (!InodeUtils.isSet(currWebAsset.getInode())) { currWebAsset = (WebAsset) APILocator.getVersionableAPI().findLiveVersion(id, APILocator.getUserAPI().getSystemUser(), false); if(InodeUtils.isSet(currWebAsset.getInode()) && !currWebAsset.isWorking() && currWebAsset.isLive()){ APILocator.getVersionableAPI().setWorking(newWebAsset); }else if(!InodeUtils.isSet(currWebAsset.getInode()) || !currWebAsset.isLive()){ throw new Exception("Working copy not found!"); } } APILocator.getVersionableAPI().setWorking(newWebAsset); return newWebAsset; } public static List getAssetsPerConditionWithPermission(Host host, String condition, Class c, int limit, int offset, String orderby, String parent, User user) { return getAssetsPerConditionWithPermission(host.getIdentifier(), condition, c, limit, offset, orderby, parent, user); } @SuppressWarnings("unchecked") public static List<WebAsset> getAssetsPerConditionWithPermission(String hostId, String condition, Class c, int limit, int offset, String orderby, String parent, User user) { HibernateUtil dh = new HibernateUtil(c); StringBuffer sb = new StringBuffer(); try { String tableName = ((Inode) c.newInstance()).getType(); sb.append("select {" + tableName + ".*} from " + tableName + ", inode " + tableName + "_1_ where " + tableName + ".inode = " + tableName + "_1_.inode and " + tableName + ".inode in ("); sb.append("select distinct " + tableName + "_condition.inode "); sb.append(" from " + tableName + " " + tableName + "_condition"); if (InodeUtils.isSet(parent)) { sb.append(", tree tree2"); } sb.append(" where " + condition); if (InodeUtils.isSet(parent)) { sb.append(" and " + tableName + "_condition.inode = tree2.child"); sb.append(" and tree2.parent = '" + parent + "'"); } if(c.equals(Container.class) || c.equals(Template.class)) { sb.append(") and " + tableName + ".inode in (select inode.inode from inode,identifier where host_inode = '" + hostId + "' and "+tableName + ".identifier = identifier.id)"); } else if(c.equals(HTMLPage.class)) { sb.append(") and " + tableName + ".inode in (select inode from identifier," + tableName + "where host_inode = '" + hostId + "' and " + tableName + ".identifier = identifier.id)"); } else { sb.append(") and " + tableName + ".inode in (select inode from identifier," + tableName + "where host_inode = '" + hostId + "' and " + tableName + ".identifier = identifier.id)"); } if(orderby != null) sb.append(" order by " + orderby); Logger.debug(WebAssetFactory.class, sb.toString()); List<WebAsset> toReturn = new ArrayList<WebAsset>(); int internalLimit = ITERATION_LIMIT; int internalOffset = 0; boolean done = false; while(!done) { Logger.debug(WebAssetFactory.class, sb.toString()); dh.setSQLQuery(sb.toString()); dh.setFirstResult(internalOffset); dh.setMaxResults(internalLimit); PermissionAPI permAPI = APILocator.getPermissionAPI(); List<WebAsset> list = dh.list(); toReturn.addAll(permAPI.filterCollection(list, PermissionAPI.PERMISSION_READ, false, user)); if(limit > 0 && toReturn.size() >= limit + offset) done = true; else if(list.size() < internalLimit) done = true; internalOffset += internalLimit; } if(offset > toReturn.size()) { toReturn = new ArrayList<WebAsset>(); } else if(limit > 0) { int toIndex = offset + limit > toReturn.size()?toReturn.size():offset + limit; toReturn = toReturn.subList(offset, toIndex); } else if (offset > 0) { toReturn = toReturn.subList(offset, toReturn.size()); } return toReturn; } catch (Exception e) { Logger.warn(WebAssetFactory.class, "getAssetsPerConditionWithPermission failed:" + e, e); } return new ArrayList<WebAsset>(); } @SuppressWarnings("unchecked") public static List<WebAsset> getAssetsWorkingWithPermission(Class c, int limit, int offset, String orderby, String parent, User user) { HibernateUtil dh = new HibernateUtil(c); StringBuilder sb = new StringBuilder(); try { if(offset < 0) offset = 0; String tableName = ((Inode) c.newInstance()).getType(); String versionTable=UtilMethods.getVersionInfoTableName(tableName); sb.append("select {").append(tableName).append(".*} from ").append(tableName).append(", inode ") .append(tableName).append("_1_,identifier identifier, ").append(versionTable).append(" vi ") .append(" where ") .append(tableName).append(".inode = ").append(tableName).append("_1_.inode and ") .append(tableName).append(".identifier = identifier.id ") .append(" and vi.identifier=").append(tableName).append(".identifier ") .append(" and vi.working_inode=").append(tableName).append(".inode "); if (parent != null) { sb.append(" and identifier.host_inode = '" + parent + "'"); } if(orderby != null) sb.append(" order by " + orderby); List<WebAsset> toReturn = new ArrayList<WebAsset>(); int internalLimit = 500; int internalOffset = 0; boolean done = false; while(!done) { Logger.debug(WebAssetFactory.class, sb.toString()); dh.setSQLQuery(sb.toString()); dh.setFirstResult(internalOffset); dh.setMaxResults(internalLimit); PermissionAPI permAPI = APILocator.getPermissionAPI(); List<WebAsset> list = dh.list(); toReturn.addAll(permAPI.filterCollection(list, PermissionAPI.PERMISSION_READ, false, user)); if(limit > 0 && toReturn.size() >= limit + offset) done = true; else if(list.size() < internalLimit) done = true; internalOffset += internalLimit; } if(offset > toReturn.size()) { toReturn = new ArrayList<WebAsset>(); } else if(limit > 0) { int toIndex = offset + limit > toReturn.size()?toReturn.size():offset + limit; toReturn = toReturn.subList(offset, toIndex); } else if (offset > 0) { toReturn = toReturn.subList(offset, toReturn.size()); } return toReturn; } catch (Exception e) { Logger.warn(WebAssetFactory.class, "getAssetsPerConditionWithPermission failed:" + e, e); } return new ArrayList<WebAsset>(); } @SuppressWarnings("unchecked") public static List<WebAsset> getAssetsPerConditionWithPermissionWithParent(String hostId, String condition, Class c, int limit, String fromAssetId, Direction direction, String orderby, String parent, boolean showDeleted, User user) { HibernateUtil dh = new HibernateUtil(c); StringBuffer sb = new StringBuffer(); try { String tableName = ((Inode) c.newInstance()).getType(); sb.append("select {" + tableName + ".*} from " + tableName + ", inode " + tableName + "_1_ where " + tableName + ".inode = " + tableName + "_1_.inode and " + tableName + ".inode in ("); sb.append("select distinct " + tableName + "_condition.inode "); sb.append(" from " + tableName + " " + tableName + "_condition"); if (InodeUtils.isSet(parent)) { sb.append(", tree tree2"); } String sqlDel = showDeleted ? com.dotmarketing.db.DbConnectionFactory.getDBTrue() : com.dotmarketing.db.DbConnectionFactory.getDBFalse(); sb.append(" where working = " + com.dotmarketing.db.DbConnectionFactory.getDBTrue() +" and deleted = " + sqlDel); if(UtilMethods.isSet(condition)) sb.append(" and (" + condition + ") "); if (InodeUtils.isSet(parent)) { sb.append(" and (" + tableName + "_condition.inode = tree2.child"); sb.append(" and tree2.parent = '" + parent + "') "); } if(c.equals(Container.class) || c.equals(Template.class)) { sb.append(") and " + tableName + ".inode in (select inode from identifier," + tableName + "where host_inode = '" + hostId + "' and " + tableName + ".identifier = identifier.id)"); } else { sb.append(") and " + tableName + ".inode in (select inode from identifier," + tableName + "where host_inode = '" + hostId + "' and " + tableName + ".identifier = identifier.id)"); } sb.append(" order by " + orderby); Logger.debug(WebAssetFactory.class, sb.toString()); dh.setSQLQuery(sb.toString()); int firstResult = 0; dh.setFirstResult(firstResult); dh.setMaxResults(MAX_LIMIT_COUNT); PermissionAPI permAPI = APILocator.getPermissionAPI(); List<WebAsset> list = dh.list(); int pos = 0; boolean offsetFound = false; while (UtilMethods.isSet(fromAssetId) && !offsetFound && (list != null) && (0 < list.size())) { pos = 0; for (WebAsset webAsset: list) { if (webAsset.getIdentifier().equals(fromAssetId)) { offsetFound = true; break; } else { ++pos; } } if (!offsetFound) { firstResult += MAX_LIMIT_COUNT; dh.setFirstResult(firstResult); list = dh.list(); } } if ((pos == 0) && !offsetFound) { --pos; offsetFound = true; } List<WebAsset> result = new ArrayList<WebAsset>(limit); WebAsset webAsset; while (offsetFound && (result.size() < limit) && (list != null) && (0 < list.size())) { if (direction.equals(Direction.NEXT)) { ++pos; while ((result.size() < limit) && (pos < list.size())) { webAsset = (WebAsset) list.get(pos); if (permAPI.doesUserHavePermission(webAsset, PermissionAPI.PERMISSION_READ, user, false)) { result.add(webAsset); } ++pos; } if (result.size() < limit) { firstResult += MAX_LIMIT_COUNT; dh.setFirstResult(firstResult); list = dh.list(); pos = -1; } } else { --pos; while ((result.size() < limit) && (-1 < pos)) { webAsset = (WebAsset) list.get(pos); if (permAPI.doesUserHavePermission(webAsset, PermissionAPI.PERMISSION_READ, user, false)) { result.add(webAsset); } --pos; } if (result.size() < limit) { firstResult -= MAX_LIMIT_COUNT; if (-1 < firstResult) { dh = new HibernateUtil(c); dh.setSQLQuery(sb.toString()); dh.setFirstResult(firstResult); dh.setMaxResults(MAX_LIMIT_COUNT); list = dh.list(); pos = MAX_LIMIT_COUNT; } else { list = null; } } } } if (direction.equals(Direction.PREVIOUS)) Collections.reverse(result); return result; } catch (Exception e) { Logger.warn(WebAssetFactory.class, "getAssetsPerConditionWithPermission failed:" + e, e); } return new ArrayList<WebAsset>(); } @SuppressWarnings("unchecked") public static List<WebAsset> getAssetsPerConditionWithPermissionWithParent(String condition, Class c, int limit, String fromAssetId, Direction direction, String orderby, String parent, boolean showDeleted, User user) { HibernateUtil dh = new HibernateUtil(c); StringBuffer sb = new StringBuffer(); try { String tableName = ((Inode) c.newInstance()).getType(); sb.append("select {" + tableName + ".*} from " + tableName + ", inode " + tableName + "_1_ where " + tableName + ".inode = " + tableName + "_1_.inode and " + tableName + ".inode in ("); sb.append("select distinct " + tableName + "_condition.inode "); sb.append(" from " + tableName + " " + tableName + "_condition "); if (InodeUtils.isSet(parent)) { sb.append(", tree tree "); } String sqlDel = showDeleted ? com.dotmarketing.db.DbConnectionFactory.getDBTrue() : com.dotmarketing.db.DbConnectionFactory.getDBFalse(); sb.append(" where working = " + com.dotmarketing.db.DbConnectionFactory.getDBTrue() +" and deleted = " + sqlDel); if(UtilMethods.isSet(condition)) { sb.append(" and (" + condition + " )"); } if (InodeUtils.isSet(parent)) { sb.append(" and (" + tableName + "_condition.inode = tree.child"); sb.append(" and tree.parent = '" + parent + "')"); } sb.append(")"); sb.append(" order by " + orderby); Logger.debug(WebAssetFactory.class, sb.toString()); dh.setSQLQuery(sb.toString()); int firstResult = 0; dh.setFirstResult(firstResult); dh.setMaxResults(MAX_LIMIT_COUNT); PermissionAPI permAPI = APILocator.getPermissionAPI(); List<WebAsset> list = dh.list(); int pos = 0; boolean offsetFound = false; while (UtilMethods.isSet(fromAssetId) && !offsetFound && (list != null) && (0 < list.size())) { pos = 0; for (WebAsset webAsset: list) { if (webAsset.getIdentifier().equals(fromAssetId)) { offsetFound = true; break; } else { ++pos; } } if (!offsetFound) { firstResult += MAX_LIMIT_COUNT; dh.setFirstResult(firstResult); list = dh.list(); } } if ((pos == 0) && !offsetFound) { --pos; offsetFound = true; } List<WebAsset> result = new ArrayList<WebAsset>(limit); WebAsset webAsset; while (offsetFound && (result.size() < limit) && (list != null) && (0 < list.size())) { if (direction.equals(Direction.NEXT)) { ++pos; while ((result.size() < limit) && (pos < list.size())) { webAsset = (WebAsset) list.get(pos); if (permAPI.doesUserHavePermission(webAsset, PermissionAPI.PERMISSION_READ, user, false)) { result.add(webAsset); } ++pos; } if (result.size() < limit) { firstResult += MAX_LIMIT_COUNT; dh.setFirstResult(firstResult); list = dh.list(); pos = -1; } } else { --pos; while ((result.size() < limit) && (-1 < pos)) { webAsset = (WebAsset) list.get(pos); if (permAPI.doesUserHavePermission(webAsset, PermissionAPI.PERMISSION_READ, user, false)) { result.add(webAsset); } --pos; } if (result.size() < limit) { firstResult -= MAX_LIMIT_COUNT; if (-1 < firstResult) { dh = new HibernateUtil(c); dh.setSQLQuery(sb.toString()); dh.setFirstResult(firstResult); dh.setMaxResults(MAX_LIMIT_COUNT); list = dh.list(); pos = MAX_LIMIT_COUNT; } else { list = null; } } } } if (direction.equals(Direction.PREVIOUS)) Collections.reverse(result); return result; } catch (Exception e) { Logger.warn(WebAssetFactory.class, "getAssetsPerConditionWithPermission failed:" + e, e); } return new ArrayList<WebAsset>(); } @SuppressWarnings("unchecked") public static java.util.List<PermissionAsset> getAssetsAndPermissionsPerRoleAndConditionWithParent(String hostId, Role[] roles, String condition, int limit, String fromAssetId, Direction direction, String orderby, Class assetsClass, String tableName, String parentId, boolean showDeleted, User user) throws DotIdentifierStateException, DotDataException, DotSecurityException { java.util.List<PermissionAsset> entries = new java.util.ArrayList<PermissionAsset>(); orderby = tableName + "." + orderby; java.util.List<WebAsset> elements = WebAssetFactory.getAssetsPerConditionWithPermissionWithParent(hostId, condition, assetsClass, limit, fromAssetId, direction, orderby, parentId, showDeleted, user); java.util.Iterator<WebAsset> elementsIter = elements.iterator(); while (elementsIter.hasNext()) { WebAsset asset = elementsIter.next(); Folder folderParent = null; if (!WebAssetFactory.isAbstractAsset(asset)) folderParent = (Folder) APILocator.getFolderAPI().findParentFolder(asset,user,false); Host host=null; try { host = APILocator.getHostAPI().findParentHost(asset, user, false); } catch (DotDataException e1) { Logger.error(WebAssetFactory.class,"Could not load host : ",e1); } catch (DotSecurityException e1) { Logger.error(WebAssetFactory.class,"User does not have required permissions : ",e1); } if(host!=null){ if(host.isArchived()){ continue; } } java.util.List<Integer> permissions = new ArrayList<Integer>(); try { permissions = permissionAPI.getPermissionIdsFromRoles(asset, roles, user); } catch (DotDataException e) { Logger.error(WebAssetFactory.class, "Could not load permissions : ",e); } PermissionAsset permAsset = new PermissionAsset(); if (!WebAssetFactory.isAbstractAsset(asset)) permAsset.setPathToMe(APILocator.getIdentifierAPI().find(folderParent).getPath()); else permAsset.setPathToMe(""); permAsset.setPermissions(permissions); permAsset.setAsset(asset); entries.add(permAsset); } return entries; } @SuppressWarnings("unchecked") public static java.util.List<PermissionAsset> getAssetsAndPermissionsPerRoleAndConditionWithParent(Role[] roles, String condition, int limit, String fromAssetId, Direction direction, String orderby, Class assetsClass, String tableName, String parentId, boolean showDeleted, User user) throws DotIdentifierStateException, DotDataException, DotSecurityException { java.util.List<PermissionAsset> entries = new java.util.ArrayList<PermissionAsset>(); orderby = tableName + "." + orderby; java.util.List<WebAsset> elements = WebAssetFactory.getAssetsPerConditionWithPermissionWithParent(condition, assetsClass, limit, fromAssetId, direction, orderby, parentId, showDeleted, user); java.util.Iterator<WebAsset> elementsIter = elements.iterator(); while (elementsIter.hasNext()) { WebAsset asset = elementsIter.next(); Folder folderParent = null; if (!WebAssetFactory.isAbstractAsset(asset)) folderParent = (Folder) APILocator.getFolderAPI().findParentFolder(asset,user,false); Host host=null; try { host = APILocator.getHostAPI().findParentHost(asset, user, false); } catch (DotDataException e1) { Logger.error(WebAssetFactory.class,"Could not load host : ",e1); } catch (DotSecurityException e1) { Logger.error(WebAssetFactory.class,"User does not have required permissions : ",e1); } if(host!=null){ if(host.isArchived()){ continue; } } java.util.List<Integer> permissions = new ArrayList<Integer>(); try { permissions = permissionAPI.getPermissionIdsFromRoles(asset, roles, user); } catch (DotDataException e) { Logger.error(WebAssetFactory.class,"Could not load permissions : ",e); } PermissionAsset permAsset = new PermissionAsset(); if (!WebAssetFactory.isAbstractAsset(asset)) permAsset.setPathToMe(APILocator.getIdentifierAPI().find(folderParent).getPath()); else permAsset.setPathToMe(""); permAsset.setPermissions(permissions); permAsset.setAsset(asset); entries.add(permAsset); } return entries; } @SuppressWarnings("unchecked") public static java.util.List<PermissionAsset> getAssetsAndPermissionsPerRoleAndCondition(String hostId, Role[] roles, String condition, int limit, int offset, String orderby, Class assetsClass, String tableName, User user) throws DotIdentifierStateException, DotDataException, DotSecurityException { java.util.List<PermissionAsset> entries = new java.util.ArrayList<PermissionAsset>(); orderby = tableName + "." + orderby; java.util.List<WebAsset> elements = WebAssetFactory.getAssetsPerConditionWithPermission(hostId, condition, assetsClass, limit, offset, orderby, null, user); java.util.Iterator<WebAsset> elementsIter = elements.iterator(); while (elementsIter.hasNext()) { WebAsset asset = elementsIter.next(); Folder folderParent = null; if (!WebAssetFactory.isAbstractAsset(asset)) folderParent = (Folder) APILocator.getFolderAPI().findParentFolder(asset,user,false); Host host=null; try { host = APILocator.getHostAPI().findParentHost(asset, user, false); } catch (DotDataException e1) { Logger.error(WebAssetFactory.class,"Could not load host : ",e1); } catch (DotSecurityException e1) { Logger.error(WebAssetFactory.class,"User does not have required permissions : ",e1); } if(host!=null){ if(host.isArchived()){ continue; } } java.util.List<Integer> permissions = new ArrayList<Integer>(); try { permissions = permissionAPI.getPermissionIdsFromRoles(asset, roles, user); } catch (DotDataException e) { Logger.error(WebAssetFactory.class,"Could not load permissions : ",e); } PermissionAsset permAsset = new PermissionAsset(); if (!WebAssetFactory.isAbstractAsset(asset)) permAsset.setPathToMe(APILocator.getIdentifierAPI().find(folderParent).getPath()); else permAsset.setPathToMe(""); permAsset.setPermissions(permissions); permAsset.setAsset(asset); entries.add(permAsset); } return entries; } /** * * @param hostId * @param roles * @param condition * @param limit * @param offset * @param orderby * @param assetsClass * @param tableName * @param parent * @return * @throws DotDataException * @throws DotIdentifierStateException * @throws DotSecurityException * @deprecated */ @SuppressWarnings("unchecked") public static java.util.List<PermissionAsset> getAssetsAndPermissionsPerRoleAndCondition(String hostId, Role[] roles, String condition, int limit, int offset, String orderby, Class assetsClass, String tableName, String parent, User user) throws DotIdentifierStateException, DotDataException, DotSecurityException { java.util.List<PermissionAsset> entries = new java.util.ArrayList<PermissionAsset>(); orderby = tableName + "." + orderby; java.util.List<WebAsset> elements = WebAssetFactory.getAssetsPerConditionWithPermission(hostId, condition, assetsClass, limit, offset, orderby, parent, user); java.util.Iterator<WebAsset> elementsIter = elements.iterator(); while (elementsIter.hasNext()) { WebAsset asset = elementsIter.next(); Folder folderParent = null; if (!WebAssetFactory.isAbstractAsset(asset)) folderParent = (Folder) APILocator.getFolderAPI().findParentFolder(asset,user,false); Host host=null; try { host = APILocator.getHostAPI().findParentHost(asset, user, false); } catch (DotDataException e1) { Logger.error(WebAssetFactory.class,"Could not load host : ",e1); } catch (DotSecurityException e1) { Logger.error(WebAssetFactory.class,"User does not have required permissions : ",e1); } if(host!=null){ if(host.isArchived()){ continue; } } java.util.List<Integer> permissions = new ArrayList<Integer>(); try { permissions = permissionAPI.getPermissionIdsFromRoles(asset, roles, user); } catch (DotDataException e) { Logger.error(WebAssetFactory.class,"Could not load permissions : ",e); } PermissionAsset permAsset = new PermissionAsset(); if (!WebAssetFactory.isAbstractAsset(asset)) permAsset.setPathToMe(APILocator.getIdentifierAPI().find(folderParent).getPath()); else permAsset.setPathToMe(""); permAsset.setPermissions(permissions); permAsset.setAsset(asset); entries.add(permAsset); } return entries; } // Generic method for all Assets. @SuppressWarnings("unchecked") public static java.util.List<PermissionAsset> getAssetsAndPermissionsPerRoleAndCondition(Role[] roles, int limit, int offset, String orderby, Class assetsClass, String tableName, User user) throws DotIdentifierStateException, DotDataException, DotSecurityException { java.util.List<PermissionAsset> entries = new java.util.ArrayList<PermissionAsset>(); orderby = tableName + "." + orderby; java.util.List<WebAsset> elements = WebAssetFactory.getAssetsWorkingWithPermission(assetsClass, limit, offset, orderby, null, user); java.util.Iterator<WebAsset> elementsIter = elements.iterator(); while (elementsIter.hasNext()) { WebAsset asset = elementsIter.next(); Folder folderParent = null; if (!WebAssetFactory.isAbstractAsset(asset)) folderParent = (Folder) APILocator.getFolderAPI().findParentFolder(asset,user,false); Host host=null; try { host = APILocator.getHostAPI().findParentHost(asset, user, false); } catch (DotDataException e1) { Logger.error(WebAssetFactory.class,"Could not load host : ",e1); } catch (DotSecurityException e1) { Logger.error(WebAssetFactory.class,"User does not have required permissions : ",e1); } if(host!=null){ if(host.isArchived()){ continue; } } java.util.List<Integer> permissions = new ArrayList<Integer>(); try { permissions = permissionAPI.getPermissionIdsFromRoles(asset, roles, user); } catch (DotDataException e) { Logger.error(WebAssetFactory.class,"Could not load permissions : ",e); } PermissionAsset permAsset = new PermissionAsset(); if (!WebAssetFactory.isAbstractAsset(asset)) permAsset.setPathToMe(APILocator.getIdentifierAPI().find(folderParent).getPath()); else permAsset.setPathToMe(""); permAsset.setPermissions(permissions); permAsset.setAsset(asset); entries.add(permAsset); } return entries; } @SuppressWarnings("unchecked") public static java.util.List<PermissionAsset> getAssetsAndPermissionsPerRoleAndCondition(Role[] roles, String condition, int limit, int offset, String orderby, Class assetsClass, String tableName, String parent, User user) throws DotIdentifierStateException, DotDataException, DotSecurityException { java.util.List<PermissionAsset> entries = new java.util.ArrayList<PermissionAsset>(); orderby = tableName + "." + orderby; java.util.List<WebAsset> elements = WebAssetFactory.getAssetsWorkingWithPermission(assetsClass, limit, offset, orderby, parent, user); java.util.Iterator<WebAsset> elementsIter = elements.iterator(); while (elementsIter.hasNext()) { WebAsset asset = elementsIter.next(); Folder folderParent = null; if (!WebAssetFactory.isAbstractAsset(asset)) folderParent = (Folder) APILocator.getFolderAPI().findParentFolder(asset,user,false); Host host=null; try { host = APILocator.getHostAPI().findParentHost(asset, user, false); } catch (DotDataException e1) { Logger.error(WebAssetFactory.class,"Could not load host : ",e1); } catch (DotSecurityException e1) { Logger.error(WebAssetFactory.class,"User does not have required permissions : ",e1); } if(host!=null){ if(host.isArchived()){ continue; } } java.util.List<Integer> permissions = new ArrayList<Integer>(); try { permissions = permissionAPI.getPermissionIdsFromRoles(asset, roles, user); } catch (DotDataException e) { Logger.error(WebAssetFactory.class,"Could not load permissions : ",e); } PermissionAsset permAsset = new PermissionAsset(); if (!WebAssetFactory.isAbstractAsset(asset)) permAsset.setPathToMe(APILocator.getIdentifierAPI().find(folderParent).getPath()); else permAsset.setPathToMe(""); permAsset.setPermissions(permissions); permAsset.setAsset(asset); entries.add(permAsset); } return entries; } public static boolean isAbstractAsset(WebAsset asset) { if (asset instanceof Container || asset instanceof Template) return true; return false; } public static void changeAssetMenuOrder(Inode asset, int newValue, User user) throws ActionException, DotDataException { // Checking permissions if (!permissionAPI.doesUserHavePermission(asset, PERMISSION_WRITE, user)) throw new ActionException(WebKeys.USER_PERMISSIONS_EXCEPTION); if (asset instanceof Folder) { if (newValue == -1) { ((Folder)asset).setShowOnMenu(false); } else { ((Folder)asset).setShowOnMenu(true); } ((Folder)asset).setSortOrder(newValue); RefreshMenus.deleteMenu(((Folder)asset)); } else if (asset instanceof WebAsset) { if (newValue == -1) { ((WebAsset)asset).setShowOnMenu(false); } else { ((WebAsset)asset).setShowOnMenu(true); } ((WebAsset)asset).setSortOrder(newValue); RefreshMenus.deleteMenu(((WebAsset)asset)); } Identifier ident=APILocator.getIdentifierAPI().find(asset); CacheLocator.getNavToolCache().removeNavByPath(ident.getHostId(), ident.getParentPath()); HibernateUtil.saveOrUpdate(asset); } /** * This method totally removes an asset from the cms * @param currWebAsset * @return */ public static boolean deleteAsset(WebAsset currWebAsset) throws Exception { return deleteAsset(currWebAsset, null); } /** * This method totally removes an asset from the cms * @param currWebAsset * @param user If the user is passed (not null) the system will check for write permission of the user in the asset * @return true if the asset was successfully removed */ public static boolean deleteAsset(WebAsset currWebAsset, User user) throws Exception { boolean returnValue = false; if (!UtilMethods.isSet(currWebAsset) || !InodeUtils.isSet(currWebAsset.getInode())) { return returnValue; } //Checking permissions int permission = PERMISSION_WRITE; if(permissionAPI.doesUserHavePermission(currWebAsset, permission, user)) { //### Delete the IDENTIFIER entry from cache ### LiveCache.removeAssetFromCache(currWebAsset); WorkingCache.removeAssetFromCache(currWebAsset); CacheLocator.getIdentifierCache().removeFromCacheByVersionable(currWebAsset); //### END Delete the entry from cache ### //Get the identifier of the webAsset Identifier identifier = APILocator.getIdentifierAPI().find(currWebAsset); APILocator.getVersionableAPI().deleteVersionInfo(identifier.getId()); //### Get and delete the webAsset ### List<Versionable> webAssetList = new ArrayList<Versionable>(); if(currWebAsset instanceof Container) { ContainerServices.unpublishContainerFile((Container)currWebAsset); webAssetList = APILocator.getVersionableAPI().findAllVersions(identifier, APILocator.getUserAPI().getSystemUser(), false); } else if(currWebAsset instanceof HTMLPage) { PageServices.unpublishPageFile((HTMLPage)currWebAsset); RefreshMenus.deleteMenu(currWebAsset); CacheLocator.getNavToolCache().removeNavByPath(identifier.getHostId(), identifier.getParentPath()); webAssetList = APILocator.getVersionableAPI().findAllVersions(identifier, APILocator.getUserAPI().getSystemUser(), false); } else if(currWebAsset instanceof Template) { TemplateServices.unpublishTemplateFile((Template)currWebAsset); //webAssetList = APILocator.getVersionableAPI().findAllVersions(identifier, APILocator.getUserAPI().getSystemUser(), false); } else if(currWebAsset instanceof Link) { webAssetList = APILocator.getVersionableAPI().findAllVersions(identifier, APILocator.getUserAPI().getSystemUser(), false); } else if(currWebAsset instanceof File) { webAssetList = APILocator.getVersionableAPI().findAllVersions(identifier, APILocator.getUserAPI().getSystemUser(), false); RefreshMenus.deleteMenu(currWebAsset); CacheLocator.getNavToolCache().removeNavByPath(identifier.getHostId(), identifier.getParentPath()); } for(Versionable webAsset : webAssetList) { //Delete the permission of each version of the asset permissionAPI.removePermissions((WebAsset)webAsset); InodeFactory.deleteInode(webAsset); } //### END Get and delete the webAsset and the identifier ### //### Get and delete the tree entries ### List<Tree> treeList = new ArrayList<Tree>(); treeList.addAll(TreeFactory.getTreesByChild(identifier.getInode())); treeList.addAll(TreeFactory.getTreesByParent(identifier.getInode())); for(Tree tree : treeList) { TreeFactory.deleteTree(tree); } //### END Get and delete the tree entries ### //### Get and delete the multitree entries ### List<MultiTree> multiTrees = new ArrayList<MultiTree>(); if (currWebAsset instanceof Container || currWebAsset instanceof HTMLPage) { multiTrees = MultiTreeFactory.getMultiTree(identifier); } if(UtilMethods.isSet(multiTrees)) { for(MultiTree multiTree : multiTrees) { MultiTreeFactory.deleteMultiTree(multiTree); } } //### END Get and delete the multitree entries ### //### Delete the Identifier ### APILocator.getIdentifierAPI().delete(identifier); //### Delete the Identifier ### returnValue = true; } else { throw new Exception(WebKeys.USER_PERMISSIONS_EXCEPTION); } return returnValue; } @SuppressWarnings("unchecked") public static int getAssetsCountPerConditionWithPermissionWithParent(String condition, Class c, int limit, int offset, String parent, boolean showDeleted, User user) { DotConnect dc = new DotConnect(); StringBuffer sb = new StringBuffer(); try { String tableName = ((Inode) c.newInstance()).getType(); sb.append("select " + tableName + ".identifier as identifier, " + tableName + "_1_.inode as inode from " + tableName + ", inode " + tableName + "_1_ where " + tableName + ".inode = " + tableName + "_1_.inode and " + tableName + ".inode in ("); sb.append("select distinct " + tableName + "_condition.inode "); sb.append(" from " + tableName + " " + tableName + "_condition "); if (InodeUtils.isSet(parent)) { sb.append(", tree tree "); } String sqlDel = showDeleted ? com.dotmarketing.db.DbConnectionFactory.getDBTrue() : com.dotmarketing.db.DbConnectionFactory.getDBFalse(); sb.append(" where working = " + com.dotmarketing.db.DbConnectionFactory.getDBTrue() +" and deleted = " + sqlDel); if(UtilMethods.isSet(condition)) { sb.append(" and (" + condition + " )"); } if (InodeUtils.isSet(parent)) { sb.append(" and (" + tableName + "_condition.inode = tree.child"); sb.append(" and tree.parent = '" + parent + "')"); } sb.append(")"); Logger.debug(WebAssetFactory.class, sb.toString()); dc.setSQL(sb.toString()); int startRow = offset; if (limit != 0) { dc.setStartRow(startRow); dc.setMaxRows(limit); } List<Map<String, String>> list = dc.loadResults(); List<Permissionable> assetsList = new ArrayList<Permissionable>(); WebAsset permissionable; PermissionAPI permAPI = APILocator.getPermissionAPI(); while ((assetsList.size() < limit) && (list != null) && (0 < list.size())) { for (Map<String, String> map: list) { permissionable = (WebAsset) c.newInstance(); permissionable.setIdentifier(map.get("identifier")); permissionable.setInode(map.get("inode")); if (permAPI.doesUserHavePermission(permissionable, PermissionAPI.PERMISSION_READ, user, false)) { assetsList.add(permissionable); if (limit < assetsList.size()) break; } } if (assetsList.size() < limit) { dc = new DotConnect(); dc.setSQL(sb.toString()); startRow += limit; dc.setStartRow(startRow); dc.setMaxRows(limit); list = dc.loadResults(); } } return assetsList.size(); } catch (Exception e) { Logger.warn(WebAssetFactory.class, "getAssetsCountPerConditionWithPermissionWithParent failed:" + e, e); } return 0; } @SuppressWarnings("unchecked") public static int getAssetsCountPerConditionWithPermission(String condition, Class c, int limit, int offset, String parent, User user) { DotConnect dc = new DotConnect(); StringBuffer sb = new StringBuffer(); try { if(offset < 0) offset = 0; String tableName = ((Inode) c.newInstance()).getType(); sb.append("select " + tableName + ".identifier as identifier, " + tableName + "_1_.inode as inode from " + tableName + ", inode " + tableName + "_1_ where " + tableName + ".inode = " + tableName + "_1_.inode and " + tableName + ".inode in ("); sb.append("select distinct " + tableName + "_condition.inode "); sb.append(" from " + tableName + " " + tableName + "_condition, tree tree, identifier identifier "); if (parent != null) { sb.append(", tree tree2"); } sb.append(" where " + condition); if (parent != null) { sb.append(" and " + tableName + "_condition.inode = tree2.child"); sb.append(" and tree2.parent = '" + parent + "'"); } sb.append(" and " + tableName + "_condition.inode = tree.child "); sb.append(" and tree.parent = identifier.id) "); List<Permissionable> toReturn = new ArrayList<Permissionable>(); int internalLimit = 500; int internalOffset = 0; boolean done = false; while(!done) { Logger.debug(WebAssetFactory.class, sb.toString()); dc.setSQL(sb.toString()); dc.setStartRow(internalOffset); dc.setMaxRows(internalLimit); List<Map<String, String>> list = dc.loadResults(); List<Permissionable> assetsList = new ArrayList<Permissionable>(); WebAsset permissionable; for (Map<String, String> map: list) { permissionable = (WebAsset) c.newInstance(); permissionable.setIdentifier(map.get("identifier")); permissionable.setInode(map.get("inode")); assetsList.add(permissionable); } PermissionAPI permAPI = APILocator.getPermissionAPI(); toReturn.addAll(permAPI.filterCollection(assetsList, PermissionAPI.PERMISSION_READ, false, user)); if(limit > 0 && toReturn.size() >= limit + offset) done = true; else if(assetsList.size() < internalLimit) done = true; internalOffset += internalLimit; } if(offset > toReturn.size()) { toReturn = new ArrayList<Permissionable>(); } else if(limit > 0) { int toIndex = offset + limit > toReturn.size()?toReturn.size():offset + limit; toReturn = toReturn.subList(offset, toIndex); } else if (offset > 0) { toReturn = toReturn.subList(offset, toReturn.size()); } return toReturn.size(); } catch (Exception e) { Logger.warn(WebAssetFactory.class, "getAssetsCountPerConditionWithPermission failed:" + e, e); } return 0; } @SuppressWarnings("unchecked") public static int getAssetsCountPerConditionWithPermissionWithParent(String hostId, String condition, Class c, int limit, int offset, String parent, boolean showDeleted, User user) { DotConnect dc = new DotConnect(); StringBuffer sb = new StringBuffer(); try { String tableName = ((Inode) c.newInstance()).getType(); sb.append("select " + tableName + ".identifier as identifier, " + tableName + "_1_.inode as inode from " + tableName + ", inode " + tableName + "_1_ where " + tableName + ".inode = " + tableName + "_1_.inode and " + tableName + ".inode in ("); sb.append("select distinct " + tableName + "_condition.inode "); sb.append(" from " + tableName + " " + tableName + "_condition"); if (InodeUtils.isSet(parent)) { sb.append(", tree tree2"); } String sqlDel = showDeleted ? com.dotmarketing.db.DbConnectionFactory.getDBTrue() : com.dotmarketing.db.DbConnectionFactory.getDBFalse(); sb.append(" where working = " + com.dotmarketing.db.DbConnectionFactory.getDBTrue() +" and deleted = " + sqlDel); if(UtilMethods.isSet(condition)) sb.append(" and (" + condition + ") "); if (InodeUtils.isSet(parent)) { sb.append(" and (" + tableName + "_condition.inode = tree2.child"); sb.append(" and tree2.parent = '" + parent + "') "); } if(c.equals(Container.class) || c.equals(Template.class)) { sb.append(") and " + tableName + ".inode in (select inode from identifier," + tableName + "where host_inode = '" + hostId + "' and " + tableName + ".identifier = identifier.id)"); } else { sb.append(") and " + tableName + ".inode in (select inode from identifier," + tableName + "where host_inode = '" + hostId + "' and " + tableName + ".identifier = identifier.id)"); } Logger.debug(WebAssetFactory.class, sb.toString()); dc.setSQL(sb.toString()); int startRow = offset; if (limit != 0) { dc.setStartRow(startRow); dc.setMaxRows(limit); } List<Map<String, String>> list = dc.loadResults(); List<Permissionable> assetsList = new ArrayList<Permissionable>(); WebAsset permissionable; PermissionAPI permAPI = APILocator.getPermissionAPI(); while ((assetsList.size() < limit) && (list != null) && (0 < list.size())) { for (Map<String, String> map: list) { permissionable = (WebAsset) c.newInstance(); permissionable.setIdentifier(map.get("identifier")); permissionable.setInode(map.get("inode")); if (permAPI.doesUserHavePermission(permissionable, PermissionAPI.PERMISSION_READ, user, false)) { assetsList.add(permissionable); if (limit < assetsList.size()) break; } } if (assetsList.size() < limit) { dc = new DotConnect(); dc.setSQL(sb.toString()); startRow += limit; dc.setStartRow(startRow); dc.setMaxRows(limit); list = dc.loadResults(); } } return assetsList.size(); } catch (Exception e) { Logger.warn(WebAssetFactory.class, "getAssetsCountPerConditionWithPermissionWithParent failed:" + e, e); } return 0; } @SuppressWarnings("unchecked") public static int getAssetsCountPerConditionWithPermission(String hostId, String condition, Class c, int limit, int offset, String parent, User user) { DotConnect dc = new DotConnect(); StringBuffer sb = new StringBuffer(); try { String tableName = ((Inode) c.newInstance()).getType(); sb.append("select " + tableName + "_1_.identifier as identifier, " + tableName + "_1_.inode as inode from " + tableName + ", inode " + tableName + "_1_ where " + tableName + ".inode = " + tableName + "_1_.inode and " + tableName + ".inode in ("); sb.append("select distinct " + tableName + "_condition.inode "); sb.append(" from " + tableName + " " + tableName + "_condition"); if (InodeUtils.isSet(parent)) { sb.append(", tree tree2"); } sb.append(" where " + condition); if (InodeUtils.isSet(parent)) { sb.append(" and " + tableName + "_condition.inode = tree2.child"); sb.append(" and tree2.parent = '" + parent + "'"); } if(c.equals(Container.class) || c.equals(Template.class)) { sb.append(") and " + tableName + ".inode in (select inode from identifier," + tableName + "where host_inode = '" + hostId + "' and " + tableName + ".identifier = identifier.id)"); } else if(c.equals(HTMLPage.class)) { sb.append(") and " + tableName + ".inode in (select inode from identifier," + tableName + "where host_inode = '" + hostId + "' and " + tableName + ".identifier = identifier.id)"); } else { sb.append(") and " + tableName + ".inode in (select tree.child from identifier, tree where host_inode = '" + hostId + "' and tree.parent = identifier.id)"); } Logger.debug(WebAssetFactory.class, sb.toString()); List<Permissionable> toReturn = new ArrayList<Permissionable>(); int internalLimit = ITERATION_LIMIT; int internalOffset = 0; boolean done = false; while(!done) { Logger.debug(WebAssetFactory.class, sb.toString()); dc.setSQL(sb.toString()); dc.setStartRow(internalOffset); dc.setMaxRows(internalLimit); List<Map<String, String>> list = dc.loadResults(); List<Permissionable> assetsList = new ArrayList<Permissionable>(); WebAsset permissionable; for (Map<String, String> map: list) { permissionable = (WebAsset) c.newInstance(); permissionable.setIdentifier(map.get("identifier")); permissionable.setInode(map.get("inode")); assetsList.add(permissionable); } PermissionAPI permAPI = APILocator.getPermissionAPI(); toReturn.addAll(permAPI.filterCollection(assetsList, PermissionAPI.PERMISSION_READ, false, user)); if(limit > 0 && toReturn.size() >= limit + offset) done = true; else if(assetsList.size() < internalLimit) done = true; internalOffset += internalLimit; } if(offset > toReturn.size()) { toReturn = new ArrayList<Permissionable>(); } else if(limit > 0) { int toIndex = offset + limit > toReturn.size()?toReturn.size():offset + limit; toReturn = toReturn.subList(offset, toIndex); } else if (offset > 0) { toReturn = toReturn.subList(offset, toReturn.size()); } return toReturn.size(); } catch (Exception e) { Logger.warn(WebAssetFactory.class, "getAssetsCountPerConditionWithPermission failed:" + e, e); } return 0; } public PaginatedArrayList<PermissionAsset> getAssetsAndPermissions(String hostId, Role[] roles, boolean includeArchived, int limit, int offset, String orderBy, String tableName, String parent, String query, User user) throws DotIdentifierStateException, DotDataException, DotSecurityException { PaginatedArrayList<PermissionAsset> paginatedEntries = new PaginatedArrayList<PermissionAsset> (); long totalCount = 0; AssetType type = AssetType.getObject(tableName.toUpperCase()); java.util.List<? extends WebAsset> elements = null; Map<String,Object> params = new HashMap<String, Object>(); if(UtilMethods.isSet(query)){ params.put("title", query.toLowerCase().replace("\'","\\\'")); } try { if (type.equals(AssetType.HTMLPAGE)){ if(UtilMethods.isSet(query)){ params.put("pageUrl", query.toLowerCase()); } elements = htmlPageAPI.findHtmlPages(user, includeArchived, params, hostId,null,null, parent, offset, limit, orderBy); }else if (type.equals(AssetType.FILE_ASSET)){ if(UtilMethods.isSet(query)){ params.put("fileName", query.toLowerCase().replace("\'","\\\'")); } elements = fileAPI.findFiles(user, includeArchived, params, hostId, null,null, parent, offset, limit, orderBy); }else if (type.equals(AssetType.CONTAINER)){ if(APILocator.getIdentifierAPI().isIdentifier(query)){ params.put("identifier", query); } elements = containerAPI.findContainers(user, includeArchived, params, hostId, null, null, parent, offset, limit, orderBy); }else if (type.equals(AssetType.TEMPLATE)){ if(APILocator.getIdentifierAPI().isIdentifier(query)){ params.put("identifier", query); } elements = templateAPI.findTemplates(user, includeArchived, params, hostId, null, null, parent, offset, limit, orderBy); }else if (type.equals(AssetType.LINK)){ elements = linksAPI.findLinks(user, includeArchived, params, hostId, null, null, parent, offset, limit, orderBy); } } catch (DotSecurityException e) { Logger.warn(WebAssetFactory.class, "getAssetsAndPermissions failed:" + e, e); } catch (DotDataException e) { Logger.warn(WebAssetFactory.class, "getAssetsAndPermissions failed:" + e, e); } totalCount = elements!=null?((PaginatedArrayList)elements).getTotalResults():0; java.util.Iterator<? extends WebAsset> elementsIter = elements.iterator(); while (elementsIter.hasNext()) { WebAsset asset = elementsIter.next(); Folder folderParent = null; if (!WebAssetFactory.isAbstractAsset(asset)) folderParent = (Folder) APILocator.getFolderAPI().findParentFolder(asset,user,false); Host host=null; try { host = APILocator.getHostAPI().findParentHost(asset, user, false); } catch (DotDataException e1) { Logger.error(WebAssetFactory.class,"Could not load host : ",e1); } catch (DotSecurityException e1) { Logger.error(WebAssetFactory.class,"User does not have required permissions : ",e1); } if(host!=null){ if(host.isArchived()){ continue; } } java.util.List<Integer> permissions = new ArrayList<Integer>(); try { permissions = permissionAPI.getPermissionIdsFromRoles(asset, roles, user); } catch (DotDataException e) { Logger.error(WebAssetFactory.class,"Could not load permissions : ",e); } PermissionAsset permAsset = new PermissionAsset(); if (!WebAssetFactory.isAbstractAsset(asset)) permAsset.setPathToMe(APILocator.getIdentifierAPI().find(folderParent).getPath()); else permAsset.setPathToMe(""); permAsset.setPermissions(permissions); permAsset.setAsset(asset); paginatedEntries.add(permAsset); } paginatedEntries.setTotalResults(totalCount); return paginatedEntries; } }
gpl-3.0
TheHortonMachine/hortonmachine
modules/src/main/java/org/hortonmachine/modules/MultiTca.java
2856
package org.hortonmachine.modules; import static org.hortonmachine.hmachine.i18n.HortonMessages.OMSMULTITCA_AUTHORCONTACTS; import static org.hortonmachine.hmachine.i18n.HortonMessages.OMSMULTITCA_AUTHORNAMES; import static org.hortonmachine.hmachine.i18n.HortonMessages.OMSMULTITCA_DESCRIPTION; import static org.hortonmachine.hmachine.i18n.HortonMessages.OMSMULTITCA_KEYWORDS; import static org.hortonmachine.hmachine.i18n.HortonMessages.OMSMULTITCA_LABEL; import static org.hortonmachine.hmachine.i18n.HortonMessages.OMSMULTITCA_LICENSE; import static org.hortonmachine.hmachine.i18n.HortonMessages.OMSMULTITCA_NAME; import static org.hortonmachine.hmachine.i18n.HortonMessages.OMSMULTITCA_STATUS; import static org.hortonmachine.hmachine.i18n.HortonMessages.OMSMULTITCA_inCp9_DESCRIPTION; import static org.hortonmachine.hmachine.i18n.HortonMessages.OMSMULTITCA_inFlow_DESCRIPTION; import static org.hortonmachine.hmachine.i18n.HortonMessages.OMSMULTITCA_inPit_DESCRIPTION; import static org.hortonmachine.hmachine.i18n.HortonMessages.OMSMULTITCA_outMultiTca_DESCRIPTION; import org.hortonmachine.gears.libs.modules.HMConstants; import org.hortonmachine.gears.libs.modules.HMModel; import org.hortonmachine.hmachine.modules.geomorphology.multitca.OmsMultiTca; import oms3.annotations.Author; import oms3.annotations.Description; import oms3.annotations.Execute; import oms3.annotations.In; import oms3.annotations.Keywords; import oms3.annotations.Label; import oms3.annotations.License; import oms3.annotations.Name; import oms3.annotations.Status; import oms3.annotations.UI; @Description(OMSMULTITCA_DESCRIPTION) @Author(name = OMSMULTITCA_AUTHORNAMES, contact = OMSMULTITCA_AUTHORCONTACTS) @Keywords(OMSMULTITCA_KEYWORDS) @Label(OMSMULTITCA_LABEL) @Name("_" + OMSMULTITCA_NAME) @Status(OMSMULTITCA_STATUS) @License(OMSMULTITCA_LICENSE) public class MultiTca extends HMModel { @Description(OMSMULTITCA_inPit_DESCRIPTION) @UI(HMConstants.FILEIN_UI_HINT_RASTER) @In public String inPit = null; @Description(OMSMULTITCA_inFlow_DESCRIPTION) @UI(HMConstants.FILEIN_UI_HINT_RASTER) @In public String inFlow = null; @Description(OMSMULTITCA_inCp9_DESCRIPTION) @UI(HMConstants.FILEIN_UI_HINT_RASTER) @In public String inCp9 = null; @Description(OMSMULTITCA_outMultiTca_DESCRIPTION) @UI(HMConstants.FILEOUT_UI_HINT) @In public String outMultiTca = null; @Execute public void process() throws Exception { OmsMultiTca multitca = new OmsMultiTca(); multitca.inPit = getRaster(inPit); multitca.inFlow = getRaster(inFlow); multitca.inCp9 = getRaster(inCp9); multitca.pm = pm; multitca.doProcess = doProcess; multitca.doReset = doReset; multitca.process(); dumpRaster(multitca.outMultiTca, outMultiTca); } }
gpl-3.0
Polfo/sigma-h
sigmah/src/main/java/org/sigmah/client/map/IconFactory.java
2745
/* * All Sigmah code is released under the GNU General Public License v3 * See COPYRIGHT.txt and LICENSE.txt. */ package org.sigmah.client.map; import com.google.gwt.maps.client.geom.Point; import com.google.gwt.maps.client.geom.Size; import com.google.gwt.maps.client.overlay.Icon; import org.sigmah.shared.report.content.BubbleMapMarker; import org.sigmah.shared.report.content.IconMapMarker; import org.sigmah.shared.report.content.MapMarker; import org.sigmah.shared.report.model.MapIcon; /** * Factory for GoogleMap Icons originating from the * {@link org.sigmah.server.endpoint.gwtrpc.MapIconServlet} * * @author Alex Bertram */ public class IconFactory { private IconFactory() {} public static Icon createIcon(MapMarker marker) { if (marker instanceof IconMapMarker) { return createIconMapMarker((IconMapMarker) marker); } else if (marker instanceof BubbleMapMarker) { return createBubbleMapMarker((BubbleMapMarker) marker); } else { return Icon.DEFAULT_ICON; } } /** * Creates a Google Maps icon based on an ActivityInfo MapIcon * * @author Alex Bertram */ public static Icon createIconMapMarker(IconMapMarker marker) { MapIcon mapIcon = marker.getIcon(); String iconUrl = "mapicons/" + mapIcon.getName() + ".png"; Icon icon = Icon.newInstance(Icon.DEFAULT_ICON); icon.setImageURL(iconUrl); icon.setIconSize(Size.newInstance(mapIcon.getWidth(), mapIcon.getHeight())); icon.setShadowSize(Size.newInstance(0, 0)); Point anchor = Point.newInstance(mapIcon.getAnchorX(), mapIcon.getAnchorY()); icon.setIconAnchor(anchor); icon.setInfoWindowAnchor(anchor); icon.setPrintImageURL(iconUrl + "&chof=gif"); icon.setMozPrintImageURL(iconUrl); return icon; } public static Icon createBubbleMapMarker(BubbleMapMarker marker) { StringBuilder sb = new StringBuilder(); sb.append("icon?t=bubble&r=").append(marker.getRadius()).append("&c=").append(marker.getColor()); String iconUrl = sb.toString(); int size = marker.getRadius() * 2; Icon icon = Icon.newInstance(Icon.DEFAULT_ICON); icon.setImageURL(iconUrl); icon.setIconSize(Size.newInstance(size, size)); icon.setShadowSize(Size.newInstance(0, 0)); Point anchor = Point.newInstance(marker.getRadius(), marker.getRadius()); icon.setIconAnchor(anchor); icon.setInfoWindowAnchor(anchor); icon.setPrintImageURL(iconUrl); icon.setMozPrintImageURL(iconUrl); return icon; } }
gpl-3.0
DevinKamer/mazes_and_minotaurs
MazesAndMinotaurs/app/src/main/java/com/example/cis/mazeminotaurs/character/stats/Score.java
184
package com.example.cis.mazeminotaurs.character.stats; /** * Created by jusmith on 3/30/17. */ public enum Score { MIGHT, GRACE, SKILL, WILL, WITS, LUCK; }
gpl-3.0
HedbergMartin/mFC
codes/v3XzZ/mFC/items/crafting/RecipeRegister.java
23423
package v3XzZ.mFC.items.crafting; import v3XzZ.mFC.mFC; import v3XzZ.mFC.lib.Blocks; import v3XzZ.mFC.lib.Items; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.oredict.OreDictionary; import cpw.mods.fml.common.registry.GameRegistry; /** * Project: mFC * * Class: RecipeRegister * * @author v3XzZ * @license Lesser GNU Public License v3 (http://www.gnu.org/licenses/lgpl.html) * */ public class RecipeRegister { public static void addRecipe(){ GameRegistry.addRecipe(new ItemStack(Items.obsidianPick, 1), new Object[] { "XXX", " | ", " | ", Character.valueOf('X'), Block.obsidian, Character.valueOf('|'), Item.stick }); GameRegistry.addRecipe(new ItemStack(Items.obsidianShovel, 1), new Object[] { " X ", " | ", " | ", Character.valueOf('X'), Block.obsidian, Character.valueOf('|'), Item.stick }); GameRegistry.addRecipe(new ItemStack(Items.obsidianAxe, 1), new Object[] { "XX ", "X| ", " | ", Character.valueOf('X'), Block.obsidian, Character.valueOf('|'), Item.stick }); GameRegistry.addRecipe(new ItemStack(Items.obsidianHoe, 1), new Object[] { "XX ", " | ", " | ", Character.valueOf('X'), Block.obsidian, Character.valueOf('|'), Item.stick }); GameRegistry.addRecipe(new ItemStack(Items.obsidianSword, 1), new Object[] { " X ", " X ", " | ", Character.valueOf('X'), Block.obsidian, Character.valueOf('|'), Item.stick }); GameRegistry.addRecipe( new ItemStack( Items.money, 40 ), new Object[] { "XXX", "CGC", "XXX", Character.valueOf('X'), Item.paper, Character.valueOf('C'), new ItemStack (Item.dyePowder, 1, 2), Character.valueOf('G'), Item.ingotGold }); GameRegistry.addRecipe( new ItemStack( Items.moldEmpty, 1 ), new Object[] { "X X", "XXX", Character.valueOf('X'), Block.stone }); GameRegistry.addShapelessRecipe( new ItemStack( Items.moldMilk, 1 ), new Object[] { new ItemStack(Items.moldEmpty), new ItemStack(Item.bucketMilk) }); GameRegistry.addShapelessRecipe( new ItemStack( Items.moldMilk, 1 ), new Object[] { new ItemStack(Items.moldEmpty), new ItemStack(Items.woodenBucketMilk) }); GameRegistry.addRecipe( new ItemStack( Items.cheeseWheel, 1 ), new Object[] { "U", Character.valueOf('U'), Items.moldCheese }); GameRegistry.addRecipe( new ItemStack( Items.drinkingGlass, 1 ), new Object[] { "X X", " X ", Character.valueOf('X'), Block.thinGlass }); GameRegistry.addShapelessRecipe( new ItemStack( Items.glassWater, 1 ), new Object[] { new ItemStack(Items.drinkingGlass), new ItemStack(Item.bucketWater) }); GameRegistry.addShapelessRecipe( new ItemStack( Items.glassWater, 1 ), new Object[] { new ItemStack(Items.drinkingGlass), new ItemStack(Items.woodenBucketWater) }); GameRegistry.addRecipe( new ItemStack( Items.Knife, 1 ), new Object[] { " U", " U ", "X ", Character.valueOf('X'), Item.stick, Character.valueOf('U'), Item.ingotIron }); GameRegistry.addShapelessRecipe( new ItemStack( Items.baconRaw, 1 ), new Object[] { new ItemStack(Items.Knife, 1, OreDictionary.WILDCARD_VALUE), new ItemStack(Item.porkRaw) }); GameRegistry.addRecipe( new ItemStack( Items.clayCup, 1 ), new Object[] { "P P", "XPX", Character.valueOf('X'), Block.sand, Character.valueOf('P'), Item.clay }); GameRegistry.addShapelessRecipe( new ItemStack( Items.cupChocolate, 1 ), new Object[] { new ItemStack(Item.dyePowder, 1, 3), new ItemStack(Items.cup, 1), new ItemStack(Item.bucketMilk, 1), }); GameRegistry.addShapelessRecipe( new ItemStack( Items.cupChocolate, 1 ), new Object[] { new ItemStack(Item.dyePowder, 1, 3), new ItemStack(Items.cup, 1), new ItemStack(Items.woodenBucketMilk, 1), }); GameRegistry.addRecipe( new ItemStack( Items.clayTeapot, 1 ), new Object[] { " H ", "PXP", " PX", Character.valueOf('X'), Block.sand, Character.valueOf('P'), Item.clay, Character.valueOf('H'), Item.stick }); GameRegistry.addShapelessRecipe( new ItemStack( Block.blockClay, 1 ), new Object[] { new ItemStack(Item.bucketWater, 1), new ItemStack(Block.dirt, 1), new ItemStack(Block.sand, 1), }); GameRegistry.addShapelessRecipe( new ItemStack( Block.blockClay, 1 ), new Object[] { new ItemStack(Items.woodenBucketWater, 1), new ItemStack(Block.dirt, 1), new ItemStack(Block.sand, 1), }); GameRegistry.addShapelessRecipe( new ItemStack( Items.breadSlice, 4 ), new Object[] { new ItemStack(Items.Knife, 1, OreDictionary.WILDCARD_VALUE), new ItemStack(Item.bread) }); GameRegistry.addRecipe( new ItemStack( Items.sandwichEgg, 1 ), new Object[] { " X ", " CP", " X ", Character.valueOf('X'), Items.breadSlice, Character.valueOf('P'), Items.friedEgg, Character.valueOf('C'), Items.cheesePiece }); GameRegistry.addRecipe( new ItemStack( Items.sandwichBacon, 1 ), new Object[] { " X ", "BCP", " X ", Character.valueOf('X'), Items.breadSlice, Character.valueOf('P'), Items.friedEgg, Character.valueOf('C'), Items.cheesePiece, Character.valueOf('B'), Items.bacon }); GameRegistry.addShapelessRecipe( new ItemStack( Items.teapotCold, 1 ), new Object[] { new ItemStack(Item.seeds, 1), new ItemStack(Item.bucketWater), new ItemStack(Items.teapot) }); GameRegistry.addShapelessRecipe( new ItemStack( Items.teapotCold, 1 ), new Object[] { new ItemStack(Item.seeds, 1), new ItemStack(Items.woodenBucketWater), new ItemStack(Items.teapot) }); GameRegistry.addRecipe( new ItemStack( Items.cupTea, 3 ), new Object[] { " # ", "XXX", Character.valueOf('#'), Items.teapotHot, Character.valueOf('X'), Items.cup }); GameRegistry.addRecipe( new ItemStack( Items.woodenBucket, 1), new Object[] { "# #", "# #", " # ", Character.valueOf('#'), Block.planks }); GameRegistry.addRecipe( new ItemStack( Items.sausageRaw, 2), new Object[] { "##", Character.valueOf('#'), Item.beefRaw }); GameRegistry.addRecipe(new ItemStack(Item.cake, 1), new Object[] { "AAA", "BEB", "CCC", Character.valueOf('A'), Items.woodenBucketMilk, Character.valueOf('B'), Item.sugar, Character.valueOf('C'), Item.wheat, Character.valueOf('E'), Item.egg }); GameRegistry.addShapelessRecipe( new ItemStack( Item.seeds, 3 ), new Object[] { new ItemStack(Item.wheat, 1) }); GameRegistry.addRecipe(new ItemStack(Item.saddle, 1), new Object[] { "AAA", "BAB", "C C", Character.valueOf('A'), Item.leather, Character.valueOf('B'), Item.silk, Character.valueOf('C'), Item.ingotIron, }); GameRegistry.addShapelessRecipe( new ItemStack(Items.pumpkinPiece, 4), new Object[] { new ItemStack(Block.pumpkin, 1), new ItemStack(Items.Knife, 1, OreDictionary.WILDCARD_VALUE) }); GameRegistry.addRecipe( new ItemStack( Items.guacamole, 1), new Object[] { " XO", " # ", Character.valueOf('#'), Item.bowlEmpty, Character.valueOf('X'), Items.avacado, Character.valueOf('O'), Items.onion }); GameRegistry.addShapelessRecipe( new ItemStack(Item.dyePowder, 1, 3), new Object[] { new ItemStack(Items.CocoaFruit, 1) }); GameRegistry.addRecipe(new ItemStack(Items.itemApplePie, 1), new Object[] { "ABA", "BEB", "CCC", Character.valueOf('A'), Items.woodenBucketMilk, Character.valueOf('B'), Item.appleRed, Character.valueOf('C'), Item.wheat, Character.valueOf('E'), Item.egg }); GameRegistry.addRecipe(new ItemStack(Items.itemApplePie, 1), new Object[] { "ABA", "BEB", "CCC", Character.valueOf('A'), Item.bucketMilk, Character.valueOf('B'), Item.appleRed, Character.valueOf('C'), Item.wheat, Character.valueOf('E'), Item.egg }); GameRegistry.addRecipe(new ItemStack(Items.itemTacoPie, 1), new Object[] { "HGF", "AEA", "CCC", Character.valueOf('A'), Items.woodenBucketMilk, Character.valueOf('C'), Item.wheat, Character.valueOf('E'), Item.egg, Character.valueOf('F'), Item.porkCooked, Character.valueOf('G'), Items.cheesePiece, Character.valueOf('H'), Items.tomato }); GameRegistry.addRecipe(new ItemStack(Items.itemTacoPie, 1), new Object[] { "HGF", "AEA", "CCC", Character.valueOf('A'), Item.bucketMilk, Character.valueOf('C'), Item.wheat, Character.valueOf('E'), Item.egg, Character.valueOf('F'), Item.porkCooked, Character.valueOf('G'), Items.cheesePiece, Character.valueOf('H'), Items.tomato }); GameRegistry.addRecipe(new ItemStack(Items.itemChocolateCake, 1), new Object[] { "BAB", "DED", "CCC", Character.valueOf('A'), Item.bucketMilk, Character.valueOf('B'), new ItemStack(Item.dyePowder, 1, 3), Character.valueOf('C'), Item.wheat, Character.valueOf('E'), Item.egg, Character.valueOf('D'), Item.sugar }); GameRegistry.addRecipe(new ItemStack(Items.itemChocolateCake, 1), new Object[] { "BAB", "DED", "CCC", Character.valueOf('A'), Items.woodenBucketMilk, Character.valueOf('B'), new ItemStack(Item.dyePowder, 1, 3), Character.valueOf('C'), Item.wheat, Character.valueOf('E'), Item.egg, Character.valueOf('D'), Item.sugar }); GameRegistry.addRecipe(new ItemStack(Items.itemMeatPie, 1), new Object[] { "BBB", "AEA", "CCC", Character.valueOf('A'), Items.woodenBucketMilk, Character.valueOf('C'), Item.wheat, Character.valueOf('E'), Item.egg, Character.valueOf('B'), Item.beefCooked }); GameRegistry.addRecipe(new ItemStack(Items.itemMeatPie, 1), new Object[] { "BBB", "AEA", "CCC", Character.valueOf('A'), Item.bucketMilk, Character.valueOf('C'), Item.wheat, Character.valueOf('E'), Item.egg, Character.valueOf('B'), Item.beefCooked }); GameRegistry.addRecipe(new ItemStack(Items.bottleOfOil, 1), new Object[] { "B", "E", Character.valueOf('B'), Items.avacado, Character.valueOf('E'), Item.glassBottle }); GameRegistry.addRecipe(new ItemStack(Items.bottleOfOil, 1), new Object[] { "BBB", " E ", Character.valueOf('B'), Item.seeds, Character.valueOf('E'), Item.glassBottle }); GameRegistry.addShapelessRecipe( new ItemStack(Items.meatScrap, 1), new Object[] { new ItemStack(Item.beefCooked, 1), new ItemStack(Items.Knife, 1, OreDictionary.WILDCARD_VALUE) }); GameRegistry.addShapelessRecipe(new ItemStack(Items.beefJerky, 1), new Object[] { new ItemStack(Item.beefRaw, 1), new ItemStack(Items.Knife, 1, OreDictionary.WILDCARD_VALUE), new ItemStack(Items.saltPile, 1) }); GameRegistry.addShapelessRecipe( new ItemStack(Items.pasta, 2), new Object[] { new ItemStack(Item.bucketWater, 1), new ItemStack(Item.egg, 1), new ItemStack(Item.wheat, 1) }); GameRegistry.addShapelessRecipe( new ItemStack(Items.pasta, 2), new Object[] { new ItemStack(Items.woodenBucketWater, 1), new ItemStack(Item.egg, 1), new ItemStack(Item.wheat, 1) }); GameRegistry.addRecipe(new ItemStack(Items.glassAppleJuice, 1), new Object[] { "B", "E", Character.valueOf('B'), Item.appleRed, Character.valueOf('E'), Items.drinkingGlass }); GameRegistry.addRecipe(new ItemStack(Items.glassMelonJuice, 1), new Object[] { "B", "E", Character.valueOf('B'), Item.melon, Character.valueOf('E'), Items.drinkingGlass }); GameRegistry.addRecipe(new ItemStack(Items.sandwichChicken, 1 ), new Object[] { " X ", "BCP", " X ", Character.valueOf('X'), Items.breadSlice, Character.valueOf('P'), Items.tomato, Character.valueOf('C'), Item.chickenCooked, Character.valueOf('B'), Items.lettuce }); GameRegistry.addRecipe(new ItemStack(Items.mayonnaise, 1), new Object[] { "K", "X", "#", Character.valueOf('#'), Item.bowlEmpty, Character.valueOf('X'), Items.bottleOfOil, Character.valueOf('K'), Item.egg }); GameRegistry.addRecipe(new ItemStack(Items.pastaMeat, 1), new Object[] { "P", "M", "#", Character.valueOf('#'), Item.bowlEmpty, Character.valueOf('P'), Items.pasta, Character.valueOf('M'), Items.meatScrap }); GameRegistry.addRecipe(new ItemStack(Items.pastaMeat, 1), new Object[] { "M", "P", "#", Character.valueOf('#'), Item.bowlEmpty, Character.valueOf('P'), Items.pasta, Character.valueOf('M'), Items.meatScrap }); GameRegistry.addRecipe(new ItemStack(Items.saladChicken, 1), new Object[] { "PKM", " # ", Character.valueOf('#'), Item.bowlEmpty, Character.valueOf('P'), Items.lettuce, Character.valueOf('K'), Item.chickenCooked, Character.valueOf('M'), Items.tomato }); GameRegistry.addRecipe(new ItemStack(Items.saladCeasar, 1), new Object[] { " Y ", "PKM", " # ", Character.valueOf('#'), Item.bowlEmpty, Character.valueOf('P'), Items.lettuce, Character.valueOf('K'), Item.chickenCooked, Character.valueOf('M'), Item.bread, Character.valueOf('Y'), Items.mayonnaise }); GameRegistry.addRecipe(new ItemStack(Items.saladPasta, 1), new Object[] { "PKM", " # ", Character.valueOf('#'), Item.bowlEmpty, Character.valueOf('P'), Items.lettuce, Character.valueOf('K'), Items.pasta, Character.valueOf('M'), Items.tomato }); GameRegistry.addRecipe(new ItemStack(Blocks.woodenTrellis, 2), new Object[] { "P P", "P P", "P P", Character.valueOf('P'), Item.stick }); GameRegistry.addRecipe(new ItemStack(Blocks.beerKeg, 1), new Object[] { "IPI", "PBP", "S S", Character.valueOf('P'), Block.planks, Character.valueOf('S'), Item.stick, Character.valueOf('B'), Item.bucketEmpty, Character.valueOf('I'), Item.ingotIron }); GameRegistry.addRecipe(new ItemStack(Items.beerBase, 1), new Object[] { "MMM", "MMM", "BHB", Character.valueOf('M'), Items.malt, Character.valueOf('H'), Block.vine , Character.valueOf('B'), Item.bucketWater }); GameRegistry.addRecipe(new ItemStack(Items.christmasMustBase, 1), new Object[] { "SMS", "MMM", "BHB", Character.valueOf('M'), Items.malt, Character.valueOf('H'), Block.vine , Character.valueOf('B'), Item.bucketWater, Character.valueOf('S'), Item.sugar }); GameRegistry.addRecipe(new ItemStack(Items.whiteWineBase, 1), new Object[] { "MMM", "MMM", "BHB", Character.valueOf('M'), Items.grapes, Character.valueOf('H'), new ItemStack(Item.dyePowder, 1, 15) , Character.valueOf('B'), Item.bucketWater }); GameRegistry.addRecipe(new ItemStack(Items.redWineBase, 1), new Object[] { "MMM", "MMM", "BHB", Character.valueOf('M'), Items.grapes, Character.valueOf('H'), new ItemStack(Item.dyePowder, 1, 1) , Character.valueOf('B'), Item.bucketWater }); GameRegistry.addRecipe(new ItemStack(Items.beerCup, 1), new Object[] { "MMS", "MM ", Character.valueOf('M'), Block.planks, Character.valueOf('S'), Item.stick }); GameRegistry.addRecipe(new ItemStack(Items.dogFood, 3), new Object[] { " S ", "PBP", " P ", Character.valueOf('S'), Item.beefRaw, Character.valueOf('B'), Item.porkRaw, Character.valueOf('P'), Item.paper }); GameRegistry.addRecipe(new ItemStack(Items.jamJar, 1), new Object[] { " P ", "X X", " X ", Character.valueOf('X'), Block.thinGlass, Character.valueOf('P'), Block.planks }); GameRegistry.addRecipe(new ItemStack(Items.StrawBerryjam, 1), new Object[] { "SSS", "UJU", Character.valueOf('S'), Items.strawBerry, Character.valueOf('J'), Items.jamJar, Character.valueOf('U'), Item.sugar }); GameRegistry.addRecipe(new ItemStack(Items.RaspBerryjam, 1), new Object[] { "SSS", "UJU", Character.valueOf('S'), Items.raspBerry, Character.valueOf('J'), Items.jamJar, Character.valueOf('U'), Item.sugar }); GameRegistry.addRecipe(new ItemStack(Items.palt, 3), new Object[] { "VPV", "PBP", "VPS", Character.valueOf('S'), Items.saltPile, Character.valueOf('B'), Item.porkCooked, Character.valueOf('V'), Item.wheat, Character.valueOf('P'), Item.potato }); GameRegistry.addRecipe(new ItemStack(Items.pancake, 3, 1), new Object[] { " J ", "WWE", "SME", Character.valueOf('S'), Items.saltPile, Character.valueOf('E'), Item.egg, Character.valueOf('W'), Item.wheat, Character.valueOf('M'), Item.bucketMilk, Character.valueOf('J'), Items.RaspBerryjam }); GameRegistry.addRecipe(new ItemStack(Items.pancake, 3, 1), new Object[] { " J ", "WWE", "SME", Character.valueOf('S'), Items.saltPile, Character.valueOf('E'), Item.egg, Character.valueOf('W'), Item.wheat, Character.valueOf('M'), Items.woodenBucketMilk, Character.valueOf('J'), Items.RaspBerryjam }); GameRegistry.addRecipe(new ItemStack(Items.pancake, 3, 0), new Object[] { " J ", "WWE", "SME", Character.valueOf('S'), Items.saltPile, Character.valueOf('E'), Item.egg, Character.valueOf('W'), Item.wheat, Character.valueOf('M'), Item.bucketMilk, Character.valueOf('J'), Items.StrawBerryjam }); GameRegistry.addRecipe(new ItemStack(Items.pancake, 3, 0), new Object[] { " J ", "WWE", "SME", Character.valueOf('S'), Items.saltPile, Character.valueOf('E'), Item.egg, Character.valueOf('W'), Item.wheat, Character.valueOf('M'), Items.woodenBucketMilk, Character.valueOf('J'), Items.StrawBerryjam }); GameRegistry.addRecipe(new ItemStack(Items.glassRaspBerryJuice, 1), new Object[] { "B", "B", "E", Character.valueOf('B'), Items.raspBerry, Character.valueOf('E'), Items.drinkingGlass }); GameRegistry.addRecipe(new ItemStack(Items.glassStrawBerryJuice, 1), new Object[] { "B", "B", "E", Character.valueOf('B'), Items.strawBerry, Character.valueOf('E'), Items.drinkingGlass }); GameRegistry.addRecipe(new ItemStack(Items.macaroniAndCheese, 1), new Object[] { "C M", " B ", Character.valueOf('B'), Item.bowlEmpty, Character.valueOf('C'), Items.cheesePiece, Character.valueOf('M'), Items.pasta }); GameRegistry.addRecipe(new ItemStack(Items.tomatoStew, 1), new Object[] { "T O", " B ", Character.valueOf('B'), Item.bowlEmpty, Character.valueOf('T'), Items.tomato, Character.valueOf('O'), Items.onion }); GameRegistry.addShapelessRecipe(new ItemStack(Items.wasabi, 2), new Object[]{ new ItemStack(Items.wasabiRoot, 1) }); GameRegistry.addRecipe(new ItemStack(Items.MakiLong, 1), new Object[]{ "LRL", "LWL", "LRL", Character.valueOf('L'), Block.waterlily, Character.valueOf('R'), Items.bowlOfRice, Character.valueOf('W'), Items.wasabi }); GameRegistry.addShapelessRecipe(new ItemStack(Items.MakiShort, 4), new Object[]{ new ItemStack(Items.MakiLong, 1), new ItemStack(Items.Knife, 1, OreDictionary.WILDCARD_VALUE) }); GameRegistry.addRecipe(new ItemStack(Items.LaxSuchi, 6), new Object[]{ "FFF", "W W", "RRR", Character.valueOf('F'), Item.fishRaw, Character.valueOf('R'), Items.bowlOfRice, Character.valueOf('W'), Items.wasabi }); GameRegistry.addRecipe(new ItemStack(Items.chocolateBar, 1), new Object[] { "S", "C", "M", Character.valueOf('S'), Item.sugar, Character.valueOf('C'), new ItemStack(Item.dyePowder, 1, 3), Character.valueOf('M'), Items.woodenBucketMilk }); GameRegistry.addRecipe(new ItemStack(Items.chocolateBar, 1), new Object[] { "S", "C", "M", Character.valueOf('S'), Item.sugar, Character.valueOf('C'), new ItemStack(Item.dyePowder, 1, 3), Character.valueOf('M'), Item.bucketMilk }); GameRegistry.addRecipe(new ItemStack(Items.cornSeeds, 1), new Object[] { "#", Character.valueOf('#'), Items.cornCob }); GameRegistry.addRecipe(new ItemStack(Items.orangeJuice), new Object[] { "X","Z", Character.valueOf('X'), Items.orange, Character.valueOf('Z'), Items.drinkingGlass }); GameRegistry.addRecipe(new ItemStack(Items.tallBottle, 4), new Object[] { " X ","X X","XXX", Character.valueOf('X'), Block.glass }); GameRegistry.addRecipe(new ItemStack(Blocks.plate, 2), new Object[] { " X ","XXX"," X ", Character.valueOf('X'), Block.planks }); GameRegistry.addRecipe(new ItemStack(Blocks.shelf, 2), new Object[] { " X ","S S", Character.valueOf('X'), Block.planks, Character.valueOf('S'), Item.stick }); GameRegistry.addRecipe(new ItemStack(Items.candyCane, 1), new Object[] { " X ","SXS"," X ", Character.valueOf('X'), Item.sugar, Character.valueOf('S'), new ItemStack(Item.dyePowder, 0, 1) }); //Smelting GameRegistry.addSmelting(Items.moldMilk.itemID, new ItemStack(Items.moldCheese, 1), 0); GameRegistry.addSmelting(Items.baconRaw.itemID, new ItemStack(Items.bacon, 1), 0); GameRegistry.addSmelting(Items.clayCup.itemID, new ItemStack(Items.cup, 1), 0); GameRegistry.addSmelting(Items.clayTeapot.itemID, new ItemStack(Items.teapot, 1), 0); GameRegistry.addSmelting(Items.teapotCold.itemID, new ItemStack(Items.teapotHot, 1), 0); GameRegistry.addSmelting(Item.egg.itemID, new ItemStack(Items.friedEgg, 1), 0); GameRegistry.addSmelting(Items.sausageRaw.itemID, new ItemStack(Items.sausage, 1), 0); GameRegistry.addSmelting(Items.woodenBucketWater.itemID, new ItemStack(Items.saltPile, 1), 0); GameRegistry.addSmelting(Item.bucketWater.itemID, new ItemStack(Items.saltPile, 1), 0); GameRegistry.addSmelting(Items.pumpkinPiece.itemID, new ItemStack(Items.roastPumpkin, 1), 0); GameRegistry.addSmelting(Item.seeds.itemID, new ItemStack(Items.malt, 1), 0); GameRegistry.addSmelting(Items.cornCob.itemID, new ItemStack(Items.cornCobCooked), 0); MinecraftForge.addGrassSeed(new ItemStack(Items.redSeeds), 10); MinecraftForge.addGrassSeed(new ItemStack(Items.yellowSeeds), 10); if(mFC.GrassDropMelon) MinecraftForge.addGrassSeed(new ItemStack(Item.melonSeeds), 10); if(mFC.GrassDropPumpkin) MinecraftForge.addGrassSeed(new ItemStack(Item.pumpkinSeeds), 10); } public static void loadModern(){ GameRegistry.addRecipe( new ItemStack( Items.hamburgerBread, 2 ), new Object[] { "XX", " ", "XX", Character.valueOf('X'), Item.wheat }); GameRegistry.addRecipe(new ItemStack(Items.hamburgerOrginal, 1), new Object[] { " X ", "QP ", " X ", Character.valueOf('X'), Items.hamburgerBread, Character.valueOf('P'), Items.hamburger, Character.valueOf('Q'), Items.lettuce }); GameRegistry.addRecipe( new ItemStack( Items.hamburgerCheese, 1 ), new Object[] { " X ", "QPT", " X ", Character.valueOf('X'), Items.hamburgerBread, Character.valueOf('P'), Items.hamburger, Character.valueOf('T'), Items.cheesePiece, Character.valueOf('Q'), Items.lettuce }); GameRegistry.addShapelessRecipe( new ItemStack( Items.hamburgerRaw, 1 ), new Object[] { new ItemStack(Items.Knife, 1), new ItemStack(Item.beefRaw) }); GameRegistry.addRecipe( new ItemStack( Items.frenchFries, 3 ), new Object[] { "U", "X", Character.valueOf('X'), Item.potato, Character.valueOf('U'), Items.Knife }); GameRegistry.addRecipe( new ItemStack( Items.hamburgerBacon, 1 ), new Object[] { " X ", "QPT", " X ", Character.valueOf('X'), Items.hamburgerBread, Character.valueOf('P'), Items.hamburger, Character.valueOf('T'), Items.cheesePiece, Character.valueOf('Q'), Items.bacon }); GameRegistry.addRecipe(new ItemStack(Items.bottleOfKetchup, 1), new Object[] { "S", "B", "E", Character.valueOf('B'), Items.tomato, Character.valueOf('E'), Item.glassBottle, Character.valueOf('S'), Item.sugar }); GameRegistry.addRecipe( new ItemStack( Items.hotDogKetchup, 1), new Object[] { "K", "X", "#", Character.valueOf('#'), Item.bread, Character.valueOf('X'), Items.sausage, Character.valueOf('K'), Items.bottleOfKetchup }); GameRegistry.addRecipe(new ItemStack(Items.hotDogKetchup, 1), new Object[] { "B", "E", Character.valueOf('B'), Items.bottleOfKetchup, Character.valueOf('E'), Items.hotDog }); GameRegistry.addSmelting(Items.hamburgerRaw.itemID, new ItemStack(Items.hamburger, 1), 0); GameRegistry.addRecipe( new ItemStack( Items.hotDog, 1), new Object[] { "X", "#", Character.valueOf('#'), Item.bread, Character.valueOf('X'), Items.sausage }); } }
gpl-3.0
tuura/workcraft-2.2
WorkcraftCore/src/main/java/org/workcraft/util/ListMap.java
1771
/* * * Copyright 2008,2009 Newcastle University * * This file is part of Workcraft. * * Workcraft is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Workcraft is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Workcraft. If not, see <http://www.gnu.org/licenses/>. * */ package org.workcraft.util; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Set; public class ListMap <K,V> { private HashMap<K,LinkedList<V>> map = new HashMap<K, LinkedList<V>>(); public void put (K key, V value) { LinkedList<V> list = map.get(key); if (list == null) { list = new LinkedList<V>(); map.put(key, list); } list.add(value); } public void remove(K key, V value) { LinkedList<V> list = map.get(key); if (list != null) { list.remove(value); if (list.isEmpty()) map.remove(key); } } public List<V> get(K key) { LinkedList<V> list = map.get(key); if (list != null) return Collections.unmodifiableList(list); else return Collections.emptyList(); } public Set<K> keySet() { return map.keySet(); } public boolean isEmpty() { return map.isEmpty(); } public Collection<LinkedList<V>> values() { return map.values(); } public void clear() { map.clear(); } }
gpl-3.0
frittatenbank/jewelthief
core/src/at/therefactory/jewelthief/ui/buttons/GrayStateButton.java
2340
/* * Copyright (C) 2016 Christian DeTamble * * This file is part of Jewel Thief. * * Jewel Thief is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Jewel Thief is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Jewel Thief. If not, see <http://www.gnu.org/licenses/>. */ package at.therefactory.jewelthief.ui.buttons; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import at.therefactory.jewelthief.JewelThief; public class GrayStateButton extends GrayButton { private final Sprite[] sprites; private final String[] captions; private short state; public GrayStateButton(String[] captions, String[] spriteIds, short initState, boolean adaptWidthToCaption, float x, float y, float width, float height) { super(captions[0], x, y, width, height, adaptWidthToCaption); this.state = initState; this.captions = captions; this.sprites = new Sprite[spriteIds.length]; for (int i = 0; i < spriteIds.length; i++) { sprites[i] = JewelThief.getInstance().getTextureAtlas().createSprite(spriteIds[i]); } } @Override public void renderCaption(SpriteBatch batch) { font.setColor(Color.DARK_GRAY); font.draw(batch, captions[state], x + xCaptionOffset + 5 + pressedOffset, y + yCaptionOffset - pressedOffset); sprites[state].setPosition(x + 10 + pressedOffset, y + height/2 - sprites[state].getHeight()/2 + 1 - pressedOffset); sprites[state].draw(batch); } @Override public void setCaption(String caption) { super.setCaption(caption); captions[state] = caption; } public void nextState() { state = (short) ((state + 1) % sprites.length); } public int getState() { return state; } }
gpl-3.0
aelred/grakn
grakn-test/src/test/java/ai/grakn/test/graql/analytics/ShortestPathTest.java
16831
package ai.grakn.test.graql.analytics; import ai.grakn.GraknGraph; import ai.grakn.GraknGraphFactory; import ai.grakn.concept.Concept; import ai.grakn.concept.ConceptId; import ai.grakn.concept.Entity; import ai.grakn.concept.EntityType; import ai.grakn.concept.RelationType; import ai.grakn.concept.RoleType; import ai.grakn.exception.GraknValidationException; import ai.grakn.graph.internal.computer.GraknSparkComputer; import ai.grakn.graql.ComputeQuery; import ai.grakn.graql.Graql; import ai.grakn.graql.internal.analytics.GraknVertexProgram; import ai.grakn.test.EngineContext; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import com.google.common.collect.Lists; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.ListIterator; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import static ai.grakn.test.GraknTestEnv.usingOrientDB; import static ai.grakn.test.GraknTestEnv.usingTinker; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assume.assumeFalse; public class ShortestPathTest { private static final String thing = "thing"; private static final String anotherThing = "anotherThing"; private static final String related = "related"; private static final String veryRelated = "veryRelated"; private ConceptId entityId1; private ConceptId entityId2; private ConceptId entityId3; private ConceptId entityId4; private ConceptId entityId5; private ConceptId relationId12; private ConceptId relationId13; private ConceptId relationId24; private ConceptId relationId34; private ConceptId relationId1A12; public GraknGraphFactory factory; @ClassRule public static EngineContext rule = EngineContext.startInMemoryServer(); @Before public void setUp() { // TODO: Fix tests in orientdb assumeFalse(usingOrientDB()); factory = rule.factoryWithNewKeyspace(); Logger logger = (Logger) org.slf4j.LoggerFactory.getLogger(GraknVertexProgram.class); logger.setLevel(Level.DEBUG); logger = (Logger) org.slf4j.LoggerFactory.getLogger(ComputeQuery.class); logger.setLevel(Level.DEBUG); } @After public void close() { GraknSparkComputer.clear(); } @Test(expected = IllegalStateException.class) public void testShortestPathExceptionIdNotFound() throws Exception { // TODO: Fix in TinkerGraphComputer assumeFalse(usingTinker()); // test on an empty graph try(GraknGraph graph = factory.getGraph()) { graph.graql().compute().path().from(entityId1).to(entityId2).execute(); } } @Test(expected = IllegalStateException.class) public void testShortestPathExceptionIdNotFoundSubgraph() throws Exception { // TODO: Fix in TinkerGraphComputer assumeFalse(usingTinker()); addOntologyAndEntities(); try(GraknGraph graph = factory.getGraph()) { graph.graql().compute().path().from(entityId1).to(entityId4).in(thing, related).execute(); } } @Test//(expected = RuntimeException.class) public void testShortestPathExceptionPathNotFound() throws Exception { // TODO: Fix in TinkerGraphComputer assumeFalse(usingTinker()); addOntologyAndEntities(); try(GraknGraph graph = factory.getGraph()) { assertFalse(graph.graql().compute().path().from(entityId1).to(entityId5).execute().isPresent()); } } @Test public void testShortestPath() throws Exception { // TODO: Fix in TinkerGraphComputer assumeFalse(usingTinker()); List<String> correctPath; List<String> result; addOntologyAndEntities(); try(GraknGraph graph = factory.getGraph()) { // directly connected vertices correctPath = Lists.newArrayList(entityId1.getValue(), relationId12.getValue()); result = graph.graql().compute().path().from(entityId1).to(relationId12).execute() .get().stream().map(Concept::getId).map(ConceptId::getValue).collect(Collectors.toList()); assertEquals(correctPath.size(), result.size()); for (int i = 0; i < result.size(); i++) { assertEquals(correctPath.get(i), result.get(i)); } Collections.reverse(correctPath); result = Graql.compute().withGraph(graph).path().to(entityId1).from(relationId12).execute() .get().stream().map(Concept::getId).map(ConceptId::getValue).collect(Collectors.toList()); assertEquals(correctPath.size(), result.size()); for (int i = 0; i < result.size(); i++) { assertEquals(correctPath.get(i), result.get(i)); } // entities connected by a relation correctPath = Lists.newArrayList(entityId1.getValue(), relationId12.getValue(), entityId2.getValue()); result = graph.graql().compute().path().from(entityId1).to(entityId2).execute() .get().stream().map(Concept::getId).map(ConceptId::getValue).collect(Collectors.toList()); assertEquals(correctPath.size(), result.size()); for (int i = 0; i < result.size(); i++) { assertEquals(correctPath.get(i), result.get(i)); } Collections.reverse(correctPath); result = graph.graql().compute().path().to(entityId1).from(entityId2).execute() .get().stream().map(Concept::getId).map(ConceptId::getValue).collect(Collectors.toList()); assertEquals(correctPath.size(), result.size()); for (int i = 0; i < result.size(); i++) { assertEquals(correctPath.get(i), result.get(i)); } // only one path exists with given subtypes correctPath = Lists.newArrayList(entityId2.getValue(), relationId12.getValue(), entityId1.getValue(), relationId13.getValue(), entityId3.getValue()); result = Graql.compute().withGraph(graph).path().to(entityId3).from(entityId2).in(thing, related).execute() .get().stream().map(Concept::getId).map(ConceptId::getValue).collect(Collectors.toList()); assertEquals(correctPath.size(), result.size()); for (int i = 0; i < result.size(); i++) { assertEquals(correctPath.get(i), result.get(i)); } Collections.reverse(correctPath); result = graph.graql().compute().path().in(thing, related).to(entityId2).from(entityId3).execute() .get().stream().map(Concept::getId).map(ConceptId::getValue).collect(Collectors.toList()); assertEquals(correctPath.size(), result.size()); for (int i = 0; i < result.size(); i++) { assertEquals(correctPath.get(i), result.get(i)); } correctPath = Lists.newArrayList(entityId1.getValue(), relationId12.getValue(), entityId2.getValue()); result = graph.graql().compute().path().in(thing, related).to(entityId2).from(entityId1).execute() .get().stream().map(Concept::getId).map(ConceptId::getValue).collect(Collectors.toList()); assertEquals(correctPath.size(), result.size()); for (int i = 0; i < result.size(); i++) { assertEquals(correctPath.get(i), result.get(i)); } Collections.reverse(correctPath); result = graph.graql().compute().path().in(thing, related).from(entityId2).to(entityId1).execute() .get().stream().map(Concept::getId).map(ConceptId::getValue).collect(Collectors.toList()); assertEquals(correctPath.size(), result.size()); for (int i = 0; i < result.size(); i++) { assertEquals(correctPath.get(i), result.get(i)); } } } @Test public void testShortestPathCastingWithThreeMessages() throws Exception { // TODO: Fix in TinkerGraphComputer assumeFalse(usingTinker()); List<String> correctPath; List<String> result; addOntologyAndEntities2(); try(GraknGraph graph = factory.getGraph()) { correctPath = Lists.newArrayList(entityId2.getValue(), relationId12.getValue(), entityId1.getValue(), relationId13.getValue(), entityId3.getValue()); result = graph.graql().compute().path().from(entityId2).to(entityId3).execute() .get().stream().map(Concept::getId).map(ConceptId::getValue).collect(Collectors.toList()); assertEquals(correctPath.size(), result.size()); for (int i = 0; i < result.size(); i++) { assertEquals(correctPath.get(i), result.get(i)); } Collections.reverse(correctPath); result = graph.graql().compute().path().to(entityId2).from(entityId3).execute() .get().stream().map(Concept::getId).map(ConceptId::getValue).collect(Collectors.toList()); assertEquals(correctPath.size(), result.size()); for (int i = 0; i < result.size(); i++) { assertEquals(correctPath.get(i), result.get(i)); } correctPath = Lists.newArrayList(relationId1A12.getValue(), entityId1.getValue(), relationId13.getValue(), entityId3.getValue()); result = graph.graql().compute().path().from(relationId1A12).to(entityId3).execute() .get().stream().map(Concept::getId).map(ConceptId::getValue).collect(Collectors.toList()); assertEquals(correctPath.size(), result.size()); for (int i = 0; i < result.size(); i++) { assertEquals(correctPath.get(i), result.get(i)); } Collections.reverse(correctPath); result = graph.graql().compute().path().to(relationId1A12).from(entityId3).execute() .get().stream().map(Concept::getId).map(ConceptId::getValue).collect(Collectors.toList()); assertEquals(correctPath.size(), result.size()); for (int i = 0; i < result.size(); i++) { assertEquals(correctPath.get(i), result.get(i)); } } } @Test public void testMultipleIndependentShortestPaths() throws GraknValidationException { assumeFalse(usingTinker()); Set<List<ConceptId>> validPaths = new HashSet<>(); ConceptId startId; ConceptId endId; try(GraknGraph graph = factory.getGraph()) { EntityType entityType = graph.putEntityType(thing); RoleType role1 = graph.putRoleType("role1"); RoleType role2 = graph.putRoleType("role2"); entityType.playsRole(role1).playsRole(role2); RelationType relationType = graph.putRelationType(related).hasRole(role1).hasRole(role2); Entity start = entityType.addEntity(); Entity end = entityType.addEntity(); startId = start.getId(); endId = end.getId(); // create N identical length paths int numberOfPaths = 10; for (int i = 0; i < numberOfPaths; i++) { List<ConceptId> validPath = new ArrayList<>(); validPath.add(startId); Entity middle = entityType.addEntity(); ConceptId middleId = middle.getId(); ConceptId assertion1 = relationType.addRelation() .putRolePlayer(role1, start) .putRolePlayer(role2, middle).getId(); validPath.add(assertion1); validPath.add(middleId); ConceptId assertion2 = relationType.addRelation() .putRolePlayer(role1, middle) .putRolePlayer(role2, end).getId(); validPath.add(assertion2); validPath.add(endId); validPaths.add(validPath); } graph.commitOnClose(); } try(GraknGraph graph = factory.getGraph()) { Optional<List<Concept>> result = graph.graql().compute().path().from(startId).to(endId).execute(); assertEquals(1, validPaths.stream().filter(path -> checkPathsAreEqual(path, result)).count()); } } private boolean checkPathsAreEqual(List<ConceptId> correctPath, Optional<List<Concept>> computedPath) { if (computedPath.isPresent()) { List<Concept> actualPath = computedPath.get(); if (actualPath.isEmpty()) { return correctPath.isEmpty(); } else { ListIterator<Concept> elements = actualPath.listIterator(); boolean returnState = true; while (elements.hasNext()) { returnState &= (correctPath.get(elements.nextIndex()).equals(elements.next().getId())); } return returnState; } } else { return correctPath.isEmpty(); } } private void addOntologyAndEntities() throws GraknValidationException { try(GraknGraph graph = factory.getGraph()) { EntityType entityType1 = graph.putEntityType(thing); EntityType entityType2 = graph.putEntityType(anotherThing); Entity entity1 = entityType1.addEntity(); Entity entity2 = entityType1.addEntity(); Entity entity3 = entityType1.addEntity(); Entity entity4 = entityType2.addEntity(); Entity entity5 = entityType1.addEntity(); entityId1 = entity1.getId(); entityId2 = entity2.getId(); entityId3 = entity3.getId(); entityId4 = entity4.getId(); entityId5 = entity5.getId(); RoleType role1 = graph.putRoleType("role1"); RoleType role2 = graph.putRoleType("role2"); entityType1.playsRole(role1).playsRole(role2); entityType2.playsRole(role1).playsRole(role2); RelationType relationType = graph.putRelationType(related).hasRole(role1).hasRole(role2); relationId12 = relationType.addRelation() .putRolePlayer(role1, entity1) .putRolePlayer(role2, entity2).getId(); relationId13 = relationType.addRelation() .putRolePlayer(role1, entity1) .putRolePlayer(role2, entity3).getId(); relationId24 = relationType.addRelation() .putRolePlayer(role1, entity2) .putRolePlayer(role2, entity4).getId(); relationId34 = relationType.addRelation() .putRolePlayer(role1, entity3) .putRolePlayer(role2, entity4).getId(); graph.commitOnClose(); } GraknSparkComputer.clear(); } private void addOntologyAndEntities2() throws GraknValidationException { try(GraknGraph graph = factory.getGraph()) { EntityType entityType = graph.putEntityType(thing); Entity entity1 = entityType.addEntity(); Entity entity2 = entityType.addEntity(); Entity entity3 = entityType.addEntity(); entityId1 = entity1.getId(); entityId2 = entity2.getId(); entityId3 = entity3.getId(); RoleType role1 = graph.putRoleType("role1"); RoleType role2 = graph.putRoleType("role2"); entityType.playsRole(role1).playsRole(role2); RelationType relationType = graph.putRelationType(related).hasRole(role1).hasRole(role2); RoleType role3 = graph.putRoleType("role3"); RoleType role4 = graph.putRoleType("role4"); entityType.playsRole(role3).playsRole(role4); relationType.playsRole(role3).playsRole(role4); RelationType relationType2 = graph.putRelationType(veryRelated).hasRole(role3).hasRole(role4); relationId12 = relationType.addRelation() .putRolePlayer(role1, entity1) .putRolePlayer(role2, entity2).getId(); relationId13 = relationType.addRelation() .putRolePlayer(role1, entity1) .putRolePlayer(role2, entity3).getId(); relationId1A12 = relationType2.addRelation() .putRolePlayer(role3, entity1) .putRolePlayer(role4, graph.getConcept(relationId12)).getId(); graph.commitOnClose(); } GraknSparkComputer.clear(); } }
gpl-3.0
McZapkie/TerraFirmaProgressivePack
TFCPPHMod/src/main/java/wahazar/tfcpphelper/blocks/BlockNeutralLiquid.java
3479
package wahazar.tfcpphelper.blocks; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; import net.minecraft.init.Blocks; import net.minecraft.util.IIcon; import net.minecraft.util.MathHelper; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.fluids.BlockFluidClassic; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidContainerRegistry; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.IFluidBlock; import wahazar.tfcpphelper.core.TFCPPBlocks; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class BlockNeutralLiquid extends BlockFluidClassic implements IFluidBlock { protected IIcon[] icons; protected String fluidName; public BlockNeutralLiquid(String fluidname) { super(FluidRegistry.getFluid(fluidname.toLowerCase()), Material.water); this.setTickRandomly(true); this.setHardness(0.0F); this.setLightLevel(0.0F); this.setLightOpacity(255); this.setQuantaPerBlock(4); this.fluidName = fluidname; this.setBlockName(fluidname); } @Override public void onEntityCollidedWithBlock(World world, int x, int y, int z, Entity e) { return; } /** * Called whenever the block is added into the world. Args: world, x, y, z */ @Override public void onBlockAdded(World world, int x, int y, int z) { //super.onBlockAdded(world, x, y, z); if (world.getBlock(x, y, z) == this) { world.scheduleBlockUpdate(x, y, z, this, this.tickRate(world)); } } /** * Lets the block know when one of its neighbor changes. Doesn't know which neighbor changed (coordinates passed are * their own) Args: x, y, z, neighbor blockID */ @Override public void onNeighborBlockChange(World world, int x, int y, int z, Block block) { super.onNeighborBlockChange(world, x, y, z, block); } @Override public int tickRate(World world) { return 10; } @Override public void registerBlockIcons(IIconRegister register) { this.getFluid().setIcons(register.registerIcon("tfcpphelper:"+fluidName+"_still"), register.registerIcon("tfcpphelper:"+fluidName+"_flow")); icons = new IIcon[]{getFluid().getStillIcon(), getFluid().getFlowingIcon()}; } @Override @SideOnly(Side.CLIENT) public IIcon getIcon(int side, int meta) { return side != 0 && side != 1 ? this.icons[1] : this.icons[0]; } @Override public FluidStack drain(World world, int x, int y, int z, boolean doDrain) { if (doDrain) { world.setBlock(x, y, z, Blocks.air); } return new FluidStack(getFluid(), MathHelper.floor_float(getQuantaPercentage(world, x, y, z) * FluidContainerRegistry.BUCKET_VOLUME)); } @Override public boolean canDrain(World world, int x, int y, int z) { return true; } @Override public float getFilledPercentage(World world, int x, int y, int z) { return 1; } @Override public Fluid getFluid() { return FluidRegistry.getFluid(fluidName.toLowerCase()); } }
gpl-3.0
octachoron/gir2java
generated-src/generated/gobject20/gobject/GParamSpecParam.java
792
package generated.gobject20.gobject; import org.bridj.BridJ; import org.bridj.Pointer; import org.bridj.ann.Field; import org.bridj.ann.Library; @Library("gobject-2.0") public class GParamSpecParam extends GParamSpec { static { BridJ.register(); } public GParamSpecParam() { super(); } public GParamSpecParam(Pointer pointer) { super(pointer); } @Field(0) public GParamSpec gparamspecparam_field_parent_instance() { return this.io.getNativeObjectField(this, 0); } @Field(0) public GParamSpecParam gparamspecparam_field_parent_instance(GParamSpec gparamspecparam_field_parent_instance) { this.io.setNativeObjectField(this, 0, gparamspecparam_field_parent_instance); return this; } }
gpl-3.0
Armarr/Autorank-2
src/me/armar/plugins/autorank/statsmanager/query/parameter/implementation/FoodTypeParameter.java
434
package me.armar.plugins.autorank.statsmanager.query.parameter.implementation; import me.armar.plugins.autorank.statsmanager.query.parameter.StatisticParameter; public class FoodTypeParameter extends StatisticParameter { public FoodTypeParameter(String value) { super(value); } @Override public String getKey() { return "foodType"; } @Override public void setKey(String key) { } }
gpl-3.0
quike/alpheusafpparser
src/main/java/com/mgz/afp/modca/EFM_EndFormMap.java
849
/* Copyright 2015 Rudolf Fiala This file is part of Alpheus AFP Parser. Alpheus AFP Parser is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Alpheus AFP Parser is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Alpheus AFP Parser. If not, see <http://www.gnu.org/licenses/> */ package com.mgz.afp.modca; import com.mgz.afp.base.StructuredFieldBaseName; public class EFM_EndFormMap extends StructuredFieldBaseName { }
gpl-3.0
HolodeckOne-Minecraft/WorldEdit
worldedit-core/src/main/java/com/sk89q/worldedit/command/argument/Chunk3dVectorConverter.java
4239
/* * WorldEdit, a Minecraft world manipulation toolkit * Copyright (C) sk89q <http://www.sk89q.com> * Copyright (C) WorldEdit team and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.sk89q.worldedit.command.argument; import com.google.common.collect.ImmutableList; import com.google.common.collect.Range; import com.google.common.reflect.TypeToken; import com.sk89q.worldedit.internal.annotation.Chunk3d; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.util.formatting.text.Component; import com.sk89q.worldedit.util.formatting.text.TextComponent; import org.enginehub.piston.CommandManager; import org.enginehub.piston.converter.ArgumentConverter; import org.enginehub.piston.converter.ArgumentConverters; import org.enginehub.piston.converter.ConversionResult; import org.enginehub.piston.converter.FailedConversion; import org.enginehub.piston.converter.SuccessfulConversion; import org.enginehub.piston.inject.InjectedValueAccess; import org.enginehub.piston.inject.Key; import java.util.List; import java.util.function.Function; public class Chunk3dVectorConverter<C, T> implements ArgumentConverter<T> { public static void register(CommandManager commandManager) { CommaSeparatedValuesConverter<Integer> intConverter = CommaSeparatedValuesConverter.wrap(ArgumentConverters.get(TypeToken.of(int.class))); commandManager.registerConverter(Key.of(BlockVector3.class, Chunk3d.class), new Chunk3dVectorConverter<>( intConverter, Range.closed(2, 3), cmps -> { switch (cmps.size()) { case 2: return BlockVector3.at(cmps.get(0), 0, cmps.get(1)); case 3: return BlockVector3.at(cmps.get(0), cmps.get(1), cmps.get(2)); default: break; } throw new AssertionError("Expected 2 or 3 components"); }, "block vector with x,z or x,y,z" )); } private final ArgumentConverter<C> componentConverter; private final Range<Integer> componentCount; private final Function<List<C>, T> vectorConstructor; private final String acceptableArguments; private Chunk3dVectorConverter(ArgumentConverter<C> componentConverter, Range<Integer> componentCount, Function<List<C>, T> vectorConstructor, String acceptableArguments) { this.componentConverter = componentConverter; this.componentCount = componentCount; this.vectorConstructor = vectorConstructor; this.acceptableArguments = acceptableArguments; } @Override public Component describeAcceptableArguments() { return TextComponent.of("any " + acceptableArguments); } @Override public ConversionResult<T> convert(String argument, InjectedValueAccess context) { ConversionResult<C> components = componentConverter.convert(argument, context); if (!components.isSuccessful()) { return components.failureAsAny(); } if (!componentCount.contains(components.get().size())) { return FailedConversion.from(new IllegalArgumentException( "Must have " + componentCount + " vector components")); } T vector = vectorConstructor.apply(ImmutableList.copyOf(components.get())); return SuccessfulConversion.fromSingle(vector); } }
gpl-3.0
jesselix/zz-algorithms
algorithms-primer/src/main/java/li/jesse/searching/BinarySearch.java
2566
package li.jesse.searching; public class BinarySearch { public enum Operation { EQUAL, GREATER, GREATER_EQUAL, LESS, LESS_EQUAL } public enum FirstLast { FIRST, LAST } public static int binarySearch(int[] array, int key) { int left = 0; int right = array.length - 1; int mid; while (left <= right) { mid = (left + right) / 2; if (key < array[mid]) { right = mid - 1; } else if (key > array[mid]) { left = mid + 1; } else { return mid; } } return -1; } public static int findElement(int[] array, int key, FirstLast firstLast, Operation operation) { int left = 0; int right = array.length - 1; int mid; int case1 = 0; boolean compareKeyWithArrayMid = false; if (FirstLast.LAST.equals(firstLast) && Operation.LESS.equals(operation)) { case1 = 0; } else if (FirstLast.LAST.equals(firstLast) && Operation.LESS_EQUAL.equals(operation)) { case1 = 1; } else if (FirstLast.FIRST.equals(firstLast) && Operation.GREATER.equals(operation)) { case1 = 2; } else if (FirstLast.FIRST.equals(firstLast) && Operation.GREATER_EQUAL.equals(operation)) { case1 = 3; } else if (FirstLast.FIRST.equals(firstLast) && Operation.EQUAL.equals(operation)) { case1 = 4; } else if (FirstLast.LAST.equals(firstLast) && Operation.EQUAL.equals(operation)) { case1 = 5; } while (left <= right) { mid = (left + right) / 2; if (case1 == 0 || case1 == 2 || case1 == 4) { compareKeyWithArrayMid = compareKeyWithArrayMid = (key <= array[mid]); } else { compareKeyWithArrayMid = (key < array[mid]); } if (compareKeyWithArrayMid) { right = mid - 1; } else { left = mid + 1; } } if (case1 == 0 || case1 == 2) { return right; } else if (case1 == 1 || case1 == 3) { return left; } else if (case1 == 4) { if (left < array.length && array[left] == key) { return left; } } else if (case1 == 5) { if (right >= 0 && array[right] == key) { return right; } } return -1; } }
gpl-3.0
samicemalone/android-vlc-remote
src/org/peterbaldwin/vlcremote/fragment/PlayingFragment.java
2474
/* * Copyright (C) 2013 Sam Malone * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.peterbaldwin.vlcremote.fragment; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import org.peterbaldwin.client.android.vlcremote.PlaybackActivity; import org.peterbaldwin.client.android.vlcremote.R; import org.peterbaldwin.vlcremote.listener.UIVisibilityListener; import org.peterbaldwin.vlcremote.model.Tags; import org.peterbaldwin.vlcremote.util.FragmentUtil; /** * * @author Ice */ public class PlayingFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup root, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.playing_fragment, root, false); FragmentUtil fu = new FragmentUtil(getChildFragmentManager()); fu.findOrReplaceFragment(R.id.fragment_playback, Tags.FRAGMENT_PLAYBACK, PlaybackFragment.class); fu.findOrReplaceFragment(R.id.fragment_info, Tags.FRAGMENT_INFO, InfoFragment.class); fu.findOrReplaceFragment(R.id.fragment_buttons, Tags.FRAGMENT_BUTTONS, ButtonsFragment.class); VolumeFragment mVolume = fu.findOrReplaceOptionalFragment(v, R.id.fragment_volume, Tags.FRAGMENT_VOLUME, VolumeFragment.class); BottomActionbarFragment mBottomActionBar = fu.findOrReplaceOptionalFragment(v, R.id.fragment_bottom_actionbar, Tags.FRAGMENT_BOTTOMBAR, BottomActionbarFragment.class); UIVisibilityListener ui = (PlaybackActivity) getActivity(); // notify activity about optional fragments visibility ui.setBottomActionbarFragmentVisible(mBottomActionBar != null); ui.setVolumeFragmentVisible(mVolume != null); return v; } }
gpl-3.0
NetHome/NetHomeServer
home-items/core-items/src/main/java/nu/nethome/home/items/net/wemo/soap/LightSoapClient.java
5218
package nu.nethome.home.items.net.wemo.soap; import org.w3c.dom.Node; import javax.xml.soap.*; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; public class LightSoapClient { public static final int DEFAULT_CONNECT_TIMEOUT = 700; public static final int DEFAULT_READ_TIMEOUT = 700; private static Logger logger = Logger.getLogger(LightSoapClient.class.getName()); private int connectionTimeout = DEFAULT_CONNECT_TIMEOUT; private int readTimeout = DEFAULT_READ_TIMEOUT; public LightSoapClient() { Logger.getLogger("com.sun.xml.internal.messaging").setLevel(Level.OFF); } public LightSoapClient(int connectionTimeout, int readTimeout) { this(); this.connectionTimeout = connectionTimeout; this.readTimeout = readTimeout; } public Map<String, String> sendRequest(String nameSpace, String serverURI, String method, List<Argument> arguments) throws SOAPException, IOException { final String ns = "u"; MessageFactory messageFactory = MessageFactory.newInstance(); SOAPMessage soapMessage = messageFactory.createMessage(); SOAPPart soapPart = soapMessage.getSOAPPart(); SOAPEnvelope envelope = soapPart.getEnvelope(); envelope.addNamespaceDeclaration(ns, nameSpace); SOAPBody soapBody = envelope.getBody(); SOAPElement soapBodyElem = soapBody.addChildElement(method, ns); for (Argument argument : arguments) { argument.addAsChild(soapBodyElem); } MimeHeaders headers = soapMessage.getMimeHeaders(); headers.addHeader("SOAPACTION", "\"" + nameSpace + "#" + method + "\""); headers.addHeader("Content-Type", "text/xml; charset=\"utf-8\""); soapMessage.saveChanges(); SOAPMessage response = sendRequest(serverURI, soapMessage); Map<String, String> result = new HashMap<>(); SOAPBody soapBody1 = response.getSOAPBody(); Iterator childElements = soapBody1.getChildElements(); while (childElements.hasNext()) { Object element = childElements.next(); if (element instanceof SOAPElement) { SOAPElement methodResponseElement = (SOAPElement) element; for (int i = 0; i < methodResponseElement.getChildNodes().getLength(); i++) { Node parameterNode = methodResponseElement.getChildNodes().item(i); if (parameterNode.getNodeType() == Node.ELEMENT_NODE && parameterNode.getChildNodes().getLength() == 1) { result.put(parameterNode.getLocalName(), parameterNode.getChildNodes().item(0).getTextContent()); } } } } return result; } private SOAPMessage sendRequest(String url, SOAPMessage request) throws SOAPException, IOException { // request.writeTo(System.out); long starttime = System.currentTimeMillis(); SOAPConnection soapConnection = SOAPConnectionFactory.newInstance().createConnection(); URL endpoint = new URL(new URL(url), "", new URLStreamHandler() { @Override protected URLConnection openConnection(URL url) throws IOException { URL target = new URL(url.toString()); URLConnection connection = target.openConnection(); connection.setConnectTimeout(connectionTimeout); connection.setReadTimeout(readTimeout); return (connection); } }); SOAPMessage soapResponse = soapConnection.call(request, endpoint); // soapResponse.writeTo(System.out); soapConnection.close(); logger.fine("SOAP msg " + url + " (" + (System.currentTimeMillis() - starttime) + " ms)"); return soapResponse; } public interface Argument { public void addAsChild(SOAPElement parent) throws SOAPException; } public static class StringArgument implements Argument{ private final String name; private final String value; public StringArgument(String name, String value) { this.name = name; this.value = value; } @Override public void addAsChild(SOAPElement parent) throws SOAPException { SOAPElement soapArgumentElement = parent.addChildElement(name); soapArgumentElement.addTextNode(value); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; StringArgument argument = (StringArgument) o; if (!name.equals(argument.name)) return false; if (!value.equals(argument.value)) return false; return true; } @Override public int hashCode() { int result = name.hashCode(); result = 31 * result + value.hashCode(); return result; } } }
gpl-3.0
ckaestne/LEADT
CIDE_Samples/cide_samples/Berkeley DB JE/src/com/sleepycat/je/txn/BasicLocker.java
9577
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2002-2006 * Sleepycat Software. All rights reserved. * * $Id: BasicLocker.java,v 1.1 2006/05/06 08:59:04 ckaestne Exp $ */ package com.sleepycat.je.txn; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import com.sleepycat.je.Database; import com.sleepycat.je.DatabaseException; import com.sleepycat.je.LockStats; import com.sleepycat.je.dbi.CursorImpl; import com.sleepycat.je.dbi.DatabaseImpl; import com.sleepycat.je.dbi.EnvironmentImpl; import com.sleepycat.je.utilint.DbLsn; /** * A concrete Locker that simply tracks locks and releases them when * operationEnd is called. */ public class BasicLocker extends Locker { /* * A BasicLocker can release all locks, so there is no need to distinguish * between read and write locks. * * ownedLock is used for the first lock obtained, and ownedLockSet is * instantiated and used only if more than one lock is obtained. This is * an optimization for the common case where only one lock is held by a * non-transactional locker. * * There's no need to track memory utilization for these non-txnal lockers, * because the lockers are short lived. */ private Lock ownedLock; private Set ownedLockSet; /** * Creates a BasicLocker. */ public BasicLocker(EnvironmentImpl env) throws DatabaseException { super(env, false, false); } /** * BasicLockers always have a fixed id, because they are never used for * recovery. */ protected long generateId(TxnManager txnManager) { return TxnManager.NULL_TXN_ID; } protected void checkState(boolean ignoreCalledByAbort) throws DatabaseException { /* Do nothing. */ } /** * @see Locker#lockInternal * @Override */ LockResult lockInternal(long nodeId, LockType lockType, boolean noWait, DatabaseImpl database) throws DatabaseException { /* Does nothing in BasicLocker. synchronized is for posterity. */ synchronized (this) { checkState(false); } long timeout = 0; boolean useNoWait = noWait || defaultNoWait; if (!useNoWait) { synchronized (this) { timeout = lockTimeOutMillis; } } /* Ask for the lock. */ LockGrantType grant = lockManager.lock (nodeId, this, lockType, timeout, useNoWait, database); return new LockResult(grant, null); } /** * Get the txn that owns the lock on this node. Return null if there's no * owning txn found. */ public Locker getWriteOwnerLocker(long nodeId) throws DatabaseException { return lockManager.getWriteOwnerLocker(new Long(nodeId)); } /** * Get the abort LSN for this node in the txn that owns the lock on this * node. Return null if there's no owning txn found. */ public long getOwnerAbortLsn(long nodeId) throws DatabaseException { Locker ownerTxn = lockManager.getWriteOwnerLocker(new Long(nodeId)); if (ownerTxn != null) { return ownerTxn.getAbortLsn(nodeId); } return DbLsn.NULL_LSN; } /** * Is never transactional. */ public boolean isTransactional() { return false; } /** * Is never serializable isolation. */ public boolean isSerializableIsolation() { return false; } /** * Is never read-committed isolation. */ public boolean isReadCommittedIsolation() { return false; } /** * No transactional locker is available. */ public Txn getTxnLocker() { return null; } /** * Creates a new instance of this txn for the same environment. No * transactional locks are held by this object, so no locks are retained. */ public Locker newNonTxnLocker() throws DatabaseException { return new BasicLocker(envImpl); } /** * Releases all locks, since all locks held by this locker are * non-transactional. */ public void releaseNonTxnLocks() throws DatabaseException { operationEnd(true); } /** * Release locks at the end of the transaction. */ public void operationEnd() throws DatabaseException { operationEnd(true); } /** * Release locks at the end of the transaction. */ public void operationEnd(boolean operationOK) throws DatabaseException { /* * Don't remove locks from txn's lock collection until iteration is * done, lest we get a ConcurrentModificationException during deadlock * graph "display". [#9544] */ if (ownedLock != null) { lockManager.release(ownedLock, this); ownedLock = null; } if (ownedLockSet != null) { Iterator iter = ownedLockSet.iterator(); while (iter.hasNext()) { Lock l = (Lock) iter.next(); lockManager.release(l, this); } /* Now clear lock collection. */ ownedLockSet.clear(); } /* Unload delete info, but don't wake up the compressor. */ synchronized (this) { if ((deleteInfo != null) && (deleteInfo.size() > 0)) { envImpl.addToCompressorQueue(deleteInfo.values(), false); // no wakeup deleteInfo.clear(); } } } /** * Transfer any MapLN locks to the db handle. */ public void setHandleLockOwner(boolean ignore /*operationOK*/, Database dbHandle, boolean dbIsClosing) throws DatabaseException { if (dbHandle != null) { if (!dbIsClosing) { transferHandleLockToHandle(dbHandle); } unregisterHandle(dbHandle); } } /** * This txn doesn't store cursors. */ public void registerCursor(CursorImpl cursor) throws DatabaseException { } /** * This txn doesn't store cursors. */ public void unRegisterCursor(CursorImpl cursor) throws DatabaseException { } /* * Transactional methods are all no-oped. */ /** * @return the abort LSN for this node. */ public long getAbortLsn(long nodeId) throws DatabaseException { return DbLsn.NULL_LSN; } /** * @return a dummy WriteLockInfo for this node. */ public WriteLockInfo getWriteLockInfo(long nodeId) throws DatabaseException { return WriteLockInfo.basicWriteLockInfo; } public void markDeleteAtTxnEnd(DatabaseImpl db, boolean deleteAtCommit) throws DatabaseException { if (deleteAtCommit) { db.deleteAndReleaseINs(); } } /** * Add a lock to set owned by this transaction. */ void addLock(Long nodeId, Lock lock, LockType type, LockGrantType grantStatus) throws DatabaseException { if (ownedLock == lock || (ownedLockSet != null && ownedLockSet.contains(lock))) { return; // Already owned } if (ownedLock == null) { ownedLock = lock; } else { if (ownedLockSet == null) { ownedLockSet = new HashSet(); } ownedLockSet.add(lock); } } /** * Remove a lock from the set owned by this txn. */ void removeLock(long nodeId, Lock lock) throws DatabaseException { if (lock == ownedLock) { ownedLock = null; } else if (ownedLockSet != null) { ownedLockSet.remove(lock); } } /** * Always false for this txn. */ public boolean createdNode(long nodeId) throws DatabaseException { return false; } /** * A lock is being demoted. Move it from the write collection into the read * collection. */ void moveWriteToReadLock(long nodeId, Lock lock) { } /** * stats */ public LockStats collectStats(LockStats stats) throws DatabaseException { if (ownedLock != null) { if (ownedLock.isOwnedWriteLock(this)) { stats.setNWriteLocks(stats.getNWriteLocks() + 1); } else { stats.setNReadLocks(stats.getNReadLocks() + 1); } } if (ownedLockSet != null) { Iterator iter = ownedLockSet.iterator(); while (iter.hasNext()) { Lock l = (Lock) iter.next(); if (l.isOwnedWriteLock(this)) { stats.setNWriteLocks(stats.getNWriteLocks() + 1); } else { stats.setNReadLocks(stats.getNReadLocks() + 1); } } } return stats; } }
gpl-3.0
gorkinovich/Icarus
src/icaro/aplicaciones/recursos/visualizacionAcceso/imp/swing/LimitadorCampoDigitos.java
687
package icaro.aplicaciones.recursos.visualizacionAcceso.imp.swing; import javax.swing.JTextField; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; @SuppressWarnings("serial") public class LimitadorCampoDigitos extends LimitadorCampoTexto { public LimitadorCampoDigitos(JTextField componenteTexto, int numeroMaximoCaracteres){ super(componenteTexto, numeroMaximoCaracteres); } public void insertString(int arg0, String arg1, AttributeSet arg2) throws BadLocationException { try{ Integer.parseInt(arg1); } catch (NumberFormatException e){ // El caracter no era un numero return; } super.insertString(arg0, arg1, arg2); } }
gpl-3.0
dk021212/weiciyuan
src/org/qii/weiciyuan/ui/basefragment/AbstractTimeLineFragment.java
27160
package org.qii.weiciyuan.ui.basefragment; import org.qii.weiciyuan.R; import org.qii.weiciyuan.bean.ItemBean; import org.qii.weiciyuan.bean.ListBean; import org.qii.weiciyuan.bean.android.AsyncTaskLoaderResult; import org.qii.weiciyuan.support.asyncdrawable.TimeLineBitmapDownloader; import org.qii.weiciyuan.support.error.WeiboException; import org.qii.weiciyuan.support.lib.ListViewMiddleMsgLoadingView; import org.qii.weiciyuan.support.lib.LongClickableLinkMovementMethod; import org.qii.weiciyuan.support.lib.TopTipBar; import org.qii.weiciyuan.support.lib.VelocityListView; import org.qii.weiciyuan.support.lib.pulltorefresh.PullToRefreshBase; import org.qii.weiciyuan.support.lib.pulltorefresh.PullToRefreshListView; import org.qii.weiciyuan.support.lib.pulltorefresh.extras.SoundPullEventListener; import org.qii.weiciyuan.support.settinghelper.SettingUtility; import org.qii.weiciyuan.support.utils.BundleArgsConstants; import org.qii.weiciyuan.support.utils.Utility; import org.qii.weiciyuan.ui.adapter.AbstractAppListAdapter; import org.qii.weiciyuan.ui.interfaces.AbstractAppFragment; import org.qii.weiciyuan.ui.loader.AbstractAsyncNetRequestTaskLoader; import org.qii.weiciyuan.ui.loader.DummyLoader; import android.os.Bundle; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; import android.view.ActionMode; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; /** * User: qii * Date: 12-8-27 * weiciyuan has two kinds of methods to send/receive network request/response asynchronously, * one is setRetainInstance(true) + AsyncTask, the other is AsyncTaskLoader * Because nested fragment(parent fragment has a viewpager, viewpager has many children fragments, * these children fragments are called nested fragment) can't use setRetainInstance(true), at this * moment * you have to use AsyncTaskLoader to solve Android configuration change(for example: change screen * orientation, * change system language) */ public abstract class AbstractTimeLineFragment<T extends ListBean> extends AbstractAppFragment { protected PullToRefreshListView pullToRefreshListView; protected TextView empty; protected ProgressBar progressBar; protected TopTipBar newMsgTipBar; protected BaseAdapter timeLineAdapter; protected View footerView; protected static final int DB_CACHE_LOADER_ID = 0; protected static final int NEW_MSG_LOADER_ID = 1; protected static final int MIDDLE_MSG_LOADER_ID = 2; protected static final int OLD_MSG_LOADER_ID = 3; protected ActionMode mActionMode; protected int savedCurrentLoadingMsgViewPositon = NO_SAVED_CURRENT_LOADING_MSG_VIEW_POSITION; public static final int NO_SAVED_CURRENT_LOADING_MSG_VIEW_POSITION = -1; public abstract T getList(); private int listViewScrollState = -1; private boolean canLoadOldData = true; public int getListViewScrollState() { return listViewScrollState; } public PullToRefreshListView getPullToRefreshListView() { return pullToRefreshListView; } public ListView getListView() { return pullToRefreshListView.getRefreshableView(); } public BaseAdapter getAdapter() { return timeLineAdapter; } public TopTipBar getNewMsgTipBar() { return newMsgTipBar; } protected void refreshLayout(T bean) { if (bean != null && bean.getSize() > 0) { // empty.setVisibility(View.INVISIBLE); progressBar.setVisibility(View.INVISIBLE); // listView.setVisibility(View.VISIBLE); } else if (bean == null || bean.getSize() == 0) { // empty.setVisibility(View.VISIBLE); progressBar.setVisibility(View.INVISIBLE); // listView.setVisibility(View.VISIBLE); } else if (bean.getSize() == bean.getTotal_number()) { // empty.setVisibility(View.INVISIBLE); progressBar.setVisibility(View.INVISIBLE); // listView.setVisibility(View.VISIBLE); } } protected abstract void listViewItemClick(AdapterView parent, View view, int position, long id); public void loadNewMsg() { canLoadOldData = true; getLoaderManager().destroyLoader(MIDDLE_MSG_LOADER_ID); getLoaderManager().destroyLoader(OLD_MSG_LOADER_ID); dismissFooterView(); getLoaderManager().restartLoader(NEW_MSG_LOADER_ID, null, msgCallback); } protected void loadOldMsg(View view) { if (getLoaderManager().getLoader(OLD_MSG_LOADER_ID) != null || !canLoadOldData) { return; } getLoaderManager().destroyLoader(NEW_MSG_LOADER_ID); getPullToRefreshListView().onRefreshComplete(); getLoaderManager().destroyLoader(MIDDLE_MSG_LOADER_ID); getLoaderManager().restartLoader(OLD_MSG_LOADER_ID, null, msgCallback); } public void loadMiddleMsg(String beginId, String endId, int position) { getLoaderManager().destroyLoader(NEW_MSG_LOADER_ID); getLoaderManager().destroyLoader(OLD_MSG_LOADER_ID); getPullToRefreshListView().onRefreshComplete(); dismissFooterView(); Bundle bundle = new Bundle(); bundle.putString("beginId", beginId); bundle.putString("endId", endId); bundle.putInt("position", position); VelocityListView velocityListView = (VelocityListView) getListView(); bundle.putBoolean("towardsBottom", velocityListView.getTowardsOrientation() == VelocityListView.TOWARDS_BOTTOM); getLoaderManager().restartLoader(MIDDLE_MSG_LOADER_ID, bundle, msgCallback); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt("savedCurrentLoadingMsgViewPositon", savedCurrentLoadingMsgViewPositon); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.listview_layout, container, false); buildLayout(inflater, view); return view; } protected void buildLayout(LayoutInflater inflater, View view) { empty = (TextView) view.findViewById(R.id.empty); progressBar = (ProgressBar) view.findViewById(R.id.progressbar); progressBar.setVisibility(View.GONE); pullToRefreshListView = (PullToRefreshListView) view.findViewById(R.id.listView); newMsgTipBar = (TopTipBar) view.findViewById(R.id.tv_unread_new_message_count_tip_bar); getListView().setHeaderDividersEnabled(false); getListView().setScrollingCacheEnabled(false); footerView = inflater.inflate(R.layout.listview_footer_layout, null); getListView().addFooterView(footerView); dismissFooterView(); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); pullToRefreshListView.setOnRefreshListener(listViewOnRefreshListener); pullToRefreshListView.setOnLastItemVisibleListener(listViewOnLastItemVisibleListener); pullToRefreshListView.setOnScrollListener(listViewOnScrollListener); pullToRefreshListView.setOnItemClickListener(listViewOnItemClickListener); pullToRefreshListView.setOnPullEventListener(getPullEventListener()); buildListAdapter(); if (savedInstanceState != null) { savedCurrentLoadingMsgViewPositon = savedInstanceState .getInt("savedCurrentLoadingMsgViewPositon", NO_SAVED_CURRENT_LOADING_MSG_VIEW_POSITION); } if (savedCurrentLoadingMsgViewPositon != NO_SAVED_CURRENT_LOADING_MSG_VIEW_POSITION && timeLineAdapter instanceof AbstractAppListAdapter) { ((AbstractAppListAdapter) timeLineAdapter) .setSavedMiddleLoadingViewPosition(savedCurrentLoadingMsgViewPositon); } } private PullToRefreshBase.OnLastItemVisibleListener listViewOnLastItemVisibleListener = new PullToRefreshBase.OnLastItemVisibleListener() { @Override public void onLastItemVisible() { if (getActivity() == null) { return; } if (getLoaderManager().getLoader(OLD_MSG_LOADER_ID) != null) { return; } loadOldMsg(null); } }; private PullToRefreshBase.OnRefreshListener<ListView> listViewOnRefreshListener = new PullToRefreshBase.OnRefreshListener<ListView>() { @Override public void onRefresh(PullToRefreshBase<ListView> refreshView) { if (getActivity() == null) { return; } if (getLoaderManager().getLoader(NEW_MSG_LOADER_ID) != null) { return; } loadNewMsg(); } }; private SoundPullEventListener<ListView> getPullEventListener() { SoundPullEventListener<ListView> listener = new SoundPullEventListener<ListView>( getActivity()); if (SettingUtility.getEnableSound()) { listener.addSoundEvent(PullToRefreshBase.State.RELEASE_TO_REFRESH, R.raw.psst1); // listener.addSoundEvent(PullToRefreshBase.State.GIVE_UP, R.raw.psst2); listener.addSoundEvent(PullToRefreshBase.State.RESET, R.raw.pop); } return listener; } private AdapterView.OnItemClickListener listViewOnItemClickListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (resetActionMode()) { return; } getListView().clearChoices(); int headerViewsCount = getListView().getHeaderViewsCount(); if (isPositionBetweenHeaderViewAndFooterView(position)) { int indexInDataSource = position - headerViewsCount; ItemBean msg = getList().getItem(indexInDataSource); if (!isNullFlag(msg)) { listViewItemClick(parent, view, indexInDataSource, id); } else { String beginId = getList().getItem(indexInDataSource + 1).getId(); String endId = getList().getItem(indexInDataSource - 1).getId(); ListViewMiddleMsgLoadingView loadingView = (ListViewMiddleMsgLoadingView) view; if (!((ListViewMiddleMsgLoadingView) view).isLoading() && savedCurrentLoadingMsgViewPositon == NO_SAVED_CURRENT_LOADING_MSG_VIEW_POSITION) { loadingView.load(); loadMiddleMsg(beginId, endId, indexInDataSource); savedCurrentLoadingMsgViewPositon = indexInDataSource + headerViewsCount; if (timeLineAdapter instanceof AbstractAppListAdapter) { ((AbstractAppListAdapter) timeLineAdapter) .setSavedMiddleLoadingViewPosition( savedCurrentLoadingMsgViewPositon); } } } } else if (isLastItem(position)) { loadOldMsg(view); } } boolean isPositionBetweenHeaderViewAndFooterView(int position) { return position - getListView().getHeaderViewsCount() < getList().getSize() && position - getListView().getHeaderViewsCount() >= 0; } boolean resetActionMode() { if (mActionMode != null) { getListView().clearChoices(); mActionMode.finish(); mActionMode = null; return true; } else { return false; } } boolean isNullFlag(ItemBean msg) { return msg == null; } boolean isLastItem(int position) { return position - 1 >= getList().getSize(); } }; private AbsListView.OnScrollListener listViewOnScrollListener = new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { listViewScrollState = scrollState; switch (scrollState) { case AbsListView.OnScrollListener.SCROLL_STATE_IDLE: if (!enableRefreshTime) { enableRefreshTime = true; getAdapter().notifyDataSetChanged(); } onListViewScrollStop(); LongClickableLinkMovementMethod.getInstance().setLongClickable(true); TimeLineBitmapDownloader.getInstance().setPauseDownloadWork(false); TimeLineBitmapDownloader.getInstance().setPauseReadWork(false); break; case AbsListView.OnScrollListener.SCROLL_STATE_FLING: enableRefreshTime = false; LongClickableLinkMovementMethod.getInstance().setLongClickable(false); TimeLineBitmapDownloader.getInstance().setPauseDownloadWork(true); TimeLineBitmapDownloader.getInstance().setPauseReadWork(true); onListViewScrollStateFling(); break; case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL: enableRefreshTime = true; LongClickableLinkMovementMethod.getInstance().setLongClickable(false); TimeLineBitmapDownloader.getInstance().setPauseDownloadWork(true); onListViewScrollStateTouchScroll(); break; } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { onListViewScroll(); } }; @Override public void onPause() { super.onPause(); TimeLineBitmapDownloader.getInstance().setPauseDownloadWork(false); TimeLineBitmapDownloader.getInstance().setPauseReadWork(false); } protected void onListViewScrollStop() { } protected void onListViewScrollStateTouchScroll() { } protected void onListViewScrollStateFling() { } protected void onListViewScroll() { if (hasActionMode()) { int position = getListView().getCheckedItemPosition(); if (getListView().getFirstVisiblePosition() > position || getListView().getLastVisiblePosition() < position) { clearActionMode(); } } if (allowLoadOldMsgBeforeReachListBottom() && getListView().getLastVisiblePosition() > 7 && getListView().getLastVisiblePosition() > getList().getSize() - 3 && getListView().getFirstVisiblePosition() != getListView().getHeaderViewsCount()) { loadOldMsg(null); } } protected boolean allowLoadOldMsgBeforeReachListBottom() { return true; } protected void showFooterView() { View view = footerView.findViewById(R.id.loading_progressbar); view.setVisibility(View.VISIBLE); view.setScaleX(1.0f); view.setScaleY(1.0f); view.setAlpha(1.0f); footerView.findViewById(R.id.laod_failed).setVisibility(View.GONE); } protected void dismissFooterView() { final View progressbar = footerView.findViewById(R.id.loading_progressbar); progressbar.animate().scaleX(0).scaleY(0).alpha(0.5f).setDuration(300) .withEndAction(new Runnable() { @Override public void run() { progressbar.setVisibility(View.GONE); } }); footerView.findViewById(R.id.laod_failed).setVisibility(View.GONE); } protected void showErrorFooterView() { View view = footerView.findViewById(R.id.loading_progressbar); view.setVisibility(View.GONE); TextView tv = ((TextView) footerView.findViewById(R.id.laod_failed)); tv.setVisibility(View.VISIBLE); } public void clearActionMode() { if (mActionMode != null) { mActionMode.finish(); mActionMode = null; } if (pullToRefreshListView != null && getListView().getCheckedItemCount() > 0) { getListView().clearChoices(); if (getAdapter() != null) { getAdapter().notifyDataSetChanged(); } } } public boolean clearActionModeIfOpen() { boolean flag = false; if (mActionMode != null) { mActionMode.finish(); mActionMode = null; flag = true; } if (pullToRefreshListView != null && getListView().getCheckedItemCount() > 0) { getListView().clearChoices(); if (getAdapter() != null) { getAdapter().notifyDataSetChanged(); } } return flag; } protected abstract void buildListAdapter(); protected boolean allowRefresh() { boolean isNewMsgLoaderLoading = getLoaderManager().getLoader(NEW_MSG_LOADER_ID) != null; return getPullToRefreshListView().getVisibility() == View.VISIBLE && !isNewMsgLoaderLoading; } @Override public void onResume() { super.onResume(); getListView().setFastScrollEnabled(SettingUtility.allowFastScroll()); getAdapter().notifyDataSetChanged(); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Loader<T> loader = getLoaderManager().getLoader(NEW_MSG_LOADER_ID); if (loader != null) { getLoaderManager().initLoader(NEW_MSG_LOADER_ID, null, msgCallback); } loader = getLoaderManager().getLoader(MIDDLE_MSG_LOADER_ID); if (loader != null) { getLoaderManager().initLoader(MIDDLE_MSG_LOADER_ID, null, msgCallback); } loader = getLoaderManager().getLoader(OLD_MSG_LOADER_ID); if (loader != null) { getLoaderManager().initLoader(OLD_MSG_LOADER_ID, null, msgCallback); } } public void setmActionMode(ActionMode mActionMode) { this.mActionMode = mActionMode; } public boolean hasActionMode() { return mActionMode != null; } protected abstract void newMsgOnPostExecute(T newValue, Bundle loaderArgs); protected abstract void oldMsgOnPostExecute(T newValue); protected void middleMsgOnPostExecute(int position, T newValue, boolean towardsBottom) { if (newValue == null) { return; } if (newValue.getSize() == 0 || newValue.getSize() == 1) { getList().getItemList().remove(position); getAdapter().notifyDataSetChanged(); return; } ItemBean lastItem = newValue.getItem(newValue.getSize() - 1); // if (!lastItem.getId().equals(endTag)) { // getList().getItemList().addAll(position, newValue.getItemList().subList(1, newValue.getSize())); // getAdapter().notifyDataSetChanged(); // return; // } // // if (lastItem.getId().equals(endTag)) { // int nullIndex = position + newValue.getSize() - 1; // getList().getItemList().addAll(position, newValue.getItemList().subList(1, newValue.getSize())); // getList().getItemList().remove(nullIndex - 1); // getList().getItemList().remove(nullIndex - 1); // getAdapter().notifyDataSetChanged(); // return; // } } protected void showListView() { progressBar.setVisibility(View.INVISIBLE); } private volatile boolean enableRefreshTime = true; public boolean isListViewFling() { return !enableRefreshTime; } private Loader<AsyncTaskLoaderResult<T>> createNewMsgLoader(int id, Bundle args) { Loader<AsyncTaskLoaderResult<T>> loader = onCreateNewMsgLoader(id, args); if (loader == null) { loader = new DummyLoader<T>(getActivity()); } if (loader instanceof AbstractAsyncNetRequestTaskLoader) { ((AbstractAsyncNetRequestTaskLoader) loader).setArgs(args); } return loader; } private Loader<AsyncTaskLoaderResult<T>> createMiddleMsgLoader(int id, Bundle args, String middleBeginId, String middleEndId, String middleEndTag, int middlePosition) { Loader<AsyncTaskLoaderResult<T>> loader = onCreateMiddleMsgLoader(id, args, middleBeginId, middleEndId, middleEndTag, middlePosition); if (loader == null) { loader = new DummyLoader<T>(getActivity()); } return loader; } private Loader<AsyncTaskLoaderResult<T>> createOldMsgLoader(int id, Bundle args) { Loader<AsyncTaskLoaderResult<T>> loader = onCreateOldMsgLoader(id, args); if (loader == null) { loader = new DummyLoader<T>(getActivity()); } return loader; } protected Loader<AsyncTaskLoaderResult<T>> onCreateNewMsgLoader(int id, Bundle args) { return null; } protected Loader<AsyncTaskLoaderResult<T>> onCreateMiddleMsgLoader(int id, Bundle args, String middleBeginId, String middleEndId, String middleEndTag, int middlePosition) { return null; } protected Loader<AsyncTaskLoaderResult<T>> onCreateOldMsgLoader(int id, Bundle args) { return null; } protected LoaderManager.LoaderCallbacks<AsyncTaskLoaderResult<T>> msgCallback = new LoaderManager.LoaderCallbacks<AsyncTaskLoaderResult<T>>() { private String middleBeginId = ""; private String middleEndId = ""; private int middlePosition = -1; private boolean towardsBottom = false; @Override public Loader<AsyncTaskLoaderResult<T>> onCreateLoader(int id, Bundle args) { clearActionMode(); showListView(); switch (id) { case NEW_MSG_LOADER_ID: if (args == null || args.getBoolean(BundleArgsConstants.SCROLL_TO_TOP)) { Utility.stopListViewScrollingAndScrollToTop(getListView()); } return createNewMsgLoader(id, args); case MIDDLE_MSG_LOADER_ID: middleBeginId = args.getString("beginId"); middleEndId = args.getString("endId"); middlePosition = args.getInt("position"); towardsBottom = args.getBoolean("towardsBottom"); return createMiddleMsgLoader(id, args, middleBeginId, middleEndId, null, middlePosition); case OLD_MSG_LOADER_ID: showFooterView(); return createOldMsgLoader(id, args); } return null; } @Override public void onLoadFinished(Loader<AsyncTaskLoaderResult<T>> loader, AsyncTaskLoaderResult<T> result) { T data = result != null ? result.data : null; WeiboException exception = result != null ? result.exception : null; Bundle args = result != null ? result.args : null; switch (loader.getId()) { case NEW_MSG_LOADER_ID: getPullToRefreshListView().onRefreshComplete(); refreshLayout(getList()); if (Utility.isAllNotNull(exception)) { newMsgTipBar.setError(exception.getError()); newMsgOnPostExecuteError(exception); } else { newMsgOnPostExecute(data, args); } break; case MIDDLE_MSG_LOADER_ID: if (exception != null) { View view = Utility.getListViewItemViewFromPosition(getListView(), savedCurrentLoadingMsgViewPositon); ListViewMiddleMsgLoadingView loadingView = (ListViewMiddleMsgLoadingView) view; if (loadingView != null) { loadingView.setErrorMessage(exception.getError()); } } else { middleMsgOnPostExecute(middlePosition, data, towardsBottom); // getAdapter().notifyDataSetChanged(); } savedCurrentLoadingMsgViewPositon = NO_SAVED_CURRENT_LOADING_MSG_VIEW_POSITION; if (timeLineAdapter instanceof AbstractAppListAdapter) { ((AbstractAppListAdapter) timeLineAdapter) .setSavedMiddleLoadingViewPosition( savedCurrentLoadingMsgViewPositon); } break; case OLD_MSG_LOADER_ID: refreshLayout(getList()); if (exception != null) { showErrorFooterView(); } else if (data != null) { canLoadOldData = data.getSize() > 1; oldMsgOnPostExecute(data); getAdapter().notifyDataSetChanged(); dismissFooterView(); } else { canLoadOldData = false; dismissFooterView(); } break; } getLoaderManager().destroyLoader(loader.getId()); } @Override public void onLoaderReset(Loader<AsyncTaskLoaderResult<T>> loader) { } }; protected void newMsgOnPostExecuteError(WeiboException exception) { } }
gpl-3.0
sujitkjha/360-Video-Player-for-Android
rajawali/src/main/java/org/rajawali3d/BufferInfo.java
1473
/** * Copyright 2013 Dennis Ippel * * 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.rajawali3d; import java.nio.Buffer; import android.opengl.GLES20; import org.rajawali3d.Geometry3D.BufferType; public class BufferInfo { public int bufferHandle = -1; public BufferType bufferType; public Buffer buffer; public int target; public int byteSize; public int usage; public int stride = 0; public int offset = 0; public int type = GLES20.GL_FLOAT; public BufferInfo() { this.usage = GLES20.GL_STATIC_DRAW; } public BufferInfo(BufferType bufferType, Buffer buffer) { this.bufferType = bufferType; this.buffer = buffer; } public String toString() { StringBuffer sb = new StringBuffer(); sb .append("Handle: ").append(bufferHandle) .append(" type: ").append(bufferType) .append(" target: ").append(target) .append(" byteSize: ").append(byteSize) .append(" usage: ").append(usage); return sb.toString(); } }
gpl-3.0
YinYanfei/CadalWorkspace
CadalRec/src/cn/cadal/rec/tryJava/TextSimilarity.java
9723
package cn.cadal.rec.tryJava; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; public class TextSimilarity { private String sourceFile = "E:/Recommendation/Dict/cbookInfo_bookno.dat"; private String destinFile = "E:/Recommendation/Dict/cbookInfo_bookno_score.dat"; // ´æ´¢¸ñʽ£º {1,['ÂÛÎÄ','¿××ÓÖø','ÈËÃñ½ÌÓý³ö°æÉç','¹Å¼®']}{...} public Map<Integer, String[]> hashBooknoInfo = null; // ÓÃÓÚ¼ÆËãËæ»úµÄÁ½¸öitem֮ǰµÄÎı¾ÏàËÆ¶È // ´æ´¢¸ñʽ£º ['1','ÂÛÎÄ','¿××ÓÖø','ÈËÃñ½ÌÓý³ö°æÉç','¹Å¼®'][...] public List<String[]> listBooknoInfo = null; // ÓÃÓÚÈ«¾Ö¼ÆËãËùÓÐitem֮ǰµÄÎı¾ÏàËÆ¶È /** * Construct function */ public TextSimilarity(){ } public TextSimilarity(String sourceFile, String destinFile){ this.sourceFile = sourceFile; this.destinFile = destinFile; } /** * Read sourceFile and store into this.hashBooknoInfo * * !! using this.hashBooknoInfo, please run this function behead */ public void ReadIntoHashBooknoInfo() { this.hashBooknoInfo = new HashMap<Integer, String[]>(); File file = new File(this.sourceFile); BufferedReader reader = null; try{ reader = new BufferedReader(new FileReader(file)); String line = null; while((line = reader.readLine()) != null) { Integer bookno = null; String []info = new String[4]; String []lineSplit = line.split("####"); bookno = Integer.valueOf(lineSplit[0].trim()); info[0] = lineSplit[1]; info[1] = lineSplit[2]; info[2] = lineSplit[3]; info[3] = lineSplit[5]; this.hashBooknoInfo.put(bookno, info); } reader.close(); }catch(Exception e){ e.printStackTrace(); }finally{ try{ if(reader != null) { reader.close(); } }catch(Exception e){ e.printStackTrace(); } } } /** * Read sourceFile and store into this.listBooknoInfo * * !! using this.listBooknoInfo, please run this function behead */ public void ReadIntoListBooknoInfo(){ this.listBooknoInfo = new ArrayList<String[]>(); File file = new File(this.sourceFile); BufferedReader reader = null; try{ reader = new BufferedReader(new FileReader(file)); String line = null; while((line = reader.readLine()) != null) { String []info = new String[5]; String []lineSplit = line.split("####"); info[0] = lineSplit[0].trim(); info[1] = lineSplit[1]; info[2] = lineSplit[2]; info[3] = lineSplit[3]; info[4] = lineSplit[5]; this.listBooknoInfo.add(info); } reader.close(); }catch(Exception e){ e.printStackTrace(); }finally{ try{ if(reader != null) { reader.close(); } }catch(Exception e){ e.printStackTrace(); } } } /** * Calculate the cosine similarity of two document * * @param * doc1 String type * @param * doc2 String type * @return * The cosine similar for doc1 and doc2 */ public double Similarity(String doc1, String doc2) { if (doc1 != null && doc1.trim().length() > 0 && doc2 != null && doc2.trim().length() > 0) { Map<Integer, int[]> AlgorithmMap = new HashMap<Integer, int[]>(); //calculate the number of word for different documents for (int i = 0; i < doc1.length(); i++) { char d1 = doc1.charAt(i); if(isHanZi(d1)){ int charIndex = getGB2312Id(d1); if(charIndex != -1){ int[] fq = AlgorithmMap.get(charIndex); if(fq != null && fq.length == 2){ fq[0]++; }else { fq = new int[2]; fq[0] = 1; fq[1] = 0; AlgorithmMap.put(charIndex, fq); } } }else{ if (!Character.isSpaceChar(d1)) { int[] fq = AlgorithmMap.get(Integer.valueOf(d1)); if (fq != null && fq.length == 2) { fq[0]++; } else { fq = new int[2]; fq[0] = 1; fq[1] = 0; AlgorithmMap.put(Integer.valueOf(d1), fq); } } } } for (int i = 0; i < doc2.length(); i++) { char d2 = doc2.charAt(i); if(isHanZi(d2)){ int charIndex = getGB2312Id(d2); if(charIndex != -1){ int[] fq = AlgorithmMap.get(charIndex); if(fq != null && fq.length == 2){ fq[1]++; }else { fq = new int[2]; fq[0] = 0; fq[1] = 1; AlgorithmMap.put(charIndex, fq); } } }else{ if (!Character.isSpaceChar(d2)) { int[] fq = AlgorithmMap.get(Integer.valueOf(d2)); if (fq != null && fq.length == 2) { fq[1]++; } else { fq = new int[2]; fq[0] = 0; fq[1] = 1; AlgorithmMap.put(Integer.valueOf(d2), fq); } } } } // iterator hash-map to calculate cosine similar Iterator<Integer> iterator = AlgorithmMap.keySet().iterator(); double sqdoc1 = 0; double sqdoc2 = 0; double denominator = 0; while(iterator.hasNext()){ int[] c = AlgorithmMap.get(iterator.next()); denominator += c[0]*c[1]; sqdoc1 += c[0]*c[0]; sqdoc2 += c[1]*c[1]; } return denominator / Math.sqrt(sqdoc1*sqdoc2); } else { return 0.0; } } /** * Chinese or not * * @param ch * Chinese word * @return * true or false */ public static boolean isHanZi(char ch) { return (ch >= 0x4E00 && ch <= 0x9FA5); } /** * To get code of GB2312 or ASCII * * @param ch * Chinese of GB2312 or ASCII(#128) * @return * The place of ch in code GB2312,-1 for unidentification */ public static short getGB2312Id(char ch) { try { byte[] buffer = Character.toString(ch).getBytes("GB2312"); if (buffer.length != 2) { return -1; // Õý³£Çé¿öÏÂbufferÓ¦¸ÃÊÇÁ½¸ö×Ö½Ú£¬·ñÔò˵Ã÷ch²»ÊôÓÚGB2312±àÂ룬¹Ê·µ»Ø'?'£¬´Ëʱ˵Ã÷²»ÈÏʶ¸Ã×Ö·û } int b0 = (int) (buffer[0] & 0x0FF) - 161; // ±àÂë´ÓA1¿ªÊ¼£¬Òò´Ë¼õÈ¥0xA1=161 int b1 = (int) (buffer[1] & 0x0FF) - 161; // µÚÒ»¸ö×Ö·ûºÍ×îºóÒ»¸ö×Ö·ûûÓкº×Ö£¬Òò´Ëÿ¸öÇøÖ»ÊÕ16*6-2=94¸öºº×Ö return (short) (b0 * 94 + b1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return -1; } /** * To calculate similarity between shuffle two book-no, such as (17951,9822) * * @param bookno1 * Book-no, such as 17951 * @param bookno2 * Book-no, such as 9822 * @return * score of two book */ public double CalSimilarityTextDistance(int bookno1, int bookno2){ try{ String []bookInfo1 = this.hashBooknoInfo.get(Integer.valueOf(bookno1)); String []bookInfo2 = this.hashBooknoInfo.get(Integer.valueOf(bookno2)); double similarity = this.Similarity(bookInfo1[0], bookInfo2[0]) * 0.6 + this.Similarity(bookInfo1[1], bookInfo2[1]) * 0.1 + this.Similarity(bookInfo1[2], bookInfo2[2]) * 0.1 + this.Similarity(bookInfo1[3], bookInfo2[3]) * 0.2; return similarity; }catch(Exception e){ e.printStackTrace(); return 0.0; } } /** * To calculate each book-no, using this.listBooknoInfo, * and the result will write into this.destinFile if the score is lager than 0.0. * destinFile store type: 1 235 0.7145 823 0.0981 ...->[(1,235,0.7145),(1,823,0.0981),...] * * @return * true or false for finish or not */ public boolean CalSimilarityTextDistance(){ FileWriter writer = null; try{ writer = new FileWriter(this.destinFile, true); int count = 1; double score = 0.0; for(int outerIndx = 0; outerIndx < this.listBooknoInfo.size(); ++outerIndx) { System.out.println(count++); String []outerStr = this.listBooknoInfo.get(outerIndx); writer.write(outerStr[0] + " "); for(int innerIndx = outerIndx + 1; innerIndx < this.listBooknoInfo.size(); ++innerIndx) { String []innerStr = this.listBooknoInfo.get(innerIndx); score = this.Similarity(outerStr[1], innerStr[1]) * 0.6 + this.Similarity(outerStr[2], innerStr[2]) * 0.1 + this.Similarity(outerStr[3], innerStr[3]) * 0.1 + this.Similarity(outerStr[4], innerStr[4]) * 0.2; if(score >= 0.0) { writer.write(innerStr[0] + " " + String.valueOf(score) + " "); } } writer.write("\n"); } writer.close(); return true; }catch(Exception e){ e.printStackTrace(); return false; }finally{ try{ if(writer != null) writer.close(); }catch(Exception e){ e.printStackTrace(); } } } /** * @param args */ public static void main(String[] args) { TextSimilarity csa = new TextSimilarity(); // String doc1 = "ÖйúÈËgoogle"; // String doc2 = "ÖйúÈËgood"; // System.out.println(csa.Similarity(doc1, doc2)); // csa.ReadIntoHashBooknoInfo(); csa.ReadIntoListBooknoInfo(); // System.out.println(csa.CalSimilarityTextDistance(310636, 310637)); // System.out.println(csa.CalSimilarityTextDistance(310638, 124572)); // System.out.println(csa.CalSimilarityTextDistance(310639, 310640)); csa.CalSimilarityTextDistance(); } /** * Getters and Setters */ public String getSourceFile() { return sourceFile; } public String getDestinFile() { return destinFile; } public void setSourceFile(String sourceFile) { this.sourceFile = sourceFile; } public void setDestinFile(String destinFile) { this.destinFile = destinFile; } public Map<Integer, String[]> getHashBooknoInfo() { return hashBooknoInfo; } public List<String[]> getListBooknoInfo() { return listBooknoInfo; } public void setHashBooknoInfo(Map<Integer, String[]> hashBooknoInfo) { this.hashBooknoInfo = hashBooknoInfo; } public void setListBooknoInfo(List<String[]> listBooknoInfo) { this.listBooknoInfo = listBooknoInfo; } }
gpl-3.0
tomtomtom09/CampCraft
build/tmp/recompileMc/sources/net/minecraft/client/resources/ResourcePackListEntryDefault.java
2942
package net.minecraft.client.resources; import com.google.gson.JsonParseException; import java.io.IOException; import net.minecraft.client.gui.GuiScreenResourcePacks; import net.minecraft.client.renderer.texture.DynamicTexture; import net.minecraft.client.renderer.texture.TextureUtil; import net.minecraft.client.resources.data.PackMetadataSection; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @SideOnly(Side.CLIENT) public class ResourcePackListEntryDefault extends ResourcePackListEntry { private static final Logger logger = LogManager.getLogger(); private final IResourcePack field_148320_d; private final ResourceLocation resourcePackIcon; public ResourcePackListEntryDefault(GuiScreenResourcePacks resourcePacksGUIIn) { super(resourcePacksGUIIn); this.field_148320_d = this.mc.getResourcePackRepository().rprDefaultResourcePack; DynamicTexture dynamictexture; try { dynamictexture = new DynamicTexture(this.field_148320_d.getPackImage()); } catch (IOException var4) { dynamictexture = TextureUtil.missingTexture; } this.resourcePackIcon = this.mc.getTextureManager().getDynamicTextureLocation("texturepackicon", dynamictexture); } protected int func_183019_a() { return 1; } protected String func_148311_a() { try { PackMetadataSection packmetadatasection = (PackMetadataSection)this.field_148320_d.getPackMetadata(this.mc.getResourcePackRepository().rprMetadataSerializer, "pack"); if (packmetadatasection != null) { return packmetadatasection.getPackDescription().getFormattedText(); } } catch (JsonParseException jsonparseexception) { logger.error((String)"Couldn\'t load metadata info", (Throwable)jsonparseexception); } catch (IOException ioexception) { logger.error((String)"Couldn\'t load metadata info", (Throwable)ioexception); } return EnumChatFormatting.RED + "Missing " + "pack.mcmeta" + " :("; } protected boolean func_148309_e() { return false; } protected boolean func_148308_f() { return false; } protected boolean func_148314_g() { return false; } protected boolean func_148307_h() { return false; } protected String func_148312_b() { return "Default"; } protected void func_148313_c() { this.mc.getTextureManager().bindTexture(this.resourcePackIcon); } protected boolean func_148310_d() { return false; } }
gpl-3.0
PrismTech/opensplice
src/api/dcps/java5/common/java/code/org/opensplice/dds/domain/DomainParticipantQos.java
2157
/* * Vortex OpenSplice * * This software and documentation are Copyright 2006 to TO_YEAR ADLINK * Technology Limited, its affiliated companies and licensors. 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.opensplice.dds.domain; import org.opensplice.dds.core.policy.Scheduling.ListenerScheduling; import org.opensplice.dds.core.policy.Scheduling.WatchdogScheduling; /** * OpenSplice-specific extension to * {@link org.omg.dds.domain.DomainParticipantQos} with support to control * scheduling class and priorities of listener and watchdog threads created by * the middleware. * * @see org.opensplice.dds.core.policy.Scheduling * @see org.opensplice.dds.core.policy.Scheduling.ListenerScheduling * @see org.opensplice.dds.core.policy.Scheduling.WatchdogScheduling */ public interface DomainParticipantQos extends org.omg.dds.domain.DomainParticipantQos { /** * Scheduling for the Listener thread of a * {@link org.omg.dds.domain.DomainParticipant} * * @return The scheduling for the Listener thread of a DomainParticipant. * * @see org.opensplice.dds.core.policy.Scheduling.ListenerScheduling */ public ListenerScheduling getListenerScheduling(); /** * Scheduling for the Watchdog thread of a * {@link org.omg.dds.domain.DomainParticipant} * * @return The scheduling for the Watchdog thread of a DomainParticipant. * * @see org.opensplice.dds.core.policy.Scheduling.WatchdogScheduling */ public WatchdogScheduling getWatchdogScheduling(); }
gpl-3.0
DraganovMartin/Bank-System
src/testClasses/communication_client_server/ExampleDisconnectNoticeHandler.java
1677
package testClasses.communication_client_server; import javax.swing.BoxLayout; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import networking.connections.Client; import networking.messages.DisconnectNotice; import networking.messages.Message; import networking.messages.Response; /** * * @author iliyan-kostov <https://github.com/iliyan-kostov/> */ public class ExampleDisconnectNoticeHandler extends networking.messageHandlers.clientside.ResponseHandler { public ExampleDisconnectNoticeHandler(Client client) { super(client); } @Override public Message handle(Message message) { try { // typecast the message into the handler-specific type: Response response = (DisconnectNotice) message; { // debugging part: JFrame frame = new JFrame("CLIENT"); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); String[] text = ("CLIENT received a message:\n" + message.toString()).split("\n"); for (int i = 0; i < text.length; i++) { panel.add(new JLabel(text[i])); } frame.add(panel); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.pack(); frame.setVisible(true); } { // process the response: not answering to a response: return null; } } catch (Exception ex) { return null; } } }
gpl-3.0
Quetzi/BluePower
src/main/java/net/quetzi/bluepower/blocks/machines/BlockTransposer.java
3095
/* * This file is part of Blue Power. * * Blue Power is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Blue Power is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Blue Power. If not, see <http://www.gnu.org/licenses/> * * @author Quetzi */ package net.quetzi.bluepower.blocks.machines; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; import net.quetzi.bluepower.blocks.BlockContainerBase; import net.quetzi.bluepower.references.GuiIDs; import net.quetzi.bluepower.references.Refs; import net.quetzi.bluepower.tileentities.tier1.TileTransposer; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class BlockTransposer extends BlockContainerBase { private IIcon textureFront; private IIcon textureSide; private IIcon textureSideActive; private IIcon textureBack; public BlockTransposer() { super(Material.rock); this.setBlockName(Refs.TRANSPOSER_NAME); } @Override protected Class<? extends TileEntity> getTileEntity() { return TileTransposer.class; } @Override public GuiIDs getGuiID() { return GuiIDs.INVALID; } @Override @SideOnly(Side.CLIENT) public IIcon getIcon(int side, int meta) { ForgeDirection direction = ForgeDirection.getOrientation(meta); if (side == direction.ordinal()) { return textureFront; } else if (side == direction.getOpposite().ordinal()) { return textureBack; } // if () { return textureSideActive; } TODO: Check if block is powered return blockIcon; } @Override @SideOnly(Side.CLIENT) public void registerBlockIcons(IIconRegister iconRegister) { this.textureFront = iconRegister.registerIcon(Refs.MODID + ":" + Refs.MACHINE_TEXTURE_LOCATION + Refs.TRANSPOSER_NAME + "_front"); this.textureBack = iconRegister.registerIcon(Refs.MODID + ":" + Refs.MACHINE_TEXTURE_LOCATION + Refs.TRANSPOSER_NAME + "_back"); this.textureSide = iconRegister.registerIcon(Refs.MODID + ":" + Refs.MACHINE_TEXTURE_LOCATION + Refs.TRANSPOSER_NAME + "_side_0"); this.textureSideActive = iconRegister.registerIcon(Refs.MODID + ":" + Refs.MACHINE_TEXTURE_LOCATION + Refs.TRANSPOSER_NAME + "_side_0_active"); this.blockIcon = iconRegister.registerIcon(Refs.MODID + ":" + Refs.MACHINE_TEXTURE_LOCATION + Refs.TRANSPOSER_NAME + "_side_0"); } }
gpl-3.0
tomtomtom09/CampCraft
build/tmp/recompileMc/sources/net/minecraft/item/ItemFood.java
4393
package net.minecraft.item; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.potion.PotionEffect; import net.minecraft.stats.StatList; import net.minecraft.world.World; public class ItemFood extends Item { /** Number of ticks to run while 'EnumAction'ing until result. */ public final int itemUseDuration; /** The amount this food item heals the player. */ private final int healAmount; private final float saturationModifier; /** Whether wolves like this food (true for raw and cooked porkchop). */ private final boolean isWolfsFavoriteMeat; /** If this field is true, the food can be consumed even if the player don't need to eat. */ private boolean alwaysEdible; /** represents the potion effect that will occurr upon eating this food. Set by setPotionEffect */ private int potionId; /** set by setPotionEffect */ private int potionDuration; /** set by setPotionEffect */ private int potionAmplifier; /** probably of the set potion effect occurring */ private float potionEffectProbability; public ItemFood(int amount, float saturation, boolean isWolfFood) { this.itemUseDuration = 32; this.healAmount = amount; this.isWolfsFavoriteMeat = isWolfFood; this.saturationModifier = saturation; this.setCreativeTab(CreativeTabs.tabFood); } public ItemFood(int amount, boolean isWolfFood) { this(amount, 0.6F, isWolfFood); } /** * Called when the player finishes using this Item (E.g. finishes eating.). Not called when the player stops using * the Item before the action is complete. */ public ItemStack onItemUseFinish(ItemStack stack, World worldIn, EntityPlayer playerIn) { --stack.stackSize; playerIn.getFoodStats().addStats(this, stack); worldIn.playSoundAtEntity(playerIn, "random.burp", 0.5F, worldIn.rand.nextFloat() * 0.1F + 0.9F); this.onFoodEaten(stack, worldIn, playerIn); playerIn.triggerAchievement(StatList.objectUseStats[Item.getIdFromItem(this)]); return stack; } protected void onFoodEaten(ItemStack stack, World worldIn, EntityPlayer player) { if (!worldIn.isRemote && this.potionId > 0 && worldIn.rand.nextFloat() < this.potionEffectProbability) { player.addPotionEffect(new PotionEffect(this.potionId, this.potionDuration * 20, this.potionAmplifier)); } } /** * How long it takes to use or consume an item */ public int getMaxItemUseDuration(ItemStack stack) { return 32; } /** * returns the action that specifies what animation to play when the items is being used */ public EnumAction getItemUseAction(ItemStack stack) { return EnumAction.EAT; } /** * Called whenever this item is equipped and the right mouse button is pressed. Args: itemStack, world, entityPlayer */ public ItemStack onItemRightClick(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn) { if (playerIn.canEat(this.alwaysEdible)) { playerIn.setItemInUse(itemStackIn, this.getMaxItemUseDuration(itemStackIn)); } return itemStackIn; } public int getHealAmount(ItemStack stack) { return this.healAmount; } public float getSaturationModifier(ItemStack stack) { return this.saturationModifier; } /** * Whether wolves like this food (true for raw and cooked porkchop). */ public boolean isWolfsFavoriteMeat() { return this.isWolfsFavoriteMeat; } /** * sets a potion effect on the item. Args: int potionId, int duration (will be multiplied by 20), int amplifier, * float probability of effect happening */ public ItemFood setPotionEffect(int id, int duration, int amplifier, float probability) { this.potionId = id; this.potionDuration = duration; this.potionAmplifier = amplifier; this.potionEffectProbability = probability; return this; } /** * Set the field 'alwaysEdible' to true, and make the food edible even if the player don't need to eat. */ public ItemFood setAlwaysEdible() { this.alwaysEdible = true; return this; } }
gpl-3.0
RobinJ1995/be.robinj.ubuntu
app/src/main/java/be/robinj/distrohopper/desktop/dash/lens/LocalFiles.java
2591
package be.robinj.distrohopper.desktop.dash.lens; import android.annotation.TargetApi; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.provider.MediaStore; import android.webkit.MimeTypeMap; import org.json.JSONException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import be.robinj.distrohopper.R; /** * Created by robin on 4/11/14. */ public class LocalFiles extends Lens { public LocalFiles (Context context) { super (context); this.icon = context.getResources ().getDrawable (R.drawable.dash_search_lens_localfiles); } public String getName () { return "Local files"; } public String getDescription () { return "Search results for files on your device"; } @Override public int getMinSDKVersion () { return 11; } @TargetApi (Build.VERSION_CODES.HONEYCOMB) public List<LensSearchResult> search (final String str, final int maxResults) throws IOException, JSONException { List<LensSearchResult> results = new ArrayList<LensSearchResult> (); int nResults = 0; String[] projection = new String[] { MediaStore.Files.FileColumns.DATA }; String selection = MediaStore.Files.FileColumns.TITLE + " LIKE '%" + str.replace ("'", "''") + "%'"; Cursor cursor = this.context.getContentResolver ().query (MediaStore.Files.getContentUri ("external"), projection, selection, null, null); while (cursor.moveToNext ()) { String path = cursor.getString (0); File file = new File (path); LensSearchResult result = new LensSearchResult (this.context, file.getName (), file.toString (), this.icon); results.add (result); if (++nResults >= maxResults) { break; } } return results; } @Override public void onClick (String url) { try { File file = new File (url); String extension = MimeTypeMap.getFileExtensionFromUrl (url); String mime = "*/*"; if (extension != null) { MimeTypeMap map = MimeTypeMap.getSingleton (); mime = map.getMimeTypeFromExtension (extension); } Intent intent = new Intent (); intent.setAction (Intent.ACTION_VIEW); intent.setDataAndType (Uri.parse (file.getPath()), mime); intent.setFlags (Intent.FLAG_ACTIVITY_NEW_TASK); this.context.startActivity (intent); } catch (ActivityNotFoundException ex) { this.showDialog ("It looks like you don't have any apps installed that can open this type of file.", false); } } }
gpl-3.0
Rwilmes/DNA
src/dna/metrics/connectivity/WCBasicU.java
4072
package dna.metrics.connectivity; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; import dna.graph.IElement; import dna.graph.edges.Edge; import dna.graph.nodes.Node; import dna.metrics.algorithms.IAfterBatch; import dna.metrics.algorithms.IAfterER; import dna.metrics.algorithms.IAfterNR; import dna.metrics.algorithms.IBeforeEA; import dna.metrics.algorithms.IBeforeNA; import dna.updates.batch.Batch; import dna.updates.update.EdgeAddition; import dna.updates.update.EdgeRemoval; import dna.updates.update.NodeAddition; import dna.updates.update.NodeRemoval; public class WCBasicU extends WCBasic implements IBeforeEA, IAfterER, IBeforeNA, IAfterNR, IAfterBatch { public WCBasicU() { super("WCBasicU"); } private HashMap<Node, WCComponent> mapping; @Override public boolean init() { if (!this.compute()) { return false; } this.mapping = new HashMap<Node, WCComponent>(); for (WCComponent c : this.components) { for (Node n : c.getNodes()) { this.mapping.put(n, c); } } return true; } @Override public boolean applyAfterUpdate(NodeRemoval nr) { Node n = (Node) nr.getNode(); WCComponent c = this.mapping.get(n); this.mapping.remove(n); c.removeNode(n); this.components.remove(c); if (c.size() > 0) { ArrayList<WCComponent> components = this.getComponents((Iterable) c .getNodes()); this.components.addAll(components); for (WCComponent c_ : components) { for (Node n_ : c_.getNodes()) { this.mapping.put(n_, c_); } } } return true; } @Override public boolean applyBeforeUpdate(NodeAddition na) { Node n = (Node) na.getNode(); WCComponent c = new WCComponent(n); this.components.add(c); this.mapping.put(n, c); return true; } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public boolean applyAfterUpdate(EdgeRemoval er) { Edge e = (Edge) er.getEdge(); Node n1 = e.getN1(); Node n2 = e.getN2(); WCComponent c = this.mapping.get(n1); // if edge is not in spanning tree: do noting if (!c.containsEdge(e)) { return true; } // split partitions otherwise this.components.remove(c); ArrayList<WCComponent> components = getComponents((Iterable) c .getNodes()); this.components.addAll(components); for (WCComponent c_ : components) { for (Node n_ : c_.getNodes()) { this.mapping.put(n_, c_); } } return true; } @Override public boolean applyBeforeUpdate(EdgeAddition ea) { Edge e = (Edge) ea.getEdge(); Node n1 = e.getN1(); Node n2 = e.getN2(); WCComponent c1 = this.mapping.get(n1); WCComponent c2 = this.mapping.get(n2); // do noting in case nodes are already in same component if (c1 == c2) { return true; } // merge components otherwise if (c1.size() > c2.size()) { this.merge(c1, c2); c1.addEdge(e); } else { this.merge(c2, c1); c2.addEdge(e); } return true; } /** * * merges the two components, i.e., adds all nodes from c2 to c1 and changes * the mapping for all added nodes to c1. finally, c2 is removed from the * list of components * * @param c1 * @param c2 */ protected void merge(WCComponent c1, WCComponent c2) { for (Node n : c2.getNodes()) { c1.addNode(n); this.mapping.put(n, c1); } c1.addEdges(c2.getEdges()); this.components.remove(c2); } protected boolean areConnected(Node n1, Node n2) { if (n1.getDegree() == 0 || n2.getDegree() == 0) { return false; } HashSet<Node> seen = new HashSet<Node>(); Queue<Node> queue = new LinkedList<Node>(); queue.add(n1); seen.add(n1); while (!queue.isEmpty()) { Node current = queue.poll(); for (IElement e_ : current.getEdges()) { Node neighbor = ((Edge) e_).getDifferingNode(current); if (neighbor.equals(n2)) { return true; } if (!seen.contains(neighbor)) { seen.add(neighbor); queue.add(neighbor); } } } return false; } @Override public boolean applyAfterBatch(Batch b) { this.setIds(); return true; } }
gpl-3.0
morogoku/MTweaks-KernelAdiutorMOD
app/src/main/java/com/moro/mtweaks/fragments/LoadingFragment.java
2248
/* * Copyright (C) 2018 Willi Ye <williye97@gmail.com> * * This file is part of Kernel Adiutor. * * Kernel Adiutor is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Kernel Adiutor is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Kernel Adiutor. If not, see <http://www.gnu.org/licenses/>. * */ package com.moro.mtweaks.fragments; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.moro.mtweaks.R; /** * Created by willi on 08.03.18. */ public class LoadingFragment extends BaseFragment { private String mTitle; private String mSummary; private TextView mTitleView; private TextView mSummaryView; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_loading, container, false); mTitleView = rootView.findViewById(R.id.title); mSummaryView = rootView.findViewById(R.id.summary); setup(); return rootView; } public void setTitle(String title) { mTitle = title; setup(); } public void setSummary(String summary) { mSummary = summary; setup(); } private void setup() { if (mTitleView != null) { if (mTitle == null) { mTitleView.setVisibility(View.GONE); } else { mTitleView.setVisibility(View.VISIBLE); mTitleView.setText(mTitle); } mSummaryView.setText(mSummary); } } }
gpl-3.0
snavaneethan1/jaffa-framework
jaffa-core/source/httpunittest/java/org/jaffa/applications/test/modules/time/components/usertimeentryviewer/ui/UserTimeEntryViewerComponent.java
12855
// .//GEN-BEGIN:_1_be /****************************************************** * Code Generated From JAFFA Framework Default Pattern * * The JAFFA Project can be found at http://jaffa.sourceforge.net * and is available under the Lesser GNU Public License ******************************************************/ package org.jaffa.applications.test.modules.time.components.usertimeentryviewer.ui; import org.apache.log4j.Logger; import java.util.EventObject; import org.jaffa.presentation.portlet.component.Component; import org.jaffa.presentation.portlet.FormKey; import org.jaffa.exceptions.ApplicationExceptions; import org.jaffa.exceptions.FrameworkException; import org.jaffa.exceptions.DomainObjectNotFoundException; import org.jaffa.datatypes.exceptions.MandatoryFieldException; import org.jaffa.middleware.Factory; import org.jaffa.components.finder.OrderByField; import org.jaffa.components.maint.*; import org.jaffa.components.dto.HeaderDto; import org.jaffa.applications.test.modules.time.components.usertimeentryviewer.IUserTimeEntryViewer; import org.jaffa.applications.test.modules.time.components.usertimeentryviewer.dto.UserTimeEntryViewerInDto; import org.jaffa.applications.test.modules.time.components.usertimeentryviewer.dto.UserTimeEntryViewerOutDto; import org.jaffa.applications.test.modules.time.domain.UserTimeEntry; import org.jaffa.applications.test.modules.time.domain.UserTimeEntryMeta; import org.jaffa.applications.test.modules.time.components.usertimeentrymaintenance.ui.UserTimeEntryMaintenanceComponent; // .//GEN-END:_1_be // Add additional imports//GEN-FIRST:_imports // .//GEN-LAST:_imports // .//GEN-BEGIN:_2_be /** The controller for the UserTimeEntryViewer. */ public class UserTimeEntryViewerComponent extends Component { private static Logger log = Logger.getLogger(UserTimeEntryViewerComponent.class); private HeaderDto m_headerDto = null; private java.lang.String m_userName; private java.lang.String m_projectCode; private java.lang.String m_task; private org.jaffa.datatypes.DateTime m_periodStart; private org.jaffa.datatypes.DateTime m_periodEnd; private UserTimeEntryViewerOutDto m_outputDto = null; private IUserTimeEntryViewer m_tx = null; private UserTimeEntryMaintenanceComponent m_updateComponent = null; private IUpdateListener m_updateListener = null; // .//GEN-END:_2_be // .//GEN-BEGIN:_quit_1_be /** This should be invoked when done with the component. */ public void quit() { // .//GEN-END:_quit_1_be // Add custom code before processing the method //GEN-FIRST:_quit_1 // .//GEN-LAST:_quit_1 // .//GEN-BEGIN:_quit_2_be if (m_tx != null) { m_tx.destroy(); m_tx = null; } if (m_updateComponent != null) { m_updateComponent.quit(); m_updateComponent = null; } m_updateListener = null; m_outputDto = null; super.quit(); } // .//GEN-END:_quit_2_be // .//GEN-BEGIN:userName_1_be /** Getter for property userName. * @return Value of property userName. */ public java.lang.String getUserName() { return m_userName; } /** Setter for property userName. * @param userName New value of property userName. */ public void setUserName(java.lang.String userName) { m_userName = userName; } // .//GEN-END:userName_1_be // .//GEN-BEGIN:projectCode_1_be /** Getter for property projectCode. * @return Value of property projectCode. */ public java.lang.String getProjectCode() { return m_projectCode; } /** Setter for property projectCode. * @param projectCode New value of property projectCode. */ public void setProjectCode(java.lang.String projectCode) { m_projectCode = projectCode; } // .//GEN-END:projectCode_1_be // .//GEN-BEGIN:task_1_be /** Getter for property task. * @return Value of property task. */ public java.lang.String getTask() { return m_task; } /** Setter for property task. * @param task New value of property task. */ public void setTask(java.lang.String task) { m_task = task; } // .//GEN-END:task_1_be // .//GEN-BEGIN:periodStart_1_be /** Getter for property periodStart. * @return Value of property periodStart. */ public org.jaffa.datatypes.DateTime getPeriodStart() { return m_periodStart; } /** Setter for property periodStart. * @param periodStart New value of property periodStart. */ public void setPeriodStart(org.jaffa.datatypes.DateTime periodStart) { m_periodStart = periodStart; } // .//GEN-END:periodStart_1_be // .//GEN-BEGIN:periodEnd_1_be /** Getter for property periodEnd. * @return Value of property periodEnd. */ public org.jaffa.datatypes.DateTime getPeriodEnd() { return m_periodEnd; } /** Setter for property periodEnd. * @param periodEnd New value of property periodEnd. */ public void setPeriodEnd(org.jaffa.datatypes.DateTime periodEnd) { m_periodEnd = periodEnd; } // .//GEN-END:periodEnd_1_be // .//GEN-BEGIN:_UserTimeEntryViewerOutDto_1_be /** Getter for property outputDto. * @return Value of property outputDto. */ public UserTimeEntryViewerOutDto getUserTimeEntryViewerOutDto() { return m_outputDto; } /** Setter for property outputDto. * @param outputDto New value of property outputDto. */ public void setUserTimeEntryViewerOutDto(UserTimeEntryViewerOutDto outputDto) { m_outputDto = outputDto; } // .//GEN-END:_UserTimeEntryViewerOutDto_1_be // .//GEN-BEGIN:_display_1_be /** This retrieves the details for the UserTimeEntry. * @throws ApplicationExceptions This will be thrown in case any invalid data has been set, or if no data has been set. * @throws FrameworkException Indicates some system error. * @return The FormKey for the View screen. */ public FormKey display() throws ApplicationExceptions, FrameworkException { ApplicationExceptions appExps = null; // .//GEN-END:_display_1_be // Add custom code before processing the method //GEN-FIRST:_display_1 // .//GEN-LAST:_display_1 // .//GEN-BEGIN:_display_2_be if (getUserName() == null) { if (appExps == null) appExps = new ApplicationExceptions(); appExps.add(new MandatoryFieldException(UserTimeEntryMeta.META_USER_NAME.getLabelToken()) ); } if (getProjectCode() == null) { if (appExps == null) appExps = new ApplicationExceptions(); appExps.add(new MandatoryFieldException(UserTimeEntryMeta.META_PROJECT_CODE.getLabelToken()) ); } if (getTask() == null) { if (appExps == null) appExps = new ApplicationExceptions(); appExps.add(new MandatoryFieldException(UserTimeEntryMeta.META_TASK.getLabelToken()) ); } if (getPeriodStart() == null) { if (appExps == null) appExps = new ApplicationExceptions(); appExps.add(new MandatoryFieldException(UserTimeEntryMeta.META_PERIOD_START.getLabelToken()) ); } if (getPeriodEnd() == null) { if (appExps == null) appExps = new ApplicationExceptions(); appExps.add(new MandatoryFieldException(UserTimeEntryMeta.META_PERIOD_END.getLabelToken()) ); } if (appExps != null && appExps.size() > 0) throw appExps; doInquiry(); return getViewerFormKey(); } // .//GEN-END:_display_2_be // .//GEN-BEGIN:_inquiry_1_be private void doInquiry() throws ApplicationExceptions, FrameworkException { UserTimeEntryViewerInDto inputDto = new UserTimeEntryViewerInDto(); // .//GEN-END:_inquiry_1_be // Add custom code before building the input dto //GEN-FIRST:_inquiry_1 // .//GEN-LAST:_inquiry_1 // .//GEN-BEGIN:_inquiry_2_be inputDto.setUserName(m_userName); inputDto.setProjectCode(m_projectCode); inputDto.setTask(m_task); inputDto.setPeriodStart(m_periodStart); inputDto.setPeriodEnd(m_periodEnd); inputDto.setHeaderDto(createHeaderDto()); // create the Tx if (m_tx == null) m_tx = (IUserTimeEntryViewer) Factory.createObject(IUserTimeEntryViewer.class); // .//GEN-END:_inquiry_2_be // Add custom code before invoking the Tx //GEN-FIRST:_inquiry_2 // .//GEN-LAST:_inquiry_2 // .//GEN-BEGIN:_inquiry_3_be // now get the details m_outputDto = m_tx.read(inputDto); // uncache the widgets getUserSession().getWidgetCache(getComponentId()).clear(); // .//GEN-END:_inquiry_3_be // Add custom code after invoking the Tx //GEN-FIRST:_inquiry_3 // .//GEN-LAST:_inquiry_3 // .//GEN-BEGIN:_inquiry_4_be // throw an exception if the output is null if (m_outputDto == null) { ApplicationExceptions appExps = new ApplicationExceptions(); appExps.add(new DomainObjectNotFoundException(UserTimeEntryMeta.getLabelToken())); throw appExps; } } // .//GEN-END:_inquiry_4_be // .//GEN-BEGIN:_createHeaderDto_1_be private HeaderDto createHeaderDto() { if (m_headerDto == null) { m_headerDto = new HeaderDto(); m_headerDto.setUserId( getUserSession().getUserId() ); m_headerDto.setVariation( getUserSession().getVariation() ); // .//GEN-END:_createHeaderDto_1_be // Add custom code before processing the action //GEN-FIRST:_createHeaderDto_1 // .//GEN-LAST:_createHeaderDto_1 // .//GEN-BEGIN:_createHeaderDto_2_be } return m_headerDto; } // .//GEN-END:_createHeaderDto_2_be // .//GEN-BEGIN:_getViewerFormKey_1_be public FormKey getViewerFormKey() { return new FormKey(UserTimeEntryViewerForm.NAME, getComponentId()); } // .//GEN-END:_getViewerFormKey_1_be // .//GEN-BEGIN:_updateObject_1_be /** Calls the UserTimeEntry.UserTimeEntryMaintenance component for updating the UserTimeEntry object. * @throws ApplicationExceptions This will be thrown in case any invalid data has been set. * @throws FrameworkException Indicates some system error. * @return The FormKey for the Update screen. */ public FormKey updateObject() throws ApplicationExceptions, FrameworkException { if (m_updateComponent == null || !m_updateComponent.isActive()) { m_updateComponent = (UserTimeEntryMaintenanceComponent) run("UserTimeEntry.UserTimeEntryMaintenance"); m_updateComponent.setReturnToFormKey(getViewerFormKey()); addListeners(m_updateComponent); } m_updateComponent.setUserName(getUserName()); m_updateComponent.setProjectCode(getProjectCode()); m_updateComponent.setTask(getTask()); m_updateComponent.setPeriodStart(getPeriodStart()); m_updateComponent.setPeriodEnd(getPeriodEnd()); if (m_updateComponent instanceof IMaintComponent) ((IMaintComponent) m_updateComponent).setMode(IMaintComponent.MODE_UPDATE); // .//GEN-END:_updateObject_1_be // Add custom code before invoking the component //GEN-FIRST:_updateObject_2 // .//GEN-LAST:_updateObject_2 // .//GEN-BEGIN:_updateObject_2_be return m_updateComponent.display(); } private IUpdateListener getUpdateListener() { if (m_updateListener == null) { m_updateListener = new IUpdateListener() { public void updateDone(EventObject source) { try { // .//GEN-END:_updateObject_2_be // Add custom code //GEN-FIRST:_updateObject_1 // .//GEN-LAST:_updateObject_1 // .//GEN-BEGIN:_updateObject_3_be doInquiry(); } catch (Exception e) { log.warn("Error in refreshing the Results screen after the Update", e); } } }; } return m_updateListener; } private void addListeners(Component comp) { if (comp instanceof IUpdateComponent) ((IUpdateComponent) comp).addUpdateListener(getUpdateListener()); } // .//GEN-END:_updateObject_3_be // All the custom code goes here //GEN-FIRST:_custom // .//GEN-LAST:_custom }
gpl-3.0
hqnghi88/gamaClone
msi.gama.core/src/msi/gaml/compilation/GamlCompilationError.java
2534
/********************************************************************************************* * * 'GamlCompilationError.java, in plugin msi.gama.core, is part of the source code of the * GAMA modeling and simulation platform. * (c) 2007-2016 UMI 209 UMMISCO IRD/UPMC & Partners * * Visit https://github.com/gama-platform/gama for license information and developers contact. * * **********************************************************************************************/ package msi.gaml.compilation; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EObject; /** * The Class GamlCompilationError. Represents the errors produced by the * validation/compilation of IDescription's. */ public class GamlCompilationError { protected boolean isWarning = false; protected boolean isInfo = false; protected final String message; protected String code; protected String[] data; protected EObject source; protected final URI uri; public GamlCompilationError(final String string, final String code, final EObject object, final boolean warning, final boolean info, final String... data) { message = string; isWarning = warning; isInfo = info; this.code = code; this.data = data; source = object; uri = object.eResource().getURI(); } public GamlCompilationError(final String string, final String code, final URI uri, final boolean warning, final boolean info, final String... data) { message = string; isWarning = warning; isInfo = info; this.code = code; this.data = data; source = null; this.uri = uri; } public String[] getData() { return data; } public URI getURI() { return uri; } public String getCode() { return code; } @Override public String toString() { return message; } public boolean isWarning() { return isWarning && !isInfo; } public boolean isInfo() { return isInfo; } public EObject getStatement() { return source; } public boolean isError() { return !isInfo && !isWarning; } @Override public boolean equals(final Object other) { if (this == other) { return true; } if (!(other instanceof GamlCompilationError)) { return false; } final GamlCompilationError error = (GamlCompilationError) other; return message.equals(error.message) && source == error.source; } @Override public int hashCode() { return message.hashCode() + (source == null ? 0 : source.hashCode()); } }
gpl-3.0
forty3degrees/graphclasses
Prototype 2 - Backup/p/src/teo/Actions/DeleteSelection.java
565
package teo.Actions; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.Action; import y.view.Graph2DView; public class DeleteSelection extends AbstractAction { private final Graph2DView view; public DeleteSelection(final Graph2DView view) { super("Delete Selection"); this.view = view; this.putValue(Action.SHORT_DESCRIPTION, "Delete Selection"); } public void actionPerformed(ActionEvent e) { view.getGraph2D().removeSelection(); view.getGraph2D().updateViews(); } }
gpl-3.0
tomtomtom09/CampCraft
build/tmp/recompileMc/sources/net/minecraft/client/particle/EntitySnowShovelFX.java
3428
package net.minecraft.client.particle; import net.minecraft.client.renderer.WorldRenderer; import net.minecraft.entity.Entity; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class EntitySnowShovelFX extends EntityFX { float snowDigParticleScale; protected EntitySnowShovelFX(World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, double ySpeedIn, double zSpeedIn) { this(worldIn, xCoordIn, yCoordIn, zCoordIn, xSpeedIn, ySpeedIn, zSpeedIn, 1.0F); } protected EntitySnowShovelFX(World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, double ySpeedIn, double zSpeedIn, float p_i1228_14_) { super(worldIn, xCoordIn, yCoordIn, zCoordIn, xSpeedIn, ySpeedIn, zSpeedIn); this.motionX *= 0.10000000149011612D; this.motionY *= 0.10000000149011612D; this.motionZ *= 0.10000000149011612D; this.motionX += xSpeedIn; this.motionY += ySpeedIn; this.motionZ += zSpeedIn; this.particleRed = this.particleGreen = this.particleBlue = 1.0F - (float)(Math.random() * 0.30000001192092896D); this.particleScale *= 0.75F; this.particleScale *= p_i1228_14_; this.snowDigParticleScale = this.particleScale; this.particleMaxAge = (int)(8.0D / (Math.random() * 0.8D + 0.2D)); this.particleMaxAge = (int)((float)this.particleMaxAge * p_i1228_14_); this.noClip = false; } /** * Renders the particle */ public void renderParticle(WorldRenderer worldRendererIn, Entity entityIn, float partialTicks, float p_180434_4_, float p_180434_5_, float p_180434_6_, float p_180434_7_, float p_180434_8_) { float f = ((float)this.particleAge + partialTicks) / (float)this.particleMaxAge * 32.0F; f = MathHelper.clamp_float(f, 0.0F, 1.0F); this.particleScale = this.snowDigParticleScale * f; super.renderParticle(worldRendererIn, entityIn, partialTicks, p_180434_4_, p_180434_5_, p_180434_6_, p_180434_7_, p_180434_8_); } /** * Called to update the entity's position/logic. */ public void onUpdate() { this.prevPosX = this.posX; this.prevPosY = this.posY; this.prevPosZ = this.posZ; if (this.particleAge++ >= this.particleMaxAge) { this.setDead(); } this.setParticleTextureIndex(7 - this.particleAge * 8 / this.particleMaxAge); this.motionY -= 0.03D; this.moveEntity(this.motionX, this.motionY, this.motionZ); this.motionX *= 0.9900000095367432D; this.motionY *= 0.9900000095367432D; this.motionZ *= 0.9900000095367432D; if (this.onGround) { this.motionX *= 0.699999988079071D; this.motionZ *= 0.699999988079071D; } } @SideOnly(Side.CLIENT) public static class Factory implements IParticleFactory { public EntityFX getEntityFX(int particleID, World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, double ySpeedIn, double zSpeedIn, int... p_178902_15_) { return new EntitySnowShovelFX(worldIn, xCoordIn, yCoordIn, zCoordIn, xSpeedIn, ySpeedIn, zSpeedIn); } } }
gpl-3.0
Abnaxos/markdown-doclet
nullity/src/main/java/javax/annotation/meta/TypeQualifierDefault.java
638
package javax.annotation.meta; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.annotation.Nonnull; /** * This qualifier is applied to an annotation to denote that the annotation * defines a default type qualifier that is visible within the scope of the * element it is applied to. */ @Documented @Target(ElementType.ANNOTATION_TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface TypeQualifierDefault { @Nonnull ElementType[] value() default {}; }
gpl-3.0
inglis-dl/onyx-instruments
interface-ecg-cardiosoft/src/main/java/org/obiba/onyx/jade/instrument/gehealthcare/BtrInputGenerator.java
5937
/******************************************************************************* * Copyright 2008(c) The OBiBa Consortium. All rights reserved. * * This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package org.obiba.onyx.jade.instrument.gehealthcare; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Map; import org.obiba.onyx.util.data.Data; /** * */ public class BtrInputGenerator { /** The size of a record's data */ private static final int RECORD_SIZE = 145; /** The bytes that represents the record's header */ private static byte[] recordHeader = getStringBytes(RECORD_SIZE + ","); /** The bytes that represents the record's end (separator when multiple records in the same file) */ private static byte[] recordEnd = { (byte) 0x0D, (byte) 0x0A }; /** The bytes that represents the EOF */ private static byte[] fileEnd = { (byte) 0x1A }; /** Useful constant */ private static byte ZERO = 0; private enum WeightUnits { // The KG unit is actually DG, but the interface will convert the value to KG, so using KG here is more meaningful KG, LBS; public void put(ByteBuffer bb) { bb.putShort((short) ordinal()); } } private enum HeightUnits { CM, IN; public void put(ByteBuffer bb) { bb.putShort((short) ordinal()); } } private enum Gender { OTHER, MALE, FEMALE; public void put(ByteBuffer bb) { bb.put((byte) ordinal()); } } private enum Ethnicity { UNKNOWN, CAUCASIAN, BLACK, ASIAN, ORIENTAL, HISPANIC, NATIVE, INUIT, POLYNESIAN, PACIFIC_ISLAND, MOGOLIAN, IDIAN; public void put(ByteBuffer bb) { bb.putShort((short) ordinal()); } } public BtrInputGenerator() { // constructor } /** * Formats the data so it can be loaded in the BTRIEVE patient table. * <p> * The data is expected to include the following attributes, presented in the following order: * <ul> * <li>Last name: string</li> * <li>First name: string</li> * <li>Birth month: short</li> * <li>Birth year (yyyy): short</li> * <li>Birth day: short</li> * <li>Patient ID: string</li> * <li>Primary key: integer</li> * <li>Weight (dg): short</li> * <li>Height (cm): short</li> * <li>Gender: one of {@link Gender} values</li> * <li>Ethnicity: one of {@link Ethnicity} values</li> * <li>Pacemaker: byte</li> * </ul> * <p> * Notes: * <ul> * <li>Primary key must be unique when loading the record.</li> * <li>Weight is given in decigrams (dg).</li> * <li>Pacemaker values are 1 (has one), 0 (does not have one).</li> * </ul> */ public ByteBuffer generateByteBuffer(Map<String, Data> inputData) { // Create a buffer that will hold the record, its header, its separator, and the eof ByteBuffer bb = ByteBuffer.allocate(RECORD_SIZE + recordHeader.length + recordEnd.length + fileEnd.length); bb.order(ByteOrder.LITTLE_ENDIAN); bb.put(recordHeader); putString(bb, inputData.get("INPUT_PARTICIPANT_LAST_NAME").getValueAsString()); // 0-30 putString(bb, inputData.get("INPUT_PARTICIPANT_FIRST_NAME").getValueAsString()); // 31-61 // We need to add one to the birthday month since the month of January is represented by "0" in // java.util.Calendar (we need January to be "1" here). short birthdayMonth = (short) (Short.parseShort(inputData.get("INPUT_PARTICIPANT_BIRTH_MONTH").getValueAsString()) + 1); bb.putShort(Short.valueOf(inputData.get("INPUT_PARTICIPANT_BIRTH_YEAR").getValueAsString())).putShort(birthdayMonth).putShort(Short.valueOf(inputData.get("INPUT_PARTICIPANT_BIRTH_DAY").getValueAsString())); // 62-63,64-65,66-67 putString(bb, inputData.get("INPUT_PARTICIPANT_BARCODE").getValueAsString()); // 68-98 bb.putInt(0); // 99-102 // Input weight is expected in decigrams so multiply the kilograms input by 10. bb.putShort((short) (Short.valueOf(inputData.get("INPUT_PARTICIPANT_WEIGHT").getValueAsString()).shortValue() * 10)); WeightUnits.KG.put(bb); // 105-106 bb.putShort(Short.valueOf(inputData.get("INPUT_PARTICIPANT_HEIGHT").getValueAsString())); HeightUnits.CM.put(bb); // 109-110 Gender gender = Gender.valueOf(inputData.get("INPUT_PARTICIPANT_GENDER").getValueAsString()); gender.put(bb); // 111 Ethnicity ethnicity = Ethnicity.valueOf(inputData.get("INPUT_PARTICIPANT_ETHNIC_GROUP").getValueAsString()); ethnicity.put(bb); // 112-113 bb.put(Byte.valueOf(inputData.get("INPUT_PARTICIPANT_PACEMAKER").getValueAsString())); // The rest is unknown. Either it is unused or its use for internal purposes. Filling it with zeroes is ok. fillWithZeroes(bb); bb.put(recordEnd).put(fileEnd); return bb; } private static void fillWithZeroes(ByteBuffer bb) { // Fill the rest of the record (everything except the record end and file end) while(bb.remaining() > recordEnd.length + fileEnd.length) { bb.put(ZERO); } } private static void putString(ByteBuffer bb, String s) { byte b[] = getStringBytes(s); for(int i = 0; i < 31; i++) { if(b != null && i < b.length) { bb.put(b[i]); } else { bb.put(ZERO); } } } private static byte[] getStringBytes(String s) { if(s == null || s.length() == 0) { return new byte[0]; } try { // I have no idea what encoding they use. We should test with accentuated characters. // ISO-8859-1 is a likely candidate. return s.getBytes("ISO-8859-1"); } catch(UnsupportedEncodingException e) { throw new RuntimeException(e); } } }
gpl-3.0
mark-walle/sbc-qsystem
QSystem/src/ru/apertum/qsystem/extra/ITask.java
2494
/* * Copyright (C) 2015 Evgeniy Egorov * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ru.apertum.qsystem.extra; import ru.apertum.qsystem.common.cmd.AJsonRPC20; import ru.apertum.qsystem.common.cmd.CmdParams; import ru.apertum.qsystem.common.model.QCustomer; /** * Если надо добавить команду, исполняемую сервером * * @author Evgeniy Egorov */ public interface ITask extends IExtra { /** * Выполнение команды :: Executing the command * * @param cmdParams входные параметры :: input parameters * @param ipAdress источник команды :: Team source * @param IP источник команды :: Team Source * @return результат выполнения команды, соблюдать протокол jsonRPC2.0 :: Result of the command, * follow the protocol jsonRPC2.0 */ public AJsonRPC20 process(CmdParams cmdParams, String ipAdress, byte[] IP); /** * Выполнение команды :: Executing the command * * @param cmdParams входные параметры :: input parameters * @param ipAdress источник команды :: Team source * @param IP источник команды :: Team Source * @param customer Customer for whicch we need to start the service * @return результат выполнения команды, соблюдать протокол jsonRPC2.0 :: Result of the command, * follow the protocol jsonRPC2.0 */ public AJsonRPC20 process(CmdParams cmdParams, String ipAdress, byte[] IP, QCustomer customer); /** * Уникальное имя команды, по которому ищется исполнитель The unique name of the team that the * artist is looking for */ public String getName(); }
gpl-3.0
nishanttotla/predator
cpachecker/src/org/sosy_lab/cpachecker/cfa/parser/eclipse/java/AstDebugg.java
9069
/* * CPAchecker is a tool for configurable software verification. * This file is part of CPAchecker. * * Copyright (C) 2007-2014 Dirk Beyer * 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. * * * CPAchecker web page: * http://cpachecker.sosy-lab.org */ package org.sosy_lab.cpachecker.cfa.parser.eclipse.java; import java.util.logging.Level; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.ASTVisitor; import org.eclipse.jdt.core.dom.ClassInstanceCreation; import org.eclipse.jdt.core.dom.MethodInvocation; import org.sosy_lab.common.log.LogManager; /** * This Visitor simply extracts the AST of the JDT Parser for debug Purposes. */ class AstDebugg extends ASTVisitor { private final LogManager logger; public AstDebugg(LogManager logger) { this.logger = logger; } @Override public void preVisit(ASTNode node) { if (isProblematicNode(node)) { logger.log(Level.WARNING, "Error in node " + node.toString()); } } private boolean isProblematicNode(ASTNode node) { int flags = node.getFlags(); return ASTNode.RECOVERED == (flags & ASTNode.RECOVERED) || ASTNode.MALFORMED == (flags & ASTNode.MALFORMED); } public static String getTypeName(int type) { String name; switch (type) { case ASTNode.ANNOTATION_TYPE_DECLARATION: name = "ANNOTATION_TYPE_DECLARATION"; break; case ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION: name = "ANNOTATION_TYPE_MEMBER_DECLARATION"; break; case ASTNode.ANONYMOUS_CLASS_DECLARATION: name = "ANONYMOUS_CLASS_DECLARATION"; break; case ASTNode.ARRAY_ACCESS: name = "ARRAY_ACCESS"; break; case ASTNode.ARRAY_CREATION: name = "ARRAY_CREATION"; break; case ASTNode.ARRAY_INITIALIZER: name = "ARRAY_INITIALIZER"; break; case ASTNode.ARRAY_TYPE: name = "ARRAY_TYPE"; break; case ASTNode.ASSERT_STATEMENT: name = "ASSERT_STATEMENT"; break; case ASTNode.ASSIGNMENT: name = "ASSIGNMENT"; break; case ASTNode.BLOCK: name = "BLOCK"; break; case ASTNode.BLOCK_COMMENT: name = "BLOCK_COMMENT"; break; case ASTNode.BOOLEAN_LITERAL: name = "BOOLEAN_LITERAL"; break; case ASTNode.BREAK_STATEMENT: name = "BREAK_STATEMENT"; break; case ASTNode.CAST_EXPRESSION: name = "CAST_EXPRESSION"; break; case ASTNode.CATCH_CLAUSE: name = "CATCH_CLAUSE"; break; case ASTNode.CHARACTER_LITERAL: name = "CHARACTER_LITERAL"; break; case ASTNode.CLASS_INSTANCE_CREATION: name = "CLASS_INSTANCE_CREATION"; break; case ASTNode.COMPILATION_UNIT: name = "COMPILATION_UNIT"; break; case ASTNode.CONDITIONAL_EXPRESSION: name = "CONDITIONAL_EXPRESSION"; break; case ASTNode.CONSTRUCTOR_INVOCATION: name = "CONSTRUCTOR_INVOCATION"; break; case ASTNode.CONTINUE_STATEMENT: name = "CONTINUE_STATEMENT"; break; case ASTNode.DO_STATEMENT: name = "DO_STATEMENT"; break; case ASTNode.EMPTY_STATEMENT: name = "EMPTY_STATEMENT"; break; case ASTNode.ENHANCED_FOR_STATEMENT: name = "ENHANCED_FOR_STATEMENT"; break; case ASTNode.ENUM_CONSTANT_DECLARATION: name = "ENUM_CONSTANT_DECLARATION"; break; case ASTNode.ENUM_DECLARATION: name = "ENUM_DECLARATION"; break; case ASTNode.EXPRESSION_STATEMENT: name = "EXPRESSION_STATEMENT"; break; case ASTNode.FIELD_ACCESS: name = "FIELD_ACCESS"; break; case ASTNode.FIELD_DECLARATION: name = "FIELD_DECLARATION"; break; case ASTNode.FOR_STATEMENT: name = "FOR_STATEMENT"; break; case ASTNode.IF_STATEMENT: name = "IF_STATEMENT"; break; case ASTNode.IMPORT_DECLARATION: name = "IMPORT_DECLARATION"; break; case ASTNode.INFIX_EXPRESSION: name = "INFIX_EXPRESSION"; break; case ASTNode.INITIALIZER: name = "INITIALIZER"; break; case ASTNode.INSTANCEOF_EXPRESSION: name = "INSTANCEOF_EXPRESSION"; break; case ASTNode.JAVADOC: name = "JAVADOC"; break; case ASTNode.LABELED_STATEMENT: name = "LABELED_STATEMENT"; break; case ASTNode.LINE_COMMENT: name = "LINE_COMMENT"; break; case ASTNode.MARKER_ANNOTATION: name = "MARKER_ANNOTATION"; break; case ASTNode.MEMBER_REF: name = "MEMBER_REF"; break; case ASTNode.MEMBER_VALUE_PAIR: name = "MEMBER_VALUE_PAIR"; break; case ASTNode.METHOD_DECLARATION: name = "METHOD_DECLARATION"; break; case ASTNode.METHOD_INVOCATION: name = "METHOD_INVOCATION"; break; case ASTNode.METHOD_REF: name = "METHOD_REF"; break; case ASTNode.METHOD_REF_PARAMETER: name = "METHOD_REF_PARAMETER"; break; case ASTNode.MODIFIER: name = "MODIFIER"; break; case ASTNode.NORMAL_ANNOTATION: name = "NORMAL_ANNOTATION"; break; case ASTNode.NULL_LITERAL: name = "NULL_LITERAL"; break; case ASTNode.NUMBER_LITERAL: name = "NUMBER_LITERAL"; break; case ASTNode.PACKAGE_DECLARATION: name = "PACKAGE_DECLARATION"; break; case ASTNode.PARAMETERIZED_TYPE: name = "PARAMETERIZED_TYPE"; break; case ASTNode.PARENTHESIZED_EXPRESSION: name = "PARENTHESIZED_EXPRESSION"; break; case ASTNode.POSTFIX_EXPRESSION: name = "POSTFIX_EXPRESSION"; break; case ASTNode.PREFIX_EXPRESSION: name = "PREFIX_EXPRESSION"; break; case ASTNode.PRIMITIVE_TYPE: name = "PRIMITIVE_TYPE"; break; case ASTNode.QUALIFIED_NAME: name = "QUALIFIED_NAME"; break; case ASTNode.QUALIFIED_TYPE: name = "QUALIFIED_TYPE"; break; case ASTNode.RETURN_STATEMENT: name = "RETURN_STATEMENT"; break; case ASTNode.SIMPLE_NAME: name = "SIMPLE_NAME"; break; case ASTNode.SIMPLE_TYPE: name = "SIMPLE_TYPE"; break; case ASTNode.SINGLE_MEMBER_ANNOTATION: name = "SINGLE_MEMBER_ANNOTATION"; break; case ASTNode.SINGLE_VARIABLE_DECLARATION: name = "SINGLE_VARIABLE_DECLARATION"; break; case ASTNode.STRING_LITERAL: name = "STRING_LITERAL"; break; case ASTNode.SUPER_CONSTRUCTOR_INVOCATION: name = "SUPER_CONSTRUCTOR_INVOCATION"; break; case ASTNode.SUPER_FIELD_ACCESS: name = "SUPER_FIELD_ACCESS"; break; case ASTNode.SUPER_METHOD_INVOCATION: name = "SUPER_METHOD_INVOCATION"; break; case ASTNode.SWITCH_CASE: name = "SWITCH_CASE"; break; case ASTNode.SWITCH_STATEMENT: name = "SWITCH_STATEMENT"; break; case ASTNode.SYNCHRONIZED_STATEMENT: name = "SYNCHRONIZED_STATEMENT"; break; case ASTNode.TAG_ELEMENT: name = "TAG_ELEMENT"; break; case ASTNode.TEXT_ELEMENT: name = "TEXT_ELEMENT"; break; case ASTNode.THIS_EXPRESSION: name = "THIS_EXPRESSION"; break; case ASTNode.THROW_STATEMENT: name = "THROW_STATEMENT"; break; case ASTNode.TRY_STATEMENT: name = "TRY_STATEMENT"; break; case ASTNode.TYPE_DECLARATION: name = "TYPE_DECLARATION"; break; case ASTNode.TYPE_DECLARATION_STATEMENT: name = "TYPE_DECLARATION_STATEMENT"; break; case ASTNode.TYPE_LITERAL: name = "TYPE_LITERAL"; break; case ASTNode.TYPE_PARAMETER: name = "TYPE_PARAMETER"; break; case ASTNode.UNION_TYPE: name = "UNION_TYPE"; break; case ASTNode.VARIABLE_DECLARATION_EXPRESSION: name = "VARIABLE_DECLARATION_EXPRESSION"; break; case ASTNode.VARIABLE_DECLARATION_FRAGMENT: name = "VARIABLE_DECLARATION_FRAGMENT"; break; case ASTNode.VARIABLE_DECLARATION_STATEMENT: name = "VARIABLE_DECLARATION_STATEMENT"; break; case ASTNode.WHILE_STATEMENT: name = "WHILE_STATEMENT"; break; case ASTNode.WILDCARD_TYPE: name = "WILDCARD_TYPE"; break; default: name = ""; break; } return name; } @Override public boolean visit(MethodInvocation mI) { mI.resolveMethodBinding(); return true; } @Override public boolean visit(ClassInstanceCreation cIC) { cIC.resolveConstructorBinding(); return true; } }
gpl-3.0
buzzinglight/IanniX
Patches/Processing/oscP5/src/oscP5/OscBundle.java
4883
/** * An OSC (Open Sound Control) library for processing. * * (c) 2004-2011 * * 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 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 * * @author Andreas Schlegel http://www.sojamo.de/libraries/oscP5 * @modified 12/19/2011 * @version 0.9.8 */ package oscP5; import java.net.DatagramPacket; import java.util.ArrayList; import netP5.Bytes; import netP5.TcpPacket; /** * Osc Bundles are collections of Osc Messages. use bundles to send multiple * osc messages to one destination. the OscBundle timetag is supported for * sending but not for receiving yet. * @related OscMessage * @related OscP5 * @example oscP5bundle */ public class OscBundle extends OscPacket { protected static final int BUNDLE_HEADER_SIZE = 16; protected static final byte[] BUNDLE_AS_BYTES = {0x23, 0x62, 0x75, 0x6E, 0x64, 0x6C, 0x65, 0x00}; private int _myMessageSize = 0; /** * instantiate a new OscBundle object. */ public OscBundle() { messages = new ArrayList<OscMessage>(); } protected OscBundle(DatagramPacket theDatagramPacket) { inetAddress = theDatagramPacket.getAddress(); port = theDatagramPacket.getPort(); hostAddress = inetAddress.toString(); _myMessageSize = parseBundle(theDatagramPacket.getData(), inetAddress, port, null); _myType = BUNDLE; } protected OscBundle(TcpPacket thePacket) { _myTcpClient = thePacket.getTcpConnection(); inetAddress = _myTcpClient.netAddress().inetaddress(); port = _myTcpClient.netAddress().port(); hostAddress = inetAddress.toString(); _myMessageSize = parseBundle(thePacket.getData(), inetAddress, port, _myTcpClient); _myType = BUNDLE; } /** * add an osc message to the osc bundle. * @param theOscMessage OscMessage */ public void add(OscMessage theOscMessage) { messages.add(new OscMessage(theOscMessage)); _myMessageSize = messages.size(); } /** * clear and reset the osc bundle for reusing. * @example oscP5bundle */ public void clear() { messages = new ArrayList<OscMessage>(); } /** * remove an OscMessage from an OscBundle. * @param theIndex int */ public void remove(int theIndex) { messages.remove(theIndex); } /** * * @param theOscMessage OscMessage */ public void remove(OscMessage theOscMessage) { messages.remove(theOscMessage); } /** * request an osc message inside the osc bundle array, * @param theIndex int * @return OscMessage */ public OscMessage getMessage(int theIndex) { return messages.get(theIndex); } /** * get the size of the osc bundle array which contains the osc messages. * @return int * @example oscP5bundle */ public int size() { return _myMessageSize; } /** * set the timetag of an osc bundle. timetags are used to synchronize events and * execute events at a given time in the future or immediately. timetags can * only be set for osc bundles, not for osc messages. oscP5 supports receiving * timetags, but does not queue messages for execution at a set time. * @param theTime long * @example oscP5bundle */ public void setTimetag(long theTime) { final long secsSince1900 = theTime / 1000 + TIMETAG_OFFSET; final long secsFractional = ((theTime % 1000) << 32) / 1000; timetag = (secsSince1900 << 32) | secsFractional; } /** * returns the current time in milliseconds. use with setTimetag. * @return long */ public static long now() { return System.currentTimeMillis(); } /** * returns a timetag as byte array. * @return byte[] */ public byte[] timetag() { return Bytes.toBytes(timetag); } /** * @todo get timetag as Date */ /** * * @return byte[] * @invisible */ public byte[] getBytes() { byte[] myBytes = new byte[0]; myBytes = Bytes.append(myBytes, BUNDLE_AS_BYTES); myBytes = Bytes.append(myBytes, timetag()); for (int i = 0; i < size(); i++) { byte[] tBytes = getMessage(i).getBytes(); myBytes = Bytes.append(myBytes, Bytes.toBytes(tBytes.length)); myBytes = Bytes.append(myBytes, tBytes); } return myBytes; } }
gpl-3.0
ckaestne/LEADT
CIDE_Samples/cide_samples/Berkeley DB JE/src/com/sleepycat/je/tree/TreeStats.java
466
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2002-2006 * Sleepycat Software. All rights reserved. * * $Id: TreeStats.java,v 1.1 2006/05/06 09:00:17 ckaestne Exp $ */ package com.sleepycat.je.tree; /** * A class that provides interesting stats about a particular tree. */ public final class TreeStats { /** * Number of times the root was split. */ public int nRootSplits = 0; }
gpl-3.0
satta/GeneDB
ng/src/org/genedb/query/bool/BooleanQueryNode.java
871
package org.genedb.query.bool; import org.genedb.query.BasicQueryI; import org.genedb.query.Detailer; import org.genedb.query.NumberedQueryI; import org.genedb.query.QueryI; import org.genedb.query.Result; public class BooleanQueryNode implements NumberedQueryI { private int index; private BasicQueryI query; public BooleanQueryNode(BasicQueryI query) { this.query = query; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public String getSimpleDescription() { return this.query.getSimpleDescription(); } public boolean isComplete() { return this.query.isComplete(); } public Result process() { return this.query.process(); } public String getName() { return this.query.getName(); } }
gpl-3.0
servinglynk/hmis-lynk-open-source
hmis-base-serialize/src/main/java/com/servinglynk/hmis/warehouse/core/model/GlobalProjectUser.java
1999
package com.servinglynk.hmis.warehouse.core.model; import java.util.Date; import java.util.UUID; import javax.validation.constraints.Pattern; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotBlank; import com.fasterxml.jackson.annotation.JsonRootName; import com.servinglynk.hmis.warehouse.common.Constants; @JsonRootName("user") public class GlobalProjectUser { private UUID userId; private UUID accountId; private String username; private String emailAddress; private String firstName; private String middleName; private String lastName; private int gender; private String status; private String link; public UUID getAccountId() { return accountId; } public void setAccountId(UUID accountId) { this.accountId = accountId; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getEmailAddress() { return emailAddress; } public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getMiddleName() { return middleName; } public void setMiddleName(String middleName) { this.middleName = middleName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public int getGender() { return gender; } public void setGender(int gender) { this.gender = gender; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public UUID getUserId() { return userId; } public void setUserId(UUID userId) { this.userId = userId; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } }
mpl-2.0
ajschult/etomica
etomica-graphics3D/src/main/java/org/jmol/util/Int2IntHash.java
2522
/* $RCSfile$ * $Author$ * $Date$ * $Revision$ * * Copyright (C) 2005 Miguel, Jmol Development, www.jmol.org * * Contact: jmol-developers@lists.sf.net * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ package org.jmol.util; public class Int2IntHash { int entryCount; Entry[] entries; public Int2IntHash(int initialCapacity) { entries = new Entry[initialCapacity]; } public synchronized int get(int key) { Entry[] entries = this.entries; int hash = (key & 0x7FFFFFFF) % entries.length; for (Entry e = entries[hash]; e != null; e = e.next) if (e.key == key) return e.value; return Integer.MIN_VALUE; } public synchronized void put(int key, int value) { Entry[] entries = this.entries; int hash = (key & 0x7FFFFFFF) % entries.length; for (Entry e = entries[hash]; e != null; e = e.next) if (e.key == key) { e.value = value; return; } if (entryCount > entries.length) rehash(); entries = this.entries; hash = (key & 0x7FFFFFFF) % entries.length; entries[hash] = new Entry(key, value, entries[hash]); ++entryCount; } private void rehash() { Entry[] oldEntries = entries; int oldSize = oldEntries.length; int newSize = oldSize * 2 + 1; Entry[] newEntries = new Entry[newSize]; for (int i = oldSize; --i >= 0; ) { for (Entry e = oldEntries[i]; e != null; ) { Entry t = e; e = e.next; int hash = (t.key & 0x7FFFFFFF) % newSize; t.next = newEntries[hash]; newEntries[hash] = t; } } entries = newEntries; } static class Entry { int key; int value; Entry next; Entry(int key, int value, Entry next) { this.key = key; this.value = value; this.next = next; } } }
mpl-2.0
jrochas/scale-proactive
src/Core/org/objectweb/proactive/core/config/CentralPAPropertyRepository.java
30933
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2012 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: proactive@ow2.org or contact@activeeon.com * * This library 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; version 3 of * the License. * * 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 * Affero General Public License for more details. * * You should have received a copy of the GNU Affero 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 * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ * $$PROACTIVE_INITIAL_DEV$$ */ package org.objectweb.proactive.core.config; import java.net.Socket; import org.objectweb.proactive.core.config.PAProperties.PAPropertiesLoaderSPI; import org.objectweb.proactive.core.filetransfer.FileTransferService; import org.objectweb.proactive.core.runtime.broadcast.BTCallbackDefaultImpl; import org.objectweb.proactive.utils.OperatingSystem; /** * The central repository of PAProperty * * Ideally the PAProperty should be defined in their own module then registered into * the {@link PAProperties} singleton. Unfortunately, until ProActive 4.3.0 it was only * possible to declare a ProActive property in a centralized enumeration. This * central repository contains all the already existing properties. */ public class CentralPAPropertyRepository implements PAPropertiesLoaderSPI { /** * Java security policy file location */ static public PAPropertyString JAVA_SECURITY_POLICY = new PAPropertyString("java.security.policy", true); /** * If IPv6 is available on the operating system the default preference is to prefer an IPv4-mapped address over an IPv6 address */ static public PAPropertyBoolean PREFER_IPV6_ADDRESSES = new PAPropertyBoolean( "java.net.preferIPv6Addresses", true); /** * If IPv6 is available on the operating system the underlying native socket will be an IPv6 socket. This allows Java(tm) applications to connect too, and accept connections from, both IPv4 and IPv6 hosts. */ static public PAPropertyBoolean PREFER_IPV4_STACK = new PAPropertyBoolean("java.net.preferIPv4Stack", true); /** * Indicate the GCM provider class, to the ProActive implementation of * Fractal/GCM set it to org.objectweb.proactive.core.component.Fractive */ static public PAPropertyString GCM_PROVIDER = new PAPropertyString("gcm.provider", true); /** * Indicate the Fractal provider class, to the ProActive implementation of * Fractal/GCM set it to org.objectweb.proactive.core.component.Fractive */ static public PAPropertyString FRACTAL_PROVIDER = new PAPropertyString("fractal.provider", true); static public PAPropertyString JAVA_SECURITY_AUTH_LOGIN_CONFIG = new PAPropertyString( "java.security.auth.login.config", true); static public PAPropertyString JAVAX_XML_TRANSFORM_TRANSFORMERFACTORY = new PAPropertyString( "javax.xml.transform.TransformerFactory", true); /* ------------------------------------ * PROACTIVE */ /** * ProActive Configuration file location * * If set ProActive will load the configuration file at the given location. */ static public PAPropertyString PA_CONFIGURATION_FILE = new PAPropertyString("proactive.configuration", false); /** * Indicates where ProActive is installed * * Can be useful to write generic deployment descriptor by using a JavaPropertyVariable * to avoid hard coded path. * * Used in unit and functional tests */ static public PAPropertyString PA_HOME = new PAPropertyString("proactive.home", false); /** * Indicates what is the operating system of the local machine * * It is not redundant with "os.name" since the only valid values those from <code>OperatingSystem</code>. * Often users are only interested to know if the computer is running unix or windows. * * @see OperatingSystem */ static public PAPropertyString PA_OS = new PAPropertyString("proactive.os", true); /** * Log4j configuration file location * * If set the specified log4j configuration file is used. Otherwise the default one, * Embedded in the ProActive jar is used. */ static public PAPropertyString LOG4J = new PAPropertyString("log4j.configuration", false); /** * URI of the remote log collector * */ static public PAPropertyString PA_LOG4J_COLLECTOR = new PAPropertyString("proactive.log4j.collector", false); /** * Qualified name of the flushing provider to use */ static public PAPropertyString PA_LOG4J_APPENDER_PROVIDER = new PAPropertyString( "proactive.log4j.appender.provider", false); /** * Specifies the name of the ProActive Runtime * * By default a random name is assigned to a ProActive Runtime. This property allows * to choose the name of the Runtime to be able to perform lookups. * * By default, the name of a runtime starts with PA_JVM</strong> */ static public PAPropertyString PA_RUNTIME_NAME = new PAPropertyString("proactive.runtime.name", false); /** * this property should be used when one wants to start only a runtime without an additional main class */ static public PAPropertyBoolean PA_RUNTIME_STAYALIVE = new PAPropertyBoolean( "proactive.runtime.stayalive", false); /** * Terminates the Runtime when the Runtime becomes empty * * If true, when all bodies have been terminated the ProActive Runtime will exit */ static public PAPropertyBoolean PA_EXIT_ON_EMPTY = new PAPropertyBoolean("proactive.exit_on_empty", false); /** * Boolean to activate automatic continuations for this runtime. */ static public PAPropertyBoolean PA_FUTURE_AC = new PAPropertyBoolean("proactive.future.ac", false); /** * Timeout value for future in synchronous requests. * can be used to set timeout on synchronous calls. Impossible otherwise * default value 0, no timeout */ static public PAPropertyLong PA_FUTURE_SYNCHREQUEST_TIMEOUT = new PAPropertyLong( "proactive.future.synchrequest.timeout", false, 0); /** * Period of the future monitoring ping, in milliseconds * * If set to 0, then future monitoring is disabled */ static public PAPropertyInteger PA_FUTUREMONITORING_TTM = new PAPropertyInteger( "proactive.futuremonitoring.ttm", false); /** * Include client side calls in stack traces */ static public PAPropertyBoolean PA_STACKTRACE = new PAPropertyBoolean("proactive.stack_trace", false); /** * Activates the legacy SAX ProActive Descriptor parser * * To check if the new JAXP parser introduced regressions. */ static public PAPropertyBoolean PA_LEGACY_PARSER = new PAPropertyBoolean("proactive.legacy.parser", false); /* ------------------------------------ * NETWORK */ /** * ProActive Communication protocol * * Suppported values are: rmi, rmissh, ibis, http */ static public PAPropertyString PA_COMMUNICATION_PROTOCOL = new PAPropertyString( "proactive.communication.protocol", false); /** * ProActive Runtime Hostname (or IP Address) * * This option can be used to set manually the Runtime IP Address. Can be * useful when the Java networking stack return a bad IP address (example: multihomed machines). * */ static public PAPropertyString PA_HOSTNAME = new PAPropertyString("proactive.hostname", false); /** * Toggle DNS resolution * * When true IP addresses are used instead of FQDNs. Can be useful with misconfigured DNS servers * or strange /etc/resolv.conf files. FQDNs passed by user or 3rd party tools are resolved and converted * into IP addresses * */ static public PAPropertyBoolean PA_NET_USE_IP_ADDRESS = new PAPropertyBoolean("proactive.useIPaddress", false); /** Enable or disable IPv6 * */ static public PAPropertyBoolean PA_NET_DISABLE_IPv6 = new PAPropertyBoolean("proactive.net.disableIPv6", false); /** * Toggle loopback IP address usage * * When true loopback IP address usage is avoided. Since Remote adapters contain only one * endpoint the right IP address must be used. This property must be set to true if a loopback * address is returned by the Java INET stack. * * If only a loopback address exists, it is used. */ static public PAPropertyBoolean PA_NET_NOLOOPBACK = new PAPropertyBoolean("proactive.net.nolocal", false); /** * Toggle Private IP address usage * * When true private IP address usage is avoided. Since Remote adapters contain only one * endpoint the right IP address must be used. This property must be set to true if a private * address is returned by the Java INET stack and this private IP is not reachable by other hosts. */ static public PAPropertyBoolean PA_NET_NOPRIVATE = new PAPropertyBoolean("proactive.net.noprivate", false); /** * Select the network interface */ static public PAPropertyString PA_NET_INTERFACE = new PAPropertyString("proactive.net.interface", false); /** Select the netmask to use (xxx.xxx.xxx.xxx/xx) * * Does not work with IPv6 addresses */ static public PAPropertyString PA_NET_NETMASK = new PAPropertyString("proactive.net.netmask", false); /** * RMI/SSH black voodoo * * Can be used to fix broken networks (multihomed, broken DNS etc.). You probably want * to post on the public ProActive mailing list before using this property. */ static public PAPropertyString PA_NET_SECONDARYNAMES = new PAPropertyString( "proactive.net.secondaryNames", false); static public PAPropertyBoolean SCHEMA_VALIDATION = new PAPropertyBoolean("schema.validation", true); /** SSL cipher suites used for RMISSL communications. * List of cipher suites used for RMISSL, separated by commas. * default is SSL_DH_anon_WITH_RC4_128_MD5. This cipher suite is used only * to have encrypted communications, without authentication, and works with default * JVM's keyStore/TrustStore * * Many others can be used. for implementing a certificate authentication... * see http://java.sun.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html * * */ static public PAPropertyString PA_SSL_CIPHER_SUITES = new PAPropertyString("proactive.ssl.cipher.suites", false); /* ------------------------------------ * RMI */ /** * Assigns a TCP port to RMI * * this property identifies the default port used by the RMI communication protocol */ static public PAPropertyInteger PA_RMI_PORT = new PAPropertyInteger("proactive.rmi.port", false); static public PAPropertyString JAVA_RMI_SERVER_CODEBASE = new PAPropertyString( "java.rmi.server.codebase", true); static public PAPropertyBoolean JAVA_RMI_SERVER_USECODEBASEONLY = new PAPropertyBoolean( "java.rmi.server.useCodebaseOnly", true, false); /** * Sockets used by the RMI remote object factory connect to the remote server * with a specified timeout value. A timeout of zero is interpreted as an infinite timeout. * The connection will then block until established or an error occurs. */ static public PAPropertyInteger PA_RMI_CONNECT_TIMEOUT = new PAPropertyInteger( "proactive.rmi.connect_timeout", false); static public PAPropertyString PA_CODEBASE = new PAPropertyString("proactive.codebase", true); static public PAPropertyBoolean PA_CLASSLOADING_USEHTTP = new PAPropertyBoolean( "proactive.classloading.useHTTP", false); /* ------------------------------------ * HTTP */ /** * Assigns a TCP port to XML-HTTP * * this property identifies the default port for the xml-http protocol */ static public PAPropertyInteger PA_XMLHTTP_PORT = new PAPropertyInteger("proactive.http.port", false); /** * Define a Connector to be used by Jetty * * By default a SelectChannelConnector is used. It is well suited to handle a lot * of mainly idle clients workload (like coarse grained master worker). If you have a * few very busy client better performances can be achieved by using a SocketConnect * * You can use a SocketConnect, a BlockingChannelConnector or a SelectChannelConnector * You CANNOT use a SSL connector. * Click * <a href="http://docs.codehaus.org/display/JETTY/Architecture">here</a> for more * information on the Jetty architecture. */ static public PAPropertyString PA_HTTP_JETTY_CONNECTOR = new PAPropertyString( "proactive.http.jetty.connector", false); /** * Jetty configuration file * * Jetty can be configured by providing a * <a href="http://docs.codehaus.org/display/JETTY/jetty.xml">jetty.xml</a> * file. Click * <a href="http://docs.codehaus.org/display/JETTY/Syntax+Reference">here </a> * for the Jetty syntax reference. */ static public PAPropertyString PA_HTTP_JETTY_XML = new PAPropertyString("proactive.http.jetty.xml", false); /** * Sockets used by the HTTP remote object factory connect to the remote server * with a specified timeout value. A timeout of zero is interpreted as an infinite timeout. * The connection will then block until established or an error occurs. */ static public PAPropertyInteger PA_HTTP_CONNECT_TIMEOUT = new PAPropertyInteger( "proactive.http.connect_timeout", false); /* ------------------------------------ * COMPONENTS */ /** Timeout in seconds for parallel creation of components */ static public PAPropertyInteger PA_COMPONENT_CREATION_TIMEOUT = new PAPropertyInteger( "components.creation.timeout", false); /** If 'true', the component framework should optimize communication between component using shortcut mechanism */ static public PAPropertyBoolean PA_COMPONENT_USE_SHORTCUTS = new PAPropertyBoolean( "proactive.components.use_shortcuts", false); /* ------------------------------------ * MIGRATION */ /** The class or interface of the location server to be looked up */ static public PAPropertyString PA_LOCATION_SERVER = new PAPropertyString("proactive.locationserver", false); /** The bind name of a location server, used during lookup */ static public PAPropertyString PA_LOCATION_SERVER_RMI = new PAPropertyString( "proactive.locationserver.rmi", false); /** The lifetime (in seconds) of a forwarder left after a migration when using the mixed location scheme */ static public PAPropertyInteger PA_MIXEDLOCATION_TTL = new PAPropertyInteger( "proactive.mixedlocation.ttl", false); /** If set to true, a forwarder will send an update to a location server when reaching * the end of its lifetime */ static public PAPropertyBoolean PA_MIXEDLOCATION_UPDATINGFORWARDER = new PAPropertyBoolean( "proactive.mixedlocation.updatingForwarder", false); /** The maximum number of migration allowed before an object must send its new location to a location server */ static public PAPropertyInteger PA_MIXEDLOCATION_MAXMIGRATIONNB = new PAPropertyInteger( "proactive.mixedlocation.maxMigrationNb", false); /** The maximum time (in seconds) an object can spend on a site before updating its location to a location server */ static public PAPropertyInteger PA_MIXEDLOCATION_MAXTIMEONSITE = new PAPropertyInteger( "proactive.mixedlocation.maxTimeOnSite", false); /* ------------------------------------ * RMISSH */ /** this property identifies the location of RMISSH key directory */ static public PAPropertyString PA_RMISSH_KEY_DIR = new PAPropertyString( "proactive.communication.rmissh.key_directory", false); /** this property identifies that when using SSH tunneling, a normal connection should be tried before tunneling */ static public PAPropertyBoolean PA_RMISSH_TRY_NORMAL_FIRST = new PAPropertyBoolean( "proactive.communication.rmissh.try_normal_first", false); /** this property identifies the SSH garbage collector period * * If set to 0, tunnels and connections are not garbage collected */ static public PAPropertyInteger PA_RMISSH_GC_PERIOD = new PAPropertyInteger( "proactive.communication.rmissh.gc_period", false); /** this property identifies the maximum idle time before a SSH tunnel or a connection is garbage collected */ static public PAPropertyInteger PA_RMISSH_GC_IDLETIME = new PAPropertyInteger( "proactive.communication.rmissh.gc_idletime", false); /** this property identifies the know hosts file location when using ssh tunneling * if undefined, the default value is user.home property concatenated to SSH_TUNNELING_DEFAULT_KNOW_HOSTS */ static public PAPropertyString PA_RMISSH_KNOWN_HOSTS = new PAPropertyString( "proactive.communication.rmissh.known_hosts", false); /** Sock connect timeout, in ms * * The timeout to be used when a SSH Tunnel is opened. 0 is interpreted * as an infinite timeout. This timeout is also used for plain socket when try_normal_first is set to true * * @see Socket */ static public PAPropertyInteger PA_RMISSH_CONNECT_TIMEOUT = new PAPropertyInteger( "proactive.communication.rmissh.connect_timeout", false); // Not documented, temporary workaround until 4.3.0 static public PAPropertyString PA_RMISSH_REMOTE_USERNAME = new PAPropertyString( "proactive.communication.rmissh.username", false); // Not documented, temporary workaround until 4.3.0 static public PAPropertyInteger PA_RMISSH_REMOTE_PORT = new PAPropertyInteger( "proactive.communication.rmissh.port", false); /* ------------------------------------ * REMOTE OBJECT - MULTI-PROTOCOL */ /** Expose object using these protocols in addition to the default one (protocols separated by comma) */ public static PAPropertyList PA_COMMUNICATION_ADDITIONAL_PROTOCOLS = new PAPropertyList( "proactive.communication.additional_protocols", ",", false); /** Impose a static order for protocols selection, this automatically deactivate benchmark (protocols separated by comma) */ public static PAPropertyList PA_COMMUNICATION_PROTOCOLS_ORDER = new PAPropertyList( "proactive.communication.protocols.order", ",", false); /** Specify a parameter for benchmark */ public static PAPropertyString PA_BENCHMARK_PARAMETER = new PAPropertyString( "proactive.communication.benchmark.parameter", false); /** The class to use for doing remoteObject Benchmark, must implement BenchmarkObject */ public static PAPropertyString PA_BENCHMARK_CLASS = new PAPropertyString( "proactive.communication.benchmark.class", false, org.objectweb.proactive.core.remoteobject.benchmark.SelectionOnly.class.getName()); /* ------------------------------------ * SECURITY */ /** this property indicates if a RMISecurityManager has to be instanciated*/ static public PAPropertyBoolean PA_SECURITYMANAGER = new PAPropertyBoolean("proactive.securitymanager", false); /** this property indicates the location of the runtime' security manager configuration file */ static public PAPropertyString PA_RUNTIME_SECURITY = new PAPropertyString("proactive.runtime.security", false); /** this property indicates the url of the security domain the runtime depends on */ static public PAPropertyString PA_RUNTIME_DOMAIN_URL = new PAPropertyString( "proactive.runtime.domain.url", false); /* ------------------------------------ * TIMIT */ /** this property indicates the list (comma separated) of the TimIt counters to activate */ static public PAPropertyString PA_TIMIT_ACTIVATION = new PAPropertyString("proactive.timit.activation", false); /* ------------------------------------ * MASTER/WORKER */ /** * Master/Worker ping period in milliseconds * * The ping period is the default interval at which workers receive a ping message * (to check if they're alive). Default to ten seconds */ static public PAPropertyInteger PA_MASTERWORKER_PINGPERIOD = new PAPropertyInteger( "proactive.masterworker.pingperiod", false); /** * Master/Worker compress tasks * * Parameter which decides wether tasks should be compressed when they are saved inside the task repository * compressing increases CPU usage on the master side, but decrease memory usage, default to false */ static public PAPropertyBoolean PA_MASTERWORKER_COMPRESSTASKS = new PAPropertyBoolean( "proactive.masterworker.compresstasks", false); /* ------------------------------------ * DISTRIBUTED GARBAGE COLLECTOR */ /** Enable the distributed garbage collector */ static public PAPropertyBoolean PA_DGC = new PAPropertyBoolean("proactive.dgc", false); /** * TimeToAlone * After this delay, we suppose we got a message from all our referencers. */ static public PAPropertyInteger PA_DGC_TTA = new PAPropertyInteger("proactive.dgc.tta", false); /** * TimeToBroadcast * Time is always in milliseconds. It is fundamental for this value * to be the same in all JVM of the distributed system, so think twice * before changing it. */ static public PAPropertyInteger PA_DGC_TTB = new PAPropertyInteger("proactive.dgc.ttb", false); /* ------------------------------------ * DISTRIBUTED DEBUGGER */ /** Enable the distributed debugger */ static public PAPropertyBoolean PA_DEBUG = new PAPropertyBoolean("proactive.debug", false); /* ------------------------------------ * MULTIACTIVITY */ static public PAPropertyString PA_MULTIACTIVITY_DEFAULT_LOGGING = new PAPropertyString("proactive.multiactivity.defaultlogfolder", false); /* ------------------------------------ * MESSAGE TAGGING */ /** Set the max period for LocalMemoryTag lease time */ static public PAPropertyInteger PA_MAX_MEMORY_TAG_LEASE = new PAPropertyInteger( "proactive.tagmemory.lease.max", false); /** Set the Period of the running thread for tag memory leasing check */ static public PAPropertyInteger PA_MEMORY_TAG_LEASE_PERIOD = new PAPropertyInteger( "proactive.tagmemory.lease.period", false); /** Enable or disable the Distributed Service ID Tag */ static public PAPropertyBoolean PA_TAG_DSF = new PAPropertyBoolean("proactive.tag.dsf", false); /* ------------------------------------ * FILE TRANSFER */ /** * The maximum number of {@link FileTransferService} objects that can be spawned * on a Node to handle file transfer requests in parallel. */ static public PAPropertyInteger PA_FILETRANSFER_MAX_SERVICES = new PAPropertyInteger( "proactive.filetransfer.services_number", false); /** * When sending a file, the maximum number of file blocks (parts) that can * be sent asynchronously before blocking for their arrival. */ static public PAPropertyInteger PA_FILETRANSFER_MAX_SIMULTANEOUS_BLOCKS = new PAPropertyInteger( "proactive.filetransfer.blocks_number", false); /** * The size, in [KB], of file blocks (parts) used to send files. */ static public PAPropertyInteger PA_FILETRANSFER_MAX_BLOCK_SIZE = new PAPropertyInteger( "proactive.filetransfer.blocks_size_kb", false); /** * The size, in [KB], of the buffers to use when reading and writing a file. */ static public PAPropertyInteger PA_FILETRANSFER_MAX_BUFFER_SIZE = new PAPropertyInteger( "proactive.filetransfer.buffer_size_kb", false); // -------------- DATA SPACES /** * This property indicates an access URL to the scratch data space. If scratch is going to be * used on host, this property and/or {@link #PA_DATASPACES_SCRATCH_PATH} should be set. */ static public PAPropertyString PA_DATASPACES_SCRATCH_URL = new PAPropertyString( "proactive.dataspaces.scratch_url", false); /** * This property indicates a location of the scratch data space. If scratch is going to be used * on host, this property and/or {@link #PA_DATASPACES_SCRATCH_URL} should be set. */ static public PAPropertyString PA_DATASPACES_SCRATCH_PATH = new PAPropertyString( "proactive.dataspaces.scratch_path", false); // -------------- VFS PROVIDER /** * This property indicates how often an auto closing mechanism is started to collect and close * all unused streams open trough file system server interface. */ static public PAPropertyInteger PA_VFSPROVIDER_SERVER_STREAM_AUTOCLOSE_CHECKING_INTERVAL_MILLIS = new PAPropertyInteger( "proactive.vfsprovider.server.stream_autoclose_checking_millis", false); /** * This property indicates a period after that a stream is perceived as unused and therefore can * be closed by auto closing mechanism. */ static public PAPropertyInteger PA_VFSPROVIDER_SERVER_STREAM_OPEN_MAXIMUM_PERIOD_MILLIS = new PAPropertyInteger( "proactive.vfsprovider.server.stream_open_maximum_period_millis", false); // -------------- Misc /** * Indicates if a Runtime is running a functional test * * <strong>Internal use</strong> * This property is set to true by the functional test framework. JVM to be killed * after a functional test are found by using this property */ static public PAPropertyBoolean PA_TEST = new PAPropertyBoolean("proactive.test", false); /** Duration of each performance test in ms */ static public PAPropertyInteger PA_TEST_PERF_DURATION = new PAPropertyInteger( "proactive.test.perf.duration", false); /** * Functional test timeout in ms * * If 0 no timeout. */ static public PAPropertyInteger PA_TEST_TIMEOUT = new PAPropertyInteger("proactive.test.timeout", false, 300000); /** * TODO vlegrand Describe this property */ static public PAPropertyString CATALINA_BASE = new PAPropertyString("catalina.base", true); /** * if true, any reference on the reified object within an outgoing request or reply is * replaced by a reference on the active object. This feature can be used when activating * an object whose source code cannot be modified to replace the code that return <code>this</code> * by the reference on the active object using <code>PAActiveObject.getStubOnThis()</code> */ static public PAPropertyBoolean PA_IMPLICITGETSTUBONTHIS = new PAPropertyBoolean( "proactive.implicitgetstubonthis", false); /** * on unix system, define the shell that the GCM deployment invokes when creating new runtimes. */ static public PAPropertyString PA_GCMD_UNIX_SHELL = new PAPropertyString("proactive.gcmd.unix.shell", false); /** * Web services framework * * Suppported value is cxf */ static public PAPropertyString PA_WEBSERVICES_FRAMEWORK = new PAPropertyString( "proactive.webservices.framework", false); /** * Web services: WSDL elementFormDefault attribute * * When creating a web service, the generated WSDL contains an XSD schema which represents * the SOAP message format. This property allows to set the elementFormDefault of this schema * to "qualified" or "unqualified". It is set to false ("unqualified") by default. */ static public PAPropertyBoolean PA_WEBSERVICES_ELEMENTFORMDEFAULT = new PAPropertyBoolean( "proactive.webservices.elementformdefault", false); /** * if true, write the bytecode of the generated stub on the disk * */ static public PAPropertyBoolean PA_MOP_WRITESTUBONDISK = new PAPropertyBoolean( "proactive.mop.writestubondisk", false); /** * Specifies the location where to write the classes generated * using the mop */ static public PAPropertyString PA_MOP_GENERATEDCLASSES_DIR = new PAPropertyString( "proactive.mop.generatedclassesdir", false); /** * activate or not the ping feature in ProActive -- each time a runtime * starts it pings a given web server. */ static public PAPropertyBoolean PA_RUNTIME_PING = new PAPropertyBoolean("proactive.runtime.ping", false, true); /** * the url to ping */ static public PAPropertyString PA_RUNTIME_PING_URL = new PAPropertyString("proactive.runtime.ping.url", false, "http://pinging.activeeon.com/ping.php"); /** * Add Runtime the ability to broadcast their presence on the network */ static public PAPropertyBoolean PA_RUNTIME_BROADCAST = new PAPropertyBoolean( "proactive.runtime.broadcast", false, false); /** * the address to use by the broadcast sockets */ static public PAPropertyString PA_RUNTIME_BROADCAST_ADDRESS = new PAPropertyString( "proactive.runtime.broadcast.address", false, "230.0.1.1"); /** * the port to use by the broadcast sockets */ static public PAPropertyInteger PA_RUNTIME_BROADCAST_PORT = new PAPropertyInteger( "proactive.runtime.broadcast.port", false, 4554); /** * the address to use by the broadcast sockets */ static public PAPropertyString PA_RUNTIME_BROADCAST_CALLBACK_CLASS = new PAPropertyString( "proactive.runtime.broadcast.callback.class", false, BTCallbackDefaultImpl.class.getName()); }
agpl-3.0
Tanaguru/Tanaguru
rules/rgaa2.2/src/test/java/org/tanaguru/rules/rgaa22/Rgaa22Rule02041Test.java
3917
/* * Tanaguru - Automated webpage assessment * Copyright (C) 2008-2015 Tanaguru.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact us by mail: tanaguru AT tanaguru DOT org */ package org.tanaguru.rules.rgaa22; import org.tanaguru.entity.audit.TestSolution; import org.tanaguru.rules.rgaa22.test.Rgaa22RuleImplementationTestCase; /** * Unit test class for the implementation of the rule 2.4 of the referential RGAA 2.2. * * @author jkowalczyk */ public class Rgaa22Rule02041Test extends Rgaa22RuleImplementationTestCase { /** * Default constructor */ public Rgaa22Rule02041Test (String testName){ super(testName); } @Override protected void setUpRuleImplementationClassName() { setRuleImplementationClassName( "org.tanaguru.rules.rgaa22.Rgaa22Rule02041"); } @Override protected void setUpWebResourceMap() { // getWebResourceMap().put("Rgaa22.Test.2.4-1Passed-01", // getWebResourceFactory().createPage( // getTestcasesFilePath() + "rgaa22/Rgaa22Rule02041/RGAA22.Test.2.4-1Passed-01.html")); // getWebResourceMap().put("Rgaa22.Test.2.4-2Failed-01", // getWebResourceFactory().createPage( // getTestcasesFilePath() + "rgaa22/Rgaa22Rule02041/RGAA22.Test.2.4-2Failed-01.html")); // getWebResourceMap().put("Rgaa22.Test.2.4-3NMI-01", // getWebResourceFactory().createPage( // getTestcasesFilePath() + "rgaa22/Rgaa22Rule02041/RGAA22.Test.2.4-3NMI-01.html")); // getWebResourceMap().put("Rgaa22.Test.2.4-4NA-01", // getWebResourceFactory().createPage( // getTestcasesFilePath() + "rgaa22/Rgaa22Rule02041/RGAA22.Test.2.4-4NA-01.html")); getWebResourceMap().put("Rgaa22.Test.2.4-5NT-01", getWebResourceFactory().createPage( getTestcasesFilePath() + "rgaa22/Rgaa22Rule02041/RGAA22.Test.2.4-5NT-01.html")); } @Override protected void setProcess() { // assertEquals(TestSolution.PASSED, // processPageTest("Rgaa22.Test.2.4-1Passed-01").getValue()); // assertEquals(TestSolution.FAILED, // processPageTest("Rgaa22.Test.2.4-2Failed-01").getValue()); // assertEquals(TestSolution.NEED_MORE_INFO, // processPageTest("Rgaa22.Test.2.4-3NMI-01").getValue()); // assertEquals(TestSolution.NOT_APPLICABLE, // processPageTest("Rgaa22.Test.2.4-4NA-01").getValue()); assertEquals(TestSolution.NOT_TESTED, processPageTest("Rgaa22.Test.2.4-5NT-01").getValue()); } @Override protected void setConsolidate() { // assertEquals(TestSolution.PASSED, // consolidate("Rgaa22.Test.2.4-1Passed-01").getValue()); // assertEquals(TestSolution.FAILED, // consolidate("Rgaa22.Test.2.4-2Failed-01").getValue()); // assertEquals(TestSolution.NEED_MORE_INFO, // consolidate("Rgaa22.Test.2.4-3NMI-01").getValue()); // assertEquals(TestSolution.NOT_APPLICABLE, // consolidate("Rgaa22.Test.2.4-4NA-01").getValue()); assertEquals(TestSolution.NOT_TESTED, consolidate("Rgaa22.Test.2.4-5NT-01").getValue()); } }
agpl-3.0
a-gogo/agogo
AMW_rest/src/main/java/ch/mobi/itc/mobiliar/rest/dtos/ResourceWithRelationsDTO.java
1985
/* * AMW - Automated Middleware allows you to manage the configurations of * your Java EE applications on an unlimited number of different environments * with various versions, including the automated deployment of those apps. * Copyright (C) 2013-2016 by Puzzle ITC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.mobi.itc.mobiliar.rest.dtos; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import ch.puzzle.itc.mobiliar.business.resourcegroup.entity.ResourceGroupEntity; import lombok.Data; import lombok.NoArgsConstructor; @XmlRootElement(name = "resource") @XmlAccessorType(XmlAccessType.FIELD) @Data @NoArgsConstructor public class ResourceWithRelationsDTO { private String name; private String type; private String release; private List<ResourceRelationDTO> relations; public ResourceWithRelationsDTO(ResourceGroupEntity resourceGroup, String release, List<ResourceRelationDTO> relations){ this.name = resourceGroup.getName(); this.type = resourceGroup.getResourceType() != null ? resourceGroup.getResourceType().getName(): null; this.release = release; if(relations!=null && !relations.isEmpty()){ this.relations = relations; } } }
agpl-3.0
MicroMappers/Service
mm-media-api/src/main/java/qa/qcri/mm/media/tool/GeoTifSlicer.java
2267
package qa.qcri.mm.media.tool; import org.geotools.utils.coveragetiler.CoverageTiler; import java.io.IOException; import java.util.logging.Level; import qa.qcri.mm.media.dao.MediaPoolDao; import qa.qcri.mm.media.store.LookUp; import java.io.File; import java.util.logging.Logger; /** * Created with IntelliJ IDEA. * User: jlucas * Date: 2/22/15 * Time: 9:53 PM * To change this template use File | Settings | File Templates. */ public class GeoTifSlicer { private final static Logger LOGGER = Logger.getLogger(GeoTifSlicer.class.toString()); public GeoTifSlicer(){} public void addSlicerQueue(String sourceURL){ try{ final CoverageTilerExtended coverageTiler = new CoverageTilerExtended(); coverageTiler.addProcessingEventListener(coverageTiler); File inputLoc = new File(sourceURL); coverageTiler.setInputLocation(inputLoc); coverageTiler.setOutputLocation(getDestinationLocation(inputLoc)); coverageTiler.setTileHeight(LookUp.TILE_HEIGHT); coverageTiler.setTileWidth(LookUp.TILE_WIDTH); final Thread t = new Thread(coverageTiler, inputLoc.getName().replace(".tif","")); t.setPriority(coverageTiler.getPriority()); t.start(); try { t.join(); } catch (InterruptedException e) { LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e); } } catch(Exception e2) { LOGGER.log(Level.SEVERE, e2.getLocalizedMessage(), e2); } } private File getDestinationLocation(File inputLoc) throws IOException { String fileName = inputLoc.getName(); fileName = fileName.replace(".tif",""); String path = inputLoc.getParent() + File.separator + fileName + File.separator + "slice" + File.separator; System.out.print("1" + inputLoc.getAbsolutePath()); System.out.print("2" + inputLoc.getCanonicalPath()); System.out.print("3" + inputLoc.getName()); System.out.print("4" + inputLoc.getParent()); System.out.print("5" + inputLoc.getPath()); File outputLoc = new File(path) ; outputLoc.mkdirs(); return outputLoc; } }
agpl-3.0
accesstest3/cfunambol
modules/email/email-core/src/main/java/com/funambol/email/admin/FormSearchAccountPanel.java
13345
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2006 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ package com.funambol.email.admin; import java.util.ArrayList; import java.awt.Dimension; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.MutableComboBoxModel; import javax.swing.SwingConstants; import javax.swing.border.TitledBorder; import com.funambol.framework.filter.Clause; import com.funambol.framework.filter.AllClause; import com.funambol.framework.filter.LogicalClause; import com.funambol.admin.ui.GuiFactory; import com.funambol.admin.util.ClauseTools; import com.funambol.admin.util.Log; /** * Panel for specifying criteria for account searching. * * @version $Id: FormSearchAccountPanel.java,v 1.1 2008-03-25 11:28:17 gbmiglia Exp $ */ public class FormSearchAccountPanel extends JPanel { // --------------------------------------------------------------- Constants /** columns upon which account search filtering applies */ private static final String PARAM_USER_NAME = "username"; private static final String PARAM_SERVER_DESCRIPTION = "description"; private static final String PARAM_ACTIVATION = "active"; private static final String PARAM_PUSH = "push"; /** acivation combo box item */ private static final String ITEM_ALL = "All"; private static final String ITEM_ACTIVE = "Active"; private static final String ITEM_NONACTIVE = "Non active"; /** push combo box item */ private static final String ITEM_PUSH_ALL = "All"; private static final String ITEM_PUSH_ACTIVE = "Active"; private static final String ITEM_PUSH_NONACTIVE = "Non active"; // ------------------------------------------------------------ Private data // // Visual elements // private JLabel jLUsername = new JLabel(); private JLabel jLServer = new JLabel(); private JLabel jLActive = new JLabel(); private JLabel jLPush = new JLabel(); private JComboBox jCBoxUsername = GuiFactory.getDefaultComboSearch(); private JComboBox jCBoxServerDescription = GuiFactory.getDefaultComboSearch(); private JTextField jTFUsername = new JTextField(); private JTextField jTFServerDescription = new JTextField(); private JComboBox jCBoxActive = new JComboBox(); private JComboBox jCBoxPush = new JComboBox(); /** label for the panel's name */ private JLabel panelName = new JLabel(); /** border to evidence the title of the panel */ private TitledBorder titledBorder1; /** button to search an account */ private JButton jBSearch = new JButton(); /** button to reset form */ private JButton jBReset = new JButton(); // ------------------------------------------------------------ Constructors /** * Creates a new instance of a FormSearchAccountPanel object. */ public FormSearchAccountPanel() { try { jbInit(); } catch (Exception e) { Log.error("Error creating Search Account Panel " + getClass().getName(), e); } } // ---------------------------------------------------------- Public methods //---------------------------------------- // Overrides javax.swing.JComponent method //---------------------------------------- /** * Set size of the panel * @return dimension of the panel */ public Dimension getPreferredSize() { return new Dimension(350, 165); } /** * Add the listener received as parameter to the buttons of the panel * @param actionListener: the listener of the action */ public void addFormActionListener(ActionListener actionListener) { jBSearch.addActionListener(actionListener); } /** * Get textfields' edited values and create a clause with these parameters * @return Clause */ public Clause getClause() { Clause clause = null; // edited value String username = jTFUsername.getText(); String serverDescription = jTFServerDescription.getText(); // combo value String cmbUser = (String)(jCBoxUsername.getSelectedItem()); String cmbServerDescription = (String)(jCBoxServerDescription.getSelectedItem()); String active = (String)jCBoxActive.getSelectedItem(); String push = (String)jCBoxPush.getSelectedItem(); String[] param = null; String[] value = null; String[] operator = null; ArrayList paramList = new ArrayList(); ArrayList valueList = new ArrayList(); ArrayList operatorList = new ArrayList(); int i = 0; if (username.equalsIgnoreCase("") || username.equalsIgnoreCase(null)) { } else { paramList.add(PARAM_USER_NAME); valueList.add(username); operatorList.add(ClauseTools.operatorViewToOperatorValue(cmbUser)); i++; } if (serverDescription.equalsIgnoreCase("") || serverDescription.equalsIgnoreCase(null)) { } else { paramList.add(PARAM_SERVER_DESCRIPTION); valueList.add(serverDescription); operatorList.add(ClauseTools.operatorViewToOperatorValue(cmbServerDescription)); i++; } // combo: activation String activationValue = null; String activationFieldValue = (String)jCBoxActive.getSelectedItem(); if(activationFieldValue == ITEM_ACTIVE) { activationValue = "y"; } else if (activationFieldValue == ITEM_NONACTIVE){ activationValue = "n"; } else if (activationFieldValue == ITEM_ALL) { activationValue = null; } Clause activationClause = null; if(activationValue != null){ paramList.add(PARAM_ACTIVATION); valueList.add(activationValue); operatorList.add(ClauseTools.operatorViewToOperatorValue("Exactly")); } else { activationClause = new AllClause(); } // combo: push String pushValue = null; String pushFieldValue = (String)jCBoxPush.getSelectedItem(); if(pushFieldValue == ITEM_PUSH_ACTIVE) { pushValue = "y"; } else if (pushFieldValue == ITEM_PUSH_NONACTIVE){ pushValue = "n"; } else if (pushFieldValue == ITEM_PUSH_ALL) { pushValue = null; } Clause pushClause = null; if(pushValue != null){ paramList.add(PARAM_PUSH); valueList.add(pushValue); operatorList.add(ClauseTools.operatorViewToOperatorValue("Exactly")); } else { pushClause = new AllClause(); } param = (String[])paramList.toArray(new String[0]); value = (String[])valueList.toArray(new String[0]); operator = (String[])operatorList.toArray(new String[0]); clause = ClauseTools.createClause(param, operator, value); if (activationClause != null && !(activationClause instanceof AllClause)){ Clause[] clauses = {activationClause, clause}; clause = new LogicalClause(LogicalClause.OPT_AND, clauses); } if (pushClause != null && !(pushClause instanceof AllClause)){ Clause[] clauses = {pushClause, clause}; clause = new LogicalClause(LogicalClause.OPT_AND, clauses); } return clause; } // --------------------------------------------------------- Private methods /** * Initializes visual elements. * * @throws Exception if error occures during creation of the panel */ private void jbInit() throws Exception { this.setLayout(null); titledBorder1 = new TitledBorder(""); this.setBorder(BorderFactory.createEmptyBorder()); panelName.setFont(GuiFactory.titlePanelFont); panelName.setText("Accounts"); panelName.setBounds(new Rectangle(0, 5, 316, 28)); panelName.setAlignmentX(SwingConstants.CENTER); panelName.setBorder(titledBorder1); MutableComboBoxModel jCBoxActiveModel = new DefaultComboBoxModel(); jCBoxActiveModel.addElement(ITEM_ALL); jCBoxActiveModel.addElement(ITEM_ACTIVE); jCBoxActiveModel.addElement(ITEM_NONACTIVE); jCBoxActive.setModel(jCBoxActiveModel); MutableComboBoxModel jCBoxPushModel = new DefaultComboBoxModel(); jCBoxPushModel.addElement(ITEM_PUSH_ALL); jCBoxPushModel.addElement(ITEM_PUSH_ACTIVE); jCBoxPushModel.addElement(ITEM_PUSH_NONACTIVE); jCBoxPush.setModel(jCBoxPushModel); jLUsername.setText("Username"); jLServer.setText("Server description"); jLActive.setText("Activation"); jLPush.setText("Push"); jLUsername.setBounds(new Rectangle(0, 53, 76, 20)); jLServer.setBounds (new Rectangle(0, 78, 90, 20)); jLActive.setBounds (new Rectangle(0, 103, 76, 20)); jLPush.setBounds (new Rectangle(0, 128, 76, 20)); jCBoxUsername.setBounds (new Rectangle(98, 53, 92, 20)); jCBoxServerDescription.setBounds(new Rectangle(98, 78, 92, 20)); jCBoxActive.setBounds (new Rectangle(98, 103, 92, 20)); jCBoxPush.setBounds (new Rectangle(98, 128, 92, 20)); jTFUsername.setBounds (new Rectangle(198, 53, 151, 20)); jTFServerDescription.setBounds(new Rectangle(198, 78, 151, 20)); jBSearch.setBounds(new Rectangle(467, 53, 88, 23)); jBSearch.setText("Search"); jBSearch.setActionCommand("ACTION_COMMAND_SEARCH_ACCOUNT"); jBReset.setBounds(new Rectangle(367, 53, 88, 23)); jBReset.setText("Reset"); jBReset.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { reset(); } }); jLUsername.setFont(GuiFactory.defaultFont); jLServer.setFont(GuiFactory.defaultFont); jLActive.setFont(GuiFactory.defaultFont); jLPush.setFont(GuiFactory.defaultFont); jCBoxUsername.setFont(GuiFactory.defaultFont); jCBoxServerDescription.setFont(GuiFactory.defaultFont); jTFUsername.setFont(GuiFactory.defaultFont); jTFServerDescription.setFont(GuiFactory.defaultFont); jCBoxActive.setFont(GuiFactory.defaultFont); jCBoxPush.setFont(GuiFactory.defaultFont); jBSearch.setFont(GuiFactory.defaultFont); jBReset.setFont(GuiFactory.defaultFont); add(panelName , null); add(jLUsername, null); add(jLServer, null); add(jLActive, null); add(jLPush, null); add(jCBoxUsername, null); add(jCBoxServerDescription, null); add(jTFUsername, null); add(jTFServerDescription, null); add(jCBoxActive, null); add(jCBoxPush, null); add(jBSearch, null); add(jBReset, null); } /** * Clears panel fields. */ private void reset() { jCBoxUsername.setSelectedIndex(0); jCBoxServerDescription.setSelectedIndex(0); jCBoxActive.setSelectedIndex(0); jCBoxPush.setSelectedIndex(0); jTFUsername.setText(""); jTFServerDescription.setText(""); } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/core/vo/lookups/DocumentEmailStatusCollection.java
4977
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.core.vo.lookups; import ims.framework.cn.data.TreeModel; import ims.framework.cn.data.TreeNode; import ims.vo.LookupInstanceCollection; import ims.vo.LookupInstVo; public class DocumentEmailStatusCollection extends LookupInstanceCollection implements ims.vo.ImsCloneable, TreeModel { private static final long serialVersionUID = 1L; public void add(DocumentEmailStatus value) { super.add(value); } public int indexOf(DocumentEmailStatus instance) { return super.indexOf(instance); } public boolean contains(DocumentEmailStatus instance) { return indexOf(instance) >= 0; } public DocumentEmailStatus get(int index) { return (DocumentEmailStatus)super.getIndex(index); } public void remove(DocumentEmailStatus instance) { if(instance != null) { int index = indexOf(instance); if(index >= 0) remove(index); } } public Object clone() { DocumentEmailStatusCollection newCol = new DocumentEmailStatusCollection(); DocumentEmailStatus item; for (int i = 0; i < super.size(); i++) { item = this.get(i); newCol.add(new DocumentEmailStatus(item.getID(), item.getText(), item.isActive(), item.getParent(), item.getImage(), item.getColor(), item.getOrder())); } for (int i = 0; i < newCol.size(); i++) { item = newCol.get(i); if (item.getParent() != null) { int parentIndex = this.indexOf(item.getParent()); if(parentIndex >= 0) item.setParent(newCol.get(parentIndex)); else item.setParent((DocumentEmailStatus)item.getParent().clone()); } } return newCol; } public DocumentEmailStatus getInstance(int instanceId) { return (DocumentEmailStatus)super.getInstanceById(instanceId); } public TreeNode[] getRootNodes() { LookupInstVo[] roots = super.getRoots(); TreeNode[] nodes = new TreeNode[roots.length]; System.arraycopy(roots, 0, nodes, 0, roots.length); return nodes; } public DocumentEmailStatus[] toArray() { DocumentEmailStatus[] arr = new DocumentEmailStatus[this.size()]; super.toArray(arr); return arr; } public static DocumentEmailStatusCollection buildFromBeanCollection(java.util.Collection beans) { DocumentEmailStatusCollection coll = new DocumentEmailStatusCollection(); if(beans == null) return coll; java.util.Iterator iter = beans.iterator(); while(iter.hasNext()) { coll.add(DocumentEmailStatus.buildLookup((ims.vo.LookupInstanceBean)iter.next())); } return coll; } public static DocumentEmailStatusCollection buildFromBeanCollection(ims.vo.LookupInstanceBean[] beans) { DocumentEmailStatusCollection coll = new DocumentEmailStatusCollection(); if(beans == null) return coll; for(int x = 0; x < beans.length; x++) { coll.add(DocumentEmailStatus.buildLookup(beans[x])); } return coll; } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/oncology/vo/lookups/RadiotherapyDelayReason.java
5534
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.oncology.vo.lookups; import ims.framework.cn.data.TreeNode; import java.util.ArrayList; import ims.framework.utils.Image; import ims.framework.utils.Color; public class RadiotherapyDelayReason extends ims.vo.LookupInstVo implements TreeNode { private static final long serialVersionUID = 1L; public RadiotherapyDelayReason() { super(); } public RadiotherapyDelayReason(int id) { super(id, "", true); } public RadiotherapyDelayReason(int id, String text, boolean active) { super(id, text, active, null, null, null); } public RadiotherapyDelayReason(int id, String text, boolean active, RadiotherapyDelayReason parent, Image image) { super(id, text, active, parent, image); } public RadiotherapyDelayReason(int id, String text, boolean active, RadiotherapyDelayReason parent, Image image, Color color) { super(id, text, active, parent, image, color); } public RadiotherapyDelayReason(int id, String text, boolean active, RadiotherapyDelayReason parent, Image image, Color color, int order) { super(id, text, active, parent, image, color, order); } public static RadiotherapyDelayReason buildLookup(ims.vo.LookupInstanceBean bean) { return new RadiotherapyDelayReason(bean.getId(), bean.getText(), bean.isActive()); } public String toString() { if(getText() != null) return getText(); return ""; } public TreeNode getParentNode() { return (RadiotherapyDelayReason)super.getParentInstance(); } public RadiotherapyDelayReason getParent() { return (RadiotherapyDelayReason)super.getParentInstance(); } public void setParent(RadiotherapyDelayReason parent) { super.setParentInstance(parent); } public TreeNode[] getChildren() { ArrayList children = super.getChildInstances(); RadiotherapyDelayReason[] typedChildren = new RadiotherapyDelayReason[children.size()]; for (int i = 0; i < children.size(); i++) { typedChildren[i] = (RadiotherapyDelayReason)children.get(i); } return typedChildren; } public int addChild(TreeNode child) { if (child instanceof RadiotherapyDelayReason) { super.addChild((RadiotherapyDelayReason)child); } return super.getChildInstances().size(); } public int removeChild(TreeNode child) { if (child instanceof RadiotherapyDelayReason) { super.removeChild((RadiotherapyDelayReason)child); } return super.getChildInstances().size(); } public Image getExpandedImage() { return super.getImage(); } public Image getCollapsedImage() { return super.getImage(); } public static ims.framework.IItemCollection getNegativeInstancesAsIItemCollection() { RadiotherapyDelayReasonCollection result = new RadiotherapyDelayReasonCollection(); return result; } public static RadiotherapyDelayReason[] getNegativeInstances() { return new RadiotherapyDelayReason[] {}; } public static String[] getNegativeInstanceNames() { return new String[] {}; } public static RadiotherapyDelayReason getNegativeInstance(String name) { if(name == null) return null; // No negative instances found return null; } public static RadiotherapyDelayReason getNegativeInstance(Integer id) { if(id == null) return null; // No negative instances found return null; } public int getTypeId() { return TYPE_ID; } public static final int TYPE_ID = 1251102; }
agpl-3.0
youribonnaffe/scheduling
rm/rm-server/src/main/java/org/ow2/proactive/resourcemanager/nodesource/infrastructure/AutoUpdateInfrastructure.java
7756
package org.ow2.proactive.resourcemanager.nodesource.infrastructure; import org.objectweb.proactive.core.node.Node; import org.objectweb.proactive.core.util.ProActiveCounter; import org.ow2.proactive.process_tree_killer.ProcessTree; import org.ow2.proactive.resourcemanager.exception.RMException; import org.ow2.proactive.resourcemanager.nodesource.common.Configurable; import org.ow2.proactive.utils.Formatter; import java.io.IOException; import java.net.InetAddress; import java.security.KeyException; import java.util.Properties; /** * * This infrastructure launching a node by download node.jar on a node machine. * Command to start a node can be tuned by client. * */ public class AutoUpdateInfrastructure extends HostsFileBasedInfrastructureManager { public static final String CLI_FILE_PROPERTY = "cli.file.property"; public static final String NODE_NAME = "node.name"; public static final String HOST_NAME = "host.name"; public static final String NODESOURCE_NAME = "nodesource.name"; public static final String NODESOURCE_CREDENTIALS = "nodesource.credentials"; @Configurable(description = "Command that will be launched for every host") protected String command = "scp -o StrictHostKeyChecking=no ${pa.rm.home}/dist/war/rest/node.jar ${host.name}:/tmp/${node.name}.jar && " + "ssh -o StrictHostKeyChecking=no ${host.name} " + "\"${java.home}/bin/java -jar /tmp/${node.name}.jar -v ${nodesource.credentials} -n ${node.name} -s ${nodesource.name} -p 30000 -r ${rm.url} " + "1>>/tmp/${node.name}.log 2>&1\""; @Override public void configure(Object... parameters) { super.configure(parameters); if (parameters != null && parameters.length >= 3) { this.command = parameters[3].toString(); } } /** * Internal node acquisition method * <p> * Starts a PA runtime on remote host using a custom script, register it manually in the * nodesource. * * @param host hostname of the node on which a node should be started * @throws org.ow2.proactive.resourcemanager.exception.RMException acquisition failed */ protected void startNodeImpl(InetAddress host) throws RMException { final String nodeName = this.nodeSource.getName() + "-" + ProActiveCounter.getUniqID(); String credentials = ""; try { credentials = new String(nodeSource.getAdministrator().getCredentials().getBase64()); } catch (KeyException e) { logger.error("Invalid credentials"); return; } Properties localProperties = new Properties(); localProperties.put(NODE_NAME, nodeName); localProperties.put(HOST_NAME, host.getHostName()); localProperties.put(NODESOURCE_CREDENTIALS, credentials); localProperties.put(NODESOURCE_NAME, nodeSource.getName()); String filledCommand = replaceProperties(command, localProperties); filledCommand = replaceProperties(filledCommand, System.getProperties()); final String pnURL = super.addDeployingNode(nodeName, filledCommand, "Deploying node on host " + host, this.nodeTimeOut); this.pnTimeout.put(pnURL, new Boolean(false)); Process p; try { logger.debug("Deploying node: " + nodeName); logger.debug("Launching the command: " + filledCommand); p = Runtime.getRuntime().exec(new String[] { "bash", "-c", filledCommand }); } catch (IOException e1) { super.declareDeployingNodeLost(pnURL, "Cannot run command: " + filledCommand + " - \n The following exception occurred: " + Formatter.stackTraceToString(e1)); throw new RMException("Cannot run command: " + filledCommand, e1); } String lf = System.lineSeparator(); int circuitBreakerThreshold = 5; while (!this.pnTimeout.get(pnURL) && circuitBreakerThreshold > 0) { try { int exitCode = p.exitValue(); if (exitCode != 0) { logger.error("Child process at " + host.getHostName() + " exited abnormally (" + exitCode + ")."); } else { logger.error("Launching node script has exited normally whereas it shouldn't."); } String pOutPut = Utils.extractProcessOutput(p); String pErrPut = Utils.extractProcessErrput(p); final String description = "Script failed to launch a node on host " + host.getHostName() + lf + " >Error code: " + exitCode + lf + " >Errput: " + pErrPut + " >Output: " + pOutPut; logger.error(description); if (super.checkNodeIsAcquiredAndDo(nodeName, null, new Runnable() { public void run() { AutoUpdateInfrastructure.this.declareDeployingNodeLost(pnURL, description); } })) { return; } else { //there isn't any race regarding node registration throw new RMException("A node " + nodeName + " is not expected anymore because of an error."); } } catch (IllegalThreadStateException e) { logger.trace("IllegalThreadStateException while waiting for " + nodeName + " registration"); } if (super.checkNodeIsAcquiredAndDo(nodeName, null, null)) { //registration is ok, we destroy the process logger.debug("Destroying the process: " + p); try { ProcessTree.get().get(p).kill(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return; } try { Thread.sleep(1000); } catch (Exception e) { circuitBreakerThreshold--; logger.trace("An exception occurred while monitoring a child process", e); } } //if we exit because of a timeout if (this.pnTimeout.get(pnURL)) { //we remove it this.pnTimeout.remove(pnURL); //we destroy the process p.destroy(); throw new RMException("Deploying Node " + nodeName + " not expected any more"); } if (circuitBreakerThreshold <= 0) { logger.error("Circuit breaker threshold reached while monitoring a child process."); throw new RMException("Several exceptions occurred while monitoring a child process."); } } private String replaceProperties(String commandLine, Properties properties) { for (Object prop : properties.keySet()) { String propName = "${" + prop + "}"; String propValue = properties.getProperty(prop.toString()); if (propValue != null) { commandLine = commandLine.replace(propName, propValue); } } return commandLine; } @Override protected void killNodeImpl(Node node, InetAddress host) throws RMException { } /** * @return short description of the IM */ public String getDescription() { return "In order to deploy a node this infrastructure ssh to a computer and uses wget to download proactive node distribution. It keep nodes always up-to-dated and does not require pre-installed proactive on a node machine."; } /** * {@inheritDoc} */ @Override public String toString() { return "AutoUpdate Infrastructure"; } }
agpl-3.0
Tanaguru/Tanaguru
web-app/tgol-report/src/main/java/org/tanaguru/webapp/report/pagination/TgolPaginatedListImpl.java
3969
/* * Tanaguru - Automated webpage assessment * Copyright (C) 2008-2015 Tanaguru.org * * This file is part of Tanaguru. * * Tanaguru is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact us by mail: tanaguru AT tanaguru DOT org */ package org.tanaguru.webapp.report.pagination; import org.tanaguru.webapp.presentation.data.PageResult; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.displaytag.pagination.PaginatedList; import org.displaytag.properties.SortOrderEnum; /** * This private class is an implementation of the PaginatedList interface * of the display tag API. This class is needed to realize sorting and * pagination on server side. * * @author jkowalczyk */ public class TgolPaginatedListImpl implements PaginatedList { /** * * @param defaultSortCriterion */ public TgolPaginatedListImpl(String defaultSortCriterion) { this.sortCriterion = defaultSortCriterion; } private List<PageResult> elementsList = new ArrayList<PageResult>(); /** * * @return */ @Override public List getList() { return elementsList; } /** * * @param elementsList */ public void setElementsList(List elementsList) { this.elementsList = elementsList; } /** * * @param elementsList */ public void addAllElements(Collection elementsList) { this.elementsList.addAll(elementsList); } private int pageNumber; /** * * @return */ @Override public int getPageNumber() { return pageNumber; } /** * * @param pageNumber */ public void setPageNumber(int pageNumber) { this.pageNumber = pageNumber; } private int objectsPerPage; /** * * @return */ @Override public int getObjectsPerPage() { return objectsPerPage; } /** * * @param objectsPerPage */ public void setObjectsPerPage(int objectsPerPage) { this.objectsPerPage = objectsPerPage; } private int fullListSize; /** * * @return */ @Override public int getFullListSize() { return fullListSize; } /** * * @param fullListSize */ public void setFullListSize(int fullListSize) { this.fullListSize = fullListSize; } private String sortCriterion; /** * * @return */ @Override public String getSortCriterion() { return sortCriterion; } /** * * @param sortCriterion */ public void setSortCriterion(String sortCriterion) { this.sortCriterion = sortCriterion; } private SortOrderEnum sortDirection = SortOrderEnum.ASCENDING; /** * * @return */ @Override public SortOrderEnum getSortDirection() { return sortDirection; } /** * * @param sortDirection */ public void setSortDirection(SortOrderEnum sortDirection) { this.sortDirection = sortDirection; } private String searchId; /** * * @return */ @Override public String getSearchId() { return searchId; } /** * * @param searchId */ public void setSearchId(String searchId) { this.searchId = searchId; } }
agpl-3.0
papparazzo/moba-server
src/main/java/moba/server/utilities/config/Config.java
2887
/* * Project: moba-server * * Copyright (C) 2016 Stefan Paproth <pappi-@gmx.de> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/agpl.txt>. * */ package moba.server.utilities.config; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import moba.server.json.JSONException; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; public class Config { protected String fileName; protected Map<String, Object> content; public Config(String fileName) throws IOException, JSONException { InputStream is = new FileInputStream(fileName); this.fileName = fileName; Yaml yaml = new Yaml(); content = (Map<String, Object>)yaml.load(is); } public void writeFile() throws IOException, JSONException { DumperOptions options = new DumperOptions(); options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); options.setIndent(4); Yaml yaml = new Yaml(options); yaml.dump(content, new FileWriter(this.fileName)); } public Object getSection(String expr) { if(content == null || content.isEmpty()) { return null; } String tokens[] = expr.split("\\."); Object o = content; for(String s : tokens) { Map<String, Object> map = (Map<String, Object>)o; if(map == null) { return null; } o = map.get(s); } if(o != null && o.getClass() == Integer.class) { o = (long)Long.valueOf((Integer)o); } return o; } public void setSection(String section, Object val) throws ConfigException { if(content == null) { content = new HashMap<>(); } content.put(section, val); } public boolean removeSection(String section) throws ConfigException { if(content == null) { throw new ConfigException("object is null"); } return (content.remove(section) != null); } public boolean sectionExists(String section) { return (getSection(section) != null); } }
agpl-3.0
JuliaSoboleva/SmartReceiptsLibrary
core/src/main/java/co/smartreceipts/core/identity/apis/login/LoginPayload.java
639
package co.smartreceipts.core.identity.apis.login; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.gson.annotations.SerializedName; import java.io.Serializable; public class LoginPayload implements Serializable { @SerializedName("login_params") private final UserCredentialsPayload userCredentialsPayload; public LoginPayload(@NonNull UserCredentialsPayload userCredentialsPayload) { this.userCredentialsPayload = userCredentialsPayload; } @Nullable public UserCredentialsPayload getUserCredentialsPayload() { return userCredentialsPayload; } }
agpl-3.0
auroreallibe/Silverpeas-Components
classifieds/classifieds-war/src/main/java/org/silverpeas/components/classifieds/servlets/handler/MyClassifiedsHandler.java
2145
/* * Copyright (C) 2000 - 2014 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have recieved a copy of the text describing * the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/docs/core/legal/floss_exception.html" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.silverpeas.components.classifieds.servlets.handler; import org.silverpeas.components.classifieds.control.ClassifiedsSessionController; import org.silverpeas.components.classifieds.model.ClassifiedDetail; import org.silverpeas.components.classifieds.servlets.FunctionHandler; import org.silverpeas.core.web.http.HttpRequest; import java.util.Collection; /** * Use Case : for publisher, show own classifieds * * @author Ludovic Bertin * */ public class MyClassifiedsHandler extends FunctionHandler { @Override public String getDestination(ClassifiedsSessionController classifiedsSC, HttpRequest request) throws Exception{ // Retrieve user own classifieds Collection<ClassifiedDetail> classifieds = classifiedsSC.getClassifiedsByUser(); // Stores objects in request request.setAttribute("Classifieds", classifieds); request.setAttribute("TitlePath", "classifieds.myClassifieds"); // Returns jsp to redirect to return "classifieds.jsp"; } }
agpl-3.0
mjshepherd/phenotips
components/patient-data-sharing/push-api/src/main/java/org/phenotips/data/push/internal/DefaultPushServerSendPatientResponse.java
2348
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/ */ package org.phenotips.data.push.internal; import org.phenotips.data.push.PushServerSendPatientResponse; import org.phenotips.data.shareprotocol.ShareProtocol; import org.json.JSONObject; public class DefaultPushServerSendPatientResponse extends DefaultPushServerGetPatientIDResponse implements PushServerSendPatientResponse { DefaultPushServerSendPatientResponse(JSONObject serverResponse) { super(serverResponse); } @Override public boolean isActionFailed_incorrectGroup() { return hasKeySetToTrue(ShareProtocol.SERVER_JSON_KEY_NAME_ERROR_INCORRECTGROUP); } @Override public boolean isActionFailed_UpdatesDisabled() { return hasKeySetToTrue(ShareProtocol.SERVER_JSON_KEY_NAME_ERROR_UPDATESDISABLED); } @Override public boolean isActionFailed_IncorrectGUID() { return hasKeySetToTrue(ShareProtocol.SERVER_JSON_KEY_NAME_ERROR_INCORRECTGUID); } @Override public boolean isActionFailed_GUIDAccessDenied() { return hasKeySetToTrue(ShareProtocol.SERVER_JSON_KEY_NAME_ERROR_GUIDACCESSDENIED); } @Override public boolean isActionFailed_MissingConsent() { return hasKeySetToTrue(ShareProtocol.SERVER_JSON_KEY_NAME_ERROR_MISSINGCONSENT); } @Override public boolean isActionFailed_knownReason() { return (super.isActionFailed_knownReason() || isActionFailed_incorrectGroup() || isActionFailed_UpdatesDisabled() || isActionFailed_IncorrectGUID() || isActionFailed_GUIDAccessDenied()); } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/DomainObjects/src/ims/oncology/configuration/domain/objects/TumourHistology.java
14558
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH /* * This code was generated * Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved. * IMS Development Environment (version 1.80 build 5589.25814) * WARNING: DO NOT MODIFY the content of this file * Generated: 12/10/2015, 13:28 * */ package ims.oncology.configuration.domain.objects; /** * * @author Kevin O'Carroll * Generated. */ public class TumourHistology extends ims.domain.DomainObject implements ims.domain.SystemInformationRetainer, java.io.Serializable { public static final int CLASSID = 1074100012; private static final long serialVersionUID = 1074100012L; public static final String CLASSVERSION = "${ClassVersion}"; @Override public boolean shouldCapQuery() { return true; } /** HistologyDescription */ private String histologyDescription; /** TaxonomyMap * Collection of ims.core.clinical.domain.objects.TaxonomyMap. */ private java.util.List taxonomyMap; /** isActive */ private Boolean isActive; /** SystemInformation */ private ims.domain.SystemInformation systemInformation = new ims.domain.SystemInformation(); public TumourHistology (Integer id, int ver) { super(id, ver); } public TumourHistology () { super(); } public TumourHistology (Integer id, int ver, Boolean includeRecord) { super(id, ver, includeRecord); } public Class getRealDomainClass() { return ims.oncology.configuration.domain.objects.TumourHistology.class; } public String getHistologyDescription() { return histologyDescription; } public void setHistologyDescription(String histologyDescription) { if ( null != histologyDescription && histologyDescription.length() > 100 ) { throw new ims.domain.exceptions.DomainRuntimeException("MaxLength ($MaxLength) exceeded for histologyDescription. Tried to set value: "+ histologyDescription); } this.histologyDescription = histologyDescription; } public java.util.List getTaxonomyMap() { if ( null == taxonomyMap ) { taxonomyMap = new java.util.ArrayList(); } return taxonomyMap; } public void setTaxonomyMap(java.util.List paramValue) { this.taxonomyMap = paramValue; } public Boolean isIsActive() { return isActive; } public void setIsActive(Boolean isActive) { this.isActive = isActive; } public ims.domain.SystemInformation getSystemInformation() { if (systemInformation == null) systemInformation = new ims.domain.SystemInformation(); return systemInformation; } /** * isConfigurationObject * Taken from the Usage property of the business object, this method will return * a boolean indicating whether this is a configuration object or not * Configuration = true, Instantiation = false */ public static boolean isConfigurationObject() { if ( "Configuration".equals("Configuration") ) return true; else return false; } public int getClassId() { return CLASSID; } public String getClassVersion() { return CLASSVERSION; } public String toAuditString() { StringBuffer auditStr = new StringBuffer(); auditStr.append("\r\n*histologyDescription* :"); auditStr.append(histologyDescription); auditStr.append("; "); auditStr.append("\r\n*taxonomyMap* :"); if (taxonomyMap != null) { int i2=0; for (i2=0; i2<taxonomyMap.size(); i2++) { if (i2 > 0) auditStr.append(","); ims.core.clinical.domain.objects.TaxonomyMap obj = (ims.core.clinical.domain.objects.TaxonomyMap)taxonomyMap.get(i2); if (obj != null) { if (i2 == 0) { auditStr.append(toShortClassName(obj)); auditStr.append("["); } auditStr.append(obj.toString()); } } if (i2 > 0) auditStr.append("] " + i2); } auditStr.append("; "); auditStr.append("\r\n*isActive* :"); auditStr.append(isActive); auditStr.append("; "); return auditStr.toString(); } public String toXMLString() { return toXMLString(new java.util.HashMap()); } public String toXMLString(java.util.HashMap domMap) { StringBuffer sb = new StringBuffer(); sb.append("<class type=\"" + this.getClass().getName() + "\" "); sb.append(" id=\"" + this.getId() + "\""); sb.append(" source=\"" + ims.configuration.EnvironmentConfig.getImportExportSourceName() + "\" "); sb.append(" classVersion=\"" + this.getClassVersion() + "\" "); sb.append(" component=\"" + this.getIsComponentClass() + "\" >"); if (domMap.get(this) == null) { domMap.put(this, this); sb.append(this.fieldsToXMLString(domMap)); } sb.append("</class>"); String keyClassName = "TumourHistology"; String externalSource = ims.configuration.EnvironmentConfig.getImportExportSourceName(); ims.configuration.ImportedObject impObj = (ims.configuration.ImportedObject)domMap.get(keyClassName + "_" + externalSource + "_" + this.getId()); if (impObj == null) { impObj = new ims.configuration.ImportedObject(); impObj.setExternalId(this.getId()); impObj.setExternalSource(externalSource); impObj.setDomainObject(this); impObj.setLocalId(this.getId()); impObj.setClassName(keyClassName); domMap.put(keyClassName + "_" + externalSource + "_" + this.getId(), impObj); } return sb.toString(); } public String fieldsToXMLString(java.util.HashMap domMap) { StringBuffer sb = new StringBuffer(); if (this.getHistologyDescription() != null) { sb.append("<histologyDescription>"); sb.append(ims.framework.utils.StringUtils.encodeXML(this.getHistologyDescription().toString())); sb.append("</histologyDescription>"); } if (this.getTaxonomyMap() != null) { if (this.getTaxonomyMap().size() > 0 ) { sb.append("<taxonomyMap>"); sb.append(ims.domain.DomainObject.toXMLString(this.getTaxonomyMap(), domMap)); sb.append("</taxonomyMap>"); } } if (this.isIsActive() != null) { sb.append("<isActive>"); sb.append(ims.framework.utils.StringUtils.encodeXML(this.isIsActive().toString())); sb.append("</isActive>"); } return sb.toString(); } public static java.util.List fromListXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.List list, java.util.HashMap domMap) throws Exception { if (list == null) list = new java.util.ArrayList(); fillListFromXMLString(list, el, factory, domMap); return list; } public static java.util.Set fromSetXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.Set set, java.util.HashMap domMap) throws Exception { if (set == null) set = new java.util.HashSet(); fillSetFromXMLString(set, el, factory, domMap); return set; } private static void fillSetFromXMLString(java.util.Set set, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { if (el == null) return; java.util.List cl = el.elements("class"); int size = cl.size(); java.util.Set newSet = new java.util.HashSet(); for(int i=0; i<size; i++) { org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i); TumourHistology domainObject = getTumourHistologyfromXML(itemEl, factory, domMap); if (domainObject == null) { continue; } //Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add) if (!set.contains(domainObject)) set.add(domainObject); newSet.add(domainObject); } java.util.Set removedSet = new java.util.HashSet(); java.util.Iterator iter = set.iterator(); //Find out which objects need to be removed while (iter.hasNext()) { ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next(); if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o)) { removedSet.add(o); } } iter = removedSet.iterator(); //Remove the unwanted objects while (iter.hasNext()) { set.remove(iter.next()); } } private static void fillListFromXMLString(java.util.List list, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { if (el == null) return; java.util.List cl = el.elements("class"); int size = cl.size(); for(int i=0; i<size; i++) { org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i); TumourHistology domainObject = getTumourHistologyfromXML(itemEl, factory, domMap); if (domainObject == null) { continue; } int domIdx = list.indexOf(domainObject); if (domIdx == -1) { list.add(i, domainObject); } else if (i != domIdx && i < list.size()) { Object tmp = list.get(i); list.set(i, list.get(domIdx)); list.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int i1=list.size(); while (i1 > size) { list.remove(i1-1); i1=list.size(); } } public static TumourHistology getTumourHistologyfromXML(String xml, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { org.dom4j.Document doc = new org.dom4j.io.SAXReader().read(new org.xml.sax.InputSource(xml)); return getTumourHistologyfromXML(doc.getRootElement(), factory, domMap); } public static TumourHistology getTumourHistologyfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { if (el == null) return null; String className = el.attributeValue("type"); if (!TumourHistology.class.getName().equals(className)) { Class clz = Class.forName(className); if (!TumourHistology.class.isAssignableFrom(clz)) throw new Exception("Element of type = " + className + " cannot be imported using the TumourHistology class"); String shortClassName = className.substring(className.lastIndexOf(".")+1); String methodName = "get" + shortClassName + "fromXML"; java.lang.reflect.Method m = clz.getMethod(methodName, new Class[]{org.dom4j.Element.class, ims.domain.DomainFactory.class, java.util.HashMap.class}); return (TumourHistology)m.invoke(null, new Object[]{el, factory, domMap}); } String impVersion = el.attributeValue("classVersion"); if(!impVersion.equals(TumourHistology.CLASSVERSION)) { throw new Exception("Incompatible class structure found. Cannot import instance."); } TumourHistology ret = null; int extId = Integer.parseInt(el.attributeValue("id")); String externalSource = el.attributeValue("source"); ret = (TumourHistology)factory.getImportedDomainObject(TumourHistology.class, externalSource, extId); if (ret == null) { ret = new TumourHistology(); } String keyClassName = "TumourHistology"; ims.configuration.ImportedObject impObj = (ims.configuration.ImportedObject)domMap.get(keyClassName + "_" + externalSource + "_" + extId); if (impObj != null) { return (TumourHistology)impObj.getDomainObject(); } else { impObj = new ims.configuration.ImportedObject(); impObj.setExternalId(extId); impObj.setExternalSource(externalSource); impObj.setDomainObject(ret); domMap.put(keyClassName + "_" + externalSource + "_" + extId, impObj); } fillFieldsfromXML(el, factory, ret, domMap); return ret; } public static void fillFieldsfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, TumourHistology obj, java.util.HashMap domMap) throws Exception { org.dom4j.Element fldEl; fldEl = el.element("histologyDescription"); if(fldEl != null) { obj.setHistologyDescription(new String(fldEl.getTextTrim())); } fldEl = el.element("taxonomyMap"); if(fldEl != null) { fldEl = fldEl.element("list"); obj.setTaxonomyMap(ims.core.clinical.domain.objects.TaxonomyMap.fromListXMLString(fldEl, factory, obj.getTaxonomyMap(), domMap)); } fldEl = el.element("isActive"); if(fldEl != null) { obj.setIsActive(new Boolean(fldEl.getTextTrim())); } } public static String[] getCollectionFields() { return new String[]{ "taxonomyMap" }; } public static class FieldNames { public static final String ID = "id"; public static final String HistologyDescription = "histologyDescription"; public static final String TaxonomyMap = "taxonomyMap"; public static final String IsActive = "isActive"; } }
agpl-3.0
kelvinmbwilo/vims
modules/report/src/main/java/org/openlmis/report/service/MailingLabelReportDataProvider.java
6355
/* * This program was produced for the U.S. Agency for International Development. It was prepared by the USAID | DELIVER PROJECT, Task Order 4. It is part of a project which utilizes code originally licensed under the terms of the Mozilla Public License (MPL) v2 and therefore is licensed under MPL v2 or later. * * This program is free software: you can redistribute it and/or modify it under the terms of the Mozilla Public License as published by the Mozilla Foundation, either version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Mozilla Public License for more details. * * You should have received a copy of the Mozilla Public License along with this program. If not, see http://www.mozilla.org/MPL/ */ package org.openlmis.report.service; import lombok.NoArgsConstructor; import org.apache.ibatis.session.RowBounds; import org.openlmis.core.domain.Facility; import org.openlmis.core.repository.mapper.GeographicZoneMapper; import org.openlmis.core.service.FacilityService; import org.openlmis.core.service.ProgramService; import org.openlmis.report.mapper.MailingLabelReportMapper; import org.openlmis.report.mapper.lookup.FacilityTypeReportMapper; import org.openlmis.report.model.params.MailingLabelReportParam; import org.openlmis.report.model.report.MailingLabelReport; import org.openlmis.report.model.ReportData; import org.openlmis.report.model.sorter.MailingLabelReportSorter; import org.openlmis.report.util.StringHelper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; import java.util.Map; @Component @NoArgsConstructor public class MailingLabelReportDataProvider extends ReportDataProvider { @Autowired private FacilityService facilityService; @Autowired private MailingLabelReportMapper mailingLabelReportMapper; @Autowired private FacilityTypeReportMapper facilityTypeMapper; @Autowired private GeographicZoneMapper geographicZoneMapper; @Autowired private ProgramService programService; private MailingLabelReportParam mailingLabelReportParam = null; private ReportData getMailingLabelReport(Facility facility) { if (facility == null) return null; return new MailingLabelReport(); } @Override protected List<? extends ReportData> getResultSetReportData(Map<String, String[]> params) { return getMainReportData(params, null, RowBounds.NO_ROW_OFFSET, RowBounds.NO_ROW_LIMIT); } private List<ReportData> getListMailingLabelsReport(List<Facility> facilityList) { if (facilityList == null) return null; List<ReportData> facilityReportList = new ArrayList<>(facilityList.size()); for (Facility facility : facilityList) { facilityReportList.add(getMailingLabelReport(facility)); } return facilityReportList; } @Override public List<? extends ReportData> getMainReportData(Map<String, String[]> filterCriteria, Map<String, String[]> sorterCriteria, int page, int pageSize) { RowBounds rowBounds = new RowBounds((page - 1) * pageSize, pageSize); MailingLabelReportSorter mailingLabelReportSorter = null; if (sorterCriteria != null) { mailingLabelReportSorter = new MailingLabelReportSorter(); mailingLabelReportSorter.setFacilityName(sorterCriteria.get("facilityName") == null ? "" : sorterCriteria.get("facilityName")[0]); mailingLabelReportSorter.setCode(sorterCriteria.get("code") == null ? "" : sorterCriteria.get("code")[0]); mailingLabelReportSorter.setFacilityType(sorterCriteria.get("facilityType") == null ? "ASC" : sorterCriteria.get("facilityType")[0]); } return mailingLabelReportMapper.SelectFilteredSortedPagedFacilities(getReportFilterData(filterCriteria), rowBounds); } public MailingLabelReportParam getReportFilterData(Map<String, String[]> filterCriteria) { if (filterCriteria != null) { mailingLabelReportParam = new MailingLabelReportParam(); mailingLabelReportParam.setFacilityType((StringHelper.isBlank(filterCriteria, "facilityType") ? 0 : Long.parseLong(filterCriteria.get("facilityType")[0]))); mailingLabelReportParam.setZone((StringHelper.isBlank(filterCriteria, "zone") ? 0 : Long.parseLong(filterCriteria.get("zone")[0]))); mailingLabelReportParam.setStatus((StringHelper.isBlank(filterCriteria, "status") ? null : Boolean.parseBoolean(filterCriteria.get("status")[0]))); mailingLabelReportParam.setOrderBy(StringHelper.isBlank(filterCriteria, "sortBy") ? "" : filterCriteria.get("sortBy")[0]); mailingLabelReportParam.setSortOrder(StringHelper.isBlank(filterCriteria, "order") ? "" : filterCriteria.get("order")[0]); mailingLabelReportParam.setProgramId(StringHelper.isBlank(filterCriteria, "program") ? 0 :Integer.parseInt(filterCriteria.get("program")[0])); StringBuffer header = new StringBuffer(); if(mailingLabelReportParam.getProgramId() == 0) header.append("Program: All"); else header.append("Program: ").append(programService.getById(new Long(mailingLabelReportParam.getProgramId())).getName()); if(mailingLabelReportParam.getZone() != 0) header.append("\nGeographic Zone: ").append(geographicZoneMapper.getWithParentById(mailingLabelReportParam.getZone()).getName()); else header.append("\nGeographic Zone: All"); if(mailingLabelReportParam.getFacilityType() != 0) header.append("\nFacility Type: " + facilityTypeMapper.getById(mailingLabelReportParam.getFacilityType()).getName()); else header.append("\nFacility Type: All"); if(mailingLabelReportParam.getStatus() == null) header.append("\nStatus : All"); else if(mailingLabelReportParam.getStatus() == true) header.append("\nStatus : Active"); else header.append("\nStatus : Inactive"); mailingLabelReportParam.setHeader(header.toString()); } return mailingLabelReportParam; } @Override public String getFilterSummary(Map<String, String[]> params) { return getReportFilterData(params).toString(); } }
agpl-3.0
DemandCube/NeverwinterDP
registry/vm/src/main/java/com/neverwinterdp/vm/client/shell/SubCommand.java
259
package com.neverwinterdp.vm.client.shell; //TODO anthony investigate remove getDescription abstract public class SubCommand { abstract public void execute(Shell shell, CommandInput cmdInput) throws Exception ; abstract public String getDescription(); }
agpl-3.0
pleku/ion-training-diary
vaadin-cdi/src/test/java/com/vaadin/cdi/uis/RootUI.java
1624
/* * Copyright 2000-2013 Vaadin Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.vaadin.cdi.uis; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.PostConstruct; import com.vaadin.cdi.CDIUI; import com.vaadin.server.VaadinRequest; import com.vaadin.ui.Label; import com.vaadin.ui.UI; import com.vaadin.ui.VerticalLayout; /** */ @CDIUI public class RootUI extends UI { private final static AtomicInteger COUNTER = new AtomicInteger(0); private int clickCount; @PostConstruct public void initialize() { COUNTER.incrementAndGet(); clickCount = 0; } @Override protected void init(VaadinRequest request) { setSizeFull(); VerticalLayout layout = new VerticalLayout(); layout.setSizeFull(); final Label label = new Label("+RootUI"); label.setId("label"); layout.addComponent(label); setContent(layout); } public static int getNumberOfInstances() { return COUNTER.get(); } public static void resetCounter() { COUNTER.set(0); } }
agpl-3.0
erdincay/ejb
src/com/lp/server/personal/service/ReiseDtoAssembler.java
3360
/******************************************************************************* * HELIUM V, Open Source ERP software for sustained success * at small and medium-sized enterprises. * Copyright (C) 2004 - 2015 HELIUM V IT-Solutions GmbH * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of theLicense, or * (at your option) any later version. * * According to sec. 7 of the GNU Affero General Public License, version 3, * the terms of the AGPL are supplemented with the following terms: * * "HELIUM V" and "HELIUM 5" are registered trademarks of * HELIUM V IT-Solutions GmbH. The licensing of the program under the * AGPL does not imply a trademark license. Therefore any rights, title and * interest in our trademarks remain entirely with us. If you want to propagate * modified versions of the Program under the name "HELIUM V" or "HELIUM 5", * you may only do so if you have a written permission by HELIUM V IT-Solutions * GmbH (to acquire a permission please contact HELIUM V IT-Solutions * at trademark@heliumv.com). * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact: developers@heliumv.com ******************************************************************************/ package com.lp.server.personal.service; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import com.lp.server.personal.ejb.Reise; public class ReiseDtoAssembler { public static ReiseDto createDto(Reise reise) { ReiseDto reiseDto = new ReiseDto(); if (reise != null) { reiseDto.setIId(reise.getIId()); reiseDto.setPersonalIId(reise.getPersonalIId()); reiseDto.setTZeit(reise.getTZeit()); reiseDto.setBBeginn(reise.getBBeginn()); reiseDto.setDiaetenIId(reise.getDiaetenIId()); reiseDto.setPartnerIId(reise.getPartnerIId()); reiseDto.setAnsprechpartnerIId(reise.getAnsprechpartnerIId()); reiseDto.setIKmbeginn(reise.getIKmbeginn()); reiseDto.setIKmende(reise.getIKmende()); reiseDto.setNSpesen(reise.getNSpesen()); reiseDto.setCFahrzeug(reise.getCFahrzeug()); reiseDto.setCKommentar(reise.getCKommentar()); reiseDto.setTAendern(reise.getTAendern()); reiseDto.setPersonalIIdAendern(reise.getPersonalIIdAendern()); reiseDto.setBelegartCNr(reise.getBelegartCNr()); reiseDto.setIBelegartid(reise.getIBelegartid()); reiseDto.setFahrzeugIId(reise.getFahrzeugIId()); reiseDto.setFFaktor(reise.getFFaktor()); } return reiseDto; } public static ReiseDto[] createDtos(Collection<?> reises) { List<ReiseDto> list = new ArrayList<ReiseDto>(); if (reises != null) { Iterator<?> iterator = reises.iterator(); while (iterator.hasNext()) { list.add(createDto((Reise) iterator.next())); } } ReiseDto[] returnArray = new ReiseDto[list.size()]; return (ReiseDto[]) list.toArray(returnArray); } }
agpl-3.0
open-health-hub/openmaxims-linux
openmaxims_workspace/Emergency/src/ims/emergency/forms/systemsreviewcc/FormInfo.java
2666
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.emergency.forms.systemsreviewcc; public final class FormInfo extends ims.framework.FormInfo { private static final long serialVersionUID = 1L; public FormInfo(Integer formId) { super(formId); } public String getNamespaceName() { return "Emergency"; } public String getFormName() { return "SystemsReviewcc"; } public int getWidth() { return 632; } public int getHeight() { return 368; } public String[] getContextVariables() { return new String[] { }; } public String getLocalVariablesPrefix() { return "_lv_Emergency.SystemsReviewcc.__internal_x_context__" + String.valueOf(getFormId()); } public ims.framework.FormInfo[] getComponentsFormInfo() { ims.framework.FormInfo[] componentsInfo = new ims.framework.FormInfo[1]; componentsInfo[0] = new ims.core.forms.authoringinfo.FormInfo(102228); return componentsInfo; } public String getImagePath() { return ""; } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/Clinical/src/ims/clinical/domain/impl/ConsultantProcedureHotlistDialogImpl.java
5173
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Calin Perebiceanu using IMS Development Environment (version 1.71 build 3642.24101) // Copyright (C) 1995-2010 IMS MAXIMS. All rights reserved. package ims.clinical.domain.impl; import ims.admin.vo.ConsultantProcedureCategoryVo; import ims.admin.vo.ConsultantProcedureCategoryVoCollection; import ims.admin.vo.domain.ConsultantProcedureCategoryVoAssembler; import ims.clinical.domain.base.impl.BaseConsultantProcedureHotlistDialogImpl; import ims.core.clinical.domain.objects.Service; import ims.core.vo.HcpLiteVo; import ims.core.vo.domain.ProcedureLiteVoAssembler; import ims.core.vo.domain.ServiceLiteVoAssembler; import ims.core.vo.lookups.ProcedureCategory; import ims.domain.DomainFactory; import ims.domain.exceptions.DomainInterfaceException; import ims.framework.exceptions.CodingRuntimeException; import java.util.ArrayList; import java.util.List; public class ConsultantProcedureHotlistDialogImpl extends BaseConsultantProcedureHotlistDialogImpl { private static final long serialVersionUID = 1L; public ims.core.vo.ServiceLiteVoCollection listServices() { return ServiceLiteVoAssembler.createServiceLiteVoCollectionFromService(getDomainFactory().listDomainObjects(Service.class)); } public ims.core.vo.ProcedureLiteVoCollection listProcedures(ProcedureCategory category, String procNameFilter, ims.core.vo.HcpLiteVo currUser) { StringBuilder query = new StringBuilder( "select p1_1 from ConsultantProcedureCategory as c1_1 left join " + "c1_1.categoryProcedures as c2_1 left join c2_1.procedures as p1_1 " + "where (p1_1.isActive = 1 and c1_1.performingHCP.id = :Hcp_id"); ArrayList<String> paramNames = new ArrayList<String>(); ArrayList<Object> paramValues = new ArrayList<Object>(); paramNames.add("Hcp_id"); paramValues.add(currUser.getID_Hcp()); if (category != null) { query.append(" and c2_1.category.id = :Category_id"); paramNames.add("Category_id"); paramValues.add(category.getID()); } if (procNameFilter != null) { query.append(" and upper(p1_1.procedureName) like :nameFilter"); //wdev-13658 paramNames.add("nameFilter"); paramValues.add("%"+procNameFilter.toUpperCase()+"%"); //wdev-13658 } query.append(" ) order by p1_1.procedureName asc "); List<?> procs = getDomainFactory().find(query.toString(),paramNames,paramValues); if (procs == null || procs.size() == 0) return null; return ProcedureLiteVoAssembler.createProcedureLiteVoCollectionFromProcedure(procs); } public ConsultantProcedureCategoryVo getConsultantProcedureCategoryByHcp(HcpLiteVo hcp) throws DomainInterfaceException { if(hcp == null) throw new CodingRuntimeException("hcp is null"); DomainFactory factory = getDomainFactory(); List conProcCateList = factory.find("from ConsultantProcedureCategory cpc where cpc.performingHCP.id = :idHcp)", new String[]{"idHcp"}, new Object[]{hcp.getID_Hcp()}); ConsultantProcedureCategoryVoCollection coll = ConsultantProcedureCategoryVoAssembler.createConsultantProcedureCategoryVoCollectionFromConsultantProcedureCategory(conProcCateList); if(coll.size()!= 0) return coll.get(0); else return null; } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/Core/src/ims/core/domain/base/impl/BaseAcceptTransferToWardDlgImpl.java
3416
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.core.domain.base.impl; import ims.domain.impl.DomainImpl; public abstract class BaseAcceptTransferToWardDlgImpl extends DomainImpl implements ims.core.domain.AcceptTransferToWardDlg, ims.domain.impl.Transactional { private static final long serialVersionUID = 1L; @SuppressWarnings("unused") public void validatesaveTransferIn(ims.core.vo.BedSpaceStateLiteVo voOldBedSpaceStateLite, ims.core.vo.InPatientEpisodeADTVo voInpatientEpisode, ims.core.vo.PendingTransfersLiteVo voPending, ims.core.vo.HomeLeaveVo voHL, ims.core.vo.PatientCaseNoteTransferVoCollection collPatientCaseNoteTransfer) { } @SuppressWarnings("unused") public void validategetInpatientEpisodeADT(ims.core.admin.pas.vo.InpatientEpisodeRefVo inpatientEpisodeRef) { } @SuppressWarnings("unused") public void validategetWardConfig(ims.core.resource.place.vo.LocationRefVo locationRef) { } @SuppressWarnings("unused") public void validatelistServices(String serviceName) { } @SuppressWarnings("unused") public void validategetCaseNoteFolders(ims.core.patient.vo.PatientRefVo patientRef, ims.core.resource.place.vo.LocationRefVo locationRef) { } @SuppressWarnings("unused") public void validateisCaseNoteFolderLocation(ims.core.patient.vo.PatientRefVo patientRef) { } }
agpl-3.0
aborg0/RapidMiner-Unuk
src/com/rapidminer/operator/preprocessing/sampling/sequences/SamplingSequenceGenerator.java
1638
/* * RapidMiner * * Copyright (C) 2001-2013 by Rapid-I and the contributors * * Complete list of developers available at our web site: * * http://rapid-i.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.operator.preprocessing.sampling.sequences; import com.rapidminer.tools.RandomGenerator; /** * This is an abstract super class of all sampling sequence generators. * Subclasses of this class will return a sequence of true/false values * to indicate that the next example to come should be part of the sample or not. * * @author Sebastian Land */ public abstract class SamplingSequenceGenerator { protected RandomGenerator random; protected SamplingSequenceGenerator(RandomGenerator random) { this.random = random; } /** * This method has to be overridden. Subclasses must implement * this method, so that it returns true if the next example should * be part of the sample or no otherwise. */ public abstract boolean useNext(); }
agpl-3.0
stephaneperry/Silverpeas-Components
whitepages/whitepages-war/src/main/java/com/silverpeas/whitePages/html/WhitePagesHtmlTools.java
1901
package com.silverpeas.whitePages.html; import java.util.List; import javax.servlet.http.HttpServletRequest; import com.stratelia.silverpeas.pdc.model.SearchAxis; import com.stratelia.silverpeas.pdc.model.Value; public class WhitePagesHtmlTools { public static String generateHtmlForPdc(List<SearchAxis> axis, String language, HttpServletRequest request) { StringBuffer result = new StringBuffer(""); for (SearchAxis searchAxis : axis) { result.append("<div>"); int axisId = searchAxis.getAxisId(); String valueInContext = request.getAttribute("Axis" + String.valueOf(axisId)) != null ? (String)request.getAttribute("Axis" + String.valueOf(axisId)) : null; String increment = ""; String selected = ""; String axisName = searchAxis.getAxisName(); StringBuffer buffer = new StringBuffer("<select name=\"Axis"+axisId+"\" size=\"1\">"); buffer.append("<option value=\"\"></option>"); List<Value> values = searchAxis.getValues(); for (Value value : values) { for (int inc=0; inc<value.getLevelNumber(); inc++) { increment += "&nbsp;&nbsp;&nbsp;&nbsp;"; } if (value.getFullPath().equals(valueInContext)) { selected = " selected"; } buffer.append("<option value=\""+value.getFullPath()+"\""+selected+">"+increment+value.getName(language)); buffer.append("</option>"); increment = ""; selected = ""; } buffer.append("</select>"); result.append("<label class=\"txtlibform\" for=\"Axis"); result.append(axisId); result.append("\">"); result.append(axisName); result.append("</label>"); result.append(buffer.toString()); result.append("</div>"); } return result.toString(); } }
agpl-3.0
open-health-hub/openmaxims-linux
openmaxims_workspace/Clinical/src/ims/clinical/forms/medicationdiscontinue/Logic.java
5214
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Rory Fitzpatrick using IMS Development Environment (version 1.45 build 2308.23992) // Copyright (C) 1995-2006 IMS MAXIMS plc. All rights reserved. package ims.clinical.forms.medicationdiscontinue; import ims.clinical.vo.DiscontinueMedicationReasonValuesVo; import ims.core.vo.Hcp; import ims.core.vo.HcpCollection; import ims.core.vo.HcpFilter; import ims.core.vo.PersonName; import ims.core.vo.lookups.MedciationCommencedDiscontinuedType; import ims.framework.enumerations.DialogResult; import ims.framework.exceptions.PresentationLogicException; import ims.framework.utils.Date; public class Logic extends BaseLogic { private static final long serialVersionUID = 1L; protected void onFormOpen() throws ims.framework.exceptions.PresentationLogicException { //Defaulting Authoring HCP and Date form.dteDate().setValue(new Date()); form.cmbDiscontinuedByType().setValue(MedciationCommencedDiscontinuedType.MOS); defaultHCP(); form.qmbHCP().setEnabled(true); if (form.getGlobalContext().Clinical.getDiscontinueMedicationReasonValuesIsNotNull()) { form.dteDate().setValue(form.getGlobalContext().Clinical.getDiscontinueMedicationReasonValues().getStoppedDate()); Hcp hcp = form.getGlobalContext().Clinical.getDiscontinueMedicationReasonValues().getStoppedHCP(); if(hcp!=null){ form.qmbHCP().newRow(hcp, hcp.toString()); form.qmbHCP().setValue(hcp); } form.cmbReasonDiscontinued().setValue(form.getGlobalContext().Clinical.getDiscontinueMedicationReasonValues().getStoppedReason()); form.txtReasonDesc().setValue(form.getGlobalContext().Clinical.getDiscontinueMedicationReasonValues().getStoppedReasonDesc()); } } protected void onBtnCancelClick() throws ims.framework.exceptions.PresentationLogicException { engine.close(DialogResult.CANCEL); } protected void onBtnOKClick() throws ims.framework.exceptions.PresentationLogicException { DiscontinueMedicationReasonValuesVo voReason = new DiscontinueMedicationReasonValuesVo(); voReason.setStoppedDate(form.dteDate().getValue()); voReason.setStoppedHCP(form.qmbHCP().getValue()); voReason.setStoppedReason(form.cmbReasonDiscontinued().getValue()); voReason.setStoppedReasonDesc(form.txtReasonDesc().getValue()); voReason.setStoppedByType(form.cmbDiscontinuedByType().getValue()); form.getGlobalContext().Clinical.setDiscontinueMedicationReasonValues(voReason); engine.close(DialogResult.OK); } protected void onQmbHCPTextSubmited(String value) { form.qmbHCP().clear(); HcpFilter filter = new HcpFilter(); PersonName name = new PersonName(); name.setSurname(value); filter.setQueryName(name); HcpCollection voHCPColl = domain.listHcps(filter); if(voHCPColl != null) { for (int i = 0; i < voHCPColl.size(); i++) { form.qmbHCP().newRow(voHCPColl.get(i), voHCPColl.get(i).toString()); } if (voHCPColl.size() == 1) { form.qmbHCP().setValue(voHCPColl.get(0)); } else if (voHCPColl.size() > 1) { form.qmbHCP().showOpened(); } } } protected void onCmbDiscontinuedByTypeValueChanged() throws PresentationLogicException { if ( (form.cmbDiscontinuedByType().getValue() != null) && (form.cmbDiscontinuedByType().getValue().equals(MedciationCommencedDiscontinuedType.MOS)) ) { form.qmbHCP().setEnabled(true); defaultHCP(); } else { form.qmbHCP().setEnabled(false); form.qmbHCP().setValue(null); } } private void defaultHCP() { Hcp hcp = (Hcp) domain.getHcpUser(); if(hcp != null) { form.qmbHCP().newRow(hcp, hcp.toString()); form.qmbHCP().setValue(hcp); } } }
agpl-3.0