repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
GhostMonk3408/MidgarCrusade
src/main/java/fr/toss/FF7itemsg/itemg32.java
156
package fr.toss.FF7itemsg; public class itemg32 extends FF7itemsgbase { public itemg32(int id) { super(id); setUnlocalizedName("itemg32"); } }
lgpl-2.1
hal/core
gui/src/main/java/org/jboss/as/console/client/shared/state/ReloadEvent.java
1645
package org.jboss.as.console.client.shared.state; /* * JBoss, Home of Professional Open Source * Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @author tags. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * 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, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * 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, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ import com.google.gwt.event.shared.EventHandler; import com.google.gwt.event.shared.GwtEvent; /** * * @author Heiko Braun * @date 2/7/11 */ public class ReloadEvent extends GwtEvent<ReloadEvent.ReloadListener> { public static final Type TYPE = new Type<ReloadListener>(); public ReloadEvent() { super(); } @Override public Type<ReloadListener> getAssociatedType() { return TYPE; } @Override protected void dispatch(ReloadListener listener) { listener.onReload(); } public interface ReloadListener extends EventHandler { void onReload(); } }
lgpl-2.1
dianhu/Kettle-Research
src/org/pentaho/di/trans/steps/dynamicsqlrow/DynamicSQLRow.java
9469
/* * Copyright (c) 2007 Pentaho Corporation. All rights reserved. * This software was developed by Pentaho Corporation and is provided under the terms * of the GNU Lesser General Public License, Version 2.1. You may not use * this file except in compliance with the license. If you need a copy of the license, * please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho * Data Integration. The Initial Developer is Samatar HASSAN. * * Software distributed under the GNU Lesser 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 org.pentaho.di.trans.steps.dynamicsqlrow; import java.sql.ResultSet; import org.pentaho.di.core.Const; import org.pentaho.di.core.database.Database; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.row.RowDataUtil; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; /** * Run dynamic SQL. * SQL is defined in a field. * * @author Samatar * @since 13-10-2008 */ public class DynamicSQLRow extends BaseStep implements StepInterface { private static Class<?> PKG = DynamicSQLRowMeta.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$ private DynamicSQLRowMeta meta; private DynamicSQLRowData data; public DynamicSQLRow(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans) { super(stepMeta, stepDataInterface, copyNr, transMeta, trans); } private synchronized void lookupValues(RowMetaInterface rowMeta, Object[] rowData) throws KettleException { boolean loadFromBuffer=true; if (first) { first=false; data.outputRowMeta = rowMeta.clone(); meta.getFields(data.outputRowMeta, getStepname(), new RowMetaInterface[] { meta.getTableFields(), }, null, this); loadFromBuffer=false; } if (log.isDetailed()) logDetailed(BaseMessages.getString(PKG, "DynamicSQLRow.Log.CheckingRow")+rowMeta.getString(rowData)); //$NON-NLS-1$ // get dynamic SQL statement String sql=getInputRowMeta().getString(rowData,data.indexOfSQLField); if(log.isDebug()) logDebug(BaseMessages.getString(PKG, "DynamicSQLRow.Log.SQLStatement",sql)); if(meta.isQueryOnlyOnChange()) { if(loadFromBuffer) { if(!data.previousSQL.equals(sql)) loadFromBuffer=false; } }else loadFromBuffer=false; if(loadFromBuffer) { incrementLinesInput(); if(!data.skipPreviousRow) { Object[] newRow = RowDataUtil.resizeArray(rowData, data.outputRowMeta.size()); int newIndex = rowMeta.size(); RowMetaInterface addMeta = data.db.getReturnRowMeta(); // read from Buffer for (int p=0;p<data.previousrowbuffer.size();p++) { Object[] getBufferRow=(Object[])data.previousrowbuffer.get(p); for (int i=0;i<addMeta.size();i++) { newRow[newIndex++] = getBufferRow[i]; } putRow(data.outputRowMeta,data.outputRowMeta.cloneRow(newRow)); } } }else { if(meta.isQueryOnlyOnChange()) data.previousrowbuffer.clear(); // Set the values on the prepared statement (for faster exec.) ResultSet rs = data.db.openQuery(sql); // Get a row from the database... Object[] add = data.db.getRow(rs); RowMetaInterface addMeta = data.db.getReturnRowMeta(); incrementLinesInput(); int counter = 0; while (add!=null && (meta.getRowLimit()==0 || counter<meta.getRowLimit())) { counter++; Object[] newRow = RowDataUtil.resizeArray(rowData, data.outputRowMeta.size()); int newIndex = rowMeta.size(); for (int i=0;i<addMeta.size();i++) { newRow[newIndex++] = add[i]; } // we have to clone, otherwise we only get the last new value putRow(data.outputRowMeta, data.outputRowMeta.cloneRow(newRow)); if(meta.isQueryOnlyOnChange()) { // add row to the previous rows buffer data.previousrowbuffer.add(add); data.skipPreviousRow=false; } if (log.isRowLevel()) logRowlevel(BaseMessages.getString(PKG, "DynamicSQLRow.Log.PutoutRow")+data.outputRowMeta.getString(newRow)); //$NON-NLS-1$ // Get a new row if (meta.getRowLimit()==0 || counter<meta.getRowLimit()) { add = data.db.getRow(rs); incrementLinesInput(); } } // Nothing found? Perhaps we have to put something out after all? if (counter==0 && meta.isOuterJoin()) { if (data.notfound==null) { data.notfound = new Object[data.db.getReturnRowMeta().size()]; } Object[] newRow = RowDataUtil.resizeArray(rowData, data.outputRowMeta.size()); int newIndex = rowMeta.size(); for (int i=0;i<data.notfound.length;i++) { newRow[newIndex++] = data.notfound[i]; } putRow(data.outputRowMeta, newRow); if(meta.isQueryOnlyOnChange()) { // add row to the previous rows buffer data.previousrowbuffer.add(data.notfound); data.skipPreviousRow=false; } } else { if(meta.isQueryOnlyOnChange() && counter==0 && !meta.isOuterJoin()) { data.skipPreviousRow=true; } } if(data.db!=null) data.db.closeQuery(rs); } // Save current parameters value as previous ones if(meta.isQueryOnlyOnChange()) { data.previousSQL= sql; } } public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta=(DynamicSQLRowMeta)smi; data=(DynamicSQLRowData)sdi; Object[] r=getRow(); // Get row from input rowset & set row busy! if (r==null) // no more input to be expected... { setOutputDone(); return false; } if (first) { if(Const.isEmpty(meta.getSQLFieldName())) throw new KettleException(BaseMessages.getString(PKG, "DynamicSQLRow.Exception.SQLFieldNameEmpty")); if(Const.isEmpty(meta.getSql())) throw new KettleException(BaseMessages.getString(PKG, "DynamicSQLRow.Exception.SQLEmpty")); // cache the position of the field if (data.indexOfSQLField<0) { data.indexOfSQLField =getInputRowMeta().indexOfValue(meta.getSQLFieldName()); if (data.indexOfSQLField<0) { // The field is unreachable ! throw new KettleException(BaseMessages.getString(PKG, "DynamicSQLRow.Exception.FieldNotFound",meta.getSQLFieldName())); //$NON-NLS-1$ //$NON-NLS-2$ } } } try { lookupValues(getInputRowMeta(), r); if (checkFeedback(getLinesRead())) { if(log.isDetailed()) logDetailed(BaseMessages.getString(PKG, "DynamicSQLRow.Log.LineNumber")+getLinesRead()); //$NON-NLS-1$ } } catch(KettleException e) { boolean sendToErrorRow=false; String errorMessage = null; if (getStepMeta().isDoingErrorHandling()) { sendToErrorRow = true; errorMessage = e.toString(); } else { logError(BaseMessages.getString(PKG, "DynamicSQLRow.Log.ErrorInStepRunning")+e.getMessage()); //$NON-NLS-1$ setErrors(1); stopAll(); setOutputDone(); // signal end to receiver(s) return false; } if (sendToErrorRow) { // Simply add this row to the error row putError(getInputRowMeta(), r, 1, errorMessage, null, "DynamicSQLRow001"); } } return true; } /** Stop the running query */ public void stopRunning(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta=(DynamicSQLRowMeta)smi; data=(DynamicSQLRowData)sdi; if (data.db!=null && !data.isCanceled) { synchronized(data.db) { data.db.cancelQuery(); } setStopped(true); data.isCanceled=true; } } public boolean init(StepMetaInterface smi, StepDataInterface sdi) { meta=(DynamicSQLRowMeta)smi; data=(DynamicSQLRowData)sdi; if (super.init(smi, sdi)) { data.db=new Database(this, meta.getDatabaseMeta()); data.db.shareVariablesWith(this); try { if (getTransMeta().isUsingUniqueConnections()) { synchronized (getTrans()) { data.db.connect(getTrans().getThreadName(), getPartitionID()); } } else { data.db.connect(getPartitionID()); } data.db.setCommit(100); // we never get a commit, but it just turns off auto-commit. if(log.isDetailed()) logDetailed(BaseMessages.getString(PKG, "DynamicSQLRow.Log.ConnectedToDB")); //$NON-NLS-1$ data.db.setQueryLimit(meta.getRowLimit()); return true; } catch(KettleException e) { logError(BaseMessages.getString(PKG, "DynamicSQLRow.Log.DatabaseError")+e.getMessage()); //$NON-NLS-1$ if(data.db!=null) data.db.disconnect(); } } return false; } public void dispose(StepMetaInterface smi, StepDataInterface sdi) { meta = (DynamicSQLRowMeta)smi; data = (DynamicSQLRowData)sdi; if(data.db!=null) data.db.disconnect(); super.dispose(smi, sdi); } }
lgpl-2.1
pbondoer/xwiki-platform
xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/objects/ListProperty.java
10384
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package com.xpn.xwiki.objects; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.dom4j.Element; import org.dom4j.dom.DOMElement; import org.hibernate.collection.PersistentCollection; import org.xwiki.xar.internal.property.ListXarObjectPropertySerializer; import com.xpn.xwiki.doc.merge.MergeResult; import com.xpn.xwiki.internal.AbstractNotifyOnUpdateList; import com.xpn.xwiki.internal.merge.MergeUtils; import com.xpn.xwiki.internal.objects.ListPropertyPersistentList; import com.xpn.xwiki.objects.classes.ListClass; public class ListProperty extends BaseProperty implements Cloneable { /** * We make this a notifying list, because we must propagate any value updates to the owner document. */ protected transient List<String> list; /** * @deprecated since 7.0M2. This was never used, since it is not the right place to handle separators. They are * defined in {@link ListClass} and that is where they are now handled through * {@link ListClass#toFormString(BaseProperty)}. */ @Deprecated private String formStringSeparator = ListClass.DEFAULT_SEPARATOR; /** * This is the actual list. It will be used during serialization/deserialization. */ private List<String> actualList = new ArrayList<String>(); { this.list = new NotifyList(this.actualList, this); } /** * @deprecated since 7.0M2. This was never used, since it is not the right place to handle separators. They are * defined in {@link ListClass} and that is where they are now handled through * {@link ListClass#toFormString(BaseProperty)}. */ @Deprecated public String getFormStringSeparator() { return this.formStringSeparator; } /** * @deprecated since 7.0M2. This was never used, since it is not the right place to handle separators. They are * defined in {@link ListClass} and that is where they are now handled through * {@link ListClass#toFormString(BaseProperty)}. */ @Deprecated public void setFormStringSeparator(String formStringSeparator) { this.formStringSeparator = formStringSeparator; } @Override public Object getValue() { return getList(); } @Override public void setValue(Object value) { this.setList((List<String>) value); } /** * This method is called by Hibernate to get the raw value to store in the database. Check the xwiki.hbm.xml file. * * @return the string value that is saved in the database */ public String getTextValue() { return toText(); } @Override public String toText() { // Always use the default separator because this is the value that is stored in the database (for non-relational // lists). return ListClass.getStringFromList(this.getList(), ListClass.DEFAULT_SEPARATOR); } /** * @deprecated Since 7.0M2. This method is here for a long time but it does not seem to have ever been used and it * does not bring any value compared to the existing {@link #toFormString()} method. */ @Deprecated public String toSingleFormString() { return super.toFormString(); } @Override public boolean equals(Object obj) { // Same Java object, they sure are equal if (this == obj) { return true; } if (!super.equals(obj)) { return false; } List<String> list1 = getList(); List<String> list2 = (List<String>) ((BaseProperty) obj).getValue(); // If the collection was not yet initialized by Hibernate // Let's use the super result.. if ((list1 instanceof PersistentCollection) && (!((PersistentCollection) list1).wasInitialized())) { return true; } if ((list2 instanceof PersistentCollection) && (!((PersistentCollection) list2).wasInitialized())) { return true; } if (list1.size() != list2.size()) { return false; } for (int i = 0; i < list1.size(); i++) { Object obj1 = list1.get(i); Object obj2 = list2.get(i); if (!obj1.equals(obj2)) { return false; } } return true; } @Override public ListProperty clone() { return (ListProperty) super.clone(); } @Override protected void cloneInternal(BaseProperty clone) { ListProperty property = (ListProperty) clone; property.actualList = new ArrayList<String>(); for (String entry : getList()) { property.actualList.add(entry); } property.list = new NotifyList(property.actualList, property); } public List<String> getList() { // Hibernate will not set the owner of the notify list, so we must make sure this has been done before returning // the list. if (this.list instanceof NotifyList) { ((NotifyList) this.list).setOwner(this); } else if (this.list instanceof ListPropertyPersistentList) { ((ListPropertyPersistentList) this.list).setOwner(this); } return this.list; } /** * Starting from 4.3M2, this method will copy the list passed as parameter. Due to XWIKI-8398 we must be able to * detect when the values in the list changes, so we cannot store the values in any type of list. * * @param list The list to copy. */ public void setList(List<String> list) { if (list == this.list || list == this.actualList) { // Accept a caller that sets the already existing list instance. return; } if (this.list instanceof ListPropertyPersistentList) { ListPropertyPersistentList persistentList = (ListPropertyPersistentList) this.list; if (persistentList.isWrapper(list)) { // Accept a caller that sets the already existing list instance. return; } } if (list instanceof ListPropertyPersistentList) { // This is the list wrapper we are using for hibernate. ListPropertyPersistentList persistentList = (ListPropertyPersistentList) list; this.list = persistentList; persistentList.setOwner(this); return; } if (list == null) { setValueDirty(true); this.actualList = new ArrayList(); this.list = new NotifyList(this.actualList, this); } else { this.list.clear(); this.list.addAll(list); } // In Oracle, empty string are converted to NULL. Since an undefined property is not found at all, it is // safe to assume that a retrieved NULL value should actually be an empty string. for (Iterator<String> it = this.list.iterator(); it.hasNext();) { if (it.next() == null) { it.remove(); } } } /** * {@inheritDoc} * <p> * This is important.. Otherwise we can get a stackoverflow calling toXML(). * </p> * * @see com.xpn.xwiki.objects.BaseProperty#toString() */ @Override public String toString() { if ((getList() instanceof PersistentCollection) && (!((PersistentCollection) getList()).wasInitialized())) { return ""; } return super.toString(); } @Override protected void mergeValue(Object previousValue, Object newValue, MergeResult mergeResult) { MergeUtils.mergeList((List<String>) previousValue, (List<String>) newValue, this.list, mergeResult); } /** * List implementation for updating dirty flag when updated. This will be accessed from ListPropertyUserType. */ public static class NotifyList extends AbstractNotifyOnUpdateList<String> { /** The owner list property. */ private ListProperty owner; /** The dirty flag. */ private boolean dirty; private List<String> actualList; /** * @param list {@link AbstractNotifyOnUpdateList}. */ public NotifyList(List<String> list) { super(list); this.actualList = list; } private NotifyList(List<String> list, ListProperty owner) { this(list); this.owner = owner; } @Override public void onUpdate() { setDirty(); } /** * @param owner The owner list property. */ public void setOwner(ListProperty owner) { if (this.dirty) { owner.setValueDirty(true); } this.owner = owner; owner.actualList = this.actualList; } /** * @return {@literal true} if the given argument is the instance that this list wraps. */ public boolean isWrapper(Object collection) { return this.actualList == collection; } /** * Set the dirty flag. */ private void setDirty() { if (this.owner != null) { this.owner.setValueDirty(true); } this.dirty = true; } } }
lgpl-2.1
unascribed/Walnut
src/main/java/com/unascribed/walnut/value/StringValue.java
533
package com.unascribed.walnut.value; public final class StringValue extends BaseValue<StringValue> { public final String value; public StringValue(String rawValue, String value) { super(rawValue); this.value = value; } @Override public StringValue clone() { return new StringValue(rawValue, value); } @Override protected boolean valuesEqual(StringValue that) { if (that.value == null) return this.value == null; return this.value.equals(that.value); } @Override public String get() { return value; } }
lgpl-2.1
1fechner/FeatureExtractor
sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-core/src/main/java/org/hibernate/boot/spi/AbstractDelegatingMetadata.java
6245
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.boot.spi; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.UUID; import org.hibernate.MappingException; import org.hibernate.SessionFactory; import org.hibernate.boot.SessionFactoryBuilder; import org.hibernate.boot.model.IdentifierGeneratorDefinition; import org.hibernate.boot.model.TypeDefinition; import org.hibernate.boot.model.relational.Database; import org.hibernate.cfg.annotations.NamedEntityGraphDefinition; import org.hibernate.cfg.annotations.NamedProcedureCallDefinition; import org.hibernate.dialect.function.SQLFunction; import org.hibernate.engine.ResultSetMappingDefinition; import org.hibernate.engine.spi.FilterDefinition; import org.hibernate.engine.spi.NamedQueryDefinition; import org.hibernate.engine.spi.NamedSQLQueryDefinition; import org.hibernate.id.factory.IdentifierGeneratorFactory; import org.hibernate.internal.NamedQueryRepository; import org.hibernate.internal.SessionFactoryImpl; import org.hibernate.mapping.FetchProfile; import org.hibernate.mapping.MappedSuperclass; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.Table; import org.hibernate.type.Type; import org.hibernate.type.TypeResolver; /** * Convenience base class for custom implementors of {@link MetadataImplementor} using delegation. * * @author Gunnar Morling * */ public abstract class AbstractDelegatingMetadata implements MetadataImplementor { private final MetadataImplementor delegate; public AbstractDelegatingMetadata(MetadataImplementor delegate) { this.delegate = delegate; } @Override public IdentifierGeneratorFactory getIdentifierGeneratorFactory() { return delegate.getIdentifierGeneratorFactory(); } @Override public Type getIdentifierType(String className) throws MappingException { return delegate.getIdentifierType( className ); } @Override public String getIdentifierPropertyName(String className) throws MappingException { return delegate.getIdentifierPropertyName( className ); } @Override public Type getReferencedPropertyType(String className, String propertyName) throws MappingException { return delegate.getReferencedPropertyType( className, propertyName ); } @Override public SessionFactoryBuilder getSessionFactoryBuilder() { return delegate.getSessionFactoryBuilder(); } @Override public SessionFactory buildSessionFactory() { return delegate.buildSessionFactory(); } @Override public UUID getUUID() { return delegate.getUUID(); } @Override public Database getDatabase() { return delegate.getDatabase(); } @Override public Collection<PersistentClass> getEntityBindings() { return delegate.getEntityBindings(); } @Override public PersistentClass getEntityBinding(String entityName) { return delegate.getEntityBinding( entityName ); } @Override public Collection<org.hibernate.mapping.Collection> getCollectionBindings() { return delegate.getCollectionBindings(); } @Override public org.hibernate.mapping.Collection getCollectionBinding(String role) { return delegate.getCollectionBinding( role ); } @Override public Map<String, String> getImports() { return delegate.getImports(); } @Override public NamedQueryDefinition getNamedQueryDefinition(String name) { return delegate.getNamedQueryDefinition( name ); } @Override public Collection<NamedQueryDefinition> getNamedQueryDefinitions() { return delegate.getNamedQueryDefinitions(); } @Override public NamedSQLQueryDefinition getNamedNativeQueryDefinition(String name) { return delegate.getNamedNativeQueryDefinition( name ); } @Override public Collection<NamedSQLQueryDefinition> getNamedNativeQueryDefinitions() { return delegate.getNamedNativeQueryDefinitions(); } @Override public Collection<NamedProcedureCallDefinition> getNamedProcedureCallDefinitions() { return delegate.getNamedProcedureCallDefinitions(); } @Override public ResultSetMappingDefinition getResultSetMapping(String name) { return delegate.getResultSetMapping( name ); } @Override public Map<String, ResultSetMappingDefinition> getResultSetMappingDefinitions() { return delegate.getResultSetMappingDefinitions(); } @Override public TypeDefinition getTypeDefinition(String typeName) { return delegate.getTypeDefinition( typeName ); } @Override public Map<String, FilterDefinition> getFilterDefinitions() { return delegate.getFilterDefinitions(); } @Override public FilterDefinition getFilterDefinition(String name) { return delegate.getFilterDefinition( name ); } @Override public FetchProfile getFetchProfile(String name) { return delegate.getFetchProfile( name ); } @Override public Collection<FetchProfile> getFetchProfiles() { return delegate.getFetchProfiles(); } @Override public NamedEntityGraphDefinition getNamedEntityGraph(String name) { return delegate.getNamedEntityGraph( name ); } @Override public Map<String, NamedEntityGraphDefinition> getNamedEntityGraphs() { return delegate.getNamedEntityGraphs(); } @Override public IdentifierGeneratorDefinition getIdentifierGenerator(String name) { return delegate.getIdentifierGenerator( name ); } @Override public Collection<Table> collectTableMappings() { return delegate.collectTableMappings(); } @Override public Map<String, SQLFunction> getSqlFunctionMap() { return delegate.getSqlFunctionMap(); } @Override public MetadataBuildingOptions getMetadataBuildingOptions() { return delegate.getMetadataBuildingOptions(); } @Override public TypeResolver getTypeResolver() { return delegate.getTypeResolver(); } @Override public NamedQueryRepository buildNamedQueryRepository(SessionFactoryImpl sessionFactory) { return delegate.buildNamedQueryRepository( sessionFactory ); } @Override public void validate() throws MappingException { delegate.validate(); } @Override public Set<MappedSuperclass> getMappedSuperclassMappingsCopy() { return delegate.getMappedSuperclassMappingsCopy(); } }
lgpl-2.1
tajinder-txstate/lenskit
lenskit-core/src/main/java/org/lenskit/inject/NodeInstantiator.java
3372
/* * LensKit, an open source recommender systems toolkit. * Copyright 2010-2014 LensKit Contributors. See CONTRIBUTORS.md. * Work on LensKit has been funded by the National Science Foundation under * grants IIS 05-34939, 08-08692, 08-12148, and 10-17697. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU 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 org.lenskit.inject; import com.google.common.base.Function; import com.google.common.base.Preconditions; import org.grouplens.grapht.*; import org.grouplens.grapht.graph.DAGNode; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.WillNotClose; /** * Instantiate graph nodes. * * @since 2.1 * @author <a href="http://www.grouplens.org">GroupLens Research</a> */ public abstract class NodeInstantiator implements Function<DAGNode<Component,Dependency>,Object> { /** * Create a node instantiator without a lifecycle manager. * @return A node instantiator that does not support lifecycle management. */ public static NodeInstantiator create() { return new DefaultImpl(null); } /** * Create a node instantiator with a lifecycle manager. * @param mgr The lifecycle manager to use. * @return A node instantiator that will register components with a lifecycle manager. */ public static NodeInstantiator create(@WillNotClose LifecycleManager mgr) { return new DefaultImpl(mgr); } /** * Instantiate a particular node in the graph. * * @param node The node to instantiate. * @return The instantiation of the node. */ public abstract Object instantiate(DAGNode<Component, Dependency> node) throws InjectionException; @Nonnull @Override public Object apply(@Nullable DAGNode<Component, Dependency> input) { Preconditions.checkNotNull(input, "input node"); try { return instantiate(input); } catch (InjectionException e) { throw new RuntimeException("Instantiation error on " + input.getLabel(), e); } } /** * Default implementation of the {@link org.lenskit.inject.NodeInstantiator} interface. * * @since 2.1 * @author <a href="http://www.grouplens.org">GroupLens Research</a> */ static class DefaultImpl extends NodeInstantiator { private final InjectionContainer container; DefaultImpl(LifecycleManager mgr) { container = InjectionContainer.create(CachePolicy.MEMOIZE, mgr); } @Override public Object instantiate(DAGNode<Component, Dependency> node) throws InjectionException { return container.makeInstantiator(node).instantiate(); } } }
lgpl-2.1
ME-Corp/MineralEssentials
src/main/java/io/github/mecorp/mineralessentials/creative/items/CreativeItems.java
411
package io.github.mecorp.mineralessentials.creative.items; import io.github.mecorp.mineralessentials.helper.RegisterHelper; import net.minecraft.item.Item; /** * Created by untamemadman on 13/11/2014. */ public class CreativeItems { public static Item MECorp; public static void RegisterCreativeItems() { MECorp = new ItemMECorp(); RegisterHelper.registerItem(MECorp); } }
lgpl-2.1
xwiki/xwiki-platform
xwiki-platform-core/xwiki-platform-livedata/xwiki-platform-livedata-test/xwiki-platform-livedata-test-docker/src/test/it/org/xwiki/livedata/test/ui/AllITs.java
1294
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.livedata.test.ui; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.xwiki.test.docker.junit5.UITest; /** * All UI tests for the livedata extension. * * @version $Id$ * @since 13.4RC1 * @since 12.10.9 */ @UITest class AllITs { @Nested @DisplayName("Live Data Tests") class NestedLiveDataIT extends LiveDataIT { } }
lgpl-2.1
kalidasya/osmo-mbt
osmotester/src/osmo/tester/optimizer/online/SearchEndCondition.java
350
package osmo.tester.optimizer.online; /** * Defines when {@link SearchingOptimizer} stops searching for a more optimal solution. * * @author Teemu Kanstren */ public interface SearchEndCondition { /** * @param state The current state of search. * @return True if search should end. */ public boolean shouldEnd(SearchState state); }
lgpl-2.1
lucee/extension-hibernate
source/java/src/org/lucee/extension/orm/hibernate/event/PostDeleteEventListenerImpl.java
836
package org.lucee.extension.orm.hibernate.event; import org.hibernate.event.spi.PostDeleteEvent; import org.hibernate.event.spi.PostDeleteEventListener; import org.hibernate.persister.entity.EntityPersister; import org.lucee.extension.orm.hibernate.CommonUtil; import lucee.runtime.Component; public class PostDeleteEventListenerImpl extends EventListener implements PostDeleteEventListener { private static final long serialVersionUID = -4882488527866603549L; public PostDeleteEventListenerImpl(Component component) { super(component, CommonUtil.POST_DELETE, false); } @Override public void onPostDelete(PostDeleteEvent event) { invoke(CommonUtil.POST_DELETE, event.getEntity()); } @Override public boolean requiresPostCommitHanding(EntityPersister arg0) { // TODO Auto-generated method stub return false; } }
lgpl-2.1
0-14N/soot-inflow
src/soot/jimple/infoflow/nativ/DefaultNativeCallHandler.java
2197
/******************************************************************************* * Copyright (c) 2012 Secure Software Engineering Group at EC SPRIDE. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html * * Contributors: Christian Fritz, Steven Arzt, Siegfried Rasthofer, Eric * Bodden, and others. ******************************************************************************/ package soot.jimple.infoflow.nativ; import java.util.HashSet; import java.util.List; import java.util.Set; import soot.Value; import soot.jimple.Constant; import soot.jimple.DefinitionStmt; import soot.jimple.Stmt; import soot.jimple.infoflow.data.Abstraction; import soot.jimple.infoflow.util.DataTypeHandler; public class DefaultNativeCallHandler extends NativeCallHandler { @Override public Set<Abstraction> getTaintedValues(Stmt call, Abstraction source, List<Value> params){ HashSet<Abstraction> set = new HashSet<Abstraction>(); //check some evaluated methods: //arraycopy: //arraycopy(Object src, int srcPos, Object dest, int destPos, int length) //Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array. if(call.getInvokeExpr().getMethod().toString().contains("arraycopy")){ if(params.get(0).equals(source.getAccessPath().getPlainValue())){ Abstraction abs = source.deriveNewAbstraction(params.get(2), call); set.add(abs); } }else{ //generic case: add taint to all non-primitive datatypes: for (int i = 0; i < params.size(); i++) { Value argValue = params.get(i); if (DataTypeHandler.isFieldRefOrArrayRef(argValue) && !(argValue instanceof Constant)) { Abstraction abs = source.deriveNewAbstraction(argValue, call); } } } //add the returnvalue: if(call instanceof DefinitionStmt){ DefinitionStmt dStmt = (DefinitionStmt) call; Abstraction abs = source.deriveNewAbstraction(dStmt.getLeftOp(), call); } return set; } }
lgpl-2.1
DaJackyl/TheKingdom-1.8
src/main/java/com/megathirio/thekingdom/blocks/TKBlockOre.java
1873
package com.megathirio.thekingdom.blocks; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import java.util.Random; /** * Created by TheJackyl on 11/14/2015. */ public class TKBlockOre extends Block{ private Item drop; private int meta; private int least_quantity; private int most_quantity; protected TKBlockOre(String unlocalizedName, Material material, Item drop, int meta, int least_quantity, int most_quantity) { super(material); this.drop = drop; this.meta = meta; this.least_quantity = least_quantity; this.most_quantity = most_quantity; this.setHarvestLevel("pickaxe", 1); this.setHardness(10.0f); this.setResistance(15.0f); this.setUnlocalizedName(unlocalizedName); this.setCreativeTab(CreativeTabs.tabBlock); } protected TKBlockOre(String unlocalizedName, Material material, Item drop, int least_quantity, int most_quantity) { this(unlocalizedName, material, drop, 0, least_quantity, most_quantity); } protected TKBlockOre(String unlocalizedName, Material mat, Item drop) { this(unlocalizedName, mat, drop, 1, 1); } @Override public Item getItemDropped(IBlockState blockstate, Random random, int fortune) { return this.drop; } @Override public int damageDropped(IBlockState blockstate) { return this.meta; } @Override public int quantityDropped(IBlockState blockstate, int fortune, Random random) { if (this.least_quantity >= this.most_quantity) return this.least_quantity; return this.least_quantity + random.nextInt(this.most_quantity - this.least_quantity + fortune + 1); } }
lgpl-2.1
syslog4j/syslog4j
src/main/java/org/productivity/java/syslog4j/impl/net/tcp/pool/PooledTCPNetSyslog.java
2110
package org.productivity.java.syslog4j.impl.net.tcp.pool; import org.productivity.java.syslog4j.SyslogRuntimeException; import org.productivity.java.syslog4j.impl.AbstractSyslogWriter; import org.productivity.java.syslog4j.impl.net.tcp.TCPNetSyslog; import org.productivity.java.syslog4j.impl.pool.AbstractSyslogPoolFactory; import org.productivity.java.syslog4j.impl.pool.generic.GenericSyslogPoolFactory; /** * PooledTCPNetSyslog is an extension of TCPNetSyslog which provides support * for Apache Commons Pool. * * <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy * of the LGPL license is available in the META-INF folder in all * distributions of Syslog4j and in the base directory of the "doc" ZIP.</p> * * @author &lt;syslog4j@productivity.org&gt; * @version $Id: PooledTCPNetSyslog.java,v 1.5 2008/12/10 04:30:15 cvs Exp $ */ public class PooledTCPNetSyslog extends TCPNetSyslog { private static final long serialVersionUID = 4279960451141784200L; protected AbstractSyslogPoolFactory poolFactory = null; public void initialize() throws SyslogRuntimeException { super.initialize(); this.poolFactory = createSyslogPoolFactory(); this.poolFactory.initialize(this); } protected AbstractSyslogPoolFactory createSyslogPoolFactory() { AbstractSyslogPoolFactory syslogPoolFactory = new GenericSyslogPoolFactory(); return syslogPoolFactory; } public AbstractSyslogWriter getWriter() { try { AbstractSyslogWriter syslogWriter = this.poolFactory.borrowSyslogWriter(); return syslogWriter; } catch (Exception e) { throw new SyslogRuntimeException(e); } } public void returnWriter(AbstractSyslogWriter syslogWriter) { try { this.poolFactory.returnSyslogWriter(syslogWriter); } catch (Exception e) { throw new SyslogRuntimeException(e); } } public void flush() throws SyslogRuntimeException { try { this.poolFactory.clear(); } catch (Exception e) { // } } public void shutdown() throws SyslogRuntimeException { try { this.poolFactory.close(); } catch (Exception e) { // } } }
lgpl-2.1
opensagres/xdocreport.eclipse
dynaresume/org.dynaresume.eclipse.search.ui/src/org/dynaresume/eclipse/search/ui/internal/ImageResources.java
1679
package org.dynaresume.eclipse.search.ui.internal; import java.net.URL; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.swt.graphics.Image; import org.osgi.framework.Bundle; public class ImageResources { public final static String ICONS_PATH = "icons/"; //$NON-NLS-1$ /** * Set of predefined Image Descriptors. */ private static final String PATH_OBJ_16 = ICONS_PATH + "obj16/"; //$NON-NLS-1$ //private static final String PATH_OBJ_24 = ICONS_PATH + "obj24/"; //$NON-NLS-1$ public static final String IMG_CLIENT_16 = "client_16"; public static void initialize(ImageRegistry imageRegistry) { registerImage(imageRegistry, IMG_CLIENT_16, PATH_OBJ_16 + "client.png"); } private static void registerImage(ImageRegistry registry, String key, String fileName) { try { IPath path = new Path(fileName); Bundle bundle = Activator.getDefault().getBundle(); URL url = FileLocator.find(bundle, path, null); if (url != null) { ImageDescriptor desc = ImageDescriptor.createFromURL(url); registry.put(key, desc); } } catch (Exception e) { } } public static ImageDescriptor getImageDescriptor(String key) { ImageRegistry imageRegistry = Activator.getDefault().getImageRegistry(); return imageRegistry.getDescriptor(key); } public static Image getImage(String key) { ImageRegistry imageRegistry = Activator.getDefault().getImageRegistry(); return imageRegistry.get(key); } }
lgpl-2.1
jsubercaze/parallelJGAP
src/test/java/org/jgap/impl/DefaultMutationRateCalculatorTest.java
2471
/* * This file is part of JGAP. * * JGAP offers a dual license model containing the LGPL as well as the MPL. * * For licensing information please see the file license.txt included with JGAP * or have a look at the top of class org.jgap.Chromosome which representatively * includes the JGAP license policy applicable for any file delivered with JGAP. */ package org.jgap.impl; import org.jgap.*; import junit.framework.*; /** * Tests the DefaultMutationRateCalculator class. * * @author Klaus Meffert * @since 1.1 */ public class DefaultMutationRateCalculatorTest extends JGAPTestCase { /** String containing the CVS revision. Read out via reflection!*/ private static final String CVS_REVISION = "$Revision: 1.13 $"; public static Test suite() { TestSuite suite = new TestSuite(DefaultMutationRateCalculatorTest.class); return suite; } public void setUp() { super.setUp(); // reset the configurational parameters set Configuration.reset(); } /** * @throws Exception * * @author Klaus Meffert */ public void testCalculateCurrentRate_0() throws Exception { IUniversalRateCalculator calc = new DefaultMutationRateCalculator(conf); Gene gene = new IntegerGene(conf, 1, 5); Chromosome chrom = new Chromosome(conf, gene, 50); conf.setSampleChromosome(chrom); int rate = calc.calculateCurrentRate(); assertEquals(conf.getChromosomeSize(), rate); } /** * @throws Exception * * @author Klaus Meffert * @since 3.0 */ public void testCalculateCurrentRate_1() throws Exception { IUniversalRateCalculator calc = new DefaultMutationRateCalculator(conf); Gene gene = new IntegerGene(conf, 1, 5); Chromosome chrom = new Chromosome(conf, gene, 30); conf.setSampleChromosome(chrom); int rate = calc.calculateCurrentRate(); assertEquals(conf.getChromosomeSize(), rate); } /** * If there are zero chromosomes in the config., the mutation rate * nevertheless should be 1, because Random needs positive integers as input * (see MutationOperator.operate for calling Random class) * @throws Exception * * @author Klaus Meffert */ public void testCalculateCurrentRate_2() throws Exception { IUniversalRateCalculator calc = new DefaultMutationRateCalculator(conf); int rate = calc.calculateCurrentRate(); assertEquals(1, rate); } }
lgpl-2.1
agentlab/powerloom-osgi
plugins/edu.isi.stella/src/edu/isi/stella/UndefinedClassException.java
3488
// -*- Mode: Java -*- // // UndefinedClassException.java /* +---------------------------- BEGIN LICENSE BLOCK ---------------------------+ | | | Version: MPL 1.1/GPL 2.0/LGPL 2.1 | | | | The contents of this file are subject to the Mozilla Public License | | Version 1.1 (the "License"); you may not use this file except in | | compliance with the License. You may obtain a copy of the License at | | http://www.mozilla.org/MPL/ | | | | Software distributed under the License is distributed on an "AS IS" basis, | | WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License | | for the specific language governing rights and limitations under the | | License. | | | | The Original Code is the STELLA Programming Language. | | | | The Initial Developer of the Original Code is | | UNIVERSITY OF SOUTHERN CALIFORNIA, INFORMATION SCIENCES INSTITUTE | | 4676 Admiralty Way, Marina Del Rey, California 90292, U.S.A. | | | | Portions created by the Initial Developer are Copyright (C) 1996-2012 | | the Initial Developer. All Rights Reserved. | | | | Contributor(s): | | | | Alternatively, the contents of this file may be used under the terms of | | either the GNU General Public License Version 2 or later (the "GPL"), or | | the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), | | in which case the provisions of the GPL or the LGPL are applicable instead | | of those above. If you wish to allow use of your version of this file only | | under the terms of either the GPL or the LGPL, and not to allow others to | | use your version of this file under the terms of the MPL, indicate your | | decision by deleting the provisions above and replace them with the notice | | and other provisions required by the GPL or the LGPL. If you do not delete | | the provisions above, a recipient may use your version of this file under | | the terms of any one of the MPL, the GPL or the LGPL. | | | +---------------------------- END LICENSE BLOCK -----------------------------+ */ package edu.isi.stella; import edu.isi.stella.javalib.*; public class UndefinedClassException extends NoSuchObjectException { public UndefinedClassException (String message) { super(message); } public static UndefinedClassException newUndefinedClassException(String message) { { UndefinedClassException self = null; self = new UndefinedClassException(message); return (self); } } }
lgpl-2.1
esig/dss
dss-asic-xades/src/test/java/eu/europa/esig/dss/asic/xades/signature/asice/ASiCEXAdESLevelBNestedCounterSignatureTest.java
8476
/** * DSS - Digital Signature Services * Copyright (C) 2015 European Commission, provided under the CEF programme * * This file is part of the "DSS - Digital Signature Services" project. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package eu.europa.esig.dss.asic.xades.signature.asice; import eu.europa.esig.dss.asic.xades.ASiCWithXAdESSignatureParameters; import eu.europa.esig.dss.asic.xades.signature.ASiCWithXAdESService; import eu.europa.esig.dss.asic.xades.validation.AbstractASiCWithXAdESTestValidation; import eu.europa.esig.dss.diagnostic.DiagnosticData; import eu.europa.esig.dss.diagnostic.SignatureWrapper; import eu.europa.esig.dss.enumerations.ASiCContainerType; import eu.europa.esig.dss.enumerations.SignatureLevel; import eu.europa.esig.dss.model.DSSDocument; import eu.europa.esig.dss.model.InMemoryDocument; import eu.europa.esig.dss.model.MimeType; import eu.europa.esig.dss.model.SignatureValue; import eu.europa.esig.dss.model.ToBeSigned; import eu.europa.esig.dss.utils.Utils; import eu.europa.esig.dss.validation.AdvancedSignature; import eu.europa.esig.dss.validation.SignedDocumentValidator; import eu.europa.esig.dss.validation.reports.Reports; import eu.europa.esig.dss.xades.signature.XAdESCounterSignatureParameters; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.Date; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; public class ASiCEXAdESLevelBNestedCounterSignatureTest extends AbstractASiCWithXAdESTestValidation { private DSSDocument documentToSign; private ASiCWithXAdESService service; private ASiCWithXAdESSignatureParameters signatureParameters; private XAdESCounterSignatureParameters counterSignatureParameters; @BeforeEach public void init() { documentToSign = new InMemoryDocument("Hello World !".getBytes(), "test.text", MimeType.TEXT); service = new ASiCWithXAdESService(getCompleteCertificateVerifier()); signatureParameters = new ASiCWithXAdESSignatureParameters(); signatureParameters.bLevel().setSigningDate(new Date()); signatureParameters.setSigningCertificate(getSigningCert()); signatureParameters.setCertificateChain(getCertificateChain()); signatureParameters.setSignatureLevel(SignatureLevel.XAdES_BASELINE_B); signatureParameters.aSiC().setContainerType(ASiCContainerType.ASiC_E); counterSignatureParameters = new XAdESCounterSignatureParameters(); counterSignatureParameters.bLevel().setSigningDate(new Date()); counterSignatureParameters.setSigningCertificate(getSigningCert()); counterSignatureParameters.setCertificateChain(getCertificateChain()); counterSignatureParameters.setSignatureLevel(SignatureLevel.XAdES_BASELINE_B); } @Test public void test() throws Exception { ToBeSigned dataToSign = service.getDataToSign(documentToSign, signatureParameters); SignatureValue signatureValue = getToken().sign(dataToSign, signatureParameters.getDigestAlgorithm(), signatureParameters.getMaskGenerationFunction(), getPrivateKeyEntry()); DSSDocument signedDocument = service.signDocument(documentToSign, signatureParameters, signatureValue); Exception exception = assertThrows(NullPointerException.class, () -> service.getDataToBeCounterSigned(signedDocument, counterSignatureParameters)); assertEquals("The Id of a signature to be counter signed shall be defined! " + "Please use SerializableCounterSignatureParameters.setSignatureIdToCounterSign(signatureId) method.", exception.getMessage()); SignedDocumentValidator validator = getValidator(signedDocument); counterSignatureParameters.setSignatureIdToCounterSign(validator.getSignatures().get(0).getId()); ToBeSigned dataToBeCounterSigned = service.getDataToBeCounterSigned(signedDocument, counterSignatureParameters); signatureValue = getToken().sign(dataToBeCounterSigned, counterSignatureParameters.getDigestAlgorithm(), counterSignatureParameters.getMaskGenerationFunction(), getPrivateKeyEntry()); DSSDocument counterSignedSignature = service.counterSignSignature(signedDocument, counterSignatureParameters, signatureValue); // counterSignedSignature.save("target/counterSignedSignature.sce"); validator = getValidator(counterSignedSignature); List<AdvancedSignature> signatures = validator.getSignatures(); assertEquals(1, signatures.size()); AdvancedSignature advancedSignature = signatures.get(0); List<AdvancedSignature> counterSignatures = advancedSignature.getCounterSignatures(); assertEquals(1, counterSignatures.size()); AdvancedSignature counterSignature = counterSignatures.get(0); assertNotNull(counterSignature.getMasterSignature()); assertEquals(0, counterSignature.getCounterSignatures().size()); counterSignatureParameters.bLevel().setSigningDate(new Date()); counterSignatureParameters.setSignatureIdToCounterSign(counterSignature.getId()); dataToBeCounterSigned = service.getDataToBeCounterSigned(counterSignedSignature, counterSignatureParameters); signatureValue = getToken().sign(dataToBeCounterSigned, counterSignatureParameters.getDigestAlgorithm(), counterSignatureParameters.getMaskGenerationFunction(), getPrivateKeyEntry()); DSSDocument nestedCounterSignedSignature = service.counterSignSignature(counterSignedSignature, counterSignatureParameters, signatureValue); // nestedCounterSignedSignature.save("target/nestedCounterSignature.sce"); validator = getValidator(nestedCounterSignedSignature); signatures = validator.getSignatures(); assertEquals(1, signatures.size()); advancedSignature = signatures.get(0); counterSignatures = advancedSignature.getCounterSignatures(); assertEquals(1, counterSignatures.size()); counterSignature = counterSignatures.get(0); assertNotNull(counterSignature.getMasterSignature()); assertEquals(1, counterSignature.getCounterSignatures().size()); Reports reports = verify(nestedCounterSignedSignature); DiagnosticData diagnosticData = reports.getDiagnosticData(); List<SignatureWrapper> signatureWrappers = diagnosticData.getSignatures(); assertEquals(3, signatureWrappers.size()); boolean rootSignatureFound = false; boolean counterSignatureFound = false; boolean nestedCounterSignatureFound = false; for (SignatureWrapper signatureWrapper : signatureWrappers) { if (!signatureWrapper.isCounterSignature()) { rootSignatureFound = true; } else if (signatureWrapper.getParent() != null && signatureWrapper.getParent().getParent() == null) { counterSignatureFound = true; } else if (signatureWrapper.getParent() != null && signatureWrapper.getParent().getParent() != null) { nestedCounterSignatureFound = true; } } assertTrue(rootSignatureFound); assertTrue(counterSignatureFound); assertTrue(nestedCounterSignatureFound); } @Override protected void verifyOriginalDocuments(SignedDocumentValidator validator, DiagnosticData diagnosticData) { List<String> signatureIdList = diagnosticData.getSignatureIdList(); for (String signatureId : signatureIdList) { if (!diagnosticData.getSignatureById(signatureId).isCounterSignature() && diagnosticData.isBLevelTechnicallyValid(signatureId)) { List<DSSDocument> retrievedOriginalDocuments = validator.getOriginalDocuments(signatureId); assertTrue(Utils.isCollectionNotEmpty(retrievedOriginalDocuments)); } } } @Override public void validate() { // do nothing } @Override protected DSSDocument getSignedDocument() { return null; } @Override protected String getSigningAlias() { return GOOD_USER; } }
lgpl-2.1
datacleaner/AnalyzerBeans
components/reference-data/src/test/java/org/eobjects/analyzer/beans/transform/DateMaskMatcherTransformerTest.java
2196
/** * AnalyzerBeans * Copyright (C) 2014 Neopost - Customer Information Management * * 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.eobjects.analyzer.beans.transform; import java.util.Arrays; import org.eobjects.analyzer.beans.api.OutputColumns; import org.eobjects.analyzer.data.MockInputColumn; import org.eobjects.analyzer.data.MockInputRow; import junit.framework.TestCase; public class DateMaskMatcherTransformerTest extends TestCase { public void testSimpleScenario() throws Exception { MockInputColumn<String> col = new MockInputColumn<String>("foo", String.class); DateMaskMatcherTransformer t = new DateMaskMatcherTransformer(col); t.setDateMasks(new String[] { "yyyy-MM-dd", "yyyy-dd-MM" }); t.init(); OutputColumns outputColumns = t.getOutputColumns(); assertEquals(2, outputColumns.getColumnCount()); assertEquals("foo 'yyyy-MM-dd'", outputColumns.getColumnName(0)); assertEquals("foo 'yyyy-dd-MM'", outputColumns.getColumnName(1)); assertEquals("[true, false]", Arrays.toString(t.transform(new MockInputRow().put(col, "2010-03-21")))); assertEquals("[false, false]", Arrays.toString(t.transform(new MockInputRow().put(col, "hello world")))); assertEquals("[false, false]", Arrays.toString(t.transform(new MockInputRow().put(col, null)))); assertEquals("[true, true]", Arrays.toString(t.transform(new MockInputRow().put(col, "2010-03-11")))); assertEquals("[false, false]", Arrays.toString(t.transform(new MockInputRow().put(col, "2010/03/21")))); } }
lgpl-3.0
smartfeeling/smartly
smartly_package_01_mongo/src/org/smartly/packages/mongo/config/Deployer.java
494
package org.smartly.packages.mongo.config; import org.smartly.commons.io.repository.deploy.FileDeployer; public class Deployer extends FileDeployer { public Deployer(final String targetFolder) { super("", targetFolder, false, false, false); } @Override public byte[] compile(byte[] data, final String filename) { return data; } @Override public byte[] compress(byte[] data, final String filename) { return null; } }
lgpl-3.0
yawlfoundation/yawl
src/org/yawlfoundation/yawl/elements/predicate/PredicateEvaluatorCache.java
2476
/* * Copyright (c) 2004-2020 The YAWL Foundation. All rights reserved. * The YAWL Foundation is a collaboration of individuals and * organisations who are committed to improving workflow technology. * * This file is part of YAWL. YAWL 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. * * YAWL 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 YAWL. If not, see <http://www.gnu.org/licenses/>. */ package org.yawlfoundation.yawl.elements.predicate; import org.yawlfoundation.yawl.elements.YDecomposition; import org.yawlfoundation.yawl.elements.state.YIdentifier; import java.util.Set; /** * @author Michael Adams * @date 5/12/12 */ public class PredicateEvaluatorCache { private static Set<PredicateEvaluator> _evaluators; public static String process(YDecomposition decomposition, String predicate, YIdentifier token) { PredicateEvaluator evaluator = getEvaluator(predicate); while (evaluator != null) { predicate = evaluator.replace(decomposition, predicate, token); evaluator = getEvaluator(predicate); } return predicate; } public static String substitute(String predicate) { PredicateEvaluator evaluator = getEvaluator(predicate); while (evaluator != null) { predicate = evaluator.substituteDefaults(predicate); evaluator = getEvaluator(predicate); } return predicate; } public static boolean accept(String predicate) { return getEvaluator(predicate) != null; } private static PredicateEvaluator getEvaluator(String predicate) { try { if (_evaluators == null) { _evaluators = PredicateEvaluatorFactory.getInstances(); } for (PredicateEvaluator evaluator : _evaluators) { if (evaluator.accept(predicate)) { return evaluator; } } } catch (Exception e) { // fall through to null } return null; } }
lgpl-3.0
dana-i2cat/opennaas-routing-nfv
extensions/bundles/vcpe/src/main/java/org/opennaas/extensions/vcpe/capability/ip/VCPEIPCapability.java
7552
package org.opennaas.extensions.vcpe.capability.ip; import static com.google.common.collect.Iterables.filter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.opennaas.core.resources.IResource; import org.opennaas.core.resources.ResourceException; import org.opennaas.core.resources.action.IAction; import org.opennaas.core.resources.action.IActionSet; import org.opennaas.core.resources.capability.AbstractCapability; import org.opennaas.core.resources.capability.CapabilityException; import org.opennaas.core.resources.descriptor.CapabilityDescriptor; import org.opennaas.core.resources.protocol.ProtocolException; import org.opennaas.extensions.router.capability.ip.IIPCapability; import org.opennaas.extensions.router.model.IPProtocolEndpoint; import org.opennaas.extensions.router.model.LogicalPort; import org.opennaas.extensions.vcpe.Activator; import org.opennaas.extensions.vcpe.capability.VCPEToRouterModelTranslator; import org.opennaas.extensions.vcpe.capability.builder.builders.helpers.GenericHelper; import org.opennaas.extensions.vcpe.manager.templates.sp.SPTemplateConstants; import org.opennaas.extensions.vcpe.model.Interface; import org.opennaas.extensions.vcpe.model.Router; import org.opennaas.extensions.vcpe.model.VCPENetworkModel; import org.opennaas.extensions.vcpe.model.helper.VCPENetworkModelHelper; public class VCPEIPCapability extends AbstractCapability implements IVCPEIPCapability { public static final String CAPABILITY_TYPE = "vcpenet_ip"; private Log log = LogFactory.getLog(VCPEIPCapability.class); private String resourceId; /** * @param descriptor * @param resourceId */ public VCPEIPCapability(CapabilityDescriptor descriptor, String resourceId) { super(descriptor); this.resourceId = resourceId; } /* * (non-Javadoc) * * @see org.opennaas.core.resources.capability.AbstractCapability#activate() */ @Override public void activate() throws CapabilityException { registerService(Activator.getContext(), CAPABILITY_TYPE, getResourceType(), getResourceName(), IVCPEIPCapability.class.getName()); setState(State.ACTIVE); } /* * (non-Javadoc) * * @see org.opennaas.core.resources.capability.AbstractCapability#deactivate() */ @Override public void deactivate() throws CapabilityException { setState(State.INACTIVE); registration.unregister(); super.deactivate(); } /* * (non-Javadoc) * * @see org.opennaas.core.resources.capability.ICapability#getCapabilityName() */ @Override public String getCapabilityName() { return CAPABILITY_TYPE; } /* * (non-Javadoc) * * @see org.opennaas.core.resources.capability.AbstractCapability#queueAction(org.opennaas.core.resources.action.IAction) */ @Override public void queueAction(IAction action) throws CapabilityException { throw new UnsupportedOperationException(); } /* * (non-Javadoc) * * @see org.opennaas.core.resources.capability.AbstractCapability#getActionSet() */ @Override public IActionSet getActionSet() throws CapabilityException { throw new UnsupportedOperationException(); } /* * (non-Javadoc) * * @see org.opennaas.extensions.vcpe.capability.ip.IVCPEIPCapability#updateIps(org.opennaas.extensions.vcpe.model.VCPENetworkModel) */ @Override public void updateIps(VCPENetworkModel updatedModel) throws CapabilityException { log.info("Update the Ip's"); if (!((VCPENetworkModel) resource.getModel()).isCreated()) throw new CapabilityException("VCPE has not been created"); VCPENetworkModel currentModel = (VCPENetworkModel) resource.getModel(); // launch commands try { for (Router router : filter(updatedModel.getElements(), Router.class)) { if (router.getTemplateName().equals(SPTemplateConstants.VCPE1_ROUTER) || router.getTemplateName().equals(SPTemplateConstants.VCPE2_ROUTER)) { for (Interface iface : router.getInterfaces()) { Interface outDatedIface = (Interface) VCPENetworkModelHelper.getElementByTemplateName(currentModel, iface.getTemplateName()); if (!outDatedIface.getIpAddress().equals(iface.getIpAddress())) { setIP(router, outDatedIface, iface.getIpAddress(), currentModel); } } } } } catch (ResourceException e) { throw new CapabilityException(e); } // execute queues try { executeLogicalRouters(currentModel); executePhysicalRouters(currentModel); } catch (Exception e) { throw new CapabilityException(e); } // update IP addresses in model for (Router router : filter(updatedModel.getElements(), Router.class)) { for (Interface iface : router.getInterfaces()) { if (router.getTemplateName().equals(SPTemplateConstants.VCPE1_ROUTER) || router.getTemplateName().equals(SPTemplateConstants.VCPE2_ROUTER)) { Interface outDatedIface = (Interface) VCPENetworkModelHelper.getElementByTemplateName(currentModel, iface.getTemplateName()); if (!outDatedIface.getIpAddress().equals(iface.getIpAddress())) { outDatedIface.setIpAddress(iface.getIpAddress()); } } } } } /** * @param model * @throws ResourceException * @throws ProtocolException */ private void executePhysicalRouters(VCPENetworkModel model) throws ResourceException, ProtocolException { Router phy1 = (Router) VCPENetworkModelHelper.getElementByTemplateName(model, SPTemplateConstants.CPE1_PHY_ROUTER); Router phy2 = (Router) VCPENetworkModelHelper.getElementByTemplateName(model, SPTemplateConstants.CPE2_PHY_ROUTER); IResource phyResource1 = GenericHelper.getResourceManager().getResource( GenericHelper.getResourceManager().getIdentifierFromResourceName("router", phy1.getName())); IResource phyResource2 = GenericHelper.getResourceManager().getResource( GenericHelper.getResourceManager().getIdentifierFromResourceName("router", phy2.getName())); GenericHelper.executeQueue(phyResource1); GenericHelper.executeQueue(phyResource2); } /** * @param model * @throws ResourceException * @throws ProtocolException */ private void executeLogicalRouters(VCPENetworkModel model) throws ResourceException, ProtocolException { Router lr1 = (Router) VCPENetworkModelHelper.getElementByTemplateName(model, SPTemplateConstants.VCPE1_ROUTER); Router lr2 = (Router) VCPENetworkModelHelper.getElementByTemplateName(model, SPTemplateConstants.VCPE2_ROUTER); IResource lrResource1 = GenericHelper.getResourceManager().getResource( GenericHelper.getResourceManager().getIdentifierFromResourceName("router", lr1.getName())); IResource lrResource2 = GenericHelper.getResourceManager().getResource( GenericHelper.getResourceManager().getIdentifierFromResourceName("router", lr2.getName())); GenericHelper.executeQueue(lrResource1); GenericHelper.executeQueue(lrResource2); } /** * @param router * @param iface * @param ipAddress * @param model * @throws ResourceException */ private void setIP(Router router, Interface iface, String ipAddress, VCPENetworkModel model) throws ResourceException { IResource routerResource = GenericHelper.getResourceManager().getResource( GenericHelper.getResourceManager().getIdentifierFromResourceName("router", router.getName())); IIPCapability capability = (IIPCapability) routerResource.getCapabilityByInterface(IIPCapability.class); LogicalPort port = VCPEToRouterModelTranslator.vCPEInterfaceToLogicalPort(iface, model); IPProtocolEndpoint ipPEP = VCPEToRouterModelTranslator.ipAddressToProtocolEndpoint(ipAddress); capability.setIPv4(port, ipPEP); } }
lgpl-3.0
BtoBastian/Javacord
javacord-api/src/main/java/org/javacord/api/event/server/ServerLeaveEvent.java
131
package org.javacord.api.event.server; /** * A server leave event. */ public interface ServerLeaveEvent extends ServerEvent { }
lgpl-3.0
JimiHFord/pj2
lib/edu/rit/io/FileResource.java
3345
//****************************************************************************** // // File: FileResource.java // Package: edu.rit.io // Unit: Class edu.rit.io.FileResource // // This Java source file is copyright (C) 2014 by Alan Kaminsky. All rights // reserved. For further information, contact the author, Alan Kaminsky, at // ark@cs.rit.edu. // // This Java source file is part of the Parallel Java 2 Library ("PJ2"). PJ2 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. // // PJ2 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. // // A copy of the GNU General Public License is provided in the file gpl.txt. You // may also obtain a copy of the GNU General Public License on the World Wide // Web at http://www.gnu.org/licenses/gpl.html. // //****************************************************************************** package edu.rit.io; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; 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.io.File; import java.net.URL; /** * Class FileResource encapsulates a file stored as a resource in the Java class * path. * * @author Alan Kaminsky * @version 19-Feb-2014 */ public class FileResource { // Hidden data members. private File file; // Exported constructors. /** * Construct a new file resource. * * @param name Resource name relative to the Java class path. * * @exception IOException * Thrown if an I/O error occurred. */ public FileResource (String name) throws IOException { // Get URL for resource. URL url = Thread.currentThread().getContextClassLoader() .getResource (name); if (url == null) throw new FileNotFoundException (String.format ("FileResource(): Resource \"%s\" not found", name)); // For a file: URL, use the file itself. if (url.getProtocol().equals ("file")) { file = new File (url.getPath()); } // For any other URL, copy the resource into a temporary file, which // will be deleted when the JVM exits. else { name = new File (name) .getName(); int i = name.lastIndexOf ('.'); String fprefix = i == -1 ? name : name.substring (0, i); String fsuffix = i == -1 ? null : name.substring (i); file = File.createTempFile (fprefix+"_tmp", fsuffix); OutputStream out = new BufferedOutputStream (new FileOutputStream (file)); InputStream in = new BufferedInputStream (url.openStream()); while ((i = in.read()) != -1) out.write (i); out.close(); in.close(); file.deleteOnExit(); } } // Exported operations. /** * Get the file for reading the file resource. * * @return File. */ public File file() { return file; } /** * Get the file name for reading the file resource. * * @return File name. */ public String filename() { return file.getPath(); } }
lgpl-3.0
almondtools/testrecorder
testrecorder-agent/src/main/java/net/amygdalum/testrecorder/types/SerializedStructuralType.java
181
package net.amygdalum.testrecorder.types; import java.util.List; public interface SerializedStructuralType extends SerializedReferenceType { List<SerializedField> fields(); }
lgpl-3.0
Metaswitch/fmj
src/javax/media/StopEvent.java
922
package javax.media; /** * Standard JMF class -- see <a href= * "http://java.sun.com/products/java-media/jmf/2.1.1/apidocs/javax/media/StopEvent.html" * target="_blank">this class in the JMF Javadoc</a>. Complete. * * @author Ken Larson * */ public class StopEvent extends TransitionEvent { private Time mediaTime; public StopEvent(Controller from, int previous, int current, int target, Time mediaTime) { super(from, previous, current, target); this.mediaTime = mediaTime; } public Time getMediaTime() { return mediaTime; } @Override public String toString() { return getClass().getName() + "[source=" + getSource() + ",previousState=" + getPreviousState() + ",currentState=" + getCurrentState() + ",targetState=" + getTargetState() + ",mediaTime=" + mediaTime + "]"; } }
lgpl-3.0
leonhad/paradoxdriver
src/main/java/com/googlecode/paradox/ParadoxResultSet.java
49730
/* * Copyright (C) 2009 Leonardo Alves da Costa * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any * later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public * License for more details. You should have received a copy of the GNU General Public License along with this * program. If not, see <http://www.gnu.org/licenses/>. */ package com.googlecode.paradox; import com.googlecode.paradox.exceptions.ParadoxException; import com.googlecode.paradox.exceptions.ParadoxNotSupportedException; import com.googlecode.paradox.metadata.ParadoxResultSetMetaData; import com.googlecode.paradox.results.Column; import com.googlecode.paradox.rowset.DataNavigation; import com.googlecode.paradox.rowset.ParadoxBlob; import com.googlecode.paradox.rowset.ParadoxClob; import com.googlecode.paradox.rowset.ValuesConverter; import com.googlecode.paradox.utils.Utils; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.lang.ref.WeakReference; import java.math.BigDecimal; import java.math.RoundingMode; import java.net.URL; import java.nio.charset.StandardCharsets; import java.sql.*; import java.util.Calendar; import java.util.List; import java.util.Map; /** * JDBC ResultSet implementation. * * @version 1.6 * @since 1.0 */ public final class ParadoxResultSet implements ResultSet { /** * Default fetch size. */ private static final int FETCH_SIZE = 10; /** * {@link ResultSet} columns. */ private final List<Column> columns; /** * This {@link ResultSet} {@link Statement}. */ private final WeakReference<Statement> statement; /** * Facade to navigate in data values. */ private final DataNavigation dataNavigation; /** * The connection information. */ private ConnectionInfo connectionInfo; /** * The amount of rows fetched. */ private int fetchSize = ParadoxResultSet.FETCH_SIZE; /** * Result set type. */ private int type = ResultSet.TYPE_SCROLL_INSENSITIVE; /** * Concurrency type. */ private int concurrency = ResultSet.CONCUR_READ_ONLY; /** * Creates a new {@link ResultSet}. * * @param connectionInfo the connection information. * @param statement the {@link Statement} for this {@link ResultSet}. * @param values row and column values. * @param columns the columns name. */ public ParadoxResultSet(final ConnectionInfo connectionInfo, final Statement statement, final List<? extends Object[]> values, final List<Column> columns) { this.statement = new WeakReference<>(statement); this.columns = columns; this.connectionInfo = connectionInfo; // Fix column indexes. int index = 1; for (final Column column : this.columns) { if (!column.isHidden()) { column.setIndex(index); index++; } } this.dataNavigation = new DataNavigation(columns, values); } /** * {@inheritDoc}. */ @Override public boolean absolute(final int row) throws SQLException { return dataNavigation.absolute(row); } /** * {@inheritDoc}. */ @Override public void afterLast() throws SQLException { this.dataNavigation.afterLast(); } /** * {@inheritDoc}. */ @Override public void beforeFirst() throws SQLException { this.dataNavigation.beforeFirst(); } /** * {@inheritDoc}. */ @Override public void cancelRowUpdates() throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void clearWarnings() { // Not used. } /** * {@inheritDoc}. */ @Override public void close() { this.dataNavigation.close(); this.connectionInfo = null; } /** * {@inheritDoc}. */ @Override public void deleteRow() throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public int findColumn(final String columnLabel) throws SQLException { for (final Column column : this.columns) { if (column.getName().equalsIgnoreCase(columnLabel)) { return column.getIndex(); } } throw new ParadoxException(ParadoxException.Error.INVALID_COLUMN, columnLabel); } /** * {@inheritDoc}. */ @Override public boolean first() throws SQLException { return this.dataNavigation.first(); } /** * {@inheritDoc}. */ @Override public Array getArray(final int columnIndex) { return null; } /** * {@inheritDoc}. */ @Override public Array getArray(final String columnLabel) { return null; } /** * {@inheritDoc}. */ @Override public InputStream getAsciiStream(final int columnIndex) throws SQLException { final String val = ValuesConverter.getString(dataNavigation.getColumnValue(columnIndex), connectionInfo); if (val != null) { new ByteArrayInputStream(val.getBytes(StandardCharsets.UTF_8)); } return null; } /** * {@inheritDoc}. */ @Override public InputStream getAsciiStream(final String columnLabel) throws SQLException { return this.getAsciiStream(this.findColumn(columnLabel)); } /** * {@inheritDoc}. */ @Override public BigDecimal getBigDecimal(final int columnIndex) throws SQLException { return ValuesConverter.getBigDecimal(dataNavigation.getColumnValue(columnIndex), connectionInfo); } /** * {@inheritDoc}. * * @deprecated this method is only used for JDBC compatibility. */ @SuppressWarnings("squid:S1133") @Deprecated @Override public BigDecimal getBigDecimal(final int columnIndex, final int scale) throws SQLException { final BigDecimal value = this.getBigDecimal(columnIndex); return value.setScale(scale, RoundingMode.HALF_DOWN); } /** * {@inheritDoc}. */ @Override public BigDecimal getBigDecimal(final String columnLabel) throws SQLException { return this.getBigDecimal(this.findColumn(columnLabel)); } /** * {@inheritDoc}. * * @deprecated this method is only used for JDBC compatibility. */ @SuppressWarnings("squid:S1133") @Deprecated @Override public BigDecimal getBigDecimal(final String columnLabel, final int scale) throws SQLException { return this.getBigDecimal(this.findColumn(columnLabel), scale); } /** * {@inheritDoc}. */ @Override public InputStream getBinaryStream(final int columnIndex) throws SQLException { final byte[] val = ValuesConverter.getByteArray(dataNavigation.getColumnValue(columnIndex), connectionInfo); if (val != null) { return new ByteArrayInputStream(val); } return null; } /** * {@inheritDoc}. */ @Override public InputStream getBinaryStream(final String columnLabel) throws SQLException { return this.getBinaryStream(this.findColumn(columnLabel)); } /** * {@inheritDoc}. */ @Override public Blob getBlob(final int columnIndex) throws SQLException { final byte[] val = ValuesConverter.getByteArray(dataNavigation.getColumnValue(columnIndex), connectionInfo); if (val != null) { return new ParadoxBlob(val); } return null; } /** * {@inheritDoc}. */ @Override public Blob getBlob(final String columnLabel) throws SQLException { return getBlob(this.findColumn(columnLabel)); } /** * {@inheritDoc}. */ @Override public boolean getBoolean(final int columnIndex) throws SQLException { Boolean ret = ValuesConverter.getBoolean(dataNavigation.getColumnValue(columnIndex), connectionInfo); if (ret != null) { return ret; } return false; } /** * {@inheritDoc}. */ @Override public boolean getBoolean(final String columnLabel) throws SQLException { return this.getBoolean(this.findColumn(columnLabel)); } /** * {@inheritDoc}. */ @Override public byte getByte(final int columnIndex) throws SQLException { Byte ret = ValuesConverter.getByte(dataNavigation.getColumnValue(columnIndex), connectionInfo); if (ret != null) { return ret; } return 0; } /** * {@inheritDoc}. */ @Override public byte getByte(final String columnLabel) throws SQLException { return this.getByte(this.findColumn(columnLabel)); } /** * {@inheritDoc}. */ @Override public byte[] getBytes(final int columnIndex) throws SQLException { return ValuesConverter.getByteArray(dataNavigation.getColumnValue(columnIndex), connectionInfo); } /** * {@inheritDoc}. */ @Override public byte[] getBytes(final String columnLabel) throws SQLException { return this.getBytes(this.findColumn(columnLabel)); } /** * {@inheritDoc}. */ @Override public Reader getCharacterStream(final int columnIndex) throws SQLException { final String val = ValuesConverter.getString(dataNavigation.getColumnValue(columnIndex), connectionInfo); if (val != null) { return new StringReader(val); } return null; } /** * {@inheritDoc}. */ @Override public Reader getCharacterStream(final String columnLabel) throws SQLException { return this.getCharacterStream(this.findColumn(columnLabel)); } /** * {@inheritDoc}. */ @Override public Clob getClob(final int columnIndex) throws SQLException { final String val = ValuesConverter.getString(dataNavigation.getColumnValue(columnIndex), connectionInfo); if (val != null) { return new ParadoxClob(val); } return null; } /** * {@inheritDoc}. */ @Override public Clob getClob(final String columnLabel) throws SQLException { return this.getClob(this.findColumn(columnLabel)); } /** * {@inheritDoc}. */ @Override public int getConcurrency() { return concurrency; } /** * Sets this concurrency type. * * @param concurrency the concurrency type. */ public void setConcurrency(int concurrency) { this.concurrency = concurrency; } /** * {@inheritDoc}. */ @Override public String getCursorName() { return "NO_NAME"; } /** * {@inheritDoc}. */ @Override public Date getDate(final int columnIndex) throws SQLException { return ValuesConverter.getDate(dataNavigation.getColumnValue(columnIndex), connectionInfo); } /** * {@inheritDoc}. */ @Override public Date getDate(final int columnIndex, final Calendar c) throws SQLException { return this.getDate(columnIndex); } /** * {@inheritDoc}. */ @Override public Date getDate(final String columnLabel) throws SQLException { return this.getDate(this.findColumn(columnLabel)); } /** * {@inheritDoc}. */ @Override public Date getDate(final String columnLabel, final Calendar cal) throws SQLException { return this.getDate(this.findColumn(columnLabel), cal); } /** * {@inheritDoc}. */ @Override public double getDouble(final int columnIndex) throws SQLException { Double ret = ValuesConverter.getDouble(dataNavigation.getColumnValue(columnIndex), connectionInfo); if (ret != null) { return ret; } return 0.0; } /** * {@inheritDoc}. */ @Override public double getDouble(final String columnLabel) throws SQLException { return this.getDouble(this.findColumn(columnLabel)); } /** * {@inheritDoc}. */ @Override public int getFetchDirection() throws SQLException { return dataNavigation.getFetchDirection(); } /** * {@inheritDoc}. */ @Override public void setFetchDirection(final int direction) throws SQLException { this.dataNavigation.setFetchDirection(direction); } /** * {@inheritDoc}. */ @Override public int getFetchSize() { return this.fetchSize; } /** * {@inheritDoc}. */ @Override public void setFetchSize(final int rows) { this.fetchSize = rows; } /** * {@inheritDoc}. */ @Override public float getFloat(final int columnIndex) throws SQLException { Float ret = ValuesConverter.getFloat(dataNavigation.getColumnValue(columnIndex), connectionInfo); if (ret != null) { return ret; } return 0.0F; } /** * {@inheritDoc}. */ @Override public float getFloat(final String columnLabel) throws SQLException { return this.getFloat(this.findColumn(columnLabel)); } /** * {@inheritDoc}. */ @Override public int getHoldability() { return this.connectionInfo.getHoldability(); } /** * {@inheritDoc}. */ @Override public int getInt(final int columnIndex) throws SQLException { Integer ret = ValuesConverter.getInteger(dataNavigation.getColumnValue(columnIndex), connectionInfo); if (ret != null) { return ret; } return 0; } /** * {@inheritDoc}. */ @Override public int getInt(final String columnLabel) throws SQLException { return this.getInt(this.findColumn(columnLabel)); } /** * {@inheritDoc}. */ @Override public long getLong(final int columnIndex) throws SQLException { Long ret = ValuesConverter.getLong(dataNavigation.getColumnValue(columnIndex), connectionInfo); if (ret != null) { return ret; } return 0; } /** * {@inheritDoc}. */ @Override public long getLong(final String columnLabel) throws SQLException { return this.getLong(this.findColumn(columnLabel)); } /** * {@inheritDoc}. */ @Override public java.sql.ResultSetMetaData getMetaData() { return new ParadoxResultSetMetaData(this.connectionInfo, this.columns); } /** * {@inheritDoc}. */ @Override public Reader getNCharacterStream(final int columnIndex) throws SQLException { return getCharacterStream(columnIndex); } /** * {@inheritDoc}. */ @Override public Reader getNCharacterStream(final String columnLabel) throws SQLException { return getCharacterStream(columnLabel); } /** * {@inheritDoc}. */ @Override public NClob getNClob(final int columnIndex) { return null; } /** * {@inheritDoc}. */ @Override public NClob getNClob(final String columnLabel) { return null; } /** * {@inheritDoc}. */ @Override public String getNString(final int columnIndex) throws SQLException { return getString(columnIndex); } /** * {@inheritDoc}. */ @Override public String getNString(final String columnLabel) throws SQLException { return getString(columnLabel); } /** * {@inheritDoc}. */ @Override public Object getObject(final int columnIndex) throws SQLException { return dataNavigation.getColumnValue(columnIndex); } /** * {@inheritDoc}. */ @Override public <T> T getObject(final int columnIndex, final Class<T> type) throws SQLException { return ValuesConverter.convert(getObject(columnIndex), type, connectionInfo); } /** * {@inheritDoc}. */ @Override public Object getObject(final int columnIndex, final Map<String, Class<?>> map) throws SQLException { return getObject(columnIndex); } /** * {@inheritDoc}. */ @Override public Object getObject(final String columnLabel) throws SQLException { return this.getObject(this.findColumn(columnLabel)); } /** * {@inheritDoc}. */ @Override public <T> T getObject(final String columnLabel, final Class<T> type) throws SQLException { return getObject(this.findColumn(columnLabel), type); } /** * {@inheritDoc}. */ @Override public Object getObject(final String columnLabel, final Map<String, Class<?>> map) throws SQLException { return this.getObject(this.findColumn(columnLabel), map); } /** * {@inheritDoc}. */ @Override public Ref getRef(final int columnIndex) throws SQLFeatureNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public Ref getRef(final String columnLabel) throws SQLException { return getRef(this.findColumn(columnLabel)); } /** * {@inheritDoc}. */ @Override public int getRow() throws SQLException { return dataNavigation.getRow(); } /** * {@inheritDoc}. */ @Override public RowId getRowId(final int columnIndex) throws SQLFeatureNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public RowId getRowId(final String columnLabel) throws SQLException { return getRowId(this.findColumn(columnLabel)); } /** * {@inheritDoc}. */ @Override public short getShort(final int columnIndex) throws SQLException { Short ret = ValuesConverter.getShort(dataNavigation.getColumnValue(columnIndex), connectionInfo); if (ret != null) { return ret; } return 0; } /** * {@inheritDoc}. */ @Override public short getShort(final String columnLabel) throws SQLException { return this.getShort(this.findColumn(columnLabel)); } /** * {@inheritDoc}. */ @Override public SQLXML getSQLXML(final int columnIndex) { return null; } /** * {@inheritDoc}. */ @Override public SQLXML getSQLXML(final String columnLabel) { return null; } /** * {@inheritDoc}. */ @Override public Statement getStatement() { if (statement != null) { return this.statement.get(); } return null; } /** * {@inheritDoc}. */ @Override public String getString(final int columnIndex) throws SQLException { return ValuesConverter.getString(dataNavigation.getColumnValue(columnIndex), connectionInfo); } /** * {@inheritDoc}. */ @Override public String getString(final String columnLabel) throws SQLException { return this.getString(this.findColumn(columnLabel)); } /** * {@inheritDoc}. */ @Override public Time getTime(final int columnIndex) throws SQLException { return ValuesConverter.getTime(dataNavigation.getColumnValue(columnIndex), connectionInfo); } /** * {@inheritDoc}. */ @Override public Time getTime(final int columnIndex, final Calendar cal) throws SQLException { return this.getTime(columnIndex); } /** * {@inheritDoc}. */ @Override public Time getTime(final String columnLabel) throws SQLException { return this.getTime(this.findColumn(columnLabel)); } /** * {@inheritDoc}. */ @Override public Time getTime(final String columnLabel, final Calendar cal) throws SQLException { return this.getTime(this.findColumn(columnLabel), cal); } /** * {@inheritDoc}. */ @Override public Timestamp getTimestamp(final int columnIndex) throws SQLException { return ValuesConverter.getTimestamp(dataNavigation.getColumnValue(columnIndex), connectionInfo); } /** * {@inheritDoc}. */ @Override public Timestamp getTimestamp(final int columnIndex, final Calendar cal) throws SQLException { return this.getTimestamp(columnIndex); } /** * {@inheritDoc}. */ @Override public Timestamp getTimestamp(final String columnLabel) throws SQLException { return this.getTimestamp(this.findColumn(columnLabel)); } /** * {@inheritDoc}. */ @Override public Timestamp getTimestamp(final String columnLabel, final Calendar cal) throws SQLException { return this.getTimestamp(this.findColumn(columnLabel), cal); } /** * {@inheritDoc}. */ @Override public int getType() { return type; } /** * Sets this type. * * @param type the ResultSet type. */ public void setType(int type) { this.type = type; } /** * {@inheritDoc}. * * @deprecated use {@link #getAsciiStream(String)} method. */ @SuppressWarnings("squid:S1133") @Deprecated @Override public InputStream getUnicodeStream(final String columnLabel) throws SQLException { return this.getAsciiStream(this.findColumn(columnLabel)); } /** * {@inheritDoc}. */ @Override public URL getURL(final int columnIndex) throws SQLFeatureNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public URL getURL(final String columnLabel) throws SQLException { return getURL(this.findColumn(columnLabel)); } /** * {@inheritDoc}. */ @Override public SQLWarning getWarnings() { return null; } /** * {@inheritDoc}. */ @Override public void insertRow() throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public boolean isAfterLast() throws SQLException { return dataNavigation.isAfterLast(); } /** * {@inheritDoc}. */ @Override public boolean isBeforeFirst() throws SQLException { return dataNavigation.isBeforeFirst(); } /** * {@inheritDoc}. */ @Override public boolean isClosed() { return dataNavigation.isClosed(); } /** * {@inheritDoc}. */ @Override public boolean isFirst() throws SQLException { return dataNavigation.isFirst(); } /** * {@inheritDoc}. */ @Override public boolean isLast() throws SQLException { return dataNavigation.isLast(); } /** * {@inheritDoc}. */ @Override public boolean isWrapperFor(final Class<?> iFace) { return Utils.isWrapperFor(this, iFace); } /** * {@inheritDoc}. */ @Override public boolean last() throws SQLException { return dataNavigation.last(); } /** * {@inheritDoc}. */ @Override public void moveToCurrentRow() { // Do nothing. } /** * {@inheritDoc}. */ @Override public void moveToInsertRow() { // Do nothing. } /** * {@inheritDoc}. */ @Override public boolean next() { return dataNavigation.next(); } /** * {@inheritDoc}. */ @Override public boolean previous() { return dataNavigation.previous(); } /** * {@inheritDoc}. * * @deprecated use {@link #getAsciiStream(int)} method. */ @SuppressWarnings("squid:S1133") @Deprecated @Override public InputStream getUnicodeStream(final int columnIndex) throws SQLException { return getAsciiStream(columnIndex); } /** * {@inheritDoc}. */ @Override public boolean relative(final int rows) throws SQLException { return dataNavigation.relative(rows); } /** * {@inheritDoc}. */ @Override public boolean rowDeleted() { return false; } /** * {@inheritDoc}. */ @Override public boolean rowInserted() { return false; } /** * {@inheritDoc}. */ @Override public boolean rowUpdated() { return false; } /** * {@inheritDoc}. */ @Override public void refreshRow() { // Nothing to do. } /** * {@inheritDoc}. */ @Override public <T> T unwrap(final Class<T> iFace) throws SQLException { return Utils.unwrap(this, iFace); } /** * {@inheritDoc}. */ @Override public void updateArray(final int columnIndex, final Array x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateArray(final String columnLabel, final Array x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateAsciiStream(final int columnIndex, final InputStream x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateAsciiStream(final int columnIndex, final InputStream x, final int length) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateAsciiStream(final int columnIndex, final InputStream x, final long length) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateAsciiStream(final String columnLabel, final InputStream x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateAsciiStream(final String columnLabel, final InputStream x, final int length) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateAsciiStream(final String columnLabel, final InputStream x, final long length) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateBigDecimal(final int columnIndex, final BigDecimal x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateBigDecimal(final String columnLabel, final BigDecimal x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateBinaryStream(final int columnIndex, final InputStream x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateBinaryStream(final int columnIndex, final InputStream x, final int length) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateBinaryStream(final int columnIndex, final InputStream x, final long length) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateBinaryStream(final String columnLabel, final InputStream x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateBinaryStream(final String columnLabel, final InputStream x, final int length) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateBinaryStream(final String columnLabel, final InputStream x, final long length) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateBlob(final int columnIndex, final Blob x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateBlob(final int columnIndex, final InputStream inputStream) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateBlob(final int columnIndex, final InputStream inputStream, final long length) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateBlob(final String columnLabel, final Blob x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateBlob(final String columnLabel, final InputStream inputStream) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateBlob(final String columnLabel, final InputStream inputStream, final long length) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateBoolean(final int columnIndex, final boolean x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateBoolean(final String columnLabel, final boolean x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateByte(final int columnIndex, final byte x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateByte(final String columnLabel, final byte x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateBytes(final int columnIndex, final byte[] x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateBytes(final String columnLabel, final byte[] x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateCharacterStream(final int columnIndex, final Reader x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateCharacterStream(final int columnIndex, final Reader x, final int length) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateCharacterStream(final int columnIndex, final Reader x, final long length) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateCharacterStream(final String columnLabel, final Reader reader) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateCharacterStream(final String columnLabel, final Reader reader, final int length) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateCharacterStream(final String columnLabel, final Reader reader, final long length) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateClob(final int columnIndex, final Clob x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateClob(final int columnIndex, final Reader reader) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateClob(final int columnIndex, final Reader reader, final long length) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateClob(final String columnLabel, final Clob x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateClob(final String columnLabel, final Reader reader) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateClob(final String columnLabel, final Reader reader, final long length) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateDate(final int columnIndex, final Date x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateDate(final String columnLabel, final Date x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateDouble(final int columnIndex, final double x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateDouble(final String columnLabel, final double x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateFloat(final int columnIndex, final float x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateFloat(final String columnLabel, final float x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateInt(final int columnIndex, final int x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateInt(final String columnLabel, final int x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateLong(final int columnIndex, final long x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateLong(final String columnLabel, final long x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateNCharacterStream(final int columnIndex, final Reader x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateNCharacterStream(final int columnIndex, final Reader x, final long length) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateNCharacterStream(final String columnLabel, final Reader reader) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateNCharacterStream(final String columnLabel, final Reader reader, final long length) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateNClob(final int columnIndex, final NClob nClob) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateNClob(final int columnIndex, final Reader reader) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateNClob(final int columnIndex, final Reader reader, final long length) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateNClob(final String columnLabel, final NClob nClob) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateNClob(final String columnLabel, final Reader reader) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateNClob(final String columnLabel, final Reader reader, final long length) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateNString(final int columnIndex, final String nString) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateNString(final String columnLabel, final String nString) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateNull(final int columnIndex) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateNull(final String columnLabel) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateObject(final int columnIndex, final Object x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateObject(final int columnIndex, final Object x, final int scaleOrLength) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateObject(final String columnLabel, final Object x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateObject(final String columnLabel, final Object x, final int scaleOrLength) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateRef(final int columnIndex, final Ref x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateRef(final String columnLabel, final Ref x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateRow() throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateRowId(final int columnIndex, final RowId x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateRowId(final String columnLabel, final RowId x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateShort(final int columnIndex, final short x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateShort(final String columnLabel, final short x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateSQLXML(final int columnIndex, final SQLXML xmlObject) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateSQLXML(final String columnLabel, final SQLXML xmlObject) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateString(final int columnIndex, final String x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateString(final String columnLabel, final String x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateTime(final int columnIndex, final Time x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateTime(final String columnLabel, final Time x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateTimestamp(final int columnIndex, final Timestamp x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public void updateTimestamp(final String columnLabel, final Timestamp x) throws ParadoxNotSupportedException { throw new ParadoxNotSupportedException(ParadoxNotSupportedException.Error.OPERATION_NOT_SUPPORTED); } /** * {@inheritDoc}. */ @Override public boolean wasNull() throws SQLException { return dataNavigation.getLastValue() == null; } @Override public String toString() { return "Columns: " + columns.size() + " " + dataNavigation; } }
lgpl-3.0
immutant/immutant-release
modules/core/src/main/java/org/immutant/core/processors/INFMounter.java
3887
/* * Copyright 2008-2014 Red Hat, Inc, and individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.immutant.core.processors; import org.immutant.core.ClojureMetaData; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.logging.Logger; import org.jboss.vfs.VFS; import org.jboss.vfs.VirtualFile; import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class INFMounter implements DeploymentUnitProcessor { @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); ClojureMetaData metaData = deploymentUnit.getAttachment(ClojureMetaData.ATTACHMENT_KEY); if (metaData == null) { return; } List<String> resourceDirs = deploymentUnit.getAttachmentList(AppDependenciesProcessor.APP_RESOURCE_PATHS); if (resourceDirs != null) { VirtualFile root = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT).getRoot(); try { mountINFDir(root, resourceDirs, "META-INF"); mountINFDir(root, resourceDirs, "WEB-INF"); } catch (Exception e) { throw new DeploymentUnitProcessingException(e); } } } private void mountINFDir(VirtualFile root, List<String> resourceDirs, String name) throws IOException { if (!root.getChild(name).exists()) { VirtualFile infDir = null; for(String dir : resourceDirs) { // lein puts a pom in a META-INF under target/classes, so we skip that if (dir.endsWith("target/classes")) { log.trace("skipping " + dir); continue; } infDir = VFS.getChild(dir).getChild(name); log.trace("looking at " + infDir); if (infDir.exists()) { log.trace("found " + infDir); break; } } if (infDir != null && infDir.exists()) { log.trace("mounting " + infDir); this.infMounts.add(VFS.mountReal(infDir.getPhysicalFile(), root.getChild(name))); } } else { log.trace(root.getChild(name) + " already exists!"); } } @Override public void undeploy(DeploymentUnit context) { for (Closeable each : this.infMounts) { try { log.trace("closing " + each); each.close(); } catch (IOException e) { e.printStackTrace(); } } } private final List<Closeable> infMounts = new ArrayList<Closeable>(); private static final Logger log = Logger.getLogger(INFMounter.class); }
lgpl-3.0
l3nz/ari4java
src/main/java/ch/loway/oss/ari4java/tools/WsClient.java
516
package ch.loway.oss.ari4java.tools; import java.util.List; /** * Interface to pluggable WebSocket client implementation * * @author mwalton */ public interface WsClient { public interface WsClientConnection { void disconnect() throws RestException; } WsClientConnection connect(HttpResponseHandler callback, String url, List<HttpParam> lParamQuery) throws RestException; void destroy(); boolean isWsConnected(); }
lgpl-3.0
Albloutant/Galacticraft
dependencies/mekanism/api/gas/IGasHandler.java
1071
package mekanism.api.gas; import net.minecraftforge.common.ForgeDirection; /** * Implement this if your tile entity accepts gas from an external source. * @author AidanBrady * */ public interface IGasHandler { /** * Transfer a certain amount of gas to this block. * @param stack - gas to add * @return gas added */ public int receiveGas(ForgeDirection side, GasStack stack); /** * Draws a certain amount of gas from this block. * @param amount - amount to draw * @return gas drawn */ public GasStack drawGas(ForgeDirection side, int amount); /** * Whether or not this block can accept gas from a certain side. * @param side - side to check * @param type - type of gas to check * @return if block accepts gas */ public boolean canReceiveGas(ForgeDirection side, Gas type); /** * Whether or not this block can be drawn of gas from a certain side. * @param side - side to check * @param type - type of gas to check * @return if block can be drawn of gas */ public boolean canDrawGas(ForgeDirection side, Gas type); }
lgpl-3.0
subes/invesdwin-util
invesdwin-util-parent/invesdwin-util/src/main/java/de/invesdwin/util/math/expression/variable/ABooleanNullableConstant.java
1123
package de.invesdwin.util.math.expression.variable; import javax.annotation.concurrent.Immutable; import de.invesdwin.util.math.expression.lambda.IEvaluateBooleanNullable; import de.invesdwin.util.math.expression.lambda.IEvaluateBooleanNullableFDate; import de.invesdwin.util.math.expression.lambda.IEvaluateBooleanNullableKey; @Immutable public abstract class ABooleanNullableConstant extends AConstant implements IBooleanNullableVariable { private final Boolean value; public ABooleanNullableConstant(final Boolean value) { this.value = value; } @Override public final IEvaluateBooleanNullable newEvaluateBooleanNullable(final String context) { return () -> value; } @Override public final IEvaluateBooleanNullableFDate newEvaluateBooleanNullableFDate(final String context) { return key -> value; } @Override public final IEvaluateBooleanNullableKey newEvaluateBooleanNullableKey(final String context) { return key -> value; } @Override public String toString() { return getExpressionName() + ": " + value; } }
lgpl-3.0
MRL-RS/visual-debugger
src/main/java/com/mrl/debugger/layers/base/MrlBaseRoadLayer.java
2397
package com.mrl.debugger.layers.base; import com.mrl.debugger.StaticViewProperties; import com.mrl.debugger.ViewLayer; import rescuecore2.misc.gui.ScreenTransform; import rescuecore2.standard.entities.Edge; import rescuecore2.standard.entities.Hydrant; import rescuecore2.standard.entities.Road; import java.awt.*; /** * @author Mahdi */ @ViewLayer(visible = true, caption = "Roads") public class MrlBaseRoadLayer extends MrlBaseAreaLayer<Road> { private static final Color ROAD_EDGE_COLOUR = Color.GRAY.darker(); private static final Color ROAD_SHAPE_COLOUR = new Color(185, 185, 185); private static final Color HYDRANT_SHAPE_COLOUR = new Color(255, 128, 100); private static final Stroke WALL_STROKE = new BasicStroke(2f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER); private static final Stroke ENTRANCE_STROKE = new BasicStroke(0.3f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER); public MrlBaseRoadLayer() { super(Road.class); } @Override protected void paintEdge(Edge e, Graphics2D g, ScreenTransform t) { g.setColor(ROAD_EDGE_COLOUR); g.setStroke(e.isPassable() ? ENTRANCE_STROKE : WALL_STROKE); g.drawLine(t.xToScreen(e.getStartX()), t.yToScreen(e.getStartY()), t.xToScreen(e.getEndX()), t.yToScreen(e.getEndY())); } // @Override // public String getName() { // ViewLayer annotation = this.getClass().getAnnotation(ViewLayer.class); // if (annotation != null) { // return annotation.caption(); // } else { // return "Roads"; // } // } @Override protected void paintShape(Road r, Polygon p, Graphics2D g) { // StandardEntityToPaint entityToPaint = StaticViewProperties.getPaintObject(r); // if (entityToPaint != null) { // g.setColor(entityToPaint.getColor()); // g.fill(p); // } else { if (r == StaticViewProperties.selectedObject) { g.setColor(Color.MAGENTA); } else { if (r instanceof Hydrant) { g.setColor(HYDRANT_SHAPE_COLOUR); } else { g.setColor(ROAD_SHAPE_COLOUR); } } // } g.fill(p); } @Override protected void paintData(Road area, Polygon p, Graphics2D g) { super.paintData(area, p, g); } }
lgpl-3.0
SonarSource/sonarqube
server/sonar-webserver-webapi/src/main/java/org/sonar/server/projectanalysis/ws/package-info.java
976
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.server.projectanalysis.ws; import javax.annotation.ParametersAreNonnullByDefault;
lgpl-3.0
golharam/rgtools
src/tools/VCFBrowser.java
26466
package tools; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Rectangle; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.filechooser.FileFilter; import javax.swing.table.DefaultTableModel; import javax.swing.table.JTableHeader; import javax.swing.table.TableColumn; import javax.swing.table.TableRowSorter; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreePath; import javax.swing.BoxLayout; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JMenuBar; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JSeparator; import javax.swing.RowFilter; import javax.swing.SwingConstants; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import htsjdk.samtools.util.IOUtil; import htsjdk.samtools.util.Log; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import javax.swing.JTable; import javax.swing.JScrollPane; import tools.vcfbrowser.AppSettings; //import chromviewer.JDAP.JDAPSample; import tools.vcfbrowser.AppSettings; import tools.vcfbrowser.VarTableModel; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; // Version 0.01: initial version // Version 0.01a: ??? // Version 0.01b: Allow specifying VCF File to load on command line // Version 0.01c: Load IGV only upon double-clicking a row // Version 0.01d: Added ability to click a column header to sort the table // Version 0.01e: Added ability to filter on gene column only // Added Go To menu item to go to specific row // Version 0.01f: Show each sample's AD/DP/GT/GP fields instead of just the genotype basecall // Allow mouseover popups on column header to give description of what the column is // Version ?????: Added Menu Item to Start IGV // Added ability to allow user to specify BAM file location(s) through menu item // Added command line option to not prompt to load BAM files // (change the command line option to the options parser) // Changed behavior of StartIGV Menu Item to connect to running IGV. // Added ability to specify column ordering from command-line when loading VCF file using --priortizeColumns // Added ability to hide column from command-line when loading VCF file using --hideColumns // Added status bar (panel) // Implemented Recent menu items // Added ability to load only a specified # of rows // TODO: Add ability to export VCF as text file using VCFToTab // TODO: Implement row labels with row number // TODO: Implement status bar indicating selected row number // TODO: Implement advanced filtering (JEXL Support) // TODO: Have VCFBrowser automatically update the VCF file with the information about BAM location // TODO: Add ability to annotate variants // TODO: Filter variants that match the reference for all samples as the variants may have // been called with other samples NOT in the VCF file and the variants may not apply // to the samples in the VCF file. // TODO: Allow split windows for browsing // TODO: Add ability to rename columns public class VCFBrowser extends JFrame { private static String APP_NAME = "eVCFerator - The VCF Browser"; private static String VERSION = "0.01f"; private static final Log log = Log.getInstance(VCFBrowser.class); private JPanel contentPane; private File workingDirectory = null; AppSettings m_appSettings = null; JMenu mnRecent = null; int mruListSize = 20; // allow 20 items in the Most Recently Used list //JMenuItem[] mruMenuItem = null; private JTable table; private VarTableModel varTableModel; private JLabel statusLabel; String prioritizeColumns = null; String hideColumns = null; boolean loadBAMs = true; int loadRows = -1; String[] bamFiles; TableRowSorter<VarTableModel> sorter; RowFilter<VarTableModel, Object> rowFilter = null; String filterText; // private Socket igv_socket = null; // private PrintWriter igv_out = null; // private BufferedReader igv_in = null; private boolean m_bUseIGV = false; /** * Launch the application. */ public static void main(final String[] args) { log.info(APP_NAME + " Version " + VERSION); EventQueue.invokeLater(new Runnable() { public void run() { try { VCFBrowser frame = new VCFBrowser(); if (args.length != 0) { frame.parseOptions(args); } frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public VCFBrowser() { loadSettings(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu mnFile = new JMenu("File"); menuBar.add(mnFile); JMenuItem mntmOpenVcf = new JMenuItem("Open VCF"); mntmOpenVcf.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { onFileOpenVCFMenuItemSelected(e); } }); mnFile.add(mntmOpenVcf); mnRecent = new JMenu("Open Recent"); mnFile.add(mnRecent); setMRU(); JMenuItem mntmExit = new JMenuItem("Exit"); mntmExit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { System.exit(0); } }); mnFile.add(mntmExit); JMenu mnEdit = new JMenu("Edit"); menuBar.add(mnEdit); JMenuItem mntmFind = new JMenuItem("Find"); mntmFind.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { onEditFind(e); } }); mnEdit.add(mntmFind); JMenuItem mntmGoTo = new JMenuItem("Go to"); mntmGoTo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { onEditGoTo(e); } }); mnEdit.add(mntmGoTo); JMenu mnIGV = new JMenu("IGV"); menuBar.add(mnIGV); JMenuItem mntmStartIGV = new JMenuItem("Connect to IGV"); mntmStartIGV.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { onConnectToIGV(e); } }); mnIGV.add(mntmStartIGV); JMenuItem mntmSpecifyBAMFiles = new JMenuItem("Specify BAM File(s)"); mntmSpecifyBAMFiles.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { onSpecifyBAMFiles(e); } }); mnIGV.add(mntmSpecifyBAMFiles); JMenu mnHelp = new JMenu("Help"); menuBar.add(mnHelp); JMenuItem mntmAbout = new JMenuItem("About"); mnHelp.add(mntmAbout); mntmAbout.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { onHelpAbout(e); } }); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setLayout(new BorderLayout(0, 0)); setContentPane(contentPane); table = new JTable() { //Implement table header tool tips. protected JTableHeader createDefaultTableHeader() { return new JTableHeader(columnModel) { public String getToolTipText(MouseEvent e) { String tip = null; java.awt.Point p = e.getPoint(); int index = columnModel.getColumnIndexAtX(p.x); int realIndex = columnModel.getColumn(index).getModelIndex(); return onGetToolTipText(realIndex); } }; } }; table.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { //if (e.getButton() == java.awt.event.MouseEvent.BUTTON3) { // System.out.println("Right Click"); //} else if (e.getClickCount() == 2) { int row = table.getSelectedRow(); onRowDoubleClicked(row); } } }); table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { updateStatus(); } }); table.setAutoCreateRowSorter(true); JScrollPane scrollPane = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); contentPane.add(scrollPane, BorderLayout.CENTER); table.setFillsViewportHeight(true); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); scrollPane.setViewportView(table); JPanel statusPanel = new JPanel(); contentPane.add(statusPanel, BorderLayout.SOUTH); statusPanel.setPreferredSize(new Dimension(contentPane.getWidth(), 16)); statusPanel.setLayout(new BoxLayout(statusPanel, BoxLayout.X_AXIS)); statusLabel = new JLabel("Ready."); statusLabel.setHorizontalAlignment(SwingConstants.LEFT); statusPanel.add(statusLabel); try { UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (InstantiationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IllegalAccessException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (UnsupportedLookAndFeelException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } private void loadSettings() { File userData = new File(System.getProperty("user.home") + File.separator + ".VCFBrowser.dat"); FileInputStream in; ObjectInputStream s; m_appSettings = null; try { in = new FileInputStream(userData); s = new ObjectInputStream(in); m_appSettings = (AppSettings)s.readObject(); s.close(); in.close(); } catch (FileNotFoundException e) { m_appSettings = null; } catch (IOException e) { m_appSettings = null; } catch (ClassNotFoundException e) { m_appSettings = null; } if (m_appSettings == null) m_appSettings = new AppSettings(); } private void saveSettings() { File userData = new File(System.getProperty("user.home") + File.separator + ".VCFBrowser.dat"); FileOutputStream f; ObjectOutputStream s; try { f = new FileOutputStream(userData); s = new ObjectOutputStream(f); s.writeObject(m_appSettings); s.flush(); s.close(); } catch (FileNotFoundException e) { } catch (IOException e) { } } // TODO: Implement Command Line Options Parser protected void parseOptions(final String[] args) { int i = 0; if (args == null) return; while (i < args.length) { log.info("Parsing arg " + i + " " + args[i]); if (args[i].equalsIgnoreCase("--noloadbam")) { this.loadBAMs = false; } else if (args[i].equalsIgnoreCase("-h")) { printUsage(); System.exit(0); } else if (i == args.length-1) { loadVCFFile(new File(args[i])); i++; } else if (args[i].equalsIgnoreCase("--prioritizeColumns")) { this.prioritizeColumns = args[i+1]; i++; } else if (args[i].equalsIgnoreCase("--hideColumns")) { this.hideColumns = args[i+1]; i++; } else if (args[i].equalsIgnoreCase("--loadRows")) { this.loadRows = Integer.parseInt(args[i+1]); i++; } else { log.error("Unknown command line option: " + args[i]); printUsage(); System.exit(-1); } i++; } } protected static void printUsage() { log.info("java -jar VCFBrowser.jar [options] [vcf file]"); log.info(" --hideColumns [comma separated list of columns] List of columns to hide in browser"); log.info(" --loadRows Specify # of rows to load"); log.info(" --noloadbam Do not prompt for BAM file locations"); log.info(" --prioritizeColumns [comma separated list of columns] List of columns to display leftmost"); log.info(" -h This help message"); } private void onClearRecentHistory() { m_appSettings.setMRUList(null); saveSettings(); setMRU(); } // Update the menu to reflect the MRU list private void setMRU() { String[] mruList = m_appSettings.getMRUList(); // remove all the recent menu items mnRecent.removeAll(); // rebuild the standard items mnRecent.add(new JSeparator()); JMenuItem mntmClearHistory = new JMenuItem("Clear History"); mntmClearHistory.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { onClearRecentHistory(); } }); mnRecent.add(mntmClearHistory); if (mruList == null) return; // Set the mru list in the menu for (int i = 0; i < mruList.length; i++) { final String text = mruList[i]; JMenuItem mruMenuItem = new JMenuItem(mruList[i]); mruMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { mruMenuItemActionPerformed(text); } }); mnRecent.insert(mruMenuItem, i); } } // Update the MRU list by shifting everything down one private void updateMRU(String file) { // update the list to include the new file String[] mruList = m_appSettings.getMRUList(); // if there is no MRU, add this as the first item if (mruList == null) { mruList = new String[1]; mruList[0] = file; } else { // if there is an MRU, add file as the first item, then remove any other instances of it // then make sure the array is not bigger than mruListSize LinkedList<String> a = new LinkedList<String>(Arrays.asList(mruList)); a.add(0, file); int i = 1; while (i < a.size()) { if (file.equals(a.get(i))) a.remove(i); else i++; } while (a.size() > mruListSize) { a.remove(a.size() - 1); } mruList = a.toArray(new String[0]); } m_appSettings.setMRUList(mruList); saveSettings(); setMRU(); } protected void mruMenuItemActionPerformed(String mruPathname) { File mruFile = new File(mruPathname); if (!mruFile.exists()) { log.error("Unable to open mruFile: " + mruPathname); return; } loadVCFFile(mruFile); } protected void onRowDoubleClicked(int row) { // If not already connected to IGV, // determine if we should try to connect and if we should, then connect, and initialize // issue navigation commands /* if (igv_out == null) { boolean worthLoading = false; for (String bamFile : bamFiles) { if (bamFile != null) worthLoading = true; } if (!worthLoading) { log.warn("No bam files specified. Not worth loading IGV"); return; } try { if (initIGV() == false) { return; } } catch (Exception e) { return; } } */ if (m_bUseIGV) { // private Socket igv_socket = null; // private PrintWriter igv_out = null; // private BufferedReader igv_in = null; try { Socket igv_socket = new Socket("127.0.0.1", 60151); if (igv_socket.isConnected()) { PrintWriter igv_out = new PrintWriter(igv_socket.getOutputStream(), true); //BufferedReader igv_in = new BufferedReader(new InputStreamReader(igv_socket.getInputStream())); String chr = (String) table.getValueAt(row, 0); Integer pos = (Integer) table.getValueAt(row, 1); log.info("Navigating IGV to " + chr + ": " + pos); igv_out.println("goto " + chr + ":" + pos); /* String response = null; try { igv_in. response = igv_in.readLine(); if (response.equals("OK")) { log.info("IGV done"); } else { log.error("IGV Error: " + response); } } catch (IOException e) { log.error("Unable to navigate IGV"); } */ igv_out.close(); //igv_in.close(); igv_socket.close(); } else { log.warn("Unable to connect to IGV"); return; } } catch (UnknownHostException e1) { log.error("Unable to connect to IGV, 127.0.0.1 is unknown host."); return; } catch (IOException e1) { log.error("Unable to connect to IGV, IOException"); e1.printStackTrace(); return; } } } private class CustomFileFilter extends FileFilter { private String fileType; private String fileTypeDesc; public CustomFileFilter(String extension, String description) { // ex ".vcf", "VCF File" fileType = extension; fileTypeDesc = description; } @Override public boolean accept(File arg0) { if (arg0.isDirectory()) return true; if (arg0.getName().endsWith(fileType)) return true; return false; } @Override public String getDescription() { return fileTypeDesc; } } protected void onFileOpenVCFMenuItemSelected(ActionEvent e) { final JFileChooser fc = new JFileChooser(); fc.setFileSelectionMode(JFileChooser.FILES_ONLY); fc.setFileFilter(new CustomFileFilter(".vcf", "VCF File")); if (workingDirectory != null) fc.setCurrentDirectory(workingDirectory); int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); //This is where a real application would open the file. log.info("Opening: " + file.getName()); workingDirectory = fc.getCurrentDirectory(); loadVCFFile(file); } } private void onEditFind(ActionEvent evt) { filterText = JOptionPane.showInputDialog(this, "Enter Gene name (in regex) to search for or nothing to clear filtering.", filterText); if ((filterText == null) || (filterText.length() == 0)) { if (rowFilter != null) { log.info("Removing filtering"); rowFilter = null; filterText = null; sorter.setRowFilter(rowFilter); } } else { log.info("Filtering table on gene name " + filterText); try { rowFilter = RowFilter.regexFilter(filterText, varTableModel.getColumnIndex("Gene")); } catch (java.util.regex.PatternSyntaxException e) { log.error("Unable to parse filter regex/text."); return; } sorter.setRowFilter(rowFilter); } } private void onEditGoTo(ActionEvent evt) { String str = JOptionPane.showInputDialog(this, "Enter line number"); if ((str != null) && (str.length() != 0)) { int lineNumber = Integer.parseInt(str); table.setRowSelectionInterval(lineNumber - 1, lineNumber - 1); Rectangle rect = table.getCellRect(lineNumber, 0, true); table.scrollRectToVisible(rect); } } private String onGetToolTipText(int colIndex) { return varTableModel.getColumnDescription(colIndex); } protected void onConnectToIGV(ActionEvent evt) { /* // If IGV is already running, simply connect to it. try { connectToIGV(); } catch (Exception e) { log.error(e.getMessage()); }*/ m_bUseIGV = true; log.info("Will attempt to use IGV"); } protected void onSpecifyBAMFiles(ActionEvent evt) { String[] samples = varTableModel.getSampleNames(); log.info("Found " + samples.length + " samples:"); for (String sampleName : samples) { log.info("Sample: " + sampleName); } // Get BAM files corresponding to samples int i = 0; bamFiles = new String[samples.length]; for (String sample : samples) { //bamFiles[i] = "http://10.228.81.46/igv/igvdata/RD1000/" + sample + "/SID" + sample + ".dedup.indelrealigner.recal.bam"; // If the BAM file is specified in the VCF file, read it from there, // else ask the user for the location of the BAM file(s) String bamFile = varTableModel.getBAMFileURI(sample); if (bamFile != null) { bamFiles[i] = bamFile; } else { JOptionPane.showMessageDialog(this, "Select BAM file(s) corresponding to sample " + sample, "Select BAM File(s)", JOptionPane.PLAIN_MESSAGE); final JFileChooser fc = new JFileChooser(); fc.setFileSelectionMode(JFileChooser.FILES_ONLY); fc.setFileFilter(new CustomFileFilter(".bam", "BAM File")); if (workingDirectory != null) fc.setCurrentDirectory(workingDirectory); int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); bamFiles[i] = file.getAbsolutePath(); } else { bamFile = JOptionPane.showInputDialog(this, "Enter BAM file URI for sample " + sample); bamFiles[i] = bamFile; } } log.info(sample + " -> " + bamFiles[i]); i++; } } protected void onHelpAbout(ActionEvent evt) { JOptionPane.showMessageDialog(this, APP_NAME + " Version " + VERSION); } protected void loadVCFFile(File VCF) { // If another VCF file is loaded, unload it prior // to loading a new one to free up memory. // This is basically a reset. if (varTableModel != null) { varTableModel = null; sorter = null; rowFilter = null; table.setRowSorter(null); table.setModel(new DefaultTableModel()); filterText = null; System.gc(); } IOUtil.assertFileIsReadable(VCF); varTableModel = new VarTableModel(VCF, loadRows); table.setModel(varTableModel); sorter = new TableRowSorter<VarTableModel>(varTableModel); table.setRowSorter(sorter); if (prioritizeColumns != null) { log.info("Re-ordering columns based on priorty string: " + prioritizeColumns); String[] columns = prioritizeColumns.split(","); int newIndex = 0; for (String column : columns) { // get view index of column TableColumn col = null; try { col = table.getColumn(column); } catch (Exception e) { log.error("Error getting column " + column + ". Skipping..."); log.error(e.getMessage()); continue; } int modelIndex = col.getModelIndex(); int oldIndex = table.convertColumnIndexToView(modelIndex); log.info("Moving column " + column + " " + oldIndex + " -> " + newIndex); table.moveColumn(oldIndex, newIndex); newIndex++; } } if (hideColumns != null) { log.info("Hiding columns based on hide string: " + hideColumns); String[] columns = hideColumns.split(","); for (String column : columns) { TableColumn tcolumn = null; try { tcolumn = table.getColumn(column); } catch (java.lang.IllegalArgumentException e) { log.error("Unknown column: " + column + ", skipping..."); continue; } tcolumn.setMinWidth(0); tcolumn.setMaxWidth(0); tcolumn.setPreferredWidth(0); } } try { this.setTitle(VCF.getCanonicalPath()); } catch (IOException e) { log.error("Unable to get path of VCF file"); } // Get sample names from VCF file if (loadBAMs) { onSpecifyBAMFiles(null); } updateMRU(VCF.getAbsolutePath()); updateStatus(); } private void updateStatus() { int selectedRows = table.getSelectedRowCount(); statusLabel.setText("Rows: " + varTableModel.getRowCount() + " " + "Selected Rows: " + selectedRows); } /* private boolean connectToIGV() throws Exception { if (isIGVRunning()) { log.info("Initializing IGV communication..."); igv_socket = new Socket("127.0.0.1", 60151); igv_out = new PrintWriter(igv_socket.getOutputStream(), true); igv_in = new BufferedReader(new InputStreamReader(igv_socket.getInputStream())); log.info("done"); } return false; } private boolean initIGV() throws Exception { if (!isIGVRunning()) { if (!startIGV()) return false; } if (igv_socket != null) return true; if (connectToIGV()) { log.info("Setting IGV genome to hg19..."); igv_out.println("genome hg19"); String response = igv_in.readLine(); if (response.equals("OK")) { log.info("done"); } else { log.error("Error: " + response); return false; } for (String bamfile : bamFiles) { log.info("Loading IGV bam file " + bamfile); igv_out.println("load " + bamfile); response = igv_in.readLine(); if (response.equals("OK")) { log.info("done"); } else { log.error("Error: " + response); return false; } } return true; } return false; } private boolean isIGVRunning() { log.info("Checking if IGV is already running..."); try { igv_socket = new Socket("127.0.0.1", 60151); igv_socket.close(); igv_socket = null; } catch (IOException e) { log.info("IGV is not running."); return false; } log.info("IGV is running."); return true; } private boolean startIGV() { log.info("Starting IGV..."); if (isIGVRunning()) { log.info("IGV is already running"); return true; } try { // TODO: Read IGV location from properties file Runtime.getRuntime().exec("/Users/golharr/bin/igv"); // Wait for IGV to load before trying to communicate with it. int connectTry = 0; while (connectTry <= 5) { Thread.sleep(5000); if (isIGVRunning()) { log.info("IGV started."); return true; } log.info("Failed to connect to IGV. Waiting 5 more seconds then trying again."); connectTry++; } } catch (IOException e) { log.error("Unable to start IGV: " + e.getMessage()); return false; } catch (InterruptedException e) { } log.error("Unable to start or connect to IGV"); return false; } */ }
lgpl-3.0
estevaosaleme/MpegMetadata
src/org/iso/mpeg/mpegv/_2010/sepv/TactilePrefType.java
5767
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.01.12 at 06:12:40 PM BRST // package org.iso.mpeg.mpegv._2010.sepv; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; import org.iso.mpeg.mpegv._2010.cidl.UserSensoryPreferenceBaseType; /** * <p>Java class for TactilePrefType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="TactilePrefType"> * &lt;complexContent> * &lt;extension base="{urn:mpeg:mpeg-v:2010:01-CIDL-NS}UserSensoryPreferenceBaseType"> * &lt;attribute name="maxTemperature" type="{http://www.w3.org/2001/XMLSchema}float" /> * &lt;attribute name="minTemperature" type="{http://www.w3.org/2001/XMLSchema}float" /> * &lt;attribute name="maxCurrent" type="{http://www.w3.org/2001/XMLSchema}float" /> * &lt;attribute name="maxVibration" type="{http://www.w3.org/2001/XMLSchema}float" /> * &lt;attribute name="tempUnit" type="{urn:mpeg:mpeg-v:2010:01-CT-NS}unitType" /> * &lt;attribute name="currentUnit" type="{urn:mpeg:mpeg-v:2010:01-CT-NS}unitType" /> * &lt;attribute name="vibrationUnit" type="{urn:mpeg:mpeg-v:2010:01-CT-NS}unitType" /> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "TactilePrefType") public class TactilePrefType extends UserSensoryPreferenceBaseType { @XmlAttribute(name = "maxTemperature") protected Float maxTemperature; @XmlAttribute(name = "minTemperature") protected Float minTemperature; @XmlAttribute(name = "maxCurrent") protected Float maxCurrent; @XmlAttribute(name = "maxVibration") protected Float maxVibration; @XmlAttribute(name = "tempUnit") protected String tempUnit; @XmlAttribute(name = "currentUnit") protected String currentUnit; @XmlAttribute(name = "vibrationUnit") protected String vibrationUnit; /** * Gets the value of the maxTemperature property. * * @return * possible object is * {@link Float } * */ public Float getMaxTemperature() { return maxTemperature; } /** * Sets the value of the maxTemperature property. * * @param value * allowed object is * {@link Float } * */ public void setMaxTemperature(Float value) { this.maxTemperature = value; } /** * Gets the value of the minTemperature property. * * @return * possible object is * {@link Float } * */ public Float getMinTemperature() { return minTemperature; } /** * Sets the value of the minTemperature property. * * @param value * allowed object is * {@link Float } * */ public void setMinTemperature(Float value) { this.minTemperature = value; } /** * Gets the value of the maxCurrent property. * * @return * possible object is * {@link Float } * */ public Float getMaxCurrent() { return maxCurrent; } /** * Sets the value of the maxCurrent property. * * @param value * allowed object is * {@link Float } * */ public void setMaxCurrent(Float value) { this.maxCurrent = value; } /** * Gets the value of the maxVibration property. * * @return * possible object is * {@link Float } * */ public Float getMaxVibration() { return maxVibration; } /** * Sets the value of the maxVibration property. * * @param value * allowed object is * {@link Float } * */ public void setMaxVibration(Float value) { this.maxVibration = value; } /** * Gets the value of the tempUnit property. * * @return * possible object is * {@link String } * */ public String getTempUnit() { return tempUnit; } /** * Sets the value of the tempUnit property. * * @param value * allowed object is * {@link String } * */ public void setTempUnit(String value) { this.tempUnit = value; } /** * Gets the value of the currentUnit property. * * @return * possible object is * {@link String } * */ public String getCurrentUnit() { return currentUnit; } /** * Sets the value of the currentUnit property. * * @param value * allowed object is * {@link String } * */ public void setCurrentUnit(String value) { this.currentUnit = value; } /** * Gets the value of the vibrationUnit property. * * @return * possible object is * {@link String } * */ public String getVibrationUnit() { return vibrationUnit; } /** * Sets the value of the vibrationUnit property. * * @param value * allowed object is * {@link String } * */ public void setVibrationUnit(String value) { this.vibrationUnit = value; } }
lgpl-3.0
ArticulatedSocialAgentsPlatform/AsapRealizer
Experimental/AsapIncrementalTTSEngine/src/asap/incrementalspeechengine/loader/IncrementalTTSEngineLoader.java
8183
/******************************************************************************* * Copyright (C) 2009-2020 Human Media Interaction, University of Twente, the Netherlands * * This file is part of the Articulated Social Agents Platform BML realizer (ASAPRealizer). * * ASAPRealizer is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License (LGPL) as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ASAPRealizer 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 Lesser General Public License * along with ASAPRealizer. If not, see http://www.gnu.org/licenses/. ******************************************************************************/ package asap.incrementalspeechengine.loader; import hmi.environmentbase.ConfigDirLoader; import hmi.environmentbase.Environment; import hmi.environmentbase.Loader; import hmi.tts.util.NullPhonemeToVisemeMapping; import hmi.tts.util.PhonemeToVisemeMapping; import hmi.tts.util.PhonemeToVisemeMappingInfo; import hmi.util.ArrayUtils; import hmi.util.Resources; import hmi.xml.XMLScanException; import hmi.xml.XMLStructureAdapter; import hmi.xml.XMLTokenizer; import inpro.apps.SimpleMonitor; import inpro.apps.util.MonitorCommandLineParser; import inpro.audio.DispatchStream; import inpro.incremental.unit.IU; import inpro.synthesis.MaryAdapter; import inpro.synthesis.MaryAdapter5internal; import inpro.synthesis.hts.IUBasedFullPStream; import inpro.synthesis.hts.VocodingAudioStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import javax.sound.sampled.AudioFormat; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import marytts.util.data.audio.DDSAudioInputStream; import asap.incrementalspeechengine.IncrementalTTSPlanner; import asap.incrementalspeechengine.IncrementalTTSUnit; import asap.incrementalspeechengine.PhraseIUManager; import asap.incrementalspeechengine.SingleThreadedPlanPlayeriSS; import asap.realizer.DefaultEngine; import asap.realizer.DefaultPlayer; import asap.realizer.Engine; import asap.realizer.lipsync.IncrementalLipSynchProvider; import asap.realizer.planunit.PlanManager; import asap.realizerembodiments.AsapRealizerEmbodiment; import asap.realizerembodiments.EngineLoader; import asap.realizerembodiments.IncrementalLipSynchProviderLoader; /** * Loads the IncrementalTTSEngine from XML * @author hvanwelbergen * */ @Slf4j public class IncrementalTTSEngineLoader implements EngineLoader { private Engine engine; private String id; private DispatchStream dispatcher; private PhonemeToVisemeMapping visemeMapping = new NullPhonemeToVisemeMapping(); private Collection<IncrementalLipSynchProvider> lipSynchers = new ArrayList<IncrementalLipSynchProvider>(); private String voicename = null; @Override public Engine getEngine() { return engine; } @Override public String getId() { return id; } private static class DispatcherInfo extends XMLStructureAdapter { @Getter private String filename; @Getter private String resource; public void decodeAttributes(HashMap<String, String> attrMap, XMLTokenizer tokenizer) { filename = getRequiredAttribute("filename", attrMap, tokenizer); resource = getRequiredAttribute("resources", attrMap, tokenizer); } public String getXMLTag() { return XMLTAG; } private static final String XMLTAG = "Dispatcher"; } @Override public void readXML(XMLTokenizer tokenizer, String loaderId, String vhId, String vhName, Environment[] environments, Loader... requiredLoaders) throws IOException { id = loaderId; AsapRealizerEmbodiment realizerEmbodiment = ArrayUtils.getFirstClassOfType(requiredLoaders, AsapRealizerEmbodiment.class); if (realizerEmbodiment == null) { throw new RuntimeException("IncrementalTTSEngineLoader requires an EmbodimentLoader containing a AsapRealizerEmbodiment"); } for (IncrementalLipSynchProviderLoader el : ArrayUtils.getClassesOfType(requiredLoaders, IncrementalLipSynchProviderLoader.class)) { lipSynchers.add(el.getLipSyncProvider()); } DispatcherInfo di = null; ConfigDirLoader maryTTS = new ConfigDirLoader("MARYTTSIncremental", "MaryTTSIncremental") { public void decodeAttributes(HashMap<String, String> attrMap, XMLTokenizer tokenizer) { String language = this.getOptionalAttribute("language", attrMap); voicename = this.getOptionalAttribute("voicename", attrMap); if (language != null) { System.setProperty("inpro.tts.language", language); } if (voicename != null) { System.setProperty("inpro.tts.voice", voicename); } super.decodeAttributes(attrMap, tokenizer); } }; while (tokenizer.atSTag()) { String tag = tokenizer.getTagName(); switch (tag) { case PhonemeToVisemeMappingInfo.XMLTAG: PhonemeToVisemeMappingInfo info = new PhonemeToVisemeMappingInfo(); info.readXML(tokenizer); visemeMapping = info.getMapping(); break; case DispatcherInfo.XMLTAG: di = new DispatcherInfo(); di.readXML(tokenizer); break; case "MaryTTSIncremental": maryTTS.readXML(tokenizer); break; default: throw new XMLScanException("Invalid tag " + tag); } } if (di == null) { throw new RuntimeException("IncrementalTTSEngineLoader requires an Dispatcher specification"); } System.setProperty("mary.base", maryTTS.getConfigDir()); //heating up the tts so that subsequent speech is processed faster DispatchStream dummydispatcher = SimpleMonitor.setupDispatcher(new MonitorCommandLineParser(new String[] { "-D", "-c", "" + new Resources(di.getResource()).getURL(di.getFilename())})); List<IU> wordIUs = MaryAdapter.getInstance().text2IUs("Heating up."); //(source, new AudioFormat(16000.0F, 16, 1, true, false)) dummydispatcher.playStream(new DDSAudioInputStream(new VocodingAudioStream(new IUBasedFullPStream(wordIUs.get(0)), MaryAdapter5internal.getDefaultHMMData(), true), new AudioFormat(16000.0F, 16, 1, true, false)), true); dummydispatcher.waitUntilDone(); dummydispatcher.close(); dispatcher = SimpleMonitor.setupDispatcher(new Resources(di.getResource()).getURL(di.getFilename())); PlanManager<IncrementalTTSUnit> planManager = new PlanManager<IncrementalTTSUnit>(); IncrementalTTSPlanner planner = new IncrementalTTSPlanner(realizerEmbodiment.getFeedbackManager(), planManager, new PhraseIUManager(dispatcher, voicename, realizerEmbodiment.getBmlScheduler()), visemeMapping, lipSynchers); engine = new DefaultEngine<IncrementalTTSUnit>(planner, new DefaultPlayer(new SingleThreadedPlanPlayeriSS<IncrementalTTSUnit>( realizerEmbodiment.getFeedbackManager(), planManager)), planManager); engine.setId(id); MaryAdapter.getInstance(); realizerEmbodiment.addEngine(engine); } @Override public void unload() { try { dispatcher.close(); } catch (IOException e) { log.warn("Error unloading: ", e); } } }
lgpl-3.0
armatys/hypergraphdb-android
hgdb-android/java/src/org/hypergraphdb/util/HGSortedSet.java
1554
/* * This file is part of the HyperGraphDB source distribution. This is copyrighted * software. For permitted uses, licensing options and redistribution, please see * the LicensingInformation file at the root level of the distribution. * * Copyright (c) 2005-2010 Kobrix Software, Inc. All rights reserved. */ package org.hypergraphdb.util; import java.util.SortedSet; import org.hypergraphdb.HGRandomAccessResult; /** * * <p> * A variation of the standard <code>SortedSet</code> interface that offers a * <code>HGRandomAccessResult</code> of its elements in addition to an * <code>Iterator</code>. Also, implementations of this interface are guaranteed * to be thread-safe. This guarantee has a little twist: if you call <code>iterator</code>, * the <code>Iterator</code> returned is not going to be thread-safe and concurrency issues * may arise if the set is being modified while the iterator is still in use. However, * if you call <code>getSearchResult</code> (note that <code>HGRandomAccessResult</code> * extends the <code>Iterator</code> interface), the resulting object will hold * a read lock on the set until its <code>close</code> is invoked. This means that any * thread trying to modify the set while there's an active search result on it will * block, and this includes the thread that opened the search result. * </p> * * @author Borislav Iordanov * * @param <E> */ public interface HGSortedSet<E> extends SortedSet<E> { HGRandomAccessResult<E> getSearchResult(); }
lgpl-3.0
sk89q/Intake
intake-example/src/main/java/com/sk89q/intake/example/sender/UserProvider.java
2046
/* * Intake, a command processing library * Copyright (C) sk89q <http://www.sk89q.com> * Copyright (C) Intake team and contributors * * 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 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 com.sk89q.intake.example.sender; import com.google.common.collect.ImmutableList; import com.sk89q.intake.argument.ArgumentException; import com.sk89q.intake.argument.ArgumentParseException; import com.sk89q.intake.argument.CommandArgs; import com.sk89q.intake.parametric.Provider; import com.sk89q.intake.parametric.ProvisionException; import javax.annotation.Nullable; import java.lang.annotation.Annotation; import java.util.List; import java.util.Map; public class UserProvider implements Provider<User> { private final Map<String, User> users; public UserProvider(Map<String, User> users) { this.users = users; } @Override public boolean isProvided() { return false; } @Nullable @Override public User get(CommandArgs arguments, List<? extends Annotation> modifiers) throws ArgumentException, ProvisionException { String name = arguments.next(); User user = users.get(name); if (user == null) { throw new ArgumentParseException("Couldn't find a user by the name '" + name + "'"); } return user; } @Override public List<String> getSuggestions(String prefix) { return ImmutableList.of(); } }
lgpl-3.0
impetus-opensource/jumbune
debugger/src/main/java/org/jumbune/debugger/instrumentation/adapter/TimerAdapter.java
3456
package org.jumbune.debugger.instrumentation.adapter; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jumbune.common.job.Config; import org.jumbune.debugger.instrumentation.utils.Environment; import org.jumbune.debugger.instrumentation.utils.InstrumentUtil; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.tree.LabelNode; import org.objectweb.asm.tree.LocalVariableNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.VarInsnNode; /** * <p> * This adapter injects code into map/reduce methods to log the execution time * </p> * */ @Deprecated public class TimerAdapter extends BaseAdapter { private static Logger logger = LogManager.getLogger(TimerAdapter.class); private Environment env; /** * <p> * Create a new instance of TimerAdapter. * </p> * * @param cv * Class Visitor */ //TODO: No ref found.... public TimerAdapter(Config config, ClassVisitor cv) { super(config, Opcodes.ASM4); this.cv = cv; } /** * <p> * Create a new instance of TimerAdapter. * </p> * @param loader * @param cv * @param env */ public TimerAdapter(Config config, ClassVisitor cv,Environment env) { super(config, Opcodes.ASM4); this.cv = cv; this.env = env; } /** * visit end method for intrumentation */ @SuppressWarnings("unchecked") @Override public void visitEnd() { if (isMapperClass() || isReducerClass()) { for (Object o : methods) { MethodNode mn = (MethodNode) o; if (InstrumentUtil.validateMapReduceMethod(mn)) { logger.debug("instrumenting " + getClassName() + "##" + mn.name); InsnList list = mn.instructions; AbstractInsnNode[] insnArr = list.toArray(); int variable = mn.maxLocals; // adding variable declaration InsnList il = new InsnList(); LabelNode newLabel = new LabelNode(); il.add(newLabel); il.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "java/lang/System", "currentTimeMillis", Type .getMethodDescriptor(Type.LONG_TYPE))); il.add(new VarInsnNode(Opcodes.LSTORE, variable)); list.insertBefore(list.getFirst(), il); // adding local variable LabelNode begin = new LabelNode(); LabelNode end = new LabelNode(); list.insertBefore(list.getFirst(), begin); list.insert(list.getLast(), end); Type type = Type.LONG_TYPE; LocalVariableNode lv = new LocalVariableNode("startMethod", type.getDescriptor(), null, begin, end, variable); mn.localVariables.add(lv); // finding the return statement for (AbstractInsnNode abstractInsnNode : insnArr) { if (abstractInsnNode.getOpcode() >= Opcodes.IRETURN && abstractInsnNode.getOpcode() <= Opcodes.RETURN) { // adding logging statement String msg = new StringBuilder( "[Method executed] [time] ").toString(); String cSymbol = env.getClassSymbol(getClassName()); String mSymbol = env.getMethodSymbol(getClassName(), cSymbol, mn.name); InsnList il1 = InstrumentUtil.addTimerLogging( cSymbol,mSymbol, variable, msg); list.insertBefore(abstractInsnNode, il1); } } } mn.visitMaxs(0, 0); } } accept(cv); } }
lgpl-3.0
rikarudo/LemPORT
src/normalization/GenderNormalizer.java
2174
package normalization; import java.util.Arrays; import java.util.regex.Pattern; import replacement.Replacement; /** * This class ... * * @author Ricardo Rodrigues * @version 0.9.9 */ public class GenderNormalizer extends Normalizer { private Pattern[] declensionExceptions = null; private Pattern[] declensionTargets = null; private Pattern[] declensionTags = null; private Replacement[] declensions = null; /** * Creates a new <code>GenderNormalizer</code> object ... * * @param declensions ... */ public GenderNormalizer(Replacement[] declensions) { this.declensions = declensions; Arrays.sort(this.declensions); declensionExceptions = new Pattern[this.declensions.length]; declensionTargets = new Pattern[this.declensions.length]; declensionTags = new Pattern[this.declensions.length]; for (int i = 0; i < declensions.length; i++) { declensionExceptions[i] = Pattern.compile(declensions[i].getExceptions()); declensionTargets[i] = Pattern.compile(declensions[i].getPrefix() + declensions[i].getTarget() + declensions[i].getSuffix()); declensionTags[i] = Pattern.compile(declensions[i].getTag()); } } /** * This method retrieves the masculine form of a given token, if it exists, * when classified with a given <em>PoS tag</em>. Otherwise, it retrieves * the same token (in lower case). * * @param token the token whose lemma is wanted * @param tag the <em>PoS tag</em> of the token * @return the masculine form of the token (when with the given tag) */ public String normalize(String token, String tag) { String normalization = token.toLowerCase(); for (int i = 0; i < declensions.length; i++) { if (declensionTargets[i].matcher(normalization).matches() && declensionTags[i].matcher(tag.toLowerCase()).matches() && !declensionExceptions[i].matcher(normalization).matches()) { normalization = normalization.substring(0, normalization.length() - declensions[i].getTarget().length()) + declensions[i].getReplacement(); break; } } return normalization; } }
lgpl-3.0
djvanenckevort/molgenis
molgenis-charts/src/main/java/org/molgenis/charts/calculations/BoxPlotCalcUtil.java
3404
package org.molgenis.charts.calculations; import org.molgenis.charts.MolgenisChartException; import java.util.List; public class BoxPlotCalcUtil { /** * calculates the 5 values needed to create a box plot and returns them in an 5 item sized array. * <p> * Double[0] = minimum; * Double[1] = firstQuantile; * Double[2] = median; * Double[3] = thirdQuantile; * Double[4] = maximum; * * @return Double[] */ public static Double[] calcBoxPlotValues(List<Double> sortedDataAscendingOrder) { if (null == sortedDataAscendingOrder) { throw new MolgenisChartException("The sortedDataAscendingOrder list is null"); } if (sortedDataAscendingOrder.isEmpty()) { return new Double[] { 0d, 0d, 0d, 0d, 0d }; } Double[] plotBoxValues = new Double[5]; plotBoxValues[0] = minimum(sortedDataAscendingOrder); plotBoxValues[1] = firstQuantile(sortedDataAscendingOrder); plotBoxValues[2] = median(sortedDataAscendingOrder); plotBoxValues[3] = thirdQuantile(sortedDataAscendingOrder); plotBoxValues[4] = maximum(sortedDataAscendingOrder); return plotBoxValues; } /** * IQR inner quartile range */ public static double iqr(double thirdQuantile, double firstQuantile) { return thirdQuantile - firstQuantile; } /** * Get the minimum value thru linear interpolations * * @return Double */ public static Double minimum(List<Double> sortedDataAscendingOrder) { return interpolateLinearlyQuantile(sortedDataAscendingOrder, (double) 0); } /** * Get the maximum value thru linear interpolations * * @return Double */ public static Double maximum(List<Double> sortedDataAscendingOrder) { return interpolateLinearlyQuantile(sortedDataAscendingOrder, (double) 1); } /** * Get the median value thru linear interpolations * * @return Double */ public static Double median(List<Double> sortedDataAscendingOrder) { return interpolateLinearlyQuantile(sortedDataAscendingOrder, 0.50); } /** * Get the firstQuantile value thru linear interpolations * * @return Double */ public static Double firstQuantile(List<Double> sortedDataAscendingOrder) { return interpolateLinearlyQuantile(sortedDataAscendingOrder, 0.25); } /** * Get the thirdQuantile value thru linear interpolations * * @return Double */ public static Double thirdQuantile(List<Double> sortedDataAscendingOrder) { return interpolateLinearlyQuantile(sortedDataAscendingOrder, 0.75); } /** * Interpolate linearly an quantile * <p> * Inspired on: http://msenux.redwoods.edu/math/R/boxplot.php * * @param sortedDataAscendingOrder sorted data in ascending order (NOT NULL) * @param p percentage * @return Double interpolated linearly quantile */ private static Double interpolateLinearlyQuantile(List<Double> sortedDataAscendingOrder, Double p) { int n = sortedDataAscendingOrder.size(); double position = (1 + (p * (n - 1))); int leftIndex = (int) Math.floor(position) - 1; int rightIndex = (int) Math.ceil(position) - 1; Double quantile; if (leftIndex == rightIndex) { quantile = sortedDataAscendingOrder.get(leftIndex); } else { Double leftIndexValue = sortedDataAscendingOrder.get(leftIndex); Double rightIndexValue = sortedDataAscendingOrder.get(rightIndex); quantile = leftIndexValue + 0.5 * (rightIndexValue - leftIndexValue); } return quantile; } }
lgpl-3.0
F1r3w477/CustomWorldGen
build/tmp/recompileMc/sources/net/minecraft/entity/player/EntityPlayerMP.java
50878
package net.minecraft.entity.player; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.mojang.authlib.GameProfile; import io.netty.buffer.Unpooled; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.annotation.Nullable; import net.minecraft.block.Block; import net.minecraft.block.BlockFence; import net.minecraft.block.BlockFenceGate; import net.minecraft.block.BlockWall; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.crash.CrashReport; import net.minecraft.crash.CrashReportCategory; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityList; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.IMerchant; import net.minecraft.entity.passive.EntityHorse; import net.minecraft.entity.projectile.EntityArrow; import net.minecraft.init.Items; import net.minecraft.init.SoundEvents; import net.minecraft.inventory.Container; import net.minecraft.inventory.ContainerChest; import net.minecraft.inventory.ContainerHorseInventory; import net.minecraft.inventory.ContainerMerchant; import net.minecraft.inventory.IContainerListener; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.SlotCrafting; import net.minecraft.item.Item; import net.minecraft.item.ItemMapBase; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.NetHandlerPlayServer; import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.client.CPacketClientSettings; import net.minecraft.network.play.server.SPacketAnimation; import net.minecraft.network.play.server.SPacketCamera; import net.minecraft.network.play.server.SPacketChangeGameState; import net.minecraft.network.play.server.SPacketChat; import net.minecraft.network.play.server.SPacketCloseWindow; import net.minecraft.network.play.server.SPacketCombatEvent; import net.minecraft.network.play.server.SPacketCustomPayload; import net.minecraft.network.play.server.SPacketDestroyEntities; import net.minecraft.network.play.server.SPacketEffect; import net.minecraft.network.play.server.SPacketEntityEffect; import net.minecraft.network.play.server.SPacketEntityStatus; import net.minecraft.network.play.server.SPacketOpenWindow; import net.minecraft.network.play.server.SPacketPlayerAbilities; import net.minecraft.network.play.server.SPacketRemoveEntityEffect; import net.minecraft.network.play.server.SPacketResourcePackSend; import net.minecraft.network.play.server.SPacketSetExperience; import net.minecraft.network.play.server.SPacketSetSlot; import net.minecraft.network.play.server.SPacketSignEditorOpen; import net.minecraft.network.play.server.SPacketSoundEffect; import net.minecraft.network.play.server.SPacketUpdateHealth; import net.minecraft.network.play.server.SPacketUpdateTileEntity; import net.minecraft.network.play.server.SPacketUseBed; import net.minecraft.network.play.server.SPacketWindowItems; import net.minecraft.network.play.server.SPacketWindowProperty; import net.minecraft.potion.PotionEffect; import net.minecraft.scoreboard.IScoreCriteria; import net.minecraft.scoreboard.Score; import net.minecraft.scoreboard.ScoreObjective; import net.minecraft.scoreboard.Team; import net.minecraft.server.MinecraftServer; import net.minecraft.server.management.PlayerInteractionManager; import net.minecraft.server.management.UserListOpsEntry; import net.minecraft.stats.Achievement; import net.minecraft.stats.AchievementList; import net.minecraft.stats.StatBase; import net.minecraft.stats.StatList; import net.minecraft.stats.StatisticsManagerServer; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityCommandBlock; import net.minecraft.tileentity.TileEntitySign; import net.minecraft.util.CooldownTracker; import net.minecraft.util.CooldownTrackerServer; import net.minecraft.util.DamageSource; import net.minecraft.util.EntityDamageSource; import net.minecraft.util.EnumHand; import net.minecraft.util.EnumHandSide; import net.minecraft.util.JsonSerializableSet; import net.minecraft.util.ReportedException; import net.minecraft.util.SoundCategory; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.Style; import net.minecraft.util.text.TextComponentTranslation; import net.minecraft.util.text.TextFormatting; import net.minecraft.village.MerchantRecipeList; import net.minecraft.world.GameType; import net.minecraft.world.IInteractionObject; import net.minecraft.world.ILockableContainer; import net.minecraft.world.WorldServer; import net.minecraft.world.biome.Biome; import net.minecraft.world.storage.loot.ILootContainer; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class EntityPlayerMP extends EntityPlayer implements IContainerListener { private static final Logger LOGGER = LogManager.getLogger(); private String language = "en_US"; /** The NetServerHandler assigned to this player by the ServerConfigurationManager. */ public NetHandlerPlayServer connection; /** Reference to the MinecraftServer object. */ public final MinecraftServer mcServer; /** The player interaction manager for this player */ public final PlayerInteractionManager interactionManager; /** player X position as seen by PlayerManager */ public double managedPosX; /** player Z position as seen by PlayerManager */ public double managedPosZ; private final List<Integer> entityRemoveQueue = Lists.<Integer>newLinkedList(); private final StatisticsManagerServer statsFile; /** the total health of the player, includes actual health and absorption health. Updated every tick. */ private float lastHealthScore = Float.MIN_VALUE; private int lastFoodScore = Integer.MIN_VALUE; private int lastAirScore = Integer.MIN_VALUE; private int lastArmorScore = Integer.MIN_VALUE; private int lastLevelScore = Integer.MIN_VALUE; private int lastExperienceScore = Integer.MIN_VALUE; /** amount of health the client was last set to */ private float lastHealth = -1.0E8F; /** set to foodStats.GetFoodLevel */ private int lastFoodLevel = -99999999; /** set to foodStats.getSaturationLevel() == 0.0F each tick */ private boolean wasHungry = true; /** Amount of experience the client was last set to */ private int lastExperience = -99999999; private int respawnInvulnerabilityTicks = 60; private EntityPlayer.EnumChatVisibility chatVisibility; private boolean chatColours = true; private long playerLastActiveTime = System.currentTimeMillis(); /** The entity the player is currently spectating through. */ private Entity spectatingEntity; private boolean invulnerableDimensionChange; /** The currently in use window ID. Incremented every time a window is opened. */ public int currentWindowId; /** * set to true when player is moving quantity of items from one inventory to another(crafting) but item in either * slot is not changed */ public boolean isChangingQuantityOnly; public int ping; /** * Set when a player beats the ender dragon, used to respawn the player at the spawn point while retaining inventory * and XP */ public boolean playerConqueredTheEnd; @SuppressWarnings("unused") public EntityPlayerMP(MinecraftServer server, WorldServer worldIn, GameProfile profile, PlayerInteractionManager interactionManagerIn) { super(worldIn, profile); interactionManagerIn.thisPlayerMP = this; this.interactionManager = interactionManagerIn; BlockPos blockpos = worldIn.provider.getRandomizedSpawnPoint(); if (false && !worldIn.provider.getHasNoSky() && worldIn.getWorldInfo().getGameType() != GameType.ADVENTURE) { int i = Math.max(0, server.getSpawnRadius(worldIn)); int j = MathHelper.floor_double(worldIn.getWorldBorder().getClosestDistance((double)blockpos.getX(), (double)blockpos.getZ())); if (j < i) { i = j; } if (j <= 1) { i = 1; } blockpos = worldIn.getTopSolidOrLiquidBlock(blockpos.add(this.rand.nextInt(i * 2 + 1) - i, 0, this.rand.nextInt(i * 2 + 1) - i)); } this.mcServer = server; this.statsFile = server.getPlayerList().getPlayerStatsFile(this); this.stepHeight = 0.0F; this.moveToBlockPosAndAngles(blockpos, 0.0F, 0.0F); while (!worldIn.getCollisionBoxes(this, this.getEntityBoundingBox()).isEmpty() && this.posY < 255.0D) { this.setPosition(this.posX, this.posY + 1.0D, this.posZ); } } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ public void readEntityFromNBT(NBTTagCompound compound) { super.readEntityFromNBT(compound); if (compound.hasKey("playerGameType", 99)) { if (this.getServer().getForceGamemode()) { this.interactionManager.setGameType(this.getServer().getGameType()); } else { this.interactionManager.setGameType(GameType.getByID(compound.getInteger("playerGameType"))); } } } /** * (abstract) Protected helper method to write subclass entity data to NBT. */ public void writeEntityToNBT(NBTTagCompound compound) { super.writeEntityToNBT(compound); compound.setInteger("playerGameType", this.interactionManager.getGameType().getID()); Entity entity = this.getLowestRidingEntity(); if (this.getRidingEntity() != null && entity != this & entity.getRecursivePassengersByType(EntityPlayerMP.class).size() == 1) { NBTTagCompound nbttagcompound = new NBTTagCompound(); NBTTagCompound nbttagcompound1 = new NBTTagCompound(); entity.writeToNBTOptional(nbttagcompound1); nbttagcompound.setUniqueId("Attach", this.getRidingEntity().getUniqueID()); nbttagcompound.setTag("Entity", nbttagcompound1); compound.setTag("RootVehicle", nbttagcompound); } } /** * Add experience levels to this player. */ public void addExperienceLevel(int levels) { super.addExperienceLevel(levels); this.lastExperience = -1; } public void removeExperienceLevel(int levels) { super.removeExperienceLevel(levels); this.lastExperience = -1; } public void addSelfToInternalCraftingInventory() { this.openContainer.addListener(this); } /** * Sends an ENTER_COMBAT packet to the client */ public void sendEnterCombat() { super.sendEnterCombat(); this.connection.sendPacket(new SPacketCombatEvent(this.getCombatTracker(), SPacketCombatEvent.Event.ENTER_COMBAT)); } /** * Sends an END_COMBAT packet to the client */ public void sendEndCombat() { super.sendEndCombat(); this.connection.sendPacket(new SPacketCombatEvent(this.getCombatTracker(), SPacketCombatEvent.Event.END_COMBAT)); } protected CooldownTracker createCooldownTracker() { return new CooldownTrackerServer(this); } /** * Called to update the entity's position/logic. */ public void onUpdate() { this.interactionManager.updateBlockRemoving(); --this.respawnInvulnerabilityTicks; if (this.hurtResistantTime > 0) { --this.hurtResistantTime; } this.openContainer.detectAndSendChanges(); if (!this.worldObj.isRemote && this.openContainer != null && !this.openContainer.canInteractWith(this)) { this.closeScreen(); this.openContainer = this.inventoryContainer; } while (!this.entityRemoveQueue.isEmpty()) { int i = Math.min(this.entityRemoveQueue.size(), Integer.MAX_VALUE); int[] aint = new int[i]; Iterator<Integer> iterator = this.entityRemoveQueue.iterator(); int j = 0; while (iterator.hasNext() && j < i) { aint[j++] = ((Integer)iterator.next()).intValue(); iterator.remove(); } this.connection.sendPacket(new SPacketDestroyEntities(aint)); } Entity entity = this.getSpectatingEntity(); if (entity != this) { if (entity.isEntityAlive()) { this.setPositionAndRotation(entity.posX, entity.posY, entity.posZ, entity.rotationYaw, entity.rotationPitch); this.mcServer.getPlayerList().serverUpdateMountedMovingPlayer(this); if (this.isSneaking()) { this.setSpectatingEntity(this); } } else { this.setSpectatingEntity(this); } } } public void onUpdateEntity() { try { super.onUpdate(); for (int i = 0; i < this.inventory.getSizeInventory(); ++i) { ItemStack itemstack = this.inventory.getStackInSlot(i); if (itemstack != null && itemstack.getItem().isMap()) { Packet<?> packet = ((ItemMapBase)itemstack.getItem()).createMapDataPacket(itemstack, this.worldObj, this); if (packet != null) { this.connection.sendPacket(packet); } } } if (this.getHealth() != this.lastHealth || this.lastFoodLevel != this.foodStats.getFoodLevel() || this.foodStats.getSaturationLevel() == 0.0F != this.wasHungry) { this.connection.sendPacket(new SPacketUpdateHealth(this.getHealth(), this.foodStats.getFoodLevel(), this.foodStats.getSaturationLevel())); this.lastHealth = this.getHealth(); this.lastFoodLevel = this.foodStats.getFoodLevel(); this.wasHungry = this.foodStats.getSaturationLevel() == 0.0F; } if (this.getHealth() + this.getAbsorptionAmount() != this.lastHealthScore) { this.lastHealthScore = this.getHealth() + this.getAbsorptionAmount(); this.updateScorePoints(IScoreCriteria.HEALTH, MathHelper.ceiling_float_int(this.lastHealthScore)); } if (this.foodStats.getFoodLevel() != this.lastFoodScore) { this.lastFoodScore = this.foodStats.getFoodLevel(); this.updateScorePoints(IScoreCriteria.FOOD, MathHelper.ceiling_float_int((float)this.lastFoodScore)); } if (this.getAir() != this.lastAirScore) { this.lastAirScore = this.getAir(); this.updateScorePoints(IScoreCriteria.AIR, MathHelper.ceiling_float_int((float)this.lastAirScore)); } if (this.getTotalArmorValue() != this.lastArmorScore) { this.lastArmorScore = this.getTotalArmorValue(); this.updateScorePoints(IScoreCriteria.ARMOR, MathHelper.ceiling_float_int((float)this.lastArmorScore)); } if (this.experienceTotal != this.lastExperienceScore) { this.lastExperienceScore = this.experienceTotal; this.updateScorePoints(IScoreCriteria.XP, MathHelper.ceiling_float_int((float)this.lastExperienceScore)); } if (this.experienceLevel != this.lastLevelScore) { this.lastLevelScore = this.experienceLevel; this.updateScorePoints(IScoreCriteria.LEVEL, MathHelper.ceiling_float_int((float)this.lastLevelScore)); } if (this.experienceTotal != this.lastExperience) { this.lastExperience = this.experienceTotal; this.connection.sendPacket(new SPacketSetExperience(this.experience, this.experienceTotal, this.experienceLevel)); } if (this.ticksExisted % 20 * 5 == 0 && !this.getStatFile().hasAchievementUnlocked(AchievementList.EXPLORE_ALL_BIOMES)) { this.updateBiomesExplored(); } } catch (Throwable throwable) { CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Ticking player"); CrashReportCategory crashreportcategory = crashreport.makeCategory("Player being ticked"); this.addEntityCrashInfo(crashreportcategory); throw new ReportedException(crashreport); } } private void updateScorePoints(IScoreCriteria criteria, int points) { for (ScoreObjective scoreobjective : this.getWorldScoreboard().getObjectivesFromCriteria(criteria)) { Score score = this.getWorldScoreboard().getOrCreateScore(this.getName(), scoreobjective); score.setScorePoints(points); } } /** * Updates all biomes that have been explored by this player and triggers Adventuring Time if player qualifies. */ protected void updateBiomesExplored() { Biome biome = this.worldObj.getBiome(new BlockPos(MathHelper.floor_double(this.posX), 0, MathHelper.floor_double(this.posZ))); String s = biome.getBiomeName(); JsonSerializableSet jsonserializableset = (JsonSerializableSet)this.getStatFile().getProgress(AchievementList.EXPLORE_ALL_BIOMES); if (jsonserializableset == null) { jsonserializableset = (JsonSerializableSet)this.getStatFile().setProgress(AchievementList.EXPLORE_ALL_BIOMES, new JsonSerializableSet()); } jsonserializableset.add(s); if (this.getStatFile().canUnlockAchievement(AchievementList.EXPLORE_ALL_BIOMES) && jsonserializableset.size() >= Biome.EXPLORATION_BIOMES_LIST.size()) { Set<Biome> set = Sets.newHashSet(Biome.EXPLORATION_BIOMES_LIST); for (String s1 : jsonserializableset) { Iterator<Biome> iterator = set.iterator(); while (iterator.hasNext()) { Biome biome1 = (Biome)iterator.next(); if (biome1.getBiomeName().equals(s1)) { iterator.remove(); } } if (set.isEmpty()) { break; } } if (set.isEmpty()) { this.addStat(AchievementList.EXPLORE_ALL_BIOMES); } } } /** * Called when the mob's health reaches 0. */ public void onDeath(DamageSource cause) { if (net.minecraftforge.common.ForgeHooks.onLivingDeath(this, cause)) return; boolean flag = this.worldObj.getGameRules().getBoolean("showDeathMessages"); this.connection.sendPacket(new SPacketCombatEvent(this.getCombatTracker(), SPacketCombatEvent.Event.ENTITY_DIED, flag)); if (flag) { Team team = this.getTeam(); if (team != null && team.getDeathMessageVisibility() != Team.EnumVisible.ALWAYS) { if (team.getDeathMessageVisibility() == Team.EnumVisible.HIDE_FOR_OTHER_TEAMS) { this.mcServer.getPlayerList().sendMessageToAllTeamMembers(this, this.getCombatTracker().getDeathMessage()); } else if (team.getDeathMessageVisibility() == Team.EnumVisible.HIDE_FOR_OWN_TEAM) { this.mcServer.getPlayerList().sendMessageToTeamOrAllPlayers(this, this.getCombatTracker().getDeathMessage()); } } else { this.mcServer.getPlayerList().sendChatMsg(this.getCombatTracker().getDeathMessage()); } } if (!this.worldObj.getGameRules().getBoolean("keepInventory") && !this.isSpectator()) { captureDrops = true; capturedDrops.clear(); this.inventory.dropAllItems(); captureDrops = false; net.minecraftforge.event.entity.player.PlayerDropsEvent event = new net.minecraftforge.event.entity.player.PlayerDropsEvent(this, cause, capturedDrops, recentlyHit > 0); if (!net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(event)) { for (net.minecraft.entity.item.EntityItem item : capturedDrops) { this.worldObj.spawnEntityInWorld(item); } } } for (ScoreObjective scoreobjective : this.worldObj.getScoreboard().getObjectivesFromCriteria(IScoreCriteria.DEATH_COUNT)) { Score score = this.getWorldScoreboard().getOrCreateScore(this.getName(), scoreobjective); score.incrementScore(); } EntityLivingBase entitylivingbase = this.getAttackingEntity(); if (entitylivingbase != null) { EntityList.EntityEggInfo entitylist$entityegginfo = (EntityList.EntityEggInfo)EntityList.ENTITY_EGGS.get(EntityList.getEntityString(entitylivingbase)); if (entitylist$entityegginfo != null) { this.addStat(entitylist$entityegginfo.entityKilledByStat); } entitylivingbase.addToPlayerScore(this, this.scoreValue); } this.addStat(StatList.DEATHS); this.takeStat(StatList.TIME_SINCE_DEATH); this.getCombatTracker().reset(); } /** * Called when the entity is attacked. */ public boolean attackEntityFrom(DamageSource source, float amount) { if (this.isEntityInvulnerable(source)) { return false; } else { boolean flag = this.mcServer.isDedicatedServer() && this.canPlayersAttack() && "fall".equals(source.damageType); if (!flag && this.respawnInvulnerabilityTicks > 0 && source != DamageSource.outOfWorld) { return false; } else { if (source instanceof EntityDamageSource) { Entity entity = source.getEntity(); if (entity instanceof EntityPlayer && !this.canAttackPlayer((EntityPlayer)entity)) { return false; } if (entity instanceof EntityArrow) { EntityArrow entityarrow = (EntityArrow)entity; if (entityarrow.shootingEntity instanceof EntityPlayer && !this.canAttackPlayer((EntityPlayer)entityarrow.shootingEntity)) { return false; } } } return super.attackEntityFrom(source, amount); } } } public boolean canAttackPlayer(EntityPlayer other) { return !this.canPlayersAttack() ? false : super.canAttackPlayer(other); } /** * Returns if other players can attack this player */ private boolean canPlayersAttack() { return this.mcServer.isPVPEnabled(); } @Nullable public Entity changeDimension(int dimensionIn) { if (!net.minecraftforge.common.ForgeHooks.onTravelToDimension(this, dimensionIn)) return this; this.invulnerableDimensionChange = true; if (this.dimension == 1 && dimensionIn == 1) { this.worldObj.removeEntity(this); if (!this.playerConqueredTheEnd) { this.playerConqueredTheEnd = true; if (this.hasAchievement(AchievementList.THE_END2)) { this.connection.sendPacket(new SPacketChangeGameState(4, 0.0F)); } else { this.addStat(AchievementList.THE_END2); this.connection.sendPacket(new SPacketChangeGameState(4, 1.0F)); } } return this; } else { if (this.dimension == 0 && dimensionIn == 1) { this.addStat(AchievementList.THE_END); dimensionIn = 1; } else { this.addStat(AchievementList.PORTAL); } this.mcServer.getPlayerList().changePlayerDimension(this, dimensionIn); this.connection.sendPacket(new SPacketEffect(1032, BlockPos.ORIGIN, 0, false)); this.lastExperience = -1; this.lastHealth = -1.0F; this.lastFoodLevel = -1; return this; } } public boolean isSpectatedByPlayer(EntityPlayerMP player) { return player.isSpectator() ? this.getSpectatingEntity() == this : (this.isSpectator() ? false : super.isSpectatedByPlayer(player)); } private void sendTileEntityUpdate(TileEntity p_147097_1_) { if (p_147097_1_ != null) { SPacketUpdateTileEntity spacketupdatetileentity = p_147097_1_.getUpdatePacket(); if (spacketupdatetileentity != null) { this.connection.sendPacket(spacketupdatetileentity); } } } /** * Called when the entity picks up an item. */ public void onItemPickup(Entity entityIn, int quantity) { super.onItemPickup(entityIn, quantity); this.openContainer.detectAndSendChanges(); } public EntityPlayer.SleepResult trySleep(BlockPos bedLocation) { EntityPlayer.SleepResult entityplayer$sleepresult = super.trySleep(bedLocation); if (entityplayer$sleepresult == EntityPlayer.SleepResult.OK) { this.addStat(StatList.SLEEP_IN_BED); Packet<?> packet = new SPacketUseBed(this, bedLocation); this.getServerWorld().getEntityTracker().sendToAllTrackingEntity(this, packet); this.connection.setPlayerLocation(this.posX, this.posY, this.posZ, this.rotationYaw, this.rotationPitch); this.connection.sendPacket(packet); } return entityplayer$sleepresult; } /** * Wake up the player if they're sleeping. */ public void wakeUpPlayer(boolean immediately, boolean updateWorldFlag, boolean setSpawn) { if (this.isPlayerSleeping()) { this.getServerWorld().getEntityTracker().sendToTrackingAndSelf(this, new SPacketAnimation(this, 2)); } super.wakeUpPlayer(immediately, updateWorldFlag, setSpawn); if (this.connection != null) { this.connection.setPlayerLocation(this.posX, this.posY, this.posZ, this.rotationYaw, this.rotationPitch); } } public boolean startRiding(Entity entityIn, boolean force) { Entity entity = this.getRidingEntity(); if (!super.startRiding(entityIn, force)) { return false; } else { Entity entity1 = this.getRidingEntity(); if (entity1 != entity && this.connection != null) { this.connection.setPlayerLocation(this.posX, this.posY, this.posZ, this.rotationYaw, this.rotationPitch); } return true; } } public void dismountRidingEntity() { Entity entity = this.getRidingEntity(); super.dismountRidingEntity(); Entity entity1 = this.getRidingEntity(); if (entity1 != entity && this.connection != null) { this.connection.setPlayerLocation(this.posX, this.posY, this.posZ, this.rotationYaw, this.rotationPitch); } } /** * Returns whether this Entity is invulnerable to the given DamageSource. */ public boolean isEntityInvulnerable(DamageSource source) { return super.isEntityInvulnerable(source) || this.isInvulnerableDimensionChange(); } protected void updateFallState(double y, boolean onGroundIn, IBlockState state, BlockPos pos) { } protected void frostWalk(BlockPos pos) { if (!this.isSpectator()) { super.frostWalk(pos); } } /** * process player falling based on movement packet */ public void handleFalling(double y, boolean onGroundIn) { int i = MathHelper.floor_double(this.posX); int j = MathHelper.floor_double(this.posY - 0.20000000298023224D); int k = MathHelper.floor_double(this.posZ); BlockPos blockpos = new BlockPos(i, j, k); IBlockState iblockstate = this.worldObj.getBlockState(blockpos); if (iblockstate.getBlock().isAir(iblockstate, this.worldObj, blockpos)) { BlockPos blockpos1 = blockpos.down(); IBlockState iblockstate1 = this.worldObj.getBlockState(blockpos1); Block block = iblockstate1.getBlock(); if (block instanceof BlockFence || block instanceof BlockWall || block instanceof BlockFenceGate) { blockpos = blockpos1; iblockstate = iblockstate1; } } super.updateFallState(y, onGroundIn, iblockstate, blockpos); } public void openEditSign(TileEntitySign signTile) { signTile.setPlayer(this); this.connection.sendPacket(new SPacketSignEditorOpen(signTile.getPos())); } /** * get the next window id to use */ public void getNextWindowId() { this.currentWindowId = this.currentWindowId % 100 + 1; } public void displayGui(IInteractionObject guiOwner) { if (guiOwner instanceof ILootContainer && ((ILootContainer)guiOwner).getLootTable() != null && this.isSpectator()) { this.addChatMessage((new TextComponentTranslation("container.spectatorCantOpen", new Object[0])).setStyle((new Style()).setColor(TextFormatting.RED))); } else { this.getNextWindowId(); this.connection.sendPacket(new SPacketOpenWindow(this.currentWindowId, guiOwner.getGuiID(), guiOwner.getDisplayName())); this.openContainer = guiOwner.createContainer(this.inventory, this); this.openContainer.windowId = this.currentWindowId; this.openContainer.addListener(this); net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.entity.player.PlayerContainerEvent.Open(this, this.openContainer)); } } /** * Displays the GUI for interacting with a chest inventory. */ public void displayGUIChest(IInventory chestInventory) { if (chestInventory instanceof ILootContainer && ((ILootContainer)chestInventory).getLootTable() != null && this.isSpectator()) { this.addChatMessage((new TextComponentTranslation("container.spectatorCantOpen", new Object[0])).setStyle((new Style()).setColor(TextFormatting.RED))); } else { if (this.openContainer != this.inventoryContainer) { this.closeScreen(); } if (chestInventory instanceof ILockableContainer) { ILockableContainer ilockablecontainer = (ILockableContainer)chestInventory; if (ilockablecontainer.isLocked() && !this.canOpen(ilockablecontainer.getLockCode()) && !this.isSpectator()) { this.connection.sendPacket(new SPacketChat(new TextComponentTranslation("container.isLocked", new Object[] {chestInventory.getDisplayName()}), (byte)2)); this.connection.sendPacket(new SPacketSoundEffect(SoundEvents.BLOCK_CHEST_LOCKED, SoundCategory.BLOCKS, this.posX, this.posY, this.posZ, 1.0F, 1.0F)); return; } } this.getNextWindowId(); if (chestInventory instanceof IInteractionObject) { this.connection.sendPacket(new SPacketOpenWindow(this.currentWindowId, ((IInteractionObject)chestInventory).getGuiID(), chestInventory.getDisplayName(), chestInventory.getSizeInventory())); this.openContainer = ((IInteractionObject)chestInventory).createContainer(this.inventory, this); } else { this.connection.sendPacket(new SPacketOpenWindow(this.currentWindowId, "minecraft:container", chestInventory.getDisplayName(), chestInventory.getSizeInventory())); this.openContainer = new ContainerChest(this.inventory, chestInventory, this); } this.openContainer.windowId = this.currentWindowId; this.openContainer.addListener(this); net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.entity.player.PlayerContainerEvent.Open(this, this.openContainer)); } } public void displayVillagerTradeGui(IMerchant villager) { this.getNextWindowId(); this.openContainer = new ContainerMerchant(this.inventory, villager, this.worldObj); this.openContainer.windowId = this.currentWindowId; this.openContainer.addListener(this); net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.entity.player.PlayerContainerEvent.Open(this, this.openContainer)); IInventory iinventory = ((ContainerMerchant)this.openContainer).getMerchantInventory(); ITextComponent itextcomponent = villager.getDisplayName(); this.connection.sendPacket(new SPacketOpenWindow(this.currentWindowId, "minecraft:villager", itextcomponent, iinventory.getSizeInventory())); MerchantRecipeList merchantrecipelist = villager.getRecipes(this); if (merchantrecipelist != null) { PacketBuffer packetbuffer = new PacketBuffer(Unpooled.buffer()); packetbuffer.writeInt(this.currentWindowId); merchantrecipelist.writeToBuf(packetbuffer); this.connection.sendPacket(new SPacketCustomPayload("MC|TrList", packetbuffer)); } } public void openGuiHorseInventory(EntityHorse horse, IInventory inventoryIn) { if (this.openContainer != this.inventoryContainer) { this.closeScreen(); } this.getNextWindowId(); this.connection.sendPacket(new SPacketOpenWindow(this.currentWindowId, "EntityHorse", inventoryIn.getDisplayName(), inventoryIn.getSizeInventory(), horse.getEntityId())); this.openContainer = new ContainerHorseInventory(this.inventory, inventoryIn, horse, this); this.openContainer.windowId = this.currentWindowId; this.openContainer.addListener(this); } public void openBook(ItemStack stack, EnumHand hand) { Item item = stack.getItem(); if (item == Items.WRITTEN_BOOK) { PacketBuffer packetbuffer = new PacketBuffer(Unpooled.buffer()); packetbuffer.writeEnumValue(hand); this.connection.sendPacket(new SPacketCustomPayload("MC|BOpen", packetbuffer)); } } public void displayGuiCommandBlock(TileEntityCommandBlock commandBlock) { commandBlock.setSendToClient(true); this.sendTileEntityUpdate(commandBlock); } /** * Sends the contents of an inventory slot to the client-side Container. This doesn't have to match the actual * contents of that slot. */ public void sendSlotContents(Container containerToSend, int slotInd, ItemStack stack) { if (!(containerToSend.getSlot(slotInd) instanceof SlotCrafting)) { if (!this.isChangingQuantityOnly) { this.connection.sendPacket(new SPacketSetSlot(containerToSend.windowId, slotInd, stack)); } } } public void sendContainerToPlayer(Container containerIn) { this.updateCraftingInventory(containerIn, containerIn.getInventory()); } /** * update the crafting window inventory with the items in the list */ public void updateCraftingInventory(Container containerToSend, List<ItemStack> itemsList) { this.connection.sendPacket(new SPacketWindowItems(containerToSend.windowId, itemsList)); this.connection.sendPacket(new SPacketSetSlot(-1, -1, this.inventory.getItemStack())); } /** * Sends two ints to the client-side Container. Used for furnace burning time, smelting progress, brewing progress, * and enchanting level. Normally the first int identifies which variable to update, and the second contains the new * value. Both are truncated to shorts in non-local SMP. */ public void sendProgressBarUpdate(Container containerIn, int varToUpdate, int newValue) { this.connection.sendPacket(new SPacketWindowProperty(containerIn.windowId, varToUpdate, newValue)); } public void sendAllWindowProperties(Container containerIn, IInventory inventory) { for (int i = 0; i < inventory.getFieldCount(); ++i) { this.connection.sendPacket(new SPacketWindowProperty(containerIn.windowId, i, inventory.getField(i))); } } /** * set current crafting inventory back to the 2x2 square */ public void closeScreen() { this.connection.sendPacket(new SPacketCloseWindow(this.openContainer.windowId)); this.closeContainer(); } /** * updates item held by mouse */ public void updateHeldItem() { if (!this.isChangingQuantityOnly) { this.connection.sendPacket(new SPacketSetSlot(-1, -1, this.inventory.getItemStack())); } } /** * Closes the container the player currently has open. */ public void closeContainer() { this.openContainer.onContainerClosed(this); net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.entity.player.PlayerContainerEvent.Close(this, this.openContainer)); this.openContainer = this.inventoryContainer; } public void setEntityActionState(float strafe, float forward, boolean jumping, boolean sneaking) { if (this.isRiding()) { if (strafe >= -1.0F && strafe <= 1.0F) { this.moveStrafing = strafe; } if (forward >= -1.0F && forward <= 1.0F) { this.moveForward = forward; } this.isJumping = jumping; this.setSneaking(sneaking); } } public boolean hasAchievement(Achievement achievementIn) { return this.statsFile.hasAchievementUnlocked(achievementIn); } /** * Adds a value to a statistic field. */ public void addStat(StatBase stat, int amount) { if (stat != null) { if (stat.isAchievement() && net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.entity.player.AchievementEvent(this, (net.minecraft.stats.Achievement) stat))) return; this.statsFile.increaseStat(this, stat, amount); for (ScoreObjective scoreobjective : this.getWorldScoreboard().getObjectivesFromCriteria(stat.getCriteria())) { this.getWorldScoreboard().getOrCreateScore(this.getName(), scoreobjective).increaseScore(amount); } if (this.statsFile.hasUnsentAchievement()) { this.statsFile.sendStats(this); } } } public void takeStat(StatBase stat) { if (stat != null) { this.statsFile.unlockAchievement(this, stat, 0); for (ScoreObjective scoreobjective : this.getWorldScoreboard().getObjectivesFromCriteria(stat.getCriteria())) { this.getWorldScoreboard().getOrCreateScore(this.getName(), scoreobjective).setScorePoints(0); } if (this.statsFile.hasUnsentAchievement()) { this.statsFile.sendStats(this); } } } public void mountEntityAndWakeUp() { this.removePassengers(); if (this.sleeping) { this.wakeUpPlayer(true, false, false); } } /** * this function is called when a players inventory is sent to him, lastHealth is updated on any dimension * transitions, then reset. */ public void setPlayerHealthUpdated() { this.lastHealth = -1.0E8F; } public void addChatComponentMessage(ITextComponent chatComponent) { this.connection.sendPacket(new SPacketChat(chatComponent)); } /** * Used for when item use count runs out, ie: eating completed */ protected void onItemUseFinish() { if (this.activeItemStack != null && this.isHandActive()) { this.connection.sendPacket(new SPacketEntityStatus(this, (byte)9)); super.onItemUseFinish(); } } /** * Copies the values from the given player into this player if boolean par2 is true. Always clones Ender Chest * Inventory. */ public void clonePlayer(EntityPlayer oldPlayer, boolean respawnFromEnd) { super.clonePlayer(oldPlayer, respawnFromEnd); this.lastExperience = -1; this.lastHealth = -1.0F; this.lastFoodLevel = -1; this.entityRemoveQueue.addAll(((EntityPlayerMP)oldPlayer).entityRemoveQueue); } protected void onNewPotionEffect(PotionEffect id) { super.onNewPotionEffect(id); this.connection.sendPacket(new SPacketEntityEffect(this.getEntityId(), id)); } protected void onChangedPotionEffect(PotionEffect id, boolean p_70695_2_) { super.onChangedPotionEffect(id, p_70695_2_); this.connection.sendPacket(new SPacketEntityEffect(this.getEntityId(), id)); } protected void onFinishedPotionEffect(PotionEffect effect) { super.onFinishedPotionEffect(effect); this.connection.sendPacket(new SPacketRemoveEntityEffect(this.getEntityId(), effect.getPotion())); } /** * Sets the position of the entity and updates the 'last' variables */ public void setPositionAndUpdate(double x, double y, double z) { this.connection.setPlayerLocation(x, y, z, this.rotationYaw, this.rotationPitch); } /** * Called when the entity is dealt a critical hit. */ public void onCriticalHit(Entity entityHit) { this.getServerWorld().getEntityTracker().sendToTrackingAndSelf(this, new SPacketAnimation(entityHit, 4)); } public void onEnchantmentCritical(Entity entityHit) { this.getServerWorld().getEntityTracker().sendToTrackingAndSelf(this, new SPacketAnimation(entityHit, 5)); } /** * Sends the player's abilities to the server (if there is one). */ public void sendPlayerAbilities() { if (this.connection != null) { this.connection.sendPacket(new SPacketPlayerAbilities(this.capabilities)); this.updatePotionMetadata(); } } public WorldServer getServerWorld() { return (WorldServer)this.worldObj; } /** * Sets the player's game mode and sends it to them. */ public void setGameType(GameType gameType) { this.interactionManager.setGameType(gameType); this.connection.sendPacket(new SPacketChangeGameState(3, (float)gameType.getID())); if (gameType == GameType.SPECTATOR) { this.dismountRidingEntity(); } else { this.setSpectatingEntity(this); } this.sendPlayerAbilities(); this.markPotionsDirty(); } /** * Returns true if the player is in spectator mode. */ public boolean isSpectator() { return this.interactionManager.getGameType() == GameType.SPECTATOR; } public boolean isCreative() { return this.interactionManager.getGameType() == GameType.CREATIVE; } /** * Send a chat message to the CommandSender */ public void addChatMessage(ITextComponent component) { this.connection.sendPacket(new SPacketChat(component)); } /** * Returns {@code true} if the CommandSender is allowed to execute the command, {@code false} if not */ public boolean canCommandSenderUseCommand(int permLevel, String commandName) { if ("seed".equals(commandName) && !this.mcServer.isDedicatedServer()) { return true; } else if (!"tell".equals(commandName) && !"help".equals(commandName) && !"me".equals(commandName) && !"trigger".equals(commandName)) { if (this.mcServer.getPlayerList().canSendCommands(this.getGameProfile())) { UserListOpsEntry userlistopsentry = (UserListOpsEntry)this.mcServer.getPlayerList().getOppedPlayers().getEntry(this.getGameProfile()); return userlistopsentry != null ? userlistopsentry.getPermissionLevel() >= permLevel : this.mcServer.getOpPermissionLevel() >= permLevel; } else { return false; } } else { return true; } } /** * Gets the player's IP address. Used in /banip. */ public String getPlayerIP() { String s = this.connection.netManager.getRemoteAddress().toString(); s = s.substring(s.indexOf("/") + 1); s = s.substring(0, s.indexOf(":")); return s; } public void handleClientSettings(CPacketClientSettings packetIn) { this.language = packetIn.getLang(); this.chatVisibility = packetIn.getChatVisibility(); this.chatColours = packetIn.isColorsEnabled(); this.getDataManager().set(PLAYER_MODEL_FLAG, Byte.valueOf((byte)packetIn.getModelPartFlags())); this.getDataManager().set(MAIN_HAND, Byte.valueOf((byte)(packetIn.getMainHand() == EnumHandSide.LEFT ? 0 : 1))); } public EntityPlayer.EnumChatVisibility getChatVisibility() { return this.chatVisibility; } public void loadResourcePack(String url, String hash) { this.connection.sendPacket(new SPacketResourcePackSend(url, hash)); } /** * Get the position in the world. <b>{@code null} is not allowed!</b> If you are not an entity in the world, return * the coordinates 0, 0, 0 */ public BlockPos getPosition() { return new BlockPos(this.posX, this.posY + 0.5D, this.posZ); } public void markPlayerActive() { this.playerLastActiveTime = MinecraftServer.getCurrentTimeMillis(); } /** * Gets the stats file for reading achievements */ public StatisticsManagerServer getStatFile() { return this.statsFile; } /** * Sends a packet to the player to remove an entity. */ public void removeEntity(Entity entityIn) { if (entityIn instanceof EntityPlayer) { this.connection.sendPacket(new SPacketDestroyEntities(new int[] {entityIn.getEntityId()})); } else { this.entityRemoveQueue.add(Integer.valueOf(entityIn.getEntityId())); } } public void addEntity(Entity entityIn) { this.entityRemoveQueue.remove(Integer.valueOf(entityIn.getEntityId())); } /** * Clears potion metadata values if the entity has no potion effects. Otherwise, updates potion effect color, * ambience, and invisibility metadata values */ protected void updatePotionMetadata() { if (this.isSpectator()) { this.resetPotionEffectMetadata(); this.setInvisible(true); } else { super.updatePotionMetadata(); } this.getServerWorld().getEntityTracker().updateVisibility(this); } public Entity getSpectatingEntity() { return (Entity)(this.spectatingEntity == null ? this : this.spectatingEntity); } public void setSpectatingEntity(Entity entityToSpectate) { Entity entity = this.getSpectatingEntity(); this.spectatingEntity = (Entity)(entityToSpectate == null ? this : entityToSpectate); if (entity != this.spectatingEntity) { this.connection.sendPacket(new SPacketCamera(this.spectatingEntity)); this.setPositionAndUpdate(this.spectatingEntity.posX, this.spectatingEntity.posY, this.spectatingEntity.posZ); } } /** * Decrements the counter for the remaining time until the entity may use a portal again. */ protected void decrementTimeUntilPortal() { if (this.timeUntilPortal > 0 && !this.invulnerableDimensionChange) { --this.timeUntilPortal; } } /** * Attacks for the player the targeted entity with the currently equipped item. The equipped item has hitEntity * called on it. Args: targetEntity */ public void attackTargetEntityWithCurrentItem(Entity targetEntity) { if (this.interactionManager.getGameType() == GameType.SPECTATOR) { this.setSpectatingEntity(targetEntity); } else { super.attackTargetEntityWithCurrentItem(targetEntity); } } public long getLastActiveTime() { return this.playerLastActiveTime; } /** * Returns null which indicates the tab list should just display the player's name, return a different value to * display the specified text instead of the player's name */ @Nullable public ITextComponent getTabListDisplayName() { return null; } public void swingArm(EnumHand hand) { super.swingArm(hand); this.resetCooldown(); } public boolean isInvulnerableDimensionChange() { return this.invulnerableDimensionChange; } public void clearInvulnerableDimensionChange() { this.invulnerableDimensionChange = false; } public void setElytraFlying() { this.setFlag(7, true); } public void clearElytraFlying() { this.setFlag(7, true); this.setFlag(7, false); } }
lgpl-3.0
labcabrera/lab-insurance
insurance-domain-core/src/main/java/org/lab/insurance/domain/core/portfolio/PortfolioOperation.java
746
package org.lab.insurance.domain.core.portfolio; import java.math.BigDecimal; import java.util.Date; import org.lab.insurance.domain.core.insurance.Asset; import org.lab.insurance.domain.core.insurance.MarketOrder; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.DBRef; import org.springframework.data.mongodb.core.mapping.Document; import lombok.Data; @Document @Data public class PortfolioOperation { @Id private String id; @DBRef private Investment source; @DBRef private Investment target; @DBRef private Asset asset; @DBRef private MarketOrder marketOrder; private Date valueDate; private BigDecimal units; private BigDecimal amount; private String description; }
lgpl-3.0
SonarSource/sonarqube
server/sonar-server-common/src/main/java/org/sonar/server/es/ResilientIndexer.java
1458
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es; import java.util.Collection; import org.sonar.db.DbSession; import org.sonar.db.es.EsQueueDto; /** * This kind of indexers that are resilient */ public interface ResilientIndexer extends StartupIndexer { /** * Index the items and delete them from es_queue table when the indexation * is done, keep it if there is a failure on the item of the collection * * @param dbSession the db session * @param items the items to be indexed * @return the number of successful indexation */ IndexingResult index(DbSession dbSession, Collection<EsQueueDto> items); }
lgpl-3.0
qub-it/fenixedu-academic
src/main/java/org/fenixedu/academic/util/date/SerializationTool.java
2560
/** * Copyright © 2002 Instituto Superior Técnico * * This file is part of FenixEdu Academic. * * FenixEdu Academic 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. * * FenixEdu Academic 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 FenixEdu Academic. If not, see <http://www.gnu.org/licenses/>. */ package org.fenixedu.academic.util.date; import org.apache.commons.lang.StringUtils; import org.joda.time.DateTime; import org.joda.time.DateTimeFieldType; import org.joda.time.Interval; import org.joda.time.YearMonthDay; public class SerializationTool { public static String yearMonthDaySerialize(final YearMonthDay yearMonthDay) { if (yearMonthDay != null) { final String dateString = String.format("%04d-%02d-%02d", yearMonthDay.get(DateTimeFieldType.year()), yearMonthDay.get(DateTimeFieldType.monthOfYear()), yearMonthDay.get(DateTimeFieldType.dayOfMonth())); return dateString; } return null; } public static YearMonthDay yearMonthDayDeserialize(final String string) { if (StringUtils.isBlank(string)) { return null; } String[] tokens = string.split("\\-"); if (tokens.length != 3) { System.err.println("Something went wrong with this object. Will be set to null - " + string); return null; } int year = Integer.parseInt(tokens[0]); int month = Integer.parseInt(tokens[1]); int day = Integer.parseInt(tokens[2]); return year == 0 || month == 0 || day == 0 ? null : new YearMonthDay(year, month, day); } public static String intervalSerialize(final Interval interval) { return interval.toString(); } public static Interval intervalDeserialize(final String string) { if (!StringUtils.isEmpty(string)) { String[] parts = string.split("/"); DateTime start = new DateTime(parts[0]); DateTime end = new DateTime(parts[1]); return new Interval(start, end); } return null; } }
lgpl-3.0
Godin/sonar
server/sonar-ce/src/main/java/org/sonar/ce/taskprocessor/CeWorkerController.java
1889
/* * SonarQube * Copyright (C) 2009-2019 SonarSource SA * mailto:info AT sonarsource DOT com * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.taskprocessor; import java.util.Optional; /** * This class is responsible of knowing/deciding which {@link CeWorker} is enabled and should actually try and find a * task to process. */ public interface CeWorkerController { interface ProcessingRecorderHook extends AutoCloseable { /** * Override to not declare any exception thrown. */ @Override void close(); } /** * Registers to the controller that the specified {@link CeWorker} */ ProcessingRecorderHook registerProcessingFor(CeWorker ceWorker); /** * Returns {@code true} if the specified {@link CeWorker} is enabled */ boolean isEnabled(CeWorker ceWorker); /** * @return the {@link CeWorker} running in the specified {@link Thread}, if any. */ Optional<CeWorker> getCeWorkerIn(Thread thread); /** * Whether at least one worker is processing a task or not. * * @return {@code false} when all workers are waiting for tasks or are being stopped. */ boolean hasAtLeastOneProcessingWorker(); }
lgpl-3.0
AKSW/topicmodeling
topicmodeling.commons/src/test/java/org/dice_research/topicmodeling/commons/collections/TopDoubleFloatCollectionTest.java
3253
package org.dice_research.topicmodeling.commons.collections; import java.util.Random; import org.dice_research.topicmodeling.commons.sort.AssociativeSort; import org.apache.commons.lang3.ArrayUtils; import org.junit.Assert; import org.junit.Test; public class TopDoubleFloatCollectionTest { private static final int DATA_SIZE = 4096; private static final int TOP_X = 100; @Test public void testTopDoubleFloatCollectionDescending() { Random rand = new Random(System.currentTimeMillis()); double values[] = new double[DATA_SIZE]; float objects[] = new float[DATA_SIZE]; for (int i = 0; i < DATA_SIZE; ++i) { values[i] = rand.nextDouble(); objects[i] = rand.nextFloat(); } TopDoubleFloatCollection topCollection = new TopDoubleFloatCollection(TOP_X, false); for (int i = 0; i < values.length; i++) { topCollection.add(values[i], objects[i]); } AssociativeSort.insertionSort(values, objects); values = ArrayUtils.subarray(values, DATA_SIZE - TOP_X, DATA_SIZE); ArrayUtils.reverse(values); Assert.assertArrayEquals(values, topCollection.values, 0); objects = ArrayUtils.subarray(objects, DATA_SIZE - TOP_X, DATA_SIZE); // Because Insertion sort is stable but sorts ascending the check if the object arrays are equal has to be done // manually int start = 0; int end = 1; float objectsSubArray1[], objectsSubArray2[]; float collectionObjects[] = topCollection.getObjects(); while (end < collectionObjects.length) { while ((end < collectionObjects.length) && (values[start] == values[end])) { ++end; } // If we have reached the end of values, we can not guarantee, that the arrays are equal if (end == collectionObjects.length) { break; } objectsSubArray1 = ArrayUtils.subarray(objects, objects.length - end, objects.length - start); objectsSubArray2 = ArrayUtils.subarray(collectionObjects, start, end); Assert.assertArrayEquals(objectsSubArray1, objectsSubArray2, 0); start = end; ++end; } } @Test public void testTopDoubleFloatCollectionAscending() { Random rand = new Random(System.currentTimeMillis()); double values[] = new double[DATA_SIZE]; float objects[] = new float[DATA_SIZE]; for (int i = 0; i < DATA_SIZE; ++i) { values[i] = rand.nextDouble(); objects[i] = rand.nextFloat(); } TopDoubleFloatCollection topCollection = new TopDoubleFloatCollection(TOP_X, true); for (int i = 0; i < values.length; i++) { topCollection.add(values[i], objects[i]); } AssociativeSort.insertionSort(values, objects); values = ArrayUtils.subarray(values, 0, TOP_X); objects = ArrayUtils.subarray(objects, 0, TOP_X); Assert.assertArrayEquals(values, topCollection.values, 0); Assert.assertArrayEquals(objects, topCollection.getObjects(), 0); } }
lgpl-3.0
heribender/SocialDataImporter
SDI-core/src/test/java/ch/sdi/report/ReportMsgTest.java
1934
/** * Copyright (c) 2014 by the original author or authors. * * This code 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. * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package ch.sdi.report; import java.util.ArrayList; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.Before; import org.junit.Test; import ch.sdi.report.ReportMsg.ReportType; /** * Testcase * * @version 1.0 (19.11.2014) * @author Heri */ public class ReportMsgTest { /** logger for this class */ private Logger myLog = LogManager.getLogger( ReportMsgTest.class ); /** * @throws java.lang.Exception */ @Before public void setUp() throws Exception { } @Test public void testOk() { for ( ReportType type : ReportType.values() ) { myLog.debug( new ReportMsg( type, "Hallo", new ArrayList<String>() ) ); } } @Test(expected=NullPointerException.class) public void testNullPointer() { for ( ReportType type : ReportType.values() ) { myLog.debug( new ReportMsg( type, "Hallo", null ) ); } } }
lgpl-3.0
mar9000/plantuml
src/net/sourceforge/plantuml/creole/Atom.java
1548
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2014, Arnaud Roques * * Project Info: http://plantuml.sourceforge.net * * This file is part of PlantUML. * * PlantUML 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. * * PlantUML 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. * * * Original Author: Arnaud Roques */ package net.sourceforge.plantuml.creole; import java.awt.geom.Dimension2D; import net.sourceforge.plantuml.graphic.StringBounder; import net.sourceforge.plantuml.ugraphic.UGraphic; import net.sourceforge.plantuml.ugraphic.UShape; interface Atom extends UShape { public Dimension2D calculateDimension(StringBounder stringBounder); public double getStartingAltitude(StringBounder stringBounder); public void drawU(UGraphic ug); }
lgpl-3.0
DivineCooperation/bco.core-manager
openhab/src/main/java/org/openbase/bco/device/openhab/manager/transform/ColorStateOnOffTypeTransformer.java
4246
package org.openbase.bco.device.openhab.manager.transform; /*- * #%L * BCO Openhab Device Manager * %% * Copyright (C) 2015 - 2021 openbase.org * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import org.eclipse.smarthome.core.library.types.DecimalType; import org.eclipse.smarthome.core.library.types.HSBType; import org.eclipse.smarthome.core.library.types.OnOffType; import org.eclipse.smarthome.core.library.types.PercentType; import org.openbase.jul.exception.*; import org.openbase.jul.extension.type.transform.HSBColorToRGBColorTransformer; import org.openbase.type.domotic.state.ColorStateType.ColorState; import org.openbase.type.domotic.state.PowerStateType; import org.openbase.type.vision.ColorType.Color.Type; import org.openbase.type.vision.HSBColorType; import java.math.BigDecimal; public class ColorStateOnOffTypeTransformer implements ServiceStateCommandTransformer<ColorState, OnOffType> { @Override public ColorState transform(final OnOffType onOffType) throws CouldNotTransformException { try { // ColorState.Builder colorState = ColorState.newBuilder(); // colorState.getColorBuilder().setType(Type.HSB); // // switch (onOffType) { // case OFF: // colorState.getColorBuilder().getHsbColorBuilder().setBrightness(0); // break; // case ON: // colorState.getColorBuilder().getHsbColorBuilder().setBrightness(1); // break; // default: // throw new CouldNotTransformException("Could not transform " + OnOffType.class.getSimpleName() + "[" + onOffType.name() + "] is unknown!"); // } // return colorState.build(); throw new TypeNotSupportedException("Transformation would generate invalid data."); // todo make sure on off types are only mapped on power states! } catch (Exception ex) { throw new CouldNotTransformException("Could not transform " + OnOffType.class.getName() + " to " + ColorState.class.getName() + "!", ex); } } @Override public OnOffType transform(final ColorState colorState) throws CouldNotTransformException { try { HSBColorType.HSBColor hsbColor; if (!colorState.hasColor()) { throw new NotAvailableException("Color"); } if (!colorState.getColor().hasType()) { throw new NotAvailableException("ColorType"); } // convert to hsv space if possible switch (colorState.getColor().getType()) { case RGB: hsbColor = HSBColorToRGBColorTransformer.transform(colorState.getColor().getRgbColor()); break; case HSB: hsbColor = colorState.getColor().getHsbColor(); break; case RGB24: default: throw new NotSupportedException(colorState.getColor().getType().name(), this); } if (hsbColor.getBrightness() > 0) { return OnOffType.ON; } else if (hsbColor.getBrightness() == 0) { return OnOffType.OFF; } else { throw new InvalidStateException("Brightness has an invalid value: "+hsbColor.getBrightness()); } } catch (Exception ex) { throw new CouldNotTransformException("Could not transform " + ColorState.class.getName() + " to " + OnOffType.class.getName() + "!", ex); } } }
lgpl-3.0
ajpahl1008/iaas
iaas-orchestration-scheduler/src/main/java/com/pahlsoft/iaas/scheduler/dao/ServerDao.java
205
package com.pahlsoft.iaas.scheduler.dao; import java.util.List; import java.util.Map; public interface ServerDao { public List<String> getExpiredServers(); public Map<String,String> getAllServers(); }
lgpl-3.0
SirmaITT/conservation-space-1.7.0
docker/sirma-platform/platform/seip-parent/platform/domain-model/domain-model-api/src/main/java/com/sirma/itt/seip/domain/search/Sorter.java
6072
package com.sirma.itt.seip.domain.search; import static com.sirma.itt.seip.util.EqualsHelper.nullSafeEquals; import java.util.List; import com.sirma.itt.seip.collections.CollectionUtils; /** * The Class Sorter that holds all data needed for sorting. */ public class Sorter { /** The Constant SORT_ASCENDING. */ public static final String SORT_ASCENDING = "asc"; /** The Constant SORT_DESCENDING. */ public static final String SORT_DESCENDING = "desc"; /** The ascending order. */ private boolean ascendingOrder = true; /** The sort field. */ private final String sortField; /** The allow missing values for sorting */ private boolean allowMissing = false; /** * Codelist numbers to match the values and sort on the code value description */ private List<Integer> codelistNumbers; /** * Marks the current sort field as one pointing to object property and not to data literal */ private boolean objectProperty = false; /** * Ascending sorter. * * @param key * the key * @return the sorter */ public static Sorter ascendingSorter(String key) { return new Sorter(key, SORT_ASCENDING); } /** * Descending sorter. * * @param key * the key * @return the sorter */ public static Sorter descendingSorter(String key) { return new Sorter(key, SORT_DESCENDING); } /** * Builds the sorter from configuration property. The value could have the following format: * <ul> * <li>key * <li>key|ASC * <li>key|DESC * </ul> * . * * @param configValue * the config value * @return the sorter or <code>null</code> if the parameter is null */ public static Sorter buildSorterFromConfig(String configValue) { if (configValue == null) { return null; } int indexOfPipe = configValue.indexOf('|'); String key = configValue; String order = SORT_ASCENDING; if (indexOfPipe > 0) { key = key.substring(0, indexOfPipe); order = configValue.substring(indexOfPipe + 1).toLowerCase(); } return new Sorter(key, order); } /** * Instantiates a new sorter. * * @param key * the key * @param isAscendingOrder * if the is ascending */ public Sorter(String key, boolean isAscendingOrder) { sortField = key; ascendingOrder = isAscendingOrder; } /** * Instantiates a new sorter. * * @param key * the key * @param isAscendingOrder * if the is ascending * @param allowNull * the allow null */ public Sorter(String key, boolean isAscendingOrder, boolean allowNull) { sortField = key; ascendingOrder = isAscendingOrder; allowMissing = allowNull; } /** * Instantiates a new sorter. * * @param key * the key * @param order * the order */ public Sorter(String key, String order) { sortField = key; ascendingOrder = order == null || SORT_ASCENDING.equalsIgnoreCase(order); } /** * Instantiates a new sorter * * @param key * the key * @param order * the order * @param codelistNumbers * list of codelist numbers that the order by field can be */ public Sorter(String key, String order, List<Integer> codelistNumbers) { this(key, order); this.codelistNumbers = codelistNumbers; } /** * Instantiates a new sorter * * @param key * the key * @param isAscendingOrder * if the sorting is in ascending order * @param codelistNumbers * list of codelist numbers that the order by field can be */ public Sorter(String key, boolean isAscendingOrder, List<Integer> codelistNumbers) { this(key, isAscendingOrder); this.codelistNumbers = codelistNumbers; } /** * Getter method for ascendingOrder. * * @return the ascendingOrder */ public boolean isAscendingOrder() { return ascendingOrder; } /** * Setter method for ascendingOrder. * * @param ascendingOrder * the ascendingOrder to set */ public void setAscendingOrder(boolean ascendingOrder) { this.ascendingOrder = ascendingOrder; } /** * Gets the sort field. * * @return the sortField */ public String getSortField() { return sortField; } /** * Allow results where the sort field value is missing */ public void setAllowMissingValues() { allowMissing = true; } /** * Checks if is missing values allowed to be returned by the search. By default missing values are removed from the * search * * @return true, if is missing values are allowed */ public boolean isMissingValuesAllowed() { return allowMissing; } /** * @return the isCodeList */ public boolean isCodeListValue() { return CollectionUtils.isNotEmpty(codelistNumbers); } /** * @return the codeLists */ public List<Integer> getCodelistNumbers() { return codelistNumbers; } /** * @param codeLists * the codeLists to set */ public void setCodelistNumbers(List<Integer> codeLists) { this.codelistNumbers = codeLists; } /** * {@inheritDoc} */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (ascendingOrder ? 1231 : 1237); result = prime * result + (sortField == null ? 0 : sortField.hashCode()); return result; } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Sorter)) { return false; } Sorter other = (Sorter) obj; return nullSafeEquals(sortField, other.sortField) && ascendingOrder == other.ascendingOrder; } /** * {@inheritDoc} */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Sorter [sortField="); builder.append(sortField); builder.append(", ascendingOrder="); builder.append(ascendingOrder); builder.append("]"); return builder.toString(); } public boolean isObjectProperty() { return objectProperty; } public Sorter setObjectProperty(boolean objectProperty) { this.objectProperty = objectProperty; return this; } }
lgpl-3.0
afishnamedjamal/LearningToMod
src/main/java/com/afishnamedjamal/learningtomod/proxy/ServerProxy.java
99
package com.afishnamedjamal.learningtomod.proxy; public class ServerProxy extends CommonProxy { }
lgpl-3.0
HATB0T/RuneCraftery
forge/mcp/temp/src/minecraft/net/minecraft/block/BlockRotatedPillar.java
1997
package net.minecraft.block; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.item.ItemStack; import net.minecraft.util.Icon; import net.minecraft.world.World; public abstract class BlockRotatedPillar extends Block { @SideOnly(Side.CLIENT) protected Icon field_111051_a; protected BlockRotatedPillar(int p_i2250_1_, Material p_i2250_2_) { super(p_i2250_1_, p_i2250_2_); } public int func_71857_b() { return 31; } public int func_85104_a(World p_85104_1_, int p_85104_2_, int p_85104_3_, int p_85104_4_, int p_85104_5_, float p_85104_6_, float p_85104_7_, float p_85104_8_, int p_85104_9_) { int var10 = p_85104_9_ & 3; byte var11 = 0; switch(p_85104_5_) { case 0: case 1: var11 = 0; break; case 2: case 3: var11 = 8; break; case 4: case 5: var11 = 4; } return var10 | var11; } @SideOnly(Side.CLIENT) public Icon func_71858_a(int p_71858_1_, int p_71858_2_) { int var3 = p_71858_2_ & 12; int var4 = p_71858_2_ & 3; return var3 == 0 && (p_71858_1_ == 1 || p_71858_1_ == 0)?this.func_111049_d(var4):(var3 == 4 && (p_71858_1_ == 5 || p_71858_1_ == 4)?this.func_111049_d(var4):(var3 == 8 && (p_71858_1_ == 2 || p_71858_1_ == 3)?this.func_111049_d(var4):this.func_111048_c(var4))); } public int func_71899_b(int p_71899_1_) { return p_71899_1_ & 3; } @SideOnly(Side.CLIENT) protected abstract Icon func_111048_c(int var1); @SideOnly(Side.CLIENT) protected Icon func_111049_d(int p_111049_1_) { return this.field_111051_a; } public int func_111050_e(int p_111050_1_) { return p_111050_1_ & 3; } protected ItemStack func_71880_c_(int p_71880_1_) { return new ItemStack(this.field_71990_ca, 1, this.func_111050_e(p_71880_1_)); } }
lgpl-3.0
Godin/sonar
server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/package-info.java
983
/* * SonarQube * Copyright (C) 2009-2019 SonarSource SA * mailto:info AT sonarsource DOT com * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.ce.task.projectanalysis.component; import javax.annotation.ParametersAreNonnullByDefault;
lgpl-3.0
android-plugin/uexWeiXin
src/org/zywx/wbpalmstar/plugin/uexweixin/VO/OpenChooseInvoiceVO.java
1390
package org.zywx.wbpalmstar.plugin.uexweixin.VO; import java.util.List; /** * File Description: 打开发票页面的传参 * <p> * Created by zhangyipeng with Email: sandy1108@163.com at Date: 2020/8/5. */ public class OpenChooseInvoiceVO { private List<CardAryBean> cardAry; public List<CardAryBean> getCardAry() { return cardAry; } public void setCardAry(List<CardAryBean> cardAry) { this.cardAry = cardAry; } public static class CardAryBean { /** * cardId : wx69b6673576ec5a65 * encryptCode : pDe7ajrY4G5z_SIDSauDkLSuF9NI * appID : O/mPnGTpBu22a1szmK2ogzhFPBh9eYzv2p70L8yzyymSPw4zpNYIVN0JMyArQ9smSepbKd2CQdkv3NvGuaGLaJYjrlrdSVrGhDOnedMr01zKjzDJkO4MOSALnNeDuIpb */ private String cardId; private String encryptCode; private String appID; public String getCardId() { return cardId; } public void setCardId(String cardId) { this.cardId = cardId; } public String getEncryptCode() { return encryptCode; } public void setEncryptCode(String encryptCode) { this.encryptCode = encryptCode; } public String getAppID() { return appID; } public void setAppID(String appID) { this.appID = appID; } } }
lgpl-3.0
totalcross/TotalCrossSDK
src/main/java/totalcross/util/regex/MatchResult.java
2607
/** * Copyright (c) 2001, Sergey A. Samokhodkin * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form * must reproduce the above copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the distribution. * - Neither the name of jregex nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @version 1.2_01 */ package totalcross.util.regex; public interface MatchResult { public int MATCH = 0; public int PREFIX = -1; public int SUFFIX = -2; public int TARGET = -3; public Pattern pattern(); public int groupCount(); public boolean isCaptured(); public boolean isCaptured(int groupId); public boolean isCaptured(String groupName); public String group(int n); public boolean getGroup(int n, StringBuffer sb); public boolean getGroup(int n, TextBuffer tb); public String group(String name); public boolean getGroup(String name, StringBuffer sb); public boolean getGroup(String name, TextBuffer tb); public String prefix(); public String suffix(); public String target(); public int targetStart(); public int targetEnd(); public char[] targetChars(); public int start(); public int end(); public int length(); public int start(int n); public int end(int n); public int length(int n); public char charAt(int i); public char charAt(int i, int groupNo); }
lgpl-3.0
ivan-kudziev/sog
app/src/main/java/by/kipind/game/olympicgames/sprite/buttons/BtnGoRight.java
1836
package by.kipind.game.olympicgames.sprite.buttons; import android.view.MotionEvent; import org.andengine.entity.scene.ITouchArea; import org.andengine.input.touch.TouchEvent; import org.andengine.opengl.texture.region.ITiledTextureRegion; import org.andengine.opengl.vbo.VertexBufferObjectManager; public class BtnGoRight extends AnimBtn { private long btnDownTime; private float ress; private int startDeg = 45; private float maxStartDeg; private float timeIntervalMinMax; public BtnGoRight(float pX, float pY, ITiledTextureRegion pTiledTextureRegion, VertexBufferObjectManager vbo) { super(pX, pY, pTiledTextureRegion, vbo); maxStartDeg = 80; timeIntervalMinMax = 300; } @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { super.onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX, pTouchAreaLocalY); if (pSceneTouchEvent.getAction() == MotionEvent.ACTION_DOWN) { btnDownTime = System.currentTimeMillis(); } if (pSceneTouchEvent.getAction() == MotionEvent.ACTION_UP) { btnDownTime = System.currentTimeMillis() - btnDownTime; if (btnDownTime > timeIntervalMinMax) { startDeg = Math.round(maxStartDeg); } else { ress = maxStartDeg * btnDownTime / timeIntervalMinMax; startDeg = Math.round(maxStartDeg * btnDownTime / timeIntervalMinMax); } actionThrow(); } return false; } public void actionThrow() { }; public int getStartDeg() { return startDeg; } public void setStartDeg(int startDeg) { this.startDeg = startDeg; } @Override public boolean onAreaTouched(TouchEvent pSceneTouchEvent, ITouchArea pTouchArea, float pTouchAreaLocalX, float pTouchAreaLocalY) { // TODO Auto-generated method stub return false; } }
lgpl-3.0
Radionz/DevOps_TCF_12
j2e/webservices/src/main/java/fr/unice/polytech/isa/tcf/webservice/CartWebServiceImpl.java
1676
package fr.unice.polytech.isa.tcf.webservice; import fr.unice.polytech.isa.tcf.CustomerFinder; import fr.unice.polytech.isa.tcf.entities.Customer; import fr.unice.polytech.isa.tcf.entities.Item; import fr.unice.polytech.isa.tcf.CartModifier; import fr.unice.polytech.isa.tcf.exceptions.PaymentException; import fr.unice.polytech.isa.tcf.exceptions.UnknownCustomerException; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.jws.WebService; import java.util.Optional; import java.util.Set; @WebService(targetNamespace = "http://www.polytech.unice.fr/si/4a/isa/tcf/cart") @Stateless(name = "CartWS") public class CartWebServiceImpl implements CartWebService { @EJB(name="stateless-cart") private CartModifier cart; @EJB private CustomerFinder finder; @Override public void addItemToCustomerCart(String customerName, Item it) throws UnknownCustomerException { cart.add(readCustomer(customerName), it); } @Override public void removeItemToCustomerCart(String customerName, Item it) throws UnknownCustomerException { cart.remove(readCustomer(customerName), it); } @Override public Set<Item> getCustomerCartContents(String customerName) throws UnknownCustomerException { return cart.contents(readCustomer(customerName)); } @Override public String validate(String customerName) throws PaymentException, UnknownCustomerException { return cart.validate(readCustomer(customerName)); } private Customer readCustomer(String customerName) throws UnknownCustomerException { Optional<Customer> c = finder.findByName(customerName); if(!c.isPresent()) throw new UnknownCustomerException(customerName); return c.get(); } }
lgpl-3.0
hdsdi3g/MyDMAM
app/hd3gtv/tools/ExecprocessBadExecutionException.java
1310
/* * This file is part of MyDMAM. * * 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 * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * Copyright (C) hdsdi3g for hd3g.tv 2013 * */ package hd3gtv.tools; import java.io.IOException; public class ExecprocessBadExecutionException extends IOException { private static final long serialVersionUID = -8807563945004074931L; private String processname; private String commandline; private int returncode; ExecprocessBadExecutionException(String processname, String commandline, int returncode) { super("Exec \"" + commandline + "\" return code " + returncode); this.commandline = commandline; this.returncode = returncode; this.processname = processname; } public int getReturncode() { return returncode; } public String getCommandline() { return commandline; } public String getProcessname() { return processname; } }
lgpl-3.0
Team-Fruit/SignPicture
src/main/java/com/kamesuta/mc/signpic/gui/package-info.java
71
@com.kamesuta.mc.NonNullByDefault package com.kamesuta.mc.signpic.gui;
lgpl-3.0
claudejin/evosuite
master/src/test/java/org/evosuite/testcase/StaticUninitializedFieldSystemTest.java
2132
package org.evosuite.testcase; import com.examples.with.different.packagename.staticfield.StaticFieldUninitialized; import org.evosuite.EvoSuite; import org.evosuite.Properties; import org.evosuite.SystemTestBase; import org.evosuite.ga.metaheuristics.GeneticAlgorithm; import org.evosuite.statistics.OutputVariable; import org.evosuite.statistics.RuntimeVariable; import org.evosuite.statistics.backend.DebugStatisticsBackend; import org.evosuite.testsuite.TestSuiteChromosome; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.Map; /** * Created by gordon on 30/11/2016. */ public class StaticUninitializedFieldSystemTest extends SystemTestBase { @Before public void setUpProperties() { Properties.RESET_STATIC_FIELDS = true; Properties.RESET_STATIC_FIELD_GETS = true; Properties.SANDBOX = true; Properties.JUNIT_CHECK = true; Properties.JUNIT_TESTS = true; Properties.PURE_INSPECTORS = true; Properties.OUTPUT_VARIABLES = "" + RuntimeVariable.HadUnstableTests; } @Test public void test() { EvoSuite evosuite = new EvoSuite(); String targetClass = StaticFieldUninitialized.class.getCanonicalName(); Properties.TARGET_CLASS = targetClass; String[] command = new String[] { "-generateSuite", "-class", targetClass }; Object result = evosuite.parseCommandLine(command); GeneticAlgorithm<?> ga = getGAFromResult(result); TestSuiteChromosome best = (TestSuiteChromosome) ga.getBestIndividual(); System.out.println(best.toString()); Map<String, OutputVariable<?>> map = DebugStatisticsBackend.getLatestWritten(); Assert.assertNotNull(map); OutputVariable unstable = map.get(RuntimeVariable.HadUnstableTests.toString()); Assert.assertNotNull(unstable); Assert.assertEquals("Unexpected unstabled test cases were generated",Boolean.FALSE, unstable.getValue()); double best_fitness = best.getFitness(); Assert.assertTrue("Optimal coverage was not achieved ", best_fitness == 0.0); } }
lgpl-3.0
claudejin/evosuite
client/src/main/java/org/evosuite/graphs/GraphPool.java
11193
/** * Copyright (C) 2010-2016 Gordon Fraser, Andrea Arcuri and EvoSuite * contributors * * This file is part of EvoSuite. * * EvoSuite 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.0 of the License, or * (at your option) any later version. * * EvoSuite 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 Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>. */ package org.evosuite.graphs; import java.util.HashMap; import java.util.Map; import org.evosuite.Properties; import org.evosuite.graphs.ccfg.ClassControlFlowGraph; import org.evosuite.graphs.ccg.ClassCallGraph; import org.evosuite.graphs.cdg.ControlDependenceGraph; import org.evosuite.graphs.cfg.ActualControlFlowGraph; import org.evosuite.graphs.cfg.RawControlFlowGraph; import org.evosuite.setup.DependencyAnalysis; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Gives access to all Graphs computed during CUT analysis such as CFGs created * by the CFGGenerator and BytcodeAnalyzer in the CFGMethodAdapter * * For each CUT and each of their methods a Raw- and an ActualControlFlowGraph * instance are stored within this pool. Additionally a ControlDependenceGraph * is computed and stored for each such method. * * This pool also offers the possibility to generate the ClassCallGraph and * ClassControlFlowGraph for a CUT. They represents the call hierarchy and * interaction of different methods within a class. * * @author Andre Mis */ public class GraphPool { private static Logger logger = LoggerFactory.getLogger(GraphPool.class); private static Map<ClassLoader, GraphPool> instanceMap = new HashMap<ClassLoader, GraphPool>(); private final ClassLoader classLoader; /** Private constructor */ private GraphPool(ClassLoader classLoader) { this.classLoader = classLoader; } public static GraphPool getInstance(ClassLoader classLoader) { if (!instanceMap.containsKey(classLoader)) { instanceMap.put(classLoader, new GraphPool(classLoader)); } return instanceMap.get(classLoader); } /** * Complete control flow graph, contains each bytecode instruction, each * label and line number node Think of the direct Known Subclasses of * http:// * asm.ow2.org/asm33/javadoc/user/org/objectweb/asm/tree/AbstractInsnNode * .html for a complete list of the nodes in this cfg * * Maps from classNames to methodNames to corresponding RawCFGs */ private final Map<String, Map<String, RawControlFlowGraph>> rawCFGs = new HashMap<String, Map<String, RawControlFlowGraph>>(); /** * Minimized control flow graph. This graph only contains the first and last * node (usually a LABEL and IRETURN), nodes which create branches (all * jumps/switches except GOTO) and nodes which were mutated. * * Maps from classNames to methodNames to corresponding ActualCFGs */ private final Map<String, Map<String, ActualControlFlowGraph>> actualCFGs = new HashMap<String, Map<String, ActualControlFlowGraph>>(); /** * Control Dependence Graphs for each method. * * Maps from classNames to methodNames to corresponding CDGs */ private final Map<String, Map<String, ControlDependenceGraph>> controlDependencies = new HashMap<String, Map<String, ControlDependenceGraph>>(); /** * Cache of all created CCFGs * * Maps from classNames to computed CCFG of that class */ private final Map<String, ClassControlFlowGraph> ccfgs = new HashMap<String, ClassControlFlowGraph>(); // retrieve graphs /** * <p> * getRawCFG * </p> * * @param className * a {@link java.lang.String} object. * @param methodName * a {@link java.lang.String} object. * @return a {@link org.evosuite.graphs.cfg.RawControlFlowGraph} object. */ public RawControlFlowGraph getRawCFG(String className, String methodName) { if (rawCFGs.get(className) == null) { logger.warn("Class unknown: " + className); logger.warn(rawCFGs.keySet().toString()); return null; } return rawCFGs.get(className).get(methodName); } /** * <p> * Getter for the field <code>rawCFGs</code>. * </p> * * @param className * a {@link java.lang.String} object. * @return a {@link java.util.Map} object. */ public Map<String, RawControlFlowGraph> getRawCFGs(String className) { if (rawCFGs.get(className) == null) { logger.warn("Class unknown: " + className); logger.warn(rawCFGs.keySet().toString()); return null; } return rawCFGs.get(className); } /** * <p> * getActualCFG * </p> * * @param className * a {@link java.lang.String} object. * @param methodName * a {@link java.lang.String} object. * @return a {@link org.evosuite.graphs.cfg.ActualControlFlowGraph} object. */ public ActualControlFlowGraph getActualCFG(String className, String methodName) { if (actualCFGs.get(className) == null) return null; return actualCFGs.get(className).get(methodName); } /** * <p> * getCDG * </p> * * @param className * a {@link java.lang.String} object. * @param methodName * a {@link java.lang.String} object. * @return a {@link org.evosuite.graphs.cdg.ControlDependenceGraph} object. */ public ControlDependenceGraph getCDG(String className, String methodName) { if (controlDependencies.get(className) == null) return null; return controlDependencies.get(className).get(methodName); } // register graphs /** * <p> * registerRawCFG * </p> * * @param cfg * a {@link org.evosuite.graphs.cfg.RawControlFlowGraph} object. */ public void registerRawCFG(RawControlFlowGraph cfg) { String className = cfg.getClassName(); String methodName = cfg.getMethodName(); if (className == null || methodName == null) throw new IllegalStateException( "expect class and method name of CFGs to be set before entering the GraphPool"); if (!rawCFGs.containsKey(className)) { rawCFGs.put(className, new HashMap<String, RawControlFlowGraph>()); } Map<String, RawControlFlowGraph> methods = rawCFGs.get(className); logger.debug("Added complete CFG for class " + className + " and method " + methodName); methods.put(methodName, cfg); if (Properties.WRITE_CFG) cfg.toDot(); } /** * <p> * registerActualCFG * </p> * * @param cfg * a {@link org.evosuite.graphs.cfg.ActualControlFlowGraph} * object. */ public void registerActualCFG(ActualControlFlowGraph cfg) { String className = cfg.getClassName(); String methodName = cfg.getMethodName(); if (className == null || methodName == null) throw new IllegalStateException( "expect class and method name of CFGs to be set before entering the GraphPool"); if (!actualCFGs.containsKey(className)) { actualCFGs.put(className, new HashMap<String, ActualControlFlowGraph>()); // diameters.put(className, new HashMap<String, Double>()); } Map<String, ActualControlFlowGraph> methods = actualCFGs.get(className); logger.debug("Added CFG for class " + className + " and method " + methodName); cfg.finalise(); methods.put(methodName, cfg); if (Properties.WRITE_CFG) cfg.toDot(); if (DependencyAnalysis.shouldInstrument(cfg.getClassName(), cfg.getMethodName())) { createAndRegisterControlDependence(cfg); } } private void createAndRegisterControlDependence(ActualControlFlowGraph cfg) { ControlDependenceGraph cd = new ControlDependenceGraph(cfg); String className = cd.getClassName(); String methodName = cd.getMethodName(); if (className == null || methodName == null) throw new IllegalStateException( "expect class and method name of CFGs to be set before entering the GraphPool"); if (!controlDependencies.containsKey(className)) controlDependencies.put(className, new HashMap<String, ControlDependenceGraph>()); Map<String, ControlDependenceGraph> cds = controlDependencies.get(className); cds.put(methodName, cd); if (Properties.WRITE_CFG) cd.toDot(); } /** * Ensures this GraphPool knows the CCFG for the given class and then * returns it. * * @param className * the name of the class of the CCFG as a * {@link java.lang.String} * @return The cached CCFG of type * {@link org.evosuite.graphs.ccfg.ClassControlFlowGraph} */ public ClassControlFlowGraph getCCFG(String className) { if (!ccfgs.containsKey(className)) { ccfgs.put(className, computeCCFG(className)); } return ccfgs.get(className); } public boolean canMakeCCFGForClass(String className) { // if(!rawCFGs.containsKey(className)) // LoggingUtils.getEvoLogger().info("unable to create CCFG for "+className); return rawCFGs.containsKey(className); } /** * Computes the CCFG for the given class * * If no CFG is known for the given class, an IllegalArgumentException is * thrown * * @param className * a {@link java.lang.String} object. * @return a {@link org.evosuite.graphs.ccfg.ClassControlFlowGraph} object. */ private ClassControlFlowGraph computeCCFG(String className) { if (rawCFGs.get(className) == null) throw new IllegalArgumentException( "can't compute CCFG, don't know CFGs for class " + className); ClassCallGraph ccg = new ClassCallGraph(classLoader, className); if (Properties.WRITE_CFG) ccg.toDot(); ClassControlFlowGraph ccfg = new ClassControlFlowGraph(ccg); if (Properties.WRITE_CFG) ccfg.toDot(); return ccfg; } /** * <p> * clear * </p> */ public void clear() { rawCFGs.clear(); actualCFGs.clear(); controlDependencies.clear(); } /** * <p> * clear * </p> * * @param className * a {@link java.lang.String} object. */ public void clear(String className) { rawCFGs.remove(className); actualCFGs.remove(className); controlDependencies.remove(className); } /** * <p> * clear * </p> * * @param className * a {@link java.lang.String} object. * @param methodName * a {@link java.lang.String} object. */ public void clear(String className, String methodName) { if (rawCFGs.containsKey(className)) rawCFGs.get(className).remove(methodName); if (actualCFGs.containsKey(className)) actualCFGs.get(className).remove(methodName); if (controlDependencies.containsKey(className)) controlDependencies.get(className).remove(methodName); } public static void clearAll(String className) { for (GraphPool pool : instanceMap.values()) { pool.clear(className); } } public static void clearAll(String className, String methodName) { for (GraphPool pool : instanceMap.values()) { pool.clear(className, methodName); } } public static void clearAll() { instanceMap.clear(); } }
lgpl-3.0
smallAreaHealthStatisticsUnit/rapidInquiryFacility
rifGenericLibrary/src/main/java/org/sahsu/rif/generic/datastorage/SQLQueryUtility.java
8611
package org.sahsu.rif.generic.datastorage; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.Statement; import org.sahsu.rif.generic.system.RIFServiceException; import org.sahsu.rif.generic.system.Messages; import org.sahsu.rif.generic.system.RIFGenericLibraryError; import org.sahsu.rif.generic.util.RIFLogger; /** * Properly closes down statements, connections, result sets. When these operations * fail, it produces error messages. The class is used to help minimise and * standardise code for cleaning up resources for database queries */ public class SQLQueryUtility { private static final RIFLogger rifLogger = RIFLogger.getLogger(); private static String lineSeparator = System.getProperty("line.separator"); private static String callingClassName="rifGenericLibrary.datastorage.pg.SQLQueryUtility"; private static final Messages GENERIC_MESSAGES = Messages.genericMessages(); /** * Close. * * @param connection the connection * @throws RIFServiceException the RIF service exception */ public static void close(final Connection connection) throws RIFServiceException { if (connection == null) { return; } try { connection.close(); } catch(SQLException sqlException) { String errorMessage = GENERIC_MESSAGES.getMessage("sqlConnectionManager.error.unableToCloseResource"); rifLogger.error( SQLQueryUtility.class, errorMessage, sqlException); throw new RIFServiceException( RIFGenericLibraryError.DB_UNABLE_CLOSE_RESOURCE, errorMessage); } } /** * Close. * * @param resultSet the result set * @throws RIFServiceException the RIF service exception */ public static void close( final ResultSet resultSet) throws RIFServiceException { if (resultSet == null) { return; } try { resultSet.close(); } catch(SQLException sqlException) { String errorMessage = GENERIC_MESSAGES.getMessage( "sqlConnectionManager.error.unableToCloseResource"); rifLogger.error( SQLQueryUtility.class, errorMessage, sqlException); throw new RIFServiceException( RIFGenericLibraryError.DB_UNABLE_CLOSE_RESOURCE, errorMessage); } } /** * Close. * * @param statement the statement * @throws RIFServiceException the RIF service exception */ public static void close( final Statement statement) throws RIFServiceException { if (statement == null) { return; } try { statement.close(); } catch(SQLException sqlException) { String errorMessage = GENERIC_MESSAGES.getMessage( "sqlConnectionManager.error.unableToCloseResource"); rifLogger.error( SQLQueryUtility.class, errorMessage, sqlException); throw new RIFServiceException( RIFGenericLibraryError.DB_UNABLE_CLOSE_RESOURCE, errorMessage); } } /** * printWarnings. Print info and warning messages * * @param ddlStatement The {@link PreparedStatement} whose warnings to print */ public static String printWarnings(Statement ddlStatement) { try { SQLWarning warnings=ddlStatement.getWarnings(); return formatWarnings(warnings); } catch(SQLException sqlException) { // Do nothing - they are warnings! rifLogger.warning(SQLQueryUtility.class, "PGSQLQueryUtility.printWarnings() caught " + "sqlException: " + sqlException.getMessage()); } return null; } /** * printWarnings. Print info and warning messages * * @param runStudyStatement The {@link PreparedStatement} whose warnings to print */ public static String printWarnings(PreparedStatement runStudyStatement) { try { SQLWarning warnings=runStudyStatement.getWarnings(); return formatWarnings(warnings); } catch(SQLException sqlException) { // Do nothing - they are warnings! rifLogger.warning(SQLQueryUtility.class, "PGSQLQueryUtility.printWarnings() caught " + "sqlException: " + sqlException.getMessage()); } return null; } private static String formatWarnings(SQLWarning warnings) { StringBuilder message; int warningCount=0; message = new StringBuilder(); while (warnings != null) { warningCount++; if (warnings.getErrorCode() == 0) { message.append(warnings.getMessage()).append(lineSeparator); } else { message.append("SQL Error/Warning >>>").append(lineSeparator) .append("Message: ").append(warnings.getMessage()) .append(lineSeparator).append("SQLState: ") .append(warnings.getSQLState()).append(lineSeparator) .append("Vendor error code: ").append(warnings.getErrorCode()) .append(lineSeparator); rifLogger.warning(SQLQueryUtility.class, "SQL Error/Warning >>>" + lineSeparator + "Message: " + warnings.getMessage() + lineSeparator + "SQLState: " + warnings.getSQLState() + lineSeparator + "Vendor error code: " + warnings.getErrorCode() + lineSeparator); } warnings = warnings.getNextWarning(); } if (message.length() > 0) { rifLogger.info(SQLQueryUtility.class, warningCount + " warnings/messages" + lineSeparator + message.toString()); return warningCount + " warnings/messages" + lineSeparator + message.toString(); } else { rifLogger.warning(SQLQueryUtility.class, "No warnings/messages found."); return "No warnings/messages found."; } } public static void commit( final Connection connection ) throws RIFServiceException { if (connection == null) { return; } try { connection.commit(); rifLogger.info(callingClassName, "COMMIT"); } catch(SQLException sqlException) { String errorMessage = GENERIC_MESSAGES.getMessage("general.db.error.unableToCommit"); throw new RIFServiceException( RIFGenericLibraryError.DB_UNABLE_TO_COMMIT, errorMessage); } } public static void rollback( final Connection connection ) throws RIFServiceException { if (connection == null) { return; } try { connection.rollback(); rifLogger.info(callingClassName, "ROLLBACK"); } catch(SQLException sqlException) { String errorMessage = GENERIC_MESSAGES.getMessage("general.db.error.unableToRollback"); throw new RIFServiceException( RIFGenericLibraryError.DB_UNABLE_TO_ROLLBACK, errorMessage); } } public static PreparedStatement createDDLStatement( final Connection connection, final QueryFormatter queryFormatter) throws SQLException { PreparedStatement statement = connection.prepareStatement( queryFormatter.generateQuery()); if (connection.getAutoCommit() != false) { connection.setAutoCommit(false); } return statement; } public static PreparedStatement createPreparedStatement( final Connection connection, final QueryFormatter queryFormatter) throws SQLException { PreparedStatement statement = connection.prepareStatement( queryFormatter.generateQuery(), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); if (connection.getHoldability() != ResultSet.CLOSE_CURSORS_AT_COMMIT) { connection.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT); } return statement; } public static PreparedStatement createPreparedStatement( final Connection connection, final String query) throws SQLException { PreparedStatement statement = connection.prepareStatement( query, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); if (connection.getHoldability() != ResultSet.CLOSE_CURSORS_AT_COMMIT) { connection.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT); } return statement; } public static CallableStatement createPreparedCall( final Connection connection, final String query) throws SQLException { //holdability set at connection level, not statement level return connection.prepareCall(query); } }
lgpl-3.0
omni-compiler/omni-compiler
XcodeML-Exc-Tools/src/exc/util/XobjectVisitable.java
107
package exc.util; public interface XobjectVisitable { public boolean enter(XobjectVisitor visitor); }
lgpl-3.0
AnorZaken/aztb
src/nu/mine/obsidian/aztb/bukkit/recipes/v1_0/RecipeHelper.java
38399
package nu.mine.obsidian.aztb.bukkit.recipes.v1_0; /* Copyright (C) 2014 Nicklas Damgren (aka AnorZaken) * * This file is part of AZTB (AnorZakens ToolBox). * * AZTB 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. * * AZTB 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 AZTB. If not, see <http://www.gnu.org/licenses/>. */ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.bukkit.Material; import org.bukkit.Server; import org.bukkit.inventory.FurnaceRecipe; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.Recipe; import org.bukkit.inventory.ShapedRecipe; import org.bukkit.inventory.ShapelessRecipe; import org.bukkit.inventory.meta.ItemMeta; //TODO: testing /** * Tool class with static methods for comparing ingredients of Bukkit {@link Recipe}s, * comparing {@link ItemStack}s and adding/removing {@link Recipe}s from a {@link Server}. * @author AnorZaken * @version 1.0b */ public class RecipeHelper { protected RecipeHelper() {} // -------- Constants -------- /** * {@link ItemStack} durability value {@value #WILDCARD_DURABILITY} is used by bukkit to represent an item-subtype wildcard. * <br><i>(Since bukkit version: ??)</i> */ final public static short WILDCARD_DURABILITY = (short) 32767; //TODO: Since what version of bukkit is this implemented??? // -------- Furnace recipe stack-size settings -------- private static boolean b_compareFurnaceStackSize = false; //Added this toggle in case bukkit starts supporting this /** * Set the compareFurnaceStackSizes setting. (<code>false</code> by default) * <br>Setting this to <code>true</code> enables stack-size comparisons when checking similarity of {@link FurnaceRecipe}s. * @param compareStackSize * @see #compareFurnaceStackSizes() */ public static void compareFurnaceStackSizes(final boolean compareStackSize) { b_compareFurnaceStackSize = compareStackSize; } /** * Get the current setting for compareFurnaceStackSizes. * @return <code>true</code> if the {@link RecipeHelper} methods are set to take {@link ItemStack} stack-size into * account when comparing {@link FurnaceRecipe}s, <code>false</code> if not. * @see #compareFurnaceStackSizes(boolean) */ public static boolean compareFurnaceStackSizes() { return b_compareFurnaceStackSize; } // -------- MetaChecker get & set -------- /** * Creates (or removes) an {@link IMetaChecker} used to compare {@link ItemMeta} of {@link ItemStack}s. * </p>If your class already implements {@link IMetaChecker} use {@link #setMetaChecker(IMetaChecker)} instead! * </p><b>Only set this if the object/class has these methods:</b><br> * <ul> * <li><code>public boolean areItemMetaIdentical(ItemMeta meta1, ItemMeta meta2)</code></li> * <li><b>(OPTIONAL)</b> <code>public boolean isValidItemMeta(ItemMeta meta)</code></li> * </ul> * <b>See {@link #itemStacksMatch(ItemStack, ItemStack, boolean)} for a description of how these are used!</b> * </p>Note1: If both arguments are <code>null</code> any current {@link IMetaChecker} instance will be * removed (if one exists). * </p>Note2: If the {@link Class} implements none of these methods as instance methods the * {@link Object} can be <code>null</code>. * </p>Note3: If the {@link Object} isn't <code>null</code> the {@link Class} argument will be * ignored. (Class inferred from {@link Object} instance). * @return <code>true</code> if both arguments are <code>null</code> or a valid and accessible * <code>areItemMetaIdentical</code> method exists, otherwise <code>false</code> * @see IMetaChecker * @see #setMetaChecker(IMetaChecker) */ public static boolean setMetaChecker(final Class<? extends Object> metaCheckerClass, final Object metaCheckerInstance) { final Class<? extends Object> clazz; clazz = metaCheckerInstance == null ? metaCheckerClass : metaCheckerInstance.getClass(); return MetaCheckerHelper.TrySetMetaChecker(null, clazz, metaCheckerInstance); } /** * Sets (or removes) the {@link IMetaChecker} used to compare {@link ItemMeta} of {@link ItemStack}s. * </p>Note1: If you want to use a class that doesn't implement the {@link IMetaChecker} interface * see {@link #setMetaChecker(Class, Object)}. * </p>Note2: If you want a simple customizable implementation of {@link IMetaChecker} see * {@link MetaChecker}. * @param metaChecker the {@link IMetaChecker} to set, or <code>null</code> to remove the current * {@link IMetaChecker} instance (thus disabling all meta-checks). * @see IMetaChecker * @see MetaChecker * @see #setMetaChecker(Class, Object) */ public static void setMetaChecker(final IMetaChecker metaChecker) { MetaCheckerHelper.TrySetMetaChecker(metaChecker, null, null); } /** * Get the {@link Class} that currently supplies {@link IMetaChecker} functionality.<br> * <b>This is not guaranteed to be a {@link Class} that implements {@link IMetaChecker}!</b> * @return <code>null</code> if there currently doesn't exist one (meta-checking disabled). * @see #setMetaChecker(Class, Object) * @see #setMetaChecker(IMetaChecker) */ public static Class<? extends Object> getMetaCheckerClass() { return MetaCheckerHelper.getMetaCheckerClass(); } /** * Get the instance Object that currently supplies {@link IMetaChecker} functionality.<br> * <b>This is not guaranteed to be an instance of {@link IMetaChecker}!</b> * @return <code>null</code> if there currently doesn't exist one (meta-checking disabled * <u><b>OR</b></u> meta-checking provided via static methods). * @see #setMetaChecker(Class, Object) * @see #setMetaChecker(IMetaChecker) * @see #getMetaChecker() */ public static Object getMetaCheckerInstance() { return MetaCheckerHelper.getMetaCheckerRaw(); } /** * Get the current {@link IMetaChecker} instance. * </p>Note: This can be a wrapper that implements {@link IMetaChecker} functionality using * method invocation (reflection) on an class/object that doesn't implement the {@link IMetaChecker} * interface itself. (Stack-traces might get printed if invocation fails.) * @return the current {@link IMetaChecker} instance, or <code>null</code> if there currently * doesn't exist one (meta-checking disabled). * @see #setMetaChecker(Class, Object) * @see #setMetaChecker(IMetaChecker) * @see IMetaChecker */ public static IMetaChecker getMetaChecker() { return MetaCheckerHelper.getMetaChecker(); } // -------- Higher abstraction methods -------- /** * Checks if trying to add a {@link Recipe} to a {@link Server} would silently fail due to collision with any existing * {@link Recipe}s and optionally removes the existing {@link Recipe}s it collides with. * </p>Note1: Multiple collisions can happen only if the {@link Recipe} argument is a wildcard {@link Recipe}. * </p>Note2: The {@link Recipe} argument is <u>not</u> added to the server by this operation! * </p>Note3: Meta-data comparisons will only be performed if an {@link IMetaChecker} has been set! * @param server * @param removeIfFound if this is <code>false</code> this operation is read-only * @param recipe * @return <code>null</code> if {@link Recipe} argument is <code>null</code>, otherwise a {@link List}&lt;{@link Recipe}&gt; * with the {@link Recipe}s on the {@link Server} that the {@link Recipe} argument collided with. * @throws IllegalArgumentException if {@link Server} is <code>null</code> * @see #isWildcardRecipe(Recipe) * @see #addRecipesToServer(Server, boolean, Recipe...) * @see #setMetaChecker(IMetaChecker) */ public static List<Recipe> serverHasSimilarIngredientRecipe(final Server server, final boolean removeIfFound, final Recipe recipe) { if (server == null) throw new IllegalArgumentException("server is null"); else if (recipe == null) return null; else { final boolean isWild = isWildcardRecipe(recipe); final List<Recipe> collisionList = isWild ? new ArrayList<Recipe>() : new ArrayList<Recipe>(1); final Iterator<Recipe> bukk_it = server.recipeIterator(); while (bukk_it.hasNext()) { final Recipe recipe2 = bukk_it.next(); if (ingredientsMatch(recipe, recipe2)) { collisionList.add(recipe2); if (removeIfFound) bukk_it.remove(); if (!isWild) return collisionList; } } return collisionList; } } /** * Adds a bunch of {@link Recipe}s to a {@link Server}, checking each for collision against an existing {@link Recipe}. * </p>Note1: This method <u>assumes</u> there are no collisions <i>within</i> the {@link Recipe} arguments to be added. * If there are argument-to-argument collisions some {@link Recipe} add operations may silently fail! * <br><b>It is the responsibility of the caller to ensure that no collisions exists among the provided {@link Recipe} * arguments themselves!</b> * </p>Note2: For performance reasons the order in which the {@link Recipe}s are actually added can differ from the * order of the {@link Recipe} arguments. (Thus the outcome of any argument-to-argument collisions are unpredictable!) * </p>Note3: This operation is roughly <b>{@code O}</b><code>(n*m + m*x)</code> where {@code n} and {@code m} is the * pre-existing and to-be-added recipes respectively, and <code>x</code> is the cost of calling * {@link Server#addRecipe(Recipe)}. (This method is intended as a faster alternative to checking each {@link Recipe} * you want to add with {@link #serverHasSimilarIngredientRecipe(Server, boolean, Recipe)} and then adding it manually.) * </p>Note4: <code>null</code> {@link Recipe}s are silently ignored. * </p>Note5: Meta-data comparisons will only be performed if an {@link IMetaChecker} has been set! * @param server * @param allowOverwriteExisting if this is <code>true</code> collisions will be resolved by removal of the existing recipe * @param recipes * @return a {@link List}&lt;{@link Recipe}&gt; - if {@code allowOverwriteExisting} is <code>true</code> this will contain all * the old recipes that where removed, if {@code allowOverwriteExisting} is <code>false</code> this will return all the * new recipes that wasn't added to the {@link Server} due to collisions. In other words it returns all the "casualties" of * collisions.<br>(Returns <code>null</code> if {@code recipes} argument is <code>null</code> or a zero-length array.) * @throws IllegalArgumentException if {@link Server} is <code>null</code> * @see #serverHasSimilarIngredientRecipe(Server, boolean, Recipe) * @see #setMetaChecker(IMetaChecker) * @see #isWildcardRecipe(Recipe) */ public static List<Recipe> addRecipesToServer(final Server server, final boolean allowOverwriteExisting, final Recipe... recipes) { if (server == null) throw new IllegalArgumentException("server is null"); else if (recipes == null || recipes.length == 0) return null; else { /* This code works by first iterating through all existing recipes, checking for collisions against the "recipes" arguments * Any removals that are required due to collisions are performed (resolved) during this iteration. * (Also the casualties are recorded in a List<Recipe>.) * Once all collisions have been resolved a small loop adds all (survived) "recipes" arguments. * List<Recipe> of casualties are returned. */ final List<Recipe> deadRecipes = new LinkedList<Recipe>(); //Casualties of collision final LinkedList<Recipe> toAdd = allowOverwriteExisting ? new LinkedList<Recipe>() : null; //(only used with overwrite) int arrSize = recipes.length; //(this will shrink as entries gets removed from the array) int wildIndexNext = 0; //Any recipe below this index is a wildcard recipe (only used with overwrite) final Iterator<Recipe> bukk_it = server.recipeIterator(); //Collision resolution phase: while (bukk_it.hasNext()) { final Recipe recipe1 = bukk_it.next(); for (int i = 0; i < arrSize; ++i) { final Recipe recipe2 = recipes[i]; if (recipe2 == null) //remove null entries to speed up operation... { --arrSize; recipes[i] = recipes[arrSize]; //"Fast delete" --i; // <-- make sure we dont accidentally skip a recipe argument when fast-deleting! } if (ingredientsMatch(recipe1, recipe2)) //Collision! { if (allowOverwriteExisting) { bukk_it.remove(); deadRecipes.add(recipe1); //add the removed recipe to the collision list if (i >= wildIndexNext) //we have not checked if this is a wildcard recipe { if (isWildcardRecipe(recipe2)) { recipes[i] = recipes[wildIndexNext]; recipes[wildIndexNext] = recipe2; ++wildIndexNext; //since i >= wildIndexNext we dont need to adjust "i" (and we cant get out of bounds) } else //recipe2 is non-wildcard and has collided already => no need to check it against remaining recipes on server { //this removal and adding to a separate list is purely optimization to reduce the number of iterations needed --arrSize; recipes[i] = recipes[arrSize]; //"Fast delete" --i; // <-- make sure we dont accidentally skip a recipe argument when fast-deleting! toAdd.add(recipe2); //move surviving non-wildcard recipe argument to separate list for performance reasons } } break; //server recipe removed => no point in checking it against remaining recipe arguments } else //!allowOverwriteExisting { deadRecipes.add(recipe2); //This recipe could not be added due to collision //recipe2 has collided already => no need to check it against remaining recipes on server: --arrSize; recipes[i] = recipes[arrSize]; //"Fast delete" --i; // <-- make sure we dont accidentally skip a recipe argument when fast-deleting! //we DONT break; here because due to wildcard mechanics the server recipe could collide with multiple arguments! } } } } //All collisions resolved... //Add-to-Server phase: for (int i = 0; i < arrSize; ++i) //adds wildcard recipes and recipes that didn't collide with anything server.addRecipe(recipes[i]); if (allowOverwriteExisting) for (Recipe r : toAdd) //adds non-wildcard recipes that where involved in collisions (but "survived" since overwrite enabled) server.addRecipe(r); //Return casualties: return deadRecipes; } } // -------- Recipe ingredients matching methods -------- /** * Checks if two {@link Recipe}s ingredients are similar* in such a way that both can't exist on a {@link Server} * at the same time. * </p>Note1: {@link ShapedRecipe}s with a 1x1 shape can collide with {@link ShapelessRecipe}s with only 1 * ingredient - this is also checked by this method! * </p>Note2: Meta-data comparisons will only be performed if an {@link IMetaChecker} has been set! * </p>&nbsp;<b>*</b><i>is wildcard recipe aware, see {@link #isWildcardRecipe(Recipe)}</i> * @param recipe1 * @param recipe2 * @return <code>true</code> if both {@link Recipe}s are <code>null</code> or are both references to the same object * or (of the same type and) have similar ingredients, otherwise <code>false</code>. * @see #compareFurnaceStackSizes() * @see #setMetaChecker(IMetaChecker) * @see #ingredientsMatchS(ShapedRecipe, ShapedRecipe) * @see #ingredientsMatchSL(ShapelessRecipe, ShapelessRecipe) * @see #ingredientsMatchF(FurnaceRecipe, FurnaceRecipe) */ public static boolean ingredientsMatch(final Recipe recipe1, final Recipe recipe2) { if (recipe1 == recipe2) return true; else if (recipe1 == null || recipe2 == null) return false; else if (recipe1 instanceof ShapedRecipe) //ShapedRecipes are probably most common so check that first { if (recipe2 instanceof ShapedRecipe) return ingredientsMatchS0((ShapedRecipe)recipe1, (ShapedRecipe)recipe2); else if (recipe2 instanceof ShapelessRecipe) return ingredientsMatchSLS0((ShapelessRecipe) recipe2, (ShapedRecipe) recipe1); } else if (recipe1 instanceof ShapelessRecipe) { if (recipe2 instanceof ShapedRecipe) return ingredientsMatchSLS0((ShapelessRecipe) recipe1, (ShapedRecipe) recipe2); else if (recipe2 instanceof ShapelessRecipe) return ingredientsMatchSL0((ShapelessRecipe)recipe1, (ShapelessRecipe)recipe2); } else if (recipe1 instanceof FurnaceRecipe) { if (recipe2 instanceof FurnaceRecipe) return ingredientsMatchF0((FurnaceRecipe)recipe1, (FurnaceRecipe)recipe2, b_compareFurnaceStackSize); } //else {} //Unknown recipe1 type! //TODO: log? throw? return false; } /** * @see #ingredientsMatch(Recipe, Recipe) */ public static boolean ingredientsMatchS(final ShapedRecipe shaped1, final ShapedRecipe shaped2) { return (shaped1 == shaped2) ? true : (shaped1 == null || shaped2 == null) ? false : ingredientsMatchS0(shaped1, shaped2); } /** * @see #ingredientsMatch(Recipe, Recipe) */ public static boolean ingredientsMatchSL(final ShapelessRecipe shapeless1, final ShapelessRecipe shapeless2) { return (shapeless1 == shapeless2) ? true : (shapeless1 == null || shapeless2 == null) ? false : ingredientsMatchSL0(shapeless1, shapeless2); } /** * Compares ingredients in a {@link ShapelessRecipe} to a {@link ShapedRecipe}. * <br><i>(They can be similar only if the {@link ShapedRecipe} is 1x1 and the {@link ShapelessRecipe} * has exactly 1 ingredient.)</i> * @see #ingredientsMatch(Recipe, Recipe) */ public static boolean ingredientsMatchSLS(final ShapelessRecipe shapeless, final ShapedRecipe shaped) { if(shapeless == null) return shaped == null; else if (shaped == null) return false; else return ingredientsMatchSLS0(shapeless, shaped); } /** * @see #ingredientsMatch(Recipe, Recipe) * @see #compareFurnaceStackSizes() */ public static boolean ingredientsMatchF(final FurnaceRecipe fRecipe1, final FurnaceRecipe fRecipe2) { return (fRecipe1 == fRecipe2) ? true : (fRecipe1 == null || fRecipe2 == null) ? false : ingredientsMatchF0(fRecipe1, fRecipe2, b_compareFurnaceStackSize); } // -------- Recipe ingredients matching methods - without reference-equality and null checks -------- /** * @see #ingredientsMatchS(ShapedRecipe, ShapedRecipe) */ protected static boolean ingredientsMatchS0(final ShapedRecipe shaped1, final ShapedRecipe shaped2) { //Check shape dimensions final String[] sh1 = shaped1.getShape(); //shape final String[] sh2 = shaped2.getShape(); final int h1 = sh1.length; //height final int h2 = sh2.length; final int w1; //width final int w2; if (h1 != h2) return false; //different height else if (h1 != 0) //(not 0x0) { w1 = sh1[0].length(); w2 = sh2[0].length(); if (w1 != w2) return false; //different width } else return true; //neither recipe had any ingredients... (0x0) //Shape dimensions match, proceed to Check actual items final Map<Character, ItemStack> im1 = shaped1.getIngredientMap(); final Map<Character, ItemStack> im2 = shaped2.getIngredientMap(); for(int i = 0; i < h1; ++i) { for(int j = 0; j < w1; ++j) { final char c1 = sh1[i].charAt(j); final char c2 = sh2[i].charAt(j); final ItemStack is1 = im1.get(c1); final ItemStack is2 = im2.get(c2); if (!itemStacksMatch(is1, is2, false)) return false; //recipes differ on grid i:j } } return true; } /** * @see #ingredientsMatchSL(ShapelessRecipe, ShapelessRecipe) */ protected static boolean ingredientsMatchSL0(final ShapelessRecipe shapeless1, final ShapelessRecipe shapeless2) { final List<ItemStack> list1 = shapeless1.getIngredientList(); final List<ItemStack> list2 = shapeless2.getIngredientList(); //return list1.size() == list2.size() && list1.containsAll(list2); //will use ItemStack.equals //^That would have been sooo nice, but doesn't account for durability 32767 if (list1.size() == list2.size()) { int arr2size = list2.size(); //used for "fast-delete" final ItemStack[] is2arr = shapeless2.getIngredientList().toArray(new ItemStack[arr2size]); for (final ItemStack is1 : list1) { for (int i = 0; /*i < arr2size*/ true; ++i) { if (i >= arr2size) //negated loop condition return false; else if (itemStacksMatch(is1, is2arr[i], true)) { --arr2size; is2arr[i] = is2arr[arr2size]; //"Fast delete" --i; // <-- make sure we dont accidentally skip a recipe argument when fast-deleting! break; } } } //return arr2size == 0; //This is always true... return true; } else return false; } /** * @see #ingredientsMatchSLS(ShapelessRecipe, ShapedRecipe) */ protected static boolean ingredientsMatchSLS0(final ShapelessRecipe shapeless, final ShapedRecipe shaped) { final List<ItemStack> listSL = shapeless.getIngredientList(); if (listSL.size() != 1) return false; //shapeless has more than 1 ingredient! final String[] shape = shaped.getShape(); if (shape.length != 1 || shape[0].length() != 1) return false; //shape not 1x1! final ItemStack isS = shaped.getIngredientMap().get(shape[0].charAt(0)); final ItemStack isSL = listSL.get(0); return itemStacksMatch(isS, isSL, true); } /** * @see #ingredientsMatchF(FurnaceRecipe, FurnaceRecipe) */ protected static boolean ingredientsMatchF0(final FurnaceRecipe fRecipe1, final FurnaceRecipe fRecipe2, final boolean compareStackSize) { return itemStacksMatch(fRecipe1.getInput(), fRecipe2.getInput(), compareStackSize); } // -------- ItemStack Helper methods -------- /** * Checks if two {@link ItemStack}s are similar*. * </p>Meta-checks (if enabled) are performed thusly: * <ul> * <li>Both {@link ItemStack}s have meta-data: * <ul> * <li>Use the {@link IMetaChecker#areItemMetaIdentical(ItemMeta, ItemMeta) * areItemMetaIdentical(ItemMeta, ItemMeta)} method to test meta similarity.</li> * </ul> * </li> * <li>None of the {@link ItemStack}s have meta-data: * <ul> * <li>Consider {@link ItemStack}s meta similar.</li> * </ul> * </li> * <li>Only one of the {@link ItemStack}s have meta-data: * <ul> * <li>Does the metaChecker implement the {@link IMetaChecker#isValidItemMeta(ItemMeta) * isValidItemMeta(ItemMeta)} method? * <ul> * <li>No**: Fail the meta similarity check (method will return <code>false</code>)</li> * <li>Yes: Fail the meta similarity check if {@link IMetaChecker#isValidItemMeta(ItemMeta) * isValidItemMeta(ItemMeta)} returns <code>true</code>, * <br>otherwise consider {@link ItemStack} metas similar. (None of them has "valid" meta-data). * </li> * </ul> * </li> * </ul> * </li> * </ul> * </p>Note: Meta-data comparisons will only be performed if an {@link IMetaChecker} has been set! * </p>&nbsp;<b>*</b><i>is wildcard aware, see {@link #isWildcardItemStack(ItemStack)}</i> * <br>&nbsp;<b>**</b><i>see {@link #setMetaChecker(Class, Object)} to understand how this can happen</i> * @param is1 * @param is2 * @param checkStackSize if this is <code>false</code> stack-sizes wont be compared. * @return <code>true</code> if both {@link ItemStack}s are <code>null</code> or both reference the same object * or they passed all <u>performed</u> similarity comparisons, otherwise <code>false</code>. * @see #isWildcardItemStack(ItemStack) * @see #setMetaChecker(Class, Object) * @see #setMetaChecker(IMetaChecker) * @see IMetaChecker */ public static boolean itemStacksMatch(final ItemStack is1, final ItemStack is2, final boolean checkStackSize) { if (is1 == is2) return true; else if (is1 == null || is2 == null) //(these simple checks could be replaced with "isValidStack"-checks) return false; else { //neither is1 nor is2 is null final Material m1 = is1.getType(); final Material m2 = is2.getType(); if (m1 != m2) return false; final short d1 = is1.getDurability(); final short d2 = is2.getDurability(); if (d1 != d2 && d1 != WILDCARD_DURABILITY && d2 != WILDCARD_DURABILITY) return false; if (checkStackSize) { final int ss1 = is1.getAmount(); final int ss2 = is2.getAmount(); if (ss1 != ss2) return false; } if (MetaCheckerHelper.isMetaCheckerAvailable()) //Check meta-data? { //Verbose code: // if (is1.hasItemMeta()) { // if(is2.hasItemMeta()) // return MetaCheckerHelper.isMetaSimilar(is1.getItemMeta(), is2.getItemMeta()); //Both have meta // else if (MetaCheckerHelper.isMetaValid(is1.getItemMeta())) // return false; //#1 had valid meta, #2 had no meta // else // return true; //#1 has invalid meta, #2 had no meta //is TRUE the expected result here?? // } else if (is2.hasItemMeta()) { // if (MetaCheckerHelper.isMetaValid(is2.getItemMeta())) // return false; //#2 had valid meta, #1 had no meta // else // return true; //#2 had invalid meta, #1 had no meta //is TRUE the expected result here?? // } else // return true; //None of them had any meta //^Same code compacted: if (is1.hasItemMeta()) { if(is2.hasItemMeta()) return MetaCheckerHelper.isMetaSimilar(is1.getItemMeta(), is2.getItemMeta()); //Both have meta else if (MetaCheckerHelper.isMetaValid(is1.getItemMeta())) return false; //#1 had valid meta, #2 had no meta } else if (is2.hasItemMeta() && MetaCheckerHelper.isMetaValid(is2.getItemMeta())) return false; //#2 had valid meta, #1 had no meta } return true; //Passed all (performed) similarity checks } } /** * Checks if an {@link ItemStack} is a wildcard {@link ItemStack}. * </p>(A wildcard {@link ItemStack} has the durability {@value #WILDCARD_DURABILITY}.) * @param itemStack * @return * @see #isWildcardRecipe(Recipe) */ public static boolean isWildcardItemStack(final ItemStack itemStack) { return itemStack != null && itemStack.getDurability() == WILDCARD_DURABILITY; } // -------- Recipe Wildcard Helper methods -------- /** * Checks if {@link Recipe} contains any wildcard {@link ItemStack}s. * (This enables a single {@link Recipe} to match several similar ingredient types.) * </p>(A wildcard {@link ItemStack} has the durability {@value #WILDCARD_DURABILITY}.) * @param recipe * @return * @see #isWildcardItemStack(ItemStack) */ public static boolean isWildcardRecipe(final Recipe recipe) { if (recipe == null) return false; else if (recipe instanceof ShapedRecipe) return isWildcardRecipeS((ShapedRecipe)recipe); else if (recipe instanceof ShapelessRecipe) return isWildcardRecipeSL((ShapelessRecipe)recipe); else if (recipe instanceof FurnaceRecipe) return isWildcardRecipeF((FurnaceRecipe)recipe); else return false; //Unknown recipe type... //TODO: log? throw? } /** * @see #isWildcardRecipe(Recipe) */ public static boolean isWildcardRecipeS(final ShapedRecipe shaped) { if (shaped == null) return false; else { final Collection<ItemStack> items = shaped.getIngredientMap().values(); for (ItemStack is : items) if (isWildcardItemStack(is)) return true; return false; } } /** * @see #isWildcardRecipe(Recipe) */ public static boolean isWildcardRecipeSL(final ShapelessRecipe shapeless) { if (shapeless == null) return false; else { for (ItemStack is : shapeless.getIngredientList()) if (isWildcardItemStack(is)) return true; return false; } } /** * @see #isWildcardRecipe(Recipe) */ public static boolean isWildcardRecipeF(final FurnaceRecipe fRecipe) { return fRecipe != null && isWildcardItemStack(fRecipe.getInput()); } // -------- MetaChecker interface / classes -------- /** * Optional interface for implementing MetaChecker methods. * <br><i>(Implementing this is preferred since it avoids reflection!)</i> * </p>(These method names is intentionally the same as CraftBooks ItemUtil.java methods.) * @author AnorZaken * @see RecipeHelper#itemStacksMatch(ItemStack, ItemStack, boolean) * @see RecipeHelper#setMetaChecker(Class, Object) * @see RecipeHelper#setMetaChecker(IMetaChecker) */ public static interface IMetaChecker { /** * Determines if two {@link ItemMeta} objects should be considered identical. * </p>Note1: This method is <u>not</u> required to be able to handle <code>null</code> arguments! * </p>Note2: See {@link RecipeHelper#itemStacksMatch(ItemStack, ItemStack, boolean)} for a * description of how this method is used by the {@link RecipeHelper} class. * @param meta1 * @param meta2 * @return <code>true</code> if the two {@link ItemMeta}s should be considered identical by the * methods in the {@link RecipeHelper} class, otherwise <code>false</code>. * @see RecipeHelper#itemStacksMatch(ItemStack, ItemStack, boolean) */ public boolean areItemMetaIdentical(ItemMeta meta1, ItemMeta meta2); /** * Determines if an {@link ItemMeta} should be considered a valid {@link ItemMeta}. * </p>Note1: This method is <u>not</u> required to be able to handle <code>null</code> as argument! * </p>Note2: See {@link RecipeHelper#itemStacksMatch(ItemStack, ItemStack, boolean)} for a * description of how this method is used by the {@link RecipeHelper} class. * @param meta * @return <code>false</code> if the {@link ItemStack} with this {@link ItemMeta} should be considered * (meta-)equivalent to an {@link ItemStack} that has no meta data, otherwise <code>true</code>. * @see RecipeHelper#itemStacksMatch(ItemStack, ItemStack, boolean) */ public boolean isValidItemMeta(ItemMeta meta); } /** * Helper class to wrap the reflection code related to the metaChecker functionality. * Thus the rest of the {@link RecipeHelper} class doesn't need to know or care about any reflection related issues. * @see RecipeHelper#setMetaChecker(Class, Object) * @see MetaCheckerHelper#TrySetMetaChecker(Class, Object) * @author AnorZaken */ protected static final class MetaCheckerHelper implements IMetaChecker { private static MetaCheckerHelper instance; //instances of this class are immutable :) // ----- Instance variables (all private and immutable) final private Class<? extends Object> metaCheckerClass; //(never null!) final private Object metaCheckerRaw; //(never null!) final private Method areIdenticalMethod; final private Method isValidMethod; final private IMetaChecker metaChecker; //(never null!) // ----- Constructors //For reflection: private MetaCheckerHelper(final Class<? extends Object> metaCheckerClass, final Object metaCheckerInstance, final Method aim, final Method ivm) { this.metaCheckerClass = metaCheckerClass; this.metaCheckerRaw = metaCheckerInstance; this.areIdenticalMethod = aim; this.isValidMethod = ivm; this.metaChecker = this; } //For IMetaChecker: private MetaCheckerHelper(final IMetaChecker metaChecker) { this.metaCheckerClass = metaChecker.getClass(); this.metaCheckerRaw = metaChecker; this.areIdenticalMethod = null; this.isValidMethod = null; this.metaChecker = metaChecker; } // ----- Raw get accessors public static Class<? extends Object> getMetaCheckerClass() { final MetaCheckerHelper instance = MetaCheckerHelper.instance; //Localize the reference (tsafety) return instance == null ? null : instance.metaCheckerClass; } public static Object getMetaCheckerRaw() { final MetaCheckerHelper instance = MetaCheckerHelper.instance; //Localize the reference (tsafety) return instance == null ? null : instance.metaCheckerRaw; } public static IMetaChecker getMetaChecker() { final MetaCheckerHelper instance = MetaCheckerHelper.instance; //Localize the reference (tsafety) return instance == null ? null : instance.metaChecker; } // ----- Helper methods /** * Checks if an {@link IMetaChecker} is available. */ public static boolean isMetaCheckerAvailable() { return instance != null; } /** * Wraps the call to {@link IMetaChecker#areItemMetaIdentical(ItemMeta, ItemMeta)} or to a reflected equivalent. * @param meta1 * @param meta2 * @return (<code>true</code> if no metaChecker available) */ public static boolean isMetaSimilar(ItemMeta meta1, ItemMeta meta2) { final IMetaChecker metaChecker = MetaCheckerHelper.getMetaChecker(); //Localize the reference (tsafety) return metaChecker == null ? true : metaChecker.areItemMetaIdentical(meta1, meta2); } /** * Wraps the call to {@link IMetaChecker#isValidItemMeta(ItemMeta)} or to a reflected equivalent. * @param meta * @return (<code>true</code> if no metaChecker available) */ public static boolean isMetaValid(ItemMeta meta) { final IMetaChecker metaChecker = MetaCheckerHelper.getMetaChecker(); //Localize the reference (tsafety) return metaChecker == null ? true : metaChecker.isValidItemMeta(meta); } // ----- "Wrapper Factory" / MetaChecker setter /** * Tries to set the {@link IMetaChecker} instance, either directly or by creating a wrapper with reflection. * </p>If {@link IMetaChecker} is <code>null</code> it will try using reflection on the provided {@link Class} * argument and, if reflection succeeds, create a wrapper that wraps the needed reflection code as an * {@link IMetaChecker} (and then set that as the active {@link IMetaChecker} instance).</i> * </p>If both the {@link IMetaChecker} and {@link Class} arguments are <code>null</code> it will remove the * currently set {@link IMetaChecker} instance (if one existed), thus disabling all meta-data checks in * {@link RecipeHelper}. * </p><i>Note: Make sure a suitable instance Object is provided if reflection is used (unless the methods are * static, in which case no instance Object is needed for method invocations).</i> * @param metaChecker * @param metaCheckerClass * @param metaCheckerRaw instance object for non-static method calls using reflection * @return <code>false</code> if reflection was needed but failed (also results in a stack-trace), otherwise * <code>true</code> * @see RecipeHelper#setMetaChecker(Class, Object) * @see RecipeHelper#setMetaChecker(IMetaChecker) */ public static boolean TrySetMetaChecker(final IMetaChecker metaChecker, final Class<? extends Object> metaCheckerClass, final Object metaCheckerRaw) { if (metaChecker != null) { instance = new MetaCheckerHelper(metaChecker); return true; } else if (metaCheckerClass == null) { instance = null; return true; } else { final Method aim; try { aim = metaCheckerRaw.getClass().getMethod("areItemMetaIdentical", ItemMeta.class, ItemMeta.class); } catch (NoSuchMethodException e) { e.printStackTrace(); return false; } catch (SecurityException e) { e.printStackTrace(); return false; } Method ivm; try { ivm = metaCheckerRaw.getClass().getMethod("isValidItemMeta", ItemMeta.class); } catch (NoSuchMethodException e) { ivm = null; } catch (SecurityException e) { e.printStackTrace(); return false; } instance = new MetaCheckerHelper(metaCheckerClass, metaCheckerRaw, aim, ivm); return true; } } // ----- Invocation wrapper methods /** * @return the returned value from calling {@code areItemMetaIdentical(ItemMeta, ItemMeta)} with reflection, * or <code>false</code> if the method invocation fails (there will be a stack-trace). * @see #areItemMetaIdentical(ItemMeta, ItemMeta) */ private boolean reflectSimilar(final ItemMeta im1, final ItemMeta im2) { try { return (Boolean) areIdenticalMethod.invoke(metaCheckerRaw, im1, im2); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (ClassCastException e) { e.printStackTrace(); } return false; } /** * @return the returned value from calling {@code isValidItemMeta(ItemMeta)} with reflection, * or <code>true</code> if the method invocation fails (there will be a stack-trace). * @see #isValidItemMeta(ItemMeta) */ private boolean reflectValid(final ItemMeta im) { try { return (Boolean) isValidMethod.invoke(metaCheckerRaw, im); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (ClassCastException e) { e.printStackTrace(); } return true; } // ----- IMetaChecker methods @Override public boolean areItemMetaIdentical(ItemMeta meta1, ItemMeta meta2) { return reflectSimilar(meta1, meta2); } @Override public boolean isValidItemMeta(ItemMeta meta) { return reflectValid(meta); } } }
lgpl-3.0
levyfan/bow
src/main/java/com/github/levyfan/reid/ml/KissMe.java
9791
package com.github.levyfan.reid.ml; import com.github.levyfan.reid.BowImage; import com.github.levyfan.reid.bow.Strip; import com.github.levyfan.reid.feature.Feature; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import org.apache.commons.math3.linear.*; import org.apache.commons.math3.util.Pair; import java.util.List; import java.util.Objects; import java.util.concurrent.*; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * @author fanliwen */ public class KissMe { private static final double ZERO = 10e-10; private static final double EPS = 10e-6; private static final int WORKER_NUM = 4; private ExecutorService executorService = Executors.newWorkStealingPool(WORKER_NUM); public RealMatrix apply(List<BowImage> bowImages, Feature.Type type) { Pair<RealMatrix, RealMatrix> pair = pairPositiveNegative(bowImages, type); RealMatrix positive = pair.getFirst(); RealMatrix negative = pair.getSecond(); RealMatrix M = inv(positive).subtract(inv(negative)); return validateCovMatrix(M); } public RealMatrix apply(List<BowImage> bowImages) throws ExecutionException, InterruptedException { Pair<RealMatrix, RealMatrix> pair = pairPositiveNegative(bowImages); RealMatrix positive = pair.getFirst(); RealMatrix negative = pair.getSecond(); RealMatrix M = inv(positive).subtract(inv(negative)); return validateCovMatrix(M); } Pair<RealMatrix, RealMatrix> pairPositiveNegative(List<BowImage> bowImages, Feature.Type type) { int length = bowImages.get(0).sp4[0].features.get(type).length; Multimap<String, Integer> idMap = ArrayListMultimap.create(); IntStream.range(0, bowImages.size()).forEach(i -> idMap.put(bowImages.get(i).id, i)); List<Object[]> objects = IntStream.range(0, bowImages.size()).parallel().mapToObj(i -> { RealMatrix positive = MatrixUtils.createRealMatrix(length, length); RealMatrix negative = MatrixUtils.createRealMatrix(length, length); BowImage x = bowImages.get(i); System.out.println("kissme: " + x.id); // positive long countPositive = idMap.get(x.id).stream().mapToLong(j -> { BowImage y = bowImages.get(j); if (Objects.equals(x.id, y.id) && j > i && !Objects.equals(x.cam, y.cam)) { Pair<RealMatrix, Long> pair = km(x, y, type); com.github.levyfan.reid.util.MatrixUtils.inplaceAdd(positive, pair.getFirst()); return pair.getSecond(); } else { return 0; } }).sum(); // negative long countNegative = ThreadLocalRandom.current().ints(5, 0, bowImages.size()).mapToLong(j -> { BowImage y = bowImages.get(j); if (!Objects.equals(x.id, y.id) && !Objects.equals(x.cam, y.cam)) { Pair<RealMatrix, Long> pair = km(x, y, type); com.github.levyfan.reid.util.MatrixUtils.inplaceAdd(negative, pair.getFirst()); return pair.getSecond(); } else { return 0; } }).sum(); return new Object[] {positive, negative, countPositive, countNegative}; }).collect(Collectors.toList()); RealMatrix positive = MatrixUtils.createRealMatrix(length, length); RealMatrix negative = MatrixUtils.createRealMatrix(length, length); long countPositive = 0; long countNegative = 0; for (Object[] obj : objects) { com.github.levyfan.reid.util.MatrixUtils.inplaceAdd(positive, (RealMatrix) obj[0]); countPositive += (long) obj[2]; com.github.levyfan.reid.util.MatrixUtils.inplaceAdd(negative, (RealMatrix) obj[1]); countNegative += (long) obj[3]; } positive = positive.scalarMultiply(1.0/(double) countPositive); negative = negative.scalarMultiply(1.0/(double) countNegative); return Pair.create(positive, negative); } Pair<RealMatrix, RealMatrix> pairPositiveNegative(List<BowImage> bowImages) throws ExecutionException, InterruptedException { int length = bowImages.get(0).hist.get(Feature.Type.ALL).length; Multimap<String, Integer> idMap = ArrayListMultimap.create(); IntStream.range(0, bowImages.size()).forEach(i -> idMap.put(bowImages.get(i).id, i)); List<List<BowImage>> input = Lists.partition( bowImages, bowImages.size() / WORKER_NUM); List<Callable<Object[]>> tasks = input.stream() .map(list -> new PairPN(length, Lists.newArrayList(list), bowImages, idMap)) .collect(Collectors.toList()); System.out.println("workers=" + WORKER_NUM); System.out.println("task_nums=" + tasks.size()); List<Future<Object[]>> output = executorService.invokeAll(tasks); RealMatrix positive = null; RealMatrix negative = null; long countPositive = 0; long countNegative = 0; for (Future<Object[]> future : output) { Object[] result = future.get(); if (positive == null) { positive = (RealMatrix) result[0]; } else { com.github.levyfan.reid.util.MatrixUtils.inplaceAdd(positive, (RealMatrix) result[0]); } if (negative == null) { negative = (RealMatrix) result[1]; } else { com.github.levyfan.reid.util.MatrixUtils.inplaceAdd(negative, (RealMatrix) result[1]); } countPositive += ((Pair<Long, Long>) result[2]).getFirst(); countNegative += ((Pair<Long, Long>) result[2]).getSecond(); } positive = positive.scalarMultiply(1.0/(double) countPositive); negative = negative.scalarMultiply(1.0/(double) countNegative); return Pair.create(positive, negative); } static RealMatrix validateCovMatrix(RealMatrix sig) { try { new CholeskyDecomposition(sig, 1.0e-5, 1.0e-10); return sig; } catch (NonPositiveDefiniteMatrixException | NonSymmetricMatrixException e) { if (e instanceof NonSymmetricMatrixException) { NonSymmetricMatrixException ee = (NonSymmetricMatrixException) e; System.out.println("(" + ee.getRow() + "," + ee.getColumn() + ")=" + sig.getEntry(ee.getRow(), ee.getColumn())); System.out.println("(" + ee.getColumn() + "," + ee.getRow() + ")=" + sig.getEntry(ee.getColumn(), ee.getRow())); } EigenDecomposition eigen = new EigenDecomposition(sig); RealMatrix v = eigen.getV(); RealMatrix d = eigen.getD().copy(); for (int n = 0; n < d.getColumnDimension(); n ++) { if (d.getEntry(n, n) < ZERO) { d.setEntry(n, n, EPS); } } sig = v.multiply(d).multiply(v.transpose()); try { new CholeskyDecomposition(sig, CholeskyDecomposition.DEFAULT_ABSOLUTE_POSITIVITY_THRESHOLD, CholeskyDecomposition.DEFAULT_ABSOLUTE_POSITIVITY_THRESHOLD); } catch (Exception ee) { ee.printStackTrace(); } return sig; } } static RealMatrix inv(RealMatrix matrix) { try { return new LUDecomposition(matrix).getSolver().getInverse(); } catch (SingularMatrixException e) { e.printStackTrace(); return new SingularValueDecomposition(matrix).getSolver().getInverse(); } } private static Pair<RealMatrix, Long> km(BowImage i, BowImage j, Feature.Type type) { int length = i.sp4[0].features.get(type).length; RealMatrix matrix = MatrixUtils.createRealMatrix(length, length); long count = 0; for (int nstrip = 0; nstrip < i.strip4.length; nstrip ++) { Strip iStrip = i.strip4[nstrip]; Strip jStrip = j.strip4[nstrip]; for (int iSuperPixel : iStrip.superPixels) { for (int jSuperPixel : jStrip.superPixels) { ArrayRealVector iFeature = new ArrayRealVector(i.sp4[iSuperPixel].features.get(type), false); ArrayRealVector jFeature = new ArrayRealVector(j.sp4[jSuperPixel].features.get(type), false); ArrayRealVector delta = iFeature.subtract(jFeature); com.github.levyfan.reid.util.MatrixUtils.inplaceAdd(matrix, delta.outerProduct(delta)); count++; } } } return Pair.create(matrix, count); } private static RealMatrix km(BowImage i, BowImage j) { ArrayRealVector iHist = new ArrayRealVector(i.hist.get(Feature.Type.ALL), false); ArrayRealVector jHist = new ArrayRealVector(j.hist.get(Feature.Type.ALL), false); ArrayRealVector delta = iHist.subtract(jHist); return delta.outerProduct(delta); } private static void km(RealMatrix matrix, BowImage i, BowImage j) { double[] iHist = i.hist.get(Feature.Type.ALL); double[] jHist = j.hist.get(Feature.Type.ALL); for (int m = 0; m < iHist.length; m ++) { for (int n = 0; n < jHist.length; n ++) { double d = (iHist[m] - jHist[m]) * (iHist[n] - jHist[n]); matrix.setEntry(m, n, matrix.getEntry(m, n) + d); } } } }
lgpl-3.0
mdilai/jweegad
external/rocksdb/java/src/main/java/org/rocksdb/ColumnFamilyOptions.java
26794
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. package org.rocksdb; import java.util.ArrayList; import java.util.List; import java.util.Properties; /** * ColumnFamilyOptions to control the behavior of a database. It will be used * during the creation of a {@link org.rocksdb.RocksDB} (i.e., RocksDB.open()). * * If {@link #dispose()} function is not called, then it will be GC'd * automatically and native resources will be released as part of the process. */ public class ColumnFamilyOptions extends RocksObject implements ColumnFamilyOptionsInterface, MutableColumnFamilyOptionsInterface { static { RocksDB.loadLibrary(); } /** * Construct ColumnFamilyOptions. * * This constructor will create (by allocating a block of memory) * an {@code rocksdb::DBOptions} in the c++ side. */ public ColumnFamilyOptions() { super(newColumnFamilyOptions()); } /** * <p>Method to get a options instance by using pre-configured * property values. If one or many values are undefined in * the context of RocksDB the method will return a null * value.</p> * * <p><strong>Note</strong>: Property keys can be derived from * getter methods within the options class. Example: the method * {@code writeBufferSize()} has a property key: * {@code write_buffer_size}.</p> * * @param properties {@link java.util.Properties} instance. * * @return {@link org.rocksdb.ColumnFamilyOptions instance} * or null. * * @throws java.lang.IllegalArgumentException if null or empty * {@link Properties} instance is passed to the method call. */ public static ColumnFamilyOptions getColumnFamilyOptionsFromProps( final Properties properties) { if (properties == null || properties.size() == 0) { throw new IllegalArgumentException( "Properties value must contain at least one value."); } ColumnFamilyOptions columnFamilyOptions = null; StringBuilder stringBuilder = new StringBuilder(); for (final String name : properties.stringPropertyNames()){ stringBuilder.append(name); stringBuilder.append("="); stringBuilder.append(properties.getProperty(name)); stringBuilder.append(";"); } long handle = getColumnFamilyOptionsFromProps( stringBuilder.toString()); if (handle != 0){ columnFamilyOptions = new ColumnFamilyOptions(handle); } return columnFamilyOptions; } @Override public ColumnFamilyOptions optimizeForPointLookup( final long blockCacheSizeMb) { optimizeForPointLookup(nativeHandle_, blockCacheSizeMb); return this; } @Override public ColumnFamilyOptions optimizeLevelStyleCompaction() { optimizeLevelStyleCompaction(nativeHandle_, DEFAULT_COMPACTION_MEMTABLE_MEMORY_BUDGET); return this; } @Override public ColumnFamilyOptions optimizeLevelStyleCompaction( final long memtableMemoryBudget) { optimizeLevelStyleCompaction(nativeHandle_, memtableMemoryBudget); return this; } @Override public ColumnFamilyOptions optimizeUniversalStyleCompaction() { optimizeUniversalStyleCompaction(nativeHandle_, DEFAULT_COMPACTION_MEMTABLE_MEMORY_BUDGET); return this; } @Override public ColumnFamilyOptions optimizeUniversalStyleCompaction( final long memtableMemoryBudget) { optimizeUniversalStyleCompaction(nativeHandle_, memtableMemoryBudget); return this; } @Override public ColumnFamilyOptions setComparator( final BuiltinComparator builtinComparator) { assert(isOwningHandle()); setComparatorHandle(nativeHandle_, builtinComparator.ordinal()); return this; } @Override public ColumnFamilyOptions setComparator( final AbstractComparator<? extends AbstractSlice<?>> comparator) { assert (isOwningHandle()); setComparatorHandle(nativeHandle_, comparator.getNativeHandle()); comparator_ = comparator; return this; } @Override public ColumnFamilyOptions setMergeOperatorName(final String name) { assert (isOwningHandle()); if (name == null) { throw new IllegalArgumentException( "Merge operator name must not be null."); } setMergeOperatorName(nativeHandle_, name); return this; } @Override public ColumnFamilyOptions setMergeOperator( final MergeOperator mergeOperator) { setMergeOperator(nativeHandle_, mergeOperator.nativeHandle_); return this; } public ColumnFamilyOptions setCompactionFilter( final AbstractCompactionFilter<? extends AbstractSlice<?>> compactionFilter) { setCompactionFilterHandle(nativeHandle_, compactionFilter.nativeHandle_); compactionFilter_ = compactionFilter; return this; } @Override public ColumnFamilyOptions setWriteBufferSize(final long writeBufferSize) { assert(isOwningHandle()); setWriteBufferSize(nativeHandle_, writeBufferSize); return this; } @Override public long writeBufferSize() { assert(isOwningHandle()); return writeBufferSize(nativeHandle_); } @Override public ColumnFamilyOptions setMaxWriteBufferNumber( final int maxWriteBufferNumber) { assert(isOwningHandle()); setMaxWriteBufferNumber(nativeHandle_, maxWriteBufferNumber); return this; } @Override public int maxWriteBufferNumber() { assert(isOwningHandle()); return maxWriteBufferNumber(nativeHandle_); } @Override public ColumnFamilyOptions setMinWriteBufferNumberToMerge( final int minWriteBufferNumberToMerge) { setMinWriteBufferNumberToMerge(nativeHandle_, minWriteBufferNumberToMerge); return this; } @Override public int minWriteBufferNumberToMerge() { return minWriteBufferNumberToMerge(nativeHandle_); } @Override public ColumnFamilyOptions useFixedLengthPrefixExtractor(final int n) { assert(isOwningHandle()); useFixedLengthPrefixExtractor(nativeHandle_, n); return this; } @Override public ColumnFamilyOptions useCappedPrefixExtractor(final int n) { assert(isOwningHandle()); useCappedPrefixExtractor(nativeHandle_, n); return this; } @Override public ColumnFamilyOptions setCompressionType( final CompressionType compressionType) { setCompressionType(nativeHandle_, compressionType.getValue()); return this; } @Override public CompressionType compressionType() { return CompressionType.values()[compressionType(nativeHandle_)]; } @Override public ColumnFamilyOptions setCompressionPerLevel( final List<CompressionType> compressionLevels) { final byte[] byteCompressionTypes = new byte[ compressionLevels.size()]; for (int i = 0; i < compressionLevels.size(); i++) { byteCompressionTypes[i] = compressionLevels.get(i).getValue(); } setCompressionPerLevel(nativeHandle_, byteCompressionTypes); return this; } @Override public List<CompressionType> compressionPerLevel() { final byte[] byteCompressionTypes = compressionPerLevel(nativeHandle_); final List<CompressionType> compressionLevels = new ArrayList<>(); for (final Byte byteCompressionType : byteCompressionTypes) { compressionLevels.add(CompressionType.getCompressionType( byteCompressionType)); } return compressionLevels; } @Override public ColumnFamilyOptions setNumLevels(final int numLevels) { setNumLevels(nativeHandle_, numLevels); return this; } @Override public int numLevels() { return numLevels(nativeHandle_); } @Override public ColumnFamilyOptions setLevelZeroFileNumCompactionTrigger( final int numFiles) { setLevelZeroFileNumCompactionTrigger( nativeHandle_, numFiles); return this; } @Override public int levelZeroFileNumCompactionTrigger() { return levelZeroFileNumCompactionTrigger(nativeHandle_); } @Override public ColumnFamilyOptions setLevelZeroSlowdownWritesTrigger( final int numFiles) { setLevelZeroSlowdownWritesTrigger(nativeHandle_, numFiles); return this; } @Override public int levelZeroSlowdownWritesTrigger() { return levelZeroSlowdownWritesTrigger(nativeHandle_); } @Override public ColumnFamilyOptions setLevelZeroStopWritesTrigger(final int numFiles) { setLevelZeroStopWritesTrigger(nativeHandle_, numFiles); return this; } @Override public int levelZeroStopWritesTrigger() { return levelZeroStopWritesTrigger(nativeHandle_); } @Override public ColumnFamilyOptions setMaxMemCompactionLevel( final int maxMemCompactionLevel) { return this; } @Override public int maxMemCompactionLevel() { return 0; } @Override public ColumnFamilyOptions setTargetFileSizeBase( final long targetFileSizeBase) { setTargetFileSizeBase(nativeHandle_, targetFileSizeBase); return this; } @Override public long targetFileSizeBase() { return targetFileSizeBase(nativeHandle_); } @Override public ColumnFamilyOptions setTargetFileSizeMultiplier( final int multiplier) { setTargetFileSizeMultiplier(nativeHandle_, multiplier); return this; } @Override public int targetFileSizeMultiplier() { return targetFileSizeMultiplier(nativeHandle_); } @Override public ColumnFamilyOptions setMaxBytesForLevelBase( final long maxBytesForLevelBase) { setMaxBytesForLevelBase(nativeHandle_, maxBytesForLevelBase); return this; } @Override public long maxBytesForLevelBase() { return maxBytesForLevelBase(nativeHandle_); } @Override public ColumnFamilyOptions setLevelCompactionDynamicLevelBytes( final boolean enableLevelCompactionDynamicLevelBytes) { setLevelCompactionDynamicLevelBytes(nativeHandle_, enableLevelCompactionDynamicLevelBytes); return this; } @Override public boolean levelCompactionDynamicLevelBytes() { return levelCompactionDynamicLevelBytes(nativeHandle_); } @Override public ColumnFamilyOptions setMaxBytesForLevelMultiplier(final double multiplier) { setMaxBytesForLevelMultiplier(nativeHandle_, multiplier); return this; } @Override public double maxBytesForLevelMultiplier() { return maxBytesForLevelMultiplier(nativeHandle_); } @Override public ColumnFamilyOptions setMaxCompactionBytes(final long maxCompactionBytes) { setMaxCompactionBytes(nativeHandle_, maxCompactionBytes); return this; } @Override public long maxCompactionBytes() { return maxCompactionBytes(nativeHandle_); } @Override public ColumnFamilyOptions setSoftRateLimit( final double softRateLimit) { setSoftRateLimit(nativeHandle_, softRateLimit); return this; } @Override public double softRateLimit() { return softRateLimit(nativeHandle_); } @Override public ColumnFamilyOptions setHardRateLimit( final double hardRateLimit) { setHardRateLimit(nativeHandle_, hardRateLimit); return this; } @Override public double hardRateLimit() { return hardRateLimit(nativeHandle_); } @Override public ColumnFamilyOptions setRateLimitDelayMaxMilliseconds( final int rateLimitDelayMaxMilliseconds) { setRateLimitDelayMaxMilliseconds( nativeHandle_, rateLimitDelayMaxMilliseconds); return this; } @Override public int rateLimitDelayMaxMilliseconds() { return rateLimitDelayMaxMilliseconds(nativeHandle_); } @Override public ColumnFamilyOptions setArenaBlockSize( final long arenaBlockSize) { setArenaBlockSize(nativeHandle_, arenaBlockSize); return this; } @Override public long arenaBlockSize() { return arenaBlockSize(nativeHandle_); } @Override public ColumnFamilyOptions setDisableAutoCompactions( final boolean disableAutoCompactions) { setDisableAutoCompactions(nativeHandle_, disableAutoCompactions); return this; } @Override public boolean disableAutoCompactions() { return disableAutoCompactions(nativeHandle_); } @Override public ColumnFamilyOptions setPurgeRedundantKvsWhileFlush( final boolean purgeRedundantKvsWhileFlush) { setPurgeRedundantKvsWhileFlush( nativeHandle_, purgeRedundantKvsWhileFlush); return this; } @Override public boolean purgeRedundantKvsWhileFlush() { return purgeRedundantKvsWhileFlush(nativeHandle_); } @Override public ColumnFamilyOptions setCompactionStyle( final CompactionStyle compactionStyle) { setCompactionStyle(nativeHandle_, compactionStyle.getValue()); return this; } @Override public CompactionStyle compactionStyle() { return CompactionStyle.values()[compactionStyle(nativeHandle_)]; } @Override public ColumnFamilyOptions setMaxTableFilesSizeFIFO( final long maxTableFilesSize) { assert(maxTableFilesSize > 0); // unsigned native type assert(isOwningHandle()); setMaxTableFilesSizeFIFO(nativeHandle_, maxTableFilesSize); return this; } @Override public long maxTableFilesSizeFIFO() { return maxTableFilesSizeFIFO(nativeHandle_); } @Override public ColumnFamilyOptions setMaxSequentialSkipInIterations( final long maxSequentialSkipInIterations) { setMaxSequentialSkipInIterations(nativeHandle_, maxSequentialSkipInIterations); return this; } @Override public long maxSequentialSkipInIterations() { return maxSequentialSkipInIterations(nativeHandle_); } @Override public ColumnFamilyOptions setMemTableConfig( final MemTableConfig config) { memTableConfig_ = config; setMemTableFactory(nativeHandle_, config.newMemTableFactoryHandle()); return this; } @Override public String memTableFactoryName() { assert(isOwningHandle()); return memTableFactoryName(nativeHandle_); } @Override public ColumnFamilyOptions setTableFormatConfig( final TableFormatConfig config) { tableFormatConfig_ = config; setTableFactory(nativeHandle_, config.newTableFactoryHandle()); return this; } @Override public String tableFactoryName() { assert(isOwningHandle()); return tableFactoryName(nativeHandle_); } @Override public ColumnFamilyOptions setInplaceUpdateSupport( final boolean inplaceUpdateSupport) { setInplaceUpdateSupport(nativeHandle_, inplaceUpdateSupport); return this; } @Override public boolean inplaceUpdateSupport() { return inplaceUpdateSupport(nativeHandle_); } @Override public ColumnFamilyOptions setInplaceUpdateNumLocks( final long inplaceUpdateNumLocks) { setInplaceUpdateNumLocks(nativeHandle_, inplaceUpdateNumLocks); return this; } @Override public long inplaceUpdateNumLocks() { return inplaceUpdateNumLocks(nativeHandle_); } @Override public ColumnFamilyOptions setMemtablePrefixBloomSizeRatio( final double memtablePrefixBloomSizeRatio) { setMemtablePrefixBloomSizeRatio(nativeHandle_, memtablePrefixBloomSizeRatio); return this; } @Override public double memtablePrefixBloomSizeRatio() { return memtablePrefixBloomSizeRatio(nativeHandle_); } @Override public ColumnFamilyOptions setBloomLocality(int bloomLocality) { setBloomLocality(nativeHandle_, bloomLocality); return this; } @Override public int bloomLocality() { return bloomLocality(nativeHandle_); } @Override public ColumnFamilyOptions setMaxSuccessiveMerges( final long maxSuccessiveMerges) { setMaxSuccessiveMerges(nativeHandle_, maxSuccessiveMerges); return this; } @Override public long maxSuccessiveMerges() { return maxSuccessiveMerges(nativeHandle_); } @Override public ColumnFamilyOptions setOptimizeFiltersForHits( final boolean optimizeFiltersForHits) { setOptimizeFiltersForHits(nativeHandle_, optimizeFiltersForHits); return this; } @Override public boolean optimizeFiltersForHits() { return optimizeFiltersForHits(nativeHandle_); } @Override public ColumnFamilyOptions setMemtableHugePageSize( long memtableHugePageSize) { setMemtableHugePageSize(nativeHandle_, memtableHugePageSize); return this; } @Override public long memtableHugePageSize() { return memtableHugePageSize(nativeHandle_); } @Override public ColumnFamilyOptions setSoftPendingCompactionBytesLimit(long softPendingCompactionBytesLimit) { setSoftPendingCompactionBytesLimit(nativeHandle_, softPendingCompactionBytesLimit); return this; } @Override public long softPendingCompactionBytesLimit() { return softPendingCompactionBytesLimit(nativeHandle_); } @Override public ColumnFamilyOptions setHardPendingCompactionBytesLimit(long hardPendingCompactionBytesLimit) { setHardPendingCompactionBytesLimit(nativeHandle_, hardPendingCompactionBytesLimit); return this; } @Override public long hardPendingCompactionBytesLimit() { return hardPendingCompactionBytesLimit(nativeHandle_); } @Override public ColumnFamilyOptions setLevel0FileNumCompactionTrigger(int level0FileNumCompactionTrigger) { setLevel0FileNumCompactionTrigger(nativeHandle_, level0FileNumCompactionTrigger); return this; } @Override public int level0FileNumCompactionTrigger() { return level0FileNumCompactionTrigger(nativeHandle_); } @Override public ColumnFamilyOptions setLevel0SlowdownWritesTrigger(int level0SlowdownWritesTrigger) { setLevel0SlowdownWritesTrigger(nativeHandle_, level0SlowdownWritesTrigger); return this; } @Override public int level0SlowdownWritesTrigger() { return level0SlowdownWritesTrigger(nativeHandle_); } @Override public ColumnFamilyOptions setLevel0StopWritesTrigger(int level0StopWritesTrigger) { setLevel0StopWritesTrigger(nativeHandle_, level0StopWritesTrigger); return this; } @Override public int level0StopWritesTrigger() { return level0StopWritesTrigger(nativeHandle_); } @Override public ColumnFamilyOptions setMaxBytesForLevelMultiplierAdditional(int[] maxBytesForLevelMultiplierAdditional) { setMaxBytesForLevelMultiplierAdditional(nativeHandle_, maxBytesForLevelMultiplierAdditional); return this; } @Override public int[] maxBytesForLevelMultiplierAdditional() { return maxBytesForLevelMultiplierAdditional(nativeHandle_); } @Override public ColumnFamilyOptions setParanoidFileChecks(boolean paranoidFileChecks) { setParanoidFileChecks(nativeHandle_, paranoidFileChecks); return this; } @Override public boolean paranoidFileChecks() { return paranoidFileChecks(nativeHandle_); } /** * <p>Private constructor to be used by * {@link #getColumnFamilyOptionsFromProps(java.util.Properties)}</p> * * @param handle native handle to ColumnFamilyOptions instance. */ private ColumnFamilyOptions(final long handle) { super(handle); } private static native long getColumnFamilyOptionsFromProps( String optString); private static native long newColumnFamilyOptions(); @Override protected final native void disposeInternal(final long handle); private native void optimizeForPointLookup(long handle, long blockCacheSizeMb); private native void optimizeLevelStyleCompaction(long handle, long memtableMemoryBudget); private native void optimizeUniversalStyleCompaction(long handle, long memtableMemoryBudget); private native void setComparatorHandle(long handle, int builtinComparator); private native void setComparatorHandle(long optHandle, long comparatorHandle); private native void setMergeOperatorName(long handle, String name); private native void setMergeOperator(long handle, long mergeOperatorHandle); private native void setCompactionFilterHandle(long handle, long compactionFilterHandle); private native void setWriteBufferSize(long handle, long writeBufferSize) throws IllegalArgumentException; private native long writeBufferSize(long handle); private native void setMaxWriteBufferNumber( long handle, int maxWriteBufferNumber); private native int maxWriteBufferNumber(long handle); private native void setMinWriteBufferNumberToMerge( long handle, int minWriteBufferNumberToMerge); private native int minWriteBufferNumberToMerge(long handle); private native void setCompressionType(long handle, byte compressionType); private native byte compressionType(long handle); private native void setCompressionPerLevel(long handle, byte[] compressionLevels); private native byte[] compressionPerLevel(long handle); private native void useFixedLengthPrefixExtractor( long handle, int prefixLength); private native void useCappedPrefixExtractor( long handle, int prefixLength); private native void setNumLevels( long handle, int numLevels); private native int numLevels(long handle); private native void setLevelZeroFileNumCompactionTrigger( long handle, int numFiles); private native int levelZeroFileNumCompactionTrigger(long handle); private native void setLevelZeroSlowdownWritesTrigger( long handle, int numFiles); private native int levelZeroSlowdownWritesTrigger(long handle); private native void setLevelZeroStopWritesTrigger( long handle, int numFiles); private native int levelZeroStopWritesTrigger(long handle); private native void setTargetFileSizeBase( long handle, long targetFileSizeBase); private native long targetFileSizeBase(long handle); private native void setTargetFileSizeMultiplier( long handle, int multiplier); private native int targetFileSizeMultiplier(long handle); private native void setMaxBytesForLevelBase( long handle, long maxBytesForLevelBase); private native long maxBytesForLevelBase(long handle); private native void setLevelCompactionDynamicLevelBytes( long handle, boolean enableLevelCompactionDynamicLevelBytes); private native boolean levelCompactionDynamicLevelBytes( long handle); private native void setMaxBytesForLevelMultiplier(long handle, double multiplier); private native double maxBytesForLevelMultiplier(long handle); private native void setMaxCompactionBytes(long handle, long maxCompactionBytes); private native long maxCompactionBytes(long handle); private native void setSoftRateLimit( long handle, double softRateLimit); private native double softRateLimit(long handle); private native void setHardRateLimit( long handle, double hardRateLimit); private native double hardRateLimit(long handle); private native void setRateLimitDelayMaxMilliseconds( long handle, int rateLimitDelayMaxMilliseconds); private native int rateLimitDelayMaxMilliseconds(long handle); private native void setArenaBlockSize( long handle, long arenaBlockSize) throws IllegalArgumentException; private native long arenaBlockSize(long handle); private native void setDisableAutoCompactions( long handle, boolean disableAutoCompactions); private native boolean disableAutoCompactions(long handle); private native void setCompactionStyle(long handle, byte compactionStyle); private native byte compactionStyle(long handle); private native void setMaxTableFilesSizeFIFO( long handle, long max_table_files_size); private native long maxTableFilesSizeFIFO(long handle); private native void setPurgeRedundantKvsWhileFlush( long handle, boolean purgeRedundantKvsWhileFlush); private native boolean purgeRedundantKvsWhileFlush(long handle); private native void setMaxSequentialSkipInIterations( long handle, long maxSequentialSkipInIterations); private native long maxSequentialSkipInIterations(long handle); private native void setMemTableFactory(long handle, long factoryHandle); private native String memTableFactoryName(long handle); private native void setTableFactory(long handle, long factoryHandle); private native String tableFactoryName(long handle); private native void setInplaceUpdateSupport( long handle, boolean inplaceUpdateSupport); private native boolean inplaceUpdateSupport(long handle); private native void setInplaceUpdateNumLocks( long handle, long inplaceUpdateNumLocks) throws IllegalArgumentException; private native long inplaceUpdateNumLocks(long handle); private native void setMemtablePrefixBloomSizeRatio( long handle, double memtablePrefixBloomSizeRatio); private native double memtablePrefixBloomSizeRatio(long handle); private native void setBloomLocality( long handle, int bloomLocality); private native int bloomLocality(long handle); private native void setMaxSuccessiveMerges( long handle, long maxSuccessiveMerges) throws IllegalArgumentException; private native long maxSuccessiveMerges(long handle); private native void setOptimizeFiltersForHits(long handle, boolean optimizeFiltersForHits); private native boolean optimizeFiltersForHits(long handle); private native void setMemtableHugePageSize(long handle, long memtableHugePageSize); private native long memtableHugePageSize(long handle); private native void setSoftPendingCompactionBytesLimit(long handle, long softPendingCompactionBytesLimit); private native long softPendingCompactionBytesLimit(long handle); private native void setHardPendingCompactionBytesLimit(long handle, long hardPendingCompactionBytesLimit); private native long hardPendingCompactionBytesLimit(long handle); private native void setLevel0FileNumCompactionTrigger(long handle, int level0FileNumCompactionTrigger); private native int level0FileNumCompactionTrigger(long handle); private native void setLevel0SlowdownWritesTrigger(long handle, int level0SlowdownWritesTrigger); private native int level0SlowdownWritesTrigger(long handle); private native void setLevel0StopWritesTrigger(long handle, int level0StopWritesTrigger); private native int level0StopWritesTrigger(long handle); private native void setMaxBytesForLevelMultiplierAdditional(long handle, int[] maxBytesForLevelMultiplierAdditional); private native int[] maxBytesForLevelMultiplierAdditional(long handle); private native void setParanoidFileChecks(long handle, boolean paranoidFileChecks); private native boolean paranoidFileChecks(long handle); MemTableConfig memTableConfig_; TableFormatConfig tableFormatConfig_; AbstractComparator<? extends AbstractSlice<?>> comparator_; AbstractCompactionFilter<? extends AbstractSlice<?>> compactionFilter_; }
lgpl-3.0
xinghuangxu/xinghuangxu.sonarqube
plugins/sonar-core-plugin/src/test/java/org/sonar/plugins/core/issue/notification/NewIssuesEmailTemplateTest.java
4535
/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2013 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube 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. * * SonarQube is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.plugins.core.issue.notification; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.sonar.api.config.EmailSettings; import org.sonar.api.notifications.Notification; import org.sonar.core.i18n.DefaultI18n; import org.sonar.plugins.emailnotifications.api.EmailMessage; import java.util.Locale; import java.util.TimeZone; import static org.fest.assertions.Assertions.assertThat; import static org.mockito.Matchers.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class NewIssuesEmailTemplateTest { NewIssuesEmailTemplate template; TimeZone initialTimeZone = TimeZone.getDefault(); @Mock DefaultI18n i18n; @Before public void setUp() { EmailSettings settings = mock(EmailSettings.class); when(settings.getServerBaseURL()).thenReturn("http://nemo.sonarsource.org"); template = new NewIssuesEmailTemplate(settings, i18n); TimeZone.setDefault(TimeZone.getTimeZone("GMT")); } @After public void tearDown() { TimeZone.setDefault(initialTimeZone); } @Test public void shouldNotFormatIfNotCorrectNotification() { Notification notification = new Notification("other-notif"); EmailMessage message = template.format(notification); assertThat(message).isNull(); } /** * <pre> * Subject: Project Struts, new issues * From: Sonar * * Project: Foo * 32 new issues * * See it in SonarQube: http://nemo.sonarsource.org/drilldown/measures/org.sonar.foo:foo?metric=new_violations * </pre> */ @Test public void shouldFormatCommentAdded() { Notification notification = new Notification("new-issues") .setFieldValue("count", "32") .setFieldValue("count-INFO", "1") .setFieldValue("count-MINOR", "3") .setFieldValue("count-MAJOR", "10") .setFieldValue("count-CRITICAL", "5") .setFieldValue("count-BLOCKER", "0") .setFieldValue("projectName", "Struts") .setFieldValue("projectKey", "org.apache:struts") .setFieldValue("projectDate", "2010-05-18T14:50:45+0000"); when(i18n.message(any(Locale.class), eq("severity.BLOCKER"), anyString())).thenReturn("Blocker"); when(i18n.message(any(Locale.class), eq("severity.CRITICAL"), anyString())).thenReturn("Critical"); when(i18n.message(any(Locale.class), eq("severity.MAJOR"), anyString())).thenReturn("Major"); when(i18n.message(any(Locale.class), eq("severity.MINOR"), anyString())).thenReturn("Minor"); when(i18n.message(any(Locale.class), eq("severity.INFO"), anyString())).thenReturn("Info"); EmailMessage message = template.format(notification); assertThat(message.getMessageId()).isEqualTo("new-issues/org.apache:struts"); assertThat(message.getSubject()).isEqualTo("Struts: new issues"); assertThat(message.getMessage()).isEqualTo("" + "Project: Struts\n" + "\n" + "32 new issues\n" + "\n" + " Blocker: 0 Critical: 5 Major: 10 Minor: 3 Info: 1\n" + "\n" + "See it in SonarQube: http://nemo.sonarsource.org/issues/search#componentRoots=org.apache%3Astruts|createdAt=2010-05-18T14%3A50%3A45%2B0000\n"); } @Test public void shouldNotAddFooterIfMissingProperties() { Notification notification = new Notification("new-issues") .setFieldValue("count", "32") .setFieldValue("projectName", "Struts"); EmailMessage message = template.format(notification); assertThat(message.getMessage()).doesNotContain("See it"); } }
lgpl-3.0
butterbrother/thytom
src/main/java/com/github/butterbrother/thytom/JarLoader.java
1672
package com.github.butterbrother.thytom; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Files; import java.nio.file.Path; /** * Осуществляет подзагрузку библиотек после запуска приложения. */ public class JarLoader { private Method addURL; /** * Инициализация * * @throws Exception */ public JarLoader() throws Exception { //URLClassLoader.addURL(URL url) - protected void addURL = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); addURL.setAccessible(true); } /** * Выполняет загрузку одиночной библиотеки * * @param library путь к библиотеке * @throws Exception ошибка загрузки */ public void load(Path library) throws Exception { if (Files.exists(library) && library.toString().endsWith(".jar")) addURL.invoke(ClassLoader.getSystemClassLoader(), library.toUri().toURL()); } /** * Выполняет загрузку всех библиотек из указанного каталога. * * @param librariesPath Каталог с библиотеками * @throws Exception ошибка при загрузке библиотек */ public void loadAll(Path librariesPath) throws Exception { if (Files.exists(librariesPath) && Files.isDirectory(librariesPath)) for (Path library : Files.newDirectoryStream(librariesPath, "*.jar")) { load(library); } } }
lgpl-3.0
unascribed/Glass-Pane
src/main/java/gminers/glasspane/component/button/PaneRadioButton.java
1770
package gminers.glasspane.component.button; import gminers.glasspane.HorzAlignment; import gminers.glasspane.event.ComponentActivateEvent; import gminers.glasspane.listener.PaneEventHandler; import lombok.Getter; /** * Implements a radio button, a mutually-exclusive version of a checkbox. To actually work as mutually exclusive, all radio buttons in the * same group need to be added to the same RadioButtonGroup object. A radio button with no group acts as a checkbox with a different * appearance. * * @author Aesen Vismea * */ public class PaneRadioButton extends PaneCheckBox { @Getter protected RadioButtonGroup group = null; public PaneRadioButton() { this("Radio Button"); } public PaneRadioButton(final RadioButtonGroup group) { this("Radio Button", group); } public PaneRadioButton(final String text) { this(text, false); } public PaneRadioButton(final String text, final RadioButtonGroup group) { this(text, false, group); } public PaneRadioButton(final String text, final boolean selected) { this(text, selected, null); } public PaneRadioButton(final String text, final boolean selected, final RadioButtonGroup group) { alignmentX = HorzAlignment.LEFT; this.text = text; this.group = group; this.selected = selected; if (group != null) { group.add(this); } u = 230; } @Override protected void doRender(final int mouseX, final int mouseY, final float partialTicks) { if (group != null) { selected = (group.getSelected() == this); } super.doRender(mouseX, mouseY, partialTicks); } @Override @PaneEventHandler public void onActivateForToggle(final ComponentActivateEvent e) { if (group == null) { super.onActivateForToggle(e); } else { group.select(this); } } }
lgpl-3.0
ravep/ponfig
src/main/java/com/unit16/conf/ComparableFactory.java
726
package com.unit16.conf; /** * * @author Ratko Veprek * * copyright 2013 unit16 atlantic gmbh * */ import com.google.common.collect.Range; import com.unit16.conf.C.Checker; public abstract class ComparableFactory<T extends Comparable<T>> extends CFactory<T> { public ComparableFactory(Group group_, String name_, Parser<T> parser_) { super(group_, name_, parser_); } public ComparableFactory<T> check(final Range<T> r) { super.check(new Checker.I<T>(r.toString()) { @Override public boolean validate(T value, C<T> def) { if(r.contains(value)) { return true; } else { error = "Value " + value + " is not in range " + r; return false; } } }); return this; } }
lgpl-3.0
ziqizhang/jate
src/main/java/uk/ac/shef/dcs/jate/JATERecursiveTaskWorker.java
2022
package uk.ac.shef.dcs.jate; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.RecursiveTask; /** * Created by zqz on 15/09/2015. */ public abstract class JATERecursiveTaskWorker<S, T> extends RecursiveTask<T>{ private static final long serialVersionUID = -5145284438127806541L; protected List<S> tasks; protected int maxTasksPerThread; public JATERecursiveTaskWorker(List<S> tasks, int maxTasksPerWorker){ this.tasks = tasks; this.maxTasksPerThread=maxTasksPerWorker; } protected abstract JATERecursiveTaskWorker<S, T> createInstance(List<S> splitTasks); protected abstract T mergeResult(List<JATERecursiveTaskWorker<S, T>> workers); protected abstract T computeSingleWorker(List<S> tasks); @Override protected T compute() { if (this.tasks.size() > maxTasksPerThread) { List<JATERecursiveTaskWorker<S, T>> subWorkers = new ArrayList<>(); subWorkers.addAll(createSubWorkers()); for (JATERecursiveTaskWorker<S, T> subWorker : subWorkers) subWorker.fork(); return mergeResult(subWorkers); } else{ return computeSingleWorker(tasks); } } protected List<JATERecursiveTaskWorker<S, T>> createSubWorkers() { List<JATERecursiveTaskWorker<S, T>> subWorkers = new ArrayList<>(); int total = tasks.size() / 2; List<S> splitTask1 = new ArrayList<>(); for (int i = 0; i < total; i++) splitTask1.add(tasks.get(i)); JATERecursiveTaskWorker<S, T> subWorker1 = createInstance(splitTask1); List<S> splitTask2 = new ArrayList<>(); for (int i = total; i < tasks.size(); i++) splitTask2.add(tasks.get(i)); JATERecursiveTaskWorker<S, T> subWorker2 = createInstance(splitTask2); subWorkers.add(subWorker1); subWorkers.add(subWorker2); return subWorkers; } }
lgpl-3.0
Deefster10k/The-UnNamed-MagicMod
src/main/java/com/deefster10k/tunmm/client/gui/GuiFactory.java
686
package com.deefster10k.tunmm.client.gui; import cpw.mods.fml.client.IModGuiFactory; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import java.util.Set; public class GuiFactory implements IModGuiFactory{ @Override public void initialize(Minecraft minecraftInstance) { } @Override public Class<? extends GuiScreen> mainConfigGuiClass() { return ModGuiConfig.class; } @Override public Set<RuntimeOptionCategoryElement> runtimeGuiCategories() { return null; } @Override public RuntimeOptionGuiHandler getHandlerFor(RuntimeOptionCategoryElement element) { return null; } }
lgpl-3.0
Agem-Bilisim/arya
arya-metadata-xul/src/main/java/tr/com/agem/arya/metadata/arya/impl/CheckboxType.java
35765
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.08.18 at 08:16:12 PM EEST // package tr.com.agem.arya.metadata.arya.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyAttribute; import javax.xml.bind.annotation.XmlAnyElement; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlElementRefs; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.namespace.QName; import org.w3c.dom.Element; /** * <p>Java class for checkboxType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="checkboxType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;group ref="{aryaportal.org}baseGroup" maxOccurs="unbounded" minOccurs="0"/> * &lt;attGroup ref="{aryaportal.org}rootAttrGroup"/> * &lt;attGroup ref="{aryaportal.org}labelImageElementAttrGroup"/> * &lt;attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="checked" type="{aryaportal.org}booleanType" /> * &lt;attribute name="disabled" type="{aryaportal.org}booleanType" /> * &lt;attribute name="tabindex" type="{aryaportal.org}intType" /> * &lt;attribute name="onCheck" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="value" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "checkboxType", propOrder = { "baseGroup" }) public class CheckboxType { @XmlElementRefs({ @XmlElementRef(name = "arya", namespace = "aryaportal.org", type = JAXBElement.class, required = false), @XmlElementRef(name = "custom-attributes", namespace = "aryaportal.org", type = JAXBElement.class, required = false), @XmlElementRef(name = "attribute", namespace = "aryaportal.org", type = JAXBElement.class, required = false), @XmlElementRef(name = "template", namespace = "aryaportal.org", type = JAXBElement.class, required = false) }) @XmlAnyElement(lax = true) protected List<Object> baseGroup; @XmlAttribute(name = "name") protected String name; @XmlAttribute(name = "checked") protected String checked; @XmlAttribute(name = "disabled") protected String disabled; @XmlAttribute(name = "tabindex") protected String tabindex; @XmlAttribute(name = "onCheck") protected String onCheck; @XmlAttribute(name = "value") protected String value; @XmlAttribute(name = "onBookmarkChange") protected String onBookmarkChange; @XmlAttribute(name = "onClientInfo") protected String onClientInfo; @XmlAttribute(name = "image") protected String image; @XmlAttribute(name = "imageContent") protected String imageContent; @XmlAttribute(name = "hoverImage") protected String hoverImage; @XmlAttribute(name = "hoverImageContent") protected String hoverImageContent; @XmlAttribute(name = "label") protected String label; @XmlAttribute(name = "context") protected String context; @XmlAttribute(name = "tooltip") protected String tooltip; @XmlAttribute(name = "onCtrlKey") protected String onCtrlKey; @XmlAttribute(name = "ctrlKeys") protected String ctrlKeys; @XmlAttribute(name = "width") protected String width; @XmlAttribute(name = "height") protected String height; @XmlAttribute(name = "sclass") protected String sclass; @XmlAttribute(name = "zclass") protected String zclass; @XmlAttribute(name = "style") protected String style; @XmlAttribute(name = "left") protected String left; @XmlAttribute(name = "top") protected String top; @XmlAttribute(name = "draggable") protected String draggable; @XmlAttribute(name = "droppable") protected String droppable; @XmlAttribute(name = "focus") protected String focus; @XmlAttribute(name = "tooltiptext") protected String tooltiptext; @XmlAttribute(name = "zindex") protected String zindex; @XmlAttribute(name = "renderdefer") protected String renderdefer; @XmlAttribute(name = "onCreate") protected String onCreate; @XmlAttribute(name = "onDrop") protected String onDrop; @XmlAttribute(name = "action") protected String action; @XmlAttribute(name = "hflex") protected String hflex; @XmlAttribute(name = "vflex") protected String vflex; @XmlAttribute(name = "apply") protected String apply; @XmlAttribute(name = "auService") protected String auService; @XmlAttribute(name = "autag") protected String autag; @XmlAttribute(name = "binder") protected String binder; @XmlAttribute(name = "children") protected String children; @XmlAttribute(name = "form") protected String form; @XmlAttribute(name = "forward") protected String forward; @XmlAttribute(name = "fulfill") protected String fulfill; @XmlAttribute(name = "id") protected String id; @XmlAttribute(name = "mold") protected String mold; @XmlAttribute(name = "onFulfill") protected String onFulfill; @XmlAttribute(name = "stubonly") protected String stubonly; @XmlAttribute(name = "use") protected String use; @XmlAttribute(name = "viewModel") protected String viewModel; @XmlAttribute(name = "visible") protected String visible; @XmlAttribute(name = "forEach") protected String forEach; @XmlAttribute(name = "forEachBegin") protected String forEachBegin; @XmlAttribute(name = "forEachEnd") protected String forEachEnd; @XmlAttribute(name = "if") protected String _if; @XmlAttribute(name = "self") protected String self; @XmlAttribute(name = "unless") protected String unless; @XmlAttribute(name = "onDoubleClick") @XmlSchemaType(name = "anySimpleType") protected String onDoubleClick; @XmlAttribute(name = "onClick") @XmlSchemaType(name = "anySimpleType") protected String onClick; @XmlAttribute(name = "onRightClick") @XmlSchemaType(name = "anySimpleType") protected String onRightClick; @XmlAnyAttribute private Map<QName, String> otherAttributes = new HashMap<QName, String>(); /** * Gets the value of the baseGroup property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the baseGroup property. * * <p> * For example, to add a new item, do as follows: * <pre> * getBaseGroup().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Element } * {@link Object } * {@link JAXBElement }{@code <}{@link AryaType }{@code >} * {@link JAXBElement }{@code <}{@link AttributeType }{@code >} * {@link JAXBElement }{@code <}{@link TemplateType }{@code >} * {@link JAXBElement }{@code <}{@link CustomAttributesType }{@code >} * * */ public List<Object> getBaseGroup() { if (baseGroup == null) { baseGroup = new ArrayList<Object>(); } return this.baseGroup; } /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Gets the value of the checked property. * * @return * possible object is * {@link String } * */ public String getChecked() { return checked; } /** * Sets the value of the checked property. * * @param value * allowed object is * {@link String } * */ public void setChecked(String value) { this.checked = value; } /** * Gets the value of the disabled property. * * @return * possible object is * {@link String } * */ public String getDisabled() { return disabled; } /** * Sets the value of the disabled property. * * @param value * allowed object is * {@link String } * */ public void setDisabled(String value) { this.disabled = value; } /** * Gets the value of the tabindex property. * * @return * possible object is * {@link String } * */ public String getTabindex() { return tabindex; } /** * Sets the value of the tabindex property. * * @param value * allowed object is * {@link String } * */ public void setTabindex(String value) { this.tabindex = value; } /** * Gets the value of the onCheck property. * * @return * possible object is * {@link String } * */ public String getOnCheck() { return onCheck; } /** * Sets the value of the onCheck property. * * @param value * allowed object is * {@link String } * */ public void setOnCheck(String value) { this.onCheck = value; } /** * Gets the value of the value property. * * @return * possible object is * {@link String } * */ public String getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link String } * */ public void setValue(String value) { this.value = value; } /** * Gets the value of the onBookmarkChange property. * * @return * possible object is * {@link String } * */ public String getOnBookmarkChange() { return onBookmarkChange; } /** * Sets the value of the onBookmarkChange property. * * @param value * allowed object is * {@link String } * */ public void setOnBookmarkChange(String value) { this.onBookmarkChange = value; } /** * Gets the value of the onClientInfo property. * * @return * possible object is * {@link String } * */ public String getOnClientInfo() { return onClientInfo; } /** * Sets the value of the onClientInfo property. * * @param value * allowed object is * {@link String } * */ public void setOnClientInfo(String value) { this.onClientInfo = value; } /** * Gets the value of the image property. * * @return * possible object is * {@link String } * */ public String getImage() { return image; } /** * Sets the value of the image property. * * @param value * allowed object is * {@link String } * */ public void setImage(String value) { this.image = value; } /** * Gets the value of the imageContent property. * * @return * possible object is * {@link String } * */ public String getImageContent() { return imageContent; } /** * Sets the value of the imageContent property. * * @param value * allowed object is * {@link String } * */ public void setImageContent(String value) { this.imageContent = value; } /** * Gets the value of the hoverImage property. * * @return * possible object is * {@link String } * */ public String getHoverImage() { return hoverImage; } /** * Sets the value of the hoverImage property. * * @param value * allowed object is * {@link String } * */ public void setHoverImage(String value) { this.hoverImage = value; } /** * Gets the value of the hoverImageContent property. * * @return * possible object is * {@link String } * */ public String getHoverImageContent() { return hoverImageContent; } /** * Sets the value of the hoverImageContent property. * * @param value * allowed object is * {@link String } * */ public void setHoverImageContent(String value) { this.hoverImageContent = value; } /** * Gets the value of the label property. * * @return * possible object is * {@link String } * */ public String getLabel() { return label; } /** * Sets the value of the label property. * * @param value * allowed object is * {@link String } * */ public void setLabel(String value) { this.label = value; } /** * Gets the value of the context property. * * @return * possible object is * {@link String } * */ public String getContext() { return context; } /** * Sets the value of the context property. * * @param value * allowed object is * {@link String } * */ public void setContext(String value) { this.context = value; } /** * Gets the value of the tooltip property. * * @return * possible object is * {@link String } * */ public String getTooltip() { return tooltip; } /** * Sets the value of the tooltip property. * * @param value * allowed object is * {@link String } * */ public void setTooltip(String value) { this.tooltip = value; } /** * Gets the value of the onCtrlKey property. * * @return * possible object is * {@link String } * */ public String getOnCtrlKey() { return onCtrlKey; } /** * Sets the value of the onCtrlKey property. * * @param value * allowed object is * {@link String } * */ public void setOnCtrlKey(String value) { this.onCtrlKey = value; } /** * Gets the value of the ctrlKeys property. * * @return * possible object is * {@link String } * */ public String getCtrlKeys() { return ctrlKeys; } /** * Sets the value of the ctrlKeys property. * * @param value * allowed object is * {@link String } * */ public void setCtrlKeys(String value) { this.ctrlKeys = value; } /** * Gets the value of the width property. * * @return * possible object is * {@link String } * */ public String getWidth() { return width; } /** * Sets the value of the width property. * * @param value * allowed object is * {@link String } * */ public void setWidth(String value) { this.width = value; } /** * Gets the value of the height property. * * @return * possible object is * {@link String } * */ public String getHeight() { return height; } /** * Sets the value of the height property. * * @param value * allowed object is * {@link String } * */ public void setHeight(String value) { this.height = value; } /** * Gets the value of the sclass property. * * @return * possible object is * {@link String } * */ public String getSclass() { return sclass; } /** * Sets the value of the sclass property. * * @param value * allowed object is * {@link String } * */ public void setSclass(String value) { this.sclass = value; } /** * Gets the value of the zclass property. * * @return * possible object is * {@link String } * */ public String getZclass() { return zclass; } /** * Sets the value of the zclass property. * * @param value * allowed object is * {@link String } * */ public void setZclass(String value) { this.zclass = value; } /** * Gets the value of the style property. * * @return * possible object is * {@link String } * */ public String getStyle() { return style; } /** * Sets the value of the style property. * * @param value * allowed object is * {@link String } * */ public void setStyle(String value) { this.style = value; } /** * Gets the value of the left property. * * @return * possible object is * {@link String } * */ public String getLeft() { return left; } /** * Sets the value of the left property. * * @param value * allowed object is * {@link String } * */ public void setLeft(String value) { this.left = value; } /** * Gets the value of the top property. * * @return * possible object is * {@link String } * */ public String getTop() { return top; } /** * Sets the value of the top property. * * @param value * allowed object is * {@link String } * */ public void setTop(String value) { this.top = value; } /** * Gets the value of the draggable property. * * @return * possible object is * {@link String } * */ public String getDraggable() { return draggable; } /** * Sets the value of the draggable property. * * @param value * allowed object is * {@link String } * */ public void setDraggable(String value) { this.draggable = value; } /** * Gets the value of the droppable property. * * @return * possible object is * {@link String } * */ public String getDroppable() { return droppable; } /** * Sets the value of the droppable property. * * @param value * allowed object is * {@link String } * */ public void setDroppable(String value) { this.droppable = value; } /** * Gets the value of the focus property. * * @return * possible object is * {@link String } * */ public String getFocus() { return focus; } /** * Sets the value of the focus property. * * @param value * allowed object is * {@link String } * */ public void setFocus(String value) { this.focus = value; } /** * Gets the value of the tooltiptext property. * * @return * possible object is * {@link String } * */ public String getTooltiptext() { return tooltiptext; } /** * Sets the value of the tooltiptext property. * * @param value * allowed object is * {@link String } * */ public void setTooltiptext(String value) { this.tooltiptext = value; } /** * Gets the value of the zindex property. * * @return * possible object is * {@link String } * */ public String getZindex() { return zindex; } /** * Sets the value of the zindex property. * * @param value * allowed object is * {@link String } * */ public void setZindex(String value) { this.zindex = value; } /** * Gets the value of the renderdefer property. * * @return * possible object is * {@link String } * */ public String getRenderdefer() { return renderdefer; } /** * Sets the value of the renderdefer property. * * @param value * allowed object is * {@link String } * */ public void setRenderdefer(String value) { this.renderdefer = value; } /** * Gets the value of the onCreate property. * * @return * possible object is * {@link String } * */ public String getOnCreate() { return onCreate; } /** * Sets the value of the onCreate property. * * @param value * allowed object is * {@link String } * */ public void setOnCreate(String value) { this.onCreate = value; } /** * Gets the value of the onDrop property. * * @return * possible object is * {@link String } * */ public String getOnDrop() { return onDrop; } /** * Sets the value of the onDrop property. * * @param value * allowed object is * {@link String } * */ public void setOnDrop(String value) { this.onDrop = value; } /** * Gets the value of the action property. * * @return * possible object is * {@link String } * */ public String getAction() { return action; } /** * Sets the value of the action property. * * @param value * allowed object is * {@link String } * */ public void setAction(String value) { this.action = value; } /** * Gets the value of the hflex property. * * @return * possible object is * {@link String } * */ public String getHflex() { return hflex; } /** * Sets the value of the hflex property. * * @param value * allowed object is * {@link String } * */ public void setHflex(String value) { this.hflex = value; } /** * Gets the value of the vflex property. * * @return * possible object is * {@link String } * */ public String getVflex() { return vflex; } /** * Sets the value of the vflex property. * * @param value * allowed object is * {@link String } * */ public void setVflex(String value) { this.vflex = value; } /** * Gets the value of the apply property. * * @return * possible object is * {@link String } * */ public String getApply() { return apply; } /** * Sets the value of the apply property. * * @param value * allowed object is * {@link String } * */ public void setApply(String value) { this.apply = value; } /** * Gets the value of the auService property. * * @return * possible object is * {@link String } * */ public String getAuService() { return auService; } /** * Sets the value of the auService property. * * @param value * allowed object is * {@link String } * */ public void setAuService(String value) { this.auService = value; } /** * Gets the value of the autag property. * * @return * possible object is * {@link String } * */ public String getAutag() { return autag; } /** * Sets the value of the autag property. * * @param value * allowed object is * {@link String } * */ public void setAutag(String value) { this.autag = value; } /** * Gets the value of the binder property. * * @return * possible object is * {@link String } * */ public String getBinder() { return binder; } /** * Sets the value of the binder property. * * @param value * allowed object is * {@link String } * */ public void setBinder(String value) { this.binder = value; } /** * Gets the value of the children property. * * @return * possible object is * {@link String } * */ public String getChildren() { return children; } /** * Sets the value of the children property. * * @param value * allowed object is * {@link String } * */ public void setChildren(String value) { this.children = value; } /** * Gets the value of the form property. * * @return * possible object is * {@link String } * */ public String getForm() { return form; } /** * Sets the value of the form property. * * @param value * allowed object is * {@link String } * */ public void setForm(String value) { this.form = value; } /** * Gets the value of the forward property. * * @return * possible object is * {@link String } * */ public String getForward() { return forward; } /** * Sets the value of the forward property. * * @param value * allowed object is * {@link String } * */ public void setForward(String value) { this.forward = value; } /** * Gets the value of the fulfill property. * * @return * possible object is * {@link String } * */ public String getFulfill() { return fulfill; } /** * Sets the value of the fulfill property. * * @param value * allowed object is * {@link String } * */ public void setFulfill(String value) { this.fulfill = value; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the mold property. * * @return * possible object is * {@link String } * */ public String getMold() { return mold; } /** * Sets the value of the mold property. * * @param value * allowed object is * {@link String } * */ public void setMold(String value) { this.mold = value; } /** * Gets the value of the onFulfill property. * * @return * possible object is * {@link String } * */ public String getOnFulfill() { return onFulfill; } /** * Sets the value of the onFulfill property. * * @param value * allowed object is * {@link String } * */ public void setOnFulfill(String value) { this.onFulfill = value; } /** * Gets the value of the stubonly property. * * @return * possible object is * {@link String } * */ public String getStubonly() { return stubonly; } /** * Sets the value of the stubonly property. * * @param value * allowed object is * {@link String } * */ public void setStubonly(String value) { this.stubonly = value; } /** * Gets the value of the use property. * * @return * possible object is * {@link String } * */ public String getUse() { return use; } /** * Sets the value of the use property. * * @param value * allowed object is * {@link String } * */ public void setUse(String value) { this.use = value; } /** * Gets the value of the viewModel property. * * @return * possible object is * {@link String } * */ public String getViewModel() { return viewModel; } /** * Sets the value of the viewModel property. * * @param value * allowed object is * {@link String } * */ public void setViewModel(String value) { this.viewModel = value; } /** * Gets the value of the visible property. * * @return * possible object is * {@link String } * */ public String getVisible() { return visible; } /** * Sets the value of the visible property. * * @param value * allowed object is * {@link String } * */ public void setVisible(String value) { this.visible = value; } /** * Gets the value of the forEach property. * * @return * possible object is * {@link String } * */ public String getForEach() { return forEach; } /** * Sets the value of the forEach property. * * @param value * allowed object is * {@link String } * */ public void setForEach(String value) { this.forEach = value; } /** * Gets the value of the forEachBegin property. * * @return * possible object is * {@link String } * */ public String getForEachBegin() { return forEachBegin; } /** * Sets the value of the forEachBegin property. * * @param value * allowed object is * {@link String } * */ public void setForEachBegin(String value) { this.forEachBegin = value; } /** * Gets the value of the forEachEnd property. * * @return * possible object is * {@link String } * */ public String getForEachEnd() { return forEachEnd; } /** * Sets the value of the forEachEnd property. * * @param value * allowed object is * {@link String } * */ public void setForEachEnd(String value) { this.forEachEnd = value; } /** * Gets the value of the if property. * * @return * possible object is * {@link String } * */ public String getIf() { return _if; } /** * Sets the value of the if property. * * @param value * allowed object is * {@link String } * */ public void setIf(String value) { this._if = value; } /** * Gets the value of the self property. * * @return * possible object is * {@link String } * */ public String getSelf() { return self; } /** * Sets the value of the self property. * * @param value * allowed object is * {@link String } * */ public void setSelf(String value) { this.self = value; } /** * Gets the value of the unless property. * * @return * possible object is * {@link String } * */ public String getUnless() { return unless; } /** * Sets the value of the unless property. * * @param value * allowed object is * {@link String } * */ public void setUnless(String value) { this.unless = value; } /** * Gets the value of the onDoubleClick property. * * @return * possible object is * {@link String } * */ public String getOnDoubleClick() { return onDoubleClick; } /** * Sets the value of the onDoubleClick property. * * @param value * allowed object is * {@link String } * */ public void setOnDoubleClick(String value) { this.onDoubleClick = value; } /** * Gets the value of the onClick property. * * @return * possible object is * {@link String } * */ public String getOnClick() { return onClick; } /** * Sets the value of the onClick property. * * @param value * allowed object is * {@link String } * */ public void setOnClick(String value) { this.onClick = value; } /** * Gets the value of the onRightClick property. * * @return * possible object is * {@link String } * */ public String getOnRightClick() { return onRightClick; } /** * Sets the value of the onRightClick property. * * @param value * allowed object is * {@link String } * */ public void setOnRightClick(String value) { this.onRightClick = value; } /** * Gets a map that contains attributes that aren't bound to any typed property on this class. * * <p> * the map is keyed by the name of the attribute and * the value is the string value of the attribute. * * the map returned by this method is live, and you can add new attribute * by updating the map directly. Because of this design, there's no setter. * * * @return * always non-null */ public Map<QName, String> getOtherAttributes() { return otherAttributes; } }
lgpl-3.0
dieudonne-willems/om-java-libs
OM-java-core/src/main/java/nl/wur/fbr/om/core/impl/points/PointImpl.java
5983
package nl.wur.fbr.om.core.impl.points; import nl.wur.fbr.om.core.impl.measures.MeasureImpl; import nl.wur.fbr.om.model.measures.Measure; import nl.wur.fbr.om.model.points.Point; import nl.wur.fbr.om.model.scales.Scale; import nl.wur.fbr.om.model.units.Unit; import org.apache.commons.lang3.Range; /** * This class implements the {@link Point Point} interface that represents a point (value and scale) on a measurement scale. * The unit in which the value is expressed in defined in the measurement scale. * * These points can be used to define a measurement scale as in the Celsius scale, which is defined by * <code>Point</code>s such as the boiling point of water, or they can be used to specify measurements on a scale, * for instance the temperature in degree celsius. For measurements like temperature, a <code>Point</code> needs * to be used, e.g. the temperature is 10 degrees Celsius, while temperature differences need to be expressed as * {@link Measure Measure}s as these values are relative. * * * @author Don Willems on 20/07/15. */ public class PointImpl implements Point{ /** The scale in which this point is defined. */ private Scale scale; /** The numerical value of this point on the scale. */ private Object numericalValue; /** * Creates a new {@link Point} with the specified scalar value on the specified measurement scale. * * @param numericalValue The scalar value. * @param scale The scale. */ public PointImpl(double numericalValue,Scale scale){ this.scale = scale; this.numericalValue = numericalValue; } /** * Creates a new {@link Point} with the specified vector value on the specified measurement scale. * * @param numericalValue The vector value. * @param scale The scale. */ public PointImpl(double[] numericalValue, Scale scale){ this.scale = scale; if(numericalValue.length==1) this.numericalValue = numericalValue[0]; else this.numericalValue = numericalValue; } /** * Creates a new {@link Point} with the specified scalar range value on the specified measurement scale. * * @param numericalValue The scalar range value. * @param scale The scale. */ public PointImpl(Range numericalValue, Scale scale){ this.scale = scale; this.numericalValue = numericalValue; } /** * The scale in which this point is defined. * * @return The measurement scale in which the point is defined. */ @Override public Scale getScale() { return scale; } /** * The numerical value of the point. * The return type is an Object but can be of type Number, or (in the future) of Vector or Tensor types. * * @return The numerical value. */ @Override public Object getNumericalValue() { return numericalValue; } /** * Returns the difference of the point with the zero point on the scale. * * @return The difference from zero point. */ @Override public Measure getDifferenceFromZero() { if(numericalValue instanceof Number) return new MeasureImpl((double)this.getNumericalValue(),this.getScale().getUnit()); if(numericalValue instanceof double[]) return new MeasureImpl((double[])this.getNumericalValue(),this.getScale().getUnit()); if(numericalValue instanceof Range) return new MeasureImpl((Range)this.getNumericalValue(),this.getScale().getUnit()); throw new NumberFormatException("THe difference to the zero point could not be determined as the numerical value" + "is not of a known numerical value type."); } /** * Returns the numerical value (as a scalar) of this point. * * @return The double value. */ @Override public double getScalarValue() { if(!(numericalValue instanceof Number)) throw new NumberFormatException("The numerical value of "+this+" is not a scalar."); return (double) numericalValue; } /** * Returns the numerical value (as a scalar range) of this point. * * @return The range value. */ @Override public Range getScalarRange() { if(!(numericalValue instanceof Range)) throw new NumberFormatException("The numerical value of "+this+" is not a scalar range."); return (Range)numericalValue; } /** * Returns the numerical value (as a vector of doubles) of this point. * * @return The vector value. */ @Override public double[] getVectorValue() { if(numericalValue instanceof Number){ double[] vec = {(double) numericalValue}; return vec; } if(!(numericalValue instanceof double[])) throw new NumberFormatException("The numerical value of "+this+" is not a vector."); return (double[]) numericalValue; } /** * A string representation of this point, the string representation of the numerical value followed by the * symbol of the unit defined in the scale if not null. For instance, a point with value 15 in the kelvin scale, * will be represented as 15 K. * @return The */ @Override public String toString(){ String str = ""; if(this.getNumericalValue() instanceof Number){ str += ""+this.getScalarValue(); }else if(this.getNumericalValue() instanceof double[]){ double[] vec = this.getVectorValue(); str += "["; for(int i=0;i<vec.length;i++){ if(i>0) str+=","; str+=""+vec[i]; } str+="]"; }else{ str+= ""+numericalValue; } if(this.getScale().getUnit()!=null && this.getScale().getUnit().getSymbol()!=null){ str+= " " + this.getScale().getUnit().getSymbol(); } str+= " (scale)"; return str; } }
lgpl-3.0
porcelli/OpenSpotLight
osl-federation/osl-federation-core/src/main/java/org/openspotlight/federation/util/GroupDifferences.java
4127
/** * OpenSpotLight - Open Source IT Governance Platform * * Copyright (c) 2009, CARAVELATECH CONSULTORIA E TECNOLOGIA EM INFORMATICA LTDA * or third-party contributors as indicated by the @author tags or express * copyright attribution statements applied by the authors. All third-party * contributions are distributed under license by CARAVELATECH CONSULTORIA E * TECNOLOGIA EM INFORMATICA LTDA. * * 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 * *********************************************************************** * OpenSpotLight - Plataforma de Governança de TI de Código Aberto * * Direitos Autorais Reservados (c) 2009, CARAVELATECH CONSULTORIA E TECNOLOGIA * EM INFORMATICA LTDA ou como contribuidores terceiros indicados pela etiqueta * @author ou por expressa atribuição de direito autoral declarada e atribuída pelo autor. * Todas as contribuições de terceiros estão distribuídas sob licença da * CARAVELATECH CONSULTORIA E TECNOLOGIA EM INFORMATICA LTDA. * * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo sob os * termos da Licença Pública Geral Menor do GNU conforme publicada pela Free Software * Foundation. * * Este programa é distribuído na expectativa de que seja útil, porém, SEM NENHUMA * GARANTIA; nem mesmo a garantia implícita de COMERCIABILIDADE OU ADEQUAÇÃO A UMA * FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral Menor do GNU para mais detalhes. * * Você deve ter recebido uma cópia da Licença Pública Geral Menor do GNU junto com este * programa; se não, escreva para: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.openspotlight.federation.util; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import org.openspotlight.common.util.Arrays; import org.openspotlight.common.util.Equals; import org.openspotlight.common.util.HashCodes; import org.openspotlight.persist.annotation.KeyProperty; import org.openspotlight.persist.annotation.SimpleNodeType; public class GroupDifferences implements SimpleNodeType, Serializable { /** * */ private static final long serialVersionUID = 6595595697385787637L; private Set<String> addedGroups = new HashSet<String>(); private Set<String> removedGroups = new HashSet<String>(); private String repositoryName; @Override public boolean equals(final Object obj) { if (!(obj instanceof GroupDifferences)) { return false; } final GroupDifferences that = (GroupDifferences) obj; return Equals.eachEquality(Arrays.of(getRepositoryName()), Arrays.andOf(that.getRepositoryName())); } public Set<String> getAddedGroups() { return addedGroups; } public Set<String> getRemovedGroups() { return removedGroups; } @KeyProperty public String getRepositoryName() { return repositoryName; } @Override public int hashCode() { return HashCodes.hashOf(getClass(), repositoryName); } public void setAddedGroups(final Set<String> addedGroups) { this.addedGroups = addedGroups; } public void setRemovedGroups(final Set<String> removedGroups) { this.removedGroups = removedGroups; } public void setRepositoryName(final String repositoryName) { this.repositoryName = repositoryName; } }
lgpl-3.0
augusting52/Android-Apps
Demo/app/src/main/java/com/libing/demo/BaseActivity.java
577
package com.libing.demo; import android.os.Bundle; import android.support.v4.app.FragmentActivity; /** * Copyright(c) 2016. LiBing Inc. All rights reserved. * <p/> * Created by Alan on 16/9/17. */ public class BaseActivity extends FragmentActivity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setActivityContent(); initView(); } protected void setActivityContent() { // TODO to Override } protected void initView() { // TODO to Override } }
lgpl-3.0
abdollahpour/xweb-wiki
src/main/java/info/bliki/api/Revision.java
1095
package info.bliki.api; /** * Manages revision data from the <a href="http://meta.wikimedia.org/w/api.php">Wikimedia API</a> */ public class Revision { String user; String timestamp; String anon; String content; public Revision() { this.user = ""; this.timestamp = ""; this.anon = ""; this.content = ""; } @Override public boolean equals(Object obj) { if (obj instanceof Revision) { return content.equals(((Revision) obj).content); } return false; } @Override public int hashCode() { return content.hashCode(); } public String getAnon() { return anon; } public void setAnon(String anon) { this.anon = anon; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } }
lgpl-3.0
abelsromero/walkmod-core
src/main/java/org/walkmod/conf/entities/impl/WalkerConfigImpl.java
2663
/* Copyright (C) 2013 Raquel Pau and Albert Coroleu. Walkmod 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. Walkmod 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 Walkmod. If not, see <http://www.gnu.org/licenses/>.*/ package org.walkmod.conf.entities.impl; import java.util.List; import java.util.Map; import org.walkmod.ChainWalker; import org.walkmod.conf.entities.ChainConfig; import org.walkmod.conf.entities.ParserConfig; import org.walkmod.conf.entities.TransformationConfig; import org.walkmod.conf.entities.WalkerConfig; public class WalkerConfigImpl implements WalkerConfig { private String type; private List<TransformationConfig> transformations; private Map<String, Object> params; private String rootNamespace; private ChainConfig architectureConfig; private ChainWalker walker; private ParserConfig parserConfig; @Override public String getType() { return type; } @Override public void setType(String type) { this.type = type; } @Override public List<TransformationConfig> getTransformations() { return transformations; } @Override public void setTransformations(List<TransformationConfig> transformations) { this.transformations = transformations; } @Override public Map<String, Object> getParams() { return params; } @Override public void setParams(Map<String, Object> params) { this.params = params; } @Override public String getRootNamespace() { return rootNamespace; } @Override public void setRootNamespace(String rootNamespace) { this.rootNamespace = rootNamespace; } @Override public void setChainConfig(ChainConfig architectureConfig) { this.architectureConfig = architectureConfig; } @Override public ChainConfig getChainConfig() { return architectureConfig; } public ChainWalker getWalker() { return walker; } public void setWalker(ChainWalker walker) { this.walker = walker; } @Override public void setParserConfig(ParserConfig parserConfig) { this.parserConfig = parserConfig; } @Override public ParserConfig getParserConfig() { return parserConfig; } }
lgpl-3.0
antonzherdev/objd
ObjDLib/Java/ObjDLib/gen/objd/collection/MSeq_impl.java
1911
package objd.collection; import objd.lang.*; public abstract class MSeq_impl<T> extends Seq_impl<T> implements MSeq<T> { public MSeq_impl() { } @Override public ImSeq<T> im() { return this.imCopy(); } @Override public ImSeq<T> imCopy() { final MArray<T> arr = new MArray<T>(); { final Iterator<T> __il__1i = this.iterator(); while(__il__1i.hasNext()) { final T item = __il__1i.next(); arr.appendItem(item); } } return arr.im(); } public boolean removeIndex(final int index) { final MIterator<T> i = this.mutableIterator(); int j = index; boolean ret = false; while(i.hasNext()) { i.next(); if(j == 0) { i.remove(); ret = true; break; } j--; } return ret; } public void setIndexItem(final int index, final T item) { final MIterator<T> i = this.mutableIterator(); int n = index; while(i.hasNext()) { if(n == 0) { i.next(); i.setValue(item); return ; } i.next(); n--; } throw new RuntimeException("Incorrect index"); } @Override public boolean removeItem(final T item) { final MIterator<T> i = this.mutableIterator(); boolean ret = false; while(i.hasNext()) { if(i.next().equals(item)) { i.remove(); ret = true; } } return ret; } public void mutableFilterBy(final F<T, Boolean> by) { final MIterator<T> i = this.mutableIterator(); while(i.hasNext()) { if(by.apply(i.next())) { i.remove(); } } } }
lgpl-3.0
cismet/belis-server
src/main/java/de/cismet/belis2/server/search/NextArbeitsauftragNummerSearch.java
3378
/*************************************************** * * cismet GmbH, Saarbruecken, Germany * * ... and it just works. * ****************************************************/ package de.cismet.belis2.server.search; import Sirius.server.middleware.interfaces.domainserver.MetaService; import lombok.Getter; import org.apache.log4j.Logger; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import de.cismet.belis.commons.constants.BelisMetaClassConstants; import de.cismet.cids.server.search.AbstractCidsServerSearch; import de.cismet.cidsx.base.types.Type; import de.cismet.cidsx.server.api.types.SearchInfo; import de.cismet.cidsx.server.api.types.SearchParameterInfo; import de.cismet.cidsx.server.search.RestApiCidsServerSearch; /** * DOCUMENT ME! * * @version $Revision$, $Date$ */ @org.openide.util.lookup.ServiceProvider(service = RestApiCidsServerSearch.class) public class NextArbeitsauftragNummerSearch extends AbstractCidsServerSearch implements RestApiCidsServerSearch { //~ Static fields/initializers --------------------------------------------- private static final transient Logger LOG = Logger.getLogger(NextArbeitsauftragNummerSearch.class); private static final DecimalFormat DF = new DecimalFormat("00000000"); //~ Instance fields -------------------------------------------------------- @Getter private final SearchInfo searchInfo; //~ Constructors ----------------------------------------------------------- /** * Creates a new NextVeranlassungNummerSearch object. */ public NextArbeitsauftragNummerSearch() { searchInfo = new SearchInfo(); searchInfo.setKey(this.getClass().getName()); searchInfo.setName(this.getClass().getSimpleName()); searchInfo.setDescription("Search for next Arbeitsauftragsnummer"); final List<SearchParameterInfo> parameterDescription = new LinkedList<SearchParameterInfo>(); searchInfo.setParameterDescription(parameterDescription); final SearchParameterInfo resultParameterInfo = new SearchParameterInfo(); resultParameterInfo.setKey("return"); resultParameterInfo.setArray(true); resultParameterInfo.setType(Type.LONG); searchInfo.setResultDescription(resultParameterInfo); } //~ Methods ---------------------------------------------------------------- /** * DOCUMENT ME! * * @param searchResult DOCUMENT ME! * * @return DOCUMENT ME! */ public static String getStringRepresentation(final List<Long> searchResult) { final Long number = (searchResult.isEmpty()) ? null : searchResult.get(0); return DF.format(number); } @Override public Collection performServerSearch() { final List<Long> numbers = new ArrayList<Long>(); final String query = "SELECT nextval('arbeitsauftragnummer_seq');"; final MetaService metaService = (MetaService)getActiveLocalServers().get(BelisMetaClassConstants.DOMAIN); try { for (final ArrayList fields : metaService.performCustomSearch(query)) { numbers.add((Long)fields.get(0)); } } catch (Exception ex) { LOG.error("", ex); } return numbers; } }
lgpl-3.0
WELTEN/dojo-ibl
src/main/java/org/celstec/arlearn2/gwtcommonlib/client/network/JsonCallbackGeneralItem.java
1440
package org.celstec.arlearn2.gwtcommonlib.client.network; import com.google.gwt.json.client.JSONValue; import org.celstec.arlearn2.gwtcommonlib.client.objects.GeneralItem; /** * **************************************************************************** * Copyright (C) 2013 Open Universiteit Nederland * <p/> * 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 3 of the License, or * (at your option) any later version. * <p/> * 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. * <p/> * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see <http://www.gnu.org/licenses/>. * <p/> * Contributors: Stefaan Ternier * **************************************************************************** */ public class JsonCallbackGeneralItem extends JsonCallback { public void onJsonReceived(JSONValue jsonValue) { if (jsonValue.isObject()!=null) { onGeneralItemReceived(GeneralItem.createObject(jsonValue.isObject())); } } public void onGeneralItemReceived(GeneralItem gi) { } }
lgpl-3.0
EMResearch/EvoMaster
e2e-tests/spring-rpc/spring-rpc-thrift/src/main/java/com/foo/rpc/examples/spring/thrifttest/ListBonks.java
13720
/** * Autogenerated by Thrift Compiler (0.15.0) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package com.foo.rpc.examples.spring.thrifttest; @SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"}) @javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.15.0)", date = "2021-12-08") public class ListBonks implements org.apache.thrift.TBase<ListBonks, ListBonks._Fields>, java.io.Serializable, Cloneable, Comparable<ListBonks> { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("ListBonks"); private static final org.apache.thrift.protocol.TField BONK_FIELD_DESC = new org.apache.thrift.protocol.TField("bonk", org.apache.thrift.protocol.TType.LIST, (short)1); private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new ListBonksStandardSchemeFactory(); private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new ListBonksTupleSchemeFactory(); public @org.apache.thrift.annotation.Nullable java.util.List<Bonk> bonk; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { BONK((short)1, "bonk"); private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>(); static { for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ @org.apache.thrift.annotation.Nullable public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // BONK return BONK; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ @org.apache.thrift.annotation.Nullable public static _Fields findByName(java.lang.String name) { return byName.get(name); } private final short _thriftId; private final java.lang.String _fieldName; _Fields(short thriftId, java.lang.String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public java.lang.String getFieldName() { return _fieldName; } } // isset id assignments public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.BONK, new org.apache.thrift.meta_data.FieldMetaData("bonk", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, Bonk.class)))); metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(ListBonks.class, metaDataMap); } public ListBonks() { } public ListBonks( java.util.List<Bonk> bonk) { this(); this.bonk = bonk; } /** * Performs a deep copy on <i>other</i>. */ public ListBonks(ListBonks other) { if (other.isSetBonk()) { java.util.List<Bonk> __this__bonk = new java.util.ArrayList<Bonk>(other.bonk.size()); for (Bonk other_element : other.bonk) { __this__bonk.add(new Bonk(other_element)); } this.bonk = __this__bonk; } } public ListBonks deepCopy() { return new ListBonks(this); } @Override public void clear() { this.bonk = null; } public int getBonkSize() { return (this.bonk == null) ? 0 : this.bonk.size(); } @org.apache.thrift.annotation.Nullable public java.util.Iterator<Bonk> getBonkIterator() { return (this.bonk == null) ? null : this.bonk.iterator(); } public void addToBonk(Bonk elem) { if (this.bonk == null) { this.bonk = new java.util.ArrayList<Bonk>(); } this.bonk.add(elem); } @org.apache.thrift.annotation.Nullable public java.util.List<Bonk> getBonk() { return this.bonk; } public ListBonks setBonk(@org.apache.thrift.annotation.Nullable java.util.List<Bonk> bonk) { this.bonk = bonk; return this; } public void unsetBonk() { this.bonk = null; } /** Returns true if field bonk is set (has been assigned a value) and false otherwise */ public boolean isSetBonk() { return this.bonk != null; } public void setBonkIsSet(boolean value) { if (!value) { this.bonk = null; } } public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable java.lang.Object value) { switch (field) { case BONK: if (value == null) { unsetBonk(); } else { setBonk((java.util.List<Bonk>)value); } break; } } @org.apache.thrift.annotation.Nullable public java.lang.Object getFieldValue(_Fields field) { switch (field) { case BONK: return getBonk(); } throw new java.lang.IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new java.lang.IllegalArgumentException(); } switch (field) { case BONK: return isSetBonk(); } throw new java.lang.IllegalStateException(); } @Override public boolean equals(java.lang.Object that) { if (that instanceof ListBonks) return this.equals((ListBonks)that); return false; } public boolean equals(ListBonks that) { if (that == null) return false; if (this == that) return true; boolean this_present_bonk = true && this.isSetBonk(); boolean that_present_bonk = true && that.isSetBonk(); if (this_present_bonk || that_present_bonk) { if (!(this_present_bonk && that_present_bonk)) return false; if (!this.bonk.equals(that.bonk)) return false; } return true; } @Override public int hashCode() { int hashCode = 1; hashCode = hashCode * 8191 + ((isSetBonk()) ? 131071 : 524287); if (isSetBonk()) hashCode = hashCode * 8191 + bonk.hashCode(); return hashCode; } @Override public int compareTo(ListBonks other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = java.lang.Boolean.compare(isSetBonk(), other.isSetBonk()); if (lastComparison != 0) { return lastComparison; } if (isSetBonk()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.bonk, other.bonk); if (lastComparison != 0) { return lastComparison; } } return 0; } @org.apache.thrift.annotation.Nullable public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { scheme(iprot).read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { scheme(oprot).write(oprot, this); } @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("ListBonks("); boolean first = true; sb.append("bonk:"); if (this.bonk == null) { sb.append("null"); } else { sb.append(this.bonk); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class ListBonksStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { public ListBonksStandardScheme getScheme() { return new ListBonksStandardScheme(); } } private static class ListBonksStandardScheme extends org.apache.thrift.scheme.StandardScheme<ListBonks> { public void read(org.apache.thrift.protocol.TProtocol iprot, ListBonks struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // BONK if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list266 = iprot.readListBegin(); struct.bonk = new java.util.ArrayList<Bonk>(_list266.size); @org.apache.thrift.annotation.Nullable Bonk _elem267; for (int _i268 = 0; _i268 < _list266.size; ++_i268) { _elem267 = new Bonk(); _elem267.read(iprot); struct.bonk.add(_elem267); } iprot.readListEnd(); } struct.setBonkIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, ListBonks struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.bonk != null) { oprot.writeFieldBegin(BONK_FIELD_DESC); { oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.bonk.size())); for (Bonk _iter269 : struct.bonk) { _iter269.write(oprot); } oprot.writeListEnd(); } oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class ListBonksTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { public ListBonksTupleScheme getScheme() { return new ListBonksTupleScheme(); } } private static class ListBonksTupleScheme extends org.apache.thrift.scheme.TupleScheme<ListBonks> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, ListBonks struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; java.util.BitSet optionals = new java.util.BitSet(); if (struct.isSetBonk()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetBonk()) { { oprot.writeI32(struct.bonk.size()); for (Bonk _iter270 : struct.bonk) { _iter270.write(oprot); } } } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, ListBonks struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; java.util.BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { { org.apache.thrift.protocol.TList _list271 = iprot.readListBegin(org.apache.thrift.protocol.TType.STRUCT); struct.bonk = new java.util.ArrayList<Bonk>(_list271.size); @org.apache.thrift.annotation.Nullable Bonk _elem272; for (int _i273 = 0; _i273 < _list271.size; ++_i273) { _elem272 = new Bonk(); _elem272.read(iprot); struct.bonk.add(_elem272); } } struct.setBonkIsSet(true); } } } private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) { return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); } }
lgpl-3.0
korvus81/ari4java
classes/ch/loway/oss/ari4java/generated/ari_1_6_0/models/LiveRecording_impl_ari_1_6_0.java
2936
package ch.loway.oss.ari4java.generated.ari_1_6_0.models; // ---------------------------------------------------- // THIS CLASS WAS GENERATED AUTOMATICALLY // PLEASE DO NOT EDIT // Generated on: Sat Sep 19 08:50:54 CEST 2015 // ---------------------------------------------------- import ch.loway.oss.ari4java.generated.*; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import java.util.Date; import java.util.List; import java.util.Map; /********************************************************** * A recording that is in progress * * Defined in file: recordings.json * Generated by: Model *********************************************************/ public class LiveRecording_impl_ari_1_6_0 implements LiveRecording, java.io.Serializable { private static final long serialVersionUID = 1L; /** Cause for recording failure if failed */ private String cause; public String getCause() { return cause; } @JsonDeserialize( as=String.class ) public void setCause(String val ) { cause = val; } /** Duration in seconds of the recording */ private int duration; public int getDuration() { return duration; } @JsonDeserialize( as=int.class ) public void setDuration(int val ) { duration = val; } /** Recording format (wav, gsm, etc.) */ private String format; public String getFormat() { return format; } @JsonDeserialize( as=String.class ) public void setFormat(String val ) { format = val; } /** Base name for the recording */ private String name; public String getName() { return name; } @JsonDeserialize( as=String.class ) public void setName(String val ) { name = val; } /** Duration of silence, in seconds, detected in the recording. This is only available if the recording was initiated with a non-zero maxSilenceSeconds. */ private int silence_duration; public int getSilence_duration() { return silence_duration; } @JsonDeserialize( as=int.class ) public void setSilence_duration(int val ) { silence_duration = val; } /** */ private String state; public String getState() { return state; } @JsonDeserialize( as=String.class ) public void setState(String val ) { state = val; } /** Duration of talking, in seconds, detected in the recording. This is only available if the recording was initiated with a non-zero maxSilenceSeconds. */ private int talking_duration; public int getTalking_duration() { return talking_duration; } @JsonDeserialize( as=int.class ) public void setTalking_duration(int val ) { talking_duration = val; } /** URI for the channel or bridge being recorded */ private String target_uri; public String getTarget_uri() { return target_uri; } @JsonDeserialize( as=String.class ) public void setTarget_uri(String val ) { target_uri = val; } /** No missing signatures from interface */ }
lgpl-3.0
loftuxab/community-edition-old
projects/slingshot/source/java/org/alfresco/web/resolver/doclib/DefaultDoclistDataUrlResolver.java
3017
/* * Copyright (C) 2005-2011 Alfresco Software Limited. * * This file is part of Alfresco * * Alfresco 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. * * Alfresco 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 Alfresco. If not, see <http://www.gnu.org/licenses/>. */ package org.alfresco.web.resolver.doclib; import java.util.HashMap; import java.util.Map; import org.springframework.extensions.surf.util.URLEncoder; /** * Resolves which data url if to use when asking the repository for nodes in the document library's document list. * * @author ewinlof */ public class DefaultDoclistDataUrlResolver implements DoclistDataUrlResolver { /** * The base path to the repository doclist webscript. */ public String basePath = null; /** * The base path to the repository doclist webscript. * * @param basePath */ public void setBasePath(String basePath) { this.basePath = basePath; } /** * Returns the url to the repository doclist webscript to use. * * @param webscript The repository doclib2 webscript tp use, i.e. doclist or node * @param params doclib2 webscript specific parameters * @param args url parameters, i.e. pagination parameters * @return The url to use when asking the repository doclist webscript. */ public String resolve(String webscript, String params, HashMap<String, String> args) { return basePath + "/" + webscript + "/" + URLEncoder.encodeUri(params) + getArgsAsParameters(args); } /** * Helper method that creates a url parameter string from a hash map. * * @param args The arguments that will be transformed to a string * @return A url parameter string */ public String getArgsAsParameters(HashMap<String, String> args) { String urlParameters = ""; // Need to reconstruct and encode original args if (args.size() > 0) { StringBuilder argsBuf = new StringBuilder(128); argsBuf.append('?'); for (Map.Entry<String, String> arg: args.entrySet()) { if (argsBuf.length() > 1) { argsBuf.append('&'); } argsBuf.append(arg.getKey()) .append('=') .append(URLEncoder.encodeUriComponent(arg.getValue().replaceAll("%25","%2525"))); } urlParameters = argsBuf.toString(); } return urlParameters; } }
lgpl-3.0
sandrosalvato94/System-Design-Project
src/polito/sdp2017/VhdlInterface/VhdlPinDirection.java
2526
package polito.sdp2017.VhdlInterface; import java.util.Collections; import java.util.Map; import java.util.TreeMap; /** * The VhdlPinDirection is an enumerative type, containing the four kind of * pin directions supported by VHDL. These directions are: * - IN : Representing an input which the module can read * - OUT : Representing a port on which the module can write * - INOUT : Representing a port on which the module can both read and write * - BUFFER : Representing a signal inside the module, which can be used both * as output and for feeding a circuit inside the module */ public enum VhdlPinDirection { IN, // equivalent to "in" port OUT, // equivalent to "out" port INOUT, // equivalent to "inout" port BUFFER; // equivalent to "buffer" port /** * matchMap is used for checking if a pin direction read from a VHDL source code is a valid * keyword for VHDL. Unless changing in the VHDL specifications, this map is supposed * to be unmodifiable. */ private static final Map<String,VhdlPinDirection> matchMap; static { Map<String,VhdlPinDirection> aMap = new TreeMap<String,VhdlPinDirection>(); aMap.put("in", IN); aMap.put("out", OUT); aMap.put("inout", INOUT); aMap.put("buffer", BUFFER); matchMap = Collections.unmodifiableMap(aMap); } /** * Transform a string parsed from a VHDL source file in its correspondent code * expressed a VhdlPinDirection. This is accomplished by looking for the sType * parameter in the matchMap. * @param sType : a String, supposed to be the key for a valid pin type in the matchMap * @return a VhdlPinDirection code */ public static VhdlPinDirection vhdlPinDirectionFromString (String sType) { String type = sType.toLowerCase(); // Takes into account that the VHDL is case insensitive if (matchMap.containsKey(type)) { // Check if the String represent a valid PinDirection for VHDL return matchMap.get(type); // Returns the proper identifier is returned } throw new RuntimeException("Unknown Vhdl type : "+sType); // If the String is not recognised a // RuntimeException is raised } /** * @return a valid VHDL String representing the PinDirection */ @Override public String toString() { switch(this) { case IN: return "in"; case OUT: return "out"; case INOUT: return "inout"; case BUFFER: return "buffer"; default: throw new IllegalArgumentException("Non valid Vhdl pin direction"); } } }
lgpl-3.0
hea3ven/BuildCraft
common/buildcraft/core/render/BlockHighlightHandler.java
2055
/** * Copyright (c) 2011-2015, SpaceToad and the BuildCraft Team * http://www.mod-buildcraft.com * * BuildCraft is distributed under the terms of the Minecraft Mod Public * License 1.0, or MMPL. Please check the contents of the license located in * http://www.mod-buildcraft.com/MMPL-1.0.txt */ package buildcraft.core.render; import org.lwjgl.opengl.GL11; import net.minecraft.block.Block; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.RenderGlobal; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraftforge.client.event.DrawBlockHighlightEvent; import buildcraft.core.lib.render.ICustomHighlight; public class BlockHighlightHandler { @SideOnly(Side.CLIENT) @SubscribeEvent public void handleBlockHighlight(DrawBlockHighlightEvent e) { if (e.target.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { int x = e.target.blockX; int y = e.target.blockY; int z = e.target.blockZ; Block block = e.player.worldObj.getBlock(x, y, z); if (block instanceof ICustomHighlight) { AxisAlignedBB[] aabbs = ((ICustomHighlight) block).getBoxes(e.player.worldObj, x, y, z, e.player); Vec3 pos = e.player.getPosition(e.partialTicks); GL11.glEnable(GL11.GL_BLEND); OpenGlHelper.glBlendFunc(770, 771, 1, 0); GL11.glColor4f(0.0F, 0.0F, 0.0F, 0.4F); GL11.glLineWidth(2.0F); GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glDepthMask(false); double exp = ((ICustomHighlight) block).getExpansion(); for (AxisAlignedBB aabb : aabbs) { RenderGlobal.drawOutlinedBoundingBox(aabb.copy().expand(exp, exp, exp) .offset(x, y, z) .offset(-pos.xCoord, -pos.yCoord, -pos.zCoord), -1); } GL11.glDepthMask(true); GL11.glEnable(GL11.GL_TEXTURE_2D); GL11.glDisable(GL11.GL_BLEND); e.setCanceled(true); } } } }
lgpl-3.0
exo-addons/social-rdbms
lib/src/main/java/org/exoplatform/social/addons/updater/utils/MigrationCounter.java
2802
/* * Copyright (C) 2003-2015 eXo Platform SAS. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.exoplatform.social.addons.updater.utils; /** * Created by The eXo Platform SAS * Author : eXoPlatform * exo@exoplatform.com * Jun 29, 2015 */ public class MigrationCounter { private int batch = 0; private long batchWatch = 0; private int total = 0; private long totalWatch = 0; private int threshold = 0; public static MigrationCounterBuilder builder() { return new MigrationCounterBuilder(); } public int getAndIncrementTotal() { this.total++; return total; } public int getAndIncrementBatch() { this.batch++; return this.batch; } public void newBatchAndWatch() { this.batch = 0; this.batchWatch = System.currentTimeMillis(); } public long endBatchWatch() { return System.currentTimeMillis() - this.batchWatch; } public int getBatch() { return this.batch; } public void newTotal() { this.total = 0; } public void newTotalAndWatch() { this.total = 0; this.totalWatch = System.currentTimeMillis(); } public long endTotalWatch() { return System.currentTimeMillis() - this.totalWatch; } public int getTotal() { return this.total; } public void newBatch() { this.batch = 0; } public boolean isPersistPoint() { return (total % threshold == 0); } public void resetBatch() { this.batch = 0; } public void reset() { this.batch = 0; this.total = 0; this.batchWatch = 0; this.totalWatch = 0; } public static class MigrationCounterBuilder { private int batch = 0; private int threshold = 0; public MigrationCounterBuilder startAtBatch(int fromBatch) { batch += fromBatch; return this; } public MigrationCounterBuilder threshold(int threshold) { this.threshold = threshold; return this; } public MigrationCounter build() { MigrationCounter counter = new MigrationCounter(); counter.batch = this.batch; counter.threshold = this.threshold; return counter; } } }
lgpl-3.0
caihongwang/ChatMe
src/com/csipsimple/widgets/ScreenLocker.java
5839
/** * Copyright (C) 2010-2012 Regis Montoya (aka r3gis - www.r3gis.fr) * This file is part of CSipSimple. * * CSipSimple 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. * If you own a pjsip commercial license you can also redistribute it * and/or modify it under the terms of the GNU Lesser General Public License * as an android library. * * CSipSimple 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 CSipSimple. If not, see <http://www.gnu.org/licenses/>. */ package com.csipsimple.widgets; import android.app.Activity; import android.content.Context; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.Window; import android.view.WindowManager; import android.widget.RelativeLayout; import com.chatme.R; import java.lang.ref.WeakReference; import java.util.Timer; import java.util.TimerTask; public class ScreenLocker extends RelativeLayout implements OnTouchListener{ //private static final String THIS_FILE = "ScreenLocker"; private Timer lockTimer; private Activity activity; private SlidingTab stab; private IOnLeftRightChoice onLRChoiceListener; public static final int WAIT_BEFORE_LOCK_LONG = 10000; public static final int WAIT_BEFORE_LOCK_START = 5000; public static final int WAIT_BEFORE_LOCK_SHORT = 500; private final static int SHOW_LOCKER = 0; private final static int HIDE_LOCKER = 1; public ScreenLocker(Context context, AttributeSet attrs) { super(context, attrs); setOnTouchListener(this); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); updateTabLayout(l, t, r, b); } /** * Re-layout the slider to put it on bottom of the screen * @param l parent view left * @param t parent view top * @param r parent view right * @param b parent view bottom */ private void updateTabLayout(int l, int t, int r, int b) { if(stab != null) { final int parentWidth = r - l; final int parentHeight = b - t; final int top = parentHeight * 3/4 - stab.getHeight()/2; final int bottom = parentHeight * 3/4 + stab.getHeight() / 2; stab.layout(0, top, parentWidth, bottom); } } public void setActivity(Activity anActivity) { activity = anActivity; } public void setOnLeftRightListener(IOnLeftRightChoice l) { onLRChoiceListener = l; } private void reset() { if(stab != null) { stab.resetView(); } } public boolean onTouch(View v, MotionEvent event) { return true; } @Override public void setVisibility(int visibility) { super.setVisibility(visibility); // We inflate the sliding tab only if we become visible. if(visibility == VISIBLE && stab == null) { stab = new SlidingTab(getContext()); LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); //lp.setMargins(0, 286, 0, 0); stab.setLayoutParams(lp); stab.setLeftHintText(R.string.unlock); stab.setLeftTabResources(R.drawable.ic_jog_dial_unlock, R.drawable.jog_tab_target_green, R.drawable.jog_tab_bar_left_answer, R.drawable.jog_tab_left_answer); stab.setRightHintText(R.string.clear_call); stab.setOnLeftRightListener(onLRChoiceListener); addView(stab); updateTabLayout(getLeft(), getTop(), getRight(), getBottom()); } } private class LockTimerTask extends TimerTask{ @Override public void run() { handler.sendMessage(handler.obtainMessage(SHOW_LOCKER)); } }; public void delayedLock(int time) { if(lockTimer != null) { lockTimer.cancel(); lockTimer.purge(); lockTimer = null; } lockTimer = new Timer("ScreenLock-timer"); lockTimer.schedule(new LockTimerTask(), time); } public void show() { setVisibility(VISIBLE); if(activity != null) { Window win = activity.getWindow(); win.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); win.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); } clearLockTasks(); } public void hide() { setVisibility(GONE); if(activity != null) { Window win = activity.getWindow(); win.addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); win.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } clearLockTasks(); reset(); } private void clearLockTasks() { if(lockTimer != null) { lockTimer.cancel(); lockTimer.purge(); lockTimer = null; } } public void tearDown() { clearLockTasks(); } private Handler handler = new ShowHideHandler(this); private static class ShowHideHandler extends Handler { WeakReference<ScreenLocker> sc; ShowHideHandler(ScreenLocker screenLocker){ sc = new WeakReference<ScreenLocker>(screenLocker); } public void handleMessage(Message msg) { ScreenLocker screenLocker = sc.get(); if(screenLocker == null) { return; } switch (msg.what) { case SHOW_LOCKER: screenLocker.show(); break; case HIDE_LOCKER: screenLocker.hide(); break; default: super.handleMessage(msg); } } }; }
lgpl-3.0
kbss-cvut/jopa
jopa-impl/src/main/java/cz/cvut/kbss/jopa/oom/converter/ToFloatConverter.java
1430
/** * Copyright (C) 2022 Czech Technical University in Prague * * 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 cz.cvut.kbss.jopa.oom.converter; public class ToFloatConverter implements ConverterWrapper<Float, Object> { @Override public Object convertToAxiomValue(Float value) { return value; } @Override public Float convertToAttribute(Object value) { assert value != null; assert supportsAxiomValueType(value.getClass()); return ((Number) value).floatValue(); } @Override public boolean supportsAxiomValueType(Class<?> type) { return Float.class.isAssignableFrom(type) || Long.class.isAssignableFrom(type) || Integer.class .isAssignableFrom(type) || Short.class.isAssignableFrom(type) || Byte.class.isAssignableFrom(type); } }
lgpl-3.0
EMResearch/EvoMaster
client-java/controller/src/test/java/org/evomaster/client/java/controller/db/DbCleanerMariaDBTest.java
1998
package org.evomaster.client.java.controller.db; import org.evomaster.client.java.controller.api.dto.database.schema.DatabaseType; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.testcontainers.containers.GenericContainer; import java.sql.Connection; import java.sql.DriverManager; import java.util.HashMap; import java.util.List; public class DbCleanerMariaDBTest extends DbCleanerTestBase{ private static final String DB_NAME = "test"; private static final int PORT = 3306; public static final GenericContainer mariadb = new GenericContainer("mariadb:10.5.9") .withEnv(new HashMap<String, String>(){{ put("MYSQL_ROOT_PASSWORD", "root"); put("MYSQL_DATABASE", DB_NAME); put("MYSQL_USER", "test"); put("MYSQL_PASSWORD", "test"); }}) .withExposedPorts(PORT); private static Connection connection; @BeforeAll public static void initClass() throws Exception{ mariadb.start(); String host = mariadb.getContainerIpAddress(); int port = mariadb.getMappedPort(PORT); String url = "jdbc:mariadb://"+host+":"+port+"/"+DB_NAME; connection = DriverManager.getConnection(url, "test", "test"); } @AfterAll public static void afterClass() throws Exception { connection.close(); mariadb.stop(); } @AfterEach public void afterTest(){ DbCleaner.dropDatabaseTables(connection, DB_NAME, null, getDbType()); } @Override protected Connection getConnection() { return connection; } @Override protected void clearDatabase(List<String> tablesToSkip, List<String> tableToClean) { DbCleaner.clearDatabase(connection, DB_NAME, tablesToSkip, tableToClean, getDbType()); } @Override protected DatabaseType getDbType() { return DatabaseType.MARIADB; } }
lgpl-3.0
jblievremont/sonarqube
server/sonar-server/src/test/java/org/sonar/server/computation/debt/CharacteristicTest.java
1863
/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2014 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube 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. * * SonarQube is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.computation.debt; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; public class CharacteristicTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void test_getter_and_setter() throws Exception { Characteristic characteristic = new Characteristic(1, "PORTABILITY"); assertThat(characteristic.getId()).isEqualTo(1); assertThat(characteristic.getKey()).isEqualTo("PORTABILITY"); } @Test public void test_to_string() throws Exception { assertThat(new Characteristic(1, "PORTABILITY").toString()).isEqualTo("Characteristic{id=1, key='PORTABILITY'}"); } @Test public void creating_a_new_characteristic_with_null_key_throws_a_NPE() throws Exception { thrown.expect(NullPointerException.class); thrown.expectMessage("key cannot be null"); new Characteristic(1, null); } }
lgpl-3.0
01org/jndn-mock
src/main/java/com/intel/jndn/mock/forwarder/PitImpl.java
1949
/* * jndn-mock * Copyright (c) 2016, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 3, as published by the Free Software Foundation. * * This program is distributed in the hope 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.intel.jndn.mock.forwarder; import com.intel.jndn.mock.MockForwarder; import net.named_data.jndn.Interest; import net.named_data.jndn.Name; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Naive implementation of a pending interest table * * @author Andrew Brown, andrew.brown@intel.com */ public class PitImpl implements MockForwarder.Pit { private final Map<Name, List<MockForwarder.PitEntry>> pit = new ConcurrentHashMap<>(); public List<MockForwarder.PitEntry> extract(Name name) { ArrayList<MockForwarder.PitEntry> entries = new ArrayList<>(); for (int i = name.size(); i >= 0; i--) { Name prefix = name.getPrefix(i); List<MockForwarder.PitEntry> pendingInterests = pit.get(prefix); if (pendingInterests != null) { entries.addAll(pendingInterests); pendingInterests.clear(); // TODO is this necessary } } return entries; } public void add(MockForwarder.PitEntry entry) { if (!pit.containsKey(entry.getInterest().getName())) { pit.put(entry.getInterest().getName(), new ArrayList<MockForwarder.PitEntry>(1)); } pit.get(entry.getInterest().getName()).add(entry); } public boolean has(Interest interest) { List<MockForwarder.PitEntry> entries = pit.get(interest.getName()); return entries != null && !entries.isEmpty(); } }
lgpl-3.0
EMResearch/EvoMaster
client-java/controller/src/main/java/org/evomaster/client/java/controller/problem/rpc/schema/params/IntParam.java
2542
package org.evomaster.client.java.controller.problem.rpc.schema.params; import org.evomaster.client.java.controller.api.dto.problem.rpc.ParamDto; import org.evomaster.client.java.controller.api.dto.problem.rpc.RPCSupportedDataType; import org.evomaster.client.java.controller.problem.rpc.schema.types.AccessibleSchema; import org.evomaster.client.java.controller.problem.rpc.schema.types.PrimitiveOrWrapperType; /** * int param */ public class IntParam extends PrimitiveOrWrapperParam<Integer> { public IntParam(String name, String type, String fullTypeName, Class<?> clazz, AccessibleSchema accessibleSchema) { super(name, type, fullTypeName, clazz, accessibleSchema); } public IntParam(String name, PrimitiveOrWrapperType type, AccessibleSchema accessibleSchema) { super(name, type, accessibleSchema); } public IntParam(String name, AccessibleSchema accessibleSchema) { super(name, new PrimitiveOrWrapperType(int.class.getSimpleName(), int.class.getName(), false, int.class), accessibleSchema); } public IntParam(String name){ this(name, null); } @Override public String getValueAsJavaString() { if (getValue() == null) return null; return ""+getValue(); } @Override public ParamDto getDto() { ParamDto dto = super.getDto(); if (getType().isWrapper) dto.type.type = RPCSupportedDataType.INT; else dto.type.type = RPCSupportedDataType.P_INT; if (getValue() != null) dto.stringValue = getValue().toString(); return dto; } @Override public IntParam copyStructure() { return new IntParam(getName(), getType(), accessibleSchema); } @Override public void setValueBasedOnStringValue(String stringValue) { try { if (stringValue != null) setValue(Integer.parseInt(stringValue)); }catch (NumberFormatException e){ throw new RuntimeException("ERROR: fail to convert "+stringValue +" as int value"); } } @Override protected void setValueBasedOnValidInstance(Object instance) { setValue((Integer) instance); } @Override public boolean isValidInstance(Object instance) { return instance instanceof Integer; } @Override public String getPrimitiveValue(String responseVarName) { if (getType().isWrapper) return responseVarName+".intValue()"; return responseVarName; } }
lgpl-3.0
racodond/sonar-css-plugin
css-frontend/src/main/java/org/sonar/css/model/property/standard/GridAutoRows.java
1160
/* * SonarQube CSS / SCSS / Less Analyzer * Copyright (C) 2013-2017 David RACODON * mailto: david.racodon@gmail.com * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.css.model.property.standard; import org.sonar.css.model.property.StandardProperty; public class GridAutoRows extends StandardProperty { public GridAutoRows() { setExperimental(true); addLinks("https://drafts.csswg.org/css-grid-1/#propdef-grid-auto-rows"); } }
lgpl-3.0
HyCraftHD/TeambattleMod
src/main/java/net/hycrafthd/teambattle/TCommands.java
378
package net.hycrafthd.teambattle; import net.hycrafthd.teambattle.command.CommandEnderchest; import net.minecraftforge.fml.common.event.FMLServerStartingEvent; public class TCommands { public TCommands(FMLServerStartingEvent event) { register(event); } private void register(FMLServerStartingEvent event) { event.registerServerCommand(new CommandEnderchest()); } }
lgpl-3.0
erikryverling/sonar-github
src/main/java/org/sonar/plugins/github/IssueComparator.java
2590
/* * SonarQube :: GitHub Plugin * Copyright (C) 2015-2016 SonarSource SA * mailto:contact AT sonarsource DOT com * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.plugins.github; import java.util.Comparator; import java.util.Objects; import javax.annotation.Nullable; import org.sonar.api.issue.Issue; import org.sonar.api.rule.Severity; public final class IssueComparator implements Comparator<Issue> { @Override public int compare(Issue left, Issue right) { // Most severe issues should be displayed first. if (left == right) { return 0; } if (left == null) { return 1; } if (right == null) { return -1; } if (Objects.equals(left.severity(), right.severity())) { // When severity is the same, sort by component key to at least group issues from // the same file together. return compareComponentKeyAndLine(left, right); } return compareSeverity(left.severity(), right.severity()); } private static int compareComponentKeyAndLine(Issue left, Issue right) { if (!left.componentKey().equals(right.componentKey())) { return left.componentKey().compareTo(right.componentKey()); } return compareInt(left.line(), right.line()); } private static int compareSeverity(String leftSeverity, String rightSeverity) { if (Severity.ALL.indexOf(leftSeverity) > Severity.ALL.indexOf(rightSeverity)) { // Display higher severity first. Relies on Severity.ALL to be sorted by severity. return -1; } else { return 1; } } private static int compareInt(@Nullable Integer leftLine, @Nullable Integer rightLine) { if (Objects.equals(leftLine, rightLine)) { return 0; } else if (leftLine == null) { return -1; } else if (rightLine == null) { return 1; } else { return leftLine.compareTo(rightLine); } } }
lgpl-3.0
neuland/firefly
web/src/de/neuland/firefly/rest/v1/LockController.java
1873
package de.neuland.firefly.rest.v1; import com.google.common.base.Optional; import de.hybris.platform.core.Registry; import de.neuland.firefly.migration.LockRepository; import de.neuland.firefly.model.FireflyLockModel; import de.neuland.firefly.rest.v1.model.Lock; import org.springframework.stereotype.Controller; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static javax.ws.rs.core.Response.Status.NOT_FOUND; import static javax.ws.rs.core.Response.Status.NO_CONTENT; import static javax.ws.rs.core.Response.Status.OK; @Controller("lockController-v1") @Path("/v1/lock") public class LockController { @GET @Produces(APPLICATION_JSON) public Response getLock() { Optional<FireflyLockModel> maybeLock = getLockRepository().findLock(); if (maybeLock.isPresent()) { FireflyLockModel lock = maybeLock.get(); Lock result = new Lock(lock.getCreationtime(), lock.getClusterNode()); return Response.status(OK) .entity(result) .build(); } else { return Response.status(NOT_FOUND) .build(); } } @DELETE public Response removeLock() { LockRepository lockRepository = getLockRepository(); Optional<FireflyLockModel> maybeLock = lockRepository.findLock(); if (maybeLock.isPresent()) { lockRepository.remove(maybeLock.get()); } return Response.status(NO_CONTENT) .build(); } private LockRepository getLockRepository() { return Registry.getGlobalApplicationContext().getBean(LockRepository.class); } }
lgpl-3.0
SonarSource/sonarqube
sonar-testing-harness/src/test/java/org/sonar/test/i18n/I18nMatchersTest.java
1900
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.test.i18n; import org.junit.Test; import java.io.File; import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.sonar.test.i18n.I18nMatchers.isBundleUpToDate; public class I18nMatchersTest { @Test public void testBundlesInsideSonarPlugin() { // synchronized bundle assertThat("myPlugin_fr_CA.properties", isBundleUpToDate()); assertFalse(new File("target/l10n/myPlugin_fr_CA.properties.report.txt").exists()); // missing keys try { assertThat("myPlugin_fr.properties", isBundleUpToDate()); assertTrue(new File("target/l10n/myPlugin_fr.properties.report.txt").exists()); } catch (AssertionError e) { assertThat(e.getMessage(), containsString("Missing translations are:\nsecond.prop")); } } @Test public void shouldNotFailIfNoMissingKeysButAdditionalKeys() { assertThat("noMissingKeys_fr.properties", isBundleUpToDate()); } }
lgpl-3.0