repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
smalyshev/blazegraph
bigdata-rdf/src/java/com/bigdata/rdf/lexicon/ITextIndexer.java
11430
/** Copyright (C) SYSTAP, LLC 2006-2015. All rights reserved. Contact: SYSTAP, LLC 2501 Calvert ST NW #106 Washington, DC 20008 licenses@systap.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 Jun 3, 2010 */ package com.bigdata.rdf.lexicon; import java.io.Serializable; import java.util.Locale; import java.util.concurrent.TimeUnit; import org.openrdf.model.Value; import com.bigdata.rdf.store.AbstractTripleStore; import com.bigdata.rdf.store.BDS; import com.bigdata.search.FullTextIndex; import com.bigdata.search.Hiterator; import com.bigdata.search.IHit; /** * Abstraction for the text indexer for RDF {@link Value}s allowing either the * built-in bigdata {@link FullTextIndex} or support for Lucene, etc. * * @author <a href="mailto:thompsonbry@users.sourceforge.net">Bryan Thompson</a> * @version $Id$ * * @see AbstractTripleStore.Options#TEXT_INDEXER_CLASS */ public interface ITextIndexer<A extends IHit> { public void create(); public void destroy(); /* * Moved to IValueCentricTextIndexer */ // /** // * <p> // * Add the terms to the full text index so that we can do fast lookup of the // * corresponding term identifiers. Only literals are tokenized. Literals // * that have a language code property are parsed using a tokenizer // * appropriate for the specified language family. Other literals and URIs // * are tokenized using the default {@link Locale}. // * </p> // * // * @param capacity // * A hint to the underlying layer about the buffer size before an // * incremental flush of the index. // * @param itr // * Iterator visiting the terms to be indexed. // * // * @todo allow registeration of datatype specific tokenizers (we already // * have language family based lookup). // */ // public void index(int capacity, Iterator<BigdataValue> valuesIterator); /** * Return <code>true</code> iff datatype literals are being indexed. */ public boolean getIndexDatatypeLiterals(); /** * Do a free text search. * * @param query * The query. * * @return The result set. */ public Hiterator<A> search(final FullTextQuery query); /** * Count free text search results. * * @param query * The query. * * @return The result count. */ public int count(final FullTextQuery query); public static class FullTextQuery implements Serializable { /** * */ private static final long serialVersionUID = 4159873519447769476L; final String query; final String languageCode; final boolean prefixMatch; final double minCosine; final double maxCosine; final int minRank; final int maxRank; final boolean matchAllTerms; final boolean matchExact; final long timeout; final TimeUnit unit; final String matchRegex; public FullTextQuery(final String query) { this( query, null, BDS.DEFAULT_PREFIX_MATCH, null, BDS.DEFAULT_MATCH_ALL_TERMS, BDS.DEFAULT_MATCH_EXACT, BDS.DEFAULT_MIN_RELEVANCE, BDS.DEFAULT_MAX_RELEVANCE, BDS.DEFAULT_MIN_RANK, BDS.DEFAULT_MAX_RANK, BDS.DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS ); } public FullTextQuery(final String query, final String languageCode, final boolean prefixMatch) { this( query, languageCode, prefixMatch, null, BDS.DEFAULT_MATCH_ALL_TERMS, BDS.DEFAULT_MATCH_EXACT, BDS.DEFAULT_MIN_RELEVANCE, BDS.DEFAULT_MAX_RELEVANCE, BDS.DEFAULT_MIN_RANK, BDS.DEFAULT_MAX_RANK, BDS.DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS ); } public FullTextQuery(final String query, final String languageCode, final boolean prefixMatch, final String matchRegex, final boolean matchAllTerms, final boolean matchExact) { this( query, languageCode, prefixMatch, matchRegex, matchAllTerms, matchExact, BDS.DEFAULT_MIN_RELEVANCE, BDS.DEFAULT_MAX_RELEVANCE, BDS.DEFAULT_MIN_RANK, BDS.DEFAULT_MAX_RANK, BDS.DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS ); } public FullTextQuery(final String query, final String languageCode, final boolean prefixMatch, final String matchRegex, final boolean matchAllTerms, final boolean matchExact, final double minCosine, final double maxCosine, final int minRank, final int maxRank) { this( query, languageCode, prefixMatch, matchRegex, matchAllTerms, matchExact, minCosine, maxCosine, minRank, maxRank, BDS.DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS ); } /** * Construct a full text query. * * @param query * The query (it will be parsed into tokens). * @param languageCode * The language code that should be used when tokenizing the * query -or- <code>null</code> to use the default {@link Locale} * ). * @param prefixMatch * When <code>true</code>, the matches will be on tokens which * include the query tokens as a prefix. This includes exact * matches as a special case when the prefix is the entire token, * but it also allows longer matches. For example, * <code>free</code> will be an exact match on <code>free</code> * but a partial match on <code>freedom</code>. When * <code>false</code>, only exact matches will be made. * @param matchRegex * A regex filter to apply to the search. * @param matchAllTerms * if true, return only hits that match all search terms * @param matchExact * if true, return only hits that have an exact match of the search string * @param minCosine * The minimum cosine that will be returned (in [0:maxCosine]). * If you specify a minimum cosine of ZERO (0.0) you can drag in * a lot of basically useless search results. * @param maxCosine * The maximum cosine that will be returned (in [minCosine:1.0]). * Useful for evaluating in relevance ranges. * @param minRank * The min rank of the search result. * @param maxRank * The max rank of the search result. * @param timeout * The timeout -or- ZERO (0) for NO timeout (this is equivalent * to using {@link Long#MAX_VALUE}). * @param unit * The unit in which the timeout is expressed. */ public FullTextQuery(final String query, final String languageCode, final boolean prefixMatch, final String matchRegex, final boolean matchAllTerms, final boolean matchExact, final double minCosine, final double maxCosine, final int minRank, final int maxRank, long timeout, final TimeUnit unit) { this.query = query; this.languageCode = languageCode; this.prefixMatch = prefixMatch; this.matchRegex = matchRegex; this.matchAllTerms = matchAllTerms; this.matchExact = matchExact; this.minCosine = minCosine; this.maxCosine = maxCosine; this.minRank = minRank; this.maxRank = maxRank; this.timeout = timeout; this.unit = unit; } /** * @return the query */ public String getQuery() { return query; } /** * @return the languageCode */ public String getLanguageCode() { return languageCode; } /** * @return the prefixMatch */ public boolean isPrefixMatch() { return prefixMatch; } /** * @return the match regex filter to apply */ public String getMatchRegex() { return matchRegex; } /** * @return the matchAllTerms */ public boolean isMatchAllTerms() { return matchAllTerms; } /** * @return the matchExact */ public boolean isMatchExact() { return matchExact; } /** * @return the minCosine */ public double getMinCosine() { return minCosine; } /** * @return the maxCosine */ public double getMaxCosine() { return maxCosine; } /** * @return the minRank */ public int getMinRank() { return minRank; } /** * @return the maxRank */ public int getMaxRank() { return maxRank; } /** * @return the timeout */ public long getTimeout() { return timeout; } /** * @return the unit */ public TimeUnit getTimeUnit() { return unit; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((languageCode == null) ? 0 : languageCode.hashCode()); result = prime * result + (matchAllTerms ? 1231 : 1237); result = prime * result + (matchExact ? 1231 : 1237); result = prime * result + (prefixMatch ? 1231 : 1237); result = prime * result + ((query == null) ? 0 : query.hashCode()); result = prime * result + ((matchRegex == null) ? 0 : matchRegex.hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; FullTextQuery other = (FullTextQuery) obj; if (languageCode == null) { if (other.languageCode != null) return false; } else if (!languageCode.equals(other.languageCode)) return false; if (matchAllTerms != other.matchAllTerms) return false; if (matchExact != other.matchExact) return false; if (prefixMatch != other.prefixMatch) return false; if (query == null) { if (other.query != null) return false; } else if (!query.equals(other.query)) return false; if (matchRegex == null) { if (other.matchRegex != null) return false; } else if (!matchRegex.equals(other.matchRegex)) return false; return true; } } }
gpl-2.0
FCC/mobile-mba-androidapp
libcore/src/com/loopj/android/http/RetryHandler.java
3814
/* Android Asynchronous Http Client Copyright (c) 2011 James Smith <james@loopj.com> http://loopj.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Some of the retry logic in this class is heavily borrowed from the fantastic droid-fu project: https://github.com/donnfelker/droid-fu */ package com.loopj.android.http; import java.io.IOException; import java.io.InterruptedIOException; import java.net.SocketException; import java.net.UnknownHostException; import java.util.HashSet; import javax.net.ssl.SSLHandshakeException; import org.apache.http.NoHttpResponseException; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.HttpRequestRetryHandler; import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.HttpContext; import android.os.SystemClock; class RetryHandler implements HttpRequestRetryHandler { private static final int RETRY_SLEEP_TIME_MILLIS = 1500; private static HashSet<Class<?>> exceptionWhitelist = new HashSet<Class<?>>(); private static HashSet<Class<?>> exceptionBlacklist = new HashSet<Class<?>>(); static { // Retry if the server dropped connection on us exceptionWhitelist.add(NoHttpResponseException.class); // retry-this, since it may happens as part of a Wi-Fi to 3G failover exceptionWhitelist.add(UnknownHostException.class); // retry-this, since it may happens as part of a Wi-Fi to 3G failover exceptionWhitelist.add(SocketException.class); // never retry timeouts exceptionBlacklist.add(InterruptedIOException.class); // never retry SSL handshake failures exceptionBlacklist.add(SSLHandshakeException.class); } private int maxRetries; public RetryHandler(int maxRetries) { this.maxRetries = maxRetries; } public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { boolean retry; Boolean b = (Boolean) context.getAttribute(ExecutionContext.HTTP_REQ_SENT); boolean sent = (b != null && b.booleanValue()); if(executionCount > maxRetries) { // Do not retry if over max retry count retry = false; } else if (exceptionBlacklist.contains(exception.getClass())) { // immediately cancel retry if the error is blacklisted retry = false; } else if (exceptionWhitelist.contains(exception.getClass())) { // immediately retry if error is whitelisted retry = true; } else if (!sent) { // for most other errors, retry only if request hasn't been fully sent yet retry = true; } else { // resend all idempotent requests HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); String requestType = currentReq.getMethod(); if(!requestType.equals("POST")) { retry = true; } else { // otherwise do not retry retry = false; } } if(retry) { SystemClock.sleep(RETRY_SLEEP_TIME_MILLIS); } else { exception.printStackTrace(); } return retry; } }
gpl-2.0
dwango/quercus
src/main/java/com/caucho/quercus/lib/dom/DOMElement.java
6308
/* * Copyright (c) 1998-2012 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Resin Open Source 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, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Sam */ package com.caucho.quercus.lib.dom; import com.caucho.quercus.annotation.Optional; import com.caucho.quercus.env.Env; import org.w3c.dom.Element; public class DOMElement extends DOMNode<Element> { public static DOMElement __construct(Env env, String name, @Optional String textContent, @Optional String namespace) { DOMElement element; if (namespace != null && namespace.length() > 0) element = getImpl(env).createElement(name, namespace); else element = getImpl(env).createElement(name); if (textContent != null && textContent.length() > 0) element.setTextContent(textContent); return element; } DOMElement(DOMImplementation impl, Element node) { super(impl, node); } public String getNodeValue() throws DOMException { // php/1zd1 return getTextContent(); } public String getAttribute(String name) { return _delegate.getAttribute(name); } public String getAttributeNS(String namespaceURI, String localName) throws DOMException { try { return _delegate.getAttributeNS(namespaceURI, localName); } catch (org.w3c.dom.DOMException ex) { throw wrap(ex); } } public DOMAttr getAttributeNode(String name) { return wrap(_delegate.getAttributeNode(name)); } public DOMAttr getAttributeNodeNS(String namespaceURI, String localName) throws DOMException { try { return wrap(_delegate.getAttributeNodeNS(namespaceURI, localName)); } catch (org.w3c.dom.DOMException ex) { throw wrap(ex); } } public DOMNodeList getElementsByTagName(String name) { return wrap(_delegate.getElementsByTagName(name)); } public DOMNodeList getElementsByTagNameNS( String namespaceURI, String localName) throws DOMException { try { return wrap(_delegate.getElementsByTagNameNS(namespaceURI, localName)); } catch (org.w3c.dom.DOMException ex) { throw wrap(ex); } } public DOMTypeInfo getSchemaTypeInfo() { return wrap(_delegate.getSchemaTypeInfo()); } public String getTagName() { return _delegate.getTagName(); } public boolean hasAttribute(String name) { return _delegate.hasAttribute(name); } public boolean hasAttributeNS(String namespaceURI, String localName) throws DOMException { try { return _delegate.hasAttributeNS(namespaceURI, localName); } catch (org.w3c.dom.DOMException ex) { throw wrap(ex); } } public void removeAttribute(String name) throws DOMException { try { _delegate.removeAttribute(name); } catch (org.w3c.dom.DOMException ex) { throw wrap(ex); } } public void removeAttributeNS(String namespaceURI, String localName) throws DOMException { try { _delegate.removeAttributeNS(namespaceURI, localName); } catch (org.w3c.dom.DOMException ex) { throw wrap(ex); } } public DOMAttr removeAttributeNode(DOMAttr oldAttr) throws DOMException { try { return wrap(_delegate.removeAttributeNode(oldAttr._delegate)); } catch (org.w3c.dom.DOMException ex) { throw wrap(ex); } } public void setAttribute(String name, String value) throws DOMException { try { _delegate.setAttribute(name, value); } catch (org.w3c.dom.DOMException ex) { throw wrap(ex); } } public void setAttributeNS(String namespaceURI, String qualifiedName, String value) throws DOMException { try { _delegate.setAttributeNS(namespaceURI, qualifiedName, value); } catch (org.w3c.dom.DOMException ex) { throw wrap(ex); } } public DOMAttr setAttributeNode(DOMAttr newAttr) throws DOMException { try { return wrap(_delegate.setAttributeNode(newAttr._delegate)); } catch (org.w3c.dom.DOMException ex) { throw wrap(ex); } } public DOMAttr setAttributeNodeNS(DOMAttr newAttr) throws DOMException { try { return wrap(_delegate.setAttributeNodeNS(newAttr._delegate)); } catch (org.w3c.dom.DOMException ex) { throw wrap(ex); } } public void setIdAttribute(String name, boolean isId) throws DOMException { try { _delegate.setIdAttribute(name, isId); } catch (org.w3c.dom.DOMException ex) { throw wrap(ex); } } public void setIdAttributeNS(String namespaceURI, String localName, boolean isId) throws DOMException { try { _delegate.setIdAttributeNS(namespaceURI, localName, isId); } catch (org.w3c.dom.DOMException ex) { throw wrap(ex); } } public void setIdAttributeNode(DOMAttr idAttr, boolean isId) throws DOMException { try { _delegate.setIdAttributeNode(idAttr._delegate, isId); } catch (org.w3c.dom.DOMException ex) { throw wrap(ex); } } public void setNodeValue(String nodeValue) throws DOMException { // php/1zd1 if (nodeValue == null) nodeValue = ""; setTextContent(nodeValue); } }
gpl-2.0
lamsfoundation/lams
3rdParty_sources/poi/org/apache/poi/ss/formula/functions/DGet.java
2719
/* ==================================================================== 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.poi.ss.formula.functions; import org.apache.poi.ss.formula.eval.BlankEval; import org.apache.poi.ss.formula.eval.ErrorEval; import org.apache.poi.ss.formula.eval.EvaluationException; import org.apache.poi.ss.formula.eval.OperandResolver; import org.apache.poi.ss.formula.eval.ValueEval; /** * Implementation of the DGet function: * Finds the value of a column in an area with given conditions. */ public final class DGet implements IDStarAlgorithm { private ValueEval result; @Override public boolean processMatch(ValueEval eval) { if(result == null) // First match, just set the value. { result = eval; } else // There was a previous match. Only one non-blank result is allowed. #NUM! on multiple values. { if(result instanceof BlankEval) { result = eval; } else { // We have a previous filled result. if(!(eval instanceof BlankEval)) { result = ErrorEval.NUM_ERROR; return false; } } } return true; } @Override public ValueEval getResult() { if(result == null) { return ErrorEval.VALUE_INVALID; } else if(result instanceof BlankEval) { return ErrorEval.VALUE_INVALID; } else try { if(OperandResolver.coerceValueToString(OperandResolver.getSingleValue(result, 0, 0)).isEmpty()) { return ErrorEval.VALUE_INVALID; } else { return result; } } catch (EvaluationException e) { return e.getErrorEval(); } } }
gpl-2.0
squaregoldfish/QuinCe
WebApp/src/uk/ac/exeter/QuinCe/jobs/InvalidJobConstructorException.java
739
package uk.ac.exeter.QuinCe.jobs; /** * Exception to indicate that the specified job class does not require a * constructor of the correct type. * * @author Steve Jones * @see Job#Job(uk.ac.exeter.QuinCe.web.system.ResourceManager, * java.util.Properties, long, java.util.Properties) */ public class InvalidJobConstructorException extends Exception { /** * The Serial Version UID */ private static final long serialVersionUID = 8855435038251108392L; /** * Constructor * * @param className * The name of the invalid class */ public InvalidJobConstructorException(String className) { super("The specified job class '" + className + "' does not have a valid constructor"); } }
gpl-3.0
seapub/SourceCode
Java/corejava9/v1ch09/checkBox/CheckBoxFrame.java
1450
package checkBox; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * A frame with a sample text label and check boxes for selecting font attributes. */ public class CheckBoxFrame extends JFrame { private JLabel label; private JCheckBox bold; private JCheckBox italic; private static final int FONTSIZE = 24; public CheckBoxFrame() { // add the sample text label label = new JLabel("The quick brown fox jumps over the lazy dog."); label.setFont(new Font("Serif", Font.BOLD, FONTSIZE)); add(label, BorderLayout.CENTER); // this listener sets the font attribute of // the label to the check box state ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent event) { int mode = 0; if (bold.isSelected()) mode += Font.BOLD; if (italic.isSelected()) mode += Font.ITALIC; label.setFont(new Font("Serif", mode, FONTSIZE)); } }; // add the check boxes JPanel buttonPanel = new JPanel(); bold = new JCheckBox("Bold"); bold.addActionListener(listener); bold.setSelected(true); buttonPanel.add(bold); italic = new JCheckBox("Italic"); italic.addActionListener(listener); buttonPanel.add(italic); add(buttonPanel, BorderLayout.SOUTH); pack(); } }
gpl-3.0
SpleenOfDoom/MochaDoom
src/m/Settings.java
1623
package m; import static g.Keys.*; import static doom.englsh.*; /** An anumeration with the most basic default Doom settings their default * values, used if nothing else is available. They are applied first thing, * and then updated from the .cfg file. * */ public enum Settings { mouse_sensitivity("5"), sfx_volume("8"), music_volume("8"), show_messages("1"), alwaysrun("1"), key_right(KEY_RIGHTARROW), key_left(KEY_LEFTARROW), key_up('w'), key_down('s'), key_strafeleft('a'), key_straferight('d'), key_fire(KEY_CTRL), key_use(' '), key_strafe(KEY_ALT), key_speed(KEY_SHIFT), use_mouse(1), mouseb_fire(0), mouseb_strafe(1), mouseb_forward(2), use_joystick( 0), joyb_fire(0), joyb_strafe(1), joyb_use(3), joyb_speed(2), screenblocks(10), detaillevel(0), snd_channels(6), usegamma(0), mb_used(2), chatmacro0(HUSTR_CHATMACRO0 ), chatmacro1(HUSTR_CHATMACRO1 ), chatmacro2( HUSTR_CHATMACRO2 ), chatmacro3(HUSTR_CHATMACRO3 ), chatmacro4( HUSTR_CHATMACRO4 ), chatmacro5( HUSTR_CHATMACRO5 ), chatmacro6(HUSTR_CHATMACRO6 ), chatmacro7( HUSTR_CHATMACRO7 ), chatmacro8(HUSTR_CHATMACRO8 ), chatmacro9( HUSTR_CHATMACRO9 ); private Settings(String defaultval){ this.value=defaultval; } private Settings(int defaultval){ this.value=Integer.toString(defaultval); } public String value; /** Normally this is default.cfg, might be .doomrc on lunix??? */ public static String basedefault="default.cfg"; }
gpl-3.0
snavaneethan1/jaffa-framework
jaffa-soa/source/java/org/jaffa/transaction/domain/TransactionDependency.java
28908
// .//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.transaction.domain; import org.apache.log4j.Logger; import java.util.*; import javax.persistence.*; import javax.xml.bind.annotation.*; import org.jaffa.datatypes.*; import org.jaffa.datatypes.adapters.DateOnlyType; import org.jaffa.datatypes.adapters.DateTimeType; import org.jaffa.metadata.*; import org.jaffa.rules.RulesEngine; import org.jaffa.persistence.*; import org.jaffa.persistence.exceptions.*; import org.jaffa.security.SecurityManager; import org.jaffa.util.*; import org.jaffa.beans.factory.config.StaticContext; import org.jaffa.exceptions.FrameworkException; import org.jaffa.exceptions.RelatedDomainObjectFoundException; import org.jaffa.exceptions.DuplicateKeyException; import org.jaffa.datatypes.exceptions.InvalidForeignKeyException; import org.jaffa.exceptions.ApplicationExceptions; import org.jaffa.transaction.domain.Transaction; import org.jaffa.transaction.domain.TransactionMeta; // .//GEN-END:1_be // Add additional imports//GEN-FIRST:imports import org.jaffa.transaction.daos.TransactionMessageDAO; import org.jaffa.transaction.daos.TransactionMessageDAOFactory; // .//GEN-LAST:imports // .//GEN-BEGIN:2_be /** * Auto Generated Persistent class for the J_TRANSACTION_DEPENDENCIES table. * @author Auto-Generated */ @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) @Entity @Table(name = "J_TRANSACTION_DEPENDENCIES") @SqlResultSetMapping(name="TransactionDependency",entities={@EntityResult(entityClass=TransactionDependency.class)}) public class TransactionDependency extends Persistent { private static final Logger log = Logger.getLogger(TransactionDependency.class); @XmlElement(name="transactionId") @Id @Basic(optional = false) @Column(name = "TRANSACTION_ID") private java.lang.String m_transactionId; @XmlElement(name="dependsOnId") @Column(name = "DEPENDS_ON_ID") private java.lang.String m_dependsOnId; @XmlElement(name="status") @Column(name = "STATUS") private java.lang.String m_status; private transient Transaction m_transactionObject; private transient Transaction m_dependsOnTransactionObject; /** * Default Constructor * * Calls the Static Context Factory to allow Spring to initialize this object */ public TransactionDependency() { StaticContext.configure(this); } /** * Check if the domain object exists for the input Primary Key. * * @return true if the domain object exists for the input Primary Key. * @throws FrameworkException Indicates some system error */ public static boolean exists(UOW uow, java.lang.String transactionId, java.lang.String dependsOnId) throws FrameworkException { // TODO this is generated code.... return (findByPK(uow, transactionId, dependsOnId) != null); } /** * Returns the domain object for the input Primary Key. * * @return the domain object for the input Primary Key. A null is returned if the domain object is not found. * @throws FrameworkException Indicates some system error */ public static TransactionDependency findByPK(UOW uow, java.lang.String transactionId, java.lang.String dependsOnId) throws FrameworkException { // TODO this is generated code.... TransactionDependency result = getTransactionDAO().getTransactionDependency(transactionId, dependsOnId); if (result != null) { result.setUOW(uow); } return result; } /** * Returns a Criteria object for retrieving the domain object based on the input Primary Key. * * @return a Criteria object for retrieving the domain object based on the input Primary Key. */ public static Criteria findByPKCriteria(java.lang.String transactionId, java.lang.String dependsOnId) { // TODO this is generated code.... return null; } /** * Check for existence prior to adding to the database. * * @throws PreAddFailedException */ protected void performPreAddExistenceCheck() { // Empty override } // .//GEN-END:2_be // .//GEN-BEGIN:transactionId_be /** * Getter for property transactionId. * * @return Value of property transactionId. */ public java.lang.String getTransactionId() { return m_transactionId; } /** * Use this method to update the property transactionId. * This method will do nothing and simply return if the input value is the same as the current value. * Validation will be performed on the input value. * This will try to lock the underlying database row, in case CAUTIOUS locking is specified at the time of query. * * @param transactionId New value of property transactionId. * @throws ValidationException if an invalid value is passed. * @throws UpdatePrimaryKeyException if this domain object was loaded from the database. * @throws ReadOnlyObjectException if a Read-Only object is updated. * @throws AlreadyLockedObjectException if the underlying database row is already locked by another process. * @throws FrameworkException Indicates some system error */ public void setTransactionId(java.lang.String transactionId) throws ValidationException, UpdatePrimaryKeyException, ReadOnlyObjectException, AlreadyLockedObjectException, FrameworkException { // ignore, if the current value and new value are the same if (m_transactionId == null ? transactionId == null : m_transactionId.equals(transactionId)) return; // this is part of the primary key.. do not update if its a database occurence. if (isDatabaseOccurence()) throw new UpdatePrimaryKeyException(); transactionId = validateTransactionId(transactionId); // .//GEN-END:transactionId_be // Add custom code before setting the value//GEN-FIRST:transactionId // .//GEN-LAST:transactionId // .//GEN-BEGIN:transactionId_1_be super.update(); super.addInitialValue(TransactionDependencyMeta.TRANSACTION_ID, m_transactionId); m_transactionId = transactionId; m_transactionObject = null; // .//GEN-END:transactionId_1_be // Add custom code after setting the value//GEN-FIRST:transactionId_3 // .//GEN-LAST:transactionId_3 // .//GEN-BEGIN:transactionId_2_be } /** * This method is present for backwards compatibility only. * It merely invokes the setTransactionId() method. * * @param transactionId New value of property transactionId. * @throws ValidationException if an invalid value is passed. * @throws UpdatePrimaryKeyException if this domain object was loaded from the database. * @throws ReadOnlyObjectException if a Read-Only object is updated. * @throws AlreadyLockedObjectException if the underlying database row is already locked by another process. * @throws FrameworkException Indicates some system error */ public void updateTransactionId(java.lang.String transactionId) throws ValidationException, UpdatePrimaryKeyException, ReadOnlyObjectException, AlreadyLockedObjectException, FrameworkException { setTransactionId(transactionId); } /** * Use this method to validate a value for the property transactionId. * * @param transactionId Value to be validated for the property transactionId. * @throws ValidationException if an invalid value is passed * @throws FrameworkException Indicates some system error */ public java.lang.String validateTransactionId(java.lang.String transactionId) throws ValidationException, FrameworkException { // .//GEN-END:transactionId_2_be // Add custom code before validation//GEN-FIRST:transactionId_1 // .//GEN-LAST:transactionId_1 // .//GEN-BEGIN:transactionId_3_be transactionId = FieldValidator.validate(transactionId, (StringFieldMetaData) TransactionDependencyMeta.META_TRANSACTION_ID, true); // Invoke the Dynamic Rules Engine RulesEngine.doAllValidationsForDomainField(TransactionDependencyMeta.getName(), TransactionDependencyMeta.TRANSACTION_ID, transactionId, this.getUOW()); // .//GEN-END:transactionId_3_be // Add custom code after a successful validation//GEN-FIRST:transactionId_2 // .//GEN-LAST:transactionId_2 // .//GEN-BEGIN:transactionId_4_be return transactionId; } // .//GEN-END:transactionId_4_be // .//GEN-BEGIN:dependsOnId_be /** * Getter for property dependsOnId. * * @return Value of property dependsOnId. */ public java.lang.String getDependsOnId() { return m_dependsOnId; } /** * Use this method to update the property dependsOnId. * This method will do nothing and simply return if the input value is the same as the current value. * Validation will be performed on the input value. * This will try to lock the underlying database row, in case CAUTIOUS locking is specified at the time of query. * * @param dependsOnId New value of property dependsOnId. * @throws ValidationException if an invalid value is passed. * @throws UpdatePrimaryKeyException if this domain object was loaded from the database. * @throws ReadOnlyObjectException if a Read-Only object is updated. * @throws AlreadyLockedObjectException if the underlying database row is already locked by another process. * @throws FrameworkException Indicates some system error */ public void setDependsOnId(java.lang.String dependsOnId) throws ValidationException, UpdatePrimaryKeyException, ReadOnlyObjectException, AlreadyLockedObjectException, FrameworkException { // ignore, if the current value and new value are the same if (m_dependsOnId == null ? dependsOnId == null : m_dependsOnId.equals(dependsOnId)) return; // this is part of the primary key.. do not update if its a database occurence. if (isDatabaseOccurence()) throw new UpdatePrimaryKeyException(); dependsOnId = validateDependsOnId(dependsOnId); // .//GEN-END:dependsOnId_be // Add custom code before setting the value//GEN-FIRST:dependsOnId // .//GEN-LAST:dependsOnId // .//GEN-BEGIN:dependsOnId_1_be super.update(); super.addInitialValue(TransactionDependencyMeta.DEPENDS_ON_ID, m_dependsOnId); m_dependsOnId = dependsOnId; m_dependsOnTransactionObject = null; // .//GEN-END:dependsOnId_1_be // Add custom code after setting the value//GEN-FIRST:dependsOnId_3 // .//GEN-LAST:dependsOnId_3 // .//GEN-BEGIN:dependsOnId_2_be } /** * This method is present for backwards compatibility only. * It merely invokes the setDependsOnId() method. * * @param dependsOnId New value of property dependsOnId. * @throws ValidationException if an invalid value is passed. * @throws UpdatePrimaryKeyException if this domain object was loaded from the database. * @throws ReadOnlyObjectException if a Read-Only object is updated. * @throws AlreadyLockedObjectException if the underlying database row is already locked by another process. * @throws FrameworkException Indicates some system error */ public void updateDependsOnId(java.lang.String dependsOnId) throws ValidationException, UpdatePrimaryKeyException, ReadOnlyObjectException, AlreadyLockedObjectException, FrameworkException { setDependsOnId(dependsOnId); } /** * Use this method to validate a value for the property dependsOnId. * * @param dependsOnId Value to be validated for the property dependsOnId. * @throws ValidationException if an invalid value is passed * @throws FrameworkException Indicates some system error */ public java.lang.String validateDependsOnId(java.lang.String dependsOnId) throws ValidationException, FrameworkException { // .//GEN-END:dependsOnId_2_be // Add custom code before validation//GEN-FIRST:dependsOnId_1 // .//GEN-LAST:dependsOnId_1 // .//GEN-BEGIN:dependsOnId_3_be dependsOnId = FieldValidator.validate(dependsOnId, (StringFieldMetaData) TransactionDependencyMeta.META_DEPENDS_ON_ID, true); // Invoke the Dynamic Rules Engine RulesEngine.doAllValidationsForDomainField(TransactionDependencyMeta.getName(), TransactionDependencyMeta.DEPENDS_ON_ID, dependsOnId, this.getUOW()); // .//GEN-END:dependsOnId_3_be // Add custom code after a successful validation//GEN-FIRST:dependsOnId_2 // .//GEN-LAST:dependsOnId_2 // .//GEN-BEGIN:dependsOnId_4_be return dependsOnId; } // .//GEN-END:dependsOnId_4_be // .//GEN-BEGIN:status_be /** * Getter for property status. * * @return Value of property status. */ public java.lang.String getStatus() { return m_status; } /** * Use this method to update the property status. * This method will do nothing and simply return if the input value is the same as the current value. * Validation will be performed on the input value. * This will try to lock the underlying database row, in case CAUTIOUS locking is specified at the time of query. * * @param status New value of property status. * @throws ValidationException if an invalid value is passed. * @throws ReadOnlyObjectException if a Read-Only object is updated. * @throws AlreadyLockedObjectException if the underlying database row is already locked by another process. * @throws FrameworkException Indicates some system error */ public void setStatus(java.lang.String status) throws ValidationException, ReadOnlyObjectException, AlreadyLockedObjectException, FrameworkException { // ignore, if the current value and new value are the same if (m_status == null ? status == null : m_status.equals(status)) return; status = validateStatus(status); // .//GEN-END:status_be // Add custom code before setting the value//GEN-FIRST:status // .//GEN-LAST:status // .//GEN-BEGIN:status_1_be super.update(); super.addInitialValue(TransactionDependencyMeta.STATUS, m_status); m_status = status; // .//GEN-END:status_1_be // Add custom code after setting the value//GEN-FIRST:status_3 // .//GEN-LAST:status_3 // .//GEN-BEGIN:status_2_be } /** * This method is present for backwards compatibility only. * It merely invokes the setStatus() method. * * @param status New value of property status. * @throws ValidationException if an invalid value is passed. * @throws ReadOnlyObjectException if a Read-Only object is updated. * @throws AlreadyLockedObjectException if the underlying database row is already locked by another process. * @throws FrameworkException Indicates some system error */ public void updateStatus(java.lang.String status) throws ValidationException, ReadOnlyObjectException, AlreadyLockedObjectException, FrameworkException { setStatus(status); } /** * Use this method to validate a value for the property status. * * @param status Value to be validated for the property status. * @throws ValidationException if an invalid value is passed * @throws FrameworkException Indicates some system error */ public java.lang.String validateStatus(java.lang.String status) throws ValidationException, FrameworkException { // .//GEN-END:status_2_be // Add custom code before validation//GEN-FIRST:status_1 // .//GEN-LAST:status_1 // .//GEN-BEGIN:status_3_be status = FieldValidator.validate(status, (StringFieldMetaData) TransactionDependencyMeta.META_STATUS, true); // Invoke the Dynamic Rules Engine RulesEngine.doAllValidationsForDomainField(TransactionDependencyMeta.getName(), TransactionDependencyMeta.STATUS, status, this.getUOW()); // .//GEN-END:status_3_be // Add custom code after a successful validation//GEN-FIRST:status_2 // .//GEN-LAST:status_2 // .//GEN-BEGIN:status_4_be return status; } // .//GEN-END:status_4_be // .//GEN-BEGIN:transactionObject_1_be /** * Returns the related foreign Transaction object. * The object is lazy-loaded. * * @return the related foreign Transaction object. * @throws ValidationException if an invalid foreign key is set. * @throws FrameworkException Indicates some system error */ public Transaction getTransactionObject() throws ValidationException, FrameworkException { findTransactionObject(false); return m_transactionObject; } /** * Finds the related foreign Transaction object. * If checkExistenceOnly is false, then the foreign object will be fetched and assigned to the corresponding member variable of this class. * If checkExistenceOnly is true, then a mere existence check is performed for the foreign object, as oppposed to fetching all the values for that object. */ private void findTransactionObject(boolean checkExistenceOnly) throws ValidationException, FrameworkException { // TODO this is generated code... if (m_transactionObject == null && getTransactionId() != null) { Transaction transaction = getTransactionDAO().getTransaction(getTransactionId()); Number count = null; if (checkExistenceOnly) { if (transaction != null) { count = 1; } } else { m_transactionObject = transaction; } if ((m_transactionObject == null) && ((count == null) || (count.intValue() <= 0))) { throw new InvalidForeignKeyException(TransactionDependencyMeta.META_TRANSACTION_ID.getLabelToken(), new Object[] {TransactionMeta.getLabelToken(), TransactionMeta.META_ID.getLabelToken()}); } } } // .//GEN-END:transactionObject_1_be // .//GEN-BEGIN:dependsOnTransactionObject_1_be /** * Returns the related foreign Transaction object. * The object is lazy-loaded. * * @return the related foreign Transaction object. * @throws ValidationException if an invalid foreign key is set. * @throws FrameworkException Indicates some system error */ public Transaction getDependsOnTransactionObject() throws ValidationException, FrameworkException { findDependsOnTransactionObject(false); return m_dependsOnTransactionObject; } /** * Finds the related foreign Transaction object. * If checkExistenceOnly is false, then the foreign object will be fetched and assigned to the corresponding member variable of this class. * If checkExistenceOnly is true, then a mere existence check is performed for the foreign object, as oppposed to fetching all the values for that object. */ private void findDependsOnTransactionObject(boolean checkExistenceOnly) throws ValidationException, FrameworkException { // TODO this is generated code... if (m_dependsOnTransactionObject == null && getDependsOnId() != null) { Transaction transaction = getTransactionDAO().getTransaction(getDependsOnId()); Number count = null; if (checkExistenceOnly) { if (transaction != null) { count = 1; } } else { m_dependsOnTransactionObject = transaction; } if ((m_dependsOnTransactionObject == null) && ((count == null) || (count.intValue() <= 0))) { throw new InvalidForeignKeyException(TransactionDependencyMeta.META_DEPENDS_ON_ID.getLabelToken(), new Object[] {TransactionMeta.getLabelToken(), TransactionMeta.META_ID.getLabelToken()}); } } } // .//GEN-END:dependsOnTransactionObject_1_be // .//GEN-BEGIN:toString_1_be /** * This returns the diagnostic information. * * @return the diagnostic information. */ public String toString() { StringBuffer buf = new StringBuffer(); buf.append("<TransactionDependency>"); buf.append("<transactionId>"); if (m_transactionId != null) buf.append(m_transactionId); buf.append("</transactionId>"); buf.append("<dependsOnId>"); if (m_dependsOnId != null) buf.append(m_dependsOnId); buf.append("</dependsOnId>"); buf.append("<status>"); if (m_status != null) buf.append(m_status); buf.append("</status>"); // .//GEN-END:toString_1_be // Add custom debug information//GEN-FIRST:toString_1 // .//GEN-LAST:toString_1 // .//GEN-BEGIN:toString_2_be buf.append(super.toString()); buf.append("</TransactionDependency>"); return buf.toString(); } // .//GEN-END:toString_2_be // .//GEN-BEGIN:clone_1_be /** * Returns a clone of the object. * * @throws CloneNotSupportedException if cloning is not supported. This should never happen. * @return a clone of the object. */ public Object clone() throws CloneNotSupportedException { TransactionDependency obj = (TransactionDependency) super.clone(); obj.m_transactionObject = null; obj.m_dependsOnTransactionObject = null; return obj; } // .//GEN-END:clone_1_be // .//GEN-BEGIN:performForeignKeyValidations_1_be /** * This method ensures that the modified foreign-keys are valid. * * @throws ApplicationExceptions if an invalid foreign key is set. * @throws FrameworkException Indicates some system error */ public void performForeignKeyValidations() throws ApplicationExceptions, FrameworkException { } // .//GEN-END:performForeignKeyValidations_1_be // .//GEN-BEGIN:performPreDeleteReferentialIntegrity_1_be /** * This method is triggered by the UOW, before adding this object to the Delete-Store. * * This will raise an exception if any associated/aggregated objects exist. * This will cascade delete all composite objects. * @throws PreDeleteFailedException if any error occurs during the process. */ public void performPreDeleteReferentialIntegrity() throws PreDeleteFailedException { } // .//GEN-END:performPreDeleteReferentialIntegrity_1_be // .//GEN-BEGIN:3_be /** * @clientCardinality 0..* * @supplierCardinality 1 * @clientQualifier transactionId * @supplierQualifier id * @link association */ /*#Transaction lnkTransaction;*/ /** * @clientCardinality 0..* * @supplierCardinality 1 * @clientQualifier dependsOnId * @supplierQualifier id * @link association */ /*#Transaction lnkTransaction;*/ // .//GEN-END:3_be // All the custom code goes here//GEN-FIRST:custom /** An enumeration of TransactionDependency Status. */ public enum Status {O, S} @Override public void postUpdate() throws PostUpdateFailedException { super.postUpdate(); //If status changes to "S" and if "SELECT COUNT(*) FROM TRANSACTION_DEPENDENCIES WHERE TRANSACTION_ID={thisTransactionDependency.transactionId} AND STATUS='O'" is zero, //then UPDATE TRANSACTIONS SET STATUS='O' WHERE ID={thisTransactionDependency.transactionId} and STATUS='H' if (isModified(TransactionDependencyMeta.STATUS) && Status.S.toString().equals(getStatus())) { try { if (log.isDebugEnabled()) { log.debug("TransactionDependency status has changed to S. Will Open parent Transaction if no other Open TransactionDependency record exists"); } TransactionMessageDAO transactionDAO = getTransactionDAO(); Transaction transaction = transactionDAO.getTransaction(getTransactionId()); if (transaction != null && Transaction.Status.H.toString().equals(transaction.getStatus())) { long count = transactionDAO.getOpenTransactionDependencyCount(transaction.getId()); if (count == 0) { transaction.setStatus(Transaction.Status.O.toString()); getUOW().update(transaction); } } } catch (Exception e) { String s = "Exception in opening parent Transaction when the associated dependencies have all been satisfied. This is being done for the TransactionDependency instance " + this; ApplicationExceptions appExps = ExceptionHelper.extractApplicationExceptions(e); if (appExps != null) { if (log.isDebugEnabled()) log.debug(s, appExps); } else { log.error(s, e); } throw new PostUpdateFailedException(new String[]{s}, e); } } } @Override public void postDelete() throws PostDeleteFailedException { super.postDelete(); //If status was "O" and if "SELECT COUNT(*) FROM TRANSACTION_DEPENDENCIES WHERE TRANSACTION_ID={thisTransactionDependency.transactionId} AND STATUS='O'" is zero, //then UPDATE TRANSACTIONS SET STATUS='O' WHERE ID={thisTransactionDependency.transactionId} and STATUS='H' if (Status.O.toString().equals(getStatus())) { try { if (log.isDebugEnabled()) { log.debug("An Open TransactionDependency status has been deleted. Will Open parent Transaction if no other Open TransactionDependency record exists"); } TransactionMessageDAO transactionDAO = getTransactionDAO(); Transaction transaction = transactionDAO.getTransaction(getTransactionId()); if ((transaction != null) && Transaction.Status.H.toString().equals(transaction.getStatus())) { long count = transactionDAO.getOpenTransactionDependencyCount(transaction.getId()); if (count == 0) { transaction.setStatus(Transaction.Status.O.toString()); getUOW().update(transaction); } } } catch (Exception e) { String s = "Exception in opening parent Transaction when the associated dependencies have all been satisfied. This is being done for the deleted TransactionDependency instance " + this; ApplicationExceptions appExps = ExceptionHelper.extractApplicationExceptions(e); if (appExps != null) { if (log.isDebugEnabled()) log.debug(s, appExps); } else { log.error(s, e); } throw new PostDeleteFailedException(new String[]{s}, e); } } } /** This method is triggered by the UOW, before adding this object to the Add-Store, but after a UOW has been associated to the object. * This will perform the following tasks: * Will invoke the PersistentHelper.exists() to check against duplicate keys. * Will invoke the performForeignKeyValidations() method to ensure no invalid foreign-keys are set. * Will invoke PersistentHelper.checkMandatoryFields() to perform mandatory field checks. * Will invoke the Rules Engine to perform mandatory field checks. * @throws PreAddFailedException if any error occurs during the process. */ public void preAdd() throws PreAddFailedException { super.doPreAdd(); } /** * {@inheritDoc} */ @Override public void validate() throws ApplicationExceptions, FrameworkException { super.validate(); } /** * Gets a DAO for transactions. * @return a DAO. */ private static TransactionMessageDAO getTransactionDAO() { return TransactionMessageDAOFactory.getTransactionMessageDAO(); } // .//GEN-LAST:custom }
gpl-3.0
KevinSeroux/DI3_ProjetTSP
src/polytech/tours/di/parallel/tsp/Instance.java
1422
package polytech.tours.di.parallel.tsp; import java.text.DecimalFormat; /** * Provides a concrete implementation of a TSP instance. * Instances of this class are inmutable. * @author Jorge E. Mendoza (dev@jorge-mendoza.com) * @version %I%, %G% * */ public class Instance{ /** * The distance matrix */ private final double[][] matrix; /** * Constructs a new TSP instance * @param n number of nodes in the underlying graph */ public Instance(double matrix[][]){ this.matrix=matrix.clone(); } /** * * @param i the first node * @param j the second node * @return the distance between node <code>i</code> and node <code>j</code> */ public double getDistance(int i, int j){ return this.matrix[i][j]; } /** * * @return the number of nodes in the instance */ public int getN(){ return matrix.length; } /** * * @return a copy of the distance matrix */ public double[][] getDistanceMatrix(){ return this.matrix.clone(); } /** * Prints the distance matrix to the standard output * @param format decimal format (e.g., #.0000 for rounding to 4 decimals) */ public void printDistanceMatrix(String format){ DecimalFormat df=new DecimalFormat(format); for(int i=0; i<this.matrix.length;i++){ for(int j=0; j<this.matrix[0].length; j++){ System.out.print(df.format(matrix[i][j])+"\t"); } System.out.print("\n"); } System.out.print("\n"); } }
gpl-3.0
testIT-ResultRepository/resultrepository-core
resultrepository-persistence/src/test/java/info/novatec/testit/resultrepository/persistence/services/graph/nodes/TestNodeIntegrationTest.java
2347
package info.novatec.testit.resultrepository.persistence.services.graph.nodes; import static org.assertj.core.api.Assertions.assertThat; import java.lang.reflect.UndeclaredThrowableException; import java.util.Set; import org.junit.Test; import info.novatec.testit.resultrepository.persistence.AbstractPersistenceIntegrationTest; public class TestNodeIntegrationTest extends AbstractPersistenceIntegrationTest { private static final String TEST = "foo.bar.Test#test1"; /* test results */ @Test public void testThatAllTestResultsCanBeRetrievedAsAStream() { inTransaction(() -> { TestResultNode testResult1 = testResultFactory.createInGraph(); TestResultNode testResult2 = testResultFactory.createInGraph(); TestResultNode testResult3 = testResultFactory.createInGraph(); TestNode test = testFactory.getOrCreateFromGraph(TEST); testResult1.setTest(test); testResult2.setTest(test); Set<TestResultNode> testResults = test.getTestResults(); assertThat(testResults).containsOnly(testResult1, testResult2).doesNotContain(testResult3); }); } @Test public void testThatLatestTestResultCanBeRetrievedAsAnOptional() { inTransaction(() -> { TestNode test = testFactory.getOrCreateFromGraph(TEST); TestResultNode testResult1 = testResultFactory.createInGraph(); TestResultNode testResult2 = testResultFactory.createInGraph(); waitToGuaranteeLatestTimestamp(); TestResultNode testResult3 = testResultFactory.createInGraph(); testResult1.setTest(test); testResult2.setTest(test); testResult3.setTest(test); assertThat(test.getLatestResult().get()).isEqualTo(testResult3); }); } private void waitToGuaranteeLatestTimestamp() { try { Thread.sleep(15); } catch (InterruptedException e) { throw new UndeclaredThrowableException(e); } } @Test public void testThatLatestTestResultCanBeRetrievedAsAnOptional_NoLatestResult() { inTransaction(() -> { TestNode test = testFactory.getOrCreateFromGraph(TEST); assertThat(test.getLatestResult().isPresent()).isFalse(); }); } }
gpl-3.0
the-learning-collective/whereat-android
app/src/test/java/org/tlc/whereat/modules/map/GoogleMarkerAdapterTest.java
2200
/** * * Copyright (c) 2015-present, Total Location Test Paragraph. * All rights reserved. * * This file is part of Where@. Where@ is free software: * you can redistribute it and/or modify it under the terms of * the GNU General Public License (GPL), either version 3 * of the License, or (at your option) any later version. * * Where@ 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. For more details, * see the full license at <http://www.gnu.org/licenses/gpl-3.0.en.html> * */ package org.tlc.whereat.modules.map; import com.google.android.gms.maps.model.Marker; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import org.tlc.whereat.BuildConfig; import org.tlc.whereat.model.UserLocation; import static org.assertj.core.api.Assertions.*; import static org.mockito.Mockito.*; import static org.tlc.whereat.support.LocationHelpers.*; /** * coded with <3 for where@ */ @RunWith(RobolectricGradleTestRunner.class) @Config(constants = BuildConfig.class, sdk = 21) public class GoogleMarkerAdapterTest { UserLocation s17 = s17UserLocationStub(); GoogleMarkerAdapter mc; Marker gm; @Before public void setup(){ gm = mock(Marker.class); mc = (GoogleMarkerAdapter) GoogleMarkerAdapter.getInstance(gm); doNothing().when(gm).setPosition(s17.asLatLon().asGoogleLatLon()); doNothing().when(gm).remove(); } @Test public void getInstance_should_instantiateMarkerContainerWrappingGoogleMarker () throws Exception { assertThat(mc).isInstanceOf(MarkerAdapter.class); assertThat(mc.mMarker).isEqualTo(gm); } @Test public void move_should_delegateToGoogleMapsAndReturnThis() throws Exception { assertThat(mc.move(s17.asLatLon())).isEqualTo(mc); verify(gm).setPosition(s17.asLatLon().asGoogleLatLon()); } @Test public void remove_should_delegateToGoogleMaps() { mc.remove(); verify(gm).remove(); } }
gpl-3.0
s20121035/rk3288_android5.1_repo
cts/tests/tests/renderscript/src/android/renderscript/cts/TestCbrt.java
13458
/* * Copyright (C) 2014 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. */ // Don't edit this file! It is auto-generated by frameworks/rs/api/gen_runtime. package android.renderscript.cts; import android.renderscript.Allocation; import android.renderscript.RSRuntimeException; import android.renderscript.Element; public class TestCbrt extends RSBaseCompute { private ScriptC_TestCbrt script; private ScriptC_TestCbrtRelaxed scriptRelaxed; @Override protected void setUp() throws Exception { super.setUp(); script = new ScriptC_TestCbrt(mRS); scriptRelaxed = new ScriptC_TestCbrtRelaxed(mRS); } public class ArgumentsFloatFloat { public float in; public Target.Floaty out; } private void checkCbrtFloatFloat() { Allocation in = createRandomAllocation(mRS, Element.DataType.FLOAT_32, 1, 0x4e2c540726cc677al, false); try { Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 1), INPUTSIZE); script.forEach_testCbrtFloatFloat(in, out); verifyResultsCbrtFloatFloat(in, out, false); } catch (Exception e) { throw new RSRuntimeException("RenderScript. Can't invoke forEach_testCbrtFloatFloat: " + e.toString()); } try { Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 1), INPUTSIZE); scriptRelaxed.forEach_testCbrtFloatFloat(in, out); verifyResultsCbrtFloatFloat(in, out, true); } catch (Exception e) { throw new RSRuntimeException("RenderScript. Can't invoke forEach_testCbrtFloatFloat: " + e.toString()); } } private void verifyResultsCbrtFloatFloat(Allocation in, Allocation out, boolean relaxed) { float[] arrayIn = new float[INPUTSIZE * 1]; in.copyTo(arrayIn); float[] arrayOut = new float[INPUTSIZE * 1]; out.copyTo(arrayOut); for (int i = 0; i < INPUTSIZE; i++) { for (int j = 0; j < 1 ; j++) { // Extract the inputs. ArgumentsFloatFloat args = new ArgumentsFloatFloat(); args.in = arrayIn[i]; // Figure out what the outputs should have been. Target target = new Target(relaxed); CoreMathVerifier.computeCbrt(args, target); // Validate the outputs. boolean valid = true; if (!args.out.couldBe(arrayOut[i * 1 + j])) { valid = false; } if (!valid) { StringBuilder message = new StringBuilder(); message.append("Input in: "); message.append(String.format("%14.8g {%8x} %15a", args.in, Float.floatToRawIntBits(args.in), args.in)); message.append("\n"); message.append("Expected output out: "); message.append(args.out.toString()); message.append("\n"); message.append("Actual output out: "); message.append(String.format("%14.8g {%8x} %15a", arrayOut[i * 1 + j], Float.floatToRawIntBits(arrayOut[i * 1 + j]), arrayOut[i * 1 + j])); if (!args.out.couldBe(arrayOut[i * 1 + j])) { message.append(" FAIL"); } message.append("\n"); assertTrue("Incorrect output for checkCbrtFloatFloat" + (relaxed ? "_relaxed" : "") + ":\n" + message.toString(), valid); } } } } private void checkCbrtFloat2Float2() { Allocation in = createRandomAllocation(mRS, Element.DataType.FLOAT_32, 2, 0x9e2a09a2eb8fdb46l, false); try { Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 2), INPUTSIZE); script.forEach_testCbrtFloat2Float2(in, out); verifyResultsCbrtFloat2Float2(in, out, false); } catch (Exception e) { throw new RSRuntimeException("RenderScript. Can't invoke forEach_testCbrtFloat2Float2: " + e.toString()); } try { Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 2), INPUTSIZE); scriptRelaxed.forEach_testCbrtFloat2Float2(in, out); verifyResultsCbrtFloat2Float2(in, out, true); } catch (Exception e) { throw new RSRuntimeException("RenderScript. Can't invoke forEach_testCbrtFloat2Float2: " + e.toString()); } } private void verifyResultsCbrtFloat2Float2(Allocation in, Allocation out, boolean relaxed) { float[] arrayIn = new float[INPUTSIZE * 2]; in.copyTo(arrayIn); float[] arrayOut = new float[INPUTSIZE * 2]; out.copyTo(arrayOut); for (int i = 0; i < INPUTSIZE; i++) { for (int j = 0; j < 2 ; j++) { // Extract the inputs. ArgumentsFloatFloat args = new ArgumentsFloatFloat(); args.in = arrayIn[i * 2 + j]; // Figure out what the outputs should have been. Target target = new Target(relaxed); CoreMathVerifier.computeCbrt(args, target); // Validate the outputs. boolean valid = true; if (!args.out.couldBe(arrayOut[i * 2 + j])) { valid = false; } if (!valid) { StringBuilder message = new StringBuilder(); message.append("Input in: "); message.append(String.format("%14.8g {%8x} %15a", args.in, Float.floatToRawIntBits(args.in), args.in)); message.append("\n"); message.append("Expected output out: "); message.append(args.out.toString()); message.append("\n"); message.append("Actual output out: "); message.append(String.format("%14.8g {%8x} %15a", arrayOut[i * 2 + j], Float.floatToRawIntBits(arrayOut[i * 2 + j]), arrayOut[i * 2 + j])); if (!args.out.couldBe(arrayOut[i * 2 + j])) { message.append(" FAIL"); } message.append("\n"); assertTrue("Incorrect output for checkCbrtFloat2Float2" + (relaxed ? "_relaxed" : "") + ":\n" + message.toString(), valid); } } } } private void checkCbrtFloat3Float3() { Allocation in = createRandomAllocation(mRS, Element.DataType.FLOAT_32, 3, 0x9e2a14444a9670e0l, false); try { Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 3), INPUTSIZE); script.forEach_testCbrtFloat3Float3(in, out); verifyResultsCbrtFloat3Float3(in, out, false); } catch (Exception e) { throw new RSRuntimeException("RenderScript. Can't invoke forEach_testCbrtFloat3Float3: " + e.toString()); } try { Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 3), INPUTSIZE); scriptRelaxed.forEach_testCbrtFloat3Float3(in, out); verifyResultsCbrtFloat3Float3(in, out, true); } catch (Exception e) { throw new RSRuntimeException("RenderScript. Can't invoke forEach_testCbrtFloat3Float3: " + e.toString()); } } private void verifyResultsCbrtFloat3Float3(Allocation in, Allocation out, boolean relaxed) { float[] arrayIn = new float[INPUTSIZE * 4]; in.copyTo(arrayIn); float[] arrayOut = new float[INPUTSIZE * 4]; out.copyTo(arrayOut); for (int i = 0; i < INPUTSIZE; i++) { for (int j = 0; j < 3 ; j++) { // Extract the inputs. ArgumentsFloatFloat args = new ArgumentsFloatFloat(); args.in = arrayIn[i * 4 + j]; // Figure out what the outputs should have been. Target target = new Target(relaxed); CoreMathVerifier.computeCbrt(args, target); // Validate the outputs. boolean valid = true; if (!args.out.couldBe(arrayOut[i * 4 + j])) { valid = false; } if (!valid) { StringBuilder message = new StringBuilder(); message.append("Input in: "); message.append(String.format("%14.8g {%8x} %15a", args.in, Float.floatToRawIntBits(args.in), args.in)); message.append("\n"); message.append("Expected output out: "); message.append(args.out.toString()); message.append("\n"); message.append("Actual output out: "); message.append(String.format("%14.8g {%8x} %15a", arrayOut[i * 4 + j], Float.floatToRawIntBits(arrayOut[i * 4 + j]), arrayOut[i * 4 + j])); if (!args.out.couldBe(arrayOut[i * 4 + j])) { message.append(" FAIL"); } message.append("\n"); assertTrue("Incorrect output for checkCbrtFloat3Float3" + (relaxed ? "_relaxed" : "") + ":\n" + message.toString(), valid); } } } } private void checkCbrtFloat4Float4() { Allocation in = createRandomAllocation(mRS, Element.DataType.FLOAT_32, 4, 0x9e2a1ee5a99d067al, false); try { Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 4), INPUTSIZE); script.forEach_testCbrtFloat4Float4(in, out); verifyResultsCbrtFloat4Float4(in, out, false); } catch (Exception e) { throw new RSRuntimeException("RenderScript. Can't invoke forEach_testCbrtFloat4Float4: " + e.toString()); } try { Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 4), INPUTSIZE); scriptRelaxed.forEach_testCbrtFloat4Float4(in, out); verifyResultsCbrtFloat4Float4(in, out, true); } catch (Exception e) { throw new RSRuntimeException("RenderScript. Can't invoke forEach_testCbrtFloat4Float4: " + e.toString()); } } private void verifyResultsCbrtFloat4Float4(Allocation in, Allocation out, boolean relaxed) { float[] arrayIn = new float[INPUTSIZE * 4]; in.copyTo(arrayIn); float[] arrayOut = new float[INPUTSIZE * 4]; out.copyTo(arrayOut); for (int i = 0; i < INPUTSIZE; i++) { for (int j = 0; j < 4 ; j++) { // Extract the inputs. ArgumentsFloatFloat args = new ArgumentsFloatFloat(); args.in = arrayIn[i * 4 + j]; // Figure out what the outputs should have been. Target target = new Target(relaxed); CoreMathVerifier.computeCbrt(args, target); // Validate the outputs. boolean valid = true; if (!args.out.couldBe(arrayOut[i * 4 + j])) { valid = false; } if (!valid) { StringBuilder message = new StringBuilder(); message.append("Input in: "); message.append(String.format("%14.8g {%8x} %15a", args.in, Float.floatToRawIntBits(args.in), args.in)); message.append("\n"); message.append("Expected output out: "); message.append(args.out.toString()); message.append("\n"); message.append("Actual output out: "); message.append(String.format("%14.8g {%8x} %15a", arrayOut[i * 4 + j], Float.floatToRawIntBits(arrayOut[i * 4 + j]), arrayOut[i * 4 + j])); if (!args.out.couldBe(arrayOut[i * 4 + j])) { message.append(" FAIL"); } message.append("\n"); assertTrue("Incorrect output for checkCbrtFloat4Float4" + (relaxed ? "_relaxed" : "") + ":\n" + message.toString(), valid); } } } } public void testCbrt() { checkCbrtFloatFloat(); checkCbrtFloat2Float2(); checkCbrtFloat3Float3(); checkCbrtFloat4Float4(); } }
gpl-3.0
SunYatong/librec
core/src/main/java/net/librec/math/algorithm/Shuffle.java
1959
// Copyright (C) 2014-2015 Guibing Guo // // This file is part of LibRec. // // LibRec 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. // // LibRec 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 LibRec. If not, see <http://www.gnu.org/licenses/>. // package net.librec.math.algorithm; import net.librec.math.structure.MatrixEntry; import net.librec.math.structure.SparseMatrix; /** * @author Haidong Zhang */ public class Shuffle { /** * Construct a shuffle for SparseMatrix. * * @param sparseMatrix the matrix to shuffle */ public Shuffle(SparseMatrix sparseMatrix) { int size = sparseMatrix.size(); sparseMatrix.isShuffle = true; sparseMatrix.shuffleRow = new int[size]; sparseMatrix.shuffleCursor = new int[size]; int i = 0; for (MatrixEntry me : sparseMatrix) { sparseMatrix.shuffleRow[i] = me.row(); sparseMatrix.shuffleCursor[i] = i; i++; } for (int k = size - 1; k > 0; k++) { int j = (int) (Randoms.uniform(0.0, 1.0) * k); int temp = sparseMatrix.shuffleRow[k]; sparseMatrix.shuffleRow[k] = sparseMatrix.shuffleRow[j]; sparseMatrix.shuffleRow[j] = temp; temp = sparseMatrix.shuffleCursor[k]; sparseMatrix.shuffleCursor[k] = sparseMatrix.shuffleCursor[j]; sparseMatrix.shuffleCursor[j] = temp; } } }
gpl-3.0
HyperPlay/NoHack
NoHack/src/me/johnnywoof/util/Utils.java
13332
package me.johnnywoof.util; import net.minecraft.server.v1_7_R4.Vec3D; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.craftbukkit.v1_7_R4.CraftWorld; import org.bukkit.craftbukkit.v1_7_R4.entity.CraftPlayer; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.util.BlockIterator; import java.lang.reflect.Field; import java.util.ArrayList; public class Utils { public static boolean canSee(Player player, Location loc2) { return ((CraftWorld) player.getLocation().getWorld()).getHandle().a(Vec3D.a(player.getLocation().getX(), player.getLocation().getY() + player.getEyeHeight(), player.getLocation().getZ()), Vec3D.a(loc2.getX(), loc2.getY(), loc2.getZ())) == null; } public static boolean isFood(Material m) { return (m == Material.COOKED_BEEF || m == Material.COOKED_CHICKEN || m == Material.COOKED_FISH || m == Material.GRILLED_PORK || m == Material.PORK || m == Material.MUSHROOM_SOUP || m == Material.RAW_BEEF || m == Material.RAW_CHICKEN || m == Material.RAW_FISH || m == Material.APPLE || m == Material.GOLDEN_APPLE || m == Material.MELON || m == Material.COOKIE || m == Material.BREAD || m == Material.SPIDER_EYE || m == Material.ROTTEN_FLESH || m == Material.POTATO_ITEM); } /** * Calculate the time in milliseconds that it should take to break the given block with the given tool * * @param tool tool to check * @param block block to check * @return time in milliseconds to break */ public static long calcSurvivalFastBreak(ItemStack tool, Material block) { if (isInstantBreak(block) || (tool.getType() == Material.SHEARS && block == Material.LEAVES)) { return 0; } double bhardness = BlockHardness.getBlockHardness(block); double thardness = ToolHardness.getToolHardness(tool.getType()); long enchantlvl = (long) tool.getEnchantmentLevel(Enchantment.DIG_SPEED); long result = Math.round((bhardness * thardness) * 0.10 * 10000); if (enchantlvl > 0) { result /= enchantlvl * enchantlvl + 1L; } result = result > 25000 ? 25000 : result < 0 ? 0 : result; if (isQuickCombo(tool, block)) { result = result / 2; } return result; } private static boolean isQuickCombo(ItemStack tool, Material m) { if (tool.getType() == Material.DIAMOND_SWORD || tool.getType() == Material.IRON_SWORD || tool.getType() == Material.STONE_SWORD || tool.getType() == Material.GOLD_SWORD || tool.getType() == Material.WOOD_SWORD) { return m == Material.WEB; } else if (tool.getType() == Material.SHEARS) { return m == Material.WOOL; } return false; } public static boolean isInstantBreak(Material m) { return m == Material.TORCH || m == Material.FLOWER_POT || m == Material.RED_ROSE || m == Material.YELLOW_FLOWER || m == Material.LONG_GRASS || m == Material.RED_MUSHROOM || m == Material.BROWN_MUSHROOM || m == Material.TRIPWIRE || m == Material.TRIPWIRE_HOOK || m == Material.DEAD_BUSH || m == Material.DIODE_BLOCK_OFF || m == Material.DIODE_BLOCK_ON || m == Material.REDSTONE_COMPARATOR_OFF || m == Material.REDSTONE_COMPARATOR_OFF || m == Material.REDSTONE_WIRE || m == Material.REDSTONE_TORCH_OFF || m == Material.REDSTONE_TORCH_ON || m == Material.DOUBLE_PLANT || m == Material.SUGAR_CANE_BLOCK; } public static boolean canReallySeeEntity(Player p, LivingEntity e) { BlockIterator bl = new BlockIterator(p, 7); boolean found = false; double md = 1; if (e.getType() == EntityType.WITHER) {//Withers are a bit trippy on distance calculations md = 9; } else if (e.getType() == EntityType.ENDERMAN) { md = 5; } else { md = md + e.getEyeHeight(); } while (bl.hasNext()) { found = true; double d = bl.next().getLocation().distanceSquared(e.getLocation()); if (d <= md) { return true; } } bl = null; if (!found) { return true;//So close to the entity block paths were not generated! } return false; } /** * @deprecated Inaccurate on some entities */ @Deprecated public static LivingEntity getTarget(Player player) { int range = 8; ArrayList<LivingEntity> livingE = new ArrayList<LivingEntity>(); for (Entity e : player.getNearbyEntities(range, range, range)) { if (e instanceof LivingEntity) { livingE.add((LivingEntity) e); } } LivingEntity target = null; BlockIterator bItr = new BlockIterator(player, range); Block block; Location loc; int bx, by, bz; double ex, ey, ez, md = Double.MAX_VALUE, d; // loop through player's line of sight while (bItr.hasNext()) { block = bItr.next(); bx = block.getX(); by = block.getY(); bz = block.getZ(); // check for entities near this block in the line of sight for (LivingEntity e : livingE) { loc = e.getLocation(); ex = loc.getX(); ey = loc.getY(); ez = loc.getZ(); d = loc.distanceSquared(player.getLocation()); if (e.getType() == EntityType.HORSE) { if ((bx - 1.2 <= ex && ex <= bx + 2.2) && (bz - 1.2 <= ez && ez <= bz + 2.2) && (by - 2.5 <= ey && ey <= by + 4.5)) { if (d < md) { md = d; target = e; } } } else { if ((bx - .80 <= ex && ex <= bx + 1.85) && (bz - .80 <= ez && ez <= bz + 1.85) && (by - 2.5 <= ey && ey <= by + 4.5)) { if (d < md) { md = d; target = e; } } } } } livingE.clear(); return target; } public static boolean instantBreak(Material m) { return m == Material.TORCH || m == Material.FLOWER_POT || m == Material.RED_ROSE || m == Material.YELLOW_FLOWER || m == Material.LONG_GRASS || m == Material.RED_MUSHROOM || m == Material.BROWN_MUSHROOM || m == Material.TRIPWIRE || m == Material.TRIPWIRE_HOOK || m == Material.DEAD_BUSH || m == Material.DIODE_BLOCK_OFF || m == Material.DIODE_BLOCK_ON || m == Material.REDSTONE_COMPARATOR_OFF || m == Material.REDSTONE_COMPARATOR_OFF || m == Material.REDSTONE_WIRE || m == Material.REDSTONE_TORCH_OFF || m == Material.REDSTONE_TORCH_ON || m == Material.DOUBLE_PLANT || m == Material.SUGAR_CANE_BLOCK; } @SuppressWarnings("deprecation")//Depercated for "magic value" :/ public static boolean canSeeBlock(Player p, Block b) { /*HashSet<Byte> igb = new HashSet<Byte>(); igb.add((byte) Material.TORCH.getId()); igb.add((byte) Material.AIR.getId()); igb.add((byte) Material.FLOWER_POT.getId()); igb.add((byte) Material.RED_ROSE.getId()); igb.add((byte) Material.YELLOW_FLOWER.getId()); igb.add((byte) Material.LONG_GRASS.getId()); igb.add((byte) Material.RED_MUSHROOM.getId()); igb.add((byte) Material.BROWN_MUSHROOM.getId()); igb.add((byte) Material.STONE_PLATE.getId()); igb.add((byte) Material.WOOD_PLATE.getId()); igb.add((byte) Material.WOOD_STEP.getId()); igb.add((byte) Material.STEP.getId()); igb.add((byte) Material.ANVIL.getId()); igb.add((byte) Material.VINE.getId()); igb.add((byte) Material.LADDER.getId()); igb.add((byte) Material.CAKE_BLOCK.getId()); igb.add((byte) Material.WATER.getId()); igb.add((byte) Material.LAVA.getId()); igb.add((byte) Material.CACTUS.getId()); igb.add((byte) Material.COCOA.getId()); igb.add((byte) Material.CARPET.getId()); igb.add((byte) Material.COBBLE_WALL.getId()); igb.add((byte) Material.NETHER_FENCE.getId()); igb.add((byte) Material.FENCE.getId()); igb.add((byte) Material.FENCE_GATE.getId()); igb.add((byte) Material.TRAP_DOOR.getId()); igb.add((byte) Material.TRIPWIRE_HOOK.getId()); igb.add((byte) Material.THIN_GLASS.getId()); igb.add((byte) Material.STAINED_GLASS_PANE.getId()); igb.add((byte) Material.STATIONARY_WATER.getId()); igb.add((byte) Material.STATIONARY_LAVA.getId()); igb.add((byte) Material.DAYLIGHT_DETECTOR.getId()); igb.add((byte) Material.WOODEN_DOOR.getId()); igb.add((byte) Material.IRON_DOOR_BLOCK.getId()); igb.add((byte) Material.SKULL.getId()); igb.add((byte) Material.DETECTOR_RAIL.getId()); igb.add((byte) Material.RAILS.getId()); igb.add((byte) Material.POWERED_RAIL.getId()); igb.add((byte) Material.SNOW.getId()); igb.add((byte) Material.SIGN_POST.getId()); igb.add((byte) Material.SIGN.getId()); igb.add((byte) Material.DEAD_BUSH.getId()); igb.add((byte) Material.DETECTOR_RAIL.getId()); igb.add((byte) Material.DIODE_BLOCK_ON.getId()); igb.add((byte) Material.DIODE_BLOCK_OFF.getId()); igb.add((byte) Material.REDSTONE_COMPARATOR_OFF.getId()); igb.add((byte) Material.REDSTONE_COMPARATOR_ON.getId()); igb.add((byte) Material.HOPPER.getId()); igb.add((byte) Material.REDSTONE_WIRE.getId()); igb.add((byte) Material.WOOD_BUTTON.getId()); igb.add((byte) Material.STONE_BUTTON.getId()); igb.add((byte) Material.LEVER.getId()); Iterator<Byte> it = igb.iterator(); while(it.hasNext()){ Byte bt = it.next(); if(bt.intValue() == b.getTypeId()){ it.remove(); } } /*new LocationIterator(p.getWorld(), p.getLocation().toVector(), new Vector(b.getX()-p.getLocation().getBlockX(), b.getY()-p.getLocation().getBlockY(), b.getZ()-p.getLocation().getBlockZ()), 0, ((p.getGameMode() == GameMode.CREATIVE) ? 8 : 6)); //new BlockIterator(p.getEyeLocation(), ((p.getGameMode() == GameMode.CREATIVE) ? 8 : 6)); Block s = p.getTargetBlock(igb, ((p.getGameMode() == GameMode.CREATIVE) ? 8 : 6)); //Pretty sure it's the one :3 */ RayTrace rt = RayTrace.eyeTrace(p, ((p.getGameMode() == GameMode.CREATIVE) ? 8 : 6)); Block s = rt.getBlock(); if (s != null) { if (s.getX() == b.getX() && s.getY() == b.getY() && s.getZ() == b.getZ() && s.getType() == b.getType() && s.getData() == b.getData()) { return true; } } return false; } public static int getPing(Player p) { return ((CraftPlayer) p).getHandle().ping; } public static double getXZDistance(double x1, double x2, double z1, double z2) { double a1 = (x2 - x1), a2 = (z2 - z1); return ((a1 * (a1)) + (a2 * a2)); } public static boolean isOnLadder(Player p) { return ((CraftPlayer) p).getHandle().h_(); } public static boolean inWater(Player e) { boolean inWater = false; try { Field f = Class.forName("net.minecraft.server.v1_7_R4.Entity").getDeclaredField("inWater"); f.setAccessible(true); inWater = f.getBoolean(((CraftPlayer) e).getHandle()); } catch (Exception ex) { ex.printStackTrace(); } return inWater; } public static int getPotionEffectLevel(Player p, PotionEffectType pet) { for (PotionEffect pe : p.getActivePotionEffects()) { if (pe.getType().getName().equals(pet.getName())) { return pe.getAmplifier() + 1; } } return 0; } public static String getIP(Player p) { return ((CraftPlayer) p).getHandle().getName(); } public static void messageStaff(String message) { for (Player p : Bukkit.getOnlinePlayers()) { if (p.hasPermission("nohack.notification") || p.isOp()) { p.sendMessage(message); } } } }
gpl-3.0
snavaneethan1/jaffa-framework
jaffa-core/source/httpunittest/java/org/jaffa/applications/test/modules/material/domain/Item.java
16362
// .//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.material.domain; import org.jaffa.datatypes.*; import org.jaffa.metadata.*; import org.jaffa.persistence.Persistent; import org.jaffa.persistence.exceptions.*; import org.jaffa.exceptions.FrameworkException; // .//GEN-END:1_be // Add additional imports//GEN-FIRST:imports // .//GEN-LAST:imports // .//GEN-BEGIN:2_be /** * Auto Generated Persistent class for the ITEM table. * @author Auto-Generated */ public class Item extends Persistent { /** Holds value of property itemId. */ private java.lang.String m_itemId; /** Holds value of property sc. */ private java.lang.String m_sc; /** Holds value of property part. */ private java.lang.String m_part; /** Holds value of property serial. */ private java.lang.String m_serial; /** Holds value of property qty. */ private java.lang.Double m_qty; // .//GEN-END:2_be // .//GEN-BEGIN:itemId_be /** Getter for property itemId. * @return Value of property itemId. */ public java.lang.String getItemId() { return m_itemId; } /** Setter for property itemId. * WARNING: This is strictly for use by the Persistence Engine. A developer should never use this method. Instead, use the update(field.Name.Upper1) method. * @param itemId New value of property itemId. */ public void setItemId(java.lang.String itemId) { m_itemId = itemId; } /** Use this method to update the property itemId. * This method will do nothing and simply return if the input value is the same as the current value. * Validation will be performed on the input value. * This will try to lock the underlying database row, in case CAUTIOUS locking is specified at the time of query. * @param itemId New value of property itemId. * @throws ValidationException if an invalid value is passed. * @throws UpdatePrimaryKeyException if this domain object was loaded from the database. * @throws ReadOnlyObjectException if a Read-Only object is updated. * @throws AlreadyLockedObjectException if the underlying database row is already locked by another process. * @throws FrameworkException Indicates some system error */ public void updateItemId(java.lang.String itemId) throws ValidationException, UpdatePrimaryKeyException, ReadOnlyObjectException, AlreadyLockedObjectException, FrameworkException { // ignore, if the current value and new value are the same if ( m_itemId == null ? itemId == null : m_itemId.equals(itemId) ) return; // this is part of the primary key.. do not update if its a database occurence. if (isDatabaseOccurence()) throw new UpdatePrimaryKeyException(); validateItemId(itemId); // .//GEN-END:itemId_be // Add custom code before setting the value//GEN-FIRST:itemId // .//GEN-LAST:itemId // .//GEN-BEGIN:itemId_1_be super.update(); setItemId(itemId); // .//GEN-END:itemId_1_be // Add custom code after setting the value//GEN-FIRST:itemId_3 // .//GEN-LAST:itemId_3 // .//GEN-BEGIN:itemId_2_be } /** Use this method to validate a value for the property itemId. * @param itemId Value to be validated for the property itemId. * @throws ValidationException if an invalid value is passed * @throws FrameworkException Indicates some system error */ public void validateItemId(java.lang.String itemId) throws ValidationException, FrameworkException { // .//GEN-END:itemId_2_be // Add custom code before validation//GEN-FIRST:itemId_1 // .//GEN-LAST:itemId_1 // .//GEN-BEGIN:itemId_3_be FieldValidator.validate(itemId, (StringFieldMetaData) ItemMeta.META_ITEM_ID, true); // .//GEN-END:itemId_3_be // Add custom code after a successful validation//GEN-FIRST:itemId_2 // .//GEN-LAST:itemId_2 // .//GEN-BEGIN:itemId_4_be } // .//GEN-END:itemId_4_be // .//GEN-BEGIN:sc_be /** Getter for property sc. * @return Value of property sc. */ public java.lang.String getSc() { return m_sc; } /** Setter for property sc. * WARNING: This is strictly for use by the Persistence Engine. A developer should never use this method. Instead, use the update(field.Name.Upper1) method. * @param sc New value of property sc. */ public void setSc(java.lang.String sc) { m_sc = sc; } /** Use this method to update the property sc. * This method will do nothing and simply return if the input value is the same as the current value. * Validation will be performed on the input value. * This will try to lock the underlying database row, in case CAUTIOUS locking is specified at the time of query. * @param sc New value of property sc. * @throws ValidationException if an invalid value is passed. * @throws ReadOnlyObjectException if a Read-Only object is updated. * @throws AlreadyLockedObjectException if the underlying database row is already locked by another process. * @throws FrameworkException Indicates some system error */ public void updateSc(java.lang.String sc) throws ValidationException, ReadOnlyObjectException, AlreadyLockedObjectException, FrameworkException { // ignore, if the current value and new value are the same if ( m_sc == null ? sc == null : m_sc.equals(sc) ) return; validateSc(sc); // .//GEN-END:sc_be // Add custom code before setting the value//GEN-FIRST:sc // .//GEN-LAST:sc // .//GEN-BEGIN:sc_1_be super.update(); setSc(sc); // .//GEN-END:sc_1_be // Add custom code after setting the value//GEN-FIRST:sc_3 // .//GEN-LAST:sc_3 // .//GEN-BEGIN:sc_2_be } /** Use this method to validate a value for the property sc. * @param sc Value to be validated for the property sc. * @throws ValidationException if an invalid value is passed * @throws FrameworkException Indicates some system error */ public void validateSc(java.lang.String sc) throws ValidationException, FrameworkException { // .//GEN-END:sc_2_be // Add custom code before validation//GEN-FIRST:sc_1 // .//GEN-LAST:sc_1 // .//GEN-BEGIN:sc_3_be FieldValidator.validate(sc, (StringFieldMetaData) ItemMeta.META_SC, true); // .//GEN-END:sc_3_be // Add custom code after a successful validation//GEN-FIRST:sc_2 // .//GEN-LAST:sc_2 // .//GEN-BEGIN:sc_4_be } // .//GEN-END:sc_4_be // .//GEN-BEGIN:part_be /** Getter for property part. * @return Value of property part. */ public java.lang.String getPart() { return m_part; } /** Setter for property part. * WARNING: This is strictly for use by the Persistence Engine. A developer should never use this method. Instead, use the update(field.Name.Upper1) method. * @param part New value of property part. */ public void setPart(java.lang.String part) { m_part = part; } /** Use this method to update the property part. * This method will do nothing and simply return if the input value is the same as the current value. * Validation will be performed on the input value. * This will try to lock the underlying database row, in case CAUTIOUS locking is specified at the time of query. * @param part New value of property part. * @throws ValidationException if an invalid value is passed. * @throws ReadOnlyObjectException if a Read-Only object is updated. * @throws AlreadyLockedObjectException if the underlying database row is already locked by another process. * @throws FrameworkException Indicates some system error */ public void updatePart(java.lang.String part) throws ValidationException, ReadOnlyObjectException, AlreadyLockedObjectException, FrameworkException { // ignore, if the current value and new value are the same if ( m_part == null ? part == null : m_part.equals(part) ) return; validatePart(part); // .//GEN-END:part_be // Add custom code before setting the value//GEN-FIRST:part // .//GEN-LAST:part // .//GEN-BEGIN:part_1_be super.update(); setPart(part); // .//GEN-END:part_1_be // Add custom code after setting the value//GEN-FIRST:part_3 // .//GEN-LAST:part_3 // .//GEN-BEGIN:part_2_be } /** Use this method to validate a value for the property part. * @param part Value to be validated for the property part. * @throws ValidationException if an invalid value is passed * @throws FrameworkException Indicates some system error */ public void validatePart(java.lang.String part) throws ValidationException, FrameworkException { // .//GEN-END:part_2_be // Add custom code before validation//GEN-FIRST:part_1 // .//GEN-LAST:part_1 // .//GEN-BEGIN:part_3_be FieldValidator.validate(part, (StringFieldMetaData) ItemMeta.META_PART, true); // .//GEN-END:part_3_be // Add custom code after a successful validation//GEN-FIRST:part_2 // .//GEN-LAST:part_2 // .//GEN-BEGIN:part_4_be } // .//GEN-END:part_4_be // .//GEN-BEGIN:serial_be /** Getter for property serial. * @return Value of property serial. */ public java.lang.String getSerial() { return m_serial; } /** Setter for property serial. * WARNING: This is strictly for use by the Persistence Engine. A developer should never use this method. Instead, use the update(field.Name.Upper1) method. * @param serial New value of property serial. */ public void setSerial(java.lang.String serial) { m_serial = serial; } /** Use this method to update the property serial. * This method will do nothing and simply return if the input value is the same as the current value. * Validation will be performed on the input value. * This will try to lock the underlying database row, in case CAUTIOUS locking is specified at the time of query. * @param serial New value of property serial. * @throws ValidationException if an invalid value is passed. * @throws ReadOnlyObjectException if a Read-Only object is updated. * @throws AlreadyLockedObjectException if the underlying database row is already locked by another process. * @throws FrameworkException Indicates some system error */ public void updateSerial(java.lang.String serial) throws ValidationException, ReadOnlyObjectException, AlreadyLockedObjectException, FrameworkException { // ignore, if the current value and new value are the same if ( m_serial == null ? serial == null : m_serial.equals(serial) ) return; validateSerial(serial); // .//GEN-END:serial_be // Add custom code before setting the value//GEN-FIRST:serial // .//GEN-LAST:serial // .//GEN-BEGIN:serial_1_be super.update(); setSerial(serial); // .//GEN-END:serial_1_be // Add custom code after setting the value//GEN-FIRST:serial_3 // .//GEN-LAST:serial_3 // .//GEN-BEGIN:serial_2_be } /** Use this method to validate a value for the property serial. * @param serial Value to be validated for the property serial. * @throws ValidationException if an invalid value is passed * @throws FrameworkException Indicates some system error */ public void validateSerial(java.lang.String serial) throws ValidationException, FrameworkException { // .//GEN-END:serial_2_be // Add custom code before validation//GEN-FIRST:serial_1 // .//GEN-LAST:serial_1 // .//GEN-BEGIN:serial_3_be FieldValidator.validate(serial, (StringFieldMetaData) ItemMeta.META_SERIAL, true); // .//GEN-END:serial_3_be // Add custom code after a successful validation//GEN-FIRST:serial_2 // .//GEN-LAST:serial_2 // .//GEN-BEGIN:serial_4_be } // .//GEN-END:serial_4_be // .//GEN-BEGIN:qty_be /** Getter for property qty. * @return Value of property qty. */ public java.lang.Double getQty() { return m_qty; } /** Setter for property qty. * WARNING: This is strictly for use by the Persistence Engine. A developer should never use this method. Instead, use the update(field.Name.Upper1) method. * @param qty New value of property qty. */ public void setQty(java.lang.Double qty) { m_qty = qty; } /** Use this method to update the property qty. * This method will do nothing and simply return if the input value is the same as the current value. * Validation will be performed on the input value. * This will try to lock the underlying database row, in case CAUTIOUS locking is specified at the time of query. * @param qty New value of property qty. * @throws ValidationException if an invalid value is passed. * @throws ReadOnlyObjectException if a Read-Only object is updated. * @throws AlreadyLockedObjectException if the underlying database row is already locked by another process. * @throws FrameworkException Indicates some system error */ public void updateQty(java.lang.Double qty) throws ValidationException, ReadOnlyObjectException, AlreadyLockedObjectException, FrameworkException { // ignore, if the current value and new value are the same if ( m_qty == null ? qty == null : m_qty.equals(qty) ) return; validateQty(qty); // .//GEN-END:qty_be // Add custom code before setting the value//GEN-FIRST:qty // .//GEN-LAST:qty // .//GEN-BEGIN:qty_1_be super.update(); setQty(qty); // .//GEN-END:qty_1_be // Add custom code after setting the value//GEN-FIRST:qty_3 // .//GEN-LAST:qty_3 // .//GEN-BEGIN:qty_2_be } /** Use this method to validate a value for the property qty. * @param qty Value to be validated for the property qty. * @throws ValidationException if an invalid value is passed * @throws FrameworkException Indicates some system error */ public void validateQty(java.lang.Double qty) throws ValidationException, FrameworkException { // .//GEN-END:qty_2_be // Add custom code before validation//GEN-FIRST:qty_1 // .//GEN-LAST:qty_1 // .//GEN-BEGIN:qty_3_be FieldValidator.validate(qty, (DecimalFieldMetaData) ItemMeta.META_QTY, true); // .//GEN-END:qty_3_be // Add custom code after a successful validation//GEN-FIRST:qty_2 // .//GEN-LAST:qty_2 // .//GEN-BEGIN:qty_4_be } // .//GEN-END:qty_4_be // .//GEN-BEGIN:3_be /** This returns the diagnostic information. * @return the diagnostic information. */ public String toString() { StringBuffer buf = new StringBuffer(); buf.append("<Item>"); buf.append("<itemId>"); if (m_itemId != null) buf.append(m_itemId); buf.append("</itemId>"); buf.append("<sc>"); if (m_sc != null) buf.append(m_sc); buf.append("</sc>"); buf.append("<part>"); if (m_part != null) buf.append(m_part); buf.append("</part>"); buf.append("<serial>"); if (m_serial != null) buf.append(m_serial); buf.append("</serial>"); buf.append("<qty>"); if (m_qty != null) buf.append(m_qty); buf.append("</qty>"); buf.append(super.toString()); buf.append("</Item>"); return buf.toString(); } // .//GEN-END:3_be // All the custom code goes here//GEN-FIRST:custom // .//GEN-LAST:custom }
gpl-3.0
tchoulihan/direct_democracy
src/main/java/com/referendum/voting/voting_system/VotingSystem.java
196
package com.referendum.voting.voting_system; public interface VotingSystem { enum VotingSystemType { MULTIPLE_CHOICE, SINGLE_CHOICE; } abstract VotingSystemType getVotingSystemType(); }
gpl-3.0
PrismTech/opensplice
src/api/dcps/java5/common/java/code/org/opensplice/dds/core/policy/PartitionImpl.java
3474
/* * 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.core.policy; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.omg.dds.core.policy.Partition; import org.omg.dds.core.policy.QosPolicy; import org.opensplice.dds.core.IllegalArgumentExceptionImpl; import org.opensplice.dds.core.OsplServiceEnvironment; public class PartitionImpl extends QosPolicyImpl implements Partition { private static final long serialVersionUID = 3060990234546666051L; private final HashSet<String> name; public PartitionImpl(OsplServiceEnvironment environment) { super(environment); this.name = new HashSet<String>(); this.name.add(""); } public PartitionImpl(OsplServiceEnvironment environment, Collection<String> name) { super(environment); if (name == null) { throw new IllegalArgumentExceptionImpl(environment, "Supplied name is invalid."); } this.name = new HashSet<String>(name); if(this.name.size() == 0){ this.name.add(""); } } public PartitionImpl(OsplServiceEnvironment environment, String... name) { super(environment); this.name = new HashSet<String>(); for(String partition: name){ this.name.add(partition); } if(this.name.size() == 0){ this.name.add(""); } } @Override public Set<String> getName() { return Collections.unmodifiableSet(this.name); } @Override public Partition withName(Collection<String> name) { return new PartitionImpl(this.environment, name); } @Override public Partition withName(String... names) { return new PartitionImpl(this.environment, names); } @Override public Class<? extends QosPolicy> getPolicyClass() { return Partition.class; } @Override public Partition withName(String name) { return new PartitionImpl(this.environment, name); } @Override public boolean equals(Object other) { if (!(other instanceof PartitionImpl)) { return false; } PartitionImpl p = (PartitionImpl) other; if (this.name.size() != p.name.size()) { return false; } if (!this.name.containsAll(p.name)) { return false; } return true; } @Override public int hashCode() { final int prime = 31; int result = 17; for (String name : this.name) { result = prime * result + name.hashCode(); } return result; } }
gpl-3.0
bannergz/Spring_uni
CLASES/Clase4/SpringJDBC/src/main/java/pe/egcc/app/domain/Cliente.java
1757
package pe.egcc.app.domain; public class Cliente { private String codigo; private String paterno; private String materno; private String nombre; private String dni; private String ciudad; private String direccion; private String telefono; private String email; public Cliente() { super(); } public Cliente(String codigo, String paterno, String materno, String nombre, String dni, String ciudad, String direccion, String telefono, String email) { super(); this.codigo = codigo; this.paterno = paterno; this.materno = materno; this.nombre = nombre; this.dni = dni; this.ciudad = ciudad; this.direccion = direccion; this.telefono = telefono; this.email = email; } public String getCodigo() { return codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } public String getPaterno() { return paterno; } public void setPaterno(String paterno) { this.paterno = paterno; } public String getMaterno() { return materno; } public void setMaterno(String materno) { this.materno = materno; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getDni() { return dni; } public void setDni(String dni) { this.dni = dni; } public String getCiudad() { return ciudad; } public void setCiudad(String ciudad) { this.ciudad = ciudad; } public String getDireccion() { return direccion; } public void setDireccion(String direccion) { this.direccion = direccion; } public String getTelefono() { return telefono; } public void setTelefono(String telefono) { this.telefono = telefono; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
gpl-3.0
uniwue-dmir/de.uniwue.dmir.heatmap
heatmap-core/src/test/java/de/uniwue/dmir/heatmap/filters/FilterDimensionsTest.java
4058
/** * Heatmap Framework - Core * * Copyright (C) 2013 Martin Becker * becker@informatik.uni-wuerzburg.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/gpl-3.0.html>. */ package de.uniwue.dmir.heatmap.filters; import java.util.Arrays; import java.util.List; import org.junit.Assert; import org.junit.Test; import de.uniwue.dmir.heatmap.IFilter; import de.uniwue.dmir.heatmap.TileSize; import de.uniwue.dmir.heatmap.tiles.coordinates.TileCoordinates; @SuppressWarnings({"rawtypes", "unchecked"}) public class FilterDimensionsTest { @Test public void simpleTestY1() { List<IFilter> filters = Arrays.asList(new IFilter[] { new TestFilter(1, 1, 0, 0), new TestFilter(1, 1, 0, 0), new TestFilter(1, 1, 0, 0), }); FilterDimensions filterDimensions = new FilterDimensions(filters); Assert.assertEquals( new FilterDimensions(1,1,0,0), filterDimensions); } @Test public void simpleTestY2() { List<IFilter> filters = Arrays.asList(new IFilter[] { new TestFilter(1, 1, 0, 0), new TestFilter(1, 1, 0, 0), new TestFilter(1, 3, 0, 0), }); FilterDimensions filterDimensions = new FilterDimensions(filters); Assert.assertEquals( new FilterDimensions(1,3,0,0), filterDimensions); } @Test public void simpleTestY3() { List<IFilter> filters = Arrays.asList(new IFilter[] { new TestFilter(1, 1, 0, 0), new TestFilter(1, 1, 0, 0), new TestFilter(1, 3, 0, 2), }); FilterDimensions filterDimensions = new FilterDimensions(filters); Assert.assertEquals( new FilterDimensions(1,3,0,2), filterDimensions); } @Test public void simpleTestY4() { List<IFilter> filters = Arrays.asList(new IFilter[] { new TestFilter(1, 2, 0, 0), new TestFilter(1, 1, 0, 0), new TestFilter(1, 3, 0, 2), }); FilterDimensions filterDimensions = new FilterDimensions(filters); Assert.assertEquals( new FilterDimensions(1,4,0,2), filterDimensions); } @Test public void simpleTestX2() { List<IFilter> filters = Arrays.asList(new IFilter[] { new TestFilter(1, 1, 0, 0), new TestFilter(1, 1, 0, 0), new TestFilter(3, 1, 0, 0), }); FilterDimensions filterDimensions = new FilterDimensions(filters); Assert.assertEquals( new FilterDimensions(3,1,0,0), filterDimensions); } @Test public void simpleTestX3() { List<IFilter> filters = Arrays.asList(new IFilter[] { new TestFilter(1, 1, 0, 0), new TestFilter(1, 1, 0, 0), new TestFilter(3, 1, 2, 0), }); FilterDimensions filterDimensions = new FilterDimensions(filters); Assert.assertEquals( new FilterDimensions(3,1,2,0), filterDimensions); } @Test public void simpleTestX4() { List<IFilter> filters = Arrays.asList(new IFilter[] { new TestFilter(2, 1, 0, 0), new TestFilter(1, 1, 0, 0), new TestFilter(3, 1, 2, 0), }); FilterDimensions filterDimensions = new FilterDimensions(filters); Assert.assertEquals( new FilterDimensions(4,1,2,0), filterDimensions); } public static class TestFilter extends AbstractConfigurableFilter { public TestFilter( int width, int height, int centerX, int centerY) { this.width = width; this.height = height; this.centerX = centerX; this.centerY = centerY; } @Override public void filter( Object dataPoint, Object tile, TileSize tileSize, TileCoordinates tileCoordinates) { } } }
gpl-3.0
vitaly-krumins/ssj
libssj/src/main/java/hcm/ssj/core/stream/ByteStream.java
3334
/* * ByteStream.java * Copyright (c) 2017 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or any later version. * * This 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 General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.core.stream; import hcm.ssj.core.Cons; /** * Created by Johnny on 11.06.2015. */ public class ByteStream extends Stream { protected byte[] _ptr; public ByteStream(int num, int dim, double sr) { super(num, dim, sr); this.bytes = 1; this.type = Cons.Type.BYTE; tot = num * dim * bytes; _ptr = new byte[tot]; } @Override public byte[] ptr() { return _ptr; } public byte[] ptrB() { return _ptr; } public void adjust(int num) { if(num < this.num) { this.num = num; this.tot = num * dim * bytes; } else { this.num = num; this.tot = num * dim * bytes; _ptr = new byte[tot]; } } public ByteStream select(int[] new_dims) { if(dim == new_dims.length) return this; ByteStream slice = new ByteStream(num, new_dims.length, sr); slice.source = source; byte[] src = this.ptr(); byte[] dst = slice.ptr(); int srcPos = 0, dstPos = 0; while(srcPos < num * dim) { for(int i = 0; i < new_dims.length; i++) dst[dstPos++] = src[srcPos + new_dims[i]]; srcPos += dim; } return slice; } public ByteStream select(int new_dim) { if(dim == 1) return this; ByteStream slice = new ByteStream(num, 1, sr); slice.source = source; byte[] src = this.ptr(); byte[] dst = slice.ptr(); int srcPos = 0, dstPos = 0; while(srcPos < num * dim) { dst[dstPos++] = src[srcPos + new_dim]; srcPos += dim; } return slice; } @Override public Stream clone() { ByteStream copy = new ByteStream(num, dim, sr); System.arraycopy(_ptr, 0, copy._ptr, 0, _ptr.length); return copy; } }
gpl-3.0
micromata/projectforge-webapp
src/test/java/org/projectforge/timesheet/TimesheetMassUpdateTest.java
16458
///////////////////////////////////////////////////////////////////////////// // // Project ProjectForge Community Edition // www.projectforge.org // // Copyright (C) 2001-2014 Kai Reinhard (k.reinhard@micromata.de) // // ProjectForge is dual-licensed. // // This community edition 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 3 of the License. // // This community edition 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.projectforge.timesheet; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import org.junit.Test; import org.projectforge.common.DateHolder; import org.projectforge.common.DatePrecision; import org.projectforge.core.BaseDao; import org.projectforge.core.UserException; import org.projectforge.fibu.KundeDO; import org.projectforge.fibu.KundeDao; import org.projectforge.fibu.ProjektDO; import org.projectforge.fibu.ProjektDao; import org.projectforge.fibu.kost.Kost2DO; import org.projectforge.fibu.kost.Kost2Dao; import org.projectforge.task.TaskDO; import org.projectforge.task.TaskDao; import org.projectforge.test.TestBase; public class TimesheetMassUpdateTest extends TestBase { // private static final Logger log = Logger.getLogger(TaskTest.class); private TimesheetDao timesheetDao; private TaskDao taskDao; private KundeDao kundeDao; private Kost2Dao kost2Dao; private ProjektDao projektDao; private DateHolder date = new DateHolder(new Date(), DatePrecision.MINUTE_15, Locale.GERMAN); public void setTimesheetDao(TimesheetDao timesheetDao) { this.timesheetDao = timesheetDao; } public void setTaskDao(TaskDao taskDao) { this.taskDao = taskDao; } public void setKundeDao(KundeDao kundeDao) { this.kundeDao = kundeDao; } public void setKost2Dao(Kost2Dao kost2Dao) { this.kost2Dao = kost2Dao; } public void setProjektDao(ProjektDao projektDao) { this.projektDao = projektDao; } @Test public void massUpdate() { final String prefix = "ts-mu1-"; final List<TimesheetDO> list = new ArrayList<TimesheetDO>(); getInitTestDB().addTask(prefix + "1", "root"); getInitTestDB().addTask(prefix + "1.1", prefix + "1"); getInitTestDB().addTask(prefix + "1.2", prefix + "1"); getInitTestDB().addTask(prefix + "2", "root"); getInitTestDB().addUser(prefix + "user1"); logon(getUser(TEST_FINANCE_USER)); list.add(createTimesheet(prefix, "1.1", "user1", 2009, 10, 21, 3, 0, 3, 15, "Office", "A lot of stuff done and more.")); list.add(createTimesheet(prefix, "1.2", "user1", 2009, 10, 21, 3, 15, 3, 30, "Office", "A lot of stuff done and more.")); TimesheetDO master = new TimesheetDO(); master.setTask(getInitTestDB().getTask(prefix + "2")); master.setLocation("Headquarter"); timesheetDao.massUpdate(list, master); assertAll(list, master); } @Test public void massUpdateWithKost2Transformation() { logon(getUser(TEST_FINANCE_USER)); final String prefix = "ts-mu50-"; final List<TimesheetDO> list = new ArrayList<TimesheetDO>(); final KundeDO kunde = new KundeDO(); kunde.setName("ACME"); kunde.setId(50); kundeDao.save(kunde); final ProjektDO projekt1 = createProjekt(kunde, 1, "Webportal", 0, 1, 2); final ProjektDO projekt2 = createProjekt(kunde, 2, "iPhone App", 0, 1); final TaskDO t1 = getInitTestDB().addTask(prefix + "1", "root"); projektDao.setTask(projekt1, t1.getId()); projektDao.update(projekt1); getInitTestDB().addTask(prefix + "1.1", prefix + "1"); getInitTestDB().addTask(prefix + "1.2", prefix + "1"); final TaskDO t2 = getInitTestDB().addTask(prefix + "2", "root"); projektDao.setTask(projekt2, t2.getId()); projektDao.update(projekt2); getInitTestDB().addTask(prefix + "2.1", prefix + "2"); getInitTestDB().addUser(prefix + "user1"); logon(getUser(TEST_ADMIN_USER)); list.add(createTimesheet(prefix, "1.1", "user1", 2009, 10, 21, 3, 0, 3, 15, "Office", "A lot of stuff done and more.", 5, 50, 1, 0)); list.add(createTimesheet(prefix, "1.2", "user1", 2009, 10, 21, 3, 15, 3, 30, "Office", "A lot of stuff done and more.", 5, 50, 1, 1)); list.add(createTimesheet(prefix, "1.2", "user1", 2009, 10, 21, 3, 30, 3, 45, "Office", "A lot of stuff done and more.", 5, 50, 1, 2)); final TimesheetDO master = new TimesheetDO(); master.setTask(getInitTestDB().getTask(prefix + "2")); master.setLocation("Headquarter"); timesheetDao.massUpdate(list, master); assertSheet(list.get(0), master); assertKost2(list.get(0), 5, 50, 2, 0); // Kost2 transformed. assertSheet(list.get(1), master); assertKost2(list.get(1), 5, 50, 2, 1); // Kost2 transformed. assertKost2(list.get(2), 5, 50, 1, 2); // Kost2 not transformed. assertEquals(getTask(prefix + "1.2").getId(), list.get(2).getTaskId()); } @Test public void massUpdateWithKost2() { logon(getUser(TEST_FINANCE_USER)); final String prefix = "ts-mu51-"; final List<TimesheetDO> list = new ArrayList<TimesheetDO>(); final KundeDO kunde = new KundeDO(); kunde.setName("ACME ltd."); kunde.setId(51); kundeDao.save(kunde); final ProjektDO projekt1 = createProjekt(kunde, 1, "Webportal", 0, 1, 2); final ProjektDO projekt2 = createProjekt(kunde, 2, "iPhone App", 0, 1); final TaskDO t1 = getInitTestDB().addTask(prefix + "1", "root"); projektDao.setTask(projekt1, t1.getId()); projektDao.update(projekt1); getInitTestDB().addTask(prefix + "1.1", prefix + "1"); getInitTestDB().addTask(prefix + "1.2", prefix + "1"); final TaskDO t2 = getInitTestDB().addTask(prefix + "2", "root"); projektDao.setTask(projekt2, t2.getId()); projektDao.update(projekt2); getInitTestDB().addTask(prefix + "2.1", prefix + "2"); getInitTestDB().addUser(prefix + "user1"); logon(getUser(TEST_ADMIN_USER)); list.add(createTimesheet(prefix, "1.1", "user1", 2009, 10, 21, 3, 0, 3, 15, "Office", "A lot of stuff done and more.", 5, 51, 1, 0)); list.add(createTimesheet(prefix, "1.2", "user1", 2009, 10, 21, 3, 15, 3, 30, "Office", "A lot of stuff done and more.", 5, 51, 1, 1)); list.add(createTimesheet(prefix, "1.2", "user1", 2009, 10, 21, 3, 30, 3, 45, "Office", "A lot of stuff done and more.", 5, 51, 1, 2)); final TimesheetDO master = new TimesheetDO(); master.setTask(getInitTestDB().getTask(prefix + "2")); master.setLocation("Headquarter"); Kost2DO kost2 = kost2Dao.getKost2(5, 51, 1, 0); // Kost2 is not supported by destination task. assertNotNull(kost2); master.setKost2(kost2); timesheetDao.massUpdate(list, master); assertEquals(getTask(prefix + "1.1").getId(), list.get(0).getTaskId()); // Not moved. assertEquals(getTask(prefix + "1.2").getId(), list.get(1).getTaskId()); // Not moved. assertEquals(getTask(prefix + "1.2").getId(), list.get(2).getTaskId()); // Not moved. assertKost2(list.get(0), 5, 51, 1, 0); // Kost2 not transformed. assertKost2(list.get(1), 5, 51, 1, 1); // Kost2 not transformed. assertKost2(list.get(2), 5, 51, 1, 2); // Kost2 not transformed. kost2 = kost2Dao.getKost2(5, 51, 2, 0); // Kost2 supported by destination task. assertNotNull(kost2); master.setKost2(kost2); timesheetDao.massUpdate(list, master); assertAll(list, master); // All sheets moved. assertKost2(list.get(0), 5, 51, 2, 0); // Kost2 transformed. assertKost2(list.get(1), 5, 51, 2, 0); // Kost2 transformed. assertKost2(list.get(2), 5, 51, 2, 0); // Kost2 transformed. } @Test public void massUpdateMixedKost2() { logon(getUser(TEST_FINANCE_USER)); final String prefix = "ts-mu52-"; final List<TimesheetDO> list = new ArrayList<TimesheetDO>(); final KundeDO kunde = new KundeDO(); kunde.setName("ACME International"); kunde.setId(52); kundeDao.save(kunde); final ProjektDO projekt1 = createProjekt(kunde, 1, "Webportal", 0, 1, 2); getInitTestDB().addTask(prefix + "1", "root"); getInitTestDB().addTask(prefix + "1.1", prefix + "1"); getInitTestDB().addTask(prefix + "1.2", prefix + "1"); final TaskDO t2 = getInitTestDB().addTask(prefix + "2", "root"); projektDao.setTask(projekt1, t2.getId()); projektDao.update(projekt1); getInitTestDB().addTask(prefix + "2.1", prefix + "2"); getInitTestDB().addUser(prefix + "user1"); logon(getUser(TEST_ADMIN_USER)); list.add(createTimesheet(prefix, "1.1", "user1", 2009, 10, 21, 3, 0, 3, 15, "Office", "A lot of stuff done and more.")); list.add(createTimesheet(prefix, "1.2", "user1", 2009, 10, 21, 3, 15, 3, 30, "Office", "A lot of stuff done and more.")); list.add(createTimesheet(prefix, "1.2", "user1", 2009, 10, 21, 3, 30, 3, 45, "Office", "A lot of stuff done and more.")); final TimesheetDO master = new TimesheetDO(); master.setTask(getInitTestDB().getTask(prefix + "2")); master.setLocation("Headquarter"); timesheetDao.massUpdate(list, master); assertEquals(getTask(prefix + "1.1").getId(), list.get(0).getTaskId()); // Not moved. assertEquals(getTask(prefix + "1.2").getId(), list.get(1).getTaskId()); // Not moved. assertEquals(getTask(prefix + "1.2").getId(), list.get(2).getTaskId()); // Not moved. assertNull(list.get(0).getKost2Id()); // Kost2 not set. assertNull(list.get(1).getKost2Id()); // Kost2 not set. assertNull(list.get(2).getKost2Id()); // Kost2 not set. final Kost2DO kost2 = kost2Dao.getKost2(5, 52, 1, 0); // Kost2 supported by destination task. assertNotNull(kost2); master.setKost2(kost2); timesheetDao.massUpdate(list, master); assertAll(list, master); // All sheets moved. assertKost2(list.get(0), 5, 52, 1, 0); // Kost2 set. assertKost2(list.get(1), 5, 52, 1, 0); // Kost2 set. assertKost2(list.get(2), 5, 52, 1, 0); // Kost2 set. } @Test public void checkMassUpdateWithTimesheetProtection() { logon(getUser(TEST_FINANCE_USER)); final String prefix = "ts-mu53-"; final List<TimesheetDO> list = new ArrayList<TimesheetDO>(); final KundeDO kunde = new KundeDO(); kunde.setName("ACME ltd."); kunde.setId(53); kundeDao.save(kunde); final TaskDO t1 = getInitTestDB().addTask(prefix + "1", "root"); final ProjektDO projekt1 = createProjekt(kunde, 1, "Webportal", 0, 1, 2); projektDao.update(projekt1.setTask(t1)); final ProjektDO projekt2 = createProjekt(kunde, 2, "iPhone App", 0, 1); getInitTestDB().addTask(prefix + "1.1", prefix + "1"); getInitTestDB().addTask(prefix + "1.2", prefix + "1"); final TaskDO t2 = getInitTestDB().addTask(prefix + "2", "root"); projektDao.setTask(projekt2, t2.getId()); projektDao.update(projekt2); final DateHolder dh = new DateHolder(); dh.setDate(2009, 11, 31); t2.setProtectTimesheetsUntil(dh.getDate()); taskDao.update(t2); getInitTestDB().addTask(prefix + "2.1", prefix + "2"); getInitTestDB().addTask(prefix + "2.2", prefix + "2"); getInitTestDB().addUser(prefix + "user"); final TimesheetDO ts1 = createTimesheet(prefix, "1.1", "user", 2009, 10, 21, 3, 0, 3, 15, "Office", "A lot of stuff done and more.", 5, 53, 1, 0); list.add(ts1); final TimesheetDO ts2 = createTimesheet(prefix, "1.2", "user", 2009, 10, 21, 3, 15, 3, 30, "Office", "A lot of stuff done and more.", 5, 53, 1, 1); list.add(ts2); final TimesheetDO ts3 = createTimesheet(prefix, "2.1", "user", 2009, 10, 21, 3, 30, 3, 45, "Office", "A lot of stuff done and more.", 5, 53, 2, 0); list.add(ts3); logon(getUser(TEST_ADMIN_USER)); final TimesheetDO master = new TimesheetDO(); master.setTask(getInitTestDB().getTask(prefix + "2.2")); timesheetDao.massUpdate(list, master); TimesheetDO ts = timesheetDao.getById(ts1.getId()); assertEquals(getTask(prefix + "1.1").getId(), ts.getTaskId()); // Not moved. assertKost2(ts, 5, 53, 1, 0); // Kost2 unmodified. ts = timesheetDao.getById(ts2.getId()); assertEquals(getTask(prefix + "1.2").getId(), ts.getTaskId()); // Not moved. assertKost2(ts, 5, 53, 1, 1); // Kost2 unmodified. assertSheet(list.get(2), master); assertKost2(list.get(2), 5, 53, 2, 0); // Kost2 unmodified. } @Test public void checkMaxMassUpdateNumber() { final List<TimesheetDO> list = new ArrayList<TimesheetDO>(); for (int i = 0; i <= BaseDao.MAX_MASS_UPDATE; i++) { list.add(new TimesheetDO()); } try { timesheetDao.massUpdate(list, new TimesheetDO()); fail("Maximum number of allowed mass updates exceeded. Not detected!"); } catch (UserException ex) { assertEquals(BaseDao.MAX_MASS_UPDATE_EXCEEDED_EXCEPTION_I18N, ex.getI18nKey()); // OK. } } private ProjektDO createProjekt(final KundeDO kunde, final Integer projektNummer, final String projektName, final Integer... kost2ArtIds) { return initTestDB.addProjekt(kunde, projektNummer, projektName, kost2ArtIds); } private void assertAll(final List<TimesheetDO> list, final TimesheetDO master) { for (final TimesheetDO sheet : list) { assertSheet(sheet, master); } } private void assertSheet(final TimesheetDO sheet, final TimesheetDO master) { if (master.getTaskId() != null) { assertEquals(master.getTaskId(), sheet.getTaskId()); } if (master.getLocation() != null) { assertEquals(master.getLocation(), sheet.getLocation()); } } private void assertKost2(final TimesheetDO sheet, final int nummernkreis, final int bereich, final int teilbereich, final int art) { final Kost2DO kost2 = sheet.getKost2(); assertNotNull(kost2); assertEquals(nummernkreis, kost2.getNummernkreis()); assertEquals(bereich, kost2.getBereich()); assertEquals(teilbereich, kost2.getTeilbereich()); assertEquals(art, (int) kost2.getKost2ArtId()); } private TimesheetDO createTimesheet(final String prefix, final String taskName, final String userName, final int year, final int month, final int day, final int fromHour, final int fromMinute, final int toHour, final int toMinute, final String location, final String description) { return createTimesheet(prefix, taskName, userName, year, month, day, fromHour, fromMinute, toHour, toMinute, location, description, 0, 0, 0, 0); } private TimesheetDO createTimesheet(final String prefix, final String taskName, final String userName, final int year, final int month, final int day, final int fromHour, final int fromMinute, final int toHour, final int toMinute, final String location, final String description, final int kost2Nummernkreis, final int kost2Bereich, final int kost2Teilbereich, final int kost2Art) { final TimesheetDO ts = new TimesheetDO(); setTimeperiod(ts, year, month, day, fromHour, fromMinute, day, toHour, toMinute); ts.setTask(initTestDB.getTask(prefix + taskName)); ts.setUser(getUser(prefix + userName)); ts.setLocation(location); ts.setDescription(description); if (kost2Nummernkreis > 0) { final Kost2DO kost2 = kost2Dao.getKost2(kost2Nummernkreis, kost2Bereich, kost2Teilbereich, kost2Art); assertNotNull(kost2); ts.setKost2(kost2); } final Serializable id = timesheetDao.internalSave(ts); return timesheetDao.getById(id); } private void setTimeperiod(TimesheetDO timesheet, int year, int month, int fromDay, int fromHour, int fromMinute, int toDay, int toHour, int toMinute) { date.setDate(year, month, fromDay, fromHour, fromMinute, 0); timesheet.setStartTime(date.getTimestamp()); date.setDate(year, month, toDay, toHour, toMinute, 0); timesheet.setStopTime(date.getTimestamp()); } }
gpl-3.0
svenoaks/QuickLyric
QuickLyric/src/main/java/com/geecko/QuickLyric/utils/IMMLeaks.java
8311
/* * * * * This file is part of QuickLyric * * Copyright © 2017 QuickLyric SPRL * * * * QuickLyric 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. * * * * QuickLyric 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 QuickLyric. If not, see <http://www.gnu.org/licenses/>. * */ package com.geecko.QuickLyric.utils; import android.app.Activity; import android.app.Application; import android.content.Context; import android.content.ContextWrapper; import android.os.Looper; import android.os.MessageQueue; import android.util.Log; import android.view.View; import android.view.ViewTreeObserver; import android.view.inputmethod.InputMethodManager; import java.lang.reflect.Field; import java.lang.reflect.Method; import static android.content.Context.INPUT_METHOD_SERVICE; import static android.os.Build.VERSION.SDK_INT; import static android.os.Build.VERSION_CODES.KITKAT; public class IMMLeaks { static class ReferenceCleaner implements MessageQueue.IdleHandler, View.OnAttachStateChangeListener, ViewTreeObserver.OnGlobalFocusChangeListener { private final InputMethodManager inputMethodManager; private final Field mHField; private final Field mServedViewField; private final Method finishInputLockedMethod; ReferenceCleaner(InputMethodManager inputMethodManager, Field mHField, Field mServedViewField, Method finishInputLockedMethod) { this.inputMethodManager = inputMethodManager; this.mHField = mHField; this.mServedViewField = mServedViewField; this.finishInputLockedMethod = finishInputLockedMethod; } @Override public void onGlobalFocusChanged(View oldFocus, View newFocus) { if (newFocus == null) { return; } if (oldFocus != null) { oldFocus.removeOnAttachStateChangeListener(this); } Looper.myQueue().removeIdleHandler(this); newFocus.addOnAttachStateChangeListener(this); } @Override public void onViewAttachedToWindow(View v) { } @Override public void onViewDetachedFromWindow(View v) { v.removeOnAttachStateChangeListener(this); Looper.myQueue().removeIdleHandler(this); Looper.myQueue().addIdleHandler(this); } @Override public boolean queueIdle() { clearInputMethodManagerLeak(); return false; } private void clearInputMethodManagerLeak() { try { Object lock = mHField.get(inputMethodManager); // This is highly dependent on the InputMethodManager implementation. synchronized (lock) { View servedView = (View) mServedViewField.get(inputMethodManager); if (servedView != null) { boolean servedViewAttached = servedView.getWindowVisibility() != View.GONE; if (servedViewAttached) { // The view held by the IMM was replaced without a global focus change. Let's make // sure we get notified when that view detaches. // Avoid double registration. servedView.removeOnAttachStateChangeListener(this); servedView.addOnAttachStateChangeListener(this); } else { // servedView is not attached. InputMethodManager is being stupid! Activity activity = extractActivity(servedView.getContext()); if (activity == null || activity.getWindow() == null) { // Unlikely case. Let's finish the input anyways. finishInputLockedMethod.invoke(inputMethodManager); } else { View decorView = activity.getWindow().peekDecorView(); boolean windowAttached = decorView.getWindowVisibility() != View.GONE; if (!windowAttached) { finishInputLockedMethod.invoke(inputMethodManager); } else { decorView.requestFocusFromTouch(); } } } } } } catch (Exception unexpected) { Log.e("IMMLeaks", "Unexpected reflection exception", unexpected); } } private Activity extractActivity(Context context) { while (true) { if (context instanceof Application) { return null; } else if (context instanceof Activity) { return (Activity) context; } else if (context instanceof ContextWrapper) { Context baseContext = ((ContextWrapper) context).getBaseContext(); // Prevent Stack Overflow. if (baseContext == context) { return null; } context = baseContext; } else { return null; } } } } /** * Fix for https://code.google.com/p/android/issues/detail?id=171190 . * * When a view that has focus gets detached, we wait for the main thread to be idle and then * check if the InputMethodManager is leaking a view. If yes, we tell it that the decor view got * focus, which is what happens if you press home and come back from recent apps. This replaces * the reference to the detached view with a reference to the decor view. * * Should be called from {@link Activity#onCreate(android.os.Bundle)} )}. */ public static void fixFocusedViewLeak(Application application) { // Don't know about other versions yet. if (SDK_INT < KITKAT || SDK_INT > 23) { return; } final InputMethodManager inputMethodManager = (InputMethodManager) application.getSystemService(INPUT_METHOD_SERVICE); final Field mServedViewField; final Field mHField; final Method finishInputLockedMethod; final Method focusInMethod; try { mServedViewField = InputMethodManager.class.getDeclaredField("mServedView"); mServedViewField.setAccessible(true); mHField = InputMethodManager.class.getDeclaredField("mServedView"); mHField.setAccessible(true); finishInputLockedMethod = InputMethodManager.class.getDeclaredMethod("finishInputLocked"); finishInputLockedMethod.setAccessible(true); focusInMethod = InputMethodManager.class.getDeclaredMethod("focusIn", View.class); focusInMethod.setAccessible(true); } catch (Exception unexpected) { Log.e("IMMLeaks", "Unexpected reflection exception", unexpected); return; } application.registerActivityLifecycleCallbacks(new LifecycleCallbacksAdapter() { @Override public void onActivityStarted(Activity activity) { ReferenceCleaner cleaner = new ReferenceCleaner(inputMethodManager, mHField, mServedViewField, finishInputLockedMethod); View rootView = activity.getWindow().getDecorView().getRootView(); ViewTreeObserver viewTreeObserver = rootView.getViewTreeObserver(); viewTreeObserver.addOnGlobalFocusChangeListener(cleaner); } }); } }
gpl-3.0
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/models/user/Buffs.java
2919
package com.habitrpg.android.habitica.models.user; import com.google.gson.annotations.SerializedName; import io.realm.RealmObject; import io.realm.annotations.PrimaryKey; public class Buffs extends RealmObject { @PrimaryKey private String userId; public Float con, str, per; @SerializedName("int") public Float _int; private Boolean snowball; private Boolean streaks; private Boolean seafoam; private Boolean spookySparkles; private Boolean shinySeed; public Buffs() { this(false, false); } public Buffs(Boolean snowball, Boolean streaks) { this.snowball = snowball; this.streaks = streaks; } public Boolean getSnowball() { return snowball != null ? snowball : Boolean.FALSE; } public void setSnowball(Boolean snowball) { this.snowball = snowball; } public Boolean getSeafoam() { return seafoam != null ? seafoam : Boolean.FALSE; } public void setSeafoam(Boolean seafoam) { this.seafoam = seafoam; } public Boolean getSpookySparkles() { return spookySparkles != null ? spookySparkles : Boolean.FALSE; } public void setSpookySparkles(Boolean spookySparkles) { this.spookySparkles = spookySparkles; } public Boolean getShinySeed() { return shinySeed != null ? shinySeed : Boolean.FALSE; } public void setShinySeed(Boolean shinySeed) { this.shinySeed = shinySeed; } public Boolean getStreaks() { return streaks != null ? streaks : Boolean.FALSE; } public void setStreaks(Boolean streaks) { this.streaks = streaks; } public void merge(Buffs stats) { if (stats == null) { return; } this.con = stats.con != null ? stats.con : this.con; this.str = stats.str != null ? stats.str : this.str; this.per = stats.per != null ? stats.per : this.per; this._int = stats._int != null ? stats._int : this._int; this.snowball = stats.snowball != null ? stats.snowball : this.snowball; this.streaks = stats.streaks != null ? stats.streaks : this.streaks; this.seafoam = stats.seafoam != null ? stats.seafoam : this.seafoam; this.shinySeed = stats.shinySeed != null ? stats.shinySeed : this.shinySeed; this.spookySparkles = stats.spookySparkles != null ? stats.spookySparkles : this.spookySparkles; } public Float getStr() { return str; } public Float get_int() { return _int; } public Float getCon() { return con; } public Float getPer() { return per; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } }
gpl-3.0
Evisceration/DeviceControl
app/src/main/java/org/namelessrom/devicecontrol/modules/wizard/pages/FinishPage.java
3330
/* * Copyright (C) 2013 - 2014 Alexander "Evisceration" Martinz * * 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.namelessrom.devicecontrol.modules.wizard.pages; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.widget.ListView; import org.namelessrom.devicecontrol.R; import org.namelessrom.devicecontrol.modules.tasker.TaskerItem; import org.namelessrom.devicecontrol.modules.wizard.setup.Page; import org.namelessrom.devicecontrol.modules.wizard.setup.SetupDataCallbacks; import org.namelessrom.devicecontrol.modules.wizard.ui.ReviewAdapter; import org.namelessrom.devicecontrol.modules.wizard.ui.SetupPageFragment; import java.util.ArrayList; import timber.log.Timber; public class FinishPage extends Page { private FinishFragment fragment; public FinishPage(Context context, SetupDataCallbacks callbacks, int titleResourceId) { super(context, callbacks, titleResourceId); } @Override public Fragment createFragment() { final Bundle args = new Bundle(); args.putString(Page.KEY_PAGE_ARGUMENT, getKey()); fragment = new FinishFragment(); fragment.setArguments(args); return fragment; } @Override public void refresh() { if (fragment != null) { fragment.setUpPage(); } } @Override public int getNextButtonResId() { return R.string.finish; } public static class FinishFragment extends SetupPageFragment { @Override protected void setUpPage() { final ListView listView = (ListView) mRootView.findViewById(android.R.id.list); final TaskerItem item = mCallbacks.getSetupData(); final ArrayList<String> entries = new ArrayList<>(4); final ArrayList<String> values = new ArrayList<>(4); entries.add(getString(R.string.trigger)); values.add(item.trigger); entries.add(getString(R.string.category)); values.add(item.category); entries.add(getString(R.string.action)); values.add(item.name); entries.add(getString(R.string.value)); values.add(item.value); final ReviewAdapter adapter = new ReviewAdapter(getActivity(), R.layout.wizard_list_item_review, entries, values); listView.setAdapter(adapter); Timber.v("TaskerItem: %s", mCallbacks.getSetupData().toString()); } @Override protected int getLayoutResource() { return R.layout.wizard_page_list; } @Override protected int getTitleResource() { return R.string.setup_complete; } } }
gpl-3.0
jtux270/translate
ovirt/backend/manager/modules/dal/src/main/java/org/ovirt/engine/core/dao/scheduling/AffinityGroupDaoImpl.java
4584
package org.ovirt.engine.core.dao.scheduling; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import org.apache.commons.lang.StringUtils; import org.ovirt.engine.core.common.scheduling.AffinityGroup; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.dal.dbbroker.DbFacadeUtils; import org.ovirt.engine.core.dao.DefaultGenericDaoDbFacade; import org.ovirt.engine.core.utils.GuidUtils; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; public class AffinityGroupDaoImpl extends DefaultGenericDaoDbFacade<AffinityGroup, Guid> implements AffinityGroupDao { public AffinityGroupDaoImpl() { super("AffinityGroup"); } @Override public List<AffinityGroup> getAllAffinityGroupsByClusterId(Guid clusterId) { return getCallsHandler().executeReadList("getAllAffinityGroupsByClusterId", createEntityRowMapper(), getCustomMapSqlParameterSource().addValue("cluster_id", clusterId)); } @Override public List<AffinityGroup> getAllAffinityGroupsByVmId(Guid vmId) { return getCallsHandler().executeReadList("getAllAffinityGroupsByVmId", createEntityRowMapper(), getCustomMapSqlParameterSource().addValue("vm_id", vmId)); } @Override public AffinityGroup getByName(String str) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("name", str); return (AffinityGroup) DbFacadeUtils.asSingleResult( getCallsHandler().executeReadList("GetAffinityGroupByName", createEntityRowMapper(), parameterSource)); } @Override public void save(AffinityGroup entity) { getCallsHandler().executeModification("InsertAffinityGroupWithMembers", createFullParametersMapper(entity)); } @Override public void update(AffinityGroup entity) { getCallsHandler().executeModification("UpdateAffinityGroupWithMembers", createFullParametersMapper(entity)); } @Override public void removeVmFromAffinityGroups(Guid vmId) { getCallsHandler().executeModification("RemoveVmFromAffinityGroups", getCustomMapSqlParameterSource().addValue("vm_id", vmId)); } @Override public List<AffinityGroup> getPositiveEnforcingAffinityGroupsByRunningVmsOnVdsId(Guid vdsId) { return getCallsHandler().executeReadList("getPositiveEnforcingAffinityGroupsByRunningVmsOnVdsId", createEntityRowMapper(), getCustomMapSqlParameterSource().addValue("vds_id", vdsId)); } @Override protected MapSqlParameterSource createFullParametersMapper(AffinityGroup entity) { return createIdParameterMapper(entity.getId()) .addValue("name", entity.getName()) .addValue("description", entity.getDescription()) .addValue("cluster_id", entity.getClusterId()) .addValue("positive", entity.isPositive()) .addValue("enforcing", entity.isEnforcing()) .addValue("vm_ids", entity.getEntityIds() == null ? StringUtils.EMPTY : StringUtils.join(entity.getEntityIds(), SEPARATOR)); } @Override protected MapSqlParameterSource createIdParameterMapper(Guid id) { return getCustomMapSqlParameterSource().addValue("id", id); } @Override protected RowMapper<AffinityGroup> createEntityRowMapper() { return AffinityGropupRowMapper.instance; } private static class AffinityGropupRowMapper implements RowMapper<AffinityGroup> { public static AffinityGropupRowMapper instance = new AffinityGropupRowMapper(); @Override public AffinityGroup mapRow(ResultSet rs, int arg1) throws SQLException { AffinityGroup affinityGroup = new AffinityGroup(); affinityGroup.setId(getGuid(rs, "id")); affinityGroup.setName(rs.getString("name")); affinityGroup.setDescription(rs.getString("description")); affinityGroup.setClusterId(getGuid(rs, "cluster_id")); affinityGroup.setPositive(rs.getBoolean("positive")); affinityGroup.setEnforcing(rs.getBoolean("enforcing")); affinityGroup.setEntityIds(GuidUtils.getGuidListFromString(rs.getString("vm_ids"))); affinityGroup.setEntityNames(split(rs.getString("vm_names"))); return affinityGroup; } } }
gpl-3.0
Gspin96/blynk-server
server/notifications/email/src/main/java/cc/blynk/server/notifications/mail/MailWrapper.java
898
package cc.blynk.server.notifications.mail; import java.util.Properties; /** * The Blynk Project. * Created by Dmitriy Dumanskiy. * Created on 06.04.15. */ public class MailWrapper { public static final String MAIL_PROPERTIES_FILENAME = "mail.properties"; private final MailClient client; public MailWrapper(Properties mailProperties) { String host = mailProperties.getProperty("mail.smtp.host"); if (host != null && host.contains("sparkpostmail")) { client = new SparkPostMailClient(mailProperties); } else { client = new GMailClient(mailProperties); } } public void sendText(String to, String subj, String body) throws Exception { client.sendText(to, subj, body); } public void sendHtml(String to, String subj, String body) throws Exception { client.sendHtml(to, subj, body); } }
gpl-3.0
HolodeckOne-Minecraft/WorldEdit
worldedit-core/src/main/java/com/sk89q/worldedit/function/EntityFunction.java
1270
/* * 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.function; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.entity.Entity; /** * Applies a function to entities. */ public interface EntityFunction { /** * Apply the function to the entity. * * @param entity the entity * @return true if something was changed * @throws WorldEditException thrown on an error */ boolean apply(Entity entity) throws WorldEditException; }
gpl-3.0
jdrossl/liferay-events
portlets/events-portlet/docroot/WEB-INF/src/com/rivetlogic/event/portlet/EventPortlet.java
12955
/** * Copyright (C) 2005-2014 Rivet Logic Corporation. * * 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 3 * 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., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ package com.rivetlogic.event.portlet; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.messaging.Message; import com.liferay.portal.kernel.messaging.MessageBusUtil; import com.liferay.portal.kernel.servlet.SessionErrors; import com.liferay.portal.kernel.servlet.SessionMessages; import com.liferay.portal.kernel.util.ParamUtil; import com.liferay.portal.kernel.util.StringPool; import com.liferay.portal.model.Layout; import com.liferay.portal.theme.ThemeDisplay; import com.liferay.portal.util.PortalUtil; import com.liferay.util.bridges.mvc.MVCPortlet; import com.rivetlogic.event.NoSuchEventException; import com.rivetlogic.event.beans.EventsPrefsBean; import com.rivetlogic.event.model.Event; import com.rivetlogic.event.model.Participant; import com.rivetlogic.event.model.Token; import com.rivetlogic.event.notification.constant.EventPortletConstants; import com.rivetlogic.event.notification.constant.NotificationConstants; import com.rivetlogic.event.notification.constant.PreferencesConstants; import com.rivetlogic.event.service.EventLocalServiceUtil; import com.rivetlogic.event.service.ParticipantLocalServiceUtil; import com.rivetlogic.event.service.TokenLocalServiceUtil; import com.rivetlogic.event.util.EventActionUtil; import com.rivetlogic.event.util.EventConstant; import com.rivetlogic.event.util.EventValidator; import com.rivetlogic.event.util.WebKeys; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.PortletException; import javax.portlet.PortletRequest; import javax.portlet.ReadOnlyException; import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; import javax.portlet.ValidatorException; /** * @author charlesrodriguez * @author christopherjimenez * @author juancarrillo */ public class EventPortlet extends MVCPortlet { public void changePreferences(ActionRequest request, ActionResponse response) { try { EventsPrefsBean prefBean = new EventsPrefsBean(request); prefBean.save(request); request.setAttribute(WebKeys.PREF_BEAN, prefBean); } catch (ReadOnlyException roe) { _log.error(PreferencesConstants.ERROR_LOAD_PREFERENCES, roe); SessionErrors.add(request, PreferencesConstants.ERROR_LOAD_PREFERENCES); } catch (ValidatorException ve) { _log.error(PreferencesConstants.ERROR_WRITE_PERFERENCES, ve); SessionErrors.add(request, PreferencesConstants.ERROR_WRITE_PERFERENCES); } catch (IOException ioe) { _log.error(PreferencesConstants.ERROR_IO_PREFERENCES, ioe); SessionErrors.add(request, PreferencesConstants.ERROR_IO_PREFERENCES); } } @Override public void doEdit(RenderRequest request, RenderResponse response) throws IOException, PortletException { String selectedTab = ParamUtil.getString(request, WebKeys.SELECTED_TAB, PreferencesConstants.DISPLAY_EMAIL_FROM); request.setAttribute(WebKeys.PREF_BEAN, new EventsPrefsBean(request)); request.setAttribute(WebKeys.SELECTED_TAB, selectedTab); super.doEdit(request, response); } @Override public void doView(RenderRequest request, RenderResponse response) throws IOException, PortletException { String jspPage = getInitParameter(VIEW_TEMPLATE); EventsPrefsBean prefBean = new EventsPrefsBean(request); Long eventId = ParamUtil.getLong(request, NotificationConstants.EVENT_ID, EventPortletConstants.INVALID_ID); if (eventId != EventPortletConstants.INVALID_ID) { jspPage = getInitParameter(CONFIRMATION_TEMPLATE); processConfirmation(request, eventId, prefBean); } request.setAttribute(WebKeys.PREF_BEAN, prefBean); include(jspPage, request, response); } public void registerUserToEvent(ActionRequest request, ActionResponse response) throws IOException { Participant participant = EventActionUtil.getParticipantFromRequest(request); List<String> errors = new ArrayList<String>(); List<String> invalidEmails = new ArrayList<String>(); List<String> repeatedEmails = new ArrayList<String>(); String redirect = ParamUtil.getString(request, WebKeys.REDIRECT); if (EventValidator.validateRegisteredParticipant(participant, null, errors, repeatedEmails, invalidEmails)) { saveParticipant(request, response, participant, redirect); } else { EventActionUtil.setErrors(errors, request); } if (!SessionErrors.isEmpty(request)) { request.setAttribute(WebKeys.PARTICIPANT_ENTRY, participant); request.setAttribute(WebKeys.REPEATED_EMAILS, repeatedEmails); request.setAttribute(WebKeys.INVALID_EMAILS, invalidEmails); response.setRenderParameter(WebKeys.MVC_PATH, WebKeys.EVENT_VIEW_PAGE); response.setRenderParameter(WebKeys.REDIRECT, redirect); response.setRenderParameter(EventPortletConstants.PARAMETER_RESOURCE_PRIMARY_KEY, ParamUtil.getString(request, NotificationConstants.EVENT_ID)); } } @Override public void render(RenderRequest request, RenderResponse response) throws PortletException, IOException { String mvcPath = ParamUtil.getString(request, WebKeys.MVC_PATH); if (mvcPath.equals(WebKeys.EVENT_VIEW_PAGE)) { EventActionUtil.loadEvent(request, true); // Remove default error messge SessionMessages.add(request, PortalUtil.getPortletId(request) + SessionMessages.KEY_SUFFIX_HIDE_DEFAULT_ERROR_MESSAGE); } super.render(request, response); } private void processConfirmation(PortletRequest request, long eventId, EventsPrefsBean eventPrefsBean) { String uuid = ParamUtil.getString(request, EventPortletConstants.PARAMETER_TOKEN, null); String[] data = null; try { Token token = TokenLocalServiceUtil.getTokenByUuid(uuid); if (!token.isExpired()) { Participant participant = ParticipantLocalServiceUtil.getParticipant(token.getParticipantId()); if (participant.getEventId() == eventId) { Event event = EventLocalServiceUtil.getEvent(eventId); Boolean isGoing = EventConstant.STATUS_GOING.equals(ParamUtil.getString(request, PARAMETER_STATUS)); participant.setStatus(isGoing ? EventConstant.EVENT_STATUS_ACCEPTER : EventConstant.EVENT_STATUS_REJECTED); TokenLocalServiceUtil.expireToken(token); ParticipantLocalServiceUtil.updateParticipant(participant); request.setAttribute(WebKeys.IS_GOING, isGoing); request.setAttribute(WebKeys.EVENT_ENTRY, event); data = new String[] { eventPrefsBean.getEmailFrom(), eventPrefsBean.getNameFrom(), event.getName(), NotificationConstants.CDF.format(event.getEventDate()), participant.getFullName(), participant.getEmail(), event.getLocation(), event.getDescription(), StringPool.BLANK, StringPool.BLANK, StringPool.BLANK, PortalUtil.getPortalURL(request) }; } else { data = new String[] { eventPrefsBean.getEmailFrom(), eventPrefsBean.getNameFrom(), StringPool.BLANK, StringPool.BLANK, participant.getFullName(), participant.getEmail(), StringPool.BLANK, StringPool.BLANK, StringPool.BLANK, StringPool.BLANK, StringPool.BLANK, PortalUtil.getPortalURL(request) }; request.setAttribute(WebKeys.INVALID, true); } } else { request.setAttribute(WebKeys.EXPIRED_TOKEN, true); } } catch (Exception e) { data = new String[] { eventPrefsBean.getEmailFrom(), eventPrefsBean.getNameFrom(), StringPool.BLANK, StringPool.BLANK, StringPool.BLANK, StringPool.BLANK, StringPool.BLANK, StringPool.BLANK, StringPool.BLANK, StringPool.BLANK, StringPool.BLANK, PortalUtil.getPortalURL(request) }; request.setAttribute(WebKeys.INVALID, true); _log.error(e.getMessage()); } eventPrefsBean.processTemplates(data); } private void saveParticipant(ActionRequest request, ActionResponse response, Participant participant, String redirect) { verifyEvent(request, participant.getEventId()); if (SessionErrors.isEmpty(request)) { try { participant.setStatus(EventConstant.EVENT_STATUS_ACCEPTER); participant = ParticipantLocalServiceUtil.addParticipant(participant); sendNotification(request, participant); SessionMessages.add(request, MESSAGE_REGISTRATION_SUCCESS); SessionMessages.add(request, MESSAGE_REGISTRATION_EMAIL); response.sendRedirect(redirect); } catch (Exception e) { _log.error(e); SessionErrors.add(request, ERROR_SAVING_PARTICIPANT); } } } private void sendNotification(PortletRequest request, Participant participant) { EventsPrefsBean prefBean = new EventsPrefsBean(request); // Events URL ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute(WebKeys.THEME_DISPLAY); Layout layout = themeDisplay.getLayout(); String publicURL = themeDisplay.getPathFriendlyURLPublic() + themeDisplay.getScopeGroup().getFriendlyURL() + layout.getFriendlyURL(); prefBean.setPublicEventsURL(publicURL); Message message = new Message(); message.put(NotificationConstants.CMD, NotificationConstants.MANUAL_EVENT_REGISTRATION); message.put(NotificationConstants.SENDER, prefBean.getEmailFrom()); message.put(NotificationConstants.SENDER_NAME, prefBean.getNameFrom()); message.put(NotificationConstants.RECIPIENTS, participant.getEmail()); message.put(NotificationConstants.BODY_TEMPLATE, prefBean.getRegularInvitationBody()); message.put(NotificationConstants.SUBJECT_TEMPLATE, prefBean.getRegularInvitationSubject()); message.put(NotificationConstants.PUBLIC_URL, prefBean.getPublicEventsURL()); message.put(NotificationConstants.PORTAL_URL, PortalUtil.getPortalURL(request)); message.put(NotificationConstants.PARTICIPANT, participant); MessageBusUtil.sendMessage(NotificationConstants.SEND_NOTIFICATION_DESTINATION, message); } private void verifyEvent(PortletRequest request, long resourcePrimKey) { try { EventLocalServiceUtil.getEvent(resourcePrimKey); } catch (Exception e) { SessionErrors.add(request, ERROR_SAVING_PARTICIPANT); if (!(e instanceof NoSuchEventException)) { _log.error(e); } } } private static final Log _log = LogFactoryUtil.getLog(EventPortlet.class); private static final String ERROR_SAVING_PARTICIPANT = "participant-save-error"; private static final String MESSAGE_REGISTRATION_EMAIL = "participant-registration-email"; private static final String MESSAGE_REGISTRATION_SUCCESS = "participant-registration-success"; private static final String VIEW_TEMPLATE = "view-template"; private static final String PARAMETER_STATUS = "status"; private static final String CONFIRMATION_TEMPLATE = "confirmation-jsp"; }
gpl-3.0
ur13l/Guanajoven
app/src/main/java/mx/gob/jovenes/guanajuato/fragments/RedesSocialesFragment.java
2158
package mx.gob.jovenes.guanajuato.fragments; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.annotation.Nullable; import android.support.design.widget.CollapsingToolbarLayout; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import mx.gob.jovenes.guanajuato.R; import mx.gob.jovenes.guanajuato.adapters.VPRedesSocialesAdapter; /** * Created by codigus on 19/5/2017. */ public class RedesSocialesFragment extends CustomFragment { private TabLayout tabs; private ViewPager viewPager; private VPRedesSocialesAdapter adapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_redes_sociales, container, false); tabs = (TabLayout) v.findViewById(R.id.tabs_redes_sociales); viewPager = (ViewPager) v.findViewById(R.id.vp_redes_sociales); adapter = new VPRedesSocialesAdapter(getFragmentManager()); viewPager.setAdapter(adapter); tabs.setupWithViewPager(viewPager); tabs.getTabAt(0).setIcon(R.drawable.ic_twitter); //tabs.getTabAt(1).setIcon(R.drawable.ic_facebook); tabs.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { System.err.println(tab.getText()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); return v; } }
gpl-3.0
s20121035/rk3288_android5.1_repo
packages/apps/Launcher3/src/com/android/launcher3/compat/LauncherActivityInfoCompat.java
1242
/* * Copyright (C) 2014 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.launcher3.compat; import android.content.ComponentName; import android.content.pm.ApplicationInfo; import android.graphics.drawable.Drawable; public abstract class LauncherActivityInfoCompat { LauncherActivityInfoCompat() { } public abstract ComponentName getComponentName(); public abstract UserHandleCompat getUser(); public abstract CharSequence getLabel(); public abstract Drawable getIcon(int density); public abstract ApplicationInfo getApplicationInfo(); public abstract long getFirstInstallTime(); public abstract Drawable getBadgedIcon(int density); }
gpl-3.0
Mazdallier/AgeCraft
src/main/java/org/agecraft/core/entity/ai/EntityAIMate.java
3207
package org.agecraft.core.entity.ai; import java.util.Iterator; import java.util.List; import java.util.Random; import net.minecraft.entity.ai.EntityAIBase; import net.minecraft.entity.item.EntityXPOrb; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.stats.StatList; import org.agecraft.core.entity.animals.EntityAnimal; public class EntityAIMate extends EntityAIBase { private EntityAnimal animal; private EntityAnimal target; private double moveSpeed; private int spawnBabyDelay; public EntityAIMate(EntityAnimal animal, double moveSpeed) { this.animal = animal; this.moveSpeed = moveSpeed; setMutexBits(3); } @Override public boolean shouldExecute() { if(animal.isInLove()) { target = getNearbyMate(); return target != null; } return false; } @Override public boolean continueExecuting() { return target.isEntityAlive() && target.isInLove() && spawnBabyDelay < 60; } @Override public void resetTask() { target = null; spawnBabyDelay = 0; } @Override public void updateTask() { animal.getLookHelper().setLookPositionWithEntity(target, 10.0F, animal.getVerticalFaceSpeed()); animal.getNavigator().tryMoveToEntityLiving(target, moveSpeed); spawnBabyDelay++; if(spawnBabyDelay >= 60 && animal.getDistanceSqToEntity(target) < 9.0F) { spawnBaby(); } } public EntityAnimal getNearbyMate() { List list = animal.worldObj.getEntitiesWithinAABB(animal.getClass(), animal.boundingBox.expand(8.0D, 8.0D, 8.0D)); double distance = Double.MAX_VALUE; EntityAnimal mate = null; Iterator iterator = list.iterator(); while(iterator.hasNext()) { EntityAnimal entity = (EntityAnimal) iterator.next(); if(animal.canMateWith(entity) && animal.getDistanceSqToEntity(entity) < distance) { mate = entity; distance = animal.getDistanceSqToEntity(entity); } } return mate; } public void spawnBaby() { EntityAnimal baby = animal.createChild(target); if(baby != null) { EntityPlayer player = animal.getBreeder(); if(player == null && target.getBreeder() != null) { player = target.getBreeder(); } if(player != null) { player.triggerAchievement(StatList.field_151186_x); } animal.setGrowingAge(6000); target.setGrowingAge(6000); animal.resetInLove(); target.resetInLove(); baby.setGrowingAge(-24000); baby.setLocationAndAngles(animal.posX, animal.posY, animal.posZ, 0.0F, 0.0F); animal.worldObj.spawnEntityInWorld(baby); Random random = animal.getRNG(); for(int i = 0; i < 7; ++i) { double x = random.nextGaussian() * 0.02D; double y = random.nextGaussian() * 0.02D; double z = random.nextGaussian() * 0.02D; animal.worldObj.spawnParticle("heart", animal.posX + (double) (random.nextFloat() * animal.width * 2.0F) - (double) animal.width, animal.posY + 0.5D + (double) (random.nextFloat() * animal.height), animal.posZ + (double) (random.nextFloat() * animal.width * 2.0F) - (double) animal.width, x, y, z); } if(animal.worldObj.getGameRules().getGameRuleBooleanValue("doMobLoot")) { animal.worldObj.spawnEntityInWorld(new EntityXPOrb(animal.worldObj, animal.posX, animal.posY, animal.posZ, random.nextInt(7) + 1)); } } } }
gpl-3.0
ByteHamster/AntennaPod
event/src/main/java/de/danoeh/antennapod/event/QueueEvent.java
1705
package de.danoeh.antennapod.event; import androidx.annotation.Nullable; import java.util.List; import de.danoeh.antennapod.model.feed.FeedItem; public class QueueEvent { public enum Action { ADDED, ADDED_ITEMS, SET_QUEUE, REMOVED, IRREVERSIBLE_REMOVED, CLEARED, DELETED_MEDIA, SORTED, MOVED } public final Action action; public final FeedItem item; public final int position; public final List<FeedItem> items; private QueueEvent(Action action, @Nullable FeedItem item, @Nullable List<FeedItem> items, int position) { this.action = action; this.item = item; this.items = items; this.position = position; } public static QueueEvent added(FeedItem item, int position) { return new QueueEvent(Action.ADDED, item, null, position); } public static QueueEvent setQueue(List<FeedItem> queue) { return new QueueEvent(Action.SET_QUEUE, null, queue, -1); } public static QueueEvent removed(FeedItem item) { return new QueueEvent(Action.REMOVED, item, null, -1); } public static QueueEvent irreversibleRemoved(FeedItem item) { return new QueueEvent(Action.IRREVERSIBLE_REMOVED, item, null, -1); } public static QueueEvent cleared() { return new QueueEvent(Action.CLEARED, null, null, -1); } public static QueueEvent sorted(List<FeedItem> sortedQueue) { return new QueueEvent(Action.SORTED, null, sortedQueue, -1); } public static QueueEvent moved(FeedItem item, int newPosition) { return new QueueEvent(Action.MOVED, item, null, newPosition); } }
gpl-3.0
IOTHUB-F4I/IoThub
fiware-cepheus/cepheus-ngsi/src/main/java/com/orange/ngsi/exception/MismatchIdException.java
967
/* * Copyright (C) 2016 Orange * * This software is distributed under the terms and conditions of the 'GNU GENERAL PUBLIC LICENSE * Version 2' license which can be found in the file 'LICENSE.txt' in this package distribution or * at 'http://www.gnu.org/licenses/gpl-2.0-standalone.html'. */ package com.orange.ngsi.exception; /** * Exception triggered when a REST ID parameter mismatches with the ID in the request body */ public class MismatchIdException extends Exception { private final String parameterId; private final String bodyId; public MismatchIdException(String parameterId, String bodyId) { this.parameterId = parameterId; this.bodyId = bodyId; } public String getMessage() { return "mismatch id between parameter " + parameterId + " and body " + bodyId; } public String getParameterId() { return parameterId; } public String getBodyId() { return bodyId; } }
gpl-3.0
patudd/steve
src/main/java/de/rwth/idsg/steve/handler/ocpp15/RemoteStopTransactionResponseHandler.java
725
package de.rwth.idsg.steve.handler.ocpp15; import de.rwth.idsg.steve.handler.AbstractOcppResponseHandler; import de.rwth.idsg.steve.web.RequestTask; import ocpp.cp._2012._06.RemoteStopTransactionResponse; /** * @author Sevket Goekay <goekay@dbis.rwth-aachen.de> * @since 30.12.2014 */ public class RemoteStopTransactionResponseHandler extends AbstractOcppResponseHandler<RemoteStopTransactionResponse> { public RemoteStopTransactionResponseHandler(RequestTask requestTask, String chargeBoxId) { super(requestTask, chargeBoxId); } @Override public void handleResult(RemoteStopTransactionResponse response) { requestTask.addNewResponse(chargeBoxId, response.getStatus().value()); } }
gpl-3.0
Marlinski/Rumble
app/src/main/java/org/disrupted/rumble/userinterface/adapter/ContactInfoRecyclerAdapter.java
2966
/* * Copyright (C) 2014 Lucien Loiseau * This file is part of Rumble. * Rumble 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. * * Rumble 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 Rumble. If not, see <http://www.gnu.org/licenses/>. */ package org.disrupted.rumble.userinterface.adapter; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import org.disrupted.rumble.R; import org.disrupted.rumble.userinterface.fragments.FragmentContactInfo; import java.util.ArrayList; /** * @author Lucien Loiseau */ public class ContactInfoRecyclerAdapter extends RecyclerView.Adapter<ContactInfoRecyclerAdapter.ContactInfoItemHolder> { public static final String TAG = "ContactInfoRecyclerAdapter"; public class ContactInfoItemHolder extends RecyclerView.ViewHolder { public ContactInfoItemHolder(View itemView) { super(itemView); } public void bindInfoItem(FragmentContactInfo.ContactInfoItem infoItem) { TextView titleView = (TextView) itemView.findViewById(R.id.contact_info_title); TextView dataView = (TextView) itemView.findViewById(R.id.contact_info_data); titleView.setText(infoItem.title); dataView.setText(infoItem.data); } } private ArrayList<FragmentContactInfo.ContactInfoItem> infoList; public ContactInfoRecyclerAdapter() { this.infoList = null; } @Override public ContactInfoRecyclerAdapter.ContactInfoItemHolder onCreateViewHolder(ViewGroup parent, int i) { LinearLayout layout = (LinearLayout) LayoutInflater.from(parent.getContext()) .inflate(R.layout.item_contact_info_list, parent, false); return new ContactInfoItemHolder(layout); } @Override public void onBindViewHolder(ContactInfoItemHolder contactInfoItemHolder, int i) { FragmentContactInfo.ContactInfoItem infoItem = infoList.get(i); contactInfoItemHolder.bindInfoItem(infoItem); } @Override public int getItemCount() { if(infoList == null) return 0; else return infoList.size(); } public void swap(ArrayList<FragmentContactInfo.ContactInfoItem> infoList) { if(this.infoList != null) this.infoList.clear(); this.infoList = infoList; notifyDataSetChanged(); } }
gpl-3.0
structr/structr
structr-db-driver-api/src/main/java/org/structr/api/search/QueryPredicate.java
1169
/* * Copyright (C) 2010-2021 Structr GmbH * * This file is part of Structr <http://structr.org>. * * Structr 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. * * Structr 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 Structr. If not, see <http://www.gnu.org/licenses/>. */ package org.structr.api.search; public interface QueryPredicate { /** * The desired query type for this predicate. Return null here if the * predicate should be ignored by the indexing system. * * @return the query type or null */ Class getQueryType(); String getName(); Class getType(); Object getValue(); String getLabel(); Occurrence getOccurrence(); boolean isExactMatch(); SortOrder getSortOrder(); }
gpl-3.0
spMohanty/sigmah_svn_to_git_migration_test
sigmah/src/main/java/org/sigmah/server/endpoint/export/sigmah/spreadsheet/template/OrgUnitSynthesisExcelTemplate.java
658
/* * All Sigmah code is released under the GNU General Public License v3 * See COPYRIGHT.txt and LICENSE.txt. */ package org.sigmah.server.endpoint.export.sigmah.spreadsheet.template; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.sigmah.server.endpoint.export.sigmah.spreadsheet.data.OrgUnitSynthesisData; import org.sigmah.shared.domain.OrgUnit; /* * @author sherzod */ public class OrgUnitSynthesisExcelTemplate extends BaseSynthesisExcelTemplate { public OrgUnitSynthesisExcelTemplate( final OrgUnitSynthesisData data, final HSSFWorkbook wb) throws Throwable { super(data,wb,OrgUnit.class); } }
gpl-3.0
andern/jcoolib
src/cartesian/Representiatons.java
2288
/* * Copyright (C) 2012 Andreas Halle * * This file is part of jcoolib * * jcoolib 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. * * jcoolib 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 jcoolib. If not, see <http://www.gnu.org/licenses/>. */ package cartesian; /** * A {@code Class} containing a grammar for the String parser. * * @author Andreas Halle */ public class Representiatons { /* * Using this makes definitions that are space-insensitive much more * readable. * NOTE: This one alone matches "". */ private static final String S = "\\s*"; /** * Matches an integer or a decimal number. * <p> * Examples of allowed forms: * <pre> * 50 * 5. * 3.1415 * .020 * </pre> * <p> * There is no limit on quantity of numbers after the decimal point. Leading * and trailing zeroes are allowed. */ public static final String NUM = "(?:\\d+(?:\\.\\d*)?|\\.\\d+)"; /** * Variables might contain letters, underscores and digits. Variables * <b>must</b> start with a letter. * <p> * Examples of allowed forms: * <pre> * x1 * x_1 * y101 * var_1 * </pre> */ public static final String VAR = "[a-z_]+\\d*"; /** * Slope-intercept form: * <pre> * y = mx + b * </pre> * where x and y are variables while m and b are constants. * <p> * Allowed forms: * <pre> * y = mx + b * y = m*x + b * y = mx * </pre> * <p> * The forms are space-insensitive, even between m and x. */ public static final String SLOPEINTERCEPTFORM2D = VAR + S + "=" + S + NUM + "\\*?" + VAR + "(?:" + S + "\\+" + S + NUM + ")?"; }
gpl-3.0
AuthMe/AuthMeReloaded
src/main/java/fr/xephi/authme/listener/OnJoinVerifier.java
9084
package fr.xephi.authme.listener; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.initialization.Reloadable; import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.Messages; import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.permission.PlayerStatePermission; import fr.xephi.authme.service.AntiBotService; import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.ValidationService; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.ProtectionSettings; import fr.xephi.authme.settings.properties.RegistrationSettings; import fr.xephi.authme.settings.properties.RestrictionSettings; import fr.xephi.authme.util.StringUtils; import fr.xephi.authme.util.Utils; import org.bukkit.Server; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerLoginEvent; import javax.annotation.PostConstruct; import javax.inject.Inject; import java.util.Collection; import java.util.regex.Pattern; /** * Service for performing various verifications when a player joins. */ public class OnJoinVerifier implements Reloadable { private final ConsoleLogger logger = ConsoleLoggerFactory.get(OnJoinVerifier.class); @Inject private Settings settings; @Inject private DataSource dataSource; @Inject private Messages messages; @Inject private PermissionsManager permissionsManager; @Inject private AntiBotService antiBotService; @Inject private ValidationService validationService; @Inject private BukkitService bukkitService; @Inject private Server server; private Pattern nicknamePattern; OnJoinVerifier() { } @PostConstruct @Override public void reload() { String nickRegEx = settings.getProperty(RestrictionSettings.ALLOWED_NICKNAME_CHARACTERS); nicknamePattern = Utils.safePatternCompile(nickRegEx); } /** * Checks if Antibot is enabled. * * @param name the joining player name to check * @param isAuthAvailable whether or not the player is registered * @throws FailedVerificationException if the verification fails */ public void checkAntibot(String name, boolean isAuthAvailable) throws FailedVerificationException { if (isAuthAvailable || permissionsManager.hasPermissionOffline(name, PlayerStatePermission.BYPASS_ANTIBOT)) { return; } if (antiBotService.shouldKick()) { antiBotService.addPlayerKick(name); throw new FailedVerificationException(MessageKey.KICK_ANTIBOT); } } /** * Checks whether non-registered players should be kicked, and if so, whether the player should be kicked. * * @param isAuthAvailable whether or not the player is registered * @throws FailedVerificationException if the verification fails */ public void checkKickNonRegistered(boolean isAuthAvailable) throws FailedVerificationException { if (!isAuthAvailable && settings.getProperty(RestrictionSettings.KICK_NON_REGISTERED)) { throw new FailedVerificationException(MessageKey.MUST_REGISTER_MESSAGE); } } /** * Checks that the name adheres to the configured username restrictions. * * @param name the name to verify * @throws FailedVerificationException if the verification fails */ public void checkIsValidName(String name) throws FailedVerificationException { if (name.length() > settings.getProperty(RestrictionSettings.MAX_NICKNAME_LENGTH) || name.length() < settings.getProperty(RestrictionSettings.MIN_NICKNAME_LENGTH)) { throw new FailedVerificationException(MessageKey.INVALID_NAME_LENGTH); } if (!nicknamePattern.matcher(name).matches()) { throw new FailedVerificationException(MessageKey.INVALID_NAME_CHARACTERS, nicknamePattern.pattern()); } } /** * Handles the case of a full server and verifies if the user's connection should really be refused * by adjusting the event object accordingly. Attempts to kick a non-VIP player to make room if the * joining player is a VIP. * * @param event the login event to verify * * @return true if the player's connection should be refused (i.e. the event does not need to be processed * further), false if the player is not refused */ public boolean refusePlayerForFullServer(PlayerLoginEvent event) { final Player player = event.getPlayer(); if (event.getResult() != PlayerLoginEvent.Result.KICK_FULL) { // Server is not full, no need to do anything return false; } else if (!permissionsManager.hasPermission(player, PlayerStatePermission.IS_VIP)) { // Server is full and player is NOT VIP; set kick message and proceed with kick event.setKickMessage(messages.retrieveSingle(player, MessageKey.KICK_FULL_SERVER)); return true; } // Server is full and player is VIP; attempt to kick a non-VIP player to make room Collection<Player> onlinePlayers = bukkitService.getOnlinePlayers(); if (onlinePlayers.size() < server.getMaxPlayers()) { event.allow(); return false; } Player nonVipPlayer = generateKickPlayer(onlinePlayers); if (nonVipPlayer != null) { nonVipPlayer.kickPlayer(messages.retrieveSingle(player, MessageKey.KICK_FOR_VIP)); event.allow(); return false; } else { logger.info("VIP player " + player.getName() + " tried to join, but the server was full"); event.setKickMessage(messages.retrieveSingle(player, MessageKey.KICK_FULL_SERVER)); return true; } } /** * Checks that the casing in the username corresponds to the one in the database, if so configured. * * @param connectingName the player name to verify * @param auth the auth object associated with the player * @throws FailedVerificationException if the verification fails */ public void checkNameCasing(String connectingName, PlayerAuth auth) throws FailedVerificationException { if (auth != null && settings.getProperty(RegistrationSettings.PREVENT_OTHER_CASE)) { String realName = auth.getRealName(); // might be null or "Player" if (StringUtils.isEmpty(realName) || "Player".equals(realName)) { dataSource.updateRealName(connectingName.toLowerCase(), connectingName); } else if (!realName.equals(connectingName)) { throw new FailedVerificationException(MessageKey.INVALID_NAME_CASE, realName, connectingName); } } } /** * Checks that the player's country is admitted. * * @param name the joining player name to verify * @param address the player address * @param isAuthAvailable whether or not the user is registered * @throws FailedVerificationException if the verification fails */ public void checkPlayerCountry(String name, String address, boolean isAuthAvailable) throws FailedVerificationException { if ((!isAuthAvailable || settings.getProperty(ProtectionSettings.ENABLE_PROTECTION_REGISTERED)) && settings.getProperty(ProtectionSettings.ENABLE_PROTECTION) && !permissionsManager.hasPermissionOffline(name, PlayerStatePermission.BYPASS_COUNTRY_CHECK) && !validationService.isCountryAdmitted(address)) { throw new FailedVerificationException(MessageKey.COUNTRY_BANNED_ERROR); } } /** * Checks if a player with the same name (case-insensitive) is already playing and refuses the * connection if so configured. * * @param name the player name to check * @throws FailedVerificationException if the verification fails */ public void checkSingleSession(String name) throws FailedVerificationException { if (!settings.getProperty(RestrictionSettings.FORCE_SINGLE_SESSION)) { return; } Player onlinePlayer = bukkitService.getPlayerExact(name); if (onlinePlayer != null) { throw new FailedVerificationException(MessageKey.USERNAME_ALREADY_ONLINE_ERROR); } } /** * Selects a non-VIP player to kick when a VIP player joins the server when full. * * @param onlinePlayers list of online players * * @return the player to kick, or null if none applicable */ private Player generateKickPlayer(Collection<Player> onlinePlayers) { for (Player player : onlinePlayers) { if (!permissionsManager.hasPermission(player, PlayerStatePermission.IS_VIP)) { return player; } } return null; } }
gpl-3.0
clementine-player/Android-Remote
app/src/main/java/de/qspool/clementineremote/backend/downloader/SongDownloaderListener.java
1057
/* This file is part of the Android Clementine Remote. * Copyright (C) 2014, Andreas Muttscheller <asfa194@gmail.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, 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 de.qspool.clementineremote.backend.downloader; import de.qspool.clementineremote.backend.elements.DownloaderResult; public interface SongDownloaderListener { public void onProgress(DownloadStatus progress); public void onDownloadResult(DownloaderResult result); }
gpl-3.0
codehz/container
lib/src/main/java/com/lody/virtual/client/hook/patchs/media/session/SessionManagerPatch.java
583
package com.lody.virtual.client.hook.patchs.media.session; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import com.lody.virtual.client.hook.base.Patch; import com.lody.virtual.client.hook.base.PatchBinderDelegate; import mirror.android.media.session.ISessionManager; /** * @author Lody */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Patch({CreateSession.class}) public class SessionManagerPatch extends PatchBinderDelegate { public SessionManagerPatch() { super(ISessionManager.Stub.TYPE, Context.MEDIA_SESSION_SERVICE); } }
gpl-3.0
mrdowden/java-frameworks
services/spark/src/main/java/com/michaeldowden/jwf/web/OrderController.java
1153
package com.michaeldowden.jwf.web; import static spark.Spark.get; import static spark.Spark.post; import static spark.Spark.put; import com.google.gson.Gson; import com.michaeldowden.jwf.model.Address; import com.michaeldowden.jwf.service.CartService; import com.michaeldowden.jwf.service.OrderService; public class OrderController { private final Gson gson = new Gson(); private final CartService cartSvc = new CartService(); private final OrderService orderSvc = new OrderService(); public void initialize() { get("/svc/order/shipping", "application/json", (req, res) -> { return orderSvc.fetchShippingAddress(req); }, gson::toJson); put("/svc/order/shipping", (req, res) -> { Address address = gson.fromJson(req.body(), Address.class); orderSvc.updateShippingAddress(req, address); return true; }); post("/svc/order/checkout", (req, res) -> { return orderSvc.checkout(req, cartSvc.fetchCart(req)); }); get("/svc/order/:orderNumber", "application/json", (req, res) -> { Integer orderNumber = Integer.valueOf(req.params("orderNumber")); return orderSvc.lookupOrder(orderNumber); }, gson::toJson); } }
gpl-3.0
AuScope/CMAR-Portal
src/test/java/org/auscope/portal/mineraloccurrence/TestMine.java
1864
package org.auscope.portal.mineraloccurrence; import org.junit.Test; import org.junit.BeforeClass; import org.xml.sax.SAXException; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.auscope.portal.Util; import javax.xml.xpath.*; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import java.io.*; import junit.framework.Assert; /** * User: Mathew Wyatt * Date: 24/03/2009 * Time: 9:01:48 AM */ public class TestMine { private static Mine mine; private static XPath xPath; @BeforeClass public static void setup() throws IOException, SAXException, XPathExpressionException, ParserConfigurationException { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); // never forget this! DocumentBuilder builder = domFactory.newDocumentBuilder(); Document mineDocument = builder.parse(new ByteArrayInputStream(Util.loadXML("src/test/resources/mineNode.xml").getBytes("UTF-8"))); XPathFactory factory = XPathFactory.newInstance(); xPath = factory.newXPath(); xPath.setNamespaceContext(new MineralOccurrenceNamespaceContext()); XPathExpression expr = xPath.compile("/er:Mine"); Node mineNode = (Node)expr.evaluate(mineDocument, XPathConstants.NODE); mine = new Mine(mineNode); } @Test public void testGetPrefferedName() throws XPathExpressionException { Assert.assertEquals("Preffered mine name is Good Hope", "Good Hope", mine.getMineNamePreffered()); } @Test public void testGetURI() throws XPathExpressionException { Assert.assertEquals("URI should be urn:cgi:feature:GSV:Mine:361068", "urn:cgi:feature:GSV:Mine:361068", mine.getMineNameURI()); } }
gpl-3.0
RubenM13/E-EDD-2.0
es.ucm.fdi.edd.gmf.diagram/src/es/ucm/fdi/gmf/edd/diagram/edit/policies/BlockItemSemanticEditPolicy.java
4406
package es.ucm.fdi.gmf.edd.diagram.edit.policies; import java.util.Iterator; import org.eclipse.emf.ecore.EAnnotation; import org.eclipse.gef.commands.Command; import org.eclipse.gmf.runtime.common.core.command.ICompositeCommand; import org.eclipse.gmf.runtime.diagram.core.commands.DeleteCommand; import org.eclipse.gmf.runtime.emf.commands.core.command.CompositeTransactionalCommand; import org.eclipse.gmf.runtime.emf.type.core.commands.DestroyElementCommand; import org.eclipse.gmf.runtime.emf.type.core.commands.DestroyReferenceCommand; import org.eclipse.gmf.runtime.emf.type.core.requests.DestroyElementRequest; import org.eclipse.gmf.runtime.emf.type.core.requests.DestroyReferenceRequest; import org.eclipse.gmf.runtime.notation.Edge; import org.eclipse.gmf.runtime.notation.Node; import org.eclipse.gmf.runtime.notation.View; import es.ucm.fdi.gmf.edd.diagram.edit.parts.BlockBlockTreeElementsCompartmentEditPart; import es.ucm.fdi.gmf.edd.diagram.edit.parts.TreeElementEditPart; import es.ucm.fdi.gmf.edd.diagram.edit.parts.TreeElementLinksEditPart; import es.ucm.fdi.gmf.edd.diagram.part.EddVisualIDRegistry; import es.ucm.fdi.gmf.edd.diagram.providers.EddElementTypes; /** * @generated */ public class BlockItemSemanticEditPolicy extends EddBaseItemSemanticEditPolicy { /** * @generated */ public BlockItemSemanticEditPolicy() { super(EddElementTypes.Block_3001); } /** * @generated */ protected Command getDestroyElementCommand(DestroyElementRequest req) { View view = (View) getHost().getModel(); CompositeTransactionalCommand cmd = new CompositeTransactionalCommand( getEditingDomain(), null); cmd.setTransactionNestingEnabled(false); EAnnotation annotation = view.getEAnnotation("Shortcut"); //$NON-NLS-1$ if (annotation == null) { // there are indirectly referenced children, need extra commands: false addDestroyChildNodesCommand(cmd); addDestroyShortcutsCommand(cmd, view); // delete host element cmd.add(new DestroyElementCommand(req)); } else { cmd.add(new DeleteCommand(getEditingDomain(), view)); } return getGEFWrapper(cmd.reduce()); } /** * @generated */ private void addDestroyChildNodesCommand(ICompositeCommand cmd) { View view = (View) getHost().getModel(); for (Iterator<?> nit = view.getChildren().iterator(); nit.hasNext();) { Node node = (Node) nit.next(); switch (EddVisualIDRegistry.getVisualID(node)) { case BlockBlockTreeElementsCompartmentEditPart.VISUAL_ID: for (Iterator<?> cit = node.getChildren().iterator(); cit .hasNext();) { Node cnode = (Node) cit.next(); switch (EddVisualIDRegistry.getVisualID(cnode)) { case TreeElementEditPart.VISUAL_ID: for (Iterator<?> it = cnode.getTargetEdges().iterator(); it .hasNext();) { Edge incomingLink = (Edge) it.next(); if (EddVisualIDRegistry.getVisualID(incomingLink) == TreeElementLinksEditPart.VISUAL_ID) { DestroyReferenceRequest r = new DestroyReferenceRequest( incomingLink.getSource().getElement(), null, incomingLink.getTarget() .getElement(), false); cmd.add(new DestroyReferenceCommand(r)); cmd.add(new DeleteCommand(getEditingDomain(), incomingLink)); continue; } } for (Iterator<?> it = cnode.getSourceEdges().iterator(); it .hasNext();) { Edge outgoingLink = (Edge) it.next(); if (EddVisualIDRegistry.getVisualID(outgoingLink) == TreeElementLinksEditPart.VISUAL_ID) { DestroyReferenceRequest r = new DestroyReferenceRequest( outgoingLink.getSource().getElement(), null, outgoingLink.getTarget() .getElement(), false); cmd.add(new DestroyReferenceCommand(r)); cmd.add(new DeleteCommand(getEditingDomain(), outgoingLink)); continue; } } cmd.add(new DestroyElementCommand( new DestroyElementRequest(getEditingDomain(), cnode.getElement(), false))); // directlyOwned: true // don't need explicit deletion of cnode as parent's view deletion would clean child views as well // cmd.add(new org.eclipse.gmf.runtime.diagram.core.commands.DeleteCommand(getEditingDomain(), cnode)); break; } } break; } } } }
gpl-3.0
ImagoTrigger/sdrtrunk
src/main/java/org/jdesktop/swingx/mapviewer/LocalResponseCache.java
7648
/******************************************************************************* * SDR Trunk * Copyright (C) 2014 Dennis Sheirer * * 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.jdesktop.swingx.mapviewer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.CacheRequest; import java.net.CacheResponse; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ResponseCache; import java.net.URI; import java.net.URLConnection; import java.util.List; import java.util.Map; /** * @author joshy */ public class LocalResponseCache extends ResponseCache { private final static Logger mLog = LoggerFactory.getLogger( LocalResponseCache.class ); private final File cacheDir; private boolean checkForUpdates; private String baseURL; /** * Private constructor to prevent instantiation. * @param baseURL the URI that should be cached or <code>null</code> (for all URLs) * @param cacheDir the cache directory * @param checkForUpdates true if the URL is queried for newer versions of a file first */ private LocalResponseCache(String baseURL, File cacheDir, boolean checkForUpdates) { this.baseURL = baseURL; this.cacheDir = cacheDir; this.checkForUpdates = checkForUpdates; if (!cacheDir.exists()) { cacheDir.mkdirs(); } } /** * Sets this cache as default response cache * @param baseURL the URL, the caching should be restricted to or <code>null</code> for none * @param cacheDir the cache directory * @param checkForUpdates true if the URL is queried for newer versions of a file first */ public static void installResponseCache(String baseURL, File cacheDir, boolean checkForUpdates) { ResponseCache.setDefault(new LocalResponseCache(baseURL, cacheDir, checkForUpdates)); } /** * Returns the local File corresponding to the given remote URI. * @param remoteUri the remote URI * @return the corresponding local file */ public File getLocalFile(URI remoteUri) { if (baseURL != null) { String remote = remoteUri.toString(); if (!remote.startsWith(baseURL)) { return null; } } StringBuilder sb = new StringBuilder(); String host = remoteUri.getHost(); String query = remoteUri.getQuery(); String path = remoteUri.getPath(); String fragment = remoteUri.getFragment(); if (host != null) { sb.append(host); } if (path != null) { sb.append(path); } if (query != null) { sb.append('?'); sb.append(query); } if (fragment != null) { sb.append('#'); sb.append(fragment); } String name; final int maxLen = 250; if (sb.length() < maxLen) { name = sb.toString(); } else { name = sb.substring(0, maxLen); } name = name.replace('?', '$'); name = name.replace('*', '$'); name = name.replace(':', '$'); name = name.replace('<', '$'); name = name.replace('>', '$'); name = name.replace('"', '$'); File f = new File(cacheDir, name); return f; } /** * @param remoteUri the remote URI * @param localFile the corresponding local file * @return true if the resource at the given remote URI is newer than the resource cached locally. */ private static boolean isUpdateAvailable(URI remoteUri, File localFile) { URLConnection conn; try { conn = remoteUri.toURL().openConnection(); } catch (MalformedURLException ex) { mLog.error("An exception occurred - ", ex ); return false; } catch (IOException ex) { mLog.error("An exception occurred - ", ex ); return false; } if (!(conn instanceof HttpURLConnection)) { // don't bother with non-http connections return false; } long localLastMod = localFile.lastModified(); long remoteLastMod = 0L; HttpURLConnection httpconn = (HttpURLConnection) conn; // disable caching so we don't get in feedback loop with ResponseCache httpconn.setUseCaches(false); try { httpconn.connect(); remoteLastMod = httpconn.getLastModified(); } catch (IOException ex) { // log.error("An exception occurred", ex);(); return false; } finally { httpconn.disconnect(); } return (remoteLastMod > localLastMod); } @Override public CacheResponse get(URI uri, String rqstMethod, Map<String, List<String>> rqstHeaders) throws IOException { File localFile = getLocalFile(uri); if (localFile == null) { // we don't want to cache this URL return null; } if (!localFile.exists()) { // the file isn't already in our cache, return null return null; } if (checkForUpdates) { if (isUpdateAvailable(uri, localFile)) { // there is an update available, so don't return cached version return null; } } return new LocalCacheResponse(localFile, rqstHeaders); } @Override public CacheRequest put(URI uri, URLConnection conn) throws IOException { // only cache http(s) GET requests if (!(conn instanceof HttpURLConnection) || !(((HttpURLConnection) conn).getRequestMethod().equals("GET"))) { return null; } File localFile = getLocalFile(uri); if (localFile == null) { // we don't want to cache this URL return null; } new File(localFile.getParent()).mkdirs(); return new LocalCacheRequest(localFile); } private class LocalCacheResponse extends CacheResponse { private FileInputStream fis; private final Map<String, List<String>> headers; private LocalCacheResponse(File localFile, Map<String, List<String>> rqstHeaders) { try { this.fis = new FileInputStream(localFile); } catch (FileNotFoundException ex) { // should not happen, since we already checked for existence mLog.error("An exception occurred - ", ex ); } this.headers = rqstHeaders; } @Override public Map<String, List<String>> getHeaders() throws IOException { return headers; } @Override public InputStream getBody() throws IOException { return fis; } } private class LocalCacheRequest extends CacheRequest { private final File localFile; private FileOutputStream fos; private LocalCacheRequest(File localFile) { this.localFile = localFile; try { this.fos = new FileOutputStream(localFile); } catch (FileNotFoundException ex) { // should not happen if cache dir is valid mLog.error("An exception occurred", ex ); } } @Override public OutputStream getBody() throws IOException { return fos; } @Override public void abort() { // abandon the cache attempt by closing the stream and deleting // the local file try { fos.close(); localFile.delete(); } catch (IOException e) { // ignore } } } }
gpl-3.0
INTechSenpai/moon-rover
pc/src/BenchmarkPathfinding.java
2413
/* * Copyright (C) 2013-2017 Pierre-François Gimenez * 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/> */ import container.Container; import exceptions.ContainerException; import exceptions.MemoryManagerException; import exceptions.PathfindingException; import pathfinding.RealGameState; import pathfinding.astar.AStarCourbe; import pathfinding.astar.arcs.CercleArrivee; import pathfinding.chemin.CheminPathfinding; import robot.Cinematique; import robot.RobotReal; import table.GameElementNames; import utils.Log; /** * Un benchmark du pathfinding courbe * * @author pf * */ public class BenchmarkPathfinding { public static void main(String[] args) { try { Container container = new Container(); Log log = container.getService(Log.class); RobotReal robot = container.getService(RobotReal.class); AStarCourbe astar = container.getService(AStarCourbe.class); RealGameState state = container.getService(RealGameState.class); CheminPathfinding chemin = container.getService(CheminPathfinding.class); CercleArrivee cercle = container.getService(CercleArrivee.class); long avant = System.nanoTime(); Cinematique depart = new Cinematique(-800, 350, Math.PI / 2, true, 0); robot.setCinematique(depart); cercle.set(GameElementNames.MINERAI_CRATERE_HAUT_GAUCHE, 230, 30, -30, 10, -10); int nbtest = 100; log.debug("Début du test…"); for(int i = 0; i < nbtest; i++) { System.out.println(i); astar.initializeNewSearchToCircle(true, state); astar.process(chemin, false); chemin.clear(); } System.out.println("Temps : " + (System.nanoTime() - avant) / (nbtest * 1000000.)); container.destructor(); } catch(PathfindingException | InterruptedException | ContainerException | MemoryManagerException e) { e.printStackTrace(); } } }
gpl-3.0
openMF/mifosx-e2e-testing
browsermob-proxy/src/main/java/org/xbill/DNS/Record.java
22813
// Copyright (c) 1999-2004 Brian Wellington (bwelling@xbill.org) package org.xbill.DNS; import org.xbill.DNS.utils.base16; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.Serializable; import java.text.DecimalFormat; import java.util.Arrays; // TODO: Auto-generated Javadoc /** * A generic DNS resource record. The specific record types extend this class. A * record contains a name, type, class, ttl, and rdata. * * @author Brian Wellington */ public abstract class Record implements Cloneable, Comparable, Serializable { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 2694906050116005466L; /** The name. */ protected Name name; /** The dclass. */ protected int type, dclass; /** The ttl. */ protected long ttl; /** The Constant byteFormat. */ private static final DecimalFormat byteFormat = new DecimalFormat(); static { byteFormat.setMinimumIntegerDigits(3); } /** * Instantiates a new record. */ protected Record() { } /** * Instantiates a new record. * * @param name * the name * @param type * the type * @param dclass * the dclass * @param ttl * the ttl */ Record(Name name, int type, int dclass, long ttl) { if (!name.isAbsolute()) throw new RelativeNameException(name); Type.check(type); DClass.check(dclass); TTL.check(ttl); this.name = name; this.type = type; this.dclass = dclass; this.ttl = ttl; } /** * Creates an empty record of the correct type; must be overriden. * * @return the object */ abstract Record getObject(); /** * Gets the empty record. * * @param name * the name * @param type * the type * @param dclass * the dclass * @param ttl * the ttl * @param hasData * the has data * @return the empty record */ private static final Record getEmptyRecord(Name name, int type, int dclass, long ttl, boolean hasData) { Record proto, rec; if (hasData) { proto = Type.getProto(type); if (proto != null) rec = proto.getObject(); else rec = new UNKRecord(); } else rec = new EmptyRecord(); rec.name = name; rec.type = type; rec.dclass = dclass; rec.ttl = ttl; return rec; } /** * Converts the type-specific RR to wire format - must be overriden. * * @param in * the in * @throws IOException * Signals that an I/O exception has occurred. */ abstract void rrFromWire(DNSInput in) throws IOException; /** * New record. * * @param name * the name * @param type * the type * @param dclass * the dclass * @param ttl * the ttl * @param length * the length * @param in * the in * @return the record * @throws IOException * Signals that an I/O exception has occurred. */ private static Record newRecord(Name name, int type, int dclass, long ttl, int length, DNSInput in) throws IOException { Record rec; rec = getEmptyRecord(name, type, dclass, ttl, in != null); if (in != null) { if (in.remaining() < length) throw new WireParseException("truncated record"); in.setActive(length); rec.rrFromWire(in); if (in.remaining() > 0) throw new WireParseException("invalid record length"); in.clearActive(); } return rec; } /** * Creates a new record, with the given parameters. * * @param name * The owner name of the record. * @param type * The record's type. * @param dclass * The record's class. * @param ttl * The record's time to live. * @param length * The length of the record's data. * @param data * The rdata of the record, in uncompressed DNS wire format. Only * the first length bytes are used. * @return the record */ public static Record newRecord(Name name, int type, int dclass, long ttl, int length, byte[] data) { if (!name.isAbsolute()) throw new RelativeNameException(name); Type.check(type); DClass.check(dclass); TTL.check(ttl); DNSInput in; if (data != null) in = new DNSInput(data); else in = null; try { return newRecord(name, type, dclass, ttl, length, in); } catch (IOException e) { return null; } } /** * Creates a new record, with the given parameters. * * @param name * The owner name of the record. * @param type * The record's type. * @param dclass * The record's class. * @param ttl * The record's time to live. * @param data * The complete rdata of the record, in uncompressed DNS wire * format. * @return the record */ public static Record newRecord(Name name, int type, int dclass, long ttl, byte[] data) { return newRecord(name, type, dclass, ttl, data.length, data); } /** * Creates a new empty record, with the given parameters. * * @param name * The owner name of the record. * @param type * The record's type. * @param dclass * The record's class. * @param ttl * The record's time to live. * @return An object of a subclass of Record */ public static Record newRecord(Name name, int type, int dclass, long ttl) { if (!name.isAbsolute()) throw new RelativeNameException(name); Type.check(type); DClass.check(dclass); TTL.check(ttl); return getEmptyRecord(name, type, dclass, ttl, false); } /** * Creates a new empty record, with the given parameters. This method is * designed to create records that will be added to the QUERY section of a * message. * * @param name * The owner name of the record. * @param type * The record's type. * @param dclass * The record's class. * @return An object of a subclass of Record */ public static Record newRecord(Name name, int type, int dclass) { return newRecord(name, type, dclass, 0); } /** * From wire. * * @param in * the in * @param section * the section * @param isUpdate * the is update * @return the record * @throws IOException * Signals that an I/O exception has occurred. */ static Record fromWire(DNSInput in, int section, boolean isUpdate) throws IOException { int type, dclass; long ttl; int length; Name name; Record rec; name = new Name(in); type = in.readU16(); dclass = in.readU16(); if (section == Section.QUESTION) return newRecord(name, type, dclass); ttl = in.readU32(); length = in.readU16(); if (length == 0 && isUpdate) return newRecord(name, type, dclass, ttl); rec = newRecord(name, type, dclass, ttl, length, in); return rec; } /** * From wire. * * @param in * the in * @param section * the section * @return the record * @throws IOException * Signals that an I/O exception has occurred. */ static Record fromWire(DNSInput in, int section) throws IOException { return fromWire(in, section, false); } /** * Builds a Record from DNS uncompressed wire format. * * @param b * the b * @param section * the section * @return the record * @throws IOException * Signals that an I/O exception has occurred. */ public static Record fromWire(byte[] b, int section) throws IOException { return fromWire(new DNSInput(b), section, false); } /** * To wire. * * @param out * the out * @param section * the section * @param c * the c */ void toWire(DNSOutput out, int section, Compression c) { name.toWire(out, c); out.writeU16(type); out.writeU16(dclass); if (section == Section.QUESTION) return; out.writeU32(ttl); int lengthPosition = out.current(); out.writeU16(0); /* until we know better */ rrToWire(out, c, false); int rrlength = out.current() - lengthPosition - 2; out.save(); out.jump(lengthPosition); out.writeU16(rrlength); out.restore(); } /** * Converts a Record into DNS uncompressed wire format. * * @param section * the section * @return the byte[] */ public byte[] toWire(int section) { DNSOutput out = new DNSOutput(); toWire(out, section, null); return out.toByteArray(); } /** * To wire canonical. * * @param out * the out * @param noTTL * the no ttl */ private void toWireCanonical(DNSOutput out, boolean noTTL) { name.toWireCanonical(out); out.writeU16(type); out.writeU16(dclass); if (noTTL) { out.writeU32(0); } else { out.writeU32(ttl); } int lengthPosition = out.current(); out.writeU16(0); /* until we know better */ rrToWire(out, null, true); int rrlength = out.current() - lengthPosition - 2; out.save(); out.jump(lengthPosition); out.writeU16(rrlength); out.restore(); } /* * Converts a Record into canonical DNS uncompressed wire format (all names * are converted to lowercase), optionally ignoring the TTL. */ /** * To wire canonical. * * @param noTTL * the no ttl * @return the byte[] */ private byte[] toWireCanonical(boolean noTTL) { DNSOutput out = new DNSOutput(); toWireCanonical(out, noTTL); return out.toByteArray(); } /** * Converts a Record into canonical DNS uncompressed wire format (all names * are converted to lowercase). * * @return the byte[] */ public byte[] toWireCanonical() { return toWireCanonical(false); } /** * Converts the rdata in a Record into canonical DNS uncompressed wire * format (all names are converted to lowercase). * * @return the byte[] */ public byte[] rdataToWireCanonical() { DNSOutput out = new DNSOutput(); rrToWire(out, null, true); return out.toByteArray(); } /** * Converts the type-specific RR to text format - must be overriden. * * @return the string */ abstract String rrToString(); /** * Converts the rdata portion of a Record into a String representation. * * @return the string */ public String rdataToString() { return rrToString(); } /** * Converts a Record into a String representation. * * @return the string */ public String toString() { StringBuffer sb = new StringBuffer(); sb.append(name); if (sb.length() < 8) sb.append("\t"); if (sb.length() < 16) sb.append("\t"); sb.append("\t"); if (Options.check("BINDTTL")) sb.append(TTL.format(ttl)); else sb.append(ttl); sb.append("\t"); if (dclass != DClass.IN || !Options.check("noPrintIN")) { sb.append(DClass.string(dclass)); sb.append("\t"); } sb.append(Type.string(type)); String rdata = rrToString(); if (!rdata.equals("")) { sb.append("\t"); sb.append(rdata); } return sb.toString(); } /** * Converts the text format of an RR to the internal format - must be * overriden. * * @param st * the st * @param origin * the origin * @throws IOException * Signals that an I/O exception has occurred. */ abstract void rdataFromString(Tokenizer st, Name origin) throws IOException; /** * Converts a String into a byte array. * * @param s * the s * @return the byte[] * @throws TextParseException * the text parse exception */ protected static byte[] byteArrayFromString(String s) throws TextParseException { byte[] array = s.getBytes(); boolean escaped = false; boolean hasEscapes = false; for (int i = 0; i < array.length; i++) { if (array[i] == '\\') { hasEscapes = true; break; } } if (!hasEscapes) { if (array.length > 255) { throw new TextParseException("text string too long"); } return array; } ByteArrayOutputStream os = new ByteArrayOutputStream(); int digits = 0; int intval = 0; for (int i = 0; i < array.length; i++) { byte b = array[i]; if (escaped) { if (b >= '0' && b <= '9' && digits < 3) { digits++; intval *= 10; intval += (b - '0'); if (intval > 255) throw new TextParseException("bad escape"); if (digits < 3) continue; b = (byte) intval; } else if (digits > 0 && digits < 3) throw new TextParseException("bad escape"); os.write(b); escaped = false; } else if (array[i] == '\\') { escaped = true; digits = 0; intval = 0; } else os.write(array[i]); } if (digits > 0 && digits < 3) throw new TextParseException("bad escape"); array = os.toByteArray(); if (array.length > 255) { throw new TextParseException("text string too long"); } return os.toByteArray(); } /** * Converts a byte array into a String. * * @param array * the array * @param quote * the quote * @return the string */ protected static String byteArrayToString(byte[] array, boolean quote) { StringBuffer sb = new StringBuffer(); if (quote) sb.append('"'); for (int i = 0; i < array.length; i++) { int b = array[i] & 0xFF; if (b < 0x20 || b >= 0x7f) { sb.append('\\'); sb.append(byteFormat.format(b)); } else if (b == '"' || b == '\\') { sb.append('\\'); sb.append((char) b); } else sb.append((char) b); } if (quote) sb.append('"'); return sb.toString(); } /** * Converts a byte array into the unknown RR format. * * @param data * the data * @return the string */ protected static String unknownToString(byte[] data) { StringBuffer sb = new StringBuffer(); sb.append("\\# "); sb.append(data.length); sb.append(" "); sb.append(base16.toString(data)); return sb.toString(); } /** * Builds a new Record from its textual representation. * * @param name * The owner name of the record. * @param type * The record's type. * @param dclass * The record's class. * @param ttl * The record's time to live. * @param st * A tokenizer containing the textual representation of the * rdata. * @param origin * The default origin to be appended to relative domain names. * @return The new record * @throws IOException * The text format was invalid. */ public static Record fromString(Name name, int type, int dclass, long ttl, Tokenizer st, Name origin) throws IOException { Record rec; if (!name.isAbsolute()) throw new RelativeNameException(name); Type.check(type); DClass.check(dclass); TTL.check(ttl); Tokenizer.Token t = st.get(); if (t.type == Tokenizer.IDENTIFIER && t.value.equals("\\#")) { int length = st.getUInt16(); byte[] data = st.getHex(); if (data == null) { data = new byte[0]; } if (length != data.length) throw st.exception("invalid unknown RR encoding: " + "length mismatch"); DNSInput in = new DNSInput(data); return newRecord(name, type, dclass, ttl, length, in); } st.unget(); rec = getEmptyRecord(name, type, dclass, ttl, true); rec.rdataFromString(st, origin); t = st.get(); if (t.type != Tokenizer.EOL && t.type != Tokenizer.EOF) { throw st.exception("unexpected tokens at end of record"); } return rec; } /** * Builds a new Record from its textual representation. * * @param name * The owner name of the record. * @param type * The record's type. * @param dclass * The record's class. * @param ttl * The record's time to live. * @param s * The textual representation of the rdata. * @param origin * The default origin to be appended to relative domain names. * @return The new record * @throws IOException * The text format was invalid. */ public static Record fromString(Name name, int type, int dclass, long ttl, String s, Name origin) throws IOException { return fromString(name, type, dclass, ttl, new Tokenizer(s), origin); } /** * Returns the record's name. * * @return the name * @see Name */ public Name getName() { return name; } /** * Returns the record's type. * * @return the type * @see Type */ public int getType() { return type; } /** * Returns the type of RRset that this record would belong to. For all types * except RRSIGRecord, this is equivalent to getType(). * * @return The type of record, if not SIGRecord. If the type is RRSIGRecord, * the type covered is returned. * @see Type * @see RRset * @see SIGRecord */ public int getRRsetType() { if (type == Type.RRSIG) { RRSIGRecord sig = (RRSIGRecord) this; return sig.getTypeCovered(); } return type; } /** * Returns the record's class. * * @return the d class */ public int getDClass() { return dclass; } /** * Returns the record's TTL. * * @return the ttl */ public long getTTL() { return ttl; } /** * Converts the type-specific RR to wire format - must be overriden. * * @param out * the out * @param c * the c * @param canonical * the canonical */ abstract void rrToWire(DNSOutput out, Compression c, boolean canonical); /** * Determines if two Records could be part of the same RRset. This compares * the name, type, and class of the Records; the ttl and rdata are not * compared. * * @param rec * the rec * @return true, if successful */ public boolean sameRRset(Record rec) { return (getRRsetType() == rec.getRRsetType() && dclass == rec.dclass && name .equals(rec.name)); } /** * Determines if two Records are identical. This compares the name, type, * class, and rdata (with names canonicalized). The TTLs are not compared. * * @param arg * The record to compare to * @return true if the records are equal, false otherwise. */ public boolean equals(Object arg) { if (arg == null || !(arg instanceof Record)) return false; Record r = (Record) arg; if (type != r.type || dclass != r.dclass || !name.equals(r.name)) return false; byte[] array1 = rdataToWireCanonical(); byte[] array2 = r.rdataToWireCanonical(); return Arrays.equals(array1, array2); } /** * Generates a hash code based on the Record's data. * * @return the int */ public int hashCode() { byte[] array = toWireCanonical(true); int code = 0; for (int i = 0; i < array.length; i++) code += ((code << 3) + (array[i] & 0xFF)); return code; } /** * Clone record. * * @return the record */ Record cloneRecord() { try { return (Record) clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException(); } } /** * Creates a new record identical to the current record, but with a * different name. This is most useful for replacing the name of a wildcard * record. * * @param name * the name * @return the record */ public Record withName(Name name) { if (!name.isAbsolute()) throw new RelativeNameException(name); Record rec = cloneRecord(); rec.name = name; return rec; } /** * Creates a new record identical to the current record, but with a * different class and ttl. This is most useful for dynamic update. * * @param dclass * the dclass * @param ttl * the ttl * @return the record */ Record withDClass(int dclass, long ttl) { Record rec = cloneRecord(); rec.dclass = dclass; rec.ttl = ttl; return rec; } /* Sets the TTL to the specified value. This is intentionally not public. */ /** * Sets the ttl. * * @param ttl * the new ttl */ void setTTL(long ttl) { this.ttl = ttl; } /** * Compares this Record to another Object. * * @param o * The Object to be compared. * @return The value 0 if the argument is a record equivalent to this * record; a value less than 0 if the argument is less than this * record in the canonical ordering, and a value greater than 0 if * the argument is greater than this record in the canonical * ordering. The canonical ordering is defined to compare by name, * class, type, and rdata. */ public int compareTo(Object o) { Record arg = (Record) o; if (this == arg) return (0); int n = name.compareTo(arg.name); if (n != 0) return (n); n = dclass - arg.dclass; if (n != 0) return (n); n = type - arg.type; if (n != 0) return (n); byte[] rdata1 = rdataToWireCanonical(); byte[] rdata2 = arg.rdataToWireCanonical(); for (int i = 0; i < rdata1.length && i < rdata2.length; i++) { n = (rdata1[i] & 0xFF) - (rdata2[i] & 0xFF); if (n != 0) return (n); } return (rdata1.length - rdata2.length); } /** * Returns the name for which additional data processing should be done for * this record. This can be used both for building responses and parsing * responses. * * @return The name to used for additional data processing, or null if this * record type does not require additional data processing. */ public Name getAdditionalName() { return null; } /* Checks that an int contains an unsigned 8 bit value */ /** * Check u8. * * @param field * the field * @param val * the val * @return the int */ static int checkU8(String field, int val) { if (val < 0 || val > 0xFF) throw new IllegalArgumentException("\"" + field + "\" " + val + " must be an unsigned 8 " + "bit value"); return val; } /* Checks that an int contains an unsigned 16 bit value */ /** * Check u16. * * @param field * the field * @param val * the val * @return the int */ static int checkU16(String field, int val) { if (val < 0 || val > 0xFFFF) throw new IllegalArgumentException("\"" + field + "\" " + val + " must be an unsigned 16 " + "bit value"); return val; } /* Checks that a long contains an unsigned 32 bit value */ /** * Check u32. * * @param field * the field * @param val * the val * @return the long */ static long checkU32(String field, long val) { if (val < 0 || val > 0xFFFFFFFFL) throw new IllegalArgumentException("\"" + field + "\" " + val + " must be an unsigned 32 " + "bit value"); return val; } /* Checks that a name is absolute */ /** * Check name. * * @param field * the field * @param name * the name * @return the name */ static Name checkName(String field, Name name) { if (!name.isAbsolute()) throw new RelativeNameException(name); return name; } }
mpl-2.0
zeromq/jeromq
src/test/java/zmq/socket/reqrep/RouterSpecTest.java
3943
package zmq.socket.reqrep; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.Ignore; import org.junit.Test; import zmq.Ctx; import zmq.Msg; import zmq.SocketBase; import zmq.ZMQ; import zmq.socket.AbstractSpecTest; public class RouterSpecTest extends AbstractSpecTest { @Test public void testFairQueueIn() throws IOException, InterruptedException { Ctx ctx = ZMQ.createContext(); List<String> binds = Arrays.asList("inproc://a", "tcp://127.0.0.1:*"); for (String bindAddress : binds) { // SHALL receive incoming messages from its peers using a fair-queuing // strategy. fairQueueIn(ctx, bindAddress, ZMQ.ZMQ_ROUTER, ZMQ.ZMQ_DEALER); } ZMQ.term(ctx); } @Test @Ignore public void testDestroyQueueOnDisconnect() throws IOException, InterruptedException { Ctx ctx = ZMQ.createContext(); List<String> binds = Arrays.asList("inproc://a", "tcp://127.0.0.1:*"); for (String bindAddress : binds) { // SHALL create a double queue when a peer connects to it. If this peer // disconnects, the ROUTER socket SHALL destroy its double queue and SHALL // discard any messages it contains. // *** Test disabled until libzmq does this properly *** // test_destroy_queue_on_disconnect (ctx); } ZMQ.term(ctx); } private void fairQueueIn(Ctx ctx, String address, int bindType, int connectType) throws IOException, InterruptedException { // Server socket will accept connections SocketBase receiver = ZMQ.socket(ctx, bindType); assertThat(receiver, notNullValue()); int timeout = 250; boolean rc = ZMQ.setSocketOption(receiver, ZMQ.ZMQ_RCVTIMEO, timeout); assertThat(rc, is(true)); rc = ZMQ.bind(receiver, address); assertThat(rc, is(true)); address = (String) ZMQ.getSocketOptionExt(receiver, ZMQ.ZMQ_LAST_ENDPOINT); assertThat(address, notNullValue()); int services = 5; List<SocketBase> senders = new ArrayList<>(); for (int peer = 0; peer < services; ++peer) { SocketBase sender = ZMQ.socket(ctx, connectType); assertThat(sender, notNullValue()); senders.add(sender); rc = ZMQ.setSocketOption(sender, ZMQ.ZMQ_RCVTIMEO, timeout); assertThat(rc, is(true)); rc = ZMQ.setSocketOption(sender, ZMQ.ZMQ_IDENTITY, "A" + peer); assertThat(rc, is(true)); rc = ZMQ.connect(sender, address); assertThat(rc, is(true)); } rc = sendSeq(senders.get(0), "M"); assertThat(rc, is(true)); recvSeq(receiver, "A0", "M"); rc = sendSeq(senders.get(0), "M"); assertThat(rc, is(true)); recvSeq(receiver, "A0", "M"); Set<String> sum = new HashSet<>(); // send N requests for (int peer = 0; peer < services; ++peer) { sendSeq(senders.get(peer), "M"); sum.add("A" + peer); } // handle N requests for (int peer = 0; peer < services; ++peer) { Msg msg = ZMQ.recv(receiver, 0); assertThat(msg, notNullValue()); assertThat(msg.size(), is(2)); sum.remove(new String(msg.data(), ZMQ.CHARSET)); recvSeq(receiver, "M"); } assertThat(sum.size(), is(0)); ZMQ.closeZeroLinger(receiver); for (SocketBase sender : senders) { ZMQ.closeZeroLinger(sender); } // Wait for disconnects. ZMQ.msleep(100); } }
mpl-2.0
carlosrusso/cda
core/src/main/java/pt/webdetails/cda/CdaBoot.java
2163
/*! * Copyright 2002 - 2015 Webdetails, a Pentaho company. All rights reserved. * * This software was developed by Webdetails and is provided under the terms * of the Mozilla Public License, Version 2.0, or any later version. You may not use * this file except in compliance with the license. If you need a copy of the license, * please go to http://mozilla.org/MPL/2.0/. The Initial Developer is Webdetails. * * Software distributed under the Mozilla Public License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to * the license for the specific language governing your rights and limitations. */ package pt.webdetails.cda; import org.pentaho.reporting.libraries.base.boot.AbstractBoot; import org.pentaho.reporting.libraries.base.config.Configuration; import org.pentaho.reporting.libraries.base.versioning.ProjectInformation; /** * Properties-based configuration holder. */ public class CdaBoot extends AbstractBoot { /** * The singleton instance of the Boot class. */ private static CdaBoot instance; /** * The project info contains all meta data about the project. */ private ProjectInformation projectInfo; protected CdaBoot() { projectInfo = CdaInfo.getInstance(); } /** * Returns the singleton instance of the boot utility class. * * @return the boot instance. */ public static synchronized CdaBoot getInstance() { if ( instance == null ) { instance = new CdaBoot(); } return instance; } /** * Loads the configuration. This will be called exactly once. * * @return The configuration. */ @Override protected Configuration loadConfiguration() { return createDefaultHierarchicalConfiguration( "/pt/webdetails/cda/cda.properties", "/cda.properties", true, CdaBoot.class ); } /** * Performs the boot. */ @Override protected void performBoot() { // any manual init work goes in here ... } /** * Returns the project info. * * @return The project info. */ @Override protected ProjectInformation getProjectInfo() { return projectInfo; } }
mpl-2.0
ReikaKalseki/Tropicraft
src/main/java/net/tropicraft/info/TCNames.java
11365
package net.tropicraft.info; /** * Class containing the names of the blocks, items, entities, etc in the mod */ public class TCNames { // Block names public static final String chunkOHead = "chunk"; public static final String chunkStairs = "chunkStairs"; public static final String eudialyteOre = "oreEudialyte"; public static final String zirconOre = "oreZircon"; public static final String azuriteOre = "oreAzurite"; public static final String oreBlock = "blockOre"; public static final String[] oreBlockNames = new String[]{"Eudialyte", "Zircon", "Azurite", "Zirconium"}; public static final String thatchBundle = "thatch"; public static final String coral = "coral"; public static final String[] coralNames = new String[]{"0", "1", "2", "3", "4", "5"}; public static final String bambooBundle = "bambooBundle"; public static final String log = "log"; public static final String[] logNames = new String[]{"Palm", "Mahogany"}; public static final String plank = "plank"; public static final String[] plankNames = new String[]{"Palm", "Mahogany"}; public static final String palmStairs = "palmStairs"; public static final String mahoganyStairs = "mahoganyStairs"; public static final String bambooStairs = "bambooStairs"; public static final String thatchStairs = "thatchStairs"; public static final String pineapple = "pineapple"; public static final String[] pineappleNames = new String[]{"Pineapple"}; public static final String stem = "Stem"; public static final String tallFlower = "tallFlower"; public static final String[] tallFlowerNames = new String[]{"Iris"}; public static final String bambooFence = "bambooFence"; public static final String thatchFence = "thatchFence"; public static final String chunkFence = "chunkFence"; public static final String palmFence = "palmFence"; public static final String mahoganyFence = "mahoganyFence"; public static final String sapling = "sapling"; public static final String[] saplingNames = new String[]{"Palm", "Mahogany", "Grapefruit", "Lemon", "Lime", "Orange"}; public static final String coffeePlant = "coffeePlant"; public static final String bambooFenceGate = "bambooFenceGate"; public static final String palmFenceGate = "palmFenceGate"; public static final String tikiTorch = "tikiTorch"; public static final String tikiUpper = tikiTorch + "_Upper"; public static final String tikiLower = tikiTorch + "_Lower"; public static final String bambooDoor = "bambooDoor"; public static final String singleSlabs = "singleSlabs"; public static final String doubleSlabs = "doubleSlabs"; public static final String[] slabTypes = new String[]{"Bamboo", "Thatch", "Chunk", "Palm"}; public static final String stillWater = "tropicsWater"; public static final String flowingWater = "flowingTropicsWater"; public static final String rainStopper = "rainStopper"; public static final String flower = "flower"; public static final String[] flowerIndices = new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14"}; public static final String[] flowerDisplayNames = {"Commelina Diffusa", "Crocosmia", "Orchid", "Canna", "Anemone", "Orange Anthurium", "Red Anthurium", "Magic Mushroom", "Pathos", "Acai Vine", "Croton", "Dracaena", "Fern", "Foilage", "Bromeliad"}; public static final String flowerPot = "flowerPot"; public static final String firePit = "firePit"; public static final String bambooChest = "bambooChest"; public static final String portal = "portal"; public static final String portalWall = "portalWall"; public static final String fruitLeaves = "fruitLeaves"; public static final String palmLeaves = "leafPalm"; public static final String leafRainforest = "leafRainforest"; public static final String[] rainforestLeafNames = new String[]{"Kapok", "Mahogany", "Fruit"}; public static final String leaf = "leaf"; public static final String[] fruitLeafNames = new String[]{"Grapefruit", "Lemon", "Lime", "Orange"}; public static final String bambooChute = "bambooChute"; public static final String purifiedSand = "purifiedSand"; public static final String mineralSand = "mineralSand"; public static final String[] mineralSandNames = new String[]{"Coral", "Green", "Black", "Mineral"}; public static final String sifter = "sifter"; public static final String curareBowl = "curareBowl"; public static final String bongoDrum = "bongoDrum"; public static final String[] bongoDrumNames = new String[]{"Small", "Medium", "Large"}; public static final String koaChest = "koaChest"; public static final String purchasePlate = "purchasePlate"; public static final String eihMixer = "eihMixer"; // Item names public static final String frogLeg = "frogLeg"; public static final String cookedFrogLeg = "cookedFrogLeg"; public static final String poisonFrogSkin = "poisonFrogSkin"; public static final String freshMarlin = "freshMarlin"; public static final String searedMarlin = "searedMarlin"; public static final String grapefruit = "grapefruit"; public static final String lemon = "lemon"; public static final String lime = "lime"; public static final String orange = "orange"; public static final String scale = "scale"; public static final String coconutChunk = "coconutChunk"; public static final String pineappleCubes = "pineappleCubes"; public static final String bambooStick = "bambooStick"; public static final String seaUrchinRoe = "seaUrchinRoe"; public static final String pearl = "pearl"; public static final String[] pearlNames = new String[]{"Solo", "Razzle"}; public static final String ore = "ore"; public static final String[] oreNames = new String[]{"Eudialyte", "Zircon", "Azurite", "Zirconium", "SmeltedZircon", "Unrefined", "Raftous"}; public static final String waterWand = "waterWand"; public static final String fishingNet = "fishingNet"; public static final String coffeeBean = "coffeeBean"; public static final String[] coffeeBeanNames = new String[]{"Berry", "Roasted", "Raw"}; public static final String scaleBoots = "scaleBoots"; public static final String scaleLeggings = "scaleLeggings"; public static final String scaleChestplate = "scaleChestplate"; public static final String scaleHelmet = "scaleHelmet"; public static final String fireBoots = "fireBoots"; public static final String fireLeggings = "fireLeggings"; public static final String fireChestplate = "fireChestplate"; public static final String fireHelmet = "fireHelmet"; public static final String axeEudialyte = "axeEudialyte"; public static final String hoeEudialyte = "hoeEudialyte"; public static final String pickaxeEudialyte = "pickaxeEudialyte"; public static final String shovelEudialyte = "shovelEudialyte"; public static final String swordEudialyte = "swordEudialyte"; public static final String axeZircon = "axeZircon"; public static final String hoeZircon = "hoeZircon"; public static final String pickaxeZircon = "pickaxeZircon"; public static final String shovelZircon = "shovelZircon"; public static final String swordZircon = "swordZircon"; public static final String axeZirconium = "axeZirconium"; public static final String hoeZirconium = "hoeZirconium"; public static final String pickaxeZirconium = "pickaxeZirconium"; public static final String shovelZirconium = "shovelZirconium"; public static final String swordZirconium = "swordZirconium"; public static final String bucketTropicsWater = "bucketTropicsWater"; public static final String chair = "chair"; public static final String umbrella = "umbrella"; public static final String fertilizer = "fertilizer"; public static final String coconut = "coconut"; public static final String coconutBomb = "coconutBomb"; public static final String innerTube = "innerTube"; public static final String dart = "dart"; public static final String dartOverlay = "dartOverlay"; public static final String curare = "curare"; public static final String curareOverlay = "curareOverlay"; public static final String dartGun = "blowGun"; public static final String shell = "shell"; public static final String[] shellNames = new String[]{"Solo", "Frox", "Pab", "Rube", "Starfish", "Turtle"}; public static final String aquaAxe = "aquaAxe"; public static final String aquaHoe = "aquaHoe"; public static final String aquaPickaxe = "aquaPickaxe"; public static final String aquaShovel = "aquaShovel"; public static final String bambooSpear = "bambooSpear"; public static final String snorkel = "snorkel"; public static final String flippers = "flippers"; public static final String dagger = "dagger"; public static final String staffFire = "staffFire"; public static final String staffTaming = "staffTaming"; public static final String fishingRodTropical = "fishingRodTropical"; public static final String recordBuriedTreasure = "record_buriedtreasure"; public static final String recordEasternIsles = "record_easternisles"; public static final String recordLowTide = "record_lowtide"; public static final String recordSummering = "record_summering"; public static final String recordTheTribe = "record_thetribe"; public static final String recordTradeWinds = "record_tradewinds"; public static final String portalEnchanter = "portalEnchanter"; public static final String bambooMug = "bambooMug"; public static final String koaFrame = "koaFrame"; public static final String tropiFrame = "tropiFrame"; public static final String cocktail = "cocktail"; public static final String leafBall = "leafBall"; public static final String fishBucket = "fishBucket"; public static final String snareTrap = "snareTrap"; public static final String encTropica = "encTropica"; public static final String[] eggTextureNames = {"iguana", "starfish", "greenfrog", "redfrog", "yellowfrog", "bluefrog", "eih", "marlin", "fish", "ashen", "turtle", "mow", "monkey", "koa", "tropicreeper", "tropiskelly", "eagleray", "failgull", "seaurchin"}; public static final String egg = "egg"; public static final String ashenMask = "ashenMask"; // Scuba public static final String dryFlippers = "dryFlippers"; public static final String dryLeggings = "dryLeggings"; public static final String dryChestplate = "dryChestplate"; public static final String dryHelmet = "dryHelmet"; public static final String dryChestplateGear = "dryChestplateGear"; public static final String wetFlippers = "wetFlippers"; public static final String wetLeggings = "wetLeggings"; public static final String wetChestplate = "wetChestplate"; public static final String wetHelmet = "wetHelmet"; public static final String wetChestplateGear = "wetChestplateGear"; public static final String scubaTank = "scubaTank"; public static final String diveComputer = "diveComputer"; public static final String bcd = "bcd"; public static final String airCompressor = "airCompressor"; }
mpl-2.0
CloudyPadmal/android-client
mifosng-android/src/main/java/com/mifos/objects/accounts/loan/LoanAccount.java
5914
/* * This project is licensed under the open source MPL V2. * See https://github.com/openMF/android-client/blob/master/LICENSE.md */ package com.mifos.objects.accounts.loan; import android.os.Parcel; import android.os.Parcelable; import com.mifos.api.local.MifosBaseModel; import com.mifos.api.local.MifosDatabase; import com.raizlabs.android.dbflow.annotation.Column; import com.raizlabs.android.dbflow.annotation.ForeignKey; import com.raizlabs.android.dbflow.annotation.ModelContainer; import com.raizlabs.android.dbflow.annotation.PrimaryKey; import com.raizlabs.android.dbflow.annotation.Table; @Table(database = MifosDatabase.class) @ModelContainer public class LoanAccount extends MifosBaseModel implements Parcelable { @Column long clientId; @Column long groupId; @PrimaryKey Integer id; @Column String accountNo; @Column String externalId; @Column Integer productId; @Column String productName; @Column @ForeignKey(saveForeignKeyModel = true) Status status; @Column @ForeignKey(saveForeignKeyModel = true) LoanType loanType; @Column Integer loanCycle; @Column Boolean inArrears; public LoanAccount() { } protected LoanAccount(Parcel in) { this.clientId = (Integer) in.readValue(Integer.class.getClassLoader()); this.id = (Integer) in.readValue(Integer.class.getClassLoader()); this.accountNo = in.readString(); this.externalId = in.readString(); this.productId = (Integer) in.readValue(Integer.class.getClassLoader()); this.productName = in.readString(); this.status = in.readParcelable(Status.class.getClassLoader()); this.loanType = in.readParcelable(LoanType.class.getClassLoader()); this.loanCycle = (Integer) in.readValue(Integer.class.getClassLoader()); this.inArrears = (Boolean) in.readValue(Boolean.class.getClassLoader()); } public long getGroupId() { return groupId; } public void setGroupId(long groupId) { this.groupId = groupId; } public long getClientId() { return this.clientId; } public void setClientId(long clientId) { this.clientId = clientId; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public LoanAccount withId(Integer id) { this.id = id; return this; } public String getAccountNo() { return accountNo; } public void setAccountNo(String accountNo) { this.accountNo = accountNo; } public LoanAccount withAccountNo(String accountNo) { this.accountNo = accountNo; return this; } public String getExternalId() { return externalId; } public void setExternalId(String externalId) { this.externalId = externalId; } public LoanAccount withExternalId(String externalId) { this.externalId = externalId; return this; } public Integer getProductId() { return productId; } public void setProductId(Integer productId) { this.productId = productId; } public LoanAccount withProductId(Integer productId) { this.productId = productId; return this; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public LoanAccount withProductName(String productName) { this.productName = productName; return this; } public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; } public LoanAccount withStatus(Status status) { this.status = status; return this; } public LoanType getLoanType() { return loanType; } public void setLoanType(LoanType loanType) { this.loanType = loanType; } public LoanAccount withLoanType(LoanType loanType) { this.loanType = loanType; return this; } public Integer getLoanCycle() { return loanCycle; } public void setLoanCycle(Integer loanCycle) { this.loanCycle = loanCycle; } public Boolean getInArrears() { return inArrears; } public void setInArrears(Boolean inArrears) { this.inArrears = inArrears; } @Override public String toString() { return "LoanAccount{" + "id=" + id + ", accountNo='" + accountNo + '\'' + ", externalId='" + externalId + '\'' + ", productId=" + productId + ", productName='" + productName + '\'' + ", status=" + status + ", loanType=" + loanType + ", loanCycle=" + loanCycle + '}'; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeValue(this.clientId); dest.writeValue(this.id); dest.writeString(this.accountNo); dest.writeString(this.externalId); dest.writeValue(this.productId); dest.writeString(this.productName); dest.writeParcelable(this.status, flags); dest.writeParcelable(this.loanType, flags); dest.writeValue(this.loanCycle); dest.writeValue(this.inArrears); } public static final Parcelable.Creator<LoanAccount> CREATOR = new Parcelable .Creator<LoanAccount>() { @Override public LoanAccount createFromParcel(Parcel source) { return new LoanAccount(source); } @Override public LoanAccount[] newArray(int size) { return new LoanAccount[size]; } }; }
mpl-2.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/ocrr/vo/lookups/ReportToTypeCollection.java
4802
//############################################################################# //# # //# 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.ocrr.vo.lookups; import ims.framework.cn.data.TreeModel; import ims.framework.cn.data.TreeNode; import ims.vo.LookupInstanceCollection; import ims.vo.LookupInstVo; public class ReportToTypeCollection extends LookupInstanceCollection implements ims.vo.ImsCloneable, TreeModel { private static final long serialVersionUID = 1L; public void add(ReportToType value) { super.add(value); } public int indexOf(ReportToType instance) { return super.indexOf(instance); } public boolean contains(ReportToType instance) { return indexOf(instance) >= 0; } public ReportToType get(int index) { return (ReportToType)super.getIndex(index); } public void remove(ReportToType instance) { if(instance != null) { int index = indexOf(instance); if(index >= 0) remove(index); } } public Object clone() { ReportToTypeCollection newCol = new ReportToTypeCollection(); ReportToType item; for (int i = 0; i < super.size(); i++) { item = this.get(i); newCol.add(new ReportToType(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((ReportToType)item.getParent().clone()); } } return newCol; } public ReportToType getInstance(int instanceId) { return (ReportToType)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 ReportToType[] toArray() { ReportToType[] arr = new ReportToType[this.size()]; super.toArray(arr); return arr; } public static ReportToTypeCollection buildFromBeanCollection(java.util.Collection beans) { ReportToTypeCollection coll = new ReportToTypeCollection(); if(beans == null) return coll; java.util.Iterator iter = beans.iterator(); while(iter.hasNext()) { coll.add(ReportToType.buildLookup((ims.vo.LookupInstanceBean)iter.next())); } return coll; } public static ReportToTypeCollection buildFromBeanCollection(ims.vo.LookupInstanceBean[] beans) { ReportToTypeCollection coll = new ReportToTypeCollection(); if(beans == null) return coll; for(int x = 0; x < beans.length; x++) { coll.add(ReportToType.buildLookup(beans[x])); } return coll; } }
agpl-3.0
erdincay/ejb
src/com/lp/server/inserat/fastlanereader/InseratartikelHandler.java
14118
/******************************************************************************* * 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.inserat.fastlanereader; import java.math.BigDecimal; import java.rmi.RemoteException; import java.util.Iterator; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.ScrollableResults; import org.hibernate.Session; import org.hibernate.SessionFactory; import com.lp.server.artikel.service.ArtikelDto; import com.lp.server.bestellung.service.BestellpositionFac; import com.lp.server.inserat.fastlanereader.generated.FLRInseratartikel; import com.lp.server.inserat.fastlanereader.generated.FLRInserater; import com.lp.server.inserat.service.InseratFac; import com.lp.server.util.Facade; import com.lp.server.util.fastlanereader.FLRSessionFactory; import com.lp.server.util.fastlanereader.UseCaseHandler; import com.lp.server.util.fastlanereader.service.query.FilterBlock; import com.lp.server.util.fastlanereader.service.query.FilterKriterium; import com.lp.server.util.fastlanereader.service.query.QueryParameters; import com.lp.server.util.fastlanereader.service.query.QueryResult; import com.lp.server.util.fastlanereader.service.query.SortierKriterium; import com.lp.server.util.fastlanereader.service.query.TableInfo; import com.lp.util.EJBExceptionLP; /** * <p> * Hier wird die FLR Funktionalitaet fuer den Auftrag implementiert. Pro UseCase * gibt es einen Handler. * </p> * <p> * Copright Logistik Pur Software GmbH (c) 2004-2007 * </p> * <p> * Erstellungsdatum 2004-08-14 * </p> * <p> * </p> * * @author martin werner, uli walch * @version 1.0 */ public class InseratartikelHandler extends UseCaseHandler { /** * */ private static final long serialVersionUID = 1L; public static final String FLR_INSERATARTIKEL = "flrinseratartikel."; public static final String FLR_INSERATARTIKEL_FROM_CLAUSE = " from FLRInseratartikel flrinseratartikel "; /** * gets the data page for the specified row using the current query. The row * at rowIndex will be located in the middle of the page. * * @param rowIndex * diese Zeile soll selektiert sein * @return QueryResult das Ergebnis der Abfrage * @throws EJBExceptionLP * Ausnahme * @see UseCaseHandler#getPageAt(java.lang.Integer) */ public QueryResult getPageAt(Integer rowIndex) throws EJBExceptionLP { QueryResult result = null; SessionFactory factory = FLRSessionFactory.getFactory(); Session session = null; try { int colCount = getTableInfo().getColumnClasses().length; int pageSize = PAGE_SIZE; int startIndex = Math.max(rowIndex.intValue() - (pageSize / 2), 0); int endIndex = startIndex + pageSize - 1; session = factory.openSession(); String queryString = this.getFromClause() + this.buildWhereClause() + this.buildOrderByClause(); Query query = session.createQuery(queryString); query.setFirstResult(startIndex); query.setMaxResults(pageSize); List<?> resultList = query.list(); Iterator<?> resultListIterator = resultList.iterator(); Object[][] rows = new Object[resultList.size()][colCount]; int row = 0; int col = 0; while (resultListIterator.hasNext()) { FLRInseratartikel inserat = (FLRInseratartikel) resultListIterator .next(); rows[row][col++] = inserat.getI_id(); rows[row][col++] = inserat.getFlrartikel().getC_nr(); ArtikelDto aDto = getArtikelFac().artikelFindByPrimaryKeySmall( inserat.getFlrartikel().getI_id(), theClientDto); rows[row][col++] = aDto.formatBezeichnung(); rows[row][col++] = inserat.getN_menge(); rows[row][col++] = inserat.getN_nettoeinzelpreis_ek(); rows[row][col++] = inserat.getN_nettoeinzelpreis_vk(); if (inserat.getFlrbestellposition() != null) { rows[row][col++] = inserat.getFlrbestellposition() .getFlrbestellung().getC_nr(); } else { rows[row][col++] = null; } row++; col = 0; } result = new QueryResult(rows, this.getRowCount(), startIndex, endIndex, 0); } catch (Exception e) { throw new EJBExceptionLP(EJBExceptionLP.FEHLER_FLR, e); } finally { try { session.close(); } catch (HibernateException he) { throw new EJBExceptionLP(EJBExceptionLP.FEHLER, he); } } return result; } /** * gets the total number of rows represented by the current query. * * @return int die Anzehl der Zeilen im Ergebnis * @see UseCaseHandler#getRowCountFromDataBase() */ protected long getRowCountFromDataBase() { long rowCount = 0; SessionFactory factory = FLRSessionFactory.getFactory(); Session session = null; try { session = factory.openSession(); String queryString = "select count(*) from FLRInseratartikel as flrinseratartikel " + this.buildWhereClause(); Query query = session.createQuery(queryString); List<?> rowCountResult = query.list(); if (rowCountResult != null && rowCountResult.size() > 0) { rowCount = ((Long) rowCountResult.get(0)).longValue(); } } catch (Exception e) { throw new EJBExceptionLP(EJBExceptionLP.FEHLER_FLR, e); } finally { if (session != null) { try { session.close(); } catch (HibernateException he) { throw new EJBExceptionLP(EJBExceptionLP.FEHLER_HIBERNATE, he); } } } return rowCount; } /** * builds the where clause of the HQL (Hibernate Query Language) statement * using the current query. * * @return the HQL where clause. */ private String buildWhereClause() { StringBuffer where = new StringBuffer(""); if (this.getQuery() != null && this.getQuery().getFilterBlock() != null && this.getQuery().getFilterBlock().filterKrit != null) { FilterBlock filterBlock = this.getQuery().getFilterBlock(); FilterKriterium[] filterKriterien = this.getQuery() .getFilterBlock().filterKrit; String booleanOperator = filterBlock.boolOperator; boolean filterAdded = false; for (int i = 0; i < filterKriterien.length; i++) { if (filterKriterien[i].isKrit) { if (filterAdded) { where.append(" " + booleanOperator); } filterAdded = true; if (filterKriterien[i].isBIgnoreCase()) { where.append(" lower(" + FLR_INSERATARTIKEL + filterKriterien[i].kritName + ")"); } else { where.append(" " + FLR_INSERATARTIKEL + filterKriterien[i].kritName); } where.append(" " + filterKriterien[i].operator); if (filterKriterien[i].isBIgnoreCase()) { where.append(" " + filterKriterien[i].value.toLowerCase()); } else { where.append(" " + filterKriterien[i].value); } } } if (filterAdded) { where.insert(0, " WHERE"); } } return where.toString(); } /** * builds the HQL (Hibernate Query Language) order by clause using the sort * criterias contained in the current query. * * @return the HQL order by clause. */ private String buildOrderByClause() { StringBuffer orderBy = new StringBuffer(""); if (this.getQuery() != null) { SortierKriterium[] kriterien = this.getQuery().getSortKrit(); boolean sortAdded = false; if (kriterien != null && kriterien.length > 0) { for (int i = 0; i < kriterien.length; i++) { if (!kriterien[i].kritName .endsWith(Facade.NICHT_SORTIERBAR)) { if (kriterien[i].isKrit) { if (sortAdded) { orderBy.append(", "); } sortAdded = true; orderBy.append(FLR_INSERATARTIKEL + kriterien[i].kritName); orderBy.append(" "); orderBy.append(kriterien[i].value); } } } } else { // no sort criteria found, add default sort if (sortAdded) { orderBy.append(", "); } orderBy.append(FLR_INSERATARTIKEL) .append("flrartikel.c_nr ASC").append(" ASC "); sortAdded = true; } if (orderBy.indexOf(FLR_INSERATARTIKEL + "i_id") < 0) { // Martin Werner original: "unique sort required because // otherwise rowNumber of selectedId // within sort() method may be different from the position of // selectedId // as returned in the page of getPageAt()." if (sortAdded) { orderBy.append(", "); } orderBy.append(" ").append(FLR_INSERATARTIKEL).append("i_id") .append(" ASC "); sortAdded = true; } if (sortAdded) { orderBy.insert(0, " ORDER BY "); } } return orderBy.toString(); } /** * get the basic from clause for the HQL statement. * * @return the from clause. */ private String getFromClause() { return "SELECT flrinseratartikel from FLRInseratartikel as flrinseratartikel "; } public QueryResult sort(SortierKriterium[] sortierKriterien, Object selectedId) throws EJBExceptionLP { QueryResult result = null; try { int rowNumber = 0; getQuery().setSortKrit(sortierKriterien); if (selectedId != null && ((Integer) selectedId).intValue() >= 0) { SessionFactory factory = FLRSessionFactory.getFactory(); Session session = null; try { session = factory.openSession(); String queryString = "select " + FLR_INSERATARTIKEL + "i_id" + FLR_INSERATARTIKEL_FROM_CLAUSE + this.buildWhereClause() + this.buildOrderByClause(); Query query = session.createQuery(queryString); ScrollableResults scrollableResult = query.scroll(); if (scrollableResult != null) { scrollableResult.beforeFirst(); while (scrollableResult.next()) { Integer id = (Integer) scrollableResult .getInteger(0); if (selectedId.equals(id)) { rowNumber = scrollableResult.getRowNumber(); break; } } } } finally { try { session.close(); } catch (HibernateException he) { throw new EJBExceptionLP( EJBExceptionLP.FEHLER_HIBERNATE, he); } } } if (rowNumber < 0 || rowNumber >= this.getRowCount()) { rowNumber = 0; } result = this.getPageAt(new Integer(rowNumber)); result.setIndexOfSelectedRow(rowNumber); } catch (Exception ex) { throw new EJBExceptionLP(EJBExceptionLP.FEHLER, ex); } return result; } public TableInfo getTableInfo() { if (super.getTableInfo() == null) { int iNachkommastellenPreisEK = 2; int iNachkommastellenPreisVK = 2; try { iNachkommastellenPreisVK = getMandantFac() .getNachkommastellenPreisVK(theClientDto.getMandant()); iNachkommastellenPreisEK = getMandantFac() .getNachkommastellenPreisEK(theClientDto.getMandant()); } catch (RemoteException e) { throwEJBExceptionLPRespectOld(e); } setTableInfo(new TableInfo( new Class[] { Integer.class, String.class, String.class, BigDecimal.class, super.getUIClassBigDecimalNachkommastellen(iNachkommastellenPreisEK), super.getUIClassBigDecimalNachkommastellen(iNachkommastellenPreisVK), String.class }, new String[] { "i_id", getTextRespectUISpr("artikel.artikelnummerlang", theClientDto.getMandant(), theClientDto.getLocUi()), getTextRespectUISpr("bes.artikelbezeichnung", theClientDto.getMandant(), theClientDto.getLocUi()), getTextRespectUISpr("lp.menge", theClientDto.getMandant(), theClientDto.getLocUi()), getTextRespectUISpr("iv.inseratartikel.ekpreis", theClientDto.getMandant(), theClientDto.getLocUi()), getTextRespectUISpr("iv.inseratartikel.vkpreis", theClientDto.getMandant(), theClientDto.getLocUi()), getTextRespectUISpr("lp.bestellnummer", theClientDto.getMandant(), theClientDto.getLocUi()) }, new int[] { QueryParameters.FLR_BREITE_SHARE_WITH_REST, // diese QueryParameters.FLR_BREITE_XM, QueryParameters.FLR_BREITE_SHARE_WITH_REST, QueryParameters.FLR_BREITE_PREIS, QueryParameters.FLR_BREITE_PREIS, QueryParameters.FLR_BREITE_PREIS, QueryParameters.FLR_BREITE_PREIS }, new String[] { "i_id", InseratFac.FLR_INSERATARTIKEL_FLRARTIKEL + ".c_nr", Facade.NICHT_SORTIERBAR, InseratFac.FLR_INSERAT_N_MENGE, InseratFac.FLR_INSERATARTIKEL_N_NETTOEINZELPREIS_EK, InseratFac.FLR_INSERATARTIKEL_N_NETTOEINZELPREIS_VK, InseratFac.FLR_INSERATARTIKEL_FLRBESTELLPOSITION + "." + BestellpositionFac.FLR_BESTELLPOSITION_FLRBESTELLUNG + ".c_nr" })); } return super.getTableInfo(); } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/Pathways/src/ims/pathways/forms/patientdiary/Logic.java
2640
//############################################################################# //# # //# 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 Daniel Laffan using IMS Development Environment (version 1.60 build 2876.30621) // Copyright (C) 1995-2007 IMS MAXIMS plc. All rights reserved. package ims.pathways.forms.patientdiary; import ims.pathways.vo.PatientEventLiteVoCollection; public class Logic extends BaseLogic { private static final long serialVersionUID = 1L; @Override protected void onFormOpen(Object[] args) throws ims.framework.exceptions.PresentationLogicException { form.diary().clear(); PatientEventLiteVoCollection voCollPatientEvents = domain.listPatientEventByPatient(form.getGlobalContext().Core.getPatientShort()); if(voCollPatientEvents != null) form.diary().addEntries(voCollPatientEvents.toIDiaryEntryArray()); } }
agpl-3.0
teoincontatto/engine
core/src/main/java/com/torodb/core/transaction/metainf/MetaDocPartIndex.java
1927
/* * ToroDB * Copyright © 2014 8Kdata Technology (www.8kdata.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.torodb.core.transaction.metainf; import java.util.Iterator; import java.util.stream.Stream; import javax.annotation.Nullable; /** */ public interface MetaDocPartIndex { public abstract boolean isUnique(); public abstract int size(); public abstract Stream<? extends MetaDocPartIndexColumn> streamColumns(); public default Iterator<? extends MetaDocPartIndexColumn> iteratorColumns() { return streamColumns().iterator(); } @Nullable public abstract MetaDocPartIndexColumn getMetaDocPartIndexColumnByPosition(int position); @Nullable public abstract MetaDocPartIndexColumn getMetaDocPartIndexColumnByIdentifier(String columnName); public abstract boolean hasSameColumns(MetaDocPartIndex docPartIndex); public default String defautToString() { return "docPartIndex{" + "unique:" + isUnique() + '}'; } /** * @throws IllegalArgumentException if this index does not contains all column from position 0 to * the position for the column with maximum position */ public abstract ImmutableMetaIdentifiedDocPartIndex immutableCopy(String identifier) throws IllegalArgumentException; }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/nursing/vo/StoolScaleVo.java
10772
//############################################################################# //# # //# 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.nursing.vo; /** * Linked to core.clinical.Assessment business object (ID: 1003100002). */ public class StoolScaleVo extends ims.core.vo.AssessmentToolVo implements ims.vo.ImsCloneable, Comparable { private static final long serialVersionUID = 1L; public StoolScaleVo() { } public StoolScaleVo(Integer id, int version) { super(id, version); } public StoolScaleVo(ims.nursing.vo.beans.StoolScaleVoBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.hcpinitiated = bean.getHcpInitiated() == null ? null : bean.getHcpInitiated().buildVo(); this.datetimeinitiated = bean.getDateTimeInitiated() == null ? null : bean.getDateTimeInitiated().buildDateTime(); this.clinicalcontact = bean.getClinicalContact() == null ? null : new ims.core.admin.vo.ClinicalContactRefVo(new Integer(bean.getClinicalContact().getId()), bean.getClinicalContact().getVersion()); this.carecontext = bean.getCareContext() == null ? null : new ims.core.admin.vo.CareContextRefVo(new Integer(bean.getCareContext().getId()), bean.getCareContext().getVersion()); this.stooltype = bean.getStoolType() == null ? null : ims.nursing.vo.lookups.StoolType.buildLookup(bean.getStoolType()); this.details = bean.getDetails(); this.result = bean.getResult() == null ? null : ims.core.vo.lookups.YesNo.buildLookup(bean.getResult()); this.frequency = bean.getFrequency(); } public void populate(ims.vo.ValueObjectBeanMap map, ims.nursing.vo.beans.StoolScaleVoBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.hcpinitiated = bean.getHcpInitiated() == null ? null : bean.getHcpInitiated().buildVo(map); this.datetimeinitiated = bean.getDateTimeInitiated() == null ? null : bean.getDateTimeInitiated().buildDateTime(); this.clinicalcontact = bean.getClinicalContact() == null ? null : new ims.core.admin.vo.ClinicalContactRefVo(new Integer(bean.getClinicalContact().getId()), bean.getClinicalContact().getVersion()); this.carecontext = bean.getCareContext() == null ? null : new ims.core.admin.vo.CareContextRefVo(new Integer(bean.getCareContext().getId()), bean.getCareContext().getVersion()); this.stooltype = bean.getStoolType() == null ? null : ims.nursing.vo.lookups.StoolType.buildLookup(bean.getStoolType()); this.details = bean.getDetails(); this.result = bean.getResult() == null ? null : ims.core.vo.lookups.YesNo.buildLookup(bean.getResult()); this.frequency = bean.getFrequency(); } public ims.vo.ValueObjectBean getBean() { return this.getBean(new ims.vo.ValueObjectBeanMap()); } public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map) { ims.nursing.vo.beans.StoolScaleVoBean bean = null; if(map != null) bean = (ims.nursing.vo.beans.StoolScaleVoBean)map.getValueObjectBean(this); if (bean == null) { bean = new ims.nursing.vo.beans.StoolScaleVoBean(); map.addValueObjectBean(this, bean); bean.populate(map, this); } return bean; } public Object getFieldValueByFieldName(String fieldName) { if(fieldName == null) throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name"); fieldName = fieldName.toUpperCase(); if(fieldName.equals("STOOLTYPE")) return getStoolType(); if(fieldName.equals("DETAILS")) return getDetails(); if(fieldName.equals("RESULT")) return getResult(); if(fieldName.equals("FREQUENCY")) return getFrequency(); return super.getFieldValueByFieldName(fieldName); } public boolean getStoolTypeIsNotNull() { return this.stooltype != null; } public ims.nursing.vo.lookups.StoolType getStoolType() { return this.stooltype; } public void setStoolType(ims.nursing.vo.lookups.StoolType value) { this.isValidated = false; this.stooltype = value; } public boolean getDetailsIsNotNull() { return this.details != null; } public String getDetails() { return this.details; } public static int getDetailsMaxLength() { return 255; } public void setDetails(String value) { this.isValidated = false; this.details = value; } public boolean getResultIsNotNull() { return this.result != null; } public ims.core.vo.lookups.YesNo getResult() { return this.result; } public void setResult(ims.core.vo.lookups.YesNo value) { this.isValidated = false; this.result = value; } public boolean getFrequencyIsNotNull() { return this.frequency != null; } public String getFrequency() { return this.frequency; } public static int getFrequencyMaxLength() { return 255; } public void setFrequency(String value) { this.isValidated = false; this.frequency = value; } public boolean isValidated() { if(this.isBusy) return true; this.isBusy = true; if(!this.isValidated) { this.isBusy = false; return false; } this.isBusy = false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(this.isBusy) return null; this.isBusy = true; java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>(); if(existingErrors != null) { for(int x = 0; x < existingErrors.length; x++) { listOfErrors.add(existingErrors[x]); } } if(this.carecontext == null) listOfErrors.add("CareContext is mandatory"); if(this.countFieldsWithValue() < 3) { listOfErrors.add("A minimum of 3 data fields must be entered"); } int errorCount = listOfErrors.size(); if(errorCount == 0) { this.isBusy = false; this.isValidated = true; return null; } String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); this.isBusy = false; this.isValidated = false; return result; } public void clearIDAndVersion() { this.id = null; this.version = 0; } public Object clone() { if(this.isBusy) return this; this.isBusy = true; StoolScaleVo clone = new StoolScaleVo(this.id, this.version); if(this.hcpinitiated == null) clone.hcpinitiated = null; else clone.hcpinitiated = (ims.core.vo.HcpLiteVo)this.hcpinitiated.clone(); if(this.datetimeinitiated == null) clone.datetimeinitiated = null; else clone.datetimeinitiated = (ims.framework.utils.DateTime)this.datetimeinitiated.clone(); clone.clinicalcontact = this.clinicalcontact; clone.carecontext = this.carecontext; if(this.stooltype == null) clone.stooltype = null; else clone.stooltype = (ims.nursing.vo.lookups.StoolType)this.stooltype.clone(); clone.details = this.details; if(this.result == null) clone.result = null; else clone.result = (ims.core.vo.lookups.YesNo)this.result.clone(); clone.frequency = this.frequency; clone.isValidated = this.isValidated; this.isBusy = false; return clone; } public int compareTo(Object obj) { return compareTo(obj, true); } public int compareTo(Object obj, boolean caseInsensitive) { if (obj == null) { return -1; } if(caseInsensitive); // this is to avoid eclipse warning only. if (!(StoolScaleVo.class.isAssignableFrom(obj.getClass()))) { throw new ClassCastException("A StoolScaleVo object cannot be compared an Object of type " + obj.getClass().getName()); } StoolScaleVo compareObj = (StoolScaleVo)obj; int retVal = 0; if (retVal == 0) { if(this.getDateTimeInitiated() == null && compareObj.getDateTimeInitiated() != null) return -1; if(this.getDateTimeInitiated() != null && compareObj.getDateTimeInitiated() == null) return 1; if(this.getDateTimeInitiated() != null && compareObj.getDateTimeInitiated() != null) retVal = this.getDateTimeInitiated().compareTo(compareObj.getDateTimeInitiated()); } return retVal; } public synchronized static int generateValueObjectUniqueID() { return ims.vo.ValueObject.generateUniqueID(); } public int countFieldsWithValue() { int count = super.countFieldsWithValue(); if(this.stooltype != null) count++; if(this.details != null) count++; if(this.result != null) count++; if(this.frequency != null) count++; return count; } public int countValueObjectFields() { return super.countValueObjectFields() + 4; } protected ims.nursing.vo.lookups.StoolType stooltype; protected String details; protected ims.core.vo.lookups.YesNo result; protected String frequency; private boolean isValidated = false; private boolean isBusy = false; }
agpl-3.0
open-health-hub/openmaxims-linux
openmaxims_workspace/ValueObjects/src/ims/core/vo/beans/PatientDocumentSearchListVoBean.java
7238
//############################################################################# //# # //# 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.core.vo.beans; public class PatientDocumentSearchListVoBean extends ims.vo.ValueObjectBean { public PatientDocumentSearchListVoBean() { } public PatientDocumentSearchListVoBean(ims.core.vo.PatientDocumentSearchListVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.creationtype = vo.getCreationType() == null ? null : (ims.vo.LookupInstanceBean)vo.getCreationType().getBean(); this.category = vo.getCategory() == null ? null : (ims.vo.LookupInstanceBean)vo.getCategory().getBean(); this.specialty = vo.getSpecialty() == null ? null : (ims.vo.LookupInstanceBean)vo.getSpecialty().getBean(); this.authoringhcp = vo.getAuthoringHCP() == null ? null : (ims.core.vo.beans.HcpLiteVoBean)vo.getAuthoringHCP().getBean(); this.documentdate = vo.getDocumentDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getDocumentDate().getBean(); this.recordingdatetime = vo.getRecordingDateTime() == null ? null : (ims.framework.utils.beans.DateTimeBean)vo.getRecordingDateTime().getBean(); this.currentdocumentstatus = vo.getCurrentDocumentStatus() == null ? null : (ims.core.vo.beans.PatientDocumentStatusVoBean)vo.getCurrentDocumentStatus().getBean(); this.responsiblehcp = vo.getResponsibleHCP() == null ? null : (ims.core.vo.beans.HcpLiteVoBean)vo.getResponsibleHCP().getBean(); } public void populate(ims.vo.ValueObjectBeanMap map, ims.core.vo.PatientDocumentSearchListVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.creationtype = vo.getCreationType() == null ? null : (ims.vo.LookupInstanceBean)vo.getCreationType().getBean(); this.category = vo.getCategory() == null ? null : (ims.vo.LookupInstanceBean)vo.getCategory().getBean(); this.specialty = vo.getSpecialty() == null ? null : (ims.vo.LookupInstanceBean)vo.getSpecialty().getBean(); this.authoringhcp = vo.getAuthoringHCP() == null ? null : (ims.core.vo.beans.HcpLiteVoBean)vo.getAuthoringHCP().getBean(map); this.documentdate = vo.getDocumentDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getDocumentDate().getBean(); this.recordingdatetime = vo.getRecordingDateTime() == null ? null : (ims.framework.utils.beans.DateTimeBean)vo.getRecordingDateTime().getBean(); this.currentdocumentstatus = vo.getCurrentDocumentStatus() == null ? null : (ims.core.vo.beans.PatientDocumentStatusVoBean)vo.getCurrentDocumentStatus().getBean(map); this.responsiblehcp = vo.getResponsibleHCP() == null ? null : (ims.core.vo.beans.HcpLiteVoBean)vo.getResponsibleHCP().getBean(map); } public ims.core.vo.PatientDocumentSearchListVo buildVo() { return this.buildVo(new ims.vo.ValueObjectBeanMap()); } public ims.core.vo.PatientDocumentSearchListVo buildVo(ims.vo.ValueObjectBeanMap map) { ims.core.vo.PatientDocumentSearchListVo vo = null; if(map != null) vo = (ims.core.vo.PatientDocumentSearchListVo)map.getValueObject(this); if(vo == null) { vo = new ims.core.vo.PatientDocumentSearchListVo(); map.addValueObject(this, vo); vo.populate(map, this); } return vo; } public Integer getId() { return this.id; } public void setId(Integer value) { this.id = value; } public int getVersion() { return this.version; } public void setVersion(int value) { this.version = value; } public ims.vo.LookupInstanceBean getCreationType() { return this.creationtype; } public void setCreationType(ims.vo.LookupInstanceBean value) { this.creationtype = value; } public ims.vo.LookupInstanceBean getCategory() { return this.category; } public void setCategory(ims.vo.LookupInstanceBean value) { this.category = value; } public ims.vo.LookupInstanceBean getSpecialty() { return this.specialty; } public void setSpecialty(ims.vo.LookupInstanceBean value) { this.specialty = value; } public ims.core.vo.beans.HcpLiteVoBean getAuthoringHCP() { return this.authoringhcp; } public void setAuthoringHCP(ims.core.vo.beans.HcpLiteVoBean value) { this.authoringhcp = value; } public ims.framework.utils.beans.DateBean getDocumentDate() { return this.documentdate; } public void setDocumentDate(ims.framework.utils.beans.DateBean value) { this.documentdate = value; } public ims.framework.utils.beans.DateTimeBean getRecordingDateTime() { return this.recordingdatetime; } public void setRecordingDateTime(ims.framework.utils.beans.DateTimeBean value) { this.recordingdatetime = value; } public ims.core.vo.beans.PatientDocumentStatusVoBean getCurrentDocumentStatus() { return this.currentdocumentstatus; } public void setCurrentDocumentStatus(ims.core.vo.beans.PatientDocumentStatusVoBean value) { this.currentdocumentstatus = value; } public ims.core.vo.beans.HcpLiteVoBean getResponsibleHCP() { return this.responsiblehcp; } public void setResponsibleHCP(ims.core.vo.beans.HcpLiteVoBean value) { this.responsiblehcp = value; } private Integer id; private int version; private ims.vo.LookupInstanceBean creationtype; private ims.vo.LookupInstanceBean category; private ims.vo.LookupInstanceBean specialty; private ims.core.vo.beans.HcpLiteVoBean authoringhcp; private ims.framework.utils.beans.DateBean documentdate; private ims.framework.utils.beans.DateTimeBean recordingdatetime; private ims.core.vo.beans.PatientDocumentStatusVoBean currentdocumentstatus; private ims.core.vo.beans.HcpLiteVoBean responsiblehcp; }
agpl-3.0
medsob/Tanaguru
web-app/tgol-si/src/main/java/org/tanaguru/webapp/entity/option/OptionFamilyImpl.java
2884
/* * 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.entity.option; import java.io.Serializable; import javax.persistence.*; import javax.xml.bind.annotation.XmlRootElement; /** * * @author jkowalczyk */ @Entity @Table(name = "TGSI_OPTION_FAMILY") @XmlRootElement public class OptionFamilyImpl implements OptionFamily, Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "Id_Option_Family") private Long id; @Column(name = "Code") private String code; @Column(name = "Label") private String label; @Column(name = "Description") private String description; @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public String getCode() { return code; } @Override public void setCode(String code) { this.code = code; } @Override public String getLabel() { return label; } @Override public void setLabel(String label) { this.label = label; } @Override public String getDescription() { return description ; } @Override public void setDescription(String description) { this.description = description; } @Override public int hashCode() { int hash = 5; hash = 67 * hash + (this.id != null ? this.id.hashCode() : 0); hash = 67 * hash + (this.code != null ? this.code.hashCode() : 0); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final OptionFamilyImpl other = (OptionFamilyImpl) obj; if (this.id == null || !this.id.equals(other.id)) { return false; } if ((this.code == null) ? (other.code != null) : !this.code.equals(other.code)) { return false; } return true; } }
agpl-3.0
stephaneperry/Silverpeas-Components
mydb/mydb-ejb/src/main/java/com/silverpeas/mydb/data/index/IndexElementComparator.java
1733
/** * Copyright (C) 2000 - 2011 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 received a copy of the text describing * the FLOSS exception, and it is also available here: * "http://repository.silverpeas.com/legal/licensing" * * 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.silverpeas.mydb.data.index; import java.util.Comparator; /** * IndexElement comparator. Elements are sorted by their names if they are different, else sorted by * their position index. * @author Antoine HEDIN */ public class IndexElementComparator implements Comparator<IndexElement> { public int compare(IndexElement element1, IndexElement element2) { if (element1.getIndexName().equals(element2.getIndexName())) { return element1.getPosition() - element2.getPosition(); } else { return element1.getIndexName().compareTo(element2.getIndexName()); } } }
agpl-3.0
RestComm/restcomm-android-sdk
Examples/restcomm-olympus/app/src/main/java/org/restcomm/android/olympus/MessageActivity.java
19224
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2015, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * 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/> * * For questions related to commercial use licensing, please contact sales@telestax.com. * */ package org.restcomm.android.olympus; import android.app.AlertDialog; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.preference.PreferenceManager; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; import org.restcomm.android.olympus.Util.Utils; import org.restcomm.android.sdk.RCClient; import org.restcomm.android.sdk.RCConnection; import org.restcomm.android.sdk.RCDevice; import org.restcomm.android.sdk.RCDeviceListener; import org.restcomm.android.sdk.util.RCException; import java.util.HashMap; import java.util.Locale; public class MessageActivity extends AppCompatActivity implements MessageFragment.Callbacks, RCDeviceListener, View.OnClickListener, ServiceConnection { private RCDevice device; boolean serviceBound = false; HashMap<String, Object> params = new HashMap<String, Object>(); // keep around for each jobId that creates a message the index it gets inside the ListView //HashMap<String, Integer> indexes = new HashMap<String, Integer>(); private static final String TAG = "MessageActivity"; private AlertDialog alertDialog; private String currentPeer; private String fullPeer; // Timer that starts if there's a live call on another Activity and periodically checks if the call is over to update the UI // TODO: need to improve this from polling to event based but we need to think in terms of general SDK API. Let's leave it like // this for now and we will revisit private Handler timerHandler = new Handler(); ImageButton btnSend; EditText txtMessage; TextView lblOngoingCall; public static String ACTION_OPEN_MESSAGE_SCREEN = "org.restcomm.android.olympus.ACTION_OPEN_MESSAGE_SCREEN"; public static String EXTRA_CONTACT_NAME = "org.restcomm.android.olympus.EXTRA_CONTACT_NAME"; private MessageFragment listFragment; /** * Whether or not the activity is in two-pane mode, i.e. running on a tablet * device. */ private boolean mTwoPane; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_message); Toolbar toolbar = (Toolbar) findViewById(R.id.message_toolbar); setSupportActionBar(toolbar); toolbar.setTitle(getTitle()); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { // Show the Up button in the action bar. actionBar.setDisplayHomeAsUpEnabled(true); } listFragment = (MessageFragment) getSupportFragmentManager().findFragmentById(R.id.message_list); alertDialog = new AlertDialog.Builder(MessageActivity.this, R.style.SimpleAlertStyle).create(); btnSend = (ImageButton) findViewById(R.id.button_send); btnSend.setOnClickListener(this); txtMessage = (EditText) findViewById(R.id.text_message); txtMessage.setOnClickListener(this); lblOngoingCall = findViewById(R.id.resume_call); lblOngoingCall.setOnClickListener(this); fullPeer = getIntent().getStringExtra(RCDevice.EXTRA_DID); // keep on note of the current peer we are texting with currentPeer = getIntent().getStringExtra(RCDevice.EXTRA_DID).replaceAll("^sip.?:", "").replaceAll("@.*$", ""); setTitle(currentPeer); } @Override protected void onStart() { super.onStart(); // The activity is about to become visible. Log.i(TAG, "%% onStart"); bindService(new Intent(this, RCDevice.class), this, Context.BIND_AUTO_CREATE); } @Override protected void onResume() { super.onResume(); Log.i(TAG, "%% onResume"); if (device != null) { // needed if we are returning from Message screen that becomes the Device listener device.setDeviceListener(this); } } @Override protected void onPause() { super.onPause(); // Another activity is taking focus (this activity is about to be "paused"). Log.i(TAG, "%% onPause"); Intent intent = getIntent(); // #129: clear the action so that on subsequent indirect activity open (i.e. via lock & unlock) we don't get the old action firing again intent.setAction("CLEAR_ACTION"); setIntent(intent); } @Override protected void onStop() { super.onStop(); // The activity is no longer visible (it is now "stopped") Log.i(TAG, "%% onStop"); if (lblOngoingCall.getVisibility() != View.GONE) { lblOngoingCall.setVisibility(View.GONE); if (timerHandler != null) { timerHandler.removeCallbacksAndMessages(null); } } // Unbind from the service if (serviceBound) { //device.detach(); unbindService(this); serviceBound = false; } } @Override protected void onDestroy() { super.onDestroy(); // The activity is about to be destroyed. Log.i(TAG, "%% onDestroy"); } // We 've set MessageActivity to be 'singleTop' on the manifest to be able to receive messages while already open, without instantiating // a new activity. When that happens we receive onNewIntent() // An activity will always be paused before receiving a new intent, so you can count on onResume() being called after this method @Override public void onNewIntent(Intent intent) { super.onNewIntent(intent); // Note that getIntent() still returns the original Intent. You can use setIntent(Intent) to update it to this new Intent. setIntent(intent); // if a mesage arrives after we have created activity it will land here handleMessage(intent); } // Callbacks for service binding, passed to bindService() @Override public void onServiceConnected(ComponentName className, IBinder service) { Log.i(TAG, "%% onServiceConnected"); // We've bound to LocalService, cast the IBinder and get LocalService instance RCDevice.RCDeviceBinder binder = (RCDevice.RCDeviceBinder) service; device = binder.getService(); if (device.isInitialized()) { RCConnection connection = device.getLiveConnection(); if (connection != null) { // we have a live connection ongoing, need to update UI so that it can be resumed lblOngoingCall.setText(String.format("%s %s", getString(R.string.resume_ongoing_call_text), connection.getPeer())); lblOngoingCall.setVisibility(View.VISIBLE); startTimer(); } } else { Log.i(TAG, "RCDevice not initialized; initializing"); PreferenceManager.setDefaultValues(this, R.xml.preferences, false); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); HashMap<String, Object> params = Utils.createParameters(prefs, this); // If exception is raised, we will close activity only if it comes from login // otherwise we will just show the error dialog device.setLogLevel(Log.VERBOSE); try { device.initialize(getApplicationContext(), params, this); } catch (RCException e) { showOkAlert("RCDevice Initialization Error", e.errorText); } } // needed if we are returning from Message screen that becomes the Device listener device.setDeviceListener(this); // We have the device reference, let's handle the call handleMessage(getIntent()); serviceBound = true; } @Override public void onServiceDisconnected(ComponentName arg0) { Log.i(TAG, "%% onServiceDisconnected"); serviceBound = false; } private void handleMessage(Intent intent) { if (device.getState() == RCDevice.DeviceState.OFFLINE) { getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.colorTextSecondary))); } else { getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.colorPrimary))); } // Get Intent parameters. if (intent.getAction().equals(ACTION_OPEN_MESSAGE_SCREEN)) { params.put(RCConnection.ParameterKeys.CONNECTION_PEER, intent.getStringExtra(RCDevice.EXTRA_DID)); String shortname = intent.getStringExtra(RCDevice.EXTRA_DID).replaceAll("^sip.?:", "").replaceAll("@.*$", ""); setTitle(shortname); } if (intent.getAction().equals(RCDevice.ACTION_INCOMING_MESSAGE)) { String message = intent.getStringExtra(RCDevice.EXTRA_MESSAGE_TEXT); //HashMap<String, String> intentParams = (HashMap<String, String>) finalIntent.getSerializableExtra(RCDevice.INCOMING_MESSAGE_PARAMS); //String username = intentParams.get(RCConnection.ParameterKeys.CONNECTION_PEER); String username = intent.getStringExtra(RCDevice.EXTRA_DID); String shortname = username.replaceAll("^sip.?:", "").replaceAll("@.*$", ""); if (!shortname.equals(currentPeer)) { // message originating from another peer, not the one we are currently texting with, just update DB and show a Toast Toast.makeText(getApplicationContext(), "New text from \'" + shortname + "\': " + message, Toast.LENGTH_LONG).show(); if (DatabaseManager.getInstance().addContactIfNeded(username)) { Toast.makeText(getApplicationContext(), "Adding '" + shortname + "\' to contacts as it doesn't exist", Toast.LENGTH_LONG).show(); } //DatabaseManager.getInstance().addMessage(shortname, message, false); listFragment.addRemoteMessage(message, shortname); return; } params.put(RCConnection.ParameterKeys.CONNECTION_PEER, username); //setTitle(shortname); if (DatabaseManager.getInstance().addContactIfNeded(username)) { Toast.makeText(getApplicationContext(), "Text message sender not found; updating Contacts with \'" + shortname + "\'", Toast.LENGTH_LONG).show(); } listFragment.addRemoteMessage(message, shortname); } } /** * Message Activity onClick */ public void onClick(View view) { if (view.getId() == R.id.button_send) { HashMap<String, String> sendParams = new HashMap<String, String>(); String connectionPeer = (String) params.get(RCConnection.ParameterKeys.CONNECTION_PEER); sendParams.put(RCConnection.ParameterKeys.CONNECTION_PEER, connectionPeer); try { String jobId = device.sendMessage(txtMessage.getText().toString(), sendParams); // also output the message in the wall listFragment.addLocalMessage(txtMessage.getText().toString(), connectionPeer.replaceAll("^sip.?:", "").replaceAll("@.*$", ""), jobId); //indexes.put(messageStatus.jobId, index); txtMessage.setText(""); //txtWall.append("Me: " + txtMessage.getText().toString() + "\n\n"); } catch (RCException e) { showOkAlert("RCDevice Error", "No Wifi connectivity"); } } else if (view.getId() == R.id.resume_call) { Intent intent = new Intent(this, CallActivity.class); intent.setAction(RCDevice.ACTION_RESUME_CALL); startActivity(intent); } } /** * RCDeviceListener callbacks */ public void onInitialized(RCDevice device, RCDeviceListener.RCConnectivityStatus connectivityStatus, int statusCode, String statusText) { Log.i(TAG, "%% onInitialized"); if (statusCode == RCClient.ErrorCodes.SUCCESS.ordinal()) { handleConnectivityUpdate(connectivityStatus, "RCDevice successfully initialized, using: " + connectivityStatus); } else if (statusCode == RCClient.ErrorCodes.ERROR_DEVICE_NO_CONNECTIVITY.ordinal()) { // This is not really an error, since if connectivity comes back the RCDevice will resume automatically handleConnectivityUpdate(connectivityStatus, null); } else { if (!isFinishing()) { showOkAlert("RCDevice Initialization Error", statusText); } } } public void onReconfigured(RCDevice device, RCConnectivityStatus connectivityStatus, int statusCode, String statusText) { Log.i(TAG, "%% onReconfigured"); } public void onError(RCDevice device, int errorCode, String errorText) { if (errorCode == RCClient.ErrorCodes.SUCCESS.ordinal()) { handleConnectivityUpdate(RCConnectivityStatus.RCConnectivityStatusNone, "RCDevice: " + errorText); } else { handleConnectivityUpdate(RCConnectivityStatus.RCConnectivityStatusNone, "RCDevice Error: " + errorText); } } public void onConnectivityUpdate(RCDevice device, RCConnectivityStatus connectivityStatus) { Log.i(TAG, "%% onConnectivityUpdate"); handleConnectivityUpdate(connectivityStatus, null); } public void onMessageSent(RCDevice device, int statusCode, String statusText, String jobId) { Log.i(TAG, "onMessageSent(): statusCode: " + statusCode + ", statusText: " + statusText); listFragment.updateMessageDeliveryStatus(jobId, statusCode, currentPeer); } public void onReleased(RCDevice device, int statusCode, String statusText) { if (statusCode != RCClient.ErrorCodes.SUCCESS.ordinal()) { showOkAlert("RCDevice Error", statusText); } //maybe we stopped the activity before onReleased is called if (serviceBound) { unbindService(this); serviceBound = false; } } /** * Helpers */ private void showOkAlert(final String title, final String detail) { Log.d(TAG, "Showing alert: " + title + ", detail: " + detail); if (alertDialog.isShowing()) { Log.w(TAG, "Alert already showing, hiding to show new alert"); alertDialog.hide(); } alertDialog.setTitle(title); alertDialog.setMessage(detail); alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alertDialog.show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_message, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (device.getState() == RCDevice.DeviceState.READY) { if (id == R.id.action_video_call) { Intent intent = new Intent(this, CallActivity.class); intent.setAction(RCDevice.ACTION_OUTGOING_CALL); intent.putExtra(RCDevice.EXTRA_DID, fullPeer); intent.putExtra(RCDevice.EXTRA_VIDEO_ENABLED, true); startActivity(intent); } if (id == R.id.action_audio_call) { Intent intent = new Intent(this, CallActivity.class); intent.setAction(RCDevice.ACTION_OUTGOING_CALL); intent.putExtra(RCDevice.EXTRA_DID, fullPeer); intent.putExtra(RCDevice.EXTRA_VIDEO_ENABLED, false); startActivity(intent); } } else if (device.getState() == RCDevice.DeviceState.BUSY) { showOkAlert("RCDevice is busy", "Call already ongoing, please hang up first if you want to start a new one"); } return super.onOptionsItemSelected(item); } public void handleConnectivityUpdate(RCConnectivityStatus connectivityStatus, String text) { if (text == null) { if (connectivityStatus == RCConnectivityStatus.RCConnectivityStatusNone) { text = "RCDevice connectivity change: Lost connectivity"; } if (connectivityStatus == RCConnectivityStatus.RCConnectivityStatusWiFi) { text = "RCDevice connectivity change: Reestablished connectivity (Wifi)"; } if (connectivityStatus == RCConnectivityStatus.RCConnectivityStatusCellular) { text = "RCDevice connectivity change: Reestablished connectivity (Cellular)"; } if (connectivityStatus == RCConnectivityStatus.RCConnectivityStatusEthernet) { text = "RCDevice connectivity change: Reestablished connectivity (Ethernet)"; } } if (connectivityStatus == RCConnectivityStatus.RCConnectivityStatusNone) { getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.colorTextSecondary))); } else { getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.colorPrimary))); } Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show(); } public void startTimer() { timerHandler.removeCallbacksAndMessages(null); // schedule a registration update after 'registrationRefresh' seconds Runnable timerRunnable = new Runnable() { @Override public void run() { if (device != null && device.isInitialized() && (device.getLiveConnection() == null)) { if (lblOngoingCall.getVisibility() != View.GONE) { lblOngoingCall.setVisibility(View.GONE); return; } } startTimer(); } }; timerHandler.postDelayed(timerRunnable, 1000); } }
agpl-3.0
IMS-MAXIMS/openMAXIMS
Source Library/openmaxims_workspace/Emergency/src/ims/emergency/forms/eventhistory/AccessLogic.java
2542
//############################################################################# //# # //# 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 Bogdan Tofei using IMS Development Environment (version 1.80 build 4471.18200) // Copyright (C) 1995-2012 IMS MAXIMS. All rights reserved. package ims.emergency.forms.eventhistory; import java.io.Serializable; public final class AccessLogic extends BaseAccessLogic implements Serializable { private static final long serialVersionUID = 1L; public boolean isAccessible() { if(!super.isAccessible()) return false; // TODO: Add your conditions here. return true; } public boolean isReadOnly() { if(super.isReadOnly()) return true; // TODO: Add your conditions here. return false; } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/ocrr/orderingresults/vo/SpecimenCollectionStatusRefVoCollection.java
6195
//############################################################################# //# # //# 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.ocrr.orderingresults.vo; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import ims.framework.enumerations.SortOrder; /** * Linked to OCRR.OrderingResults.SpecimenCollectionStatus business object (ID: 1070100012). */ public class SpecimenCollectionStatusRefVoCollection extends ims.vo.ValueObjectCollection implements ims.domain.IDomainCollectionGetter, ims.vo.ImsCloneable, Iterable<SpecimenCollectionStatusRefVo> { private static final long serialVersionUID = 1L; private ArrayList<SpecimenCollectionStatusRefVo> col = new ArrayList<SpecimenCollectionStatusRefVo>(); public final String getBoClassName() { return "ims.ocrr.orderingresults.domain.objects.SpecimenCollectionStatus"; } public ims.domain.IDomainGetter[] getIDomainGetterItems() { ims.domain.IDomainGetter[] result = new ims.domain.IDomainGetter[col.size()]; col.toArray(result); return result; } public boolean add(SpecimenCollectionStatusRefVo value) { if(value == null) return false; if(this.col.indexOf(value) < 0) { return this.col.add(value); } return false; } public boolean add(int index, SpecimenCollectionStatusRefVo value) { if(value == null) return false; if(this.col.indexOf(value) < 0) { this.col.add(index, value); return true; } return false; } public void clear() { this.col.clear(); } public void remove(int index) { this.col.remove(index); } public int size() { return this.col.size(); } public int indexOf(SpecimenCollectionStatusRefVo instance) { return col.indexOf(instance); } public SpecimenCollectionStatusRefVo get(int index) { return this.col.get(index); } public boolean set(int index, SpecimenCollectionStatusRefVo value) { if(value == null) return false; this.col.set(index, value); return true; } public void remove(SpecimenCollectionStatusRefVo instance) { if(instance != null) { int index = indexOf(instance); if(index >= 0) remove(index); } } public boolean contains(SpecimenCollectionStatusRefVo instance) { return indexOf(instance) >= 0; } public Object clone() { SpecimenCollectionStatusRefVoCollection clone = new SpecimenCollectionStatusRefVoCollection(); for(int x = 0; x < this.col.size(); x++) { if(this.col.get(x) != null) clone.col.add((SpecimenCollectionStatusRefVo)this.col.get(x).clone()); else clone.col.add(null); } return clone; } public boolean isValidated() { return true; } public String[] validate() { return null; } public SpecimenCollectionStatusRefVo[] toArray() { SpecimenCollectionStatusRefVo[] arr = new SpecimenCollectionStatusRefVo[col.size()]; col.toArray(arr); return arr; } public SpecimenCollectionStatusRefVoCollection sort() { return sort(SortOrder.ASCENDING); } public SpecimenCollectionStatusRefVoCollection sort(SortOrder order) { return sort(new SpecimenCollectionStatusRefVoComparator(order)); } @SuppressWarnings("unchecked") public SpecimenCollectionStatusRefVoCollection sort(Comparator comparator) { Collections.sort(this.col, comparator); return this; } public Iterator<SpecimenCollectionStatusRefVo> iterator() { return col.iterator(); } @Override protected ArrayList getTypedCollection() { return col; } private class SpecimenCollectionStatusRefVoComparator implements Comparator { private int direction = 1; public SpecimenCollectionStatusRefVoComparator() { this(SortOrder.ASCENDING); } public SpecimenCollectionStatusRefVoComparator(SortOrder order) { if (order == SortOrder.DESCENDING) { this.direction = -1; } } public int compare(Object obj1, Object obj2) { SpecimenCollectionStatusRefVo voObj1 = (SpecimenCollectionStatusRefVo)obj1; SpecimenCollectionStatusRefVo voObj2 = (SpecimenCollectionStatusRefVo)obj2; return direction*(voObj1.compareTo(voObj2)); } } }
agpl-3.0
migue/voltdb
tests/test_apps/exportbenchmark/src/exportbenchmark/NoOpExporter.java
2811
/* This file is part of VoltDB. * Copyright (C) 2008-2017 VoltDB Inc. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS 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. */ /* * This samples uses multiple threads to post synchronous requests to the * VoltDB server, simulating multiple client application posting * synchronous requests to the database, using the native VoltDB client * library. * * While synchronous processing can cause performance bottlenecks (each * caller waits for a transaction answer before calling another * transaction), the VoltDB cluster at large is still able to perform at * blazing speeds when many clients are connected to it. */ package exportbenchmark; import java.util.Properties; import org.voltdb.export.AdvertisedDataSource; import org.voltdb.exportclient.ExportClientBase; import org.voltdb.exportclient.ExportDecoderBase; public class NoOpExporter extends ExportClientBase { @Override public void configure(Properties config) throws Exception { // We have no properties to configure at this point } static class NoOpExportDecoder extends ExportDecoderBase { NoOpExportDecoder(AdvertisedDataSource source) { super(source); } @Override public void sourceNoLongerAdvertised(AdvertisedDataSource source) { // The AdvertiseDataSource is no longer available. If file descriptors // or threads were allocated to handle the source, free them here. } @Override public boolean processRow(int rowSize, byte[] rowData) throws RestartBlockException { // We don't want to do anything yet return true; } } @Override public ExportDecoderBase constructExportDecoder(AdvertisedDataSource source) { return new NoOpExportDecoder(source); } }
agpl-3.0
yiducn/airvis
src/main/java/org/duyi/airVis/StationInfo.java
940
package org.duyi.airVis; /** * Created by yidu on 9/21/15. */ public class StationInfo { String code = ""; String name = ""; String city = ""; double latitude; double longitude; public StationInfo(){ } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public double getLatitude() { return latitude; } public void setLatitude(double latitude) { this.latitude = latitude; } public double getLongitude() { return longitude; } public void setLongitude(double longitude) { this.longitude = longitude; } }
agpl-3.0
Tanaguru/Tanaguru
rules/accessiweb2.1/src/test/java/org/tanaguru/rules/accessiweb21/Aw21Rule08101Test.java
3475
/* * 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.accessiweb21; import org.tanaguru.entity.audit.TestSolution; import org.tanaguru.rules.accessiweb21.test.Aw21RuleImplementationTestCase; /** * Unit test class for the implementation of the rule 8.10.1 of the referential Accessiweb 2.1. * * @author jkowalczyk */ public class Aw21Rule08101Test extends Aw21RuleImplementationTestCase { /** * Default constructor */ public Aw21Rule08101Test (String testName){ super(testName); } @Override protected void setUpRuleImplementationClassName() { setRuleImplementationClassName( "org.tanaguru.rules.accessiweb21.Aw21Rule08101"); } @Override protected void setUpWebResourceMap() { // getWebResourceMap().put("Aw21.Test.8.10.1-1Passed-01", // getWebResourceFactory().createPage( // getTestcasesFilePath() + "AW21/Aw21Rule08101/Aw21.Test.8.10.1-1Passed-01.html")); // getWebResourceMap().put("Aw21.Test.8.10.1-2Failed-01", // getWebResourceFactory().createPage( // getTestcasesFilePath() + "AW21/Aw21Rule08101/Aw21.Test.8.10.1-2Failed-01.html")); getWebResourceMap().put("Aw21.Test.8.10.1-3NMI-01", getWebResourceFactory().createPage( getTestcasesFilePath() + "AW21/Aw21Rule08101/Aw21.Test.8.10.1-3NMI-01.html")); // getWebResourceMap().put("Aw21.Test.8.10.1-4NA-01", // getWebResourceFactory().createPage( // getTestcasesFilePath() + "AW21/Aw21Rule08101/Aw21.Test.8.10.1-4NA-01.html")); } @Override protected void setProcess() { // assertEquals(TestSolution.PASSED, // processPageTest("Aw21.Test.8.10.1-1Passed-01").getValue()); // assertEquals(TestSolution.FAILED, // processPageTest("Aw21.Test.8.10.1-2Failed-01").getValue()); assertEquals(TestSolution.NOT_TESTED, processPageTest("Aw21.Test.8.10.1-3NMI-01").getValue()); // assertEquals(TestSolution.NOT_APPLICABLE, // processPageTest("Aw21.Test.8.10.1-4NA-01").getValue()); } @Override protected void setConsolidate() { // assertEquals(TestSolution.PASSED, // consolidate("Aw21.Test.8.10.1-1Passed-01").getValue()); // assertEquals(TestSolution.FAILED, // consolidate("Aw21.Test.8.10.1-2Failed-01").getValue()); assertEquals(TestSolution.NOT_TESTED, consolidate("Aw21.Test.8.10.1-3NMI-01").getValue()); // assertEquals(TestSolution.NOT_APPLICABLE, // consolidate("Aw21.Test.8.10.1-4NA-01").getValue()); } }
agpl-3.0
aihua/opennms
opennms-services/src/test/java/org/opennms/netmgt/collectd/CollectdIntegrationTest.java
10864
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2007-2017 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2017 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 Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero 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.collectd; import static org.easymock.EasyMock.anyObject; import static org.easymock.EasyMock.eq; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import static org.opennms.core.utils.InetAddressUtils.addr; import static org.opennms.core.utils.InetAddressUtils.str; import java.io.File; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.easymock.EasyMock; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import org.opennms.core.utils.InsufficientInformationException; import org.opennms.netmgt.collection.support.DefaultServiceCollectorRegistry; import org.opennms.netmgt.collection.test.api.CollectorTestUtils; import org.opennms.netmgt.config.CollectdConfigFactory; import org.opennms.netmgt.config.PollOutagesConfigFactory; import org.opennms.netmgt.config.ThresholdingConfigFactory; import org.opennms.netmgt.config.collectd.CollectdConfiguration; import org.opennms.netmgt.config.collectd.Collector; import org.opennms.netmgt.config.collectd.Filter; import org.opennms.netmgt.config.collectd.Package; import org.opennms.netmgt.config.collectd.Parameter; import org.opennms.netmgt.config.collectd.Service; import org.opennms.netmgt.dao.api.IpInterfaceDao; import org.opennms.netmgt.dao.api.NodeDao; import org.opennms.netmgt.dao.mock.MockEventIpcManager; import org.opennms.netmgt.dao.mock.MockTransactionTemplate; import org.opennms.netmgt.events.api.EventConstants; import org.opennms.netmgt.events.api.EventIpcManager; import org.opennms.netmgt.events.api.EventIpcManagerFactory; import org.opennms.netmgt.filter.FilterDaoFactory; import org.opennms.netmgt.filter.api.FilterDao; import org.opennms.netmgt.mock.MockPersisterFactory; import org.opennms.netmgt.model.NetworkBuilder; import org.opennms.netmgt.model.NetworkBuilder.InterfaceBuilder; import org.opennms.netmgt.model.NetworkBuilder.NodeBuilder; import org.opennms.netmgt.model.OnmsIpInterface; import org.opennms.netmgt.model.OnmsMonitoredService; import org.opennms.netmgt.model.OnmsServiceType; import org.opennms.netmgt.model.events.EventBuilder; import org.opennms.test.mock.EasyMockUtils; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; /** * CollectdIntegrationTest * * @author brozow */ public class CollectdIntegrationTest { protected static final String TEST_KEY_PARM_NAME = "key"; private static Map<String, CollectdIntegrationTest> m_tests = new HashMap<String, CollectdIntegrationTest>(); private EventIpcManager m_eventIpcManager; private Collectd m_collectd; private EasyMockUtils m_mockUtils; private CollectdConfigFactory m_collectdConfigFactory; private CollectdConfiguration m_collectdConfiguration; private String m_key; private MockServiceCollector m_serviceCollector; private IpInterfaceDao m_ifaceDao; private NodeDao m_nodeDao; private FilterDao m_filterDao; @Rule public TestName m_testName = new TestName(); @Before public void setUp() throws Exception { m_eventIpcManager = new MockEventIpcManager(); EventIpcManagerFactory.setIpcManager(m_eventIpcManager); m_mockUtils = new EasyMockUtils(); m_filterDao = m_mockUtils.createMock(FilterDao.class); FilterDaoFactory.setInstance(m_filterDao); // This call will also ensure that the poll-outages.xml file can parse IPv4 // and IPv6 addresses. Resource resource = new ClassPathResource("etc/poll-outages.xml"); PollOutagesConfigFactory factory = new PollOutagesConfigFactory(resource); factory.afterPropertiesSet(); PollOutagesConfigFactory.setInstance(factory); File homeDir = resource.getFile().getParentFile().getParentFile(); System.setProperty("opennms.home", homeDir.getAbsolutePath()); resource = new ClassPathResource("/test-thresholds.xml"); ThresholdingConfigFactory.setInstance(new ThresholdingConfigFactory(resource.getInputStream())); // set up test using a string key m_key = m_testName.getMethodName()+System.nanoTime(); m_tests.put(m_key, this); //create a collector definition Collector collector = new Collector(); collector.setService("SNMP"); collector.setClassName(MockServiceCollector.class.getName()); // pass the key to the collector definition so it can look up the associated test Parameter param = new Parameter(); param.setKey(TEST_KEY_PARM_NAME); param.setValue(m_key); collector.addParameter(param); m_collectdConfigFactory = m_mockUtils.createMock(CollectdConfigFactory.class); m_collectdConfiguration = m_mockUtils.createMock(CollectdConfiguration.class); EasyMock.expect(m_collectdConfigFactory.getCollectdConfig()).andReturn(m_collectdConfiguration).anyTimes(); EasyMock.expect(m_collectdConfiguration.getCollectors()).andReturn(Collections.singletonList(collector)).anyTimes(); EasyMock.expect(m_collectdConfiguration.getThreads()).andReturn(1).anyTimes(); m_ifaceDao = m_mockUtils.createMock(IpInterfaceDao.class); m_nodeDao = m_mockUtils.createMock(NodeDao.class); m_collectd = new Collectd() { @Override protected void handleInsufficientInfo(InsufficientInformationException e) { fail("Invalid event received: "+e.getMessage()); } }; OnmsServiceType snmp = new OnmsServiceType("SNMP"); NetworkBuilder netBuilder = new NetworkBuilder(); NodeBuilder nodeBuilder = netBuilder.addNode("node1").setId(1); InterfaceBuilder ifaceBlder = netBuilder.addInterface("192.168.1.1") .setId(2) .setIsSnmpPrimary("P"); ifaceBlder.addSnmpInterface(1); OnmsMonitoredService svc = netBuilder.addService(snmp); List<OnmsIpInterface> initialIfs = Collections.emptyList(); EasyMock.expect(m_ifaceDao.findByServiceType(snmp.getName())).andReturn(initialIfs).anyTimes(); m_filterDao.flushActiveIpAddressListCache(); EasyMock.expect(m_nodeDao.load(1)).andReturn(nodeBuilder.getNode()).anyTimes(); createGetPackagesExpectation(svc); EasyMock.expect(m_ifaceDao.load(2)).andReturn(ifaceBlder.getInterface()).anyTimes(); m_mockUtils.replayAll(); final MockTransactionTemplate transTemplate = new MockTransactionTemplate(); transTemplate.afterPropertiesSet(); m_collectd.setCollectdConfigFactory(m_collectdConfigFactory); m_collectd.setEventIpcManager(m_eventIpcManager); m_collectd.setTransactionTemplate(transTemplate); m_collectd.setIpInterfaceDao(m_ifaceDao); m_collectd.setNodeDao(m_nodeDao); m_collectd.setFilterDao(m_filterDao); m_collectd.setPersisterFactory(new MockPersisterFactory()); m_collectd.setServiceCollectorRegistry(new DefaultServiceCollectorRegistry()); m_collectd.setLocationAwareCollectorClient(CollectorTestUtils.createLocationAwareCollectorClient()); // Inits the class m_collectd.afterPropertiesSet(); //assertNotNull(m_serviceCollector); } public static void setServiceCollectorInTest(String testKey, MockServiceCollector collector) { CollectdIntegrationTest test = m_tests.get(testKey); assertNotNull(test); test.setServiceCollector(collector); } private void setServiceCollector(MockServiceCollector collector) { m_serviceCollector = collector; } @After public void tearDown() { m_tests.remove(m_key); } @Test public void testIt() throws InterruptedException { m_collectd.start(); EventBuilder bldr = new EventBuilder(EventConstants.NODE_GAINED_SERVICE_EVENT_UEI, "Test"); bldr.setNodeid(1); bldr.setInterface(addr("192.168.1.1")); bldr.setService("SNMP"); m_collectd.onEvent(bldr.getEvent()); Thread.sleep(2000); assertNotNull(m_serviceCollector); assertEquals(1, m_serviceCollector.getCollectCount()); m_mockUtils.verifyAll(); } private void createGetPackagesExpectation(OnmsMonitoredService svc) { String rule = "ipaddr = '"+ str(svc.getIpAddress())+"'"; //EasyMock.expect(m_filterDao.getActiveIPAddressList(rule)).andReturn(Collections.singletonList(svc.getIpAddress())); final Package pkg = new Package(); pkg.setName("testPackage"); Filter filter = new Filter(); filter.setContent(rule); pkg.setFilter(filter); final Service collector = new Service(); collector.setName("SNMP"); collector.setStatus("on"); collector.setInterval(3000l); Parameter parm = new Parameter(); parm.setKey(TEST_KEY_PARM_NAME); parm.setValue(m_key); collector.setParameters(Collections.singletonList(parm)); pkg.addService(collector); EasyMock.expect(m_collectdConfiguration.getPackages()).andReturn(Collections.singletonList(pkg)); EasyMock.expect(m_collectdConfigFactory.interfaceInPackage(anyObject(OnmsIpInterface.class), eq(pkg))).andReturn(true); } }
agpl-3.0
IMS-MAXIMS/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/dto_move/vo/RadiotherapyMachineRefVo.java
5266
//############################################################################# //# # //# 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.dto_move.vo; /** * Linked to dto_move.RadiotherapyMachine business object (ID: 1105100003). */ public class RadiotherapyMachineRefVo extends ims.vo.ValueObjectRef implements ims.domain.IDomainGetter { private static final long serialVersionUID = 1L; public RadiotherapyMachineRefVo() { } public RadiotherapyMachineRefVo(Integer id, int version) { super(id, version); } public final boolean getID_RadiotherapyMachineIsNotNull() { return this.id != null; } public final Integer getID_RadiotherapyMachine() { return this.id; } public final void setID_RadiotherapyMachine(Integer value) { this.id = value; } public final int getVersion_RadiotherapyMachine() { return this.version; } public Object clone() { return new RadiotherapyMachineRefVo(this.id, this.version); } public final RadiotherapyMachineRefVo toRadiotherapyMachineRefVo() { if(this.id == null) return this; return new RadiotherapyMachineRefVo(this.id, this.version); } public boolean equals(Object obj) { if(!(obj instanceof RadiotherapyMachineRefVo)) return false; RadiotherapyMachineRefVo compareObj = (RadiotherapyMachineRefVo)obj; if(this.id != null && compareObj.getBoId() != null) return this.id.equals(compareObj.getBoId()); if(this.id != null && compareObj.getBoId() == null) return false; if(this.id == null && compareObj.getBoId() != null) return false; return super.equals(obj); } public int hashCode() { if(this.id != null) return this.id.intValue(); return super.hashCode(); } public boolean isValidated() { return true; } public String[] validate() { return null; } public String getBoClassName() { return "ims.dto_move.domain.objects.RadiotherapyMachine"; } public Class getDomainClass() { return ims.dto_move.domain.objects.RadiotherapyMachine.class; } public String getIItemText() { return toString(); } public String toString() { return this.getClass().toString() + " (ID: " + (this.id == null ? "null" : this.id.toString()) + ")"; } public int compareTo(Object obj) { if (obj == null) return -1; if (!(obj instanceof RadiotherapyMachineRefVo)) throw new ClassCastException("A RadiotherapyMachineRefVo object cannot be compared an Object of type " + obj.getClass().getName()); if (this.id == null) return 1; if (((RadiotherapyMachineRefVo)obj).getBoId() == null) return -1; return this.id.compareTo(((RadiotherapyMachineRefVo)obj).getBoId()); } // this method is not needed. It is here for compatibility purpose only. public int compareTo(Object obj, boolean caseInsensitive) { if(caseInsensitive); // this is to avoid Eclipse warning return compareTo(obj); } public Object getFieldValueByFieldName(String fieldName) { if(fieldName == null) throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name"); fieldName = fieldName.toUpperCase(); if(fieldName.equals("ID_RADIOTHERAPYMACHINE")) return getID_RadiotherapyMachine(); return super.getFieldValueByFieldName(fieldName); } }
agpl-3.0
erdincay/ejb
src/com/lp/server/finanz/service/ErgebnisgruppeDtoAssembler.java
3661
/******************************************************************************* * 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.finanz.service; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import com.lp.server.finanz.ejb.Ergebnisgruppe; public class ErgebnisgruppeDtoAssembler { public static ErgebnisgruppeDto createDto(Ergebnisgruppe ergebnisgruppe) { ErgebnisgruppeDto ergebnisgruppeDto = new ErgebnisgruppeDto(); if (ergebnisgruppe != null) { ergebnisgruppeDto.setIId(ergebnisgruppe.getIId()); ergebnisgruppeDto.setMandantCNr(ergebnisgruppe.getMandantCNr()); ergebnisgruppeDto.setCBez(ergebnisgruppe.getCBez()); ergebnisgruppeDto.setErgebnisgruppeIIdSumme(ergebnisgruppe .getErgebnisgruppeIIdSumme()); ergebnisgruppeDto.setIReihung(ergebnisgruppe.getIReihung()); ergebnisgruppeDto.setBSummeNegativ(ergebnisgruppe .getBSummenegativ()); ergebnisgruppeDto.setBInvertiert(ergebnisgruppe.getBInvertiert()); ergebnisgruppeDto.setTAnlegen(ergebnisgruppe.getTAnlegen()); ergebnisgruppeDto.setPersonalIIdAnlegen(ergebnisgruppe .getPersonalIIdAnlegen()); ergebnisgruppeDto.setTAendern(ergebnisgruppe.getTAendern()); ergebnisgruppeDto.setPersonalIIdAendern(ergebnisgruppe .getPersonalIIdAendern()); ergebnisgruppeDto.setBProzentbasis(ergebnisgruppe .getBProzentbasis()); ergebnisgruppeDto.setITyp(ergebnisgruppe.getITyp()); ergebnisgruppeDto.setBBilanzgruppe(ergebnisgruppe .getBBilanzgruppe()); } return ergebnisgruppeDto; } public static ErgebnisgruppeDto[] createDtos(Collection<?> ergebnisgruppes) { List<ErgebnisgruppeDto> list = new ArrayList<ErgebnisgruppeDto>(); if (ergebnisgruppes != null) { Iterator<?> iterator = ergebnisgruppes.iterator(); while (iterator.hasNext()) { list.add(createDto((Ergebnisgruppe) iterator.next())); } } ErgebnisgruppeDto[] returnArray = new ErgebnisgruppeDto[list.size()]; return (ErgebnisgruppeDto[]) list.toArray(returnArray); } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/core/configuration/vo/TCIRequestsBatchRefVo.java
5237
//############################################################################# //# # //# 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.configuration.vo; /** * Linked to core.configuration.TCIRequestsBatch business object (ID: 1028100086). */ public class TCIRequestsBatchRefVo extends ims.vo.ValueObjectRef implements ims.domain.IDomainGetter { private static final long serialVersionUID = 1L; public TCIRequestsBatchRefVo() { } public TCIRequestsBatchRefVo(Integer id, int version) { super(id, version); } public final boolean getID_TCIRequestsBatchIsNotNull() { return this.id != null; } public final Integer getID_TCIRequestsBatch() { return this.id; } public final void setID_TCIRequestsBatch(Integer value) { this.id = value; } public final int getVersion_TCIRequestsBatch() { return this.version; } public Object clone() { return new TCIRequestsBatchRefVo(this.id, this.version); } public final TCIRequestsBatchRefVo toTCIRequestsBatchRefVo() { if(this.id == null) return this; return new TCIRequestsBatchRefVo(this.id, this.version); } public boolean equals(Object obj) { if(!(obj instanceof TCIRequestsBatchRefVo)) return false; TCIRequestsBatchRefVo compareObj = (TCIRequestsBatchRefVo)obj; if(this.id != null && compareObj.getBoId() != null) return this.id.equals(compareObj.getBoId()); if(this.id != null && compareObj.getBoId() == null) return false; if(this.id == null && compareObj.getBoId() != null) return false; return super.equals(obj); } public int hashCode() { if(this.id != null) return this.id.intValue(); return super.hashCode(); } public boolean isValidated() { return true; } public String[] validate() { return null; } public String getBoClassName() { return "ims.core.configuration.domain.objects.TCIRequestsBatch"; } public Class getDomainClass() { return ims.core.configuration.domain.objects.TCIRequestsBatch.class; } public String getIItemText() { return toString(); } public String toString() { return this.getClass().toString() + " (ID: " + (this.id == null ? "null" : this.id.toString()) + ")"; } public int compareTo(Object obj) { if (obj == null) return -1; if (!(obj instanceof TCIRequestsBatchRefVo)) throw new ClassCastException("A TCIRequestsBatchRefVo object cannot be compared an Object of type " + obj.getClass().getName()); if (this.id == null) return 1; if (((TCIRequestsBatchRefVo)obj).getBoId() == null) return -1; return this.id.compareTo(((TCIRequestsBatchRefVo)obj).getBoId()); } // this method is not needed. It is here for compatibility purpose only. public int compareTo(Object obj, boolean caseInsensitive) { if(caseInsensitive); // this is to avoid Eclipse warning return compareTo(obj); } public Object getFieldValueByFieldName(String fieldName) { if(fieldName == null) throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name"); fieldName = fieldName.toUpperCase(); if(fieldName.equals("ID_TCIREQUESTSBATCH")) return getID_TCIRequestsBatch(); return super.getFieldValueByFieldName(fieldName); } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/COE/src/ims/coe/forms/assessinfectioncontrol/ConfigFlags.java
2743
//############################################################################# //# # //# 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 package ims.coe.forms.assessinfectioncontrol; import java.io.Serializable; public final class ConfigFlags extends ims.framework.FormConfigFlags implements Serializable { private static final long serialVersionUID = 1L; public final STALE_OBJECT_MESSAGEClass STALE_OBJECT_MESSAGE; public ConfigFlags(ims.framework.ConfigFlag configFlags) { super(configFlags); STALE_OBJECT_MESSAGE = new STALE_OBJECT_MESSAGEClass(configFlags); } public final class STALE_OBJECT_MESSAGEClass implements Serializable { private static final long serialVersionUID = 1L; private final ims.framework.ConfigFlag configFlags; public STALE_OBJECT_MESSAGEClass(ims.framework.ConfigFlag configFlags) { this.configFlags = configFlags; } public String getValue() { return (String)configFlags.get("STALE_OBJECT_MESSAGE"); } } }
agpl-3.0
erdincay/ejb
src/com/lp/server/personal/service/TaetigkeitartsprDtoAssembler.java
2931
/******************************************************************************* * 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.Taetigkeitartspr; public class TaetigkeitartsprDtoAssembler { public static TaetigkeitartsprDto createDto( Taetigkeitartspr taetigkeitartspr) { TaetigkeitartsprDto taetigkeitartsprDto = new TaetigkeitartsprDto(); if (taetigkeitartspr != null) { taetigkeitartsprDto.setLocaleCNr(taetigkeitartspr.getPk().getLocaleCNr()); taetigkeitartsprDto.setTaetigkeitartCNr(taetigkeitartspr .getPk().getTaetigkeitartCNr()); taetigkeitartsprDto.setCBez(taetigkeitartspr.getCBez()); } return taetigkeitartsprDto; } public static TaetigkeitartsprDto[] createDtos(Collection<?> taetigkeitartsprs) { List<TaetigkeitartsprDto> list = new ArrayList<TaetigkeitartsprDto>(); if (taetigkeitartsprs != null) { Iterator<?> iterator = taetigkeitartsprs.iterator(); while (iterator.hasNext()) { list.add(createDto((Taetigkeitartspr) iterator.next())); } } TaetigkeitartsprDto[] returnArray = new TaetigkeitartsprDto[list.size()]; return (TaetigkeitartsprDto[]) list.toArray(returnArray); } }
agpl-3.0
IMS-MAXIMS/openMAXIMS
Source Library/openmaxims_workspace/ClinicalAdmin/src/ims/clinicaladmin/forms/motorchartconfiguration/GlobalContext.java
3453
//############################################################################# //# # //# 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.clinicaladmin.forms.motorchartconfiguration; import java.io.Serializable; public final class GlobalContext extends ims.framework.FormContext implements Serializable { private static final long serialVersionUID = 1L; public GlobalContext(ims.framework.Context context) { super(context); ClinicalAdmin = new ClinicalAdminContext(context); } public final class ClinicalAdminContext implements Serializable { private static final long serialVersionUID = 1L; private ClinicalAdminContext(ims.framework.Context context) { this.context = context; } public boolean getMotorChartDetailsIsNotNull() { return !cx_ClinicalAdminMotorChartDetails.getValueIsNull(context); } public ims.core.vo.MotorChartAreaDetailVo getMotorChartDetails() { return (ims.core.vo.MotorChartAreaDetailVo)cx_ClinicalAdminMotorChartDetails.getValue(context); } public void setMotorChartDetails(ims.core.vo.MotorChartAreaDetailVo value) { cx_ClinicalAdminMotorChartDetails.setValue(context, value); } private ims.framework.ContextVariable cx_ClinicalAdminMotorChartDetails = new ims.framework.ContextVariable("ClinicalAdmin.MotorChartDetails", "_cv_ClinicalAdmin.MotorChartDetails"); private ims.framework.Context context; } public ClinicalAdminContext ClinicalAdmin; }
agpl-3.0
linearregression/scylla-jmx
src/main/java/com/yammer/metrics/core/APIMeter.java
1120
package com.yammer.metrics.core; /* * Copyright 2015 Cloudius Systems * * Modified by Cloudius Systems */ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import com.cloudius.urchin.api.APIClient; public class APIMeter extends Meter { String url; private APIClient c = new APIClient(); public APIMeter(String _url, ScheduledExecutorService tickThread, String eventType, TimeUnit rateUnit, Clock clock) { super(tickThread, eventType, rateUnit, clock); // TODO Auto-generated constructor stub url = _url; } public long get_value() { return c.getLongValue(url); } // Meter doesn't have a set value method. // to mimic it, we clear the old value and set it to a new one. // This is safe because the only this method would be used // to update the values public long set(long new_value) { long res = super.count(); mark(-res); mark(new_value); return res; } @Override void tick() { set(get_value()); super.tick(); } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/Core/src/ims/core/forms/webpaslaunchdialog/GlobalContext.java
3134
//############################################################################# //# # //# 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.forms.webpaslaunchdialog; import java.io.Serializable; public final class GlobalContext extends ims.framework.FormContext implements Serializable { private static final long serialVersionUID = 1L; public GlobalContext(ims.framework.Context context) { super(context); Core = new CoreContext(context); } public final class CoreContext implements Serializable { private static final long serialVersionUID = 1L; private CoreContext(ims.framework.Context context) { this.context = context; } public boolean getPatientShortIsNotNull() { return !cx_CorePatientShort.getValueIsNull(context); } public ims.core.vo.PatientShort getPatientShort() { return (ims.core.vo.PatientShort)cx_CorePatientShort.getValue(context); } private ims.framework.ContextVariable cx_CorePatientShort = new ims.framework.ContextVariable("Core.PatientShort", "_cvp_Core.PatientShort"); private ims.framework.Context context; } public CoreContext Core; }
agpl-3.0
open-health-hub/openmaxims-linux
openmaxims_workspace/ValueObjects/src/ims/emergency/vo/beans/EDPartialAdmissionVoBean.java
8306
//############################################################################# //# # //# 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.vo.beans; public class EDPartialAdmissionVoBean extends ims.vo.ValueObjectBean { public EDPartialAdmissionVoBean() { } public EDPartialAdmissionVoBean(ims.emergency.vo.EDPartialAdmissionVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.decisiontoadmitdatetime = vo.getDecisionToAdmitDateTime() == null ? null : (ims.framework.utils.beans.DateTimeBean)vo.getDecisionToAdmitDateTime().getBean(); this.specialty = vo.getSpecialty() == null ? null : (ims.vo.LookupInstanceBean)vo.getSpecialty().getBean(); this.allocateddatetime = vo.getAllocatedDateTime() == null ? null : (ims.framework.utils.beans.DateTimeBean)vo.getAllocatedDateTime().getBean(); this.allocatedbedtype = vo.getAllocatedBedType() == null ? null : (ims.vo.LookupInstanceBean)vo.getAllocatedBedType().getBean(); this.allocatedbednote = vo.getAllocatedBedNote(); this.allocatedward = vo.getAllocatedWard() == null ? null : (ims.core.vo.beans.LocationLiteVoBean)vo.getAllocatedWard().getBean(); this.allocatedstatus = vo.getAllocatedStatus() == null ? null : (ims.vo.LookupInstanceBean)vo.getAllocatedStatus().getBean(); this.admissiondatetime = vo.getAdmissionDateTime() == null ? null : (ims.framework.utils.beans.DateTimeBean)vo.getAdmissionDateTime().getBean(); this.admissionward = vo.getAdmissionWard() == null ? null : (ims.core.vo.beans.LocationLiteVoBean)vo.getAdmissionWard().getBean(); this.admittingconsultant = vo.getAdmittingConsultant() == null ? null : (ims.vo.LookupInstanceBean)vo.getAdmittingConsultant().getBean(); } public void populate(ims.vo.ValueObjectBeanMap map, ims.emergency.vo.EDPartialAdmissionVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.decisiontoadmitdatetime = vo.getDecisionToAdmitDateTime() == null ? null : (ims.framework.utils.beans.DateTimeBean)vo.getDecisionToAdmitDateTime().getBean(); this.specialty = vo.getSpecialty() == null ? null : (ims.vo.LookupInstanceBean)vo.getSpecialty().getBean(); this.allocateddatetime = vo.getAllocatedDateTime() == null ? null : (ims.framework.utils.beans.DateTimeBean)vo.getAllocatedDateTime().getBean(); this.allocatedbedtype = vo.getAllocatedBedType() == null ? null : (ims.vo.LookupInstanceBean)vo.getAllocatedBedType().getBean(); this.allocatedbednote = vo.getAllocatedBedNote(); this.allocatedward = vo.getAllocatedWard() == null ? null : (ims.core.vo.beans.LocationLiteVoBean)vo.getAllocatedWard().getBean(map); this.allocatedstatus = vo.getAllocatedStatus() == null ? null : (ims.vo.LookupInstanceBean)vo.getAllocatedStatus().getBean(); this.admissiondatetime = vo.getAdmissionDateTime() == null ? null : (ims.framework.utils.beans.DateTimeBean)vo.getAdmissionDateTime().getBean(); this.admissionward = vo.getAdmissionWard() == null ? null : (ims.core.vo.beans.LocationLiteVoBean)vo.getAdmissionWard().getBean(map); this.admittingconsultant = vo.getAdmittingConsultant() == null ? null : (ims.vo.LookupInstanceBean)vo.getAdmittingConsultant().getBean(); } public ims.emergency.vo.EDPartialAdmissionVo buildVo() { return this.buildVo(new ims.vo.ValueObjectBeanMap()); } public ims.emergency.vo.EDPartialAdmissionVo buildVo(ims.vo.ValueObjectBeanMap map) { ims.emergency.vo.EDPartialAdmissionVo vo = null; if(map != null) vo = (ims.emergency.vo.EDPartialAdmissionVo)map.getValueObject(this); if(vo == null) { vo = new ims.emergency.vo.EDPartialAdmissionVo(); map.addValueObject(this, vo); vo.populate(map, this); } return vo; } public Integer getId() { return this.id; } public void setId(Integer value) { this.id = value; } public int getVersion() { return this.version; } public void setVersion(int value) { this.version = value; } public ims.framework.utils.beans.DateTimeBean getDecisionToAdmitDateTime() { return this.decisiontoadmitdatetime; } public void setDecisionToAdmitDateTime(ims.framework.utils.beans.DateTimeBean value) { this.decisiontoadmitdatetime = value; } public ims.vo.LookupInstanceBean getSpecialty() { return this.specialty; } public void setSpecialty(ims.vo.LookupInstanceBean value) { this.specialty = value; } public ims.framework.utils.beans.DateTimeBean getAllocatedDateTime() { return this.allocateddatetime; } public void setAllocatedDateTime(ims.framework.utils.beans.DateTimeBean value) { this.allocateddatetime = value; } public ims.vo.LookupInstanceBean getAllocatedBedType() { return this.allocatedbedtype; } public void setAllocatedBedType(ims.vo.LookupInstanceBean value) { this.allocatedbedtype = value; } public String getAllocatedBedNote() { return this.allocatedbednote; } public void setAllocatedBedNote(String value) { this.allocatedbednote = value; } public ims.core.vo.beans.LocationLiteVoBean getAllocatedWard() { return this.allocatedward; } public void setAllocatedWard(ims.core.vo.beans.LocationLiteVoBean value) { this.allocatedward = value; } public ims.vo.LookupInstanceBean getAllocatedStatus() { return this.allocatedstatus; } public void setAllocatedStatus(ims.vo.LookupInstanceBean value) { this.allocatedstatus = value; } public ims.framework.utils.beans.DateTimeBean getAdmissionDateTime() { return this.admissiondatetime; } public void setAdmissionDateTime(ims.framework.utils.beans.DateTimeBean value) { this.admissiondatetime = value; } public ims.core.vo.beans.LocationLiteVoBean getAdmissionWard() { return this.admissionward; } public void setAdmissionWard(ims.core.vo.beans.LocationLiteVoBean value) { this.admissionward = value; } public ims.vo.LookupInstanceBean getAdmittingConsultant() { return this.admittingconsultant; } public void setAdmittingConsultant(ims.vo.LookupInstanceBean value) { this.admittingconsultant = value; } private Integer id; private int version; private ims.framework.utils.beans.DateTimeBean decisiontoadmitdatetime; private ims.vo.LookupInstanceBean specialty; private ims.framework.utils.beans.DateTimeBean allocateddatetime; private ims.vo.LookupInstanceBean allocatedbedtype; private String allocatedbednote; private ims.core.vo.beans.LocationLiteVoBean allocatedward; private ims.vo.LookupInstanceBean allocatedstatus; private ims.framework.utils.beans.DateTimeBean admissiondatetime; private ims.core.vo.beans.LocationLiteVoBean admissionward; private ims.vo.LookupInstanceBean admittingconsultant; }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/pathways/vo/PatientJourneyEventInterfaceVoCollection.java
9530
//############################################################################# //# # //# 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.pathways.vo; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import ims.framework.enumerations.SortOrder; /** * Linked to Pathways.PatientEvent business object (ID: 1088100002). */ public class PatientJourneyEventInterfaceVoCollection extends ims.vo.ValueObjectCollection implements ims.vo.ImsCloneable, Iterable<PatientJourneyEventInterfaceVo> { private static final long serialVersionUID = 1L; private ArrayList<PatientJourneyEventInterfaceVo> col = new ArrayList<PatientJourneyEventInterfaceVo>(); public String getBoClassName() { return "ims.pathways.domain.objects.PatientEvent"; } public boolean add(PatientJourneyEventInterfaceVo value) { if(value == null) return false; if(this.col.indexOf(value) < 0) { return this.col.add(value); } return false; } public boolean add(int index, PatientJourneyEventInterfaceVo value) { if(value == null) return false; if(this.col.indexOf(value) < 0) { this.col.add(index, value); return true; } return false; } public void clear() { this.col.clear(); } public void remove(int index) { this.col.remove(index); } public int size() { return this.col.size(); } public int indexOf(PatientJourneyEventInterfaceVo instance) { return col.indexOf(instance); } public PatientJourneyEventInterfaceVo get(int index) { return this.col.get(index); } public boolean set(int index, PatientJourneyEventInterfaceVo value) { if(value == null) return false; this.col.set(index, value); return true; } public void remove(PatientJourneyEventInterfaceVo instance) { if(instance != null) { int index = indexOf(instance); if(index >= 0) remove(index); } } public boolean contains(PatientJourneyEventInterfaceVo instance) { return indexOf(instance) >= 0; } public Object clone() { PatientJourneyEventInterfaceVoCollection clone = new PatientJourneyEventInterfaceVoCollection(); for(int x = 0; x < this.col.size(); x++) { if(this.col.get(x) != null) clone.col.add((PatientJourneyEventInterfaceVo)this.col.get(x).clone()); else clone.col.add(null); } return clone; } public boolean isValidated() { for(int x = 0; x < col.size(); x++) if(!this.col.get(x).isValidated()) return false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(col.size() == 0) return null; java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>(); if(existingErrors != null) { for(int x = 0; x < existingErrors.length; x++) { listOfErrors.add(existingErrors[x]); } } for(int x = 0; x < col.size(); x++) { String[] listOfOtherErrors = this.col.get(x).validate(); if(listOfOtherErrors != null) { for(int y = 0; y < listOfOtherErrors.length; y++) { listOfErrors.add(listOfOtherErrors[y]); } } } int errorCount = listOfErrors.size(); if(errorCount == 0) return null; String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); return result; } public PatientJourneyEventInterfaceVoCollection sort() { return sort(SortOrder.ASCENDING); } public PatientJourneyEventInterfaceVoCollection sort(boolean caseInsensitive) { return sort(SortOrder.ASCENDING, caseInsensitive); } public PatientJourneyEventInterfaceVoCollection sort(SortOrder order) { return sort(new PatientJourneyEventInterfaceVoComparator(order)); } public PatientJourneyEventInterfaceVoCollection sort(SortOrder order, boolean caseInsensitive) { return sort(new PatientJourneyEventInterfaceVoComparator(order, caseInsensitive)); } @SuppressWarnings("unchecked") public PatientJourneyEventInterfaceVoCollection sort(Comparator comparator) { Collections.sort(col, comparator); return this; } public ims.pathways.vo.PatientEventRefVoCollection toRefVoCollection() { ims.pathways.vo.PatientEventRefVoCollection result = new ims.pathways.vo.PatientEventRefVoCollection(); for(int x = 0; x < this.col.size(); x++) { result.add(this.col.get(x)); } return result; } public PatientJourneyEventInterfaceVo[] toArray() { PatientJourneyEventInterfaceVo[] arr = new PatientJourneyEventInterfaceVo[col.size()]; col.toArray(arr); return arr; } public ims.vo.interfaces.IPatientJourneyEvent[] toIPatientJourneyEventArray() { ims.vo.interfaces.IPatientJourneyEvent[] arr = new ims.vo.interfaces.IPatientJourneyEvent[col.size()]; col.toArray(arr); return arr; } public Iterator<PatientJourneyEventInterfaceVo> iterator() { return col.iterator(); } @Override protected ArrayList getTypedCollection() { return col; } private class PatientJourneyEventInterfaceVoComparator implements Comparator { private int direction = 1; private boolean caseInsensitive = true; public PatientJourneyEventInterfaceVoComparator() { this(SortOrder.ASCENDING); } public PatientJourneyEventInterfaceVoComparator(SortOrder order) { if (order == SortOrder.DESCENDING) { direction = -1; } } public PatientJourneyEventInterfaceVoComparator(SortOrder order, boolean caseInsensitive) { if (order == SortOrder.DESCENDING) { direction = -1; } this.caseInsensitive = caseInsensitive; } public int compare(Object obj1, Object obj2) { PatientJourneyEventInterfaceVo voObj1 = (PatientJourneyEventInterfaceVo)obj1; PatientJourneyEventInterfaceVo voObj2 = (PatientJourneyEventInterfaceVo)obj2; return direction*(voObj1.compareTo(voObj2, this.caseInsensitive)); } public boolean equals(Object obj) { return false; } } public ims.pathways.vo.beans.PatientJourneyEventInterfaceVoBean[] getBeanCollection() { return getBeanCollectionArray(); } public ims.pathways.vo.beans.PatientJourneyEventInterfaceVoBean[] getBeanCollectionArray() { ims.pathways.vo.beans.PatientJourneyEventInterfaceVoBean[] result = new ims.pathways.vo.beans.PatientJourneyEventInterfaceVoBean[col.size()]; for(int i = 0; i < col.size(); i++) { PatientJourneyEventInterfaceVo vo = ((PatientJourneyEventInterfaceVo)col.get(i)); result[i] = (ims.pathways.vo.beans.PatientJourneyEventInterfaceVoBean)vo.getBean(); } return result; } public static PatientJourneyEventInterfaceVoCollection buildFromBeanCollection(java.util.Collection beans) { PatientJourneyEventInterfaceVoCollection coll = new PatientJourneyEventInterfaceVoCollection(); if(beans == null) return coll; java.util.Iterator iter = beans.iterator(); while (iter.hasNext()) { coll.add(((ims.pathways.vo.beans.PatientJourneyEventInterfaceVoBean)iter.next()).buildVo()); } return coll; } public static PatientJourneyEventInterfaceVoCollection buildFromBeanCollection(ims.pathways.vo.beans.PatientJourneyEventInterfaceVoBean[] beans) { PatientJourneyEventInterfaceVoCollection coll = new PatientJourneyEventInterfaceVoCollection(); if(beans == null) return coll; for(int x = 0; x < beans.length; x++) { coll.add(beans[x].buildVo()); } return coll; } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/DomainObjects/src/ims/oncology/configuration/domain/objects/TumourSerumMarker.java
15690
//############################################################################# //# # //# 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 TumourSerumMarker extends ims.domain.DomainObject implements ims.domain.SystemInformationRetainer, java.io.Serializable { public static final int CLASSID = 1075100005; private static final long serialVersionUID = 1075100005L; public static final String CLASSVERSION = "${ClassVersion}"; @Override public boolean shouldCapQuery() { return true; } /** SerumMarkerValue */ private String serumMarkerValue; /** SerumMarkerDescription */ private String serumMarkerDescription; /** 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 TumourSerumMarker (Integer id, int ver) { super(id, ver); } public TumourSerumMarker () { super(); } public TumourSerumMarker (Integer id, int ver, Boolean includeRecord) { super(id, ver, includeRecord); } public Class getRealDomainClass() { return ims.oncology.configuration.domain.objects.TumourSerumMarker.class; } public String getSerumMarkerValue() { return serumMarkerValue; } public void setSerumMarkerValue(String serumMarkerValue) { if ( null != serumMarkerValue && serumMarkerValue.length() > 10 ) { throw new ims.domain.exceptions.DomainRuntimeException("MaxLength ($MaxLength) exceeded for serumMarkerValue. Tried to set value: "+ serumMarkerValue); } this.serumMarkerValue = serumMarkerValue; } public String getSerumMarkerDescription() { return serumMarkerDescription; } public void setSerumMarkerDescription(String serumMarkerDescription) { if ( null != serumMarkerDescription && serumMarkerDescription.length() > 150 ) { throw new ims.domain.exceptions.DomainRuntimeException("MaxLength ($MaxLength) exceeded for serumMarkerDescription. Tried to set value: "+ serumMarkerDescription); } this.serumMarkerDescription = serumMarkerDescription; } 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*serumMarkerValue* :"); auditStr.append(serumMarkerValue); auditStr.append("; "); auditStr.append("\r\n*serumMarkerDescription* :"); auditStr.append(serumMarkerDescription); auditStr.append("; "); auditStr.append("\r\n*taxonomyMap* :"); if (taxonomyMap != null) { int i3=0; for (i3=0; i3<taxonomyMap.size(); i3++) { if (i3 > 0) auditStr.append(","); ims.core.clinical.domain.objects.TaxonomyMap obj = (ims.core.clinical.domain.objects.TaxonomyMap)taxonomyMap.get(i3); if (obj != null) { if (i3 == 0) { auditStr.append(toShortClassName(obj)); auditStr.append("["); } auditStr.append(obj.toString()); } } if (i3 > 0) auditStr.append("] " + i3); } 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 = "TumourSerumMarker"; 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.getSerumMarkerValue() != null) { sb.append("<serumMarkerValue>"); sb.append(ims.framework.utils.StringUtils.encodeXML(this.getSerumMarkerValue().toString())); sb.append("</serumMarkerValue>"); } if (this.getSerumMarkerDescription() != null) { sb.append("<serumMarkerDescription>"); sb.append(ims.framework.utils.StringUtils.encodeXML(this.getSerumMarkerDescription().toString())); sb.append("</serumMarkerDescription>"); } 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); TumourSerumMarker domainObject = getTumourSerumMarkerfromXML(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); TumourSerumMarker domainObject = getTumourSerumMarkerfromXML(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 TumourSerumMarker getTumourSerumMarkerfromXML(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 getTumourSerumMarkerfromXML(doc.getRootElement(), factory, domMap); } public static TumourSerumMarker getTumourSerumMarkerfromXML(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 (!TumourSerumMarker.class.getName().equals(className)) { Class clz = Class.forName(className); if (!TumourSerumMarker.class.isAssignableFrom(clz)) throw new Exception("Element of type = " + className + " cannot be imported using the TumourSerumMarker 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 (TumourSerumMarker)m.invoke(null, new Object[]{el, factory, domMap}); } String impVersion = el.attributeValue("classVersion"); if(!impVersion.equals(TumourSerumMarker.CLASSVERSION)) { throw new Exception("Incompatible class structure found. Cannot import instance."); } TumourSerumMarker ret = null; int extId = Integer.parseInt(el.attributeValue("id")); String externalSource = el.attributeValue("source"); ret = (TumourSerumMarker)factory.getImportedDomainObject(TumourSerumMarker.class, externalSource, extId); if (ret == null) { ret = new TumourSerumMarker(); } String keyClassName = "TumourSerumMarker"; ims.configuration.ImportedObject impObj = (ims.configuration.ImportedObject)domMap.get(keyClassName + "_" + externalSource + "_" + extId); if (impObj != null) { return (TumourSerumMarker)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, TumourSerumMarker obj, java.util.HashMap domMap) throws Exception { org.dom4j.Element fldEl; fldEl = el.element("serumMarkerValue"); if(fldEl != null) { obj.setSerumMarkerValue(new String(fldEl.getTextTrim())); } fldEl = el.element("serumMarkerDescription"); if(fldEl != null) { obj.setSerumMarkerDescription(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 SerumMarkerValue = "serumMarkerValue"; public static final String SerumMarkerDescription = "serumMarkerDescription"; public static final String TaxonomyMap = "taxonomyMap"; public static final String IsActive = "isActive"; } }
agpl-3.0
ozwillo/ozwillo-portal
src/main/java/org/oasis_eu/portal/model/Languages.java
1479
package org.oasis_eu.portal.model; import java.util.Locale; /** * User: schambon * Date: 6/11/14 */ public enum Languages { ENGLISH("English", OasisLocales.ENGLISH), FRENCH("Français", OasisLocales.FRENCH), ITALIAN("Italiano", OasisLocales.ITALIAN), SPANISH("Español", OasisLocales.SPANISH), CATALAN("Català", OasisLocales.CATALAN), BULGARIAN("български", OasisLocales.BULGARIAN), TURKISH("Türkçe", OasisLocales.TURKISH); private String name; private OasisLocales locale; Languages(String name, OasisLocales locale) { this.name = name; this.locale = locale; } public String getName() { return name; } public String getLanguage() { return locale.getLocale().getLanguage(); } public Locale getLocale() { return locale.getLocale(); } public static Languages getByLocale(Locale locale) { return getByLocale(locale, null); } public static Languages getByLocale(Locale locale, Languages defaultLang) { for (Languages l : values()) { if (l.getLanguage().equals(locale.getLanguage())) { return l; } } return defaultLang; } public static Languages getByLanguageTag(String languageTag) { for (Languages l : values()) { if (l.getLanguage().equals(languageTag)) { return l; } } return null; } }
agpl-3.0
deerwalk/voltdb
src/frontend/org/voltdb/snmp/FaultFacility.java
1354
/* This file is part of VoltDB. * Copyright (C) 2008-2017 VoltDB Inc. * * 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 VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb.snmp; import static com.google_voltpatches.common.base.Preconditions.checkArgument; import java.util.List; import com.google_voltpatches.common.collect.ImmutableList; public enum FaultFacility { __unsmnp__, // ordinal 0 doesn't map to SNMP enumerations HOST, MEMORY, DISK, INITIATOR, CLUSTER, DR; static final List<FaultFacility> values = ImmutableList.copyOf(values()); public final static FaultFacility valueOf(int ordinal) { checkArgument(ordinal > __unsmnp__.ordinal() && ordinal < values.size()); return values.get(ordinal); } }
agpl-3.0
aborg0/RapidMiner-Unuk
src/com/rapidminer/operator/generator/SinusFrequencyFunction.java
1546
/* * 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.generator; /** * The label is 10 * sin(3 * att1) + 12 * sin(7 * att1) + 11 * sin(5 * att2) + * 9 * sin(10 * att2) + 10 * sin(8 * (att1 + att2)). * * @author Ingo Mierswa */ public class SinusFrequencyFunction extends RegressionFunction { public double calculate(double[] att) throws FunctionException { if (att.length < 2) throw new FunctionException("Sinus frequency function", "needs at least 2 attributes!"); return 10 * Math.sin(3 * att[0]) + 12 * Math.sin(7 * att[0]) + 11 * Math.sin(5 * att[1]) + 9 * Math.sin(10 * att[1]) + 10 * Math.sin(8 * (att[0] + att[1])); } @Override public int getMinNumberOfAttributes() { return 2; } }
agpl-3.0
ggiudetti/opencms-core
src/org/opencms/importexport/CmsImportExportManager.java
43884
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software GmbH & Co. KG, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.importexport; import org.opencms.configuration.CmsConfigurationException; import org.opencms.db.CmsUserExportSettings; import org.opencms.file.CmsObject; import org.opencms.i18n.CmsMessageContainer; import org.opencms.main.CmsEvent; import org.opencms.main.CmsException; import org.opencms.main.CmsLog; import org.opencms.main.I_CmsEventListener; import org.opencms.main.OpenCms; import org.opencms.report.I_CmsReport; import org.opencms.security.CmsRole; import org.opencms.security.CmsRoleViolationException; import org.opencms.security.I_CmsPrincipal; import org.opencms.xml.CmsXmlException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.dom4j.Document; import org.dom4j.io.SAXReader; /** * Provides information about how to handle imported resources.<p> * * @since 6.0.0 * * @see OpenCms#getImportExportManager() */ public class CmsImportExportManager { /** Time modes to specify how time stamps should be handled. */ public static enum TimestampMode { /** Use the time of import for the timestamp. */ IMPORTTIME, /** Use the timestamp of the imported file. */ FILETIME, /** The timestamp is explicitly given. */ VFSTIME; /** Returns the default timestamp mode. * @return the default timestamp mode */ public static TimestampMode getDefaultTimeStampMode() { return VFSTIME; } /** More robust version of {@link java.lang.Enum#valueOf(java.lang.Class, String)} that is case insensitive * and defaults for all "unreadable" arguments to the default timestamp mode. * @param value the TimeMode value as String * @return <code>value</code> as TimeMode object, or the default time mode, if <code>value</code> can't be converted to a TimeMode object. */ public static TimestampMode getEnum(String value) { if (null == value) { return getDefaultTimeStampMode(); } else { try { return TimestampMode.valueOf(value.toUpperCase()); } catch (@SuppressWarnings("unused") IllegalArgumentException e) { return getDefaultTimeStampMode(); } } } } /** Tag in the {@link #EXPORT_MANIFEST} for the "userinfo/entry@name" attribute, contains the additional user info entry name. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String A_NAME = A_CmsImport.A_NAME; /** Tag in the {@link #EXPORT_MANIFEST} for the "userinfo/entry@type" attribute, contains the additional user info entry data type name. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String A_TYPE = A_CmsImport.A_TYPE; /** The name of the XML manifest file used for the description of exported OpenCms VFS properties and attributes. */ public static final String EXPORT_MANIFEST = "manifest.xml"; /** The current version of the OpenCms export (appears in the {@link #EXPORT_MANIFEST} header). */ public static final String EXPORT_VERSION = "" + CmsImportVersion10.IMPORT_VERSION10; /** * The name of the XML manifest file used for the description of exported OpenCms VFS properties and attributes.<p> * * @deprecated use {@link #EXPORT_MANIFEST} instead */ @Deprecated public static final String EXPORT_XMLFILENAME = EXPORT_MANIFEST; /** Tag in the {@link #EXPORT_MANIFEST} for the "access" node. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_ACCESS = A_CmsImport.N_ACCESS; /** Tag in the {@link #EXPORT_MANIFEST} for the "allowed" node, to identify allowed user permissions. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_ACCESSCONTROL_ALLOWEDPERMISSIONS = A_CmsImport.N_ACCESSCONTROL_ALLOWEDPERMISSIONS; /** Tag in the {@link #EXPORT_MANIFEST} for the "denied" node, to identify denied user permissions. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_ACCESSCONTROL_DENIEDPERMISSIONS = A_CmsImport.N_ACCESSCONTROL_DENIEDPERMISSIONS; /** Tag in the {@link #EXPORT_MANIFEST} for the "accesscontrol" node, to identify access control entries. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_ACCESSCONTROL_ENTRIES = A_CmsImport.N_ACCESSCONTROL_ENTRIES; /** Tag in the {@link #EXPORT_MANIFEST} for the "accessentry" node, to identify a single access control entry. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_ACCESSCONTROL_ENTRY = A_CmsImport.N_ACCESSCONTROL_ENTRY; /** Tag in the {@link #EXPORT_MANIFEST} for the "permissionset" node, to identify a permission set. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_ACCESSCONTROL_PERMISSIONSET = A_CmsImport.N_ACCESSCONTROL_PERMISSIONSET; /** Tag in the {@link #EXPORT_MANIFEST} for the "uuidprincipal" node, to identify a principal UUID. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_ACCESSCONTROL_PRINCIPAL = A_CmsImport.N_ACCESSCONTROL_PRINCIPAL; /** Tag for the "creator" node (appears in the {@link #EXPORT_MANIFEST} header). */ public static final String N_CREATOR = "creator"; /** Tag for the "createdate" node (appears in the {@link #EXPORT_MANIFEST} header). */ public static final String N_DATE = "createdate"; /** Tag in the {@link #EXPORT_MANIFEST} for the "datecreated" node, contains the date created VFS file attribute. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_DATECREATED = A_CmsImport.N_DATECREATED; /** Tag in the {@link #EXPORT_MANIFEST} for the "dateexpired" node, contains the expiration date VFS file attribute. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_DATEEXPIRED = A_CmsImport.N_DATEEXPIRED; /** Tag in the {@link #EXPORT_MANIFEST} for the "datelastmodified" node, contains the date last modified VFS file attribute. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_DATELASTMODIFIED = A_CmsImport.N_DATELASTMODIFIED; /** Tag in the {@link #EXPORT_MANIFEST} for the "datereleased" node, contains the release date VFS file attribute. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_DATERELEASED = A_CmsImport.N_DATERELEASED; /** Tag in the {@link #EXPORT_MANIFEST} for the "defaultgroup" node, for backward compatibility with OpenCms 5.x. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_DEFAULTGROUP = A_CmsImport.N_DEFAULTGROUP; /** Tag in the {@link #EXPORT_MANIFEST} for the "description" node, contains a users description test. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_DESCRIPTION = A_CmsImport.N_DESCRIPTION; /** Tag in the {@link #EXPORT_MANIFEST} for the "destination" node, contains target VFS file name. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_DESTINATION = A_CmsImport.N_DESTINATION; /** Tag in the {@link #EXPORT_MANIFEST} for the "email" node, contains a users email. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_EMAIL = A_CmsImport.N_EMAIL; /** Tag in the {@link #EXPORT_MANIFEST} for the "export" node. */ public static final String N_EXPORT = "export"; /** Tag in the {@link #EXPORT_MANIFEST} for the "file" node, container node for all VFS resources. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_FILE = A_CmsImport.N_FILE; /** Tag in the {@link #EXPORT_MANIFEST} for the "firstname" node, contains a users first name. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_FIRSTNAME = A_CmsImport.N_FIRSTNAME; /** Tag in the {@link #EXPORT_MANIFEST} for the "flags" node, contains the flags of a VFS resource. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_FLAGS = A_CmsImport.N_FLAGS; /** Tag in the {@link #EXPORT_MANIFEST} for the "groupdata" node, contains a users group data. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_GROUPDATA = A_CmsImport.N_GROUPDATA; /** Tag in the {@link #EXPORT_MANIFEST} for the "groupname" node, contains a groups name. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_GROUPNAME = A_CmsImport.N_GROUPNAME; /** Tag in the {@link #EXPORT_MANIFEST} for the "id" node, only required for backward compatibility with import version 2. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_ID = A_CmsImport.N_ID; /** Tag in the {@link #EXPORT_MANIFEST}, starts the manifest info header. */ public static final String N_INFO = "info"; /** Tag in the {@link #EXPORT_MANIFEST} for the "lastmodified" node, only required for backward compatibility with import version 2. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_LASTMODIFIED = A_CmsImport.N_LASTMODIFIED; /** Tag in the {@link #EXPORT_MANIFEST} for the "lastname" node, contains a users last name. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_LASTNAME = A_CmsImport.N_LASTNAME; /** Tag in the {@link #EXPORT_MANIFEST} for the "name" node, contains a users login name. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_NAME = A_CmsImport.N_NAME; /** Tag in the {@link #EXPORT_MANIFEST} for the "opencms_version" node, appears in the manifest info header. */ public static final String N_OC_VERSION = "opencms_version"; /** Tag in the {@link #EXPORT_MANIFEST} for the "parentgroup" node, contains a groups parent group name. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_PARENTGROUP = A_CmsImport.N_PARENTGROUP; /** Tag in the {@link #EXPORT_MANIFEST} for the "password" node, contains a users encrypted password. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_PASSWORD = A_CmsImport.N_PASSWORD; /** Tag in the {@link #EXPORT_MANIFEST} for the "infoproject" node, appears in the manifest info header. */ public static final String N_INFO_PROJECT = "infoproject"; /** Tag in the {@link #EXPORT_MANIFEST} for the "properties" node, starts the list of properties of a VFS resource. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_PROPERTIES = A_CmsImport.N_PROPERTIES; /** Tag in the {@link #EXPORT_MANIFEST} for the "property" node, starts a property for a VFS resource. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_PROPERTY = A_CmsImport.N_PROPERTY; /** Tag in the {@link #EXPORT_MANIFEST} for the "type" property attribute, contains a property type. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_PROPERTY_ATTRIB_TYPE = A_CmsImport.N_PROPERTY_ATTRIB_TYPE; /** Tag in the {@link #EXPORT_MANIFEST} for the "shared" property type attribute value. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_PROPERTY_ATTRIB_TYPE_SHARED = A_CmsImport.N_PROPERTY_ATTRIB_TYPE_SHARED; /** Tag in the {@link #EXPORT_MANIFEST} for the "relation" node, starts a relation for a VFS resource. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_RELATION = A_CmsImport.N_RELATION; /** Tag in the {@link #EXPORT_MANIFEST} for the "id" relation attribute, contains the structure id of the target resource of the relation. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_RELATION_ATTRIBUTE_ID = A_CmsImport.N_RELATION_ATTRIBUTE_ID; /** Tag in the {@link #EXPORT_MANIFEST} for the "path" relation attribute, contains the path to the target resource of the relation. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_RELATION_ATTRIBUTE_PATH = A_CmsImport.N_RELATION_ATTRIBUTE_PATH; /** Tag in the {@link #EXPORT_MANIFEST} for the "type" relation attribute, contains the type of relation. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_RELATION_ATTRIBUTE_TYPE = A_CmsImport.N_RELATION_ATTRIBUTE_TYPE; /** Tag in the {@link #EXPORT_MANIFEST} for the "relations" node, starts the list of relations of a VFS resources. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_RELATIONS = A_CmsImport.N_RELATIONS; /** Tag in the {@link #EXPORT_MANIFEST} for the "source" node, contains the source path of a VFS resource in the import zip (or folder). * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_SOURCE = A_CmsImport.N_SOURCE; /** Tag in the {@link #EXPORT_MANIFEST} for the "address" node, contains a users address. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_TAG_ADDRESS = A_CmsImport.N_TAG_ADDRESS; /** Tag in the {@link #EXPORT_MANIFEST} for the "type" node, the resource type name of a VFS resource. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_TYPE = A_CmsImport.N_TYPE; /** Tag in the {@link #EXPORT_MANIFEST} for the "user" node, starts the user data. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_USER = A_CmsImport.N_USER; /** Tag in the {@link #EXPORT_MANIFEST} for the "usercreated" node, contains the name of the user who created the VFS resource. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_USERCREATED = A_CmsImport.N_USERCREATED; /** Tag in the {@link #EXPORT_MANIFEST} for the "userdata" node, starts the list of users. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_USERDATA = A_CmsImport.N_USERDATA; /** Tag in the {@link #EXPORT_MANIFEST} for the "usergroupdatas" node, starts the users group data. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_USERGROUPDATA = A_CmsImport.N_USERGROUPDATA; /** Tag in the {@link #EXPORT_MANIFEST} for the "orgunitdatas" node, starts the organizational unit data. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_ORGUNITDATA = A_CmsImport.N_ORGUNITDATA; /** Tag in the {@link #EXPORT_MANIFEST} for the "usergroups" node, starts the users group data. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_USERGROUPS = A_CmsImport.N_USERGROUPS; /** Tag in the {@link #EXPORT_MANIFEST} for the "userinfo" node, contains the additional user info. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_USERINFO = A_CmsImport.N_USERINFO; /** Tag in the {@link #EXPORT_MANIFEST} for the "userinfo/entry" node, contains the additional user info entry value. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_USERINFO_ENTRY = A_CmsImport.N_USERINFO_ENTRY; /** Tag in the {@link #EXPORT_MANIFEST} for the "userlastmodified" node, contains the name of the user who last modified the VFS resource. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_USERLASTMODIFIED = A_CmsImport.N_USERLASTMODIFIED; /** Tag in the {@link #EXPORT_MANIFEST} for the "uuidresource" node, contains a the resource UUID of a VFS resource. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_UUIDRESOURCE = A_CmsImport.N_UUIDRESOURCE; /** Tag in the {@link #EXPORT_MANIFEST} for the "uuidstructure" node, only required for backward compatibility with import version 2. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_UUIDSTRUCTURE = A_CmsImport.N_UUIDSTRUCTURE; /** Tag in the {@link #EXPORT_MANIFEST} for the "value" node, contains the value of a property. * @deprecated Use the appropriate tag from latest import class instead*/ @Deprecated public static final String N_VALUE = A_CmsImport.N_VALUE; /** Tag in the {@link #EXPORT_MANIFEST} for the "export_version" node, appears in the manifest info header. */ public static final String N_VERSION = "export_version"; /** Property to specify the export time written for a resource's date last modified. */ public static final String PROP_EXPORT_TIMESTAMP = "export.timestamp"; /** The log object for this class. */ private static final Log LOG = CmsLog.getLog(CmsImportExportManager.class); /** Boolean flag whether imported pages should be converted into XML pages. */ private boolean m_convertToXmlPage; /** The default values of the HTML->OpenCms Template converter. */ private CmsExtendedHtmlImportDefault m_extendedHtmlImportDefault; /** List of property keys that should be removed from imported resources. */ private List<String> m_ignoredProperties; /** Map from resource types to default timestamp modes. */ private Map<String, TimestampMode> m_defaultTimestampModes; /** List of immutable resources that should remain unchanged when resources are imported. */ private List<String> m_immutableResources; /** List of resourcetypes. Only used as helper for initializing the default timestamp modes. */ private List<String> m_resourcetypes; /** The initialized import/export handlers. */ private List<I_CmsImportExportHandler> m_importExportHandlers; /** Import principal group translations. */ private Map<String, String> m_importGroupTranslations; /** Import principal user translations. */ private Map<String, String> m_importUserTranslations; /** The configured import versions class names. */ private List<I_CmsImport> m_importVersionClasses; /** Boolean flag whether colliding resources should be overwritten during the import. */ private boolean m_overwriteCollidingResources; /** The user export settings. */ private CmsUserExportSettings m_userExportSettings; /** The URL of a 4.x OpenCms application to import content correct into 5.x OpenCms application. */ private String m_webAppUrl; /** * Creates a new instance for the import/export manager, will be called by the import/export configuration manager. */ public CmsImportExportManager() { if (LOG.isInfoEnabled()) { LOG.info(Messages.get().getBundle().key(Messages.INIT_IMPORTEXPORT_INITIALIZING_0)); } m_importExportHandlers = new ArrayList<I_CmsImportExportHandler>(); m_immutableResources = new ArrayList<String>(); m_ignoredProperties = new ArrayList<String>(); m_convertToXmlPage = true; m_importGroupTranslations = new HashMap<String, String>(); m_importUserTranslations = new HashMap<String, String>(); m_overwriteCollidingResources = true; m_importVersionClasses = new ArrayList<I_CmsImport>(); m_defaultTimestampModes = new HashMap<String, TimestampMode>(); m_resourcetypes = new ArrayList<String>(); } /** Adds the provided default timestamp mode for the resourcetypes in list {@link #m_resourcetypes}. * The method is called by the digester. * @param timestampMode the timestamp mode to add as default. */ public void addDefaultTimestampMode(String timestampMode) { if (null != timestampMode) { try { TimestampMode mode = TimestampMode.valueOf(timestampMode.toUpperCase()); for (String resourcetype : m_resourcetypes) { m_defaultTimestampModes.put(resourcetype, mode); if (LOG.isDebugEnabled()) { LOG.debug( Messages.get().getBundle().key( Messages.LOG_IMPORTEXPORT_EXPORT_SETTIMESTAMPMODE_2, timestampMode, resourcetype)); } } } catch (IllegalArgumentException e) { LOG.error( Messages.get().getBundle().key( Messages.ERR_IMPORTEXPORT_EXPORT_INVALID_TIMESTAMPMODE_2, timestampMode, m_resourcetypes.toString()), e); } } else { LOG.error( Messages.get().getBundle().key( Messages.ERR_IMPORTEXPORT_EXPORT_MISSING_TIMESTAMPMODE_1, m_resourcetypes.toString())); } m_resourcetypes.clear(); } /** * Adds a property name to the list of properties that should be removed from imported resources.<p> * * @param propertyName a property name */ public void addIgnoredProperty(String propertyName) { if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_IMPORTEXPORT_IGNORING_PROPERTY_1, propertyName)); } m_ignoredProperties.add(propertyName); } /** * Adds a resource to the list of immutable resources that should remain * unchanged when resources are imported.<p> * * @param immutableResource a resources uri in the OpenCms VFS */ public void addImmutableResource(String immutableResource) { if (LOG.isDebugEnabled()) { LOG.debug( Messages.get().getBundle().key( Messages.LOG_IMPORTEXPORT_ADDED_IMMUTABLE_RESOURCE_1, immutableResource)); } m_immutableResources.add(immutableResource); } /** * Adds an import/export handler to the list of configured handlers.<p> * * @param handler the import/export handler to add */ public void addImportExportHandler(I_CmsImportExportHandler handler) { if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_IMPORTEXPORT_ADDED_IMPORTEXPORT_HANDLER_1, handler)); } m_importExportHandlers.add(handler); } /** * Adds an import princial translation to the configuration.<p> * * @param type the princial type ("USER" or "GROUP") * @param from the "from" translation source * @param to the "to" translation target */ public void addImportPrincipalTranslation(String type, String from, String to) { if (LOG.isDebugEnabled()) { LOG.debug( Messages.get().getBundle().key( Messages.LOG_IMPORTEXPORT_ADDED_PRINCIPAL_TRANSLATION_3, type, from, to)); } if (I_CmsPrincipal.PRINCIPAL_GROUP.equalsIgnoreCase(type)) { m_importGroupTranslations.put(from, to); if (LOG.isInfoEnabled()) { LOG.info( Messages.get().getBundle().key(Messages.INIT_IMPORTEXPORT_ADDED_GROUP_TRANSLATION_2, from, to)); } } else if (I_CmsPrincipal.PRINCIPAL_USER.equalsIgnoreCase(type)) { m_importUserTranslations.put(from, to); if (LOG.isInfoEnabled()) { LOG.info(Messages.get().getBundle().key(Messages.INIT_IMPORTEXPORT_ADDED_USER_TRANSLATION_2, from, to)); } } } /** * Adds a import version class name to the configuration.<p> * * @param importVersionClass the import version class name to add */ public void addImportVersionClass(I_CmsImport importVersionClass) { if (LOG.isDebugEnabled()) { LOG.debug( Messages.get().getBundle().key(Messages.LOG_IMPORTEXPORT_ADDED_IMPORT_VERSION_1, importVersionClass)); } m_importVersionClasses.add(importVersionClass); } /** Adds a resourcetype name to the list of resourcetypes that obtain a default timestamp mode in {@link #addDefaultTimestampMode(String)}. * The method is called only by the digester. * * @param resourcetypeName name of the resourcetype */ public void addResourceTypeForDefaultTimestampMode(String resourcetypeName) { m_resourcetypes.add(resourcetypeName); } /** * Checks if imported pages should be converted into XML pages.<p> * * @return true, if imported pages should be converted into XML pages */ public boolean convertToXmlPage() { return m_convertToXmlPage; } /** * Checks if the current user has permissions to export Cms data of a specified export handler, * and if so, triggers the handler to write the export.<p> * * @param cms the cms context * @param handler handler containing the export data * @param report the output report * * @throws CmsRoleViolationException if the current user is not a allowed to export the OpenCms database * @throws CmsImportExportException if operation was not successful * @throws CmsConfigurationException if something goes wrong * * @see I_CmsImportExportHandler */ public void exportData(CmsObject cms, I_CmsImportExportHandler handler, I_CmsReport report) throws CmsConfigurationException, CmsImportExportException, CmsRoleViolationException { OpenCms.getRoleManager().checkRole(cms, CmsRole.DATABASE_MANAGER); handler.exportData(cms, report); } /** Returns the default timestamp mode for the resourcetype - or <code>null</code> if no default mode is set. * @param resourcetypeName name of the resourcetype to get the timestamp mode for * @return if set, the default timestamp mode for the resourcetype, otherwise <code>null</code> */ public TimestampMode getDefaultTimestampMode(String resourcetypeName) { return m_defaultTimestampModes.get(resourcetypeName); } /** Returns the map from resourcetype names to default timestamp modes. * @return the map from resourcetype names to default timestamp modes. */ public Map<TimestampMode, List<String>> getDefaultTimestampModes() { Map<TimestampMode, List<String>> result = new HashMap<TimestampMode, List<String>>(); for (String resourcetype : m_defaultTimestampModes.keySet()) { TimestampMode mode = m_defaultTimestampModes.get(resourcetype); if (result.containsKey(mode)) { result.get(mode).add(resourcetype); } else { List<String> list = new ArrayList<String>(); list.add(resourcetype); result.put(mode, list); } } return result; } /** * Returns the extendedHtmlImportDefault.<p> * * @return the extendedHtmlImportDefault */ public CmsExtendedHtmlImportDefault getExtendedHtmlImportDefault() { return getExtendedHtmlImportDefault(false); } /** * Returns the extendedHtmlImportDefault.<p> * *@param withNull returns the extendenHtmlImport as null if its null, * otherwise a new CmsExtendedHtmlImportDefault Object is generated * * @return the extendedHtmlImportDefault */ public CmsExtendedHtmlImportDefault getExtendedHtmlImportDefault(boolean withNull) { return (withNull || (m_extendedHtmlImportDefault != null) ? m_extendedHtmlImportDefault : new CmsExtendedHtmlImportDefault()); } /** * Returns the list of property keys that should be removed from imported resources.<p> * * @return the list of property keys that should be removed from imported resources, or Collections.EMPTY_LIST */ public List<String> getIgnoredProperties() { return m_ignoredProperties; } /** * Returns the list of immutable resources that should remain unchanged when resources are * imported.<p> * * Certain system resources should not be changed during import. This is the case for the main * folders in the /system/ folder. Changes to these folders usually should not be imported to * another system.<p> * * @return the list of immutable resources, or {@link Collections#EMPTY_LIST} */ public List<String> getImmutableResources() { return m_immutableResources; } /** * Returns an instance of an import/export handler implementation that is able to import * a specified resource.<p> * * @param parameters the import parameters * * @return an instance of an import/export handler implementation * * @throws CmsImportExportException if something goes wrong */ public I_CmsImportExportHandler getImportExportHandler(CmsImportParameters parameters) throws CmsImportExportException { Document manifest; InputStream stream = null; CmsImportHelper helper = new CmsImportHelper(parameters); try { helper.openFile(); stream = helper.getFileStream(CmsImportExportManager.EXPORT_MANIFEST); SAXReader reader = new SAXReader(false); reader.setValidation(false); reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); manifest = reader.read(stream); } catch (Throwable e) { throw new CmsImportExportException( Messages.get().container(Messages.ERR_IMPORTEXPORT_FILE_NOT_FOUND_1, EXPORT_MANIFEST), e); } finally { try { if (stream != null) { stream.close(); } } catch (@SuppressWarnings("unused") Exception e) { // noop } helper.closeFile(); } for (int i = 0; i < m_importExportHandlers.size(); i++) { I_CmsImportExportHandler handler = m_importExportHandlers.get(i); if (handler.matches(manifest)) { return handler; } } CmsMessageContainer message = Messages.get().container( Messages.ERR_IMPORTEXPORT_ERROR_NO_HANDLER_FOUND_1, EXPORT_MANIFEST); if (LOG.isDebugEnabled()) { LOG.debug(message.key()); } throw new CmsImportExportException(message); } /** * Returns the list of configured import/export handlers.<p> * * @return the list of configured import/export handlers */ public List<I_CmsImportExportHandler> getImportExportHandlers() { return m_importExportHandlers; } /** * Returns the configured principal group translations.<p> * * @return the configured principal group translations */ public Map<String, String> getImportGroupTranslations() { return m_importGroupTranslations; } /** * Returns the configured principal user translations.<p> * * @return the configured principal user translations */ public Map<String, String> getImportUserTranslations() { return m_importUserTranslations; } /** * Returns the configured import version class names.<p> * * @return the configured import version class names */ public List<I_CmsImport> getImportVersionClasses() { return m_importVersionClasses; } /** * Returns the URL of a 4.x OpenCms app. (e.g. http://localhost:8080/opencms/opencms/) * from which content was exported.<p> * * This setting is required to import content of 4.x OpenCms apps. correct into 5.x OpenCms apps.<p> * * @return the webAppUrl. */ public String getOldWebAppUrl() { return m_webAppUrl; } /** * Returns the user settings for export.<p> * * @return the user settings for export */ public CmsUserExportSettings getUserExportSettings() { return m_userExportSettings; } /** * Checks if the current user has permissions to import data into the Cms, * and if so, creates a new import handler instance that imports the data.<p> * * @param cms the current OpenCms context object * @param report a Cms report to print log messages * @param parameters the import parameters * * @throws CmsRoleViolationException if the current user is not allowed to import the OpenCms database * @throws CmsImportExportException if operation was not successful * @throws CmsXmlException if the manifest of the import could not be unmarshalled * @throws CmsException in case of errors accessing the VFS * * @see I_CmsImportExportHandler * @see #importData(CmsObject, String, String, I_CmsReport) */ public void importData(CmsObject cms, I_CmsReport report, CmsImportParameters parameters) throws CmsImportExportException, CmsXmlException, CmsRoleViolationException, CmsException { // check the required role permissions OpenCms.getRoleManager().checkRole(cms, CmsRole.DATABASE_MANAGER); try { OpenCms.fireCmsEvent( new CmsEvent(I_CmsEventListener.EVENT_CLEAR_CACHES, Collections.<String, Object> emptyMap())); I_CmsImportExportHandler handler = getImportExportHandler(parameters); synchronized (handler) { handler.setImportParameters(parameters); handler.importData(cms, report); } } finally { OpenCms.fireCmsEvent( new CmsEvent(I_CmsEventListener.EVENT_CLEAR_CACHES, Collections.<String, Object> emptyMap())); } } /** * Checks if the current user has permissions to import data into the Cms, * and if so, creates a new import handler instance that imports the data.<p> * * @param cms the current OpenCms context object * @param importFile the name (absolute path) of the resource (zipfile or folder) to be imported * @param importPath the name (absolute path) of the destination folder in the Cms if required, or null * @param report a Cms report to print log messages * * @throws CmsRoleViolationException if the current user is not allowed to import the OpenCms database * @throws CmsImportExportException if operation was not successful * @throws CmsXmlException if the manifest of the import could not be unmarshalled * @throws CmsException in case of errors accessing the VFS * * @see I_CmsImportExportHandler * @see #importData(CmsObject, I_CmsReport, CmsImportParameters) * * @deprecated use {@link #importData(CmsObject, I_CmsReport, CmsImportParameters)} instead */ @Deprecated public void importData(CmsObject cms, String importFile, String importPath, I_CmsReport report) throws CmsImportExportException, CmsXmlException, CmsRoleViolationException, CmsException { CmsImportParameters parameters = new CmsImportParameters(importFile, importPath, false); importData(cms, report, parameters); } /** * Checks if colliding resources should be overwritten during the import.<p> * * @return true, if colliding resources should be overwritten during the import * @see #setOverwriteCollidingResources(boolean) */ public boolean overwriteCollidingResources() { return m_overwriteCollidingResources; } /** * Sets if imported pages should be converted into XML pages.<p> * * @param convertToXmlPage true, if imported pages should be converted into XML pages. */ public void setConvertToXmlPage(boolean convertToXmlPage) { if (LOG.isDebugEnabled()) { LOG.debug( Messages.get().getBundle().key( Messages.LOG_IMPORTEXPORT_SET_CONVERT_PARAMETER_1, Boolean.toString(convertToXmlPage))); } m_convertToXmlPage = convertToXmlPage; } /** * Sets if imported pages should be converted into XML pages.<p> * * @param convertToXmlPage <code>"true"</code>, if imported pages should be converted into XML pages. */ public void setConvertToXmlPage(String convertToXmlPage) { setConvertToXmlPage(Boolean.valueOf(convertToXmlPage).booleanValue()); } /** * Sets the extendedHtmlImportDefault.<p> * * @param extendedHtmlImportDefault the extendedHtmlImportDefault to set */ public void setExtendedHtmlImportDefault(CmsExtendedHtmlImportDefault extendedHtmlImportDefault) { m_extendedHtmlImportDefault = extendedHtmlImportDefault; } /** * Sets the URL of a 4.x OpenCms app. (e.g. http://localhost:8080/opencms/opencms/) * from which content was exported.<p> * * This setting is required to import content of 4.x OpenCms apps. correct into 5.x OpenCms apps.<p> * * @param webAppUrl a URL of the a OpenCms app. (e.g. http://localhost:8080/opencms/opencms/) */ public void setOldWebAppUrl(String webAppUrl) { if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_IMPORTEXPORT_SET_OLD_WEBAPP_URL_1, webAppUrl)); } m_webAppUrl = webAppUrl; } /** * Sets whether colliding resources should be overwritten during the import for a * specified import implementation.<p> * * v1 and v2 imports (without resource UUIDs in the manifest) *MUST* overwrite colliding * resources. Don't forget to set this flag back to it's original value in v1 and v2 * import implementations!<p> * * This flag must be set to false to force imports > v2 to move colliding resources to * /system/lost-found/.<p> * * The import implementation has to take care to set this flag correct!<p> * * @param overwriteCollidingResources true if colliding resources should be overwritten during the import */ public void setOverwriteCollidingResources(boolean overwriteCollidingResources) { if (LOG.isDebugEnabled()) { LOG.debug( Messages.get().getBundle().key( Messages.LOG_IMPORTEXPORT_SET_OVERWRITE_PARAMETER_1, Boolean.toString(overwriteCollidingResources))); } m_overwriteCollidingResources = overwriteCollidingResources; } /** * @see CmsImportExportManager#setOverwriteCollidingResources(boolean) * * @param overwriteCollidingResources <code>"true"</code> if colliding resources should be overwritten during the import */ public void setOverwriteCollidingResources(String overwriteCollidingResources) { setOverwriteCollidingResources(Boolean.valueOf(overwriteCollidingResources).booleanValue()); } /** * Sets the user export settings.<p> * * @param userExportSettings the user export settings to set */ public void setUserExportSettings(CmsUserExportSettings userExportSettings) { m_userExportSettings = userExportSettings; } /** * Returns the translated name for the given group name.<p> * * If no matching name is found, the given group name is returned.<p> * * @param name the group name to translate * @return the translated name for the given group name */ public String translateGroup(String name) { if (m_importGroupTranslations == null) { return name; } String match = m_importGroupTranslations.get(name); if (match != null) { return match; } else { return name; } } /** * Returns the translated name for the given user name.<p> * * If no matching name is found, the given user name is returned.<p> * * @param name the user name to translate * @return the translated name for the given user name */ public String translateUser(String name) { if (m_importUserTranslations == null) { return name; } String match = m_importUserTranslations.get(name); if (match != null) { return match; } else { return name; } } }
lgpl-2.1
google-code-export/flies
server/zanata-war/src/main/java/org/zanata/webtrans/shared/model/DocumentInfo.java
809
package org.zanata.webtrans.shared.model; import java.io.Serializable; public class DocumentInfo implements HasIdentifier<DocumentId>, Serializable { private static final long serialVersionUID = 1L; private DocumentId id; private String name; private String path; // for GWT @SuppressWarnings("unused") private DocumentInfo() { } public DocumentInfo(DocumentId id, String name, String path) { this.id = id; this.name = name; this.path = path; } public DocumentId getId() { return id; } public String getName() { return name; } public String getPath() { return path; } @Override public String toString() { return "DocumentInfo(name=" + name + ",path=" + path + ",id=" + id + ")"; } }
lgpl-2.1
konradkwisniewski/abixen-platform
abixen-platform-business-intelligence-service/src/main/java/com/abixen/platform/service/businessintelligence/multivisualisation/service/DatabaseConnectionService.java
2052
/** * Copyright (c) 2010-present Abixen Systems. All rights reserved. * * 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. */ package com.abixen.platform.service.businessintelligence.multivisualisation.service; import com.abixen.platform.service.businessintelligence.multivisualisation.form.DatabaseConnectionForm; import com.abixen.platform.service.businessintelligence.multivisualisation.model.impl.database.DatabaseConnection; import com.abixen.platform.service.businessintelligence.multivisualisation.model.impl.datasource.DataSourceColumn; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.util.List; public interface DatabaseConnectionService { Page<DatabaseConnection> findAllDatabaseConnections(Pageable pageable); DatabaseConnection findDatabaseConnection(Long id); void deleteDatabaseConnection(Long id); DatabaseConnection buildDatabaseConnection(DatabaseConnectionForm databaseConnectionForm); DatabaseConnection createDatabaseConnection(DatabaseConnectionForm databaseConnectionForm); DatabaseConnection updateDatabaseConnection(DatabaseConnectionForm databaseConnectionForm); DatabaseConnection createDatabaseConnection(DatabaseConnection databaseConnection); DatabaseConnection updateDatabaseConnection(DatabaseConnection databaseConnection); void testDatabaseConnection(DatabaseConnectionForm databaseConnectionForm); List<String> getTables(Long databaseConnectionId); List<DataSourceColumn> getTableColumns(Long databaseConnectionId, String table); }
lgpl-2.1
dogjaw2233/tiu-s-mod
build/tmp/recompileMc/sources/net/minecraft/block/properties/PropertyHelper.java
1311
package net.minecraft.block.properties; import com.google.common.base.Objects; public abstract class PropertyHelper<T extends Comparable<T>> implements IProperty<T> { private final Class<T> valueClass; private final String name; protected PropertyHelper(String name, Class<T> valueClass) { this.valueClass = valueClass; this.name = name; } public String getName() { return this.name; } public Class<T> getValueClass() { return this.valueClass; } public String toString() { return Objects.toStringHelper(this).add("name", this.name).add("clazz", this.valueClass).add("values", this.getAllowedValues()).toString(); } public boolean equals(Object p_equals_1_) { if (this == p_equals_1_) { return true; } else if (p_equals_1_ != null && this.getClass() == p_equals_1_.getClass()) { PropertyHelper propertyhelper = (PropertyHelper)p_equals_1_; return this.valueClass.equals(propertyhelper.valueClass) && this.name.equals(propertyhelper.name); } else { return false; } } public int hashCode() { return 31 * this.valueClass.hashCode() + this.name.hashCode(); } }
lgpl-2.1
ropalka/jboss-msc
src/main/java/org/jboss/msc/inject/InjectorLogger.java
2345
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.msc.inject; import org.jboss.logging.Logger; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; /** * The injector logger interface. * * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> */ @MessageLogger(projectCode = "MSC") @Deprecated interface InjectorLogger { // ********************************************************** // ********************************************************** // ** ** // ** IMPORTANT - Be sure to check against the 2.x ** // ** codebase before assigning additional IDs ** // ** in this file! ** // ** ** // ********************************************************** // ********************************************************** @LogMessage(level = Logger.Level.WARN) @Message(id = 100, value = "Unexpected failure to uninject %s") void uninjectFailed(@Cause Throwable cause, Object target); InjectorLogger INSTANCE = Logger.getMessageLogger(InjectorLogger.class, "org.jboss.msc.inject"); }
lgpl-2.1
hohonuuli/vars
vars-jpa/src/main/java/vars/annotation/jpa/VideoArchiveDAOImpl.java
6419
package vars.annotation.jpa; import vars.annotation.FormatCodes; import vars.jpa.DAO; import vars.jpa.JPAEntity; import vars.knowledgebase.Concept; import vars.VARSPersistenceException; import java.util.Set; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.HashMap; import com.google.inject.Inject; import javax.persistence.EntityManager; import vars.annotation.AnnotationFactory; import vars.annotation.Association; import vars.annotation.CameraDeployment; import vars.annotation.Observation; import vars.annotation.VideoArchive; import vars.annotation.VideoArchiveDAO; import vars.annotation.VideoArchiveSet; import vars.annotation.VideoFrame; /** * Created by IntelliJ IDEA. * User: brian * Date: Aug 7, 2009 * Time: 4:41:26 PM * To change this template use File | Settings | File Templates. */ public class VideoArchiveDAOImpl extends DAO implements VideoArchiveDAO { private final AnnotationFactory annotationFactory; @Inject public VideoArchiveDAOImpl(EntityManager entityManager, AnnotationFactory annotationFactory) { super(entityManager); this.annotationFactory = annotationFactory; } public Set<String> findAllLinkValues(VideoArchive videoArchive, String linkName) { return findAllLinkValues(videoArchive, linkName, null); } /** * This should only be called within JPA/DAO transaction * @param videoArchive * @param linkName * @param concept * @return */ public Set<String> findAllLinkValues(VideoArchive videoArchive, String linkName, Concept concept) { // Due to lazy loading we want to iterate through all objects in a collection videoArchive = find(videoArchive); Collection<? extends VideoFrame> videoFrames = videoArchive.getVideoArchiveSet().getVideoFrames(); Set<String> linkValues = new HashSet<String>(); for (VideoFrame videoFrame : videoFrames) { for (Observation observation : videoFrame.getObservations()) { if (concept == null || concept.getConceptName(observation.getConceptName()) != null) { for (Association association : observation.getAssociations()) { if (linkName.equals(association.getLinkName())) { linkValues.add(association.getLinkValue()); } } } } } return linkValues; } /** * Call this within a transaction. The returned {@link VideoArchive} will be * in the database */ public VideoArchive findOrCreateByParameters(String platform, int sequenceNumber, String videoArchiveName) { // ---- Step 1: Look up VideoArchive by Name VideoArchive videoArchive = findByName(videoArchiveName); if (videoArchive == null) { // ---- Step 2: No match was found. See if the desired deployment exists VideoArchiveSet videoArchiveSet = null; Map<String, Object> params2 = new HashMap<String, Object>(); params2.put("platformName", platform); params2.put("sequenceNumber", sequenceNumber); List<VideoArchiveSet> vas = findByNamedQuery("VideoArchiveSet.findByPlatformAndSequenceNumber", params2); if (vas.size() == 1) { videoArchiveSet = vas.get(0); } else if (vas.size() > 1) { throw new VARSPersistenceException("There's a problem!! More than one VideoArchiveSet " + "with platform = " + platform + " and sequenceNumber = " + sequenceNumber + " exists in the database"); } else { videoArchiveSet = annotationFactory.newVideoArchiveSet(); videoArchiveSet.setPlatformName(platform); videoArchiveSet.setFormatCode(FormatCodes.UNKNOWN.getCode()); persist(videoArchiveSet); CameraDeployment cameraDeployment = annotationFactory.newCameraDeployment(); cameraDeployment.setSequenceNumber(sequenceNumber); videoArchiveSet.addCameraDeployment(cameraDeployment); persist(cameraDeployment); } videoArchive = annotationFactory.newVideoArchive(); videoArchive.setName(videoArchiveName); videoArchiveSet.addVideoArchive(videoArchive); persist(videoArchive); } return videoArchive; } public VideoArchive findByName(final String name) { VideoArchive videoArchive = null; Map<String, Object> params = new HashMap<String, Object>() {{ put("name", name); }}; List<VideoArchive> videoArchives = findByNamedQuery("VideoArchive.findByName", params); if (videoArchives.size() == 1) { videoArchive = videoArchives.get(0); } else if (videoArchives.size() > 1) { throw new VARSPersistenceException("There's a problem!! More than one VideoArchive named " + name + " exists in the database"); } return videoArchive; } /** * This should be called within a DAO transaction * @param videoArchive * @return */ public VideoArchive deleteEmptyVideoFrames(VideoArchive videoArchive) { Collection<VideoFrame> emptyFrames = (Collection<VideoFrame>) videoArchive.getEmptyVideoFrames(); int n = 0; boolean doFetch = emptyFrames.size() > 0; for (vars.annotation.VideoFrame videoFrame : emptyFrames) { videoArchive.removeVideoFrame(videoFrame); n++; } /* * Delete in a single transaction if possible */ if (doFetch) { try { for (VideoFrame videoFrame : emptyFrames) { remove(videoFrame); } log.debug("Deleted " + n + " empty VideoFrames from " + videoArchive); } finally { videoArchive = findByPrimaryKey(videoArchive.getClass(), ((JPAEntity) videoArchive).getId()); } } return videoArchive; } @Override public VideoArchive findByPrimaryKey(Object primaryKey) { return findByPrimaryKey(VideoArchiveImpl.class, primaryKey); } }
lgpl-2.1
jtalks-org/jtalks-common
jtalks-common-model/src/main/java/org/jtalks/common/util/FlywayWrapper.java
3248
/** * Copyright (C) 2011 JTalks.org Team * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jtalks.common.util; import com.googlecode.flyway.core.Flyway; import com.googlecode.flyway.core.exception.FlywayException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * Wrapper that allows disabling flyway migrations, schema cleanup and initialization. * * @author Kirill Afonin * @author Alexey Malev */ public class FlywayWrapper extends Flyway { private boolean enabled = false; /** * Can be used for disabling/enabling migrations and init. * They are disabled by default. * * @param enabled is migrations enabled */ public void setEnabled(boolean enabled) { this.enabled = enabled; } /** * {@inheritDoc} */ @Override public int migrate() { if (enabled) { return super.migrate(); } return 0; } /** * <p>This method performs {@link Flyway#init()} if there is no metadata table in the specified schema and if * <code>smartInit()</code> is enabled.</p> * <p><b>It is strongly recommended to disable this in production usage.</b></p> * * @throws FlywayException Any {@link SQLException} thrown inside the method * is wrapped into {@link FlywayException} */ public void smartInit() { if (this.enabled) { try { Connection connection = this.getDataSource().getConnection(); try { PreparedStatement checkTableExistenceStatement = connection.prepareStatement("show tables like ?"); try { checkTableExistenceStatement.setString(1, this.getTable()); ResultSet fetchedTableNames = checkTableExistenceStatement.executeQuery(); try { if (!fetchedTableNames.next()) { super.init(); } } finally { fetchedTableNames.close(); } } finally { checkTableExistenceStatement.close(); } } finally { connection.close(); } } catch (SQLException e) { throw new FlywayException(e.getLocalizedMessage(), e); } } } }
lgpl-2.1
awltech/org.parallelj
parallelj-core-parent/parallelj-core/src/test/java/tutorial/MyInnerProgram.java
2694
/* * ParallelJ, framework for parallel computing * * Copyright (C) 2010, 2011, 2012 Atos Worldline or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. * * 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package tutorial; import javax.annotation.Generated; import org.parallelj.Capacity; import org.parallelj.Program; import org.parallelj.Begin; import org.parallelj.AndSplit; import org.parallelj.AndJoin; /** * Program org.parallelj.test.demo.MyInnerProgram Description : **/ @Generated("//J") @Program public class MyInnerProgram { private String val; public MyInnerProgram(String val) { super(); this.val = val; } @Begin @Capacity(1) public ToUpperCase procone() { System.out.println("Display procone 1a: " + val); ToUpperCase toUpperCase = new ToUpperCase(); toUpperCase.setSource(val); return toUpperCase; } @AndSplit({ "proctwo" }) @Capacity(1) public void procone(ToUpperCase toUpperCase, String result) { System.out.println("RES one: " + result); } @AndJoin @Capacity(1) public ToUpperCase proctwo() { System.out.println("Display proctwo 1b: " + val); ToUpperCase toUpperCase = new ToUpperCase(); toUpperCase.setSource(val); return toUpperCase; } @AndSplit({ "procthree" }) @Capacity(1) public void proctwo(ToUpperCase toUpperCase, String result) { // System.out.println("Display proctwo 1b: " + iteratortwo.next()); System.out.println("RES two: " + result); } @AndJoin @Capacity(1) public ToUpperCase procthree() { System.out.println("Display procthree 1c: " + val); ToUpperCase toUpperCase = new ToUpperCase(); toUpperCase.setSource(val); return toUpperCase; } @AndSplit({ "end" }) @Capacity(1) public void procthree(ToUpperCase toUpperCase, String result) { System.out.println("RES three: " + result); } public String getVal() { return val; } public void setVal(String val) { this.val = val; } }
lgpl-2.1
pixlepix/MineChem
src/main/java/pixlepix/minechem/client/render/tileentity/TileEntitySynthesisRenderer.java
1528
package pixlepix.minechem.client.render.tileentity; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; import pixlepix.minechem.common.tileentity.TileEntitySynthesis; import pixlepix.minechem.common.utils.ConstantValue; public class TileEntitySynthesisRenderer extends TileEntitySpecialRenderer { @Override public void renderTileEntityAt(TileEntity tileEntity, double x, double y, double z, float scale) { if (tileEntity instanceof TileEntitySynthesis) { TileEntitySynthesis synthesis = (TileEntitySynthesis) tileEntity; int facing = synthesis.getFacing(); if (synthesis.getEnergyStored() > 100) synthesis.model.updateArm(); GL11.glPushMatrix(); GL11.glTranslated(x + 0.5D, y + 1.5D, z + 0.5D); GL11.glRotatef(180f, 0f, 0f, 1f); GL11.glRotatef(facing * 90.0F, 0.0F, 1.0F, 0.0F); GL11.glEnable(GL11.GL_LIGHTING); GL11.glEnable(GL11.GL_BLEND); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); bindTexture(new ResourceLocation(ConstantValue.MOD_ID, ConstantValue.SYNTHESIS_MODEL)); synthesis.model.render(0.0625F); GL11.glDisable(GL11.GL_BLEND); GL11.glDisable(GL11.GL_LIGHTING); GL11.glPopMatrix(); } } }
lgpl-2.1
dresden-ocl/dresdenocl
plugins/org.dresdenocl.interpreter/src/org/dresdenocl/interpreter/event/IInterpreterRegistryListener.java
3262
/** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright (C) 2007 Ronny Brandt (Ronny_Brandt@web.de). * * All rights reserved. * * * * This work was done as a project at the Chair for Software Technology, * * Dresden University Of Technology, Germany (http://st.inf.tu-dresden.de). * * It is understood that any modification not identified as such is not * * covered by the preceding statement. * * * * This work is free software; you can redistribute it and/or modify it * * under the terms of the GNU Library General Public License as published * * by the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This work 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 Library General Public * * License for more details. * * * * You should have received a copy of the GNU Library General Public License * * along with this library; if not, you can view it online at * * http://www.fsf.org/licensing/licenses/gpl.html. * * * * To submit a bug report, send a comment, or get the latest news on this * * project, please visit the website: http://dresden-ocl.sourceforge.net. * * For more information on OCL and related projects visit the OCL Portal: * * http://st.inf.tu-dresden.de/ocl * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ package org.dresdenocl.interpreter.event; import org.dresdenocl.interpreter.IInterpreterRegistry; import org.dresdenocl.interpreter.event.internal.InterpreterRegistryEvent; /** * <p> * The listener interface for receiving {@link IInterpreterRegistry} events. The * class that is interested in processing a {@link IInterpreterRegistry} event * implements this interface, and the object created with that class is * registered with a component using the component's * <code>addIInterpreterRegistryListener<code> method. When * the {@link IInterpreterRegistry} event occurs, that object's appropriate * method is invoked. * </p> * * @see IInterpreterRegistryEvent * * @author Ronny Brandt */ public interface IInterpreterRegistryListener { /** * <p> * Invoked when the interpretation finished. * </p> * * @param event * The {@link InterpreterRegistryEvent} that is fired. */ void interpretationFinished(InterpreterRegistryEvent event); }
lgpl-3.0
find-sec-bugs/find-sec-bugs
findsecbugs-samples-java/src/test/java/testcode/pathtraversal/PathTraversal.java
1288
package testcode.pathtraversal; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.RandomAccessFile; import java.net.URI; import java.net.URISyntaxException; public class PathTraversal { static final String safefinalString = "SAFE"; public static void main(String[] args) throws IOException, URISyntaxException { String input = args.length > 0 ? args[0] : "../../../../etc/password\u0000"; new File(input); new File("test/" + input, "misc.jpg"); new RandomAccessFile(input, "r"); new File(new URI(args[0])); new FileReader(input); new FileInputStream(input); new FileWriter(input); new FileWriter(input, true); new FileOutputStream(input); new FileOutputStream(input, true); // false positive test new RandomAccessFile("safe", args[0]); new FileWriter("safe".toUpperCase()); new File(new URI("safe")); File.createTempFile(input, "safe"); File.createTempFile("safe", input); File.createTempFile("safe", input, new File("safeDir")); new File(safefinalString); } }
lgpl-3.0
kaspersorensen/DataCleaner
engine/core/src/test/java/org/datacleaner/components/filter/MaxRowsFilterTest.java
4303
/** * DataCleaner (community edition) * Copyright (C) 2014 Free Software Foundation, Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * 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 distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.datacleaner.components.filter; import org.apache.metamodel.query.Query; import org.datacleaner.components.maxrows.MaxRowsFilter; import org.datacleaner.components.maxrows.MaxRowsFilter.Category; import org.datacleaner.data.MockInputRow; import org.datacleaner.descriptors.Descriptors; import org.datacleaner.descriptors.FilterDescriptor; import junit.framework.TestCase; public class MaxRowsFilterTest extends TestCase { public void testDescriptor() throws Exception { final FilterDescriptor<MaxRowsFilter, MaxRowsFilter.Category> desc = Descriptors.ofFilter(MaxRowsFilter.class); assertEquals("Max rows", desc.getDisplayName()); } public void testCounter1() throws Exception { final MaxRowsFilter f = new MaxRowsFilter(1, 3); assertEquals(MaxRowsFilter.Category.VALID, f.categorize(new MockInputRow())); assertEquals(MaxRowsFilter.Category.VALID, f.categorize(new MockInputRow())); assertEquals(MaxRowsFilter.Category.VALID, f.categorize(new MockInputRow())); assertEquals(MaxRowsFilter.Category.INVALID, f.categorize(new MockInputRow())); } public void testCounter2() throws Exception { final MaxRowsFilter f = new MaxRowsFilter(2, 3); assertEquals(MaxRowsFilter.Category.INVALID, f.categorize(new MockInputRow())); assertEquals(MaxRowsFilter.Category.VALID, f.categorize(new MockInputRow())); assertEquals(MaxRowsFilter.Category.VALID, f.categorize(new MockInputRow())); assertEquals(MaxRowsFilter.Category.VALID, f.categorize(new MockInputRow())); assertEquals(MaxRowsFilter.Category.INVALID, f.categorize(new MockInputRow())); } public void testOptimizeTwiceSubset() throws Exception { // offset 10, limit 20 (so rec. 10-30) final MaxRowsFilter f1 = new MaxRowsFilter(10, 20); // offset 15, limit 1 (so rec. 15-16, which becomes then 25-16) final MaxRowsFilter f2 = new MaxRowsFilter(15, 1); final Query q = new Query(); f1.optimizeQuery(q, Category.VALID); f2.optimizeQuery(q, Category.VALID); assertEquals(25, q.getFirstRow().intValue()); assertEquals(1, q.getMaxRows().intValue()); } public void testOptimizeTwiceOverlappingIntervals() throws Exception { // offset 10, limit 20 (so rec. 10-30) final MaxRowsFilter f1 = new MaxRowsFilter(10, 20); // offset 15, limit 30 (so rec. 15-45, which becomes then 25-45, but // since 45 is beyond the limit of the first filter, it should finally // become 25-30) final MaxRowsFilter f2 = new MaxRowsFilter(15, 30); final Query q = new Query(); f1.optimizeQuery(q, Category.VALID); f2.optimizeQuery(q, Category.VALID); assertEquals(25, q.getFirstRow().intValue()); assertEquals(5, q.getMaxRows().intValue()); } public void testOptimizeTwiceImpossibleIntervals() throws Exception { // offset 10, limit 20 (so rec. 10-30) final MaxRowsFilter f1 = new MaxRowsFilter(10, 20); // offset 45, limit 30 (so rec. 45-75, which is a totally different // range than f1's range) final MaxRowsFilter f2 = new MaxRowsFilter(45, 30); final Query q = new Query(); f1.optimizeQuery(q, Category.VALID); f2.optimizeQuery(q, Category.VALID); assertEquals(55, q.getFirstRow().intValue()); assertEquals(0, q.getMaxRows().intValue()); } }
lgpl-3.0
Albloutant/Galacticraft
dependencies/codechicken/core/NetworkClosedException.java
113
package codechicken.core; @SuppressWarnings("serial") public class NetworkClosedException extends Exception { }
lgpl-3.0
marissaDubbelaar/GOAD3.1.1
molgenis-data-platform/src/main/java/org/molgenis/data/platform/bootstrap/SystemEntityTypeBootstrapper.java
1899
package org.molgenis.data.platform.bootstrap; import org.molgenis.data.i18n.SystemEntityTypeI18nInitializer; import org.molgenis.data.meta.system.SystemEntityTypeInitializer; import org.molgenis.data.meta.system.SystemEntityTypePersister; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component; import static java.util.Objects.requireNonNull; @Component public class SystemEntityTypeBootstrapper { private static final Logger LOG = LoggerFactory.getLogger(SystemEntityTypeBootstrapper.class); private final SystemEntityTypeInitializer systemEntityTypeInitializer; private final SystemEntityTypeI18nInitializer systemEntityTypeI18nInitializer; private final SystemEntityTypePersister systemEntityTypePersister; @Autowired SystemEntityTypeBootstrapper(SystemEntityTypeInitializer systemEntityTypeInitializer, SystemEntityTypeI18nInitializer systemEntityTypeI18nInitializer, SystemEntityTypePersister systemEntityTypePersister) { this.systemEntityTypeInitializer = requireNonNull(systemEntityTypeInitializer); this.systemEntityTypeI18nInitializer = systemEntityTypeI18nInitializer; this.systemEntityTypePersister = requireNonNull(systemEntityTypePersister); } public void bootstrap(ContextRefreshedEvent event) { LOG.trace("Initializing system entity meta data ..."); systemEntityTypeInitializer.initialize(event); LOG.trace("Initialized system entity meta data"); LOG.trace("Internationalizing system entity meta data ..."); systemEntityTypeI18nInitializer.initialize(event); LOG.trace("Internationalized system entity meta data"); LOG.trace("Persisting system entity meta data ..."); systemEntityTypePersister.persist(); LOG.trace("Persisted system entity meta data"); } }
lgpl-3.0
sklaxel/inera-axel
shs/shs-broker/shs-product-mongodb/src/test/java/se/inera/axel/shs/broker/product/mongo/MongoDBTestContextConfig.java
4194
/** * Copyright (C) 2013 Inera AB (http://www.inera.se) * * This file is part of Inera Axel (http://code.google.com/p/inera-axel). * * Inera Axel 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. * * Inera Axel 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 se.inera.axel.shs.broker.product.mongo; import com.mongodb.Mongo; import com.mongodb.ServerAddress; import de.flapdoodle.embed.mongo.Command; import de.flapdoodle.embed.mongo.MongodExecutable; import de.flapdoodle.embed.mongo.MongodProcess; import de.flapdoodle.embed.mongo.MongodStarter; import de.flapdoodle.embed.mongo.config.*; import de.flapdoodle.embed.mongo.distribution.Version; import de.flapdoodle.embed.process.config.IRuntimeConfig; import de.flapdoodle.embed.process.extract.UUIDTempNaming; import de.flapdoodle.embed.process.runtime.Network; import org.springframework.beans.factory.DisposableBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.mongodb.MongoDbFactory; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.SimpleMongoDbFactory; import org.springframework.data.mongodb.repository.support.MongoRepositoryFactory; @Configuration public class MongoDBTestContextConfig implements DisposableBean { public @Bean(destroyMethod = "stop") MongodExecutable mongodExecutable() throws Exception { IMongodConfig mongodConfig = new MongodConfigBuilder() .version(Version.Main.V2_2) .net(new Net(Network.getFreeServerPort(), Network.localhostIsIPv6())) .build(); IRuntimeConfig runtimeConfig = new RuntimeConfigBuilder() .defaults(Command.MongoD) .artifactStore(new ArtifactStoreBuilder() .defaults(Command.MongoD) .executableNaming(new UUIDTempNaming()) ) .build(); MongodStarter runtime = MongodStarter.getInstance(runtimeConfig); return runtime.prepare(mongodConfig); } public @Bean(destroyMethod = "stop") MongodProcess mongodProcess() throws Exception { MongodProcess mongod = mongodExecutable().start(); return mongod; } public @Bean(destroyMethod = "close") Mongo mongo() throws Exception { MongodProcess mongodProcess = mongodProcess(); return new Mongo(new ServerAddress(mongodProcess.getConfig().net().getServerAddress(), mongodProcess.getConfig().net().getPort())); } public @Bean MongoDbFactory mongoDbFactory() throws Exception { return new SimpleMongoDbFactory(mongo(), "axel-test"); } public @Bean MongoOperations mongoOperations() throws Exception { return new MongoTemplate(mongoDbFactory()); } public @Bean MongoRepositoryFactory mongoRepositoryFactory() throws Exception { return new MongoRepositoryFactory(mongoOperations()); } public @Bean MongoShsProductRepository mongoShsProductRepository() throws Exception { return mongoRepositoryFactory().getRepository(MongoShsProductRepository.class); } public @Bean ProductAssembler productAssembler() throws Exception { return new ProductAssembler(); } @Override public void destroy() throws Exception { Mongo mongo = mongo(); if (mongo != null) mongo.close(); MongodProcess mongodProcess = mongodProcess(); if (mongodProcess != null) mongodProcess.stop(); } }
lgpl-3.0
liubingzsd/uavplayground
src/jaron/gps/GPSUtil.java
2823
package jaron.gps; /** * The <code>GPSUtil</code> class provides some utility functionality * for the GPS data handling. * * @author jarontec gmail com * @version 1.2 * @since 1.1 */ public class GPSUtil { /** * Returns the distance between two locations. * * @param lat1 the latitude coordinate of the first location * @param lon1 the longitude coordinate of the first location * @param lat2 the latitude coordinate of the second location * @param lon2 the longitude coordinate of the second location * @return the calculated distance in kilometers */ public static double getDistance(double lat1, double lon1, double lat2, double lon2) { /* Source: http://www.movable-type.co.uk/scripts/latlong.html var R = 6371; // km var dLat = (lat2-lat1).toRad(); var dLon = (lon2-lon1).toRad(); var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * Math.sin(dLon/2) * Math.sin(dLon/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); var d = R * c; */ int R = 6371; double dLat = Math.toRadians((lat2 - lat1)); double dLon = Math.toRadians((lon2 - lon1)); double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2); double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); double d = R * c; return d; } /** * Returns the distance between two locations. * * @param lat1 a <code>Latitude</code> object containing the latitude coordinate of the first location * @param lon1 a <code>Latitude</code> object containing the longitude coordinate of the first location * @param lat2 a <code>Latitude</code> object containing the latitude coordinate of the second location * @param lon2 a <code>Latitude</code> object containing the longitude coordinate of the second location * @return the calculated distance in kilometers */ public static double getDistance(Latitude lat1, Longitude lon1, Latitude lat2, Longitude lon2){ return getDistance(lat1.getDecimal(), lon1.getDecimal(), lat2.getDecimal(), lon2.getDecimal()); } /** * Returns the distance between two locations. * * @param p1 a <code>Trackpoint</code> object containing the first location * @param p2 a <code>Trackpoint</code> object containing the second location * @return the calculated distance in kilometers */ public static double getDistance(Trackpoint p1, Trackpoint p2) { return getDistance(p1.getLatitude().getDecimal(), p1.getLongitude().getDecimal(), p2.getLatitude().getDecimal(), p2.getLongitude().getDecimal()); } }
lgpl-3.0
snmaher/xacml4j
xacml-core/src/main/java/org/xacml4j/v30/marshal/PolicyMarshaller.java
961
package org.xacml4j.v30.marshal; /* * #%L * Xacml4J Core Engine Implementation * %% * Copyright (C) 2009 - 2014 Xacml4J.org * %% * 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 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 Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ import org.xacml4j.v30.CompositeDecisionRule; public interface PolicyMarshaller extends Marshaller<CompositeDecisionRule> { }
lgpl-3.0
aocalderon/PhD
Y2Q3/PBFE4/src/test/Itemsets.java
4985
package test; /* This file is copyright (c) 2008-2012 Philippe Fournier-Viger * * This file is part of the SPMF DATA MINING SOFTWARE * (http://www.philippe-fournier-viger.com/spmf). * * SPMF 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. * SPMF 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 * SPMF. If not, see <http://www.gnu.org/licenses/>. */ import java.util.ArrayList; import java.util.List; /** * This class represents a set of itemsets, where an itemset is an array of integers * with an associated support count. Itemsets are ordered by size. For * example, level 1 means itemsets of size 1 (that contains 1 item). * * @author Philippe Fournier-Viger */ public class Itemsets{ /** We store the itemsets in a list named "levels". Position i in "levels" contains the list of itemsets of size i */ private final List<List<Itemset>> levels = new ArrayList<List<Itemset>>(); /** the total number of itemsets **/ private int itemsetsCount = 0; /** a name that we give to these itemsets (e.g. "frequent itemsets") */ private String name; /** * Constructor * @param name the name of these itemsets */ public Itemsets(String name) { this.name = name; levels.add(new ArrayList<Itemset>()); // We create an empty level 0 by // default. } /* (non-Javadoc) * @see ca.pfv.spmf.patterns.itemset_array_integers_with_count.AbstractItemsets#printItemsets(int) */ public void printItemsets(int nbObject) { System.out.println(" ------- " + name + " -------"); int patternCount = 0; int levelCount = 0; // for each level (a level is a set of itemsets having the same number of items) for (List<Itemset> level : levels) { // print how many items are contained in this level System.out.println(" L" + levelCount + " "); // for each itemset for (Itemset itemset : level) { // Arrays.sort(itemset.getItems()); // print the itemset System.out.print(" pattern " + patternCount + ": "); itemset.print(); // print the support of this itemset System.out.print("support : " + itemset.getAbsoluteSupport()); // + itemset.getRelativeSupportAsString(nbObject)); patternCount++; System.out.println(""); } levelCount++; } System.out.println(" --------------------------------"); } public void printItemsets() { for (List<Itemset> level : levels) { for (Itemset itemset : level) { System.out.format("%s[%d]%n", itemset.toString(), itemset.getAbsoluteSupport()); } } } public Integer countItemsets(int mu){ int count = 0; for (List<Itemset> level : levels) { if(level.size() !=0){ if(level.get(0).size() >= mu){ count += level.size(); } } } return count; } public ArrayList<ArrayList<Integer>> getItemsets(int mu){ ArrayList<ArrayList<Integer>> itemsets = new ArrayList<ArrayList<Integer>>(); for (List<Itemset> level : levels) { if(level.size() !=0){ if(level.get(0).size() >= mu){ for(int i = 0; i < level.size(); i++){ int[] array = level.get(i).getItems(); ArrayList<Integer> list = new ArrayList<Integer>(array.length); for (int j = 0; j < array.length; j++) list.add(Integer.valueOf(array[j])); itemsets.add(list); } } } } return itemsets; } /* (non-Javadoc) * @see ca.pfv.spmf.patterns.itemset_array_integers_with_count.AbstractItemsets#addItemset(ca.pfv.spmf.patterns.itemset_array_integers_with_count.Itemset, int) */ public void addItemset(Itemset itemset, int k) { while (levels.size() <= k) { levels.add(new ArrayList<Itemset>()); } levels.get(k).add(itemset); itemsetsCount++; } /* (non-Javadoc) * @see ca.pfv.spmf.patterns.itemset_array_integers_with_count.AbstractItemsets#getLevels() */ public List<List<Itemset>> getLevels() { return levels; } /* (non-Javadoc) * @see ca.pfv.spmf.patterns.itemset_array_integers_with_count.AbstractItemsets#getItemsetsCount() */ public int getItemsetsCount() { return itemsetsCount; } /* (non-Javadoc) * @see ca.pfv.spmf.patterns.itemset_array_integers_with_count.AbstractItemsets#setName(java.lang.String) */ public void setName(String newName) { name = newName; } /* (non-Javadoc) * @see ca.pfv.spmf.patterns.itemset_array_integers_with_count.AbstractItemsets#decreaseItemsetCount() */ public void decreaseItemsetCount() { itemsetsCount--; } }
lgpl-3.0
BassJel/Jouve-Project
source/java/com/doculibre/constellio/wicket/panels/results/PopupSearchResultPanel.java
8525
/** * Constellio, Open Source Enterprise Search * Copyright (C) 2010 DocuLibre inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * 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 distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package com.doculibre.constellio.wicket.panels.results; import java.util.Collection; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringUtils; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.wicket.RequestCycle; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.behavior.AttributeAppender; import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.LoadableDetachableModel; import org.apache.wicket.protocol.http.WebRequest; import com.doculibre.constellio.entities.IndexField; import com.doculibre.constellio.entities.RawContent; import com.doculibre.constellio.entities.Record; import com.doculibre.constellio.entities.RecordCollection; import com.doculibre.constellio.entities.search.SimpleSearch; import com.doculibre.constellio.services.RawContentServices; import com.doculibre.constellio.services.RecordCollectionServices; import com.doculibre.constellio.services.RecordServices; import com.doculibre.constellio.servlets.ComputeSearchResultClickServlet; import com.doculibre.constellio.utils.ConstellioSpringUtils; import com.doculibre.constellio.wicket.data.SearchResultsDataProvider; import com.doculibre.constellio.wicket.models.RecordModel; import com.doculibre.constellio.wicket.panels.elevate.ElevatePanel; @SuppressWarnings("serial") public class PopupSearchResultPanel extends Panel { // private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss"); public PopupSearchResultPanel(String id, SolrDocument doc, final SearchResultsDataProvider dataProvider) { super(id); RecordCollectionServices collectionServices = ConstellioSpringUtils.getRecordCollectionServices(); String solrServerName = dataProvider.getSimpleSearch().getCollectionName(); RecordCollection collection = collectionServices.get(solrServerName); IndexField uniqueKeyField = collection.getUniqueKeyIndexField(); IndexField defaultSearchField = collection.getDefaultSearchIndexField(); IndexField urlField = collection.getUrlIndexField(); IndexField titleField = collection.getTitleIndexField(); // title String documentID = (String) getFieldValue(doc, uniqueKeyField.getName()); String documentTitle = (String) getFieldValue(doc, titleField.getName()); if (StringUtils.isBlank(documentTitle)) { if (urlField == null) { documentTitle = (String) getFieldValue(doc, uniqueKeyField.getName()); } else { documentTitle = (String) getFieldValue(doc, urlField.getName()); } } if (documentTitle.length() > 120) { documentTitle = documentTitle.substring(0, 120) + " ..."; } // content RecordServices recordServices = ConstellioSpringUtils.getRecordServices(); Record record = recordServices.get(doc); RawContentServices rawContentServices = ConstellioSpringUtils.getRawContentServices(); List<RawContent> rawContents = rawContentServices.getRawContents(record); StringBuilder content = new StringBuilder(); for (RawContent raw : rawContents) { byte[] bytes = raw.getContent(); content.append(new String(bytes)); } String documentContent = content.toString(); // date String documentLastModified = getFieldValue(doc, IndexField.LAST_MODIFIED_FIELD); // Description du document dans extrait: QueryResponse response = dataProvider.getQueryResponse(); Map<String, Map<String, List<String>>> highlighting = response.getHighlighting(); final String recordURL = record.getUrl(); Map<String, List<String>> fieldsHighlighting = highlighting.get(recordURL); String extrait = getExcerptFromHighlight(defaultSearchField.getName(), fieldsHighlighting); final ModalWindow detailsDocumentModal = new ModalWindow("detailsDocumentModal"); add(detailsDocumentModal); detailsDocumentModal.setCssClassName(ModalWindow.CSS_CLASS_GRAY); detailsDocumentModal.setContent(new PopupDetailsPanel(detailsDocumentModal.getContentId(), documentContent, documentLastModified)); detailsDocumentModal.setCookieName("detailsDocumentModal"); String modalTitle = documentTitle; detailsDocumentModal.setTitle(modalTitle); AjaxLink detailsDocumentLink = new AjaxLink("detailsDocumentLink") { @Override public void onClick(AjaxRequestTarget target) { detailsDocumentModal.show(target); } }; add(detailsDocumentLink); final RecordModel recordModel = new RecordModel(record); AttributeAppender computeClickAttributeModifier = new AttributeAppender("onclick", true, new LoadableDetachableModel() { @Override protected Object load() { Record record = recordModel.getObject(); SimpleSearch simpleSearch = dataProvider.getSimpleSearch(); WebRequest webRequest = (WebRequest) RequestCycle.get().getRequest(); HttpServletRequest httpRequest = webRequest.getHttpServletRequest(); return ComputeSearchResultClickServlet.getCallbackJavascript(httpRequest, simpleSearch, record); } @Override protected void onDetach() { recordModel.detach(); super.onDetach(); } }, ";") { @Override protected String newValue(String currentValue, String appendValue) { return appendValue + currentValue; } }; detailsDocumentLink.add(computeClickAttributeModifier); Label subjectLabel = new Label("subject", documentTitle); detailsDocumentLink.add(subjectLabel.setEscapeModelStrings(false)); Label extraitLbl = new Label("documentContent", extrait); add(extraitLbl.setEscapeModelStrings(false)); add(new Label("date", "Date : " + documentLastModified)); add(new ElevatePanel("elevatePanel", record, dataProvider.getSimpleSearch())); } private String getExcerptFromHighlight(String defaultSearchFieldName, Map<String, List<String>> fieldsHighlighting) { String exerpt = ""; if (fieldsHighlighting != null) { List<String> fieldHighlighting = fieldsHighlighting.get(defaultSearchFieldName); if (fieldHighlighting != null) { StringBuffer sb = new StringBuffer(); for (String val : fieldHighlighting) { sb.append(StringEscapeUtils.unescapeXml(val) + " ... "); } if (sb.length() > 0) { exerpt = sb.toString().trim(); } } } return exerpt; } /** * Will never return null * * @param doc * @param fieldName * @return */ private String getFieldValue(SolrDocument doc, String fieldName) { Collection<Object> values = doc.getFieldValues(fieldName); if (values == null) { return ""; } return StringUtils.join(values.toArray(), ", "); } }
lgpl-3.0
netxilia/netxilia
server/src/main/java/org/netxilia/server/rest/html/sheet/EditSheetModel.java
3600
/******************************************************************************* * * Copyright 2010 Alexandru Craciun, and individual contributors as indicated * by the @authors tag. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. ******************************************************************************/ package org.netxilia.server.rest.html.sheet; import java.util.Collection; import org.netxilia.api.display.StyleDefinition; public class EditSheetModel { private final SheetModel sheetModel; private final SheetModel summarySheetModel; private final SheetModel privateSheetModel; private final Collection<StyleDefinition> fontSizes; private final Collection<StyleDefinition> backgrounds; private final Collection<StyleDefinition> foregrounds; private final Collection<StyleDefinition> formatters; private final Collection<StyleDefinition> editors; private final int backgroundColumns; private final int foregroundColumns; public EditSheetModel(SheetModel sheetModel, SheetModel summarySheetModel, SheetModel privateSheetModel, Collection<StyleDefinition> fontSizes, Collection<StyleDefinition> backgrounds, Collection<StyleDefinition> foregrounds, Collection<StyleDefinition> formatters, Collection<StyleDefinition> editors) { this.sheetModel = sheetModel; this.summarySheetModel = summarySheetModel; this.privateSheetModel = privateSheetModel; // no need to copy the collections - they are built inside the service only this.fontSizes = fontSizes; this.backgrounds = backgrounds; this.foregrounds = foregrounds; this.formatters = formatters; this.editors = editors; backgroundColumns = (int) Math.ceil(Math.sqrt(backgrounds.size())); foregroundColumns = (int) Math.ceil(Math.sqrt(foregrounds.size())); } public SheetModel getSheetModel() { return sheetModel; } public SheetModel getSummarySheetModel() { return summarySheetModel; } public SheetModel getPrivateSheetModel() { return privateSheetModel; } public Collection<StyleDefinition> getFontSizes() { return fontSizes; } public Collection<StyleDefinition> getBackgrounds() { return backgrounds; } public StyleDefinition getFirstBackground() { return backgrounds.size() > 0 ? backgrounds.iterator().next() : null; } public Collection<StyleDefinition> getForegrounds() { return foregrounds; } public StyleDefinition getFirstForeground() { return foregrounds.size() > 0 ? foregrounds.iterator().next() : null; } public Collection<StyleDefinition> getFormatters() { return formatters; } public Collection<StyleDefinition> getEditors() { return editors; } public int getBackgroundColumns() { return backgroundColumns; } public int getForegroundColumns() { return foregroundColumns; } }
lgpl-3.0