repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
geotools/geotools | modules/library/main/src/main/java/org/geotools/data/store/ContentState.java | 14110 | /*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2006-2015, Open Source Geospatial Foundation (OSGeo)
*
* 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;
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
package org.geotools.data.store;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import org.geotools.data.BatchFeatureEvent;
import org.geotools.data.Diff;
import org.geotools.data.FeatureEvent;
import org.geotools.data.FeatureEvent.Type;
import org.geotools.data.FeatureListener;
import org.geotools.data.FeatureSource;
import org.geotools.data.Transaction;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.opengis.feature.Feature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.filter.Filter;
import org.opengis.filter.FilterFactory;
import org.opengis.filter.identity.FeatureId;
/**
* The state of an entry in a DataStore, maintained on a per-transaction basis. For information
* maintained on a typeName basis see {@link ContentEntry}.
*
* <h3>Data Cache Synchronization Required</h2>
*
* <p>The default ContentState implementation maintains cached values on a per transaction basis:
*
* <ul>
* <li>feature type ({@link #getFeatureType()}
* <li>number of features ({@link #getCount()}
* <li>spatial extent ({@link #getBounds()}
* </ul>
*
* Other types of state depend on the data format and must be handled by a subclass.
*
* <p>This class is a "data object" used to store values and is not thread safe. It is up to clients
* of this class to ensure that values are set in a thread-safe / synchronized manner. For example:
*
* <pre>
* <code>
* ContentState state = ...;
*
* //get the count
* int count = state.getCount();
* if ( count == -1 ) {
* synchronized ( state ) {
* count = calculateCount();
* state.setCount( count );
* }
* }</code></pre>
*
* <h3>Event Notification</h3>
*
* The list of listeners interested in event notification as features are modified and edited is
* stored as part of ContentState. Each notification is considered to be broadcast from a specific
* FeatureSource. Since several ContentFeatureStores can be on the same transaction (and thus share
* a ContentState) the fire methods listed here require you pass in the FeatureSource making the
* change; this requires that your individual FeatureWriters keep a pointer to the
* ContentFeatureStore which created them.
*
* <p>You may also make use of {@link ContentFeatureSource#canEvent} value of {@code false} allowing
* the base ContentFeatureStore class to take responsibility for sending event notifications.
*
* <h3>Transaction Independence</h3>
*
* <p>The default ContentState implementation also supports the handling of {@link
* ContentFeatureSource#canTransaction} value of {@code false}. The implementation asks ContentState
* to store a {@link Diff} which is used to record any modifications made until commit is called.
*
* <p>Internally a {@link Transaction.State} is used to notify the implementation of {{@link
* Transaction#commit} and {@link Transaction#rollback()}.
*
* <h3>Extension</h3>
*
* This class may be extended if your implementaiton wishes to capture additional information per
* transaction. A database implementation using a JDBCContentState to store a JDBC Connection
* remains a good example.
*
* <p>Subclasses may extend (not override) the following methods:
*
* <ul>
* <li>{@link #flush()} - remember to call super.flush()
* <li>{@link #close()} - remember to call super.close()
* </ul>
*
* Subclasses should also override {@link #copy()} to ensure any additional state they are keeping
* is correctly accounted for.
*
* @author Jody Garnett (LISASoft)
* @author Justin Deoliveira, The Open Planning Project
* @version 8.0
* @since 2.6
*/
public class ContentState {
/** Transaction the state works from. */
protected Transaction tx;
/** entry maintaining the state */
protected ContentEntry entry;
// CACHE
/** cached feature type */
protected SimpleFeatureType featureType;
/** cached number of features */
protected int count = -1;
/** cached bounds of features */
protected ReferencedEnvelope bounds;
// EVENT NOTIFICATION SUPPORT
/**
* Even used for batch notification; used to collect the bounds and feature ids generated over
* the course of a transaction.
*/
protected BatchFeatureEvent batchFeatureEvent;
/** observers */
protected List<FeatureListener> listeners = Collections.synchronizedList(new ArrayList<>());
// TRANSACTION SUPPORT
/**
* Callback used to issue batch feature events when commit/rollback issued on the transaction.
*/
protected DiffTransactionState transactionState = new DiffTransactionState(this);
/**
* Creates a new state.
*
* @param entry The entry for the state.
*/
public ContentState(ContentEntry entry) {
this.entry = entry;
}
/**
* Creates a new state from a previous one.
*
* <p>All state from the specified <tt>state</tt> is copied. Therefore subclasses extending this
* constructor should clone all mutable objects.
*
* @param state The existing state.
*/
protected ContentState(ContentState state) {
this(state.getEntry());
featureType = state.featureType;
count = state.count;
bounds = state.bounds == null ? null : ReferencedEnvelope.reference(state.bounds);
batchFeatureEvent = null;
}
/** The entry which maintains the state. */
public ContentEntry getEntry() {
return entry;
}
/** The transaction associated with the state. */
public Transaction getTransaction() {
return tx;
}
/** Sets the transaction associated with the state. */
public void setTransaction(Transaction tx) {
this.tx = tx;
if (tx != Transaction.AUTO_COMMIT) {
tx.putState(this.entry, transactionState);
}
}
/** The cached feature type. */
public final SimpleFeatureType getFeatureType() {
return featureType;
}
/** Sets the cached feature type. */
public final void setFeatureType(SimpleFeatureType featureType) {
this.featureType = featureType;
}
/** The cached number of features. */
public final int getCount() {
return count;
}
/** Sets the cached number of features. */
public final void setCount(int count) {
this.count = count;
}
/** The cached spatial extent. */
public final ReferencedEnvelope getBounds() {
return bounds;
}
/** Sets the cached spatial extent. */
public final void setBounds(ReferencedEnvelope bounds) {
this.bounds = bounds;
}
/**
* Adds a listener for collection events.
*
* @param listener The listener to add
*/
public final void addListener(FeatureListener listener) {
listeners.add(listener);
}
/**
* Removes a listener for collection events.
*
* @param listener The listener to remove
*/
public final void removeListener(FeatureListener listener) {
listeners.remove(listener);
}
public BatchFeatureEvent getBatchFeatureEvent() {
return batchFeatureEvent;
}
/** Used to quickly test if any listeners are available. */
public final boolean hasListener() {
if (!listeners.isEmpty()) {
return true;
}
if (this.tx == Transaction.AUTO_COMMIT && this.entry.state.size() > 1) {
// We are the auto commit state; and there is at least one other thread to notify
return true;
}
return false;
}
/**
* Creates a FeatureEvent indicating that the provided feature has been changed.
*
* <p>This method is provided to simplify event notification for implementors by constructing a
* FeatureEvent internally (and then only if listeners are interested). You may find it easier
* to construct your own FeatureEvent using {{@link #hasListener()} to check if you need to fire
* events at all.
*
* @param source FeatureSource responsible for the change
* @param feature The updated feature
* @param before the bounds of the feature before the change
*/
public void fireFeatureUpdated(
FeatureSource<?, ?> source, Feature feature, ReferencedEnvelope before) {
if (feature == null) {
return; // nothing changed
}
if (listeners.isEmpty() && tx != Transaction.AUTO_COMMIT) return; // nobody is listenting
Filter filter = idFilter(feature);
ReferencedEnvelope bounds = ReferencedEnvelope.reference(feature.getBounds());
if (bounds != null) {
bounds.expandToInclude(before);
}
FeatureEvent event = new FeatureEvent(source, Type.CHANGED, bounds, filter);
fireFeatureEvent(event);
}
/** Used to issue a Type.ADDED FeatureEvent indicating a new feature being created */
public final void fireFeatureAdded(FeatureSource<?, ?> source, Feature feature) {
if (listeners.isEmpty() && tx != Transaction.AUTO_COMMIT) return;
Filter filter = idFilter(feature);
ReferencedEnvelope bounds = ReferencedEnvelope.reference(feature.getBounds());
FeatureEvent event = new FeatureEvent(source, Type.ADDED, bounds, filter);
fireFeatureEvent(event);
}
public void fireFeatureRemoved(FeatureSource<?, ?> source, Feature feature) {
if (listeners.isEmpty() && tx != Transaction.AUTO_COMMIT) return;
Filter filter = idFilter(feature);
ReferencedEnvelope bounds = ReferencedEnvelope.reference(feature.getBounds());
FeatureEvent event = new FeatureEvent(source, Type.REMOVED, bounds, filter);
fireFeatureEvent(event);
}
/** Helper method or building fid filters. */
Filter idFilter(Feature feature) {
FilterFactory ff = this.entry.dataStore.getFilterFactory();
Set<FeatureId> fids = new HashSet<>();
fids.add(feature.getIdentifier());
return ff.id(fids);
}
/**
* Used to issue a single FeatureEvent.
*
* <p>If this content state is used for Transaction.AUTO_COMMIT the notification will be passed
* to all interested parties.
*
* <p>If not this event will be recored as part of a BatchFeatureEvent that will to be issued
* using issueBatchFeatureEvent()
*/
public final void fireFeatureEvent(FeatureEvent event) {
if (this.tx == Transaction.AUTO_COMMIT) {
this.entry.notifiyFeatureEvent(this, event);
} else {
// we are not in auto-commit mode so we need to batch
// up the changes for when the commit goes out
if (batchFeatureEvent == null) {
batchFeatureEvent = new BatchFeatureEvent(event.getFeatureSource());
}
batchFeatureEvent.add(event);
}
if (listeners.isEmpty()) {
return;
}
for (FeatureListener listener : listeners) {
try {
listener.changed(event);
} catch (Throwable t) {
this.entry.dataStore.LOGGER.log(
Level.WARNING, "Problem issuing batch feature event " + event, t);
}
}
}
/**
* Notifies all waiting listeners that a commit has been issued; this notification is also sent
* to our
*/
public final void fireBatchFeatureEvent(boolean isCommit) {
if (batchFeatureEvent == null) {
return;
}
if (isCommit) {
batchFeatureEvent.setType(Type.COMMIT);
// This state already knows about the changes, let others know a modifications was made
this.entry.notifiyFeatureEvent(this, batchFeatureEvent);
} else {
batchFeatureEvent.setType(Type.ROLLBACK);
// Notify this state about the rollback, other transactions see no change
for (FeatureListener listener : listeners) {
try {
listener.changed(batchFeatureEvent);
} catch (Throwable t) {
this.entry.dataStore.LOGGER.log(
Level.WARNING,
"Problem issuing batch feature event " + batchFeatureEvent,
t);
}
}
}
batchFeatureEvent = null;
}
/**
* Clears cached state.
*
* <p>This method does not affect any non-cached state. This method may be extended by
* subclasses, but not overiden.
*/
public void flush() {
featureType = null;
count = -1;
bounds = null;
}
/**
* Clears all state.
*
* <p>Any resources that the state holds onto (like a database connection) should be closed or
* disposes when this method is called. This method may be extended by subclasses, but not
* overiden.
*/
public void close() {
featureType = null;
if (listeners != null) {
listeners.clear();
listeners = null;
}
}
/**
* Copies the state.
*
* <p>Subclasses should override this method. Any mutable state objects should be cloned.
*
* @return A copy of the state.
*/
public ContentState copy() {
return new ContentState(this);
}
}
| lgpl-2.1 |
vboerchers/checkstyle | src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/PkgControlRegExpTest.java | 4008 | ////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2016 the original author or authors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.checks.imports;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import org.junit.Before;
import org.junit.Test;
public class PkgControlRegExpTest {
private final PkgControl pcRoot = new PkgControl("com.kazgroup.courtlink", false);
private final PkgControl pcCommon = new PkgControl(pcRoot, "common", false);
@Before
public void setUp() {
pcRoot.addGuard(new Guard(false, false, ".*\\.(spring|lui)framework", false, true));
pcRoot.addGuard(new Guard(false, false, "org\\.hibernate", false, true));
pcRoot.addGuard(new Guard(true, false, "org\\.(apache|lui)\\.commons", false, true));
pcCommon.addGuard(new Guard(true, false, "org\\.h.*", false, true));
}
@Test
public void testLocateFinest() {
assertEquals(pcRoot, pcRoot
.locateFinest("com.kazgroup.courtlink.domain"));
assertEquals(pcCommon, pcRoot
.locateFinest("com.kazgroup.courtlink.common.api"));
assertNull(pcRoot.locateFinest("com"));
}
@Test
public void testCheckAccess() {
assertEquals(AccessResult.DISALLOWED, pcCommon.checkAccess(
"org.springframework.something",
"com.kazgroup.courtlink.common"));
assertEquals(AccessResult.DISALLOWED, pcCommon.checkAccess(
"org.luiframework.something",
"com.kazgroup.courtlink.common"));
assertEquals(AccessResult.DISALLOWED, pcCommon.checkAccess(
"de.springframework.something",
"com.kazgroup.courtlink.common"));
assertEquals(AccessResult.DISALLOWED, pcCommon.checkAccess(
"de.luiframework.something",
"com.kazgroup.courtlink.common"));
assertEquals(AccessResult.ALLOWED, pcCommon
.checkAccess("org.apache.commons.something",
"com.kazgroup.courtlink.common"));
assertEquals(AccessResult.ALLOWED, pcCommon
.checkAccess("org.lui.commons.something",
"com.kazgroup.courtlink.common"));
assertEquals(AccessResult.DISALLOWED, pcCommon.checkAccess(
"org.apache.commons", "com.kazgroup.courtlink.common"));
assertEquals(AccessResult.DISALLOWED, pcCommon.checkAccess(
"org.lui.commons", "com.kazgroup.courtlink.common"));
assertEquals(AccessResult.ALLOWED, pcCommon.checkAccess(
"org.hibernate.something", "com.kazgroup.courtlink.common"));
assertEquals(AccessResult.DISALLOWED, pcCommon.checkAccess(
"com.badpackage.something", "com.kazgroup.courtlink.common"));
assertEquals(AccessResult.DISALLOWED, pcRoot.checkAccess(
"org.hibernate.something", "com.kazgroup.courtlink"));
}
@Test
public void testUnknownPkg() {
assertNull(pcRoot.locateFinest("net.another"));
}
}
| lgpl-2.1 |
Cazsius/Spice-of-Life-Carrot-Edition | src/main/java/com/cazsius/solcarrot/client/gui/FoodData.java | 1194 | package com.cazsius.solcarrot.client.gui;
import com.cazsius.solcarrot.SOLCarrotConfig;
import com.cazsius.solcarrot.client.FoodItems;
import com.cazsius.solcarrot.tracking.FoodList;
import com.cazsius.solcarrot.tracking.ProgressInfo;
import net.minecraft.item.Item;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/** collects the information the food book needs in a convenient single location */
@OnlyIn(Dist.CLIENT)
final class FoodData {
public final FoodList foodList;
public final ProgressInfo progressInfo;
public final List<Item> validFoods;
public final List<Item> eatenFoods;
public final List<Item> uneatenFoods;
FoodData(FoodList foodList) {
this.foodList = foodList;
this.progressInfo = foodList.getProgressInfo();
this.validFoods = FoodItems.getAllFoods().stream()
.filter(SOLCarrotConfig::isHearty)
.collect(Collectors.toList());
this.eatenFoods = new ArrayList<>();
this.uneatenFoods = new ArrayList<>();
for (Item food : validFoods) {
(foodList.hasEaten(food) ? eatenFoods : uneatenFoods).add(food);
}
}
}
| lgpl-2.1 |
nict-wisdom/rasc | jp.go.nict.ial.servicecontainer.handler.websocketjsonrpc/test/jp/go/nict/ial/servicecontainer/handler/websocketjson/LaunchClientWSJsonRpcClientArray.java | 1749 | /*
* Copyright (C) 2014 Information Analysis Laboratory, NICT
*
* RaSC 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.
*
* RaSC 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 jp.go.nict.ial.servicecontainer.handler.websocketjson;
import java.net.URL;
import java.util.Arrays;
import jp.go.nict.ial.client.wsjsonrpc.WebSocketJsonRpcClientFactory;
import jp.go.nict.ial.servicecontainer.handler.websocketjson.test.HelloArrayIntf;
import jp.go.nict.langrid.commons.rpc.ArrayElementsNotifier;
import jp.go.nict.langrid.commons.rpc.ArrayElementsReceiver;
public class LaunchClientWSJsonRpcClientArray {
public static void main(String[] args) throws Exception{
WebSocketJsonRpcClientFactory f = new WebSocketJsonRpcClientFactory();
try{
HelloArrayIntf h = f.create(
HelloArrayIntf.class,
new URL("http://localhost:8080/wsjsServices/HelloArray")
);
((ArrayElementsNotifier)h).setReceiver(new ArrayElementsReceiver<String>() {
@Override
public void receive(String element) {
System.out.println("ae: " + element);
}
});
System.out.println(Arrays.toString(h.hello("hi")));
System.out.println(Arrays.toString(h.hello("hi")));
} finally{
f.closeAll();
}
}
}
| lgpl-2.1 |
1fechner/FeatureExtractor | sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditedAtSuperclassLevel/auditMethodSubclass/AuditedMethodSubclassEntity.java | 2099 | /*
* 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.envers.test.integration.superclass.auditedAtSuperclassLevel.auditMethodSubclass;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.envers.Audited;
import org.hibernate.envers.test.integration.superclass.auditedAtSuperclassLevel.AuditedAllMappedSuperclass;
/**
* @author Adam Warski (adam at warski dot org)
* @author Hern&aacut;n Chanfreau
*/
@Entity
@Table(name = "AuditedMethodSubclass")
public class AuditedMethodSubclassEntity extends AuditedAllMappedSuperclass {
@Id
@GeneratedValue
private Integer id;
@Audited
private String subAuditedStr;
public AuditedMethodSubclassEntity() {
}
public AuditedMethodSubclassEntity(Integer id, String str, String otherString, String subAuditedStr) {
super( str, otherString );
this.subAuditedStr = subAuditedStr;
this.id = id;
}
public AuditedMethodSubclassEntity(String str, String otherString, String subAuditedStr) {
super( str, otherString );
this.subAuditedStr = subAuditedStr;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSubAuditedStr() {
return subAuditedStr;
}
public void setSubAuditedStr(String subAuditedStr) {
this.subAuditedStr = subAuditedStr;
}
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( !(o instanceof AuditedMethodSubclassEntity) ) {
return false;
}
if ( !super.equals( o ) ) {
return false;
}
AuditedMethodSubclassEntity that = (AuditedMethodSubclassEntity) o;
if ( id != null ? !id.equals( that.id ) : that.id != null ) {
return false;
}
return true;
}
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (id != null ? id.hashCode() : 0);
return result;
}
}
| lgpl-2.1 |
Chicken-Bones/CCObfuscator | codechicken/obfuscator/fs/DirMod.java | 2135 | package codechicken.obfuscator.fs;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class DirMod extends FileMod
{
private ZipOutputStream zipout;
public DirMod(ObfReadThread read, File dir, boolean modify, boolean zip) throws IOException
{
super(read, dir, modify);
if(modify() && zip)
{
File out = new File(read.outDir, name+".zip");
if(out.exists())
throw new RuntimeException("Duplicate output mod: "+name);
out.getParentFile().mkdirs();
out.createNewFile();
zipout = new ZipOutputStream(new FileOutputStream(out));
}
}
@Override
public void read(ModEntryReader reader) throws IOException
{
run.out().println("Reading mod: "+name);
read(file, "", reader);
}
private void read(File dir, String prefix, ModEntryReader reader) throws IOException
{
for(File file : dir.listFiles())
{
String name = prefix+(prefix.length() == 0 ? "" : "/")+file.getName();
if(file.isDirectory())
read(file, name, reader);
else
{
FileInputStream in = new FileInputStream(file);
reader.read(this, in, name, file.length());
in.close();
}
}
}
@Override
public boolean writeAsync()
{
return true;
}
@Override
public void write(ModEntry entry) throws IOException
{
if(zipout != null)
{
run.fine().println("Writing: "+entry.getName()+" to "+name);
zipout.putNextEntry(new ZipEntry(entry.getName()));
entry.write(zipout);
zipout.closeEntry();
}
else
{
super.write(entry);
}
}
@Override
public void close() throws IOException
{
if(zipout != null)
zipout.close();
}
}
| lgpl-2.1 |
lat-lon/deegree2-base | deegree2-core/src/main/java/org/deegree/model/coverage/grid/FloatGridCoverage.java | 7860 | //$HeadURL$
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2009 by:
Department of Geography, University of Bonn
and
lat/lon GmbH
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 2.1 of the License, or (at your option)
any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: info@deegree.org
----------------------------------------------------------------------------*/
package org.deegree.model.coverage.grid;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.Raster;
import java.awt.image.renderable.RenderableImage;
import org.deegree.model.spatialschema.Envelope;
import org.deegree.ogcwebservices.wcs.describecoverage.CoverageOffering;
/**
*
*
* @author <a href="mailto:poth@lat-lon.de">Andreas Poth</a>
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*/
public class FloatGridCoverage extends AbstractGridCoverage {
private static final long serialVersionUID = -3642652899429594623L;
private float[][][] data = null;
/**
* @param coverageOffering
* @param envelope
* @param data
*/
public FloatGridCoverage( CoverageOffering coverageOffering, Envelope envelope, float[][][] data ) {
this( coverageOffering, envelope, false, data );
}
/**
* @param coverageOffering
* @param envelope
* @param isEditable
* @param data
*/
public FloatGridCoverage( CoverageOffering coverageOffering, Envelope envelope, boolean isEditable, float[][][] data ) {
super( coverageOffering, envelope, isEditable );
this.data = data;
}
/**
* @param coverageOffering
* @param envelope
* @param sources
*/
public FloatGridCoverage( CoverageOffering coverageOffering, Envelope envelope, FloatGridCoverage[] sources ) {
super( coverageOffering, envelope, sources );
}
/**
* The number of sample dimensions in the coverage. For grid coverages, a sample dimension is a band.
*
* @return The number of sample dimensions in the coverage.
* @UML mandatory numSampleDimensions
*/
public int getNumSampleDimensions() {
if ( data != null ) {
return data.length;
}
return sources[0].getNumSampleDimensions();
}
/**
* Returns 2D view of this coverage as a renderable image. This optional operation allows interoperability with <A
* HREF="http://java.sun.com/products/java-media/2D/">Java2D</A>. If this coverage is a
* {@link "org.opengis.coverage.grid.GridCoverage"} backed by a {@link java.awt.image.RenderedImage}, the underlying
* image can be obtained with:
*
* <code>getRenderableImage(0,1).{@linkplain RenderableImage#createDefaultRendering()
* createDefaultRendering()}</code>
*
* @param xAxis
* Dimension to use for the <var>x</var> axis.
* @param yAxis
* Dimension to use for the <var>y</var> axis.
* @return A 2D view of this coverage as a renderable image.
* @throws UnsupportedOperationException
* if this optional operation is not supported.
* @throws IndexOutOfBoundsException
* if <code>xAxis</code> or <code>yAxis</code> is out of bounds.
*/
@Override
public RenderableImage getRenderableImage( int xAxis, int yAxis )
throws UnsupportedOperationException, IndexOutOfBoundsException {
if ( data != null ) {
return null;
}
// TODO if multi images -> sources.length > 0
return null;
}
/**
* this is a deegree convenience method which returns the source image of an <tt>ImageGridCoverage</tt>. In procipal
* the same can be done with the getRenderableImage(int xAxis, int yAxis) method. but creating a
* <tt>RenderableImage</tt> image is very slow. I xAxis or yAxis <= 0 then the size of the returned image will be
* calculated from the source images of the coverage.
*
* @param xAxis
* Dimension to use for the <var>x</var> axis.
* @param yAxis
* Dimension to use for the <var>y</var> axis.
* @return the image
*/
@Override
public BufferedImage getAsImage( int xAxis, int yAxis ) {
if ( xAxis <= 0 || yAxis <= 0 ) {
// get default size if passed target size is <= 0
Rectangle rect = calculateOriginalSize();
xAxis = rect.width;
yAxis = rect.height;
}
BufferedImage bi = new BufferedImage( xAxis, yAxis, BufferedImage.TYPE_INT_ARGB );
if ( data != null ) {
BufferedImage img = new BufferedImage( data[0][0].length, data[0].length, BufferedImage.TYPE_INT_ARGB );
Raster raster = img.getData();
DataBuffer buf = raster.getDataBuffer();
for ( int i = 0; i < data[0][0].length; i++ ) {
for ( int j = 0; j < data[0].length; j++ ) {
buf.setElem( j * data[0][0].length + i, Float.floatToIntBits( data[0][j][i] ) );
}
}
img.setData( raster );
if ( img.getWidth() != bi.getWidth() || img.getHeight() != bi.getHeight() ) {
// just resize if source image size is different from
// target image size
Graphics g = bi.getGraphics();
g.drawImage( img, 0, 0, bi.getWidth(), bi.getHeight(), null );
g.dispose();
}
} else {
// it's a complex FloatGridCoverage made up of different
// source coverages
for ( int i = 0; i < sources.length; i++ ) {
BufferedImage sourceImg = ( (AbstractGridCoverage) sources[i] ).getAsImage( -1, -1 );
bi = paintImage( bi, this.getEnvelope(), sourceImg, sources[i].getEnvelope() );
}
}
return bi;
}
/**
* calculates the original size of a gridcoverage based on its resolution and the envelope(s) of its source(s).
*
* @return the size
*/
private Rectangle calculateOriginalSize() {
if ( data != null ) {
return new Rectangle( data[0][0].length, data[0].length );
}
BufferedImage bi = ( (ImageGridCoverage) sources[0] ).getAsImage( -1, -1 );
Envelope env = sources[0].getEnvelope();
double dx = env.getWidth() / bi.getWidth();
double dy = env.getHeight() / bi.getHeight();
env = this.getEnvelope();
int w = (int) Math.round( env.getWidth() / dx );
int h = (int) Math.round( env.getHeight() / dy );
return new Rectangle( w, h );
}
}
| lgpl-2.1 |
phiresky/tuxguitar | TuxGuitar-ui-toolkit-jfx/src/org/herac/tuxguitar/ui/jfx/toolbar/JFXToolActionMenuItem.java | 2436 | package org.herac.tuxguitar.ui.jfx.toolbar;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Bounds;
import javafx.scene.input.MouseEvent;
import org.herac.tuxguitar.ui.event.UISelectionListener;
import org.herac.tuxguitar.ui.jfx.event.JFXSelectionListenerManager;
import org.herac.tuxguitar.ui.jfx.menu.JFXPopupMenu;
import org.herac.tuxguitar.ui.jfx.widget.JFXButton;
import org.herac.tuxguitar.ui.menu.UIMenu;
import org.herac.tuxguitar.ui.menu.UIPopupMenu;
import org.herac.tuxguitar.ui.resource.UIPosition;
import org.herac.tuxguitar.ui.resource.UIRectangle;
import org.herac.tuxguitar.ui.toolbar.UIToolActionMenuItem;
public class JFXToolActionMenuItem extends JFXButton implements UIToolActionMenuItem {
private Double mouseX;
private UIPopupMenu menu;
private JFXSelectionListenerManager<ActionEvent> selectionListener;
public JFXToolActionMenuItem(JFXToolBar parent) {
super(parent);
this.menu = new JFXPopupMenu(parent.getControl().getScene().getWindow());
this.selectionListener = new JFXSelectionListenerManager<ActionEvent>(this);
this.getControl().setFocusTraversable(false);
this.getControl().setOnMousePressed(new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
JFXToolActionMenuItem.this.handleMouseEvent(event);
}
});
this.getControl().setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
JFXToolActionMenuItem.this.handleActionEvent(event);
}
});
}
public void addSelectionListener(UISelectionListener listener) {
this.selectionListener.addListener(listener);
}
public void removeSelectionListener(UISelectionListener listener) {
this.selectionListener.removeListener(listener);
}
public UIMenu getMenu() {
return this.menu;
}
public void openMenu() {
Bounds bounds = this.getControl().getBoundsInLocal();
Bounds screenBounds = this.getControl().localToScreen(bounds);
this.menu.open(new UIPosition((float) screenBounds.getMinX(), (float) (screenBounds.getMinY() + bounds.getHeight())));
}
public void handleActionEvent(ActionEvent event) {
UIRectangle bounds = this.getBounds();
if( this.mouseX == null || this.mouseX < (bounds.getWidth() - 10)) {
this.selectionListener.handle(event);
} else {
this.openMenu();
}
}
public void handleMouseEvent(MouseEvent event) {
this.mouseX = event.getX();
}
}
| lgpl-2.1 |
dheid/wings3 | wings/src/main/java/org/wings/plaf/css/ScrollPaneCG.java | 3938 | /*
* Copyright 2000,2005 wingS development team.
*
* This file is part of wingS (http://wingsframework.org).
*
* wingS 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.
*
* Please see COPYING for the complete licence.
*/
package org.wings.plaf.css;
import java.awt.Adjustable;
import java.io.IOException;
import org.wings.*;
import org.wings.style.CSSProperty;
import org.wings.io.Device;
import org.wings.script.JavaScriptDOMListener;
import org.wings.session.ScriptManager;
import org.wings.plaf.css.script.*;
public class ScrollPaneCG extends org.wings.plaf.css.AbstractComponentCG implements org.wings.plaf.ScrollPaneCG {
private static final long serialVersionUID = 1L;
@Override
public void writeInternal(Device device, SComponent component) throws IOException {
SScrollPane scrollpane = (SScrollPane) component;
if (scrollpane.getMode() == SScrollPane.MODE_COMPLETE) {
SDimension preferredSize = scrollpane.getPreferredSize();
if (preferredSize == null) {
scrollpane.setPreferredSize(new SDimension(200, 400));
} else {
if (preferredSize.getWidthInt() < 0) Utils.setPreferredSize(component, "200", preferredSize.getHeight());
if (preferredSize.getHeightInt() < 0) Utils.setPreferredSize(component, preferredSize.getWidth(), "400");;
}
ScriptManager.getInstance().addScriptListener(new LayoutScrollPaneScript(component.getName()));
writeContent(device, component);
} else {
writeContent(device, component);
}
Adjustable sb = scrollpane.getVerticalScrollBar();
SComponent viewport = (SComponent)scrollpane.getScrollable();
if (viewport != null && sb instanceof SScrollBar) {
final JavaScriptDOMListener handleMouseWheel = new JavaScriptDOMListener(
"DOMMouseScroll",
"wingS.scrollbar.handleMouseWheel", '\'' +((SScrollBar)sb).getName()+ '\'', viewport);
viewport.addScriptListener(handleMouseWheel);
}
}
public static void writeContent(Device device, SComponent c) throws IOException {
SScrollPane scrollPane = (SScrollPane) c;
SDimension preferredSize = scrollPane.getPreferredSize();
String height = preferredSize != null ? preferredSize.getHeight() : null;
boolean clientLayout = Utils.isMSIE(scrollPane) && height != null && !"auto".equals(height)
&& scrollPane.getMode() != SScrollPane.MODE_COMPLETE;
boolean clientFix = Utils.isMSIE(scrollPane) && (height == null || "auto".equals(height))
&& scrollPane.getMode() != SScrollPane.MODE_COMPLETE;
device.print("<table");
if (clientLayout) {
Utils.optAttribute(device, "layoutHeight", height);
Utils.setPreferredSize(scrollPane, preferredSize.getWidth(), null);
}
if (scrollPane.getMode() == SScrollPane.MODE_COMPLETE)
scrollPane.setAttribute(CSSProperty.TABLE_LAYOUT, "fixed");
else
scrollPane.setAttribute(CSSProperty.TABLE_LAYOUT, null);
Utils.writeAllAttributes(device, scrollPane);
if (clientLayout) {
Utils.setPreferredSize(scrollPane, preferredSize.getWidth(), height);
scrollPane.getSession().getScriptManager().addScriptListener(new LayoutFillScript(scrollPane.getName()));
}
else if (clientFix)
scrollPane.getSession().getScriptManager().addScriptListener(new LayoutFixScript(scrollPane.getName()));
device.print(">");
Utils.renderContainer(device, scrollPane);
device.print("</table>");
}
}
| lgpl-2.1 |
geotools/geotools | modules/ogc/net.opengis.wmts/src/net/opengis/gml311/KnotType.java | 5864 | /**
*/
package net.opengis.gml311;
import java.math.BigInteger;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Knot Type</b></em>'.
* <!-- end-user-doc -->
*
* <!-- begin-model-doc -->
* A knot is a breakpoint on a piecewise spline curve.
* <!-- end-model-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link net.opengis.gml311.KnotType#getValue <em>Value</em>}</li>
* <li>{@link net.opengis.gml311.KnotType#getMultiplicity <em>Multiplicity</em>}</li>
* <li>{@link net.opengis.gml311.KnotType#getWeight <em>Weight</em>}</li>
* </ul>
*
* @see net.opengis.gml311.Gml311Package#getKnotType()
* @model extendedMetaData="name='KnotType' kind='elementOnly'"
* @generated
*/
public interface KnotType extends EObject {
/**
* Returns the value of the '<em><b>Value</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* The property "value" is the value of the parameter at the knot of the spline. The sequence of knots shall be a non-decreasing sequence. That is, each knot's value in the sequence shall be equal to or greater than the previous knot's value. The use of equal consecutive knots is normally handled using the multiplicity.
* <!-- end-model-doc -->
* @return the value of the '<em>Value</em>' attribute.
* @see #isSetValue()
* @see #unsetValue()
* @see #setValue(double)
* @see net.opengis.gml311.Gml311Package#getKnotType_Value()
* @model unsettable="true" dataType="org.eclipse.emf.ecore.xml.type.Double" required="true"
* extendedMetaData="kind='element' name='value' namespace='##targetNamespace'"
* @generated
*/
double getValue();
/**
* Sets the value of the '{@link net.opengis.gml311.KnotType#getValue <em>Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Value</em>' attribute.
* @see #isSetValue()
* @see #unsetValue()
* @see #getValue()
* @generated
*/
void setValue(double value);
/**
* Unsets the value of the '{@link net.opengis.gml311.KnotType#getValue <em>Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isSetValue()
* @see #getValue()
* @see #setValue(double)
* @generated
*/
void unsetValue();
/**
* Returns whether the value of the '{@link net.opengis.gml311.KnotType#getValue <em>Value</em>}' attribute is set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return whether the value of the '<em>Value</em>' attribute is set.
* @see #unsetValue()
* @see #getValue()
* @see #setValue(double)
* @generated
*/
boolean isSetValue();
/**
* Returns the value of the '<em><b>Multiplicity</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* The property "multiplicity" is the multiplicity of this knot used in the definition of the spline (with the same weight).
* <!-- end-model-doc -->
* @return the value of the '<em>Multiplicity</em>' attribute.
* @see #setMultiplicity(BigInteger)
* @see net.opengis.gml311.Gml311Package#getKnotType_Multiplicity()
* @model dataType="org.eclipse.emf.ecore.xml.type.NonNegativeInteger" required="true"
* extendedMetaData="kind='element' name='multiplicity' namespace='##targetNamespace'"
* @generated
*/
BigInteger getMultiplicity();
/**
* Sets the value of the '{@link net.opengis.gml311.KnotType#getMultiplicity <em>Multiplicity</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Multiplicity</em>' attribute.
* @see #getMultiplicity()
* @generated
*/
void setMultiplicity(BigInteger value);
/**
* Returns the value of the '<em><b>Weight</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* The property "weight" is the value of the averaging weight used for this knot of the spline.
* <!-- end-model-doc -->
* @return the value of the '<em>Weight</em>' attribute.
* @see #isSetWeight()
* @see #unsetWeight()
* @see #setWeight(double)
* @see net.opengis.gml311.Gml311Package#getKnotType_Weight()
* @model unsettable="true" dataType="org.eclipse.emf.ecore.xml.type.Double" required="true"
* extendedMetaData="kind='element' name='weight' namespace='##targetNamespace'"
* @generated
*/
double getWeight();
/**
* Sets the value of the '{@link net.opengis.gml311.KnotType#getWeight <em>Weight</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Weight</em>' attribute.
* @see #isSetWeight()
* @see #unsetWeight()
* @see #getWeight()
* @generated
*/
void setWeight(double value);
/**
* Unsets the value of the '{@link net.opengis.gml311.KnotType#getWeight <em>Weight</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isSetWeight()
* @see #getWeight()
* @see #setWeight(double)
* @generated
*/
void unsetWeight();
/**
* Returns whether the value of the '{@link net.opengis.gml311.KnotType#getWeight <em>Weight</em>}' attribute is set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return whether the value of the '<em>Weight</em>' attribute is set.
* @see #unsetWeight()
* @see #getWeight()
* @see #setWeight(double)
* @generated
*/
boolean isSetWeight();
} // KnotType
| lgpl-2.1 |
jomarmar/cling-osgi | basedriver/src/main/java/org/fourthline/cling/osgi/basedriver/ApacheUpnpServiceConfiguration.java | 1927 | /*
* Copyright (C) 2013 4th Line GmbH, Switzerland
*
* The contents of this file are subject to the terms of either the GNU
* Lesser General Public License Version 2 or later ("LGPL") or the
* Common Development and Distribution License Version 1 or later
* ("CDDL") (collectively, the "License"). You may not use this file
* except in compliance with the License. See LICENSE.txt for more
* information.
*
* 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.
*/
package org.fourthline.cling.osgi.basedriver;
import org.fourthline.cling.DefaultUpnpServiceConfiguration;
import org.jemz.core.upnp.cling.transport.jetty9.StreamClientConfigurationImpl;
import org.jemz.core.upnp.cling.transport.jetty9.StreamClientImpl;
//import org.jemz.core.upnp.cling.transport.jetty8.StreamClientConfigurationImpl;
//import org.jemz.core.upnp.cling.transport.jetty8.StreamClientImpl;
import org.fourthline.cling.transport.impl.StreamServerConfigurationImpl;
import org.fourthline.cling.transport.impl.StreamServerImpl;
import org.fourthline.cling.transport.spi.NetworkAddressFactory;
import org.fourthline.cling.transport.spi.StreamClient;
import org.fourthline.cling.transport.spi.StreamServer;
/**
* @author Bruce Green
*/
public class ApacheUpnpServiceConfiguration extends DefaultUpnpServiceConfiguration {
@Override
public StreamClient<?> createStreamClient() {
return new StreamClientImpl(new StreamClientConfigurationImpl(getSyncProtocolExecutorService()));
}
@Override
public StreamServer<?> createStreamServer(NetworkAddressFactory networkAddressFactory) {
return new StreamServerImpl(
new StreamServerConfigurationImpl(
networkAddressFactory.getStreamListenPort()
)
);
}
}
| lgpl-2.1 |
metlos/rhq-plugin-annotation-processor | annotations/src/main/java/org/rhq/plugin/annotation/metric/Units.java | 1263 | /*
* RHQ Management Platform
* Copyright (C) 2013 Red Hat, Inc.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package org.rhq.plugin.annotation.metric;
/**
* Metric Units.
*
* @author Galder Zamarreño
* @since 4.0
*/
public enum Units {
NONE, PERCENTAGE, BITS, KILOBITS, MEGABITS, GIGABITS, TERABITS, PETABITS, BYTES, KILOBYTES, MEGABYTES, GIGABYTES,
TERABYTES, PETABYTES, EPOCH_MILLISECONDS, EPOCH_SECONDS, JIFFYS, NANOSECONDS, MICROSECONDS, MILLISECONDS, SECONDS,
MINUTES, HOURS, DAYS, KELVIN, CELSIUS, FAHRENHEIT;
@Override
public String toString() {
return super.toString().toLowerCase();
}
}
| lgpl-2.1 |
threerings/nenya | core/src/main/java/com/threerings/media/animation/FadeImageAnimation.java | 1631 | //
// Nenya library - tools for developing networked games
// Copyright (C) 2002-2012 Three Rings Design, Inc., All Rights Reserved
// https://github.com/threerings/nenya
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.media.animation;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import com.threerings.media.image.Mirage;
/**
* Fades an image in or out by varying the alpha level during rendering.
*/
public class FadeImageAnimation extends FadeAnimation
{
/**
* Creates an image fading animation.
*/
public FadeImageAnimation (Mirage image, int x, int y, float alpha, float step, float target)
{
super(new Rectangle(x, y, image.getWidth(), image.getHeight()), alpha, step, target);
_image = image;
}
@Override
protected void paintAnimation (Graphics2D gfx)
{
_image.paint(gfx, _bounds.x, _bounds.y);
}
protected Mirage _image;
}
| lgpl-2.1 |
themnd/sampleTaxes | src/main/java/it/sampleTaxes/processor/Processor.java | 346 | package it.sampleTaxes.processor;
import it.sampleTaxes.orders.Order;
import it.sampleTaxes.receipts.Receipt;
/**
* Processor.
*
* @author mnova
*/
public interface Processor {
/**
* Process an order.
*
* @param order a not null order.
* @return a not null Receipt.
*/
Receipt apply(final Order order);
}
| lgpl-2.1 |
1fechner/FeatureExtractor | sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/query/TwoEntityOneAuditedQueryGenerator.java | 6662 | /*
* 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.envers.internal.entities.mapper.relation.query;
import org.hibernate.envers.configuration.internal.AuditEntitiesConfiguration;
import org.hibernate.envers.internal.entities.mapper.relation.MiddleComponentData;
import org.hibernate.envers.internal.entities.mapper.relation.MiddleIdData;
import org.hibernate.envers.internal.tools.query.Parameters;
import org.hibernate.envers.internal.tools.query.QueryBuilder;
import org.hibernate.envers.strategy.AuditStrategy;
import static org.hibernate.envers.internal.entities.mapper.relation.query.QueryConstants.DEL_REVISION_TYPE_PARAMETER;
import static org.hibernate.envers.internal.entities.mapper.relation.query.QueryConstants.MIDDLE_ENTITY_ALIAS;
import static org.hibernate.envers.internal.entities.mapper.relation.query.QueryConstants.REFERENCED_ENTITY_ALIAS;
import static org.hibernate.envers.internal.entities.mapper.relation.query.QueryConstants.REVISION_PARAMETER;
/**
* Selects data from a relation middle-table and a related non-audited entity.
*
* @author Adam Warski (adam at warski dot org)
* @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com)
*/
public final class TwoEntityOneAuditedQueryGenerator extends AbstractRelationQueryGenerator {
private final String queryString;
private final String queryRemovedString;
public TwoEntityOneAuditedQueryGenerator(
AuditEntitiesConfiguration verEntCfg, AuditStrategy auditStrategy,
String versionsMiddleEntityName, MiddleIdData referencingIdData,
MiddleIdData referencedIdData, boolean revisionTypeInId,
MiddleComponentData... componentData) {
super( verEntCfg, referencingIdData, revisionTypeInId );
/*
* The valid query that we need to create:
* SELECT new list(ee, e) FROM referencedEntity e, middleEntity ee
* WHERE
* (entities referenced by the middle table; id_ref_ed = id of the referenced entity)
* ee.id_ref_ed = e.id_ref_ed AND
* (only entities referenced by the association; id_ref_ing = id of the referencing entity)
* ee.id_ref_ing = :id_ref_ing AND
*
* (the association at revision :revision)
* --> for DefaultAuditStrategy:
* ee.revision = (SELECT max(ee2.revision) FROM middleEntity ee2
* WHERE ee2.revision <= :revision AND ee2.originalId.* = ee.originalId.*)
*
* --> for ValidityAuditStrategy:
* ee.revision <= :revision and (ee.endRevision > :revision or ee.endRevision is null)
*
* AND
*
* (only non-deleted entities and associations)
* ee.revision_type != DEL
*/
final QueryBuilder commonPart = commonQueryPart(
referencedIdData,
versionsMiddleEntityName,
verEntCfg.getOriginalIdPropName()
);
final QueryBuilder validQuery = commonPart.deepCopy();
final QueryBuilder removedQuery = commonPart.deepCopy();
createValidDataRestrictions(
auditStrategy, versionsMiddleEntityName, validQuery, validQuery.getRootParameters(), componentData
);
createValidAndRemovedDataRestrictions( auditStrategy, versionsMiddleEntityName, removedQuery, componentData );
queryString = queryToString( validQuery );
queryRemovedString = queryToString( removedQuery );
}
/**
* Compute common part for both queries.
*/
private QueryBuilder commonQueryPart(
MiddleIdData referencedIdData, String versionsMiddleEntityName,
String originalIdPropertyName) {
final String eeOriginalIdPropertyPath = MIDDLE_ENTITY_ALIAS + "." + originalIdPropertyName;
// SELECT new list(ee) FROM middleEntity ee
final QueryBuilder qb = new QueryBuilder( versionsMiddleEntityName, MIDDLE_ENTITY_ALIAS );
qb.addFrom( referencedIdData.getEntityName(), REFERENCED_ENTITY_ALIAS, false );
qb.addProjection( "new list", MIDDLE_ENTITY_ALIAS + ", " + REFERENCED_ENTITY_ALIAS, null, false );
// WHERE
final Parameters rootParameters = qb.getRootParameters();
// ee.id_ref_ed = e.id_ref_ed
referencedIdData.getPrefixedMapper().addIdsEqualToQuery(
rootParameters, eeOriginalIdPropertyPath, referencedIdData.getOriginalMapper(), REFERENCED_ENTITY_ALIAS
);
// ee.originalId.id_ref_ing = :id_ref_ing
referencingIdData.getPrefixedMapper().addNamedIdEqualsToQuery( rootParameters, originalIdPropertyName, true );
return qb;
}
/**
* Creates query restrictions used to retrieve only actual data.
*/
private void createValidDataRestrictions(
AuditStrategy auditStrategy, String versionsMiddleEntityName, QueryBuilder qb,
Parameters rootParameters, MiddleComponentData... componentData) {
final String revisionPropertyPath = verEntCfg.getRevisionNumberPath();
final String originalIdPropertyName = verEntCfg.getOriginalIdPropName();
final String eeOriginalIdPropertyPath = MIDDLE_ENTITY_ALIAS + "." + originalIdPropertyName;
// (with ee association at revision :revision)
// --> based on auditStrategy (see above)
auditStrategy.addAssociationAtRevisionRestriction(
qb, rootParameters, revisionPropertyPath, verEntCfg.getRevisionEndFieldName(), true,
referencingIdData, versionsMiddleEntityName, eeOriginalIdPropertyPath, revisionPropertyPath,
originalIdPropertyName, MIDDLE_ENTITY_ALIAS, true, componentData
);
// ee.revision_type != DEL
rootParameters.addWhereWithNamedParam( getRevisionTypePath(), "!=", DEL_REVISION_TYPE_PARAMETER );
}
/**
* Create query restrictions used to retrieve actual data and deletions that took place at exactly given revision.
*/
private void createValidAndRemovedDataRestrictions(
AuditStrategy auditStrategy, String versionsMiddleEntityName,
QueryBuilder remQb, MiddleComponentData... componentData) {
final Parameters disjoint = remQb.getRootParameters().addSubParameters( "or" );
// Restrictions to match all valid rows.
final Parameters valid = disjoint.addSubParameters( "and" );
// Restrictions to match all rows deleted at exactly given revision.
final Parameters removed = disjoint.addSubParameters( "and" );
createValidDataRestrictions( auditStrategy, versionsMiddleEntityName, remQb, valid, componentData );
// ee.revision = :revision
removed.addWhereWithNamedParam( verEntCfg.getRevisionNumberPath(), "=", REVISION_PARAMETER );
// ee.revision_type = DEL
removed.addWhereWithNamedParam( getRevisionTypePath(), "=", DEL_REVISION_TYPE_PARAMETER );
}
@Override
protected String getQueryString() {
return queryString;
}
@Override
protected String getQueryRemovedString() {
return queryRemovedString;
}
}
| lgpl-2.1 |
evolute-pt/dbtransfer | src/main/java/pt/evolute/dbtransfer/Config.java | 1892 | package pt.evolute.dbtransfer;
import java.util.Properties;
public class Config implements ConfigurationProperties{
private static Properties PROPS = new Properties();
public static boolean ignoreEmpty()
{
return getValue( ONLY_NOT_EMPTY );
}
public static boolean analyse()
{
return getValue( ANALYSE );
}
private static boolean getValue( String name ) {
return Boolean.parseBoolean( PROPS.getProperty( name, "false" ) );
}
public static void setProperties(Properties p) {
PROPS.putAll( p );
}
public static boolean debug() {
return getValue( DEBUG );
}
public static boolean transfer() {
return getValue( TRANSFER );
}
public static boolean constrain() {
return getValue( CONSTRAIN );
}
public static boolean diff() {
return getValue( DIFF );
}
public static int getParallelThreads()
{
int t = 1;
String s = PROPS.getProperty( TRANSFER_THREADS );
if( s != null && !s.isEmpty() )
{
try
{
t = Integer.parseInt( s );
}
catch( NumberFormatException ex )
{
System.err.println( "Error in property: " + TRANSFER_THREADS + "=" + s );
}
}
return t;
}
public static boolean checkDependencies() {
return getValue( TRANSFER_CHECK_DEPS );
}
public static String getDiffComment() {
return PROPS.getProperty( DIFF_COMMENT );
}
public static boolean escapeUnicode() {
return getValue( TRANSFER_ESCAPE_UNICODE );
}
public static String getDestinationTablePrefix()
{
return PROPS.getProperty( DESTINATION_TABLE_PREFIX, "" );
}
public static String getAnalyseDeleteIfExists()
{
return PROPS.getProperty( ANALYSE_DELETE_IF_EXISTS, "false" );
}
public static String getDiffIgnoreDestinationTableCount()
{
return PROPS.getProperty( DIFF_IGNORE_DESTINATION_TABLE_COUNT, "false" );
}
public static String getDiffUseMD5()
{
return PROPS.getProperty( DIFF_USE_MD5, "true" );
}
}
| lgpl-2.1 |
champtar/fmj-sourceforge-mirror | src.examples.ejmf/ejmf/toolkit/multiplayer/TrackSlider.java | 1447 | package ejmf.toolkit.multiplayer;
import java.awt.Dimension;
import javax.swing.JSlider;
/**
* A visual representation of a Track.
*/
public class TrackSlider extends JSlider {
private int _defaultTrackHeight = 16;
private int trackHeight = _defaultTrackHeight;
private long displayBeginTime,
displayEndTime;
private Track track = null;
/**
* Create a TrackSlider for Track.
*
* @param track Track whose data slider will reflect
*/
public TrackSlider(Track track) {
super(HORIZONTAL, 0, 900, 0);
this.track = track;
setEnabled(false);
setExtent(0);
}
/**
* @return track number of Track slider is displaying.
*/
public int getTrackNumber() {
return track.getTrackNumber();
}
/**
* Identfiy this UI for UIManager.
* @return string representation of UI class ID
*/
public String getUIClassID() {
return "TrackSliderUI";
}
/**
* To simplify GUI so we were able to concentrate
* on JMF code, the slider is a fixed width.
* @return fixed dimesion of a TrackSlider
*/
public Dimension getPreferredSize() {
return new Dimension(900, trackHeight);
}
/**
* This method is over-ridden and rendered a no-op
* to prevent slider from painting a pointed tip
* on thumb.
*/
public void setPaintTicks(boolean flag) {
// Need to squash this so that rectangular
// thumb is drawn...BasicSliderUI wants to
// draw a pointy thumb is ticks are set.
}
}
| lgpl-2.1 |
jochenvdv/checkstyle | src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/NestedTryDepthCheck.java | 2698 | ////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2017 the original author or authors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.checks.coding;
import com.puppycrawl.tools.checkstyle.FileStatefulCheck;
import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
/**
* Restricts nested try-catch-finally blocks to a specified depth (default = 1).
* @author <a href="mailto:simon@redhillconsulting.com.au">Simon Harris</a>
*/
@FileStatefulCheck
public final class NestedTryDepthCheck extends AbstractCheck {
/**
* A key is pointing to the warning message text in "messages.properties"
* file.
*/
public static final String MSG_KEY = "nested.try.depth";
/** Maximum allowed nesting depth. */
private int max = 1;
/** Current nesting depth. */
private int depth;
/**
* Setter for maximum allowed nesting depth.
* @param max maximum allowed nesting depth.
*/
public void setMax(int max) {
this.max = max;
}
@Override
public int[] getDefaultTokens() {
return getAcceptableTokens();
}
@Override
public int[] getAcceptableTokens() {
return new int[] {TokenTypes.LITERAL_TRY};
}
@Override
public int[] getRequiredTokens() {
return getAcceptableTokens();
}
@Override
public void beginTree(DetailAST rootAST) {
depth = 0;
}
@Override
public void visitToken(DetailAST literalTry) {
if (depth > max) {
log(literalTry, MSG_KEY, depth, max);
}
++depth;
}
@Override
public void leaveToken(DetailAST literalTry) {
--depth;
}
}
| lgpl-2.1 |
ME-Corp/MineralEssentials | src/main/java/io/github/mecorp/mineralessentials/api/cofh/api/energy/ItemEnergyContainer.java | 2604 | package io.github.mecorp.mineralessentials.api.cofh.api.energy;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
/**
* Reference implementation of {@link IEnergyContainerItem}. Use/extend this or implement your own.
*
* @author King Lemming
*
*/
public class ItemEnergyContainer extends Item implements IEnergyContainerItem {
protected int capacity;
protected int maxReceive;
protected int maxExtract;
public ItemEnergyContainer() {
}
public ItemEnergyContainer(int capacity) {
this(capacity, capacity, capacity);
}
public ItemEnergyContainer(int capacity, int maxTransfer) {
this(capacity, maxTransfer, maxTransfer);
}
public ItemEnergyContainer(int capacity, int maxReceive, int maxExtract) {
this.capacity = capacity;
this.maxReceive = maxReceive;
this.maxExtract = maxExtract;
}
public ItemEnergyContainer setCapacity(int capacity) {
this.capacity = capacity;
return this;
}
public void setMaxTransfer(int maxTransfer) {
setMaxReceive(maxTransfer);
setMaxExtract(maxTransfer);
}
public void setMaxReceive(int maxReceive) {
this.maxReceive = maxReceive;
}
public void setMaxExtract(int maxExtract) {
this.maxExtract = maxExtract;
}
/* IEnergyContainerItem */
@Override
public int receiveEnergy(ItemStack container, int maxReceive, boolean simulate) {
if (container.stackTagCompound == null) {
container.stackTagCompound = new NBTTagCompound();
}
int energy = container.stackTagCompound.getInteger("Energy");
int energyReceived = Math.min(capacity - energy, Math.min(this.maxReceive, maxReceive));
if (!simulate) {
energy += energyReceived;
container.stackTagCompound.setInteger("Energy", energy);
}
return energyReceived;
}
@Override
public int extractEnergy(ItemStack container, int maxExtract, boolean simulate) {
if (container.stackTagCompound == null || !container.stackTagCompound.hasKey("Energy")) {
return 0;
}
int energy = container.stackTagCompound.getInteger("Energy");
int energyExtracted = Math.min(energy, Math.min(this.maxExtract, maxExtract));
if (!simulate) {
energy -= energyExtracted;
container.stackTagCompound.setInteger("Energy", energy);
}
return energyExtracted;
}
@Override
public int getEnergyStored(ItemStack container) {
if (container.stackTagCompound == null || !container.stackTagCompound.hasKey("Energy")) {
return 0;
}
return container.stackTagCompound.getInteger("Energy");
}
@Override
public int getMaxEnergyStored(ItemStack container) {
return capacity;
}
}
| lgpl-2.1 |
the-realest-stu/Rustic | src/main/java/rustic/common/world/WorldGenIronwoodTree.java | 3516 | package rustic.common.world;
import java.util.Random;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.gen.feature.WorldGenAbstractTree;
import rustic.common.blocks.BlockLeavesRustic;
import rustic.common.blocks.BlockLogRustic;
import rustic.common.blocks.BlockPlanksRustic;
import rustic.common.blocks.ModBlocks;
public class WorldGenIronwoodTree extends WorldGenAbstractTree {
private static final IBlockState LOG = ModBlocks.LOG.getDefaultState().withProperty(BlockLogRustic.VARIANT, BlockPlanksRustic.EnumType.IRONWOOD);
private static final IBlockState LEAF = ModBlocks.LEAVES.getDefaultState().withProperty(BlockLeavesRustic.VARIANT, BlockPlanksRustic.EnumType.IRONWOOD).withProperty(BlockLeavesRustic.CHECK_DECAY, false);
public WorldGenIronwoodTree(boolean notify) {
super(notify);
}
@Override
public boolean generate(World worldIn, Random rand, BlockPos position) {
int i = rand.nextInt(6) + 7;
boolean flag = true;
if (position.getY() >= 1 && position.getY() + i + 1 <= 256) {
for (int j = position.getY(); j <= position.getY() + 1 + i; ++j) {
int k = 1;
if (j == position.getY()) {
k = 0;
}
if (j >= position.getY() + 1 + i - 2) {
k = 2;
}
BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos();
for (int l = position.getX() - k; l <= position.getX() + k && flag; ++l) {
for (int i1 = position.getZ() - k; i1 <= position.getZ() + k && flag; ++i1) {
if (j >= 0 && j < worldIn.getHeight()) {
if (!this.isReplaceable(worldIn, blockpos$mutableblockpos.setPos(l, j, i1))) {
flag = false;
}
} else {
flag = false;
}
}
}
}
if (!flag) {
return false;
} else {
BlockPos down = position.down();
IBlockState state = worldIn.getBlockState(down);
boolean isSoil = state.getBlock().canSustainPlant(state, worldIn, down, net.minecraft.util.EnumFacing.UP, (net.minecraft.block.BlockSapling) Blocks.SAPLING);
if (isSoil && position.getY() < worldIn.getHeight() - i - 1) {
state.getBlock().onPlantGrow(state, worldIn, down, position);
for (int i2 = position.getY() - 3 + i; i2 <= position.getY() + i; ++i2) {
int k2 = i2 - (position.getY() + i);
int l2 = 1 - k2 / 2;
for (int i3 = position.getX() - l2; i3 <= position.getX() + l2; ++i3) {
int j1 = i3 - position.getX();
for (int k1 = position.getZ() - l2; k1 <= position.getZ() + l2; ++k1) {
int l1 = k1 - position.getZ();
if (Math.abs(j1) != l2 || Math.abs(l1) != l2 || rand.nextInt(2) != 0 && k2 != 0) {
BlockPos blockpos = new BlockPos(i3, i2, k1);
IBlockState state2 = worldIn.getBlockState(blockpos);
if (state2.getBlock().isAir(state2, worldIn, blockpos) || state2.getBlock().isAir(state2, worldIn, blockpos)) {
this.setBlockAndNotifyAdequately(worldIn, blockpos, LEAF);
}
}
}
}
}
for (int j2 = 0; j2 < i; ++j2) {
BlockPos upN = position.up(j2);
IBlockState state2 = worldIn.getBlockState(upN);
if (state2.getBlock().isAir(state2, worldIn, upN) || state2.getBlock().isLeaves(state2, worldIn, upN)) {
this.setBlockAndNotifyAdequately(worldIn, position.up(j2), LOG);
}
}
return true;
} else {
return false;
}
}
} else {
return false;
}
}
}
| lgpl-2.1 |
niithub/angelonline | dao/src/main/java/com/njbd/ao/pojo/CourseType.java | 2425 | package com.njbd.ao.pojo;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;
@Table(name = "t_coursetype")
public class CourseType {
private String coursetypeId;
private String coursetypeName;
private String coursetypeLogo;
private Date createTime;
private Date updateTime;
@Id
@GeneratedValue(generator = "generator")
@Column(unique = true, nullable = false)
public String getCoursetypeId() {
return coursetypeId;
}
public void setCoursetypeId(String coursetypeId) {
this.coursetypeId = coursetypeId == null ? null : coursetypeId.trim();
}
@Column(name = "coursetype_name")
public String getCoursetypeName() {
return coursetypeName;
}
public void setCoursetypeName(String coursetypeName) {
this.coursetypeName = coursetypeName == null ? null : coursetypeName.trim();
}
@Column(name = "coursetype_logo")
public String getCoursetypeLogo() {
return coursetypeLogo;
}
public void setCoursetypeLogo(String coursetypeLogo) {
this.coursetypeLogo = coursetypeLogo == null ? null : coursetypeLogo.trim();
}
@Column(name = "create_time")
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Column(name = "update_time")
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public CourseType() {
}
public CourseType(String coursetypeId, String coursetypeName, String coursetypeLogo,
Date createTime, Date updateTime) {
this.coursetypeId = coursetypeId;
this.coursetypeName = coursetypeName;
this.coursetypeLogo = coursetypeLogo;
this.createTime = createTime;
this.updateTime = updateTime;
}
@Override
public String toString() {
return "CourseType{" +
"coursetypeId='" + coursetypeId + '\'' +
", coursetypeName='" + coursetypeName + '\'' +
", coursetypeLogo='" + coursetypeLogo + '\'' +
", createTime=" + createTime +
", updateTime=" + updateTime +
'}';
}
} | lgpl-2.1 |
cogtool/cogtool | java/edu/cmu/cs/hcii/cogtool/util/Alerter.java | 20008 | /*******************************************************************************
* CogTool Copyright Notice and Distribution Terms
* CogTool 1.3, Copyright (c) 2005-2013 Carnegie Mellon University
* This software is distributed under the terms of the FSF Lesser
* Gnu Public License (see LGPL.txt).
*
* CogTool 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.
*
* CogTool 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 CogTool; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* CogTool makes use of several third-party components, with the
* following notices:
*
* Eclipse SWT version 3.448
* Eclipse GEF Draw2D version 3.2.1
*
* Unless otherwise indicated, all Content made available by the Eclipse
* Foundation is provided to you under the terms and conditions of the Eclipse
* Public License Version 1.0 ("EPL"). A copy of the EPL is provided with this
* Content and is also available at http://www.eclipse.org/legal/epl-v10.html.
*
* CLISP version 2.38
*
* Copyright (c) Sam Steingold, Bruno Haible 2001-2006
* This software is distributed under the terms of the FSF Gnu Public License.
* See COPYRIGHT file in clisp installation folder for more information.
*
* ACT-R 6.0
*
* Copyright (c) 1998-2007 Dan Bothell, Mike Byrne, Christian Lebiere &
* John R Anderson.
* This software is distributed under the terms of the FSF Lesser
* Gnu Public License (see LGPL.txt).
*
* Apache Jakarta Commons-Lang 2.1
*
* This product contains software developed by the Apache Software Foundation
* (http://www.apache.org/)
*
* jopt-simple version 1.0
*
* Copyright (c) 2004-2013 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Mozilla XULRunner 1.9.0.5
*
* 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 J2SE(TM) Java Runtime Environment version 5.0
*
* Copyright 2009 Sun Microsystems, Inc., 4150
* Network Circle, Santa Clara, California 95054, U.S.A. All
* rights reserved. U.S.
* See the LICENSE file in the jre folder for more information.
******************************************************************************/
package edu.cmu.cs.hcii.cogtool.util;
import java.util.ArrayList;
import java.util.EventObject;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
/**
* Standard implementation for providing semantic notification to an observer
* of a specific change to an observed subject instance.
*
* @author mlh
* @see IAlerter
*/
public class Alerter implements IAlerter
{
/**
* Support class for enumerating <code>AlertHandlerEntry</code> instances
* such that the <code>eventClass</code> value of each returned instance
* will "inherit" or "be assignable to" the given <code>eventClass</code>.
* <p>
* Enumeration progresses by examining each entry associated with the
* given object to determine if it subsumes the given
* <code>eventClass</code>. That is, the given <code>alertType</code>
* parameter must "inherit" (or "be assignable to") the
* <code>eventClass</code> value of each <code>AlertHandlerEntry</code>
* instance enumerated. When one is found during <code>hasNext</code>,
* it is "remembered" and returned by the subsequent <code>next</code>
* call.
*
* @author mlh
*/
protected static class AlertHandlerIterator implements Iterator<Alerter.AlertHandlerEntry>
{
/**
* The Java class that represents the semantic change;
* enumerated <code>AlertHandlerEntry</code> instances must have a
* <code>eventClass</code> value that subsumes this class.
*/
protected Class<? extends EventObject> alertClass;
/**
* An iterator that will enumerate all handlers associated with
* the <code>Alerter</code> object.
*/
protected Iterator<Alerter.AlertHandlerEntry> allHandlers;
/**
* The last found <code>AlertHandlerEntry</code> instance
* that satisfies the constraint that its <code>eventClass</code>
* value subsumes <code>alertClass</code>.
*/
protected Alerter.AlertHandlerEntry nextEntry;
/**
* Initialize the iteration.
*
* @param alertType the class of the semantic change of interest
* @param alertAllHandlers the iterator of all handlers associated
* with the <code>Alerter</code> object
* @author mlh
*/
public AlertHandlerIterator(Class<? extends EventObject> alertType,
Iterator<Alerter.AlertHandlerEntry> alertAllHandlers)
{
alertClass = alertType;
allHandlers = alertAllHandlers;
nextEntry = null;
}
/**
* Determine if another <code>AlertHandlerEntry</code> instances
* that satisfies the constraint is yet to be enumerated.
*
* @return true iff an instance has been found and not yet
* fetched by a call to <code>next</code> or another
* satisfying instance is enumerated by the iterator
* that generates all handler entries
* @author mlh
*/
public boolean hasNext()
{
// Only need to search if the last valid entry was consumed.
if (nextEntry == null) {
while (allHandlers.hasNext()) {
Alerter.AlertHandlerEntry entry = allHandlers.next();
// Try to find another handler whose associated class
// subsumes the given <code>alertClass</code>.
// That is, the semantic change class "inherits" or
// "is assignable to" the class associated with the
// alert handler.
if (entry.eventClass.isAssignableFrom(alertClass)) {
nextEntry = entry;
return true; // Found the next one
}
}
return false; // No more left
}
return true; // Haven't consumed the last one yet
}
/**
* Returns the next <code>AlertHandlerEntry</code> instance
* containing a handler that would be invoked if a semantic change
* of the given class would be made.
* <p>
* According to the specification of <code>Iterator</code>,
* this method raises <code>NoSuchElementException</code>
* if there are no more entries to enumerate. Thus, <code>next</code>
* should only be called after a successful (that is,
* <code>true</code>) return of a call to <code>hasNext</code>.
*
* @return the next <code>AlertHandlerEntry</code> instance containing
* a handler that would be invoked if a semantic change
* of the given class would be made
* @exception <code>NoSuchElementException</code> if no more entries
* exist to enumerate
* @author mlh
* @see java.util.Iterator
*/
public Alerter.AlertHandlerEntry next()
{
if (hasNext()) {
Alerter.AlertHandlerEntry returnValue = nextEntry;
nextEntry = null; // indicate this one has been consumed
return returnValue;
}
throw new NoSuchElementException();
}
/**
* Remove the last enumerated <code>AlertHandlerEntry</code> instance
* from the associated collection; NOT IMPLEMENTED.
*
* @exception <code>UnsupportedOperationException</code> as this
* method is not implemented.
* @author mlh
* @see java.util.Iterator
*/
public void remove()
{
// Not implemented!
throw new UnsupportedOperationException();
}
}
/**
* When enumerating the objects that will handle the notification
* of a semantic change (specific or not), the objects generated
* are of this type. It associates the handler object with
* the subclass of <code>EventObject</code> that reflects the
* semantic change of interest.
*
* @author mlh
*/
public static class AlertHandlerEntry
{
public Object observer;
public Class<? extends EventObject> eventClass;
public AlertHandler handler;
/**
* Initialize the association of handler with the class of the semantic
* change in which it is interested.
*
* @param obs the observer of the semantic change
* @param evtClass the class of the semantic change of interest
* @param h the handler to be notified of the change
* @author mlh
*/
public AlertHandlerEntry(Object obs,
Class<? extends EventObject> evtClass,
AlertHandler h)
{
observer = obs;
eventClass = evtClass;
handler = h;
}
}
/**
* To hold the handlers that will respond to semantic changes in this
* object.
*/
protected List<Alerter.AlertHandlerEntry> handlers = null;
/**
* Add a handler to observe semantic changes raised by this instance
* of the specified semantic type (a subclass of <code>EventObject</code>).
* <p>
* The same handler may be added more than once; if so, it will be
* notified more than once.
* <p>
* Handlers will be invoked in the same order as they were registered.
*
* @param observer the object interested in the semantic event
* @param eventClass the class of the semantic change of interest
* @param handler the handler to be notified of the change
* @param noDuplicates whether to prevent duplicate entries
* @author mlh
*/
public void addHandler(Object observer,
Class<? extends EventObject> eventClass,
AlertHandler handler,
boolean noDuplicates)
{
if (handlers == null) {
handlers = new ArrayList<Alerter.AlertHandlerEntry>();
}
else if (noDuplicates) {
for (int i = 0; i < handlers.size(); i++) {
Alerter.AlertHandlerEntry entry =
handlers.get(i);
if ((entry.observer == observer) &&
(entry.eventClass == eventClass) &&
(entry.handler == handler))
{
return;
}
}
}
handlers.add(new Alerter.AlertHandlerEntry(observer,
eventClass,
handler));
}
/**
* Add a handler to observe semantic changes raised by this instance
* of the specified semantic type (a subclass of <code>EventObject</code>).
* <p>
* The same handler may be added more than once; if so, it will be
* notified more than once.
* <p>
* Handlers will be invoked in the same order as they were registered.
* <p>
* The list holding <code>AlertHandlerEntry</code> instances
* is created only when needed.
* <p>
* Equivalent to invoking 4-parameter addHandler with noDuplicates = true.
*
* @param observer the object interested in the semantic event
* @param eventClass the class of the semantic change of interest
* @param handler the handler to be notified of the change
* @author mlh
*/
public void addHandler(Object observer,
Class<? extends EventObject> eventClass,
AlertHandler handler)
{
addHandler(observer, eventClass, handler, true);
}
/**
* Remove the first registration of the given handler as specified
* to observe semantic changes raised by this instance
* of the specified semantic type (a subclass of <code>EventObject</code>).
* <p>
* To remove all registrations, repeat the call to
* <code>removeHandler</code> until it returns <code>false</code>.
*
* @param eventClass the class of the semantic change of interest
* @param handler the handler to be notified of the change
* @return true iff the remove was successful
* @author mlh
*/
public boolean removeHandler(Class<? extends EventObject> eventClass, AlertHandler handler)
{
Iterator<Alerter.AlertHandlerEntry> allHandlers = getHandlers(); // enumerate all handlers
while (allHandlers.hasNext()) {
Alerter.AlertHandlerEntry entry = allHandlers.next();
if ((entry.eventClass == eventClass) && (entry.handler == handler))
{
// Removal works because all handlers are enumerated
allHandlers.remove();
return true;
}
}
return false;
}
// TODO Currently it's easy to accidentally leak AlertHandlers, since
// the code that installs them has to be careful to arrange to
// remove them. It seems likely that using weak collections here
// might make it possible for them to be automagically GCed. This
// should be investigated.
/**
* Remove all registered handlers for observing semantic changes
* associated with the given observer.
*
* @param observer the object interested in the semantic event
* @author mlh
*/
public void removeAllHandlers(Object observer)
{
Iterator<Alerter.AlertHandlerEntry> allHandlers = getHandlers(); // enumerate all handlers
while (allHandlers.hasNext()) {
Alerter.AlertHandlerEntry entry = allHandlers.next();
if (entry.observer == observer) {
allHandlers.remove();
}
}
}
/**
* Enumerate all the handler-type pairs registered on this instance.
* <p>
* The returned iterator instance will enumerate
* <code>AlertHandlerEntry</code> instances.
*
* @return an iterator that enumerates all handlers registered
* on this instance
* @author mlh
*/
public Iterator<Alerter.AlertHandlerEntry> getHandlers()
{
if (handlers != null) {
return handlers.iterator();
}
// Used because there are no handlers
return new EmptyIterator<Alerter.AlertHandlerEntry>();
}
/**
* Enumerate all the handler-type pairs registered on this instance
* that would be invoked if a semantic change of the given type occurred.
* <p>
* The returned iterator instance will enumerate
* <code>AlertHandlerEntry</code> instances.
* <p>
* Note that the given <code>eventClass</code> parameter will "inherit"
* (or "be assignable to") the <code>eventClass</code> value of each
* <code>AlertHandlerEntry</code> instance enumerated.
*
* @param eventClass the class of the semantic change of interest
* @return an iterator that enumerates handlers registered
* to be notified of semantic changes of the
* given "type"
* @author mlh
*/
public Iterator<Alerter.AlertHandlerEntry> getHandlers(Class<? extends EventObject> eventClass)
{
if (handlers != null) {
// We need to cache all applicable handlers based on the requested
// eventClass in case some handler is removed from the set of
// handlers associated with this object by one of the "earlier"
// handler executions.
List<Alerter.AlertHandlerEntry> applicableHandlers = new ArrayList<Alerter.AlertHandlerEntry>();
Iterator<Alerter.AlertHandlerEntry> allHandlers = handlers.iterator();
while (allHandlers.hasNext()) {
Alerter.AlertHandlerEntry entry = allHandlers.next();
// Try to find another handler whose associated class
// subsumes the given <code>alertClass</code>.
// That is, the semantic change class "inherits" or
// "is assignable to" the class associated with the
// alert handler.
if (entry.eventClass.isAssignableFrom(eventClass)) {
applicableHandlers.add(entry);
}
}
return applicableHandlers.iterator();
// return new AlertHandlerIterator(eventClass,
// this.handlers.iterator());
}
// Used because there are no handlers
return new EmptyIterator<Alerter.AlertHandlerEntry>();
}
/**
* Notify all handlers that are interested in the given semantic change.
* <p>
* Only those handlers associated with <code>EventObject</code> subclasses
* that the given <code>alert</code> "inherits" (or "could be assigned to")
* will be notified.
* <p>
* Each handler is notified by invoking its <code>handleAlert</code>
* method with the given semantic change data.
*
* @param alert the data reflecting the semantic change
* @author mlh
*/
public void raiseAlert(EventObject alert)
{
Iterator<Alerter.AlertHandlerEntry> alertHandlers = getHandlers(alert.getClass());
while (alertHandlers.hasNext()) {
Alerter.AlertHandlerEntry entry = alertHandlers.next();
entry.handler.handleAlert(alert);
}
}
}
| lgpl-2.1 |
Metaswitch/jitsi | test/net/java/sip/communicator/slick/protocol/sip/TestAccountInstallation.java | 9441 | /*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.slick.protocol.sip;
import java.util.*;
import junit.framework.*;
import net.java.sip.communicator.impl.protocol.sip.*;
import net.java.sip.communicator.service.protocol.*;
import org.osgi.framework.*;
public class TestAccountInstallation
extends TestCase
{
/**
* Creates the test with the specified method name.
* @param name the name of the method to execute.
*/
public TestAccountInstallation(String name)
{
super(name);
}
/**
* JUnit setup method.
* @throws Exception in case anything goes wrong.
*/
@Override
protected void setUp() throws Exception
{
super.setUp();
}
/**
* JUnit teardown method.
* @throws Exception in case anything goes wrong.
*/
@Override
protected void tearDown() throws Exception
{
super.tearDown();
}
/**
* Installs an account and verifies whether the installation has gone well.
*/
public void testInstallAccount()
{
// first obtain a reference to the provider factory
ServiceReference[] serRefs = null;
String osgiFilter = "(" + ProtocolProviderFactory.PROTOCOL
+ "="+ProtocolNames.SIP+")";
try{
serRefs = SipSlickFixture.bc.getServiceReferences(
ProtocolProviderFactory.class.getName(), osgiFilter);
}
catch (InvalidSyntaxException ex)
{
//this really shouldhn't occur as the filter expression is static.
fail(osgiFilter + " is not a valid osgi filter");
}
assertTrue(
"Failed to find a provider factory service for protocol SIP",
serRefs != null && serRefs.length > 0);
//Keep the reference for later usage.
ProtocolProviderFactory sipProviderFactory = (ProtocolProviderFactory)
SipSlickFixture.bc.getService(serRefs[0]);
//make sure the account is empty
assertTrue("There was an account registered with the account mananger "
+"before we've installed any",
sipProviderFactory.getRegisteredAccounts().size() == 0);
//Prepare the properties of the first sip account.
Hashtable<String,String> sipAccount1Properties = getAccountProperties(
SipProtocolProviderServiceLick.ACCOUNT_1_PREFIX);
Hashtable<String, String> sipAccount2Properties = getAccountProperties(
SipProtocolProviderServiceLick.ACCOUNT_2_PREFIX);
//try to install an account with a null account id
try{
sipProviderFactory.installAccount(
null, sipAccount1Properties);
fail("installing an account with a null account id must result "
+"in a NullPointerException");
}catch(NullPointerException exc)
{
//that's what had to happen
}
//now really install the accounts
sipProviderFactory.installAccount(
sipAccount1Properties.get(ProtocolProviderFactory.USER_ID)
, sipAccount1Properties);
sipProviderFactory.installAccount(
sipAccount2Properties.get(ProtocolProviderFactory.USER_ID)
, sipAccount2Properties);
//try to install one of the accounts one more time and verify that an
//excepion is thrown.
try{
sipProviderFactory.installAccount(
sipAccount1Properties.get(ProtocolProviderFactory.USER_ID)
, sipAccount1Properties);
fail("An IllegalStateException must be thrown when trying to "+
"install a duplicate account");
}catch(IllegalStateException exc)
{
//that's what supposed to happen.
}
//Verify that the provider factory is aware of our installation
assertTrue(
"The newly installed account was not in the acc man's "
+"registered accounts!",
sipProviderFactory.getRegisteredAccounts().size() == 2);
//Verify protocol providers corresponding to the new account have
//been properly registered with the osgi framework.
osgiFilter =
"(&("+ProtocolProviderFactory.PROTOCOL +"="+ProtocolNames.SIP+")"
+"(" + ProtocolProviderFactory.USER_ID
+ "=" + sipAccount1Properties.get(
ProtocolProviderFactory.USER_ID)
+ "))";
try
{
serRefs = SipSlickFixture.bc.getServiceReferences(
ProtocolProviderService.class.getName(),
osgiFilter);
}
catch (InvalidSyntaxException ex)
{
//this really shouldhn't occur as the filter expression is static.
fail(osgiFilter + "is not a valid osgi filter");
}
assertTrue("A SIP protocol provider was apparently not installed as "
+ "requested."
, serRefs != null && serRefs.length > 0);
Object icqProtocolProvider
= SipSlickFixture.bc.getService(serRefs[0]);
assertTrue("The installed protocol provider does not implement "
+ "the protocol provider service."
,icqProtocolProvider instanceof ProtocolProviderService);
}
/**
* Returns all properties necessary for the intialization of the account
* with <tt>accountPrefix</tt>.
* @param accountPrefix the prefix contained by all property names for the
* the account we'd like to initialized
* @return a Hashtable that can be used when creating the account in a
* protocol provider factory.
*/
private Hashtable<String, String> getAccountProperties(String accountPrefix)
{
Hashtable<String, String> table = new Hashtable<String, String>();
String userID = System.getProperty(
accountPrefix + ProtocolProviderFactory.USER_ID, null);
assertNotNull(
"The system property named "
+ accountPrefix + ProtocolProviderFactory.USER_ID
+" has to tontain a valid SIP address that could be used during "
+"SIP Communicator's tests."
, userID);
table.put(ProtocolProviderFactory.USER_ID, userID);
String displayName = System.getProperty(
accountPrefix + ProtocolProviderFactory.DISPLAY_NAME, null);
assertNotNull(
"The system property named "
+ accountPrefix + ProtocolProviderFactory.DISPLAY_NAME
+ " has to contain a valid name string that could be used during "
+ "SIP Communicator's tests."
, displayName);
table.put(ProtocolProviderFactory.DISPLAY_NAME, displayName);
String passwd = System.getProperty(
accountPrefix + ProtocolProviderFactory.PASSWORD, null );
assertNotNull(
"The system property named "
+ accountPrefix + ProtocolProviderFactory.PASSWORD
+" has to contain the password corresponding to the account "
+ "specified in "
+ accountPrefix + ProtocolProviderFactory.USER_ID
, passwd);
table.put(ProtocolProviderFactory.PASSWORD, passwd);
String serverAddress = System.getProperty(
accountPrefix + ProtocolProviderFactory.SERVER_ADDRESS, null );
assertNotNull(
"The system property named "
+ accountPrefix + ProtocolProviderFactory.SERVER_ADDRESS
+" has to contain a valid server address to use for testing."
, serverAddress);
table.put(ProtocolProviderFactory.SERVER_ADDRESS, serverAddress);
String serverPort = System.getProperty(
accountPrefix + ProtocolProviderFactory.SERVER_PORT, null );
if(serverPort != null)
{
table.put(ProtocolProviderFactory.SERVER_PORT, serverPort);
}
String proxyAddress = System.getProperty(
accountPrefix + ProtocolProviderFactory.PROXY_ADDRESS, null );
if(serverPort != null)
{
table.put(ProtocolProviderFactory.PROXY_ADDRESS, proxyAddress);
String proxyPort = System.getProperty(
accountPrefix + ProtocolProviderFactory.PROXY_PORT, null );
if(proxyPort != null)
{
table.put(ProtocolProviderFactory.PROXY_PORT, proxyPort);
}
}
String xCapServerUri = System.getProperty(accountPrefix +
SipProtocolProviderServiceLick.XCAP_SERVER_PROPERTY_NAME, null);
if (xCapServerUri != null)
{
table.put(ServerStoredContactListSipImpl.XCAP_ENABLE,
Boolean.TRUE.toString());
table.put(ServerStoredContactListSipImpl.XCAP_USE_SIP_CREDETIALS,
Boolean.TRUE.toString());
table.put(ServerStoredContactListSipImpl.XCAP_USE_SIP_CREDETIALS,
Boolean.TRUE.toString());
table.put(ServerStoredContactListSipImpl.XCAP_SERVER_URI,
xCapServerUri);
}
table.put(ProtocolProviderFactory.FORCE_P2P_MODE,
Boolean.FALSE.toString());
return table;
}
}
| lgpl-2.1 |
andyglow/binxml | src/org/binxml/impl/model/extern/AbstractExternalizer.java | 505 | package org.binxml.impl.model.extern;
import org.binxml.impl.CodeContext;
import org.binxml.impl.IExternalizable;
import org.binxml.impl.model.IComposite;
/**
* @author andy
* @creationDate on 21.07.2004
*/
public abstract class AbstractExternalizer implements IExternalizable {
protected IComposite composite;
protected CodeContext context;
public AbstractExternalizer(IComposite comp, CodeContext context) {
this.composite = comp;
this.context= context;
}
}
| lgpl-2.1 |
huasanyelao/lucene1.0 | com/lucene/queryParser/SimpleCharStream.java | 11703 | /* Generated By:JavaCC: Do not edit this line. SimpleCharStream.java Version 5.0 */
/* JavaCCOptions:STATIC=false,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */
package com.lucene.queryParser;
/**
* An implementation of interface CharStream, where the stream is assumed to
* contain only ASCII characters (without unicode processing).
*/
public class SimpleCharStream
{
/** Whether parser is static. */
public static final boolean staticFlag = false;
int bufsize;
int available;
int tokenBegin;
/** Position in buffer. */
public int bufpos = -1;
protected int bufline[];
protected int bufcolumn[];
protected int column = 0;
protected int line = 1;
protected boolean prevCharIsCR = false;
protected boolean prevCharIsLF = false;
protected java.io.Reader inputStream;
protected char[] buffer;
protected int maxNextCharInd = 0;
protected int inBuf = 0;
protected int tabSize = 8;
protected void setTabSize(int i) { tabSize = i; }
protected int getTabSize(int i) { return tabSize; }
protected void ExpandBuff(boolean wrapAround)
{
char[] newbuffer = new char[bufsize + 2048];
int newbufline[] = new int[bufsize + 2048];
int newbufcolumn[] = new int[bufsize + 2048];
try
{
if (wrapAround)
{
System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos);
buffer = newbuffer;
System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos);
bufline = newbufline;
System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos);
bufcolumn = newbufcolumn;
maxNextCharInd = (bufpos += (bufsize - tokenBegin));
}
else
{
System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
buffer = newbuffer;
System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
bufline = newbufline;
System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
bufcolumn = newbufcolumn;
maxNextCharInd = (bufpos -= tokenBegin);
}
}
catch (Throwable t)
{
throw new Error(t.getMessage());
}
bufsize += 2048;
available = bufsize;
tokenBegin = 0;
}
protected void FillBuff() throws java.io.IOException
{
if (maxNextCharInd == available)
{
if (available == bufsize)
{
if (tokenBegin > 2048)
{
bufpos = maxNextCharInd = 0;
available = tokenBegin;
}
else if (tokenBegin < 0)
bufpos = maxNextCharInd = 0;
else
ExpandBuff(false);
}
else if (available > tokenBegin)
available = bufsize;
else if ((tokenBegin - available) < 2048)
ExpandBuff(true);
else
available = tokenBegin;
}
int i;
try {
if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1)
{
inputStream.close();
throw new java.io.IOException();
}
else
maxNextCharInd += i;
return;
}
catch(java.io.IOException e) {
--bufpos;
backup(0);
if (tokenBegin == -1)
tokenBegin = bufpos;
throw e;
}
}
/** Start. */
public char BeginToken() throws java.io.IOException
{
tokenBegin = -1;
char c = readChar();
tokenBegin = bufpos;
return c;
}
protected void UpdateLineColumn(char c)
{
column++;
if (prevCharIsLF)
{
prevCharIsLF = false;
line += (column = 1);
}
else if (prevCharIsCR)
{
prevCharIsCR = false;
if (c == '\n')
{
prevCharIsLF = true;
}
else
line += (column = 1);
}
switch (c)
{
case '\r' :
prevCharIsCR = true;
break;
case '\n' :
prevCharIsLF = true;
break;
case '\t' :
column--;
column += (tabSize - (column % tabSize));
break;
default :
break;
}
bufline[bufpos] = line;
bufcolumn[bufpos] = column;
}
/** Read a character. */
public char readChar() throws java.io.IOException
{
if (inBuf > 0)
{
--inBuf;
if (++bufpos == bufsize)
bufpos = 0;
return buffer[bufpos];
}
if (++bufpos >= maxNextCharInd)
FillBuff();
char c = buffer[bufpos];
UpdateLineColumn(c);
return c;
}
@Deprecated
/**
* @deprecated
* @see #getEndColumn
*/
public int getColumn() {
return bufcolumn[bufpos];
}
@Deprecated
/**
* @deprecated
* @see #getEndLine
*/
public int getLine() {
return bufline[bufpos];
}
/** Get token end column number. */
public int getEndColumn() {
return bufcolumn[bufpos];
}
/** Get token end line number. */
public int getEndLine() {
return bufline[bufpos];
}
/** Get token beginning column number. */
public int getBeginColumn() {
return bufcolumn[tokenBegin];
}
/** Get token beginning line number. */
public int getBeginLine() {
return bufline[tokenBegin];
}
/** Backup a number of characters. */
public void backup(int amount) {
inBuf += amount;
if ((bufpos -= amount) < 0)
bufpos += bufsize;
}
/** Constructor. */
public SimpleCharStream(java.io.Reader dstream, int startline,
int startcolumn, int buffersize)
{
inputStream = dstream;
line = startline;
column = startcolumn - 1;
available = bufsize = buffersize;
buffer = new char[buffersize];
bufline = new int[buffersize];
bufcolumn = new int[buffersize];
}
/** Constructor. */
public SimpleCharStream(java.io.Reader dstream, int startline,
int startcolumn)
{
this(dstream, startline, startcolumn, 4096);
}
/** Constructor. */
public SimpleCharStream(java.io.Reader dstream)
{
this(dstream, 1, 1, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.Reader dstream, int startline,
int startcolumn, int buffersize)
{
inputStream = dstream;
line = startline;
column = startcolumn - 1;
if (buffer == null || buffersize != buffer.length)
{
available = bufsize = buffersize;
buffer = new char[buffersize];
bufline = new int[buffersize];
bufcolumn = new int[buffersize];
}
prevCharIsLF = prevCharIsCR = false;
tokenBegin = inBuf = maxNextCharInd = 0;
bufpos = -1;
}
/** Reinitialise. */
public void ReInit(java.io.Reader dstream, int startline,
int startcolumn)
{
ReInit(dstream, startline, startcolumn, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.Reader dstream)
{
ReInit(dstream, 1, 1, 4096);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,
int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException
{
this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream, int startline,
int startcolumn, int buffersize)
{
this(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,
int startcolumn) throws java.io.UnsupportedEncodingException
{
this(dstream, encoding, startline, startcolumn, 4096);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream, int startline,
int startcolumn)
{
this(dstream, startline, startcolumn, 4096);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException
{
this(dstream, encoding, 1, 1, 4096);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream)
{
this(dstream, 1, 1, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream, String encoding, int startline,
int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException
{
ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream, int startline,
int startcolumn, int buffersize)
{
ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException
{
ReInit(dstream, encoding, 1, 1, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream)
{
ReInit(dstream, 1, 1, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream, String encoding, int startline,
int startcolumn) throws java.io.UnsupportedEncodingException
{
ReInit(dstream, encoding, startline, startcolumn, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream, int startline,
int startcolumn)
{
ReInit(dstream, startline, startcolumn, 4096);
}
/** Get token literal value. */
public String GetImage()
{
if (bufpos >= tokenBegin)
return new String(buffer, tokenBegin, bufpos - tokenBegin + 1);
else
return new String(buffer, tokenBegin, bufsize - tokenBegin) +
new String(buffer, 0, bufpos + 1);
}
/** Get the suffix. */
public char[] GetSuffix(int len)
{
char[] ret = new char[len];
if ((bufpos + 1) >= len)
System.arraycopy(buffer, bufpos - len + 1, ret, 0, len);
else
{
System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0,
len - bufpos - 1);
System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1);
}
return ret;
}
/** Reset buffer when finished. */
public void Done()
{
buffer = null;
bufline = null;
bufcolumn = null;
}
/**
* Method to adjust line and column numbers for the start of a token.
*/
public void adjustBeginLineColumn(int newLine, int newCol)
{
int start = tokenBegin;
int len;
if (bufpos >= tokenBegin)
{
len = bufpos - tokenBegin + inBuf + 1;
}
else
{
len = bufsize - tokenBegin + bufpos + 1 + inBuf;
}
int i = 0, j = 0, k = 0;
int nextColDiff = 0, columnDiff = 0;
while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize])
{
bufline[j] = newLine;
nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j];
bufcolumn[j] = newCol + columnDiff;
columnDiff = nextColDiff;
i++;
}
if (i < len)
{
bufline[j] = newLine++;
bufcolumn[j] = newCol + columnDiff;
while (i++ < len)
{
if (bufline[j = start % bufsize] != bufline[++start % bufsize])
bufline[j] = newLine++;
else
bufline[j] = newLine;
}
}
line = bufline[j];
column = bufcolumn[j];
}
}
/* JavaCC - OriginalChecksum=3c0f3cb6bc7b7b3cd6fc06b4707c5e05 (do not edit this line) */
| lgpl-2.1 |
cacheonix/cacheonix-core | annotations/test/src/org/cacheonix/impl/transformer/CacheonixAnnotationsCombinedTest.java | 11069 | /**
*
*/
/*
* Cacheonix Systems licenses this file to You under the LGPL 2.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.cacheonix.org/products/cacheonix/license-lgpl-2.1.htm
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cacheonix.impl.transformer;
import java.io.IOException;
import java.math.BigDecimal;
import org.cacheonix.Cacheonix;
import org.cacheonix.cache.Cache;
import org.cacheonix.cache.ConfigurationException;
import org.cacheonix.impl.annotations.tests.CacheAnnotatedTest;
import junit.framework.TestCase;
/**
*
*/
public class CacheonixAnnotationsCombinedTest extends TestCase {
private final static String cacheName = "org.cacheonix.impl.annotations.tests.CacheAnnotatedTest";
public void testGetItem() throws ConfigurationException, IOException {
final CacheAnnotatedTest tst = new CacheAnnotatedTest();
final String key = "three";
final String valOne = tst.getItem(key);
// Cache cache =
// Cacheonix.getInstance("test_cacheonix_annotations_config.xml").getCache("org.cacheonix.impl.annotations.tests.CacheAnnotatedTest");
final Cache cache = Cacheonix.getInstance(
"test_cacheonix_annotations_config.xml").getCache(cacheName);
assertNotNull(cache);
// org/cacheonix/impl/annotations/tests/CacheAnnotatedTestgetNothing()Ljava/lang/String;
// String strSyntheticKey = tst.getClass().getName().replace(".", "/") +
// "getItem" + "(Ljava/lang/String;)Ljava/lang/String;";
final String strSyntheticKey = cacheName;
final GeneratedKey keyX = new GeneratedKey(GeneratedKey
.addKeyElement(strSyntheticKey), GeneratedKey
.addKeyElement(key));
final Object valCheck = cache.get(keyX);
assertEquals(valOne, valCheck.toString());
}
public void testGet3Item() throws ConfigurationException, IOException {
final CacheAnnotatedTest tst = new CacheAnnotatedTest();
final String key1 = "three";
final String key2 = "three";
final String key3 = "three";
final String valOne = tst.get3Items(key1, key2, key3);
final Cache cache = Cacheonix.getInstance(
"test_cacheonix_annotations_config.xml").getCache(cacheName);
assertNotNull(cache);
// String strSyntheticKey = tst.getClass().getName().replace(".", "/") +
// "get3Items" +
// "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;";
final String strSyntheticKey = cacheName;
final GeneratedKey keyX = new GeneratedKey(GeneratedKey
.addKeyElement(strSyntheticKey), GeneratedKey
.addKeyElement(key1), GeneratedKey.addKeyElement(key2),
GeneratedKey.addKeyElement(key3));
final Object valCheck = cache.get(keyX);
assertEquals(valOne, valCheck.toString());
}
public void testGetMoreThanFiveArgsTest() throws ConfigurationException,
IOException {
final CacheAnnotatedTest tst = new CacheAnnotatedTest();
final int ikey1 = 252525;
final double dkey2 = 345678.9876D;
final String key3 = "teen";
final BigDecimal ke4 = new BigDecimal(345);
final double dke5 = 678.999999999D;
final float ke6 = 2348.9089867F;
final BigDecimal ke7 = new BigDecimal(9999999999999L);
final String valOne = tst.getMoreThanFiveArgs(ikey1, dkey2, key3, ke4,
dke5, ke6, ke7);
// String strSyntheticKey = tst.getClass().getName().replace(".", "/") +
// "getMoreThanFiveArgs"
// +
// "(IDLjava/lang/String;Ljava/lang/Object;DFLjava/lang/Object;)Ljava/lang/String;";
final Cache cache = Cacheonix.getInstance(
"test_cacheonix_annotations_config.xml").getCache(cacheName);
assertNotNull(cache);
final GeneratedKey keyX = new GeneratedKey(GeneratedKey
.addKeyElement(cacheName), GeneratedKey
.addKeyElement(ikey1), GeneratedKey.addKeyElement(dkey2),
GeneratedKey.addKeyElement(key3), GeneratedKey
.addKeyElement(ke4), GeneratedKey.addKeyElement(dke5),
GeneratedKey.addKeyElement(ke6), GeneratedKey
.addKeyElement(ke7));
final Object valCheck = cache.get(keyX);
assertEquals(valOne, valCheck);
final GeneratedKey keyF = new GeneratedKey(GeneratedKey
.addKeyElement(cacheName), GeneratedKey
.addKeyElement(ikey1 + 23), GeneratedKey.addKeyElement(dkey2),
GeneratedKey.addKeyElement(key3), GeneratedKey
.addKeyElement(ke4), GeneratedKey.addKeyElement(dke5),
GeneratedKey.addKeyElement(ke6), GeneratedKey
.addKeyElement(ke7));
final Object valCheck2 = cache.get(keyX);
final Object valCheckF = cache.get(keyF);
assertFalse(valCheck2.equals(valCheckF));
}
public void testGetNothing() throws ConfigurationException, IOException {
final CacheAnnotatedTest tst = new CacheAnnotatedTest();
final String valOne = tst.getNothing();
// Cache cache =
// Cacheonix.getInstance("test_cacheonix_annotations_config.xml").getCache("org.cacheonix.impl.annotations.tests.CacheAnnotatedTest");
final Cache cache = Cacheonix.getInstance(
"test_cacheonix_annotations_config.xml").getCache(cacheName);
assertNotNull(cache);
// String strSyntheticKey = tst.getClass().getName().replace(".", "/") +
// "getNothing" + "()Ljava/lang/String;";
final String strSyntheticKey = cacheName;
final GeneratedKey keyX = new GeneratedKey(GeneratedKey
.addKeyElement(strSyntheticKey));
final Object valCheck = cache.get(keyX);
assertEquals(valOne, valCheck.toString());
}
public void testGetMoreThanFiveArgsWithNullTest()
throws ConfigurationException, IOException {
final CacheAnnotatedTest tst = new CacheAnnotatedTest();
final int ikey1 = 252525;
final double dkey2 = 345678.9876D;
final String key3 = "teen";
final BigDecimal ke4 = null;
final double dke5 = 678.999999999D;
final float ke6 = 2348.9089867F;
final BigDecimal ke7 = null;
final String valOne = tst.getMoreThanFiveArgs(ikey1, dkey2, key3, ke4,
dke5, ke6, ke7);
// String strSyntheticKey = tst.getClass().getName().replace(".", "/") +
// "getMoreThanFiveArgs"
// +
// "(IDLjava/lang/String;Ljava/lang/Object;DFLjava/lang/Object;)Ljava/lang/String;";
final Cache cache = Cacheonix.getInstance(
"test_cacheonix_annotations_config.xml").getCache(cacheName);
assertNotNull(cache);
final GeneratedKey keyX = new GeneratedKey(GeneratedKey
.addKeyElement(cacheName), GeneratedKey
.addKeyElement(ikey1), GeneratedKey.addKeyElement(dkey2),
GeneratedKey.addKeyElement(key3), GeneratedKey
.addKeyElement(ke4), GeneratedKey.addKeyElement(dke5),
GeneratedKey.addKeyElement(ke6), GeneratedKey
.addKeyElement(ke7));
final Object valCheck = cache.get(keyX);
assertEquals(valOne, valCheck);
final GeneratedKey keyF = new GeneratedKey(GeneratedKey
.addKeyElement(cacheName), GeneratedKey
.addKeyElement(ikey1 + 23), GeneratedKey.addKeyElement(dkey2),
GeneratedKey.addKeyElement(key3), GeneratedKey
.addKeyElement(ke4), GeneratedKey.addKeyElement(dke5),
GeneratedKey.addKeyElement(ke6), GeneratedKey
.addKeyElement(ke7));
final Object valCheck2 = cache.get(keyX);
final Object valCheckF = cache.get(keyF);
assertFalse(valCheck2.equals(valCheckF));
}
public void testGetFuncWithArgsParamsTest() throws ConfigurationException,
IOException {
final CacheAnnotatedTest tst = new CacheAnnotatedTest();
final int ikey1 = 252525;
final double dkey2 = 345678.9876D;
final String key3 = "teen";
final BigDecimal ke4 = new BigDecimal(345);
final double dke5 = 678.999999999D;
final float ke6 = 2348.9089867F;
final BigDecimal ke7 = new BigDecimal(9999999999999L);
final String valOne = tst.getFuncWithArgsParams(ikey1, dkey2, key3,
ke4, dke5, ke6, ke7);
// String strSyntheticKey = tst.getClass().getName().replace(".", "/") +
// "getFuncWithArgsParams"
// +
// "(IDLjava/lang/String;Ljava/lang/Object;DFLjava/lang/Object;)Ljava/lang/String;";
final Cache cache = Cacheonix.getInstance(
"test_cacheonix_annotations_config.xml").getCache(cacheName);
assertNotNull(cache);
final GeneratedKey keyX = new GeneratedKey(GeneratedKey
.addKeyElement(cacheName), GeneratedKey
.addKeyElement(ikey1), GeneratedKey.addKeyElement(dkey2),
// GeneratedKey.addKeyElement(key3),
// GeneratedKey.addKeyElement(ke4),
// GeneratedKey.addKeyElement(dke5),
// GeneratedKey.addKeyElement(ke6),
GeneratedKey.addKeyElement(ke7));
final Object valCheck = cache.get(keyX);
assertEquals(valOne, valCheck);
final GeneratedKey keyF = new GeneratedKey(GeneratedKey
.addKeyElement(cacheName), GeneratedKey
.addKeyElement(ikey1 + 23), GeneratedKey.addKeyElement(dkey2),
// GeneratedKey.addKeyElement(key3),
// GeneratedKey.addKeyElement(ke4),
// GeneratedKey.addKeyElement(dke5),
// GeneratedKey.addKeyElement(ke6),
GeneratedKey.addKeyElement(ke7));
final Object valCheck2 = cache.get(keyX);
final Object valCheckF = cache.get(keyF);
assertFalse(valCheck2.equals(valCheckF));
}
public void testCacheInvalidateFuncTest() throws ConfigurationException,
IOException {
final CacheAnnotatedTest tst = new CacheAnnotatedTest();
final String key = "teen";
final String valOne = tst.getItem(key);
final Cache cache = Cacheonix.getInstance(
"test_cacheonix_annotations_config.xml").getCache(cacheName);
assertNotNull(cache);
final GeneratedKey keyX = new GeneratedKey(GeneratedKey
.addKeyElement(cacheName), GeneratedKey
.addKeyElement(key));
final Object valCheck = cache.get(keyX);
assertEquals(valOne, valCheck);
tst.putItem(key, "SomethingImportant");
final Object valInvalidateCheck = cache.get(keyX);
assertNull(valInvalidateCheck);
assertNotSame(valCheck, valInvalidateCheck); // NOPMD
}
}
| lgpl-2.1 |
QuickServerLab/QuickServer-Main | src/main/org/quickserver/util/logging/SimpleConsoleWithThreadFormatter.java | 1973 | /*
* This file is part of the QuickServer library
* Copyright (C) QuickServer.org
*
* Use, modification, copying and distribution of this software is subject to
* the terms and conditions of the GNU Lesser General Public License.
* You should have received a copy of the GNU LGP License along with this
* library; if not, you can download a copy from <http://www.quickserver.org/>.
*
* For questions, suggestions, bug-reports, enhancement-requests etc.
* visit http://www.quickserver.org
*
*/
package org.quickserver.util.logging;
import java.util.logging.*;
import java.util.Date;
import java.text.SimpleDateFormat;
import org.quickserver.util.MyString;
/**
* Formats the LogRecord as "HH:mm:ss,SSS [LEVEL] [<Thread-ID> - <ThreadName>] Class.method() - MESSAGE"
* @since 1.5
*/
public class SimpleConsoleWithThreadFormatter extends Formatter {
private final SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss,SSS");
private final String lineSeparator = System.getProperty("line.separator");
public String format(LogRecord record) {
Date date = new Date();
date.setTime(record.getMillis());
StringBuilder sb = new StringBuilder();
sb.append(df.format(date));
sb.append(" [");
sb.append(MyString.alignLeft(record.getLevel().getLocalizedName(), 7));
sb.append("] ");
sb.append("[").append(record.getThreadID()).append(" - ");
sb.append(Thread.currentThread().getName());
sb.append("] ");
if(record.getSourceClassName() != null) {
sb.append(record.getSourceClassName());
} else {
sb.append(record.getLoggerName());
}
if(record.getSourceMethodName() != null) {
sb.append('.');
sb.append(record.getSourceMethodName());
}
sb.append(" - ");
sb.append(formatMessage(record));
if(record.getThrown() != null) {
sb.append(lineSeparator);
sb.append("[Exception: ");
sb.append(record.getThrown().toString());
sb.append(']');
}
sb.append(lineSeparator);
return sb.toString();
}
}
| lgpl-2.1 |
ambs/exist | exist-core/src/main/java/org/exist/backup/BackupDescriptor.java | 2543 | /*
* eXist-db Open Source Native XML Database
* Copyright (C) 2001 The eXist-db Authors
*
* info@exist-db.org
* http://www.exist-db.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.exist.backup;
import org.exist.util.EXistInputSource;
import org.exist.util.XMLReaderPool;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Date;
import java.util.Properties;
public interface BackupDescriptor {
String COLLECTION_DESCRIPTOR = "__contents__.xml";
String BACKUP_PROPERTIES = "backup.properties";
String PREVIOUS_PROP_NAME = "previous";
String NUMBER_IN_SEQUENCE_PROP_NAME = "nr-in-sequence";
String INCREMENTAL_PROP_NAME = "incremental";
String DATE_PROP_NAME = "date";
EXistInputSource getInputSource();
EXistInputSource getInputSource(String describedItem);
EXistInputSource getBlobInputSource(String blobId);
BackupDescriptor getChildBackupDescriptor(String describedItem);
BackupDescriptor getBackupDescriptor(String describedItem);
String getName();
String getSymbolicPath();
String getSymbolicPath(String describedItem, boolean isChildDescriptor);
/**
* Returns general properties of the backup, normally including the creation date or if it is an incremental backup.
*
* @return a Properties object or null if no properties were found
* @throws IOException if there was an error in the properties file
*/
Properties getProperties() throws IOException;
Path getParentDir();
Date getDate();
boolean before(long timestamp);
void parse(XMLReaderPool parserPool, ContentHandler handler)
throws IOException, SAXException;
Path getRepoBackup() throws IOException;
long getNumberOfFiles();
}
| lgpl-2.1 |
pezi/treedb-cmdb | src/main/java/at/treedb/at/treedb/ui/UIoption.java | 5456 | /*
* (C) Copyright 2014-2016 Peter Sauer (http://treedb.at/).
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
package at.treedb.ui;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import at.treedb.ci.Image;
import at.treedb.ci.ImageDummy;
import at.treedb.db.Base;
import at.treedb.db.ClassID;
import at.treedb.db.DAO;
import at.treedb.db.DAOiface;
import at.treedb.db.DBkey;
import at.treedb.domain.Domain;
import at.treedb.i18n.Istring;
import at.treedb.user.User;
@SuppressWarnings("serial")
@Entity
public class UIoption extends Base implements Cloneable {
public static class UIoptionDummy {
private String value;
private String option;
private ImageDummy imageDummy;
public UIoptionDummy(String value, String option, ImageDummy iDummy) {
this.option = option;
this.value = value;
this.imageDummy = iDummy;
}
public UIoptionDummy(String value, String option) {
this.option = option;
this.value = value;
this.imageDummy = null;
}
public String getValue() {
return value;
}
public String getOption() {
return option;
}
public ImageDummy getImageDummy() {
return imageDummy;
}
}
@DBkey(value = UIselect.class)
private int selectId;
@Column(name = "m_value") // firebird problem
private String value;
@Column(name = "m_option")
@DBkey(Istring.class)
private int option;
@Column(name = "m_index")
private int index;
@DBkey(value = Image.class)
private int image;
public String getValue() {
return value;
}
public int getOption() {
return option;
}
public int getSelectId() {
return selectId;
}
public int getIndex() {
return index;
}
public int getIcon() {
return image;
}
public enum Fields {
value, option, index
}
protected UIoption() {
}
protected UIoption(int selectId, String value, int option, int index, int image) {
this.selectId = selectId;
this.value = value;
this.option = option;
this.index = index;
this.image = image;
}
public static UIoption create(DAOiface dao, Domain domain, User user, int selectId, String value, int option,
int index, int image) throws Exception {
UIoption opt = new UIoption(selectId, value, option, index, image);
Base.save(dao, domain, user, opt);
return opt;
}
public static UIoption load(int id) throws Exception {
return (UIoption) Base.load(null, UIoption.class, id, null);
}
@SuppressWarnings("unchecked")
public static UIoption[] loadList(DAOiface dao, int selectId, Date date) throws Exception {
List<Base> list = null;
boolean localDAO = false;
if (dao == null) {
dao = DAO.getDAO();
localDAO = true;
}
try {
if (localDAO) {
dao.beginTransaction();
}
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("selectid", selectId);
// load only active entities
if (date == null) {
map.put("status", at.treedb.db.HistorizationIface.STATUS.ACTIVE);
list = (List<Base>) dao.query(
"select data from " + UIoption.class.getSimpleName()
+ " data where data.selectId= :selectid and data.status = :status order by data.index",
map);
} else {
map.put("date", date);
list = (List<Base>) dao.query("select data from " + UIoption.class.getSimpleName()
+ " data where data.selectID = :selectid and data.lastModified < :date and (data.deletionDate = null or data.deletionDate > :date) "
+ " order by data.version having max(data.version)", map);
}
if (localDAO) {
dao.endTransaction();
}
} catch (Exception e) {
if (localDAO) {
dao.rollback();
}
throw e;
}
if (list.size() == 0) {
return null;
}
UIoption[] options = new UIoption[list.size()];
int index = 0;
for (Base b : list) {
options[index++] = (UIoption) b;
}
return options;
}
/*
* public void update(User user, long l) throws Exception { UpdateMap map =
* new UpdateMap(UIoption.Fields.class);
* map.addLong(UIoption.Fields.longValue, l); Base.update(user, this, 0,
* null, map); }
*/
@Override
public ClassID getCID() {
return ClassID.UIOPTION;
}
}
| lgpl-2.1 |
armctec/NextLevel | src/main/java/com/armctec/nl/machines/block/BlockTank.java | 9948 | package com.armctec.nl.machines.block;
import java.util.ArrayList;
import com.armctec.nl.general.block.BlockAdvanced;
import com.armctec.nl.general.utility.CheckBlocks;
import com.armctec.nl.machines.gui.CreativeTabMachines;
import com.armctec.nl.machines.reference.ModConfig;
import com.armctec.nl.machines.reference.Names;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyInteger;
import net.minecraft.block.state.BlockState;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumWorldBlockLayer;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
// Modo 0: Sem Conexao
// Modo 1: Conexao Acima
// Modo 2: Conexao Abaixo
// Modo 3: Conexao Esquerda
// Modo 4: Conexao Direita
// Modo 5: Conexao Atras
// Modo 6: Conexao Frente
public class BlockTank extends BlockAdvanced
{
public static final PropertyInteger MODO = PropertyInteger.create("modo", 0, 9);
public BlockTank()
{
super();
this.setCreativeTab(CreativeTabMachines.MACHINES_TAB);
this.isBlockContainer = true;
setBlockName(ModConfig.MOD_ID, Names.Blocks.TANQUE);
this.setDefaultState(this.blockState.getBaseState().withProperty(MODO, 0));
}
@Override
public IBlockState getStateFromMeta(int meta)
{
return this.getDefaultState().withProperty(MODO, Integer.valueOf(meta));
}
@Override
public int getMetaFromState(IBlockState state)
{
return ((Integer)state.getValue(MODO)).intValue();
}
@Override
protected BlockState createBlockState()
{
//ModConfig.Log.info("createBlockState");
return new BlockState(this, new IProperty[] {MODO});
}
private boolean checkBreakBlock(World worldIn, BlockPos pos, BlockPos posini, ArrayList<BlockPos> list, int z)
{
if(list.contains(pos))
return false;
if(z==0)
return false;
z--;
list.add(pos);
CheckBlocks chk = new CheckBlocks(worldIn, pos, this);
// Modo 0: Sem Conexao
// Modo 1: Conexao Acima, Up
// Modo 2: Conexao Abaixo, Down
// Modo 3: Conexao Atras, North
// Modo 4: Conexao Frente, South
// Modo 5: Conexao Esquerda, East
// Modo 6: Conexao Direita, West
// Modo 7: Conexao Up, Down
// Modo 8: Conexao East, West
// Modo 9: Conexao North, East
switch(chk.conta_conexoes)
{
case 0:
if(pos != posini)
worldIn.setBlockState(pos, getDefaultState().withProperty(MODO, 0));
return true;
case 1:
if(chk.checkDown == true)
{
if(pos != posini)
worldIn.setBlockState(pos, getDefaultState().withProperty(MODO, 2));
checkBreakBlock(worldIn, chk.downPos, posini, list, z);
}
if(chk.checkUp == true)
{
if(pos != posini)
worldIn.setBlockState(pos, getDefaultState().withProperty(MODO, 1));
checkBreakBlock(worldIn, chk.upPos, posini, list, z);
}
if(chk.checkEast == true)
{
if(pos != posini)
worldIn.setBlockState(pos, getDefaultState().withProperty(MODO, 5));
checkBreakBlock(worldIn, chk.eastPos, posini, list, z);
}
if(chk.checkWest == true)
{
if(pos != posini)
worldIn.setBlockState(pos, getDefaultState().withProperty(MODO, 6));
checkBreakBlock(worldIn, chk.westPos, posini, list, z);
}
if(chk.checkNorth == true)
{
if(pos != posini)
worldIn.setBlockState(pos, getDefaultState().withProperty(MODO, 3));
checkBreakBlock(worldIn, chk.northPos, posini, list, z);
}
if(chk.checkSouth == true)
{
if(pos != posini)
worldIn.setBlockState(pos, getDefaultState().withProperty(MODO, 4));
checkBreakBlock(worldIn, chk.southPos, posini, list, z);
}
break;
case 2:
if(chk.checkDown == true && chk.checkUp == true)
{
if(pos != posini)
worldIn.setBlockState(pos, getDefaultState().withProperty(MODO, 7));
checkBreakBlock(worldIn, chk.downPos, posini, list, z);
checkBreakBlock(worldIn, chk.upPos, posini, list, z);
break;
}
if(chk.checkEast == true && chk.checkWest == true)
{
if(pos != posini)
worldIn.setBlockState(pos, getDefaultState().withProperty(MODO, 8));
checkBreakBlock(worldIn, chk.eastPos, posini, list, z);
checkBreakBlock(worldIn, chk.westPos, posini, list, z);
break;
}
if(chk.checkNorth == true && chk.checkSouth == true)
{
if(pos != posini)
worldIn.setBlockState(pos, getDefaultState().withProperty(MODO, 9));
checkBreakBlock(worldIn, chk.northPos, posini, list, z);
checkBreakBlock(worldIn, chk.southPos, posini, list, z);
break;
}
return false;
default:
if(chk.northBlock == this)
checkBreakBlock(worldIn, chk.northPos, posini, list, z);
if(chk.southBlock == this)
checkBreakBlock(worldIn, chk.southPos, posini, list, z);
if(chk.eastBlock == this)
checkBreakBlock(worldIn, chk.eastPos, posini, list, z);
if(chk.westBlock == this)
checkBreakBlock(worldIn, chk.westPos, posini, list, z);
if(chk.downBlock == this)
checkBreakBlock(worldIn, chk.downPos, posini, list, z);
if(chk.upBlock == this)
checkBreakBlock(worldIn, chk.upPos, posini, list, z);
return false;
}
return true;
}
@Override
public void breakBlock(World worldIn, BlockPos pos, IBlockState state)
{
super.breakBlock(worldIn, pos, state);
ArrayList<BlockPos> list = new ArrayList<BlockPos>();
checkBreakBlock(worldIn, pos, pos, list, 3);
list.clear();
}
private boolean checkPlaceBlock(World worldIn, BlockPos pos, ArrayList<BlockPos> list, int z)
{
if(list.contains(pos))
return false;
if(z==0)
return false;
z--;
list.add(pos);
CheckBlocks chk = new CheckBlocks(worldIn, pos, this);
// Modo 0: Sem Conexao
// Modo 1: Conexao Acima, Up
// Modo 2: Conexao Abaixo, Down
// Modo 3: Conexao Atras, North
// Modo 4: Conexao Frente, South
// Modo 5: Conexao Esquerda, East
// Modo 6: Conexao Direita, West
// Modo 7: Conexao Up, Down
// Modo 8: Conexao East, West
// Modo 9: Conexao North, East
switch(chk.conta_conexoes)
{
case 0:
return false;
case 1:
if(chk.checkDown == true)
{
worldIn.setBlockState(pos, getDefaultState().withProperty(MODO, 2));
checkPlaceBlock(worldIn, chk.downPos, list, z);
}
if(chk.checkUp == true)
{
worldIn.setBlockState(pos, getDefaultState().withProperty(MODO, 1));
checkPlaceBlock(worldIn, chk.upPos, list, z);
}
if(chk.checkEast == true)
{
worldIn.setBlockState(pos, getDefaultState().withProperty(MODO, 5));
checkPlaceBlock(worldIn, chk.eastPos, list, z);
}
if(chk.checkWest == true)
{
worldIn.setBlockState(pos, getDefaultState().withProperty(MODO, 6));
checkPlaceBlock(worldIn, chk.westPos, list, z);
}
if(chk.checkNorth == true)
{
worldIn.setBlockState(pos, getDefaultState().withProperty(MODO, 3));
checkPlaceBlock(worldIn, chk.northPos, list, z);
}
if(chk.checkSouth == true)
{
worldIn.setBlockState(pos, getDefaultState().withProperty(MODO, 4));
checkPlaceBlock(worldIn, chk.southPos, list, z);
}
break;
case 2:
if(chk.checkDown == true && chk.checkUp == true)
{
worldIn.setBlockState(pos, getDefaultState().withProperty(MODO, 7));
checkPlaceBlock(worldIn, chk.downPos, list, z);
checkPlaceBlock(worldIn, chk.upPos, list, z);
break;
}
if(chk.checkEast == true && chk.checkWest == true)
{
worldIn.setBlockState(pos, getDefaultState().withProperty(MODO, 8));
checkPlaceBlock(worldIn, chk.eastPos, list, z);
checkPlaceBlock(worldIn, chk.westPos, list, z);
break;
}
if(chk.checkNorth == true && chk.checkSouth == true)
{
worldIn.setBlockState(pos, getDefaultState().withProperty(MODO, 9));
checkPlaceBlock(worldIn, chk.northPos, list, z);
checkPlaceBlock(worldIn, chk.southPos, list, z);
break;
}
return false;
default:
return false;
}
return true;
}
@Override
public IBlockState onBlockPlaced(World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer)
{
ArrayList<BlockPos> list = new ArrayList<BlockPos>();
IBlockState retorno = super.onBlockPlaced(worldIn, pos, facing, hitX, hitY, hitZ, meta, placer).withProperty(MODO, 0);
if(checkPlaceBlock(worldIn, pos, list, 3)==false)
return retorno;
list.clear();
return worldIn.getBlockState(pos);
}
@Override
public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumFacing side, float hitX, float hitY, float hitZ)
{
int valor = (Integer) state.getValue(MODO);
valor++;
if(valor>9)
valor = 0;
worldIn.setBlockState(pos, getDefaultState().withProperty(MODO, valor));
return true;
}
@SideOnly(Side.CLIENT)
@Override
public IBlockState getStateForEntityRender(IBlockState state)
{
return this.getDefaultState().withProperty(MODO, state.getValue(MODO));
}
@Override
public IBlockState getActualState(IBlockState state, IBlockAccess worldIn, BlockPos pos)
{
return this.getDefaultState().withProperty(MODO, state.getValue(MODO));
}
@SideOnly(Side.CLIENT)
public EnumWorldBlockLayer getBlockLayer()
{
return EnumWorldBlockLayer.CUTOUT_MIPPED;
}
}
| lgpl-2.1 |
pbondoer/xwiki-platform | xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/filter/input/XWikiAttachmentEventGenerator.java | 4959 | /*
* 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.internal.filter.input;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.lang.reflect.ParameterizedType;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.util.DefaultParameterizedType;
import org.xwiki.filter.FilterEventParameters;
import org.xwiki.filter.FilterException;
import org.xwiki.filter.event.model.WikiAttachmentFilter;
import org.xwiki.filter.event.xwiki.XWikiWikiAttachmentFilter;
import org.xwiki.filter.instance.input.DocumentInstanceInputProperties;
import org.xwiki.filter.instance.input.EntityEventGenerator;
import org.xwiki.filter.instance.internal.input.AbstractBeanEntityEventGenerator;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiAttachment;
import com.xpn.xwiki.doc.XWikiAttachmentArchive;
import com.xpn.xwiki.internal.filter.XWikiAttachmentFilter;
/**
* @version $Id$
* @since 6.2M1
*/
@Component
@Singleton
// TODO: add support for real revision events (instead of the jrcs archive )
public class XWikiAttachmentEventGenerator
extends AbstractBeanEntityEventGenerator<XWikiAttachment, XWikiAttachmentFilter, DocumentInstanceInputProperties>
{
/**
* The role of this component.
*/
public static final ParameterizedType ROLE = new DefaultParameterizedType(null, EntityEventGenerator.class,
XWikiAttachment.class, DocumentInstanceInputProperties.class);
@Inject
private Provider<XWikiContext> xcontextProvider;
@Inject
private Logger logger;
@Override
public void write(XWikiAttachment attachment, Object filter, XWikiAttachmentFilter attachmentFilter,
DocumentInstanceInputProperties properties) throws FilterException
{
XWikiContext xcontext = this.xcontextProvider.get();
FilterEventParameters attachmentParameters = new FilterEventParameters();
if (attachment.getAuthor() != null) {
attachmentParameters.put(WikiAttachmentFilter.PARAMETER_REVISION_AUTHOR, attachment.getAuthor());
}
attachmentParameters.put(WikiAttachmentFilter.PARAMETER_REVISION_COMMENT, attachment.getComment());
attachmentParameters.put(WikiAttachmentFilter.PARAMETER_REVISION_DATE, attachment.getDate());
attachmentParameters.put(WikiAttachmentFilter.PARAMETER_REVISION, attachment.getVersion());
if (StringUtils.isNotEmpty(attachment.getMimeType())) {
attachmentParameters.put(WikiAttachmentFilter.PARAMETER_MIMETYPE, attachment.getMimeType());
}
if (properties.isWithJRCSRevisions()) {
try {
// We need to make sure content is loaded
XWikiAttachmentArchive archive;
archive = attachment.loadArchive(xcontext);
if (archive != null) {
attachmentParameters.put(XWikiWikiAttachmentFilter.PARAMETER_JRCSREVISIONS,
archive.getArchiveAsString());
}
} catch (XWikiException e) {
this.logger.error("Attachment [{}] has malformed history", attachment.getReference(), e);
}
}
InputStream content;
Long size;
if (properties.isWithWikiAttachmentsContent()) {
try {
content = attachment.getContentInputStream(xcontext);
size = Long.valueOf(attachment.getLongSize());
} catch (XWikiException e) {
this.logger.error("Failed to get content of attachment [{}]", attachment.getReference(), e);
content = new ByteArrayInputStream(new byte[0]);
size = 0L;
}
} else {
content = null;
size = null;
}
// WikiAttachment
attachmentFilter.onWikiAttachment(attachment.getFilename(), content, size, attachmentParameters);
}
}
| lgpl-2.1 |
leodmurillo/sonar | sonar-plugin-api/src/main/java/org/sonar/api/web/DefaultTab.java | 1229 | /*
* Sonar, open source software quality management tool.
* Copyright (C) 2008-2011 SonarSource
* mailto:contact AT sonarsource DOT com
*
* Sonar 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.
*
* Sonar 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 Sonar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.api.web;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @since 2.0
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface DefaultTab {
// default value is all metrics
String[] metrics() default {};
}
| lgpl-3.0 |
Kast0rTr0y/community-edition | projects/repository/source/java/org/alfresco/repo/node/db/traitextender/NodeServiceExtension.java | 171 |
package org.alfresco.repo.node.db.traitextender;
import org.alfresco.service.cmr.repository.NodeService;
public interface NodeServiceExtension extends NodeService
{
}
| lgpl-3.0 |
qfactor2013/BizStudyParallel | JSP_Servlet/Professor_Exam/step07_miniProject_s/src/model/CustomerDao.java | 3867 | package model;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class CustomerDao {
private static DataSource source = null;
static{
try{
Context ctx = new InitialContext();
// source = (DataSource)ctx.lookup("java:comp/env/jdbc/myoracle");
source = (DataSource)ctx.lookup("java:comp/env/jdbc/myoracle");
System.out.println(source);
}catch(Exception e) {
e.printStackTrace();
}
}
public static void insert(CustomerVo cvo) throws SQLException{
Connection con = null;
PreparedStatement pstmt = null;
String query = "INSERT INTO customer VALUES(?,?,?,?)";
try{
con = source.getConnection();
pstmt = con.prepareStatement(query);
pstmt.setString(1, cvo.getId());
pstmt.setString(2, cvo.getPassword());
pstmt.setString(3, cvo.getName());
pstmt.setString(4, cvo.getEmail());
pstmt.executeUpdate();
}catch(SQLException s){
s.printStackTrace();
throw s;
}finally{
close(con, pstmt);
}
}
/**
* 특정 고객을 Database customr table에서 삭제한다.<br>
* 호출 하는 곳으로 부터 삭제할 게시물의 id (PK)를 받아 Database에서 삭제한다..
*
* Query : delete
*
* 1. Connection 생성
* 2. PreparedStatement 생성
* 3. 쿼리 전송
* 4. close()
* @param id
* @throws SQLException
*/
public static void delete(String id) throws SQLException{
?
}
/**
* 특정 고객의 password와 email 정보를 Database customr table에서 갱신한다.<br>
*
* Query : update
*
* 1. Connection 생성
* 2. PreparedStatement 생성
* 3. 쿼리 전송
* 4. close()
* @param id
* @throws SQLException
*/
public static void update(CustomerVo cvo) throws SQLException{
Connection con = null;
PreparedStatement pstmt = null;
String query
= "UPDATE customer SET password = ? , email = ? WHERE id = ?";
try{
con = source.getConnection();
pstmt = con.prepareStatement(query);
pstmt.setString(1,cvo.getPassword());
pstmt.setString(2,cvo.getEmail());
pstmt.setString(3,cvo.getId());
pstmt.executeQuery();
}catch(SQLException s){
s.printStackTrace();
throw s;
}finally{
close(con, pstmt);
}
}
/**
* 모든 고객의 정보를 Database customr table에서 검색한다.<br>
*
* Query : select
*
* 1. Connection 생성
* 2. PreparedStatement 생성
* 3. 쿼리 전송
* 4. close()
* @param id
* @throws SQLException
*/
public static ArrayList getCustomers() throws SQLException{
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
ArrayList allList = new ArrayList();
String sql = "SELECT * FROM customer";
try{
conn = source.getConnection();
pstmt = conn.prepareStatement(sql);
rset = pstmt.executeQuery();
while(rset.next()){
allList.add(new CustomerVo(rset.getString(1),
rset.getString(2),
rset.getString(3),
rset.getString(4)));
}
}catch(SQLException sqle){
sqle.printStackTrace();
throw sqle;
}finally{
close(conn, pstmt, rset);
}
return allList;
}
private static void close(Connection conn, Statement stmt, ResultSet rset) throws SQLException{
if(conn!=null) conn.close();
if(stmt!=null) stmt.close();
if(rset!=null) rset.close();
}
private static void close(Connection conn, Statement stmt) throws SQLException{
if(conn!=null) conn.close();
if(stmt!=null) stmt.close();
}
} | lgpl-3.0 |
galleon1/chocolate-milk | src/org/chocolate_milk/model/descriptors/BillingRateAddDescriptor.java | 7802 | /*
* This class was automatically generated with
* <a href="http://www.castor.org">Castor 1.3.1</a>, using an XML
* Schema.
* $Id: BillingRateAddDescriptor.java,v 1.1.1.1 2010-05-04 22:06:01 ryan Exp $
*/
package org.chocolate_milk.model.descriptors;
//---------------------------------/
//- Imported classes and packages -/
//---------------------------------/
import org.chocolate_milk.model.BillingRateAdd;
/**
* Class BillingRateAddDescriptor.
*
* @version $Revision: 1.1.1.1 $ $Date: 2010-05-04 22:06:01 $
*/
public class BillingRateAddDescriptor extends org.exolab.castor.xml.util.XMLClassDescriptorImpl {
//--------------------------/
//- Class/Member Variables -/
//--------------------------/
/**
* Field _elementDefinition.
*/
private boolean _elementDefinition;
/**
* Field _nsPrefix.
*/
private java.lang.String _nsPrefix;
/**
* Field _nsURI.
*/
private java.lang.String _nsURI;
/**
* Field _xmlName.
*/
private java.lang.String _xmlName;
/**
* Field _identity.
*/
private org.exolab.castor.xml.XMLFieldDescriptor _identity;
//----------------/
//- Constructors -/
//----------------/
public BillingRateAddDescriptor() {
super();
_xmlName = "BillingRateAdd";
_elementDefinition = true;
//-- set grouping compositor
setCompositorAsSequence();
org.exolab.castor.xml.util.XMLFieldDescriptorImpl desc = null;
org.exolab.castor.mapping.FieldHandler handler = null;
org.exolab.castor.xml.FieldValidator fieldValidator = null;
//-- initialize attribute descriptors
//-- initialize element descriptors
//-- _name
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(java.lang.String.class, "_name", "Name", org.exolab.castor.xml.NodeType.Element);
desc.setImmutable(true);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
BillingRateAdd target = (BillingRateAdd) object;
return target.getName();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
BillingRateAdd target = (BillingRateAdd) object;
target.setName( (java.lang.String) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return null;
}
};
desc.setSchemaType("string");
desc.setHandler(handler);
desc.setRequired(true);
desc.setMultivalued(false);
addFieldDescriptor(desc);
addSequenceElement(desc);
//-- validation code for: _name
fieldValidator = new org.exolab.castor.xml.FieldValidator();
fieldValidator.setMinOccurs(1);
{ //-- local scope
org.exolab.castor.xml.validators.StringValidator typeValidator;
typeValidator = new org.exolab.castor.xml.validators.StringValidator();
fieldValidator.setValidator(typeValidator);
typeValidator.setWhiteSpace("preserve");
typeValidator.setMaxLength(31);
}
desc.setValidator(fieldValidator);
//-- _billingRateAddChoice
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(org.chocolate_milk.model.BillingRateAddChoice.class, "_billingRateAddChoice", "-error-if-this-is-used-", org.exolab.castor.xml.NodeType.Element);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
BillingRateAdd target = (BillingRateAdd) object;
return target.getBillingRateAddChoice();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
BillingRateAdd target = (BillingRateAdd) object;
target.setBillingRateAddChoice( (org.chocolate_milk.model.BillingRateAddChoice) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return new org.chocolate_milk.model.BillingRateAddChoice();
}
};
desc.setSchemaType("org.chocolate_milk.model.BillingRateAddChoice");
desc.setHandler(handler);
desc.setContainer(true);
desc.setClassDescriptor(new org.chocolate_milk.model.descriptors.BillingRateAddChoiceDescriptor());
desc.setRequired(true);
desc.setMultivalued(false);
addFieldDescriptor(desc);
addSequenceElement(desc);
//-- validation code for: _billingRateAddChoice
fieldValidator = new org.exolab.castor.xml.FieldValidator();
fieldValidator.setMinOccurs(1);
{ //-- local scope
}
desc.setValidator(fieldValidator);
}
//-----------/
//- Methods -/
//-----------/
/**
* Method getAccessMode.
*
* @return the access mode specified for this class.
*/
@Override()
public org.exolab.castor.mapping.AccessMode getAccessMode(
) {
return null;
}
/**
* Method getIdentity.
*
* @return the identity field, null if this class has no
* identity.
*/
@Override()
public org.exolab.castor.mapping.FieldDescriptor getIdentity(
) {
return _identity;
}
/**
* Method getJavaClass.
*
* @return the Java class represented by this descriptor.
*/
@Override()
public java.lang.Class getJavaClass(
) {
return org.chocolate_milk.model.BillingRateAdd.class;
}
/**
* Method getNameSpacePrefix.
*
* @return the namespace prefix to use when marshaling as XML.
*/
@Override()
public java.lang.String getNameSpacePrefix(
) {
return _nsPrefix;
}
/**
* Method getNameSpaceURI.
*
* @return the namespace URI used when marshaling and
* unmarshaling as XML.
*/
@Override()
public java.lang.String getNameSpaceURI(
) {
return _nsURI;
}
/**
* Method getValidator.
*
* @return a specific validator for the class described by this
* ClassDescriptor.
*/
@Override()
public org.exolab.castor.xml.TypeValidator getValidator(
) {
return this;
}
/**
* Method getXMLName.
*
* @return the XML Name for the Class being described.
*/
@Override()
public java.lang.String getXMLName(
) {
return _xmlName;
}
/**
* Method isElementDefinition.
*
* @return true if XML schema definition of this Class is that
* of a global
* element or element with anonymous type definition.
*/
public boolean isElementDefinition(
) {
return _elementDefinition;
}
}
| lgpl-3.0 |
SergiyKolesnikov/fuji | examples/BerkeleyDB-fuji-compilable/base/com/sleepycat/je/utilint/CmdUtil.java | 3224 | package com.sleepycat.je.utilint;
import java.io.File;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.je.config.EnvironmentParams;
import com.sleepycat.je.dbi.EnvironmentImpl;
import de.ovgu.cide.jakutil.*;
/**
* Convenience methods for command line utilities.
*/
public class CmdUtil {
public static String getArg( String[] argv, int whichArg) throws IllegalArgumentException {
if (whichArg < argv.length) {
return argv[whichArg];
}
else {
throw new IllegalArgumentException();
}
}
/**
* Parse a string into a long. If the string starts with 0x, this is a hex
* number, else it's decimal.
*/
public static long readLongNumber( String longVal){
if (longVal.startsWith("0x")) {
return Long.parseLong(longVal.substring(2),16);
}
else {
return Long.parseLong(longVal);
}
}
private static final String printableChars="!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
public static void formatEntry( StringBuffer sb, byte[] entryData, boolean formatUsingPrintable){
for (int i=0; i < entryData.length; i++) {
int b=entryData[i] & 0xff;
if (formatUsingPrintable) {
if (isPrint(b)) {
if (b == 0134) {
sb.append('\\');
}
sb.append(printableChars.charAt(b - 33));
}
else {
sb.append('\\');
String hex=Integer.toHexString(b);
if (b < 16) {
sb.append('0');
}
sb.append(hex);
}
}
else {
String hex=Integer.toHexString(b);
if (b < 16) {
sb.append('0');
}
sb.append(hex);
}
}
}
private static boolean isPrint( int b){
return (b < 0177) && (040 < b);
}
/**
* Create an environment suitable for utilities. Utilities should in
* general send trace output to the console and not to the db log.
*/
public static EnvironmentImpl makeUtilityEnvironment( File envHome, boolean readOnly) throws DatabaseException {
EnvironmentConfig config=new EnvironmentConfig();
config.setReadOnly(readOnly);
hook853(config);
hook854(config);
hook855(config);
config.setConfigParam(EnvironmentParams.ENV_RECOVERY.getName(),"false");
EnvironmentImpl envImpl=new EnvironmentImpl(envHome,config);
return envImpl;
}
/**
* Returns a description of the java command for running a utility, without
* arguments. For utilities the last name of the class name can be
* specified when "-jar je.jar" is used.
*/
public static String getJavaCommand( Class cls){
String clsName=cls.getName();
String lastName=clsName.substring(clsName.lastIndexOf('.') + 1);
return "java { " + cls.getName() + " | -jar je.jar "+ lastName+ " }";
}
protected static void hook853( EnvironmentConfig config) throws DatabaseException {
}
protected static void hook854( EnvironmentConfig config) throws DatabaseException {
}
protected static void hook855( EnvironmentConfig config) throws DatabaseException {
}
}
| lgpl-3.0 |
btrplace/scheduler-UCC-15 | btrpsl/src/main/java/org/btrplace/btrpsl/tree/ExportStatement.java | 3985 | /*
* Copyright (c) 2014 University Nice Sophia Antipolis
*
* This file is part of btrplace.
* 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.
*
* 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 program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.btrplace.btrpsl.tree;
import org.antlr.runtime.Token;
import org.btrplace.btrpsl.ErrorReporter;
import org.btrplace.btrpsl.Script;
import org.btrplace.btrpsl.antlr.ANTLRBtrplaceSL2Parser;
import org.btrplace.btrpsl.element.BtrpOperand;
import org.btrplace.btrpsl.element.BtrpSet;
import org.btrplace.btrpsl.element.IgnorableOperand;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Statement to specify a list of variables to export.
* This is only allowed if the script belong to a specified namespace.
* When a variable is exported, it is exported using its current identifier
* and its fully qualified name, with is the variable identifier prefixed by the namespace.
*
* @author Fabien Hermenier
*/
public class ExportStatement extends BtrPlaceTree {
private Script script;
/**
* Make a new statement.
*
* @param t the export token
* @param scr the script to alter with the variables to export
* @param errs the list of errors
*/
public ExportStatement(Token t, Script scr, ErrorReporter errs) {
super(t, errs);
this.script = scr;
}
@Override
public BtrpOperand go(BtrPlaceTree parent) {
Set<String> scope = new HashSet<>();
List<BtrpOperand> toAdd = new ArrayList<>();
for (int i = 0; i < getChildCount(); i++) {
if (getChild(i).getType() == ANTLRBtrplaceSL2Parser.ENUM_VAR) {
BtrpOperand r = getChild(i).go(this);
if (r == IgnorableOperand.getInstance()) {
return r;
}
for (BtrpOperand o : ((BtrpSet) r).getValues()) {
toAdd.add(o);
}
} else if (getChild(i).getType() == ANTLRBtrplaceSL2Parser.VARIABLE) {
toAdd.add(getChild(i).go(this));
} else if (getChild(i).getType() == ANTLRBtrplaceSL2Parser.TIMES) {
scope.add("*");
} else if (getChild(i).getType() == ANTLRBtrplaceSL2Parser.IDENTIFIER) {
scope.add(getChild(i).getText());
} else {
BtrpOperand e = getChild(i).go(this);
if (e == IgnorableOperand.getInstance()) {
return e;
}
toAdd.addAll(flatten(e));
}
}
try {
for (BtrpOperand op : toAdd) {
script.addExportable(op.label(), op, scope);
}
} catch (UnsupportedOperationException ex) {
return ignoreError(ex.getMessage());
}
return IgnorableOperand.getInstance();
}
private static List<BtrpOperand> flatten(BtrpOperand o) {
List<BtrpOperand> ret = new ArrayList<>();
if (o.label() != null) {
ret.add(o);
} else {
if (o.degree() == 0) {
throw new UnsupportedOperationException(o + ": Variable expected");
} else {
BtrpSet s = (BtrpSet) o;
for (BtrpOperand so : s.getValues()) {
ret.addAll(flatten(so));
}
}
}
return ret;
}
}
| lgpl-3.0 |
xinghuangxu/xinghuangxu.sonarqube | sonar-batch/src/main/java/org/sonar/batch/debt/DebtModelLoader.java | 4117 | /*
* 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.batch.debt;
import org.sonar.api.BatchComponent;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rules.Rule;
import org.sonar.api.rules.RuleFinder;
import org.sonar.api.rules.RuleQuery;
import org.sonar.api.technicaldebt.batch.TechnicalDebtModel;
import org.sonar.api.technicaldebt.batch.internal.DefaultCharacteristic;
import org.sonar.core.technicaldebt.DefaultTechnicalDebtModel;
import org.sonar.core.technicaldebt.db.CharacteristicDao;
import org.sonar.core.technicaldebt.db.CharacteristicDto;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import static com.google.common.collect.Maps.newHashMap;
public class DebtModelLoader implements BatchComponent {
private final CharacteristicDao dao;
private final RuleFinder ruleFinder;
public DebtModelLoader(CharacteristicDao dao, RuleFinder ruleFinder) {
this.dao = dao;
this.ruleFinder = ruleFinder;
}
public TechnicalDebtModel load() {
DefaultTechnicalDebtModel model = new DefaultTechnicalDebtModel();
List<CharacteristicDto> dtos = dao.selectEnabledCharacteristics();
Map<Integer, DefaultCharacteristic> characteristicsById = newHashMap();
addRootCharacteristics(model, dtos, characteristicsById);
addCharacteristics(dtos, characteristicsById);
addRequirements(dtos, characteristicsById);
return model;
}
private void addRootCharacteristics(DefaultTechnicalDebtModel model, List<CharacteristicDto> dtos, Map<Integer, DefaultCharacteristic> characteristicsById) {
for (CharacteristicDto dto : dtos) {
if (dto.getParentId() == null) {
DefaultCharacteristic rootCharacteristic = dto.toCharacteristic(null);
model.addRootCharacteristic(rootCharacteristic);
characteristicsById.put(dto.getId(), rootCharacteristic);
}
}
}
private void addCharacteristics(List<CharacteristicDto> dtos, Map<Integer, DefaultCharacteristic> characteristicsById) {
for (CharacteristicDto dto : dtos) {
if (dto.getParentId() != null && dto.getRuleId() == null) {
DefaultCharacteristic parent = characteristicsById.get(dto.getParentId());
DefaultCharacteristic characteristic = dto.toCharacteristic(parent);
characteristicsById.put(dto.getId(), characteristic);
}
}
}
private void addRequirements(List<CharacteristicDto> dtos, Map<Integer, DefaultCharacteristic> characteristicsById) {
Map<Integer, Rule> rulesById = rulesById(ruleFinder.findAll(RuleQuery.create()));
for (CharacteristicDto dto : dtos) {
Integer ruleId = dto.getRuleId();
if (ruleId != null) {
DefaultCharacteristic characteristic = characteristicsById.get(dto.getParentId());
DefaultCharacteristic rootCharacteristic = characteristicsById.get(dto.getRootId());
Rule rule = rulesById.get(ruleId);
RuleKey ruleKey = RuleKey.of(rule.getRepositoryKey(), rule.getKey());
dto.toRequirement(ruleKey, characteristic, rootCharacteristic);
}
}
}
private Map<Integer, Rule> rulesById(Collection<Rule> rules) {
Map<Integer, Rule> rulesById = newHashMap();
for (Rule rule : rules) {
rulesById.put(rule.getId(), rule);
}
return rulesById;
}
}
| lgpl-3.0 |
galleon1/chocolate-milk | src/org/chocolate_milk/model/descriptors/PriceLevelModChoiceDescriptor.java | 7901 | /*
* This class was automatically generated with
* <a href="http://www.castor.org">Castor 1.3.1</a>, using an XML
* Schema.
* $Id: PriceLevelModChoiceDescriptor.java,v 1.1.1.1 2010-05-04 22:06:01 ryan Exp $
*/
package org.chocolate_milk.model.descriptors;
//---------------------------------/
//- Imported classes and packages -/
//---------------------------------/
import org.chocolate_milk.model.PriceLevelModChoice;
/**
* Class PriceLevelModChoiceDescriptor.
*
* @version $Revision: 1.1.1.1 $ $Date: 2010-05-04 22:06:01 $
*/
public class PriceLevelModChoiceDescriptor extends org.exolab.castor.xml.util.XMLClassDescriptorImpl {
//--------------------------/
//- Class/Member Variables -/
//--------------------------/
/**
* Field _elementDefinition.
*/
private boolean _elementDefinition;
/**
* Field _nsPrefix.
*/
private java.lang.String _nsPrefix;
/**
* Field _nsURI.
*/
private java.lang.String _nsURI;
/**
* Field _xmlName.
*/
private java.lang.String _xmlName;
/**
* Field _identity.
*/
private org.exolab.castor.xml.XMLFieldDescriptor _identity;
//----------------/
//- Constructors -/
//----------------/
public PriceLevelModChoiceDescriptor() {
super();
_elementDefinition = false;
//-- set grouping compositor
setCompositorAsChoice();
org.exolab.castor.xml.util.XMLFieldDescriptorImpl desc = null;
org.exolab.castor.mapping.FieldHandler handler = null;
org.exolab.castor.xml.FieldValidator fieldValidator = null;
//-- initialize attribute descriptors
//-- initialize element descriptors
//-- _priceLevelFixedPercentage
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(java.lang.String.class, "_priceLevelFixedPercentage", "PriceLevelFixedPercentage", org.exolab.castor.xml.NodeType.Element);
desc.setImmutable(true);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
PriceLevelModChoice target = (PriceLevelModChoice) object;
return target.getPriceLevelFixedPercentage();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
PriceLevelModChoice target = (PriceLevelModChoice) object;
target.setPriceLevelFixedPercentage( (java.lang.String) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return null;
}
};
desc.setSchemaType("string");
desc.setHandler(handler);
desc.setMultivalued(false);
addFieldDescriptor(desc);
addSequenceElement(desc);
//-- validation code for: _priceLevelFixedPercentage
fieldValidator = new org.exolab.castor.xml.FieldValidator();
{ //-- local scope
org.exolab.castor.xml.validators.StringValidator typeValidator;
typeValidator = new org.exolab.castor.xml.validators.StringValidator();
fieldValidator.setValidator(typeValidator);
typeValidator.addPattern("([+\\-]?[0-9]{1,10}(\\.[0-9]{1,5})?)?");
typeValidator.setWhiteSpace("preserve");
}
desc.setValidator(fieldValidator);
//-- _priceLevelPerItemCurrency
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(org.chocolate_milk.model.PriceLevelPerItemCurrency.class, "_priceLevelPerItemCurrency", "-error-if-this-is-used-", org.exolab.castor.xml.NodeType.Element);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
PriceLevelModChoice target = (PriceLevelModChoice) object;
return target.getPriceLevelPerItemCurrency();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
PriceLevelModChoice target = (PriceLevelModChoice) object;
target.setPriceLevelPerItemCurrency( (org.chocolate_milk.model.PriceLevelPerItemCurrency) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return new org.chocolate_milk.model.PriceLevelPerItemCurrency();
}
};
desc.setSchemaType("org.chocolate_milk.model.PriceLevelPerItemCurrency");
desc.setHandler(handler);
desc.setContainer(true);
desc.setClassDescriptor(new org.chocolate_milk.model.descriptors.PriceLevelPerItemCurrencyDescriptor());
desc.setMultivalued(false);
addFieldDescriptor(desc);
addSequenceElement(desc);
//-- validation code for: _priceLevelPerItemCurrency
fieldValidator = new org.exolab.castor.xml.FieldValidator();
{ //-- local scope
}
desc.setValidator(fieldValidator);
}
//-----------/
//- Methods -/
//-----------/
/**
* Method getAccessMode.
*
* @return the access mode specified for this class.
*/
@Override()
public org.exolab.castor.mapping.AccessMode getAccessMode(
) {
return null;
}
/**
* Method getIdentity.
*
* @return the identity field, null if this class has no
* identity.
*/
@Override()
public org.exolab.castor.mapping.FieldDescriptor getIdentity(
) {
return _identity;
}
/**
* Method getJavaClass.
*
* @return the Java class represented by this descriptor.
*/
@Override()
public java.lang.Class getJavaClass(
) {
return org.chocolate_milk.model.PriceLevelModChoice.class;
}
/**
* Method getNameSpacePrefix.
*
* @return the namespace prefix to use when marshaling as XML.
*/
@Override()
public java.lang.String getNameSpacePrefix(
) {
return _nsPrefix;
}
/**
* Method getNameSpaceURI.
*
* @return the namespace URI used when marshaling and
* unmarshaling as XML.
*/
@Override()
public java.lang.String getNameSpaceURI(
) {
return _nsURI;
}
/**
* Method getValidator.
*
* @return a specific validator for the class described by this
* ClassDescriptor.
*/
@Override()
public org.exolab.castor.xml.TypeValidator getValidator(
) {
return this;
}
/**
* Method getXMLName.
*
* @return the XML Name for the Class being described.
*/
@Override()
public java.lang.String getXMLName(
) {
return _xmlName;
}
/**
* Method isElementDefinition.
*
* @return true if XML schema definition of this Class is that
* of a global
* element or element with anonymous type definition.
*/
public boolean isElementDefinition(
) {
return _elementDefinition;
}
}
| lgpl-3.0 |
fabienvauchelles/superpipes | superpipes/src/main/java/com/vaushell/superpipes/transforms/uri/T_CheckURI.java | 4590 | /*
* Copyright (C) 2013 Fabien Vauchelles (fabien_AT_vauchelles_DOT_com).
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3, 29 June 2007, 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 com.vaushell.superpipes.transforms.uri;
import com.vaushell.superpipes.dispatch.Message;
import com.vaushell.superpipes.tools.HTTPhelper;
import com.vaushell.superpipes.tools.retry.A_Retry;
import com.vaushell.superpipes.tools.retry.RetryException;
import com.vaushell.superpipes.transforms.A_Transform;
import java.io.IOException;
import java.net.URI;
import org.apache.http.impl.client.CloseableHttpClient;
import org.joda.time.Duration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Check if the URI exists.
*
* @author Fabien Vauchelles (fabien_AT_vauchelles_DOT_com)
*/
public class T_CheckURI
extends A_Transform
{
// PUBLIC
public T_CheckURI()
{
super();
this.client = null;
}
@Override
public void prepare()
throws Exception
{
this.client = HTTPhelper.createBuilder().build();
}
@Override
public Message transform( final Message message )
throws Exception
{
// Receive
if ( LOGGER.isTraceEnabled() )
{
LOGGER.trace( "[" + getNode().getNodeID() + "/" + getClass().getSimpleName() + "] transform message : " + Message.
formatSimple( message ) );
}
if ( !message.contains( Message.KeyIndex.URI ) )
{
return null;
}
final URI uri = (URI) message.getProperty( Message.KeyIndex.URI );
try
{
new A_Retry<Void>()
{
@Override
protected Void executeContent()
throws IOException
{
if ( HTTPhelper.isURIvalid( client ,
uri ,
getProperties().getConfigDuration( "timeout" ,
new Duration( 20L * 1000L ) ) ) )
{
return null;
}
else
{
throw new IOException( "Cannot validate URI=" + uri );
}
}
}
.setRetry( getProperties().getConfigInteger( "retry" ,
3 ) )
.setWaitTime( getProperties().getConfigDuration( "wait-time" ,
new Duration( 2000L ) ) )
.setWaitTimeMultiplier( getProperties().getConfigDouble( "wait-time-multiplier" ,
2.0 ) )
.setJitterRange( getProperties().getConfigInteger( "jitter-range" ,
500 ) )
.setMaxDuration( getProperties().getConfigDuration( "max-duration" ,
new Duration( 10_000L ) ) )
.execute();
return message;
}
catch( final RetryException ex )
{
if ( LOGGER.isTraceEnabled() )
{
LOGGER.trace( "[" + getNode().getNodeID() + "/" + getClass().getSimpleName() + "] Invalid URI : " + uri.
toString() ,
ex );
}
return null;
}
}
@Override
public void terminate()
throws IOException
{
if ( client != null )
{
client.close();
}
}
// PRIVATE
private static final Logger LOGGER = LoggerFactory.getLogger( T_CheckURI.class );
private CloseableHttpClient client;
}
| lgpl-3.0 |
JpressProjects/jpress | module-article/module-article-service-provider/src/main/java/io/jpress/module/article/service/task/ArticleCommentReplyCountUpdateTask.java | 2234 | /**
* Copyright (c) 2016-2020, Michael Yang 杨福海 (fuhai999@gmail.com).
* <p>
* Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.gnu.org/licenses/lgpl-3.0.txt
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.jpress.module.article.service.task;
import com.jfinal.aop.Aop;
import com.jfinal.plugin.activerecord.Db;
import io.jboot.components.schedule.annotation.FixedRate;
import io.jpress.module.article.service.ArticleCommentService;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
/**
* @author Michael Yang 杨福海 (fuhai999@gmail.com)
* @version V1.0
* @Title: 用于更新评论的 被回复 数量
* @Package io.jpress.module.article.task
*/
@FixedRate(period = 60, initialDelay = 60)
public class ArticleCommentReplyCountUpdateTask implements Runnable {
private static Map<Long, AtomicLong> countsMap = new ConcurrentHashMap<>();
public static void recordCount(Long id) {
AtomicLong count = countsMap.get(id);
if (count == null) {
count = new AtomicLong(0);
countsMap.put(id, count);
}
count.getAndIncrement();
}
@Override
public void run() {
if (countsMap.isEmpty()) {
return;
}
Map<Long, AtomicLong> articleViews = new HashMap<>(countsMap);
countsMap.clear();
for (Map.Entry<Long, AtomicLong> entry : articleViews.entrySet()) {
Db.update("update article_comment set reply_count = reply_count + "
+ entry.getValue().get()
+ " where id = ? ", entry.getKey());
Aop.get(ArticleCommentService.class).deleteCacheById(entry.getKey());
}
}
}
| lgpl-3.0 |
SergiyKolesnikov/fuji | tests/MultipleTopTypes/F1/A.java | 353 | //F1
class A {
public static void main(String[] argv) {
System.out.println(new A().m());
System.out.println(new B().m());
System.out.println(new C().m());
}
String m() {
return "F1:A";
}
}
class B {
String m() {
return "F1:B";
}
}
class C {
String m() {
return "F1:C";
}
}
| lgpl-3.0 |
premiummarkets/pm | premiumMarkets/pm-core/src/main/java/com/finance/pms/events/scoring/functions/Line.java | 3552 | package com.finance.pms.events.scoring.functions;
public class Line<XT extends Comparable<XT>, YT extends Comparable<YT>> implements Comparable<Line<XT, YT>>{
private XT xStart;
private XT xEnd;
private YT intersect;
private Double slope;
//Test
private YT lowKnot;
private YT highKnot;
private YT relativeDifference;
private Double surfaceOfChange;
public Line() {
super();
}
public XT getxEnd() {
return xEnd;
}
public void setxEnd(XT xEnd) {
this.xEnd = xEnd;
}
public YT getIntersect() {
return intersect;
}
public XT getxStart() {
return xStart;
}
public void setIntersect(XT xStart, YT intersect) {
this.xStart = xStart;
this.intersect = intersect;
}
public Double getSlope() {
return slope;
}
public void setSlope(Double slope) {
this.slope = slope;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((intersect == null) ? 0 : intersect.hashCode());
result = prime * result + ((slope == null) ? 0 : slope.hashCode());
result = prime * result + ((xEnd == null) ? 0 : xEnd.hashCode());
result = prime * result + ((xStart == null) ? 0 : xStart.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
@SuppressWarnings("unchecked")
Line<XT, YT> other = (Line<XT, YT>) obj;
if (intersect == null) {
if (other.intersect != null)
return false;
} else if (!intersect.equals(other.intersect))
return false;
if (slope == null) {
if (other.slope != null)
return false;
} else if (!slope.equals(other.slope))
return false;
if (xEnd == null) {
if (other.xEnd != null)
return false;
} else if (!xEnd.equals(other.xEnd))
return false;
if (xStart == null) {
if (other.xStart != null)
return false;
} else if (!xStart.equals(other.xStart))
return false;
return true;
}
@Override
public int compareTo(Line<XT, YT> obj) {
if (this == obj) return 0;
Line<XT, YT> other = (Line<XT, YT>) obj;
if (intersect == null) {
if (other.intersect != null)
return -1;
}
int cmp = intersect.compareTo(other.intersect);
if (cmp != 0) return cmp;
if (slope == null) {
if (other.slope != null)
return -1;
}
cmp = slope.compareTo(other.slope);
if (cmp != 0) return cmp;
if (cmp != 0) return cmp;
if (xEnd == null) {
if (other.xEnd != null)
return -1;
}
cmp = xEnd.compareTo(other.xEnd);
if (cmp != 0)
return cmp;
if (xStart == null) {
if (other.xStart != null)
return -1;
}
cmp = xStart.compareTo(other.xStart);
return cmp;
}
public boolean isSet() {
return xStart != null && xEnd != null && slope != null && intersect != null;
}
public void set(Line<XT, YT> otherTangent) {
this.setIntersect(otherTangent.getxStart(), otherTangent.getIntersect());
this.setxEnd(otherTangent.getxEnd());
this.setSlope(otherTangent.getSlope());
}
//Test
public void setToleranceCriterias(YT lowKnot, YT highKnot, YT relativeDifference) {
this.lowKnot = lowKnot;
this.highKnot= highKnot;
this.relativeDifference = relativeDifference;
}
public void setSurface(Double surfaceOfChange) {
this.surfaceOfChange = surfaceOfChange;
}
public YT getLowKnot() {
return lowKnot;
}
public YT getHighKnot() {
return highKnot;
}
public YT getRelativeDifference() {
return relativeDifference;
}
public Double getSurfaceOfChange() {
return surfaceOfChange;
}
}
| lgpl-3.0 |
janhway/otv-new | MediaData/src/main/java/MediaData/controllers/SpiderRestApi.java | 2176 | package MediaData.controllers;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import MediaData.dao.ProgramDao;
import MediaData.entity.Episode;
import MediaData.entity.Movie;
import MediaData.entity.Program;
import MediaData.msg.OttMedia;
import MediaData.msg.SubStoryInfo;
@Controller
@RequestMapping("/spiderRestApi")
public class SpiderRestApi {
private final Logger log = LoggerFactory.getLogger(SpiderRestApi.class);
@Autowired
private ProgramDao programDao;
@RequestMapping(value = "/ottmedia", method = RequestMethod.POST, headers = "Content-Type=application/json;charset=utf-8")
public @ResponseBody
String crtOttMedia(@RequestBody OttMedia om) {
Program p = programDao.getProgram(om.getTitle());
if (p == null) {
p = new Program();
p.setTitle(om.getTitle());
p.setActors(om.getActors());
p.setDirectors(om.getDirectors());
p.setOriginCountry(om.getOriginCountry());
p.setReleaseYear(om.getReleaseYear());
p.setGenre(om.getGenre());
p.setDescription(om.getDescription());
p.setPicUrl(om.getPicUrl());
List<Episode> epList = new ArrayList<Episode>();
for (SubStoryInfo ssi : om.getEpisodeList()) {
Episode ep = new Episode();
Movie mv = new Movie();
mv.setEpisode(ep);
mv.setPlayUrl(ssi.getPlayUrl());
Set<Movie> mvList = new HashSet<Movie>();
mvList.add(mv);
ep.setMovieList(mvList);
ep.setProgram(p);
ep.setTitle(ssi.getTitle());
ep.setDuration(Integer.valueOf(ssi.getDuration()));
ep.setPicUrl(ssi.getPicUrl());
ep.setDescription(ssi.getDescrip());
epList.add(ep);
}
p.setEpisodeList(epList);
programDao.saveProgram(p);
} else {
log.info("add it later.");
}
return "ok";
}
}
| lgpl-3.0 |
gchq/stroom-stats | stroom-stats-service/src/main/java/stroom/stats/configuration/common/HasName.java | 867 |
/*
* Copyright 2017 Crown Copyright
*
* This file is part of Stroom-Stats.
*
* Stroom-Stats 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.
*
* Stroom-Stats 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 Stroom-Stats. If not, see <http://www.gnu.org/licenses/>.
*/
package stroom.stats.configuration.common;
public interface HasName {
String getName();
void setName(final String name);
}
| lgpl-3.0 |
joansmith/sonarqube | server/sonar-server/src/main/java/org/sonar/server/computation/language/LanguageRepositoryImpl.java | 2143 | /*
* SonarQube
* Copyright (C) 2009-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.server.computation.language;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import java.util.Collections;
import java.util.Map;
import javax.annotation.Nonnull;
import org.sonar.api.resources.Language;
import static com.google.common.base.Predicates.notNull;
import static com.google.common.collect.Iterables.filter;
import static com.google.common.collect.Maps.uniqueIndex;
import static java.util.Arrays.asList;
/**
* Implementation of {@link LanguageRepository} which find {@link Language} instances available in the container.
*/
public class LanguageRepositoryImpl implements LanguageRepository {
private final Map<String, Language> languagesByKey;
public LanguageRepositoryImpl() {
this.languagesByKey = Collections.emptyMap();
}
public LanguageRepositoryImpl(Language... languages) {
this.languagesByKey = uniqueIndex(filter(asList(languages), notNull()), LanguageToKey.INSTANCE);
}
@Override
public Optional<Language> find(String languageKey) {
return Optional.fromNullable(languagesByKey.get(languageKey));
}
private enum LanguageToKey implements Function<Language, String> {
INSTANCE;
@Override
public String apply(@Nonnull Language input) {
return input.getKey();
}
}
}
| lgpl-3.0 |
yermak/StraightFlow | web/src/main/java/com/strightflow/core/events/fieldconfiguration/ListedFieldConfigurationEvent.java | 746 | package com.strightflow.core.events.fieldconfiguration;
import com.strightflow.core.events.LoadedEvent;
import com.strightflow.rest.domain.FieldConfigurationInfo;
import java.util.List;
/**
* Created by yermak on 22/5/14.
*/
public class ListedFieldConfigurationEvent extends LoadedEvent {
private List fieldConfigurationInfos;
public ListedFieldConfigurationEvent(List<FieldConfigurationInfo> fieldConfigurationInfos) {
this.fieldConfigurationInfos = fieldConfigurationInfos;
}
public List getFieldConfigurationInfos() {
return fieldConfigurationInfos;
}
public void setFieldConfigurationInfos(List fieldConfigurationInfos) {
this.fieldConfigurationInfos = fieldConfigurationInfos;
}
} | lgpl-3.0 |
qiqjiao/study | spring/JavaBuildTools/src/main/java/com/technologyconversations/articles/javabuildtools/Game.java | 1121 | package com.technologyconversations.articles.javabuildtools;
public class Game {
private Player player1;
private Player player2;
private static final int MIN_SCORE_TO_WIN = 3;
public Game(final Player player1Value, final Player player2Value) {
this.player1 = player1Value;
this.player2 = player2Value;
}
public final String getScore() {
if (player1.getScore() >= MIN_SCORE_TO_WIN && player2.getScore() >= MIN_SCORE_TO_WIN) {
if (Math.abs(player2.getScore() - player1.getScore()) >= 2) {
return getLeadPlayer().getName() + " won";
} else if (player1.getScore() == player2.getScore()) {
return "deuce";
} else {
return "advantage " + getLeadPlayer().getName();
}
} else {
return player1.getScoreDescription() + ", " + player2.getScoreDescription();
}
}
public final Player getLeadPlayer() {
if (player1.getScore() > player2.getScore()) {
return player1;
} else {
return player2;
}
}
}
| lgpl-3.0 |
Godin/sonar | server/sonar-server-common/src/main/java/org/sonar/server/issue/notification/MetricStatsInt.java | 1384 | /*
* 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.server.issue.notification;
public class MetricStatsInt {
private int onLeak = 0;
private int offLeak = 0;
MetricStatsInt increment(boolean onLeak) {
if (onLeak) {
this.onLeak += 1;
} else {
this.offLeak += 1;
}
return this;
}
public int getOnLeak() {
return onLeak;
}
public int getTotal() {
return onLeak + offLeak;
}
@Override
public String toString() {
return "MetricStatsInt{" +
"onLeak=" + onLeak +
", offLeak=" + offLeak +
'}';
}
}
| lgpl-3.0 |
masp/MRPG | src/masp/plugins/mlight/enums/ItemType.java | 356 | package masp.plugins.mlight.enums;
public enum ItemType {
RING, CAPE, BELT, HELMET, CHESTPLATE, LEGGINGS, BOOT, EARRING, AMULET, BADGE, PET, OTHER;
public static ItemType getItemType(String name) {
for (ItemType type : ItemType.values()) {
if (type.toString().equalsIgnoreCase(name)) {
return type;
}
}
return null;
}
}
| lgpl-3.0 |
anandswarupv/DataCleaner | engine/env/spark/src/main/java/org/datacleaner/spark/SparkJobContext.java | 7842 | /**
* DataCleaner (community edition)
* 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.datacleaner.spark;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.metamodel.util.FileResource;
import org.apache.metamodel.util.Func;
import org.apache.metamodel.util.HdfsResource;
import org.apache.metamodel.util.Resource;
import org.apache.spark.Accumulator;
import org.apache.spark.api.java.JavaSparkContext;
import org.datacleaner.configuration.DataCleanerConfiguration;
import org.datacleaner.configuration.JaxbConfigurationReader;
import org.datacleaner.job.AnalysisJob;
import org.datacleaner.job.AnalyzerJob;
import org.datacleaner.job.ComponentJob;
import org.datacleaner.job.FilterJob;
import org.datacleaner.job.JaxbJobReader;
import org.datacleaner.job.OutputDataStreamJob;
import org.datacleaner.job.TransformerJob;
/**
* A container for for values that need to be passed between Spark workers. All
* the values need to be {@link Serializable} or loadable from those
* {@link Serializable} properties.
*/
public class SparkJobContext implements Serializable {
public static final String ACCUMULATOR_CONFIGURATION_READS = "DataCleanerConfiguration reads";
public static final String ACCUMULATOR_JOB_READS = "AnalysisJob reads";
private static final long serialVersionUID = 1L;
private final String _configurationPath;
private final String _analysisJobPath;
private final Map<String, Accumulator<Integer>> _accumulators;
// cached/transient state
private transient DataCleanerConfiguration _dataCleanerConfiguration;
private transient AnalysisJob _analysisJob;
private transient List<ComponentJob> _componentList;
public SparkJobContext(JavaSparkContext sparkContext, final String dataCleanerConfigurationPath,
final String analysisJobXmlPath) {
_accumulators = new HashMap<>();
_accumulators.put(ACCUMULATOR_JOB_READS, sparkContext.accumulator(0));
_accumulators.put(ACCUMULATOR_CONFIGURATION_READS, sparkContext.accumulator(0));
_configurationPath = dataCleanerConfigurationPath;
_analysisJobPath = analysisJobXmlPath;
}
public String getConfigurationPath() {
return _configurationPath;
}
public DataCleanerConfiguration getConfiguration() {
if (_dataCleanerConfiguration == null) {
_accumulators.get(ACCUMULATOR_CONFIGURATION_READS).add(1);
final Resource configurationResource = createResource(_configurationPath);
_dataCleanerConfiguration = configurationResource.read(new Func<InputStream, DataCleanerConfiguration>() {
@Override
public DataCleanerConfiguration eval(InputStream in) {
final JaxbConfigurationReader confReader = new JaxbConfigurationReader();
return confReader.read(in);
}
});
}
return _dataCleanerConfiguration;
}
private static Resource createResource(String path) {
if (path.toLowerCase().startsWith("hdfs:")) {
return new HdfsResource(path);
}
return new FileResource(path);
}
public AnalysisJob getAnalysisJob() {
if (_analysisJob == null) {
_accumulators.get(ACCUMULATOR_JOB_READS).add(1);
final Resource analysisJobResource = createResource(_analysisJobPath);
final DataCleanerConfiguration configuration = getConfiguration();
_analysisJob = analysisJobResource.read(new Func<InputStream, AnalysisJob>() {
@Override
public AnalysisJob eval(InputStream in) {
final JaxbJobReader jobReader = new JaxbJobReader(configuration);
final AnalysisJob analysisJob = jobReader.read(in);
return analysisJob;
}
});
}
return _analysisJob;
}
public String getAnalysisJobPath() {
return _analysisJobPath;
}
public Map<String, Accumulator<Integer>> getAccumulators() {
return _accumulators;
}
public String getComponentKey(ComponentJob componentJob) {
List<ComponentJob> componentJobList = getComponentList();
for (int i = 0; i < componentJobList.size(); i++) {
if (componentJob.equals(componentJobList.get(i))) {
return String.valueOf(i);
}
}
return null;
}
public ComponentJob getComponentByKey(String key) {
List<ComponentJob> componentJobList = getComponentList();
for (int i = 0; i < componentJobList.size(); i++) {
final ComponentJob componentJob = componentJobList.get(i);
if (key.equals(getComponentKey(componentJob))) {
return componentJob;
}
}
return null;
}
public List<ComponentJob> getComponentList() {
if (_componentList == null) {
_componentList = buildComponentList(getAnalysisJob());
}
return _componentList;
}
private List<ComponentJob> buildComponentList(AnalysisJob analysisJob) {
List<ComponentJob> componentJobList = new ArrayList<>();
List<TransformerJob> transformerJobs = analysisJob.getTransformerJobs();
List<FilterJob> filterJobs = analysisJob.getFilterJobs();
List<AnalyzerJob> analyzerJobs = analysisJob.getAnalyzerJobs();
for (TransformerJob transformerJob : transformerJobs) {
componentJobList.add(transformerJob);
}
for (FilterJob filterJob : filterJobs) {
componentJobList.add(filterJob);
}
for (AnalyzerJob analyzerJob : analyzerJobs) {
componentJobList.add(analyzerJob);
}
for (TransformerJob transformerJob : analysisJob.getTransformerJobs()) {
for (OutputDataStreamJob outputDataStreamJob : transformerJob.getOutputDataStreamJobs()) {
AnalysisJob outputDataStreamAnalysisJob = outputDataStreamJob.getJob();
componentJobList.addAll(buildComponentList(outputDataStreamAnalysisJob));
}
}
for (FilterJob filterJob : analysisJob.getFilterJobs()) {
for (OutputDataStreamJob outputDataStreamJob : filterJob.getOutputDataStreamJobs()) {
AnalysisJob outputDataStreamAnalysisJob = outputDataStreamJob.getJob();
componentJobList.addAll(buildComponentList(outputDataStreamAnalysisJob));
}
}
for (AnalyzerJob analyzerJob : analysisJob.getAnalyzerJobs()) {
for (OutputDataStreamJob outputDataStreamJob : analyzerJob.getOutputDataStreamJobs()) {
AnalysisJob outputDataStreamAnalysisJob = outputDataStreamJob.getJob();
componentJobList.addAll(buildComponentList(outputDataStreamAnalysisJob));
}
}
return componentJobList;
}
}
| lgpl-3.0 |
xinghuangxu/xinghuangxu.sonarqube | sonar-core/src/main/java/org/sonar/core/user/AuthorDto.java | 2207 | /*
* 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.core.user;
import java.util.Date;
/**
* @since 3.0
*/
public final class AuthorDto {
private Long id;
private Long personId;
private String login;
private Date createdAt;
private Date updatedAt;
public Long getId() {
return id;
}
public AuthorDto setId(Long id) {
this.id = id;
return this;
}
public Long getPersonId() {
return personId;
}
public AuthorDto setPersonId(Long personId) {
this.personId = personId;
return this;
}
public String getLogin() {
return login;
}
public AuthorDto setLogin(String login) {
this.login = login;
return this;
}
public Date getCreatedAt() {
return createdAt;//NOSONAR May expose internal representation by returning reference to mutable object
}
public AuthorDto setCreatedAt(Date createdAt) {
this.createdAt = createdAt;// NOSONAR May expose internal representation by incorporating reference to mutable object
return this;
}
public Date getUpdatedAt() {
return updatedAt;//NOSONAR May expose internal representation by returning reference to mutable object
}
public AuthorDto setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;// NOSONAR May expose internal representation by incorporating reference to mutable object
return this;
}
}
| lgpl-3.0 |
joansmith/sonarqube | server/sonar-server/src/main/java/org/sonar/server/user/UpdateUser.java | 3147 | /*
* SonarQube
* Copyright (C) 2009-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.server.user;
import java.util.List;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkNotNull;
public class UpdateUser {
private String login;
private String name;
private String email;
private List<String> scmAccounts;
private String password;
private ExternalIdentity externalIdentity;
boolean nameChanged;
boolean emailChanged;
boolean scmAccountsChanged;
boolean passwordChanged;
boolean externalIdentityChanged;
private UpdateUser(String login) {
// No direct call to this constructor
this.login = login;
}
public String login() {
return login;
}
@CheckForNull
public String name() {
return name;
}
public UpdateUser setName(@Nullable String name) {
this.name = name;
nameChanged = true;
return this;
}
@CheckForNull
public String email() {
return email;
}
public UpdateUser setEmail(@Nullable String email) {
this.email = email;
emailChanged = true;
return this;
}
@CheckForNull
public List<String> scmAccounts() {
return scmAccounts;
}
public UpdateUser setScmAccounts(@Nullable List<String> scmAccounts) {
this.scmAccounts = scmAccounts;
scmAccountsChanged = true;
return this;
}
@CheckForNull
public String password() {
return password;
}
public UpdateUser setPassword(@Nullable String password) {
this.password = password;
passwordChanged = true;
return this;
}
@CheckForNull
public ExternalIdentity externalIdentity() {
return externalIdentity;
}
public UpdateUser setExternalIdentity(@Nullable ExternalIdentity externalIdentity) {
this.externalIdentity = externalIdentity;
externalIdentityChanged = true;
return this;
}
public boolean isNameChanged() {
return nameChanged;
}
public boolean isEmailChanged() {
return emailChanged;
}
public boolean isScmAccountsChanged() {
return scmAccountsChanged;
}
public boolean isPasswordChanged() {
return passwordChanged;
}
public boolean isExternalIdentityChanged() {
return externalIdentityChanged;
}
public static UpdateUser create(String login) {
checkNotNull(login);
return new UpdateUser(login);
}
}
| lgpl-3.0 |
TobiasMende/CASi | src/de/uniluebeck/imis/casi/simulation/model/World.java | 14441 | /* CASi Context Awareness Simulation Software
* Copyright (C) 2012 Moritz Bürger, Marvin Frick, Tobias Mende
*
* This program is free software. It is licensed under the
* GNU Lesser General Public License with one clarification.
*
* You should have received a copy of the
* GNU Lesser General Public License along with this program.
* See the LICENSE.txt file in this projects root folder or visit
* <http://www.gnu.org/licenses/lgpl.html> for more details.
*/
package de.uniluebeck.imis.casi.simulation.model;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
import java.util.logging.Logger;
import de.uniluebeck.imis.casi.CASi;
import de.uniluebeck.imis.casi.simulation.engine.SimulationClock;
import de.uniluebeck.imis.casi.simulation.engine.SimulationEngine;
import de.uniluebeck.imis.casi.simulation.factory.GraphicFactory;
import de.uniluebeck.imis.casi.simulation.factory.PathFactory;
import de.uniluebeck.imis.casi.simulation.factory.WorldFactory;
/**
* World Class that is kind of a root object for a Model tree
*
* @author Marvin Frick, Tobias Mende
*
*/
public class World {
/** The development logger */
private static final Logger log = Logger.getLogger(World.class.getName());
/** A set containing the rooms */
private Set<Room> rooms;
/** A set containing the agents */
private TreeSet<Agent> agents;
/** A set containing the actuators */
private TreeSet<AbstractInteractionComponent> interactionComponents;
/** Collection of components that are neither agents, actuators nor sensors */
private TreeSet<AbstractComponent> components;
/** The start time in this world */
private SimulationTime startTime;
/** Background image for the simulation */
private Image backgroundImage;
/**
* The door graph is a graph with doors as nodes. In this case its an
* adjacency matrix that saves the distance between doors if they are in the
* same room or <code>-1</code> otherwise.
*/
private double[][] doorGraph;
/**
* This matrix holds the paths between adjacent doors.
*/
private Path[][] doorPaths;
/** The size of the world */
private Dimension simulationDimension;
/**
* Flag for saving whether this world is sealed or not. If sealed, no
* changes can be made. Every call to a setter would cause an exception. If
* not sealed, the world can not be simulated.
*/
private boolean sealed;
/**
* Default Constructor
*/
public World() {
Comparator<AbstractComponent> idComparator = new Comparator<AbstractComponent>() {
@Override
public int compare(AbstractComponent one, AbstractComponent two) {
return one.getIdentifier().compareTo(two.getIdentifier());
}
};
agents = new TreeSet<Agent>(idComparator);
interactionComponents = new TreeSet<AbstractInteractionComponent>(
idComparator);
components = new TreeSet<AbstractComponent>(idComparator);
}
/**
* Seals the world
*
*/
public void seal() {
sealed = true;
}
/**
* Initializes the world
*/
public void init() {
if (doorGraph != null
|| SimulationEngine.getInstance().getWorld() == null) {
log.warning("Don't call init yet!");
return;
}
calculateDimension();
calculateDoorGraph();
printDoorGraph();
calculateDoorPaths();
connectInteractionComponentsWithAgents();
registerInteractionComponents();
}
/**
* Connects all interaction components with the communication handler.
*/
private void registerInteractionComponents() {
CASi.SIM_LOG.info("Registering components at the communication handler! Please stay tuned...");
for(AbstractInteractionComponent comp : interactionComponents) {
comp.init();
}
}
/**
* Adds all sensors and actuators as listeners to the agents.
*/
private void connectInteractionComponentsWithAgents() {
log.fine("Connecting agents with sensors and actuators");
for (Agent agent : agents) {
for (AbstractInteractionComponent comp : interactionComponents) {
if (comp.checkInterest(agent)) {
agent.addVetoableListener(comp);
}
}
}
log.fine("All agents are connected");
}
/**
* Get all rooms, hold by this world
*
* @return a collection of rooms
* @throws IllegalAccessException
* if the world isn't sealed
*/
public Set<Room> getRooms() throws IllegalAccessException {
if (!sealed) {
throw new IllegalAccessException("World isn't sealed!");
}
return rooms;
}
/**
* Get all agents that are part of this world.
*
* @return a collection of agents
* @throws IllegalAccessException
* if the world isn't sealed
*/
public TreeSet<Agent> getAgents() throws IllegalAccessException {
if (!sealed) {
throw new IllegalAccessException("World isn't sealed!");
}
return agents;
}
/**
* Getter for all actuators in this world
*
* @return a collection of actuators
* @throws IllegalAccessException
* if the world isn't sealed
*/
public Set<AbstractInteractionComponent> getInteractionComponents()
throws IllegalAccessException {
if (!sealed) {
throw new IllegalAccessException("World isn't sealed!");
}
return interactionComponents;
}
/**
* Getter for components that are neither actuators nor sensors.
*
* @return a collection of unspecified components
* @throws IllegalAccessException
* if the world isn't sealed
*/
public Set<AbstractComponent> getComponents() throws IllegalAccessException {
if (!sealed) {
throw new IllegalAccessException("World isn't sealed!");
}
return components;
}
/**
* Getter for the startTime of this simulation
*
* @return the start time
*/
public SimulationTime getStartTime() {
return startTime;
}
/**
* Getter for the door graph
*
* @return an adjacency matrix that holds the adjacencies of doors with the
* specific best case costs (the distance between two doors)
* @throws IllegalAccessException
* if the world isn't sealed
*
*/
public double[][] getDoorGraph() throws IllegalAccessException {
if (!sealed) {
throw new IllegalAccessException("World isn't sealed!");
}
return doorGraph;
}
/**
* Getter for a path between two adjacent doors
*
* @param start
* the start door
* @param end
* the end door
* @return a path or <code>null</code> if no path was found.
* @throws IllegalAccessException
* if the world isn't sealed
*/
public Path getDoorPath(Door start, Door end) throws IllegalAccessException {
if (!sealed) {
throw new IllegalAccessException("World isn't sealed!");
}
if (start.equals(end)) {
log.severe("Shouldn't call this method if doors are equal!");
return null;
}
Path path = doorPaths[start.getIntIdentifier()][end.getIntIdentifier()];
if (path == null) {
// Path didn't exist this way. try another way round
path = doorPaths[end.getIntIdentifier()][start.getIntIdentifier()];
// Reverse path if one is found
path = (path != null) ? doorPaths[end.getIntIdentifier()][start
.getIntIdentifier()].reversed() : null;
}
return path;
}
/**
* Getter for the background image
*
* @return the background image
* @throws IllegalAccessException
* if the world isn't sealed
*/
public Image getBackgroundImage() throws IllegalAccessException {
if (!sealed) {
throw new IllegalAccessException("World isn't sealed!");
}
return backgroundImage;
}
/**
* Method for checking whether this world is sealed or not.
*
* @return <code>true</code> if the world is sealed, <code>false</code>
* otherwise.
*/
public boolean isSealed() {
return sealed;
}
/**
* Setter for the rooms
*
* @param rooms
* a collection of rooms to set.
* @throws IllegalAccessException
* if the world is sealed.
*/
public void setRooms(Set<Room> rooms) throws IllegalAccessException {
if (sealed) {
throw new IllegalAccessException("World is sealed!");
}
this.rooms = rooms;
}
/**
* Setter for agents
*
* @param agents
* a collection of agents to set
* @throws IllegalAccessException
* if the world is sealed.
*/
public void setAgents(Collection<Agent> agents)
throws IllegalAccessException {
if (sealed) {
throw new IllegalAccessException("World is sealed!");
}
this.agents.clear();
this.agents.addAll(agents);
for (Agent a : agents) {
SimulationClock.getInstance().addListener(a);
}
}
/**
* Setter for actuators and sensors
*
* @param interactionComponents
* a collection of actuators and sensors
* @throws IllegalAccessException
* if the world is sealed.
*/
public void setInteractionComponents(
Collection<AbstractInteractionComponent> interactionComponents)
throws IllegalAccessException {
if (sealed) {
throw new IllegalAccessException("World is sealed!");
}
this.interactionComponents.clear();
this.interactionComponents.addAll(interactionComponents);
}
/**
* Setter for unspecified components
*
* @param components
* a collection of components that are neither actuators nor
* sensors
* @throws IllegalAccessException
* if the world is sealed.
*/
public void setComponents(Collection<AbstractComponent> components)
throws IllegalAccessException {
if (sealed) {
throw new IllegalAccessException("World is sealed!");
}
this.components.clear();
this.components.addAll(components);
}
/**
* Setter for the start time in this world
*
* @param startTime
* the start time
* @throws IllegalAccessException
* if the world is sealed.
*/
public void setStartTime(SimulationTime startTime)
throws IllegalAccessException {
if (sealed) {
throw new IllegalAccessException("World is sealed!");
}
this.startTime = startTime;
}
/**
* Setter for the background image behind the simulation
*
* @param backgroundImage
* the background image to set
* @throws IllegalAccessException
* if the world is sealed.
*/
public void setBackgroundImage(Image backgroundImage)
throws IllegalAccessException {
if (sealed) {
throw new IllegalAccessException("World is sealed!");
}
this.backgroundImage = backgroundImage;
}
/**
* Calculates the adjacency matrix that represents the door graph.
*/
private void calculateDoorGraph() {
int size = Door.getNumberOfDoors();
doorGraph = new double[size][size];
initializeDoorGraph();
for (Room room : rooms) {
// Get a list of doors for each room
ArrayList<Door> doors = new ArrayList<Door>(room.getDoors());
// For each door in this room, calculate distances to all other
// doors of this room.
log.config("Doors in " + room + ": " + doors);
calculateAdjacencies(doors);
}
}
/**
* Calculates the adjacencies and costs between doors in a given list and
* stores them in the doorGraph
*
* @param doors
* the list of doors
*/
private void calculateAdjacencies(ArrayList<Door> doors) {
for (Door first : doors) {
for (Door second : doors) {
if (first.equals(second)) {
doorGraph[first.getIntIdentifier()][second
.getIntIdentifier()] = 0.0;
continue;
}
doorGraph[first.getIntIdentifier()][second.getIntIdentifier()] = 1;
}
}
}
/**
* Sets all distances to <code>Double.NEGATIVE_INFINITY</code>, meaning that
* the doors arn't adjacent.
*/
private void initializeDoorGraph() {
log.info("Initializing Doorgraph");
int size = doorGraph.length;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
doorGraph[i][j] = Double.NEGATIVE_INFINITY;
}
}
}
/**
* Calculates the paths from each door to all adjacent other doors. And
* saves them in the doorPaths matrix
*/
private void calculateDoorPaths() {
doorPaths = new Path[doorGraph.length][doorGraph.length];
for (int i = 0; i < doorPaths.length; i++) {
for (int j = 0; j < i; j++) {
if (i == j || doorGraph[i][j] <= 0) {
// Doors are equal or not adjacent
doorPaths[i][j] = null;
continue;
}
Door from = WorldFactory.findDoorForIdentifier(i);
Door to = WorldFactory.findDoorForIdentifier(j);
if (from != null && to != null) {
doorPaths[i][j] = PathFactory.findPath(from, to);
} else {
doorPaths[i][j] = null;
}
}
}
}
/**
* Prints the adjacency matrix of doors
*/
private void printDoorGraph() {
log.fine("The door graph:");
StringBuffer head = new StringBuffer();
head.append("\t ");
for (int j = 0; j < doorGraph.length; j++) {
head.append("d-" + j + "\t ");
}
StringBuffer b = new StringBuffer();
b.append(head.toString());
b.append("\n");
for (int i = 0; i < doorGraph.length; i++) {
b.append("d-" + i + ":\t ");
for (int j = 0; j < doorGraph.length; j++) {
b.append(doorGraph[i][j] + "\t ");
}
b.append("\n");
}
log.fine(b.toString());
}
/**
* Getter for the dimension of the simulation. The dimension is the size for
* a panel which shows the world.
*
* @return the dimension
*/
public Dimension getSimulationDimension() {
return simulationDimension;
}
/**
* Calculates the dimension of the simulation area-
*/
private void calculateDimension() {
CASi.SIM_LOG.info("Calculating the size of the simulation");
Set<Wall> walls = new HashSet<Wall>();
for (Room r : rooms) {
walls.addAll(r.getWalls());
}
Point min = new Point(Integer.MAX_VALUE, Integer.MAX_VALUE);
Point max = new Point(Integer.MIN_VALUE, Integer.MIN_VALUE);
for (Wall w : walls) {
Point start = GraphicFactory.getPointRepresentation(w
.getStartPoint());
Point end = GraphicFactory.getPointRepresentation(w.getEndPoint());
if (start.x < min.x) {
min.x = start.x;
}
if (start.y < min.y) {
min.y = start.y;
}
if (start.x > max.x) {
max.x = start.x;
}
if (start.y > max.y) {
max.y = start.y;
}
if (end.x < min.x) {
min.x = end.x;
}
if (end.y < min.y) {
min.y = end.y;
}
if (end.x > max.x) {
max.x = end.x;
}
if (end.y > max.y) {
max.y = end.y;
}
}
simulationDimension = new Dimension(max.x - min.x, max.y - min.y);
}
}
| lgpl-3.0 |
OpenSoftwareSolutions/PDFReporter-Studio | com.jaspersoft.studio.components/src/com/jaspersoft/studio/components/table/model/column/MColumn.java | 16330 | /*******************************************************************************
* Copyright (C) 2005 - 2014 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com.
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
******************************************************************************/
package com.jaspersoft.studio.components.table.model.column;
import java.beans.PropertyChangeEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import net.sf.jasperreports.components.table.DesignCell;
import net.sf.jasperreports.components.table.StandardBaseColumn;
import net.sf.jasperreports.components.table.util.TableUtil;
import net.sf.jasperreports.engine.JRConstants;
import net.sf.jasperreports.engine.JRPropertiesHolder;
import net.sf.jasperreports.engine.JRPropertiesMap;
import net.sf.jasperreports.engine.JRPropertyExpression;
import net.sf.jasperreports.engine.design.JRDesignElement;
import net.sf.jasperreports.engine.design.JRDesignGroup;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.design.events.JRPropertyChangeSupport;
import org.eclipse.draw2d.ColorConstants;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.graphics.Color;
import org.eclipse.ui.views.properties.IPropertyDescriptor;
import com.jaspersoft.studio.components.table.TableManager;
import com.jaspersoft.studio.components.table.TableNodeIconDescriptor;
import com.jaspersoft.studio.components.table.messages.Messages;
import com.jaspersoft.studio.components.table.model.AMCollection;
import com.jaspersoft.studio.components.table.model.MTable;
import com.jaspersoft.studio.components.table.model.MTableGroupFooter;
import com.jaspersoft.studio.components.table.model.MTableGroupHeader;
import com.jaspersoft.studio.components.table.model.columngroup.MColumnGroup;
import com.jaspersoft.studio.components.table.model.columngroup.MColumnGroupCell;
import com.jaspersoft.studio.components.table.util.TableColumnNumerator;
import com.jaspersoft.studio.components.table.util.TableColumnSize;
import com.jaspersoft.studio.model.ANode;
import com.jaspersoft.studio.model.APropertyNode;
import com.jaspersoft.studio.model.IContainer;
import com.jaspersoft.studio.model.IContainerEditPart;
import com.jaspersoft.studio.model.IContainerLayout;
import com.jaspersoft.studio.model.IGraphicElement;
import com.jaspersoft.studio.model.INode;
import com.jaspersoft.studio.model.IPastable;
import com.jaspersoft.studio.model.MGraphicElement;
import com.jaspersoft.studio.model.util.IIconDescriptor;
import com.jaspersoft.studio.property.descriptor.expression.ExprUtil;
import com.jaspersoft.studio.property.descriptor.expression.JRExpressionPropertyDescriptor;
import com.jaspersoft.studio.property.descriptor.propexpr.JPropertyExpressionsDescriptor;
import com.jaspersoft.studio.property.descriptor.propexpr.PropertyExpressionsDTO;
import com.jaspersoft.studio.property.descriptors.PixelPropertyDescriptor;
import com.jaspersoft.studio.utils.Misc;
public class MColumn extends APropertyNode implements IPastable, IContainer,
IContainerLayout, IGraphicElement, IContainerEditPart {
public static final long serialVersionUID = JRConstants.SERIAL_VERSION_UID;
/** The icon descriptor. */
private static IIconDescriptor iconDescriptor;
public static String PROPERTY_NAME = "NAME";
/**
* Gets the icon descriptor.
*
* @return the icon descriptor
*/
public static IIconDescriptor getIconDescriptor() {
if (iconDescriptor == null)
iconDescriptor = new TableNodeIconDescriptor("tablecell"); //$NON-NLS-1$
return iconDescriptor;
}
/**
* Instantiates a new m field.
*/
public MColumn() {
super();
}
private JRDesignGroup jrGroup;
public JRDesignGroup getJrGroup() {
return jrGroup;
}
/**
* Instantiates a new m field.
*
* @param parent
* the parent
* @param jfRield
* the jf rield
* @param newIndex
* the new index
*/
public MColumn(ANode parent, StandardBaseColumn column, String name,
int index) {
super(parent, index);
setValue(column);
this.name = name;
List<ANode> n = getAMCollection();
if (n != null && !n.isEmpty()) {
ANode aNode = n.get(n.size() - 1);
type = TableColumnSize.getType(aNode.getClass());
if (aNode instanceof MTableGroupHeader) {
jrGroup = ((MTableGroupHeader) aNode).getJrDesignGroup();
grName = jrGroup.getName();
}
if (aNode instanceof MTableGroupFooter) {
jrGroup = ((MTableGroupFooter) aNode).getJrDesignGroup();
grName = jrGroup.getName();
}
}
}
public MColumn getNorth() {
ANode mparent = getParent();
if (TableManager.isBottomOfTable(type)) {
if (this instanceof MColumnGroup
|| this instanceof MColumnGroupCell)
return (MColumn) getChildren().get(0);
MTable mtable = getMTable();
List<ANode> amCollection = getAMCollection();
int index = mtable.getChildren().indexOf(
amCollection.get(amCollection.size() - 1));
AMCollection newmc = (AMCollection) mtable.getChildren().get(
index - 1);
return (MColumn) newmc.getChildren().get(0);
} else if (mparent instanceof MColumnGroup
|| mparent instanceof MColumnGroupCell)
return (MColumn) mparent;
MTable mtable = getMTable();
int index = mtable.getChildren().indexOf(mparent);
if (index > 0) {
AMCollection newmc = (AMCollection) mtable.getChildren().get(
index - 1);
return getBottomColumn(newmc.getChildren());
} else
return null;
}
private MColumn getBottomColumn(List<INode> newmc) {
for (INode col : newmc) {
if (col instanceof MColumnGroup || col instanceof MColumnGroupCell)
col = getBottomColumn(col.getChildren());
if (col instanceof MColumn)
return (MColumn) col;
}
return null;
}
private String grName;
private int type = TableUtil.TABLE_HEADER;
public int getType() {
return type;
}
public String getGrName() {
return Misc.nvl(grName);
}
@Override
public StandardBaseColumn getValue() {
return (StandardBaseColumn) super.getValue();
}
private String name;
@Override
public Color getForeground() {
return ColorConstants.lightGray;
}
/*
* (non-Javadoc)
*
* @see com.jaspersoft.studio.model.INode#getDisplayText()
*/
public String getDisplayText() {
return name;
}
public String getName() {
return name;
}
public void setName(String name) {
String oldValue = this.name;
this.name = name;
getPropertyChangeSupport().firePropertyChange(PROPERTY_NAME, oldValue, name); //$NON-NLS-1$
}
/*
* (non-Javadoc)
*
* @see com.jaspersoft.studio.model.INode#getImagePath()
*/
public ImageDescriptor getImagePath() {
return getIconDescriptor().getIcon16();
}
/*
* (non-Javadoc)
*
* @see com.jaspersoft.studio.model.INode#getToolTip()
*/
@Override
public String getToolTip() {
String tt = "";// getValue().getUUID().toString() + "\n";
List<ANode> nodes = getAMCollection();
for (int i = nodes.size() - 1; i >= 0; i--)
tt += nodes.get(i).getDisplayText() + "\n";
tt += "\t" + getIconDescriptor().getToolTip() + ": " + getDisplayText();
return tt;
}
private static IPropertyDescriptor[] descriptors;
private static Map<String, Object> defaultsMap;
@Override
public Map<String, Object> getDefaultsMap() {
return defaultsMap;
}
@Override
public IPropertyDescriptor[] getDescriptors() {
return descriptors;
}
@Override
public void setDescriptors(IPropertyDescriptor[] descriptors1,
Map<String, Object> defaultsMap1) {
descriptors = descriptors1;
defaultsMap = defaultsMap1;
}
/**
* Creates the property descriptors.
*
* @param desc
* the desc
*/
@Override
public void createPropertyDescriptors(List<IPropertyDescriptor> desc,
Map<String, Object> defaultsMap) {
JRExpressionPropertyDescriptor printWhenExprD = new JRExpressionPropertyDescriptor(
StandardBaseColumn.PROPERTY_PRINT_WHEN_EXPRESSION,
Messages.MColumn_print_when_expression);
printWhenExprD
.setDescription(Messages.MColumn_print_when_expression_description);
desc.add(printWhenExprD);
PixelPropertyDescriptor wD = new PixelPropertyDescriptor(
StandardBaseColumn.PROPERTY_WIDTH,
Messages.MColumn_column_width);
desc.add(wD);
// JPropertiesPropertyDescriptor propertiesMapD = new
// JPropertiesPropertyDescriptor(
// MGraphicElement.PROPERTY_MAP,
// com.jaspersoft.studio.messages.Messages.common_properties);
// propertiesMapD
// .setDescription(com.jaspersoft.studio.messages.Messages.common_properties);
// desc.add(propertiesMapD);
JPropertyExpressionsDescriptor propertiesD = new JPropertyExpressionsDescriptor(
JRDesignElement.PROPERTY_PROPERTY_EXPRESSIONS,
com.jaspersoft.studio.messages.Messages.MGraphicElement_property_expressions);
propertiesD
.setDescription(com.jaspersoft.studio.messages.Messages.MGraphicElement_property_expressions_description);
desc.add(propertiesD);
printWhenExprD.setCategory(Messages.MColumn_column_properties_category);
wD.setCategory(Messages.MColumn_column_properties_category);
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.views.properties.IPropertySource#getPropertyValue(java
* .lang.Object)
*/
public Object getPropertyValue(Object id) {
StandardBaseColumn jrElement = getValue();
if (id.equals(StandardBaseColumn.PROPERTY_WIDTH))
return jrElement.getWidth();
if (id.equals(StandardBaseColumn.PROPERTY_PRINT_WHEN_EXPRESSION))
return ExprUtil.getExpression(jrElement.getPrintWhenExpression());
if (id.equals(DesignCell.PROPERTY_HEIGHT))
return getMTable().getTableManager().getYhcolumn(type, grName,
jrElement).height;
JRPropertiesMap propertiesMap = jrElement.getPropertiesMap();
if (propertiesMap != null)
propertiesMap = propertiesMap.cloneProperties();
if (id.equals(JRDesignElement.PROPERTY_PROPERTY_EXPRESSIONS)) {
JRPropertyExpression[] propertyExpressions = jrElement
.getPropertyExpressions();
if (propertyExpressions != null)
propertyExpressions = propertyExpressions.clone();
return new PropertyExpressionsDTO(propertyExpressions,
propertiesMap, this);
}
if (id.equals(MGraphicElement.PROPERTY_MAP))
return propertiesMap;
return null;
}
private boolean canSet = true;
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.views.properties.IPropertySource#setPropertyValue(java
* .lang.Object, java.lang.Object)
*/
public void setPropertyValue(Object id, Object value) {
StandardBaseColumn jrElement = getValue();
if (id.equals(StandardBaseColumn.PROPERTY_WIDTH)) {
if ((Integer) value >= 0 && canSet) {
canSet = false;
MTable table = getMTable();
table.getTableManager().setWidth(jrElement, (Integer) value);
table.getTableManager().update();
// table.getTableManager().refresh();
getPropertyChangeSupport()
.firePropertyChange(
new PropertyChangeEvent(this,
StandardBaseColumn.PROPERTY_WIDTH,
null, value));
canSet = true;
}
} else if (id.equals(DesignCell.PROPERTY_HEIGHT)) {
MTable mtable = getMTable();
Integer height = (Integer) value;
AMCollection section = getSection();
if (section != null && height.intValue() >= 0) {
@SuppressWarnings("unchecked")
Class<AMCollection> classType = (Class<AMCollection>) section
.getClass();
String grName = null;
if (section instanceof MTableGroupHeader)
grName = ((MTableGroupHeader) section).getJrDesignGroup()
.getName();
if (section instanceof MTableGroupFooter)
grName = ((MTableGroupFooter) section).getJrDesignGroup()
.getName();
mtable.getTableManager().setHeight(null, height, jrElement,
TableColumnSize.getType(classType), grName);
// cell.setHeight(height);
mtable.getTableManager().update();
getPropertyChangeSupport().firePropertyChange(
new PropertyChangeEvent(this,
DesignCell.PROPERTY_HEIGHT, null, value));
}
} else if (id.equals(StandardBaseColumn.PROPERTY_PRINT_WHEN_EXPRESSION))
jrElement.setPrintWhenExpression(ExprUtil.setValues(
jrElement.getPrintWhenExpression(), value, null));
else if (id.equals(MGraphicElement.PROPERTY_MAP)) {
JRPropertiesMap v = (JRPropertiesMap) value;
String[] names = jrElement.getPropertiesMap().getPropertyNames();
for (int i = 0; i < names.length; i++) {
jrElement.getPropertiesMap().removeProperty(names[i]);
}
names = v.getPropertyNames();
for (int i = 0; i < names.length; i++)
jrElement.getPropertiesMap().setProperty(names[i],
v.getProperty(names[i]));
this.getPropertyChangeSupport().firePropertyChange(
MGraphicElement.PROPERTY_MAP, false, true);
} else if (id.equals(JRDesignElement.PROPERTY_PROPERTY_EXPRESSIONS)) {
if (value instanceof PropertyExpressionsDTO) {
PropertyExpressionsDTO dto = (PropertyExpressionsDTO) value;
JRPropertyExpression[] v = dto.getPropExpressions();
JRPropertyExpression[] expr = jrElement
.getPropertyExpressions();
if (expr != null)
for (JRPropertyExpression ex : expr)
jrElement.removePropertyExpression(ex);
if (v != null)
for (JRPropertyExpression p : v)
jrElement.addPropertyExpression(p);
// now change properties
JRPropertiesMap vmap = dto.getPropMap();
String[] names = jrElement.getPropertiesMap()
.getPropertyNames();
for (int i = 0; i < names.length; i++) {
jrElement.getPropertiesMap().removeProperty(names[i]);
}
if (vmap != null) {
names = vmap.getPropertyNames();
for (int i = 0; i < names.length; i++)
jrElement.getPropertiesMap().setProperty(names[i],
vmap.getProperty(names[i]));
this.getPropertyChangeSupport().firePropertyChange(
MGraphicElement.PROPERTY_MAP, false, true);
}
}
}
}
public JRDesignElement createJRElement(JasperDesign jasperDesign) {
return null;
}
public MTable getMTable() {
ANode node = getParent();
while (node != null) {
if (node instanceof MTable) {
return (MTable) node;
}
node = node.getParent();
}
return null;
}
private List<ANode> list;
public List<ANode> getAMCollection() {
if (list == null) {
list = new ArrayList<ANode>();
ANode node = getParent();
while (node != null) {
list.add(node);
if (node instanceof AMCollection)
return list;
node = node.getParent();
}
}
return list;
}
@Override
public void propertyChange(final PropertyChangeEvent evt) {
final AMCollection section = getSection();
if (section != null) {
if (evt.getPropertyName().equals(section.getCellEvent())) {
if (evt.getSource() == this.getValue()) {
final StandardBaseColumn bc = (StandardBaseColumn) evt
.getSource();
final ANode parent = (ANode) getParent();
final MColumn child = this;
final int newIndex = parent.getChildren().indexOf(this);
parent.removeChild(child);
section.createColumn(parent, bc, 122, newIndex);
MTable mtable = (MTable) section.getParent();
if (mtable == null){
((JRPropertyChangeSupport)evt.getSource()).removePropertyChangeListener(child);
} else {
mtable.getTableManager().refresh();
TableColumnNumerator.renumerateColumnNames(mtable);
parent.propertyChange(evt);
}
}
}
}
super.propertyChange(evt);
}
public AMCollection getSection() {
INode n = getParent();
while (n != null) {
if (n instanceof AMCollection)
return (AMCollection) n;
n = n.getParent();
}
return null;
}
public Rectangle getBounds() {
StandardBaseColumn c = getValue();
MTable mc = getMTable();
if (mc != null && c != null)
return mc.getTableManager().getBounds(c, type, grName);
return null;
}
public int getDefaultWidth() {
return 0;
}
public int getDefaultHeight() {
return 0;
}
@Override
public JRPropertiesHolder[] getPropertyHolder() {
return new JRPropertiesHolder[] { getValue(), getMTable().getValue() };
}
}
| lgpl-3.0 |
automenta/spacegraph1 | run/automenta/spacenet/run/old/graph/neural/DemoBrainz.java | 6295 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package automenta.spacenet.run.old.graph.neural;
import automenta.spacenet.plugin.neural.brainz.AbstractNeuron;
import automenta.spacenet.plugin.neural.brainz.Brain;
import automenta.spacenet.plugin.neural.brainz.BrainBuilder;
import automenta.spacenet.plugin.neural.brainz.BrainGraph;
import automenta.spacenet.plugin.neural.brainz.InterNeuron;
import automenta.spacenet.plugin.neural.brainz.MotorNeuron;
import automenta.spacenet.plugin.neural.brainz.SenseNeuron;
import automenta.spacenet.run.ArdorSpacetime;
import automenta.spacenet.run.old.DefaultGraphBuilder;
import automenta.spacenet.space.Repeat;
import automenta.spacenet.space.geom.Box;
import automenta.spacenet.space.geom.Box.BoxShape;
import automenta.spacenet.space.geom.ProcessBox;
import automenta.spacenet.space.geom.Rect;
import automenta.spacenet.space.geom.Rect.RectShape;
import automenta.spacenet.space.geom.graph.GraphBox;
import automenta.spacenet.space.geom.graph.GraphBoxBuilder;
import automenta.spacenet.space.geom.graph.GraphBoxModel;
import automenta.spacenet.space.geom.graph.arrange.GridListing;
import automenta.spacenet.space.geom.layout.ColRect;
import automenta.spacenet.var.Maths;
import automenta.spacenet.var.graph.MemGraph;
import automenta.spacenet.var.physical.Color;
import com.ardor3d.scenegraph.Spatial;
/**
*
* @author seh
*/
public class DemoBrainz extends ProcessBox {
final Brain b = new BrainBuilder(16, 8).newBrain(100, 4, 32);
double neuronBoxUpdatePeriod = 0.05;
double neuronUpdatePeriod = 0.05;
private Rect outputRect;
private double[] nextOutputs;
public MemGraph getGraph() {
return new BrainGraph(b);
}
double neuronScale = 0.7;
public GraphBoxBuilder getGraphBuilder() {
return new DefaultGraphBuilder() {
@Override public Box newNodeSpace(Object node) {
Box b = new Box(BoxShape.Empty);
if (node instanceof AbstractNeuron) {
final AbstractNeuron i = (AbstractNeuron) node;
final Rect r = b.add(new Rect(node instanceof InterNeuron ? RectShape.Rect : RectShape.Ellipse));
b.add(new Repeat(neuronBoxUpdatePeriod) {
@Override protected void update(double t, double dt, Spatial parent) {
double o = i.getOutput();
double p = o;
if (i instanceof InterNeuron)
p = ((InterNeuron)i).getPotential();
r.color(getNeuronColor(o, p));
r.scale( 0.25 + (Math.abs( o ) + Math.abs(p)) * neuronScale);
}
});
}
return b;
}
};
}
@Override protected void start() {
double size = 20.0;
//V3 boundsMax = new V3(size, size, size);
// ForceDirectedParameters par = new ForceDirectedParameters(boundsMax, 0.01, 0.001, 1.0);
// double updatePeriod = 0.05;
// double interpSpeed = 0.3;
// int substeps = 12;
//ForceDirecting arr = new ForceDirecting(par, updatePeriod, substeps, interpSpeed);
GraphBoxModel arr = new GridListing(-0.5, -0.5, 0.5, 0.5, null);
add(new GraphBox(getGraph(), getGraphBuilder(), arr));
//add(new ForceDirectedParametersEditWindow(par, DemoDefaults.font)).move(-1, 0, 0);
System.out.println(b.getTotalNeurons() + " * " + b.getTotalSynapses());
System.out.println("senses: " + b.getSense());
System.out.println("neurons: " + b.getNeuron());
System.out.println("motors: " + b.getMotor());
// final Map<SenseNeuron, Rect> senseRect = new HashMap();
// final Map<InterNeuron, Rect> neuronRect = new HashMap();
// double x = 0;
// double s = 0.1;
// for (InterNeuron i : b.getNeuron()) {
// Rect r = add(new Rect(RectShape.Rect));
// r.scale(0.1, 1);
// r.move(x, 0, 0);
// neuronRect.put(i, r);
// x += s;
// }
//
// x = 0;
// s = 0.1;
// for (SenseNeuron i : b.getSense()) {
// Rect r = add(new Rect(RectShape.Rect));
// r.scale(0.1, 1);
// r.move(x, 1, 0);
// senseRect.put(i, r);
// x += s;
// }
outputRect = add(new Rect(RectShape.Empty)).move(0.8,0,0).scale(0.5);
add(new Repeat(3.0) {
@Override protected void update(double t, double dt, Spatial parent) {
randomizeInputs();
}
});
add(new Repeat(neuronUpdatePeriod) {
@Override protected void update(double t, double dt, Spatial parent) {
updateInputs();
b.forward();
updateOutputs();
}
});
}
protected void updateOutputs() {
outputRect.removeAll();
Rect[] o = new Rect[b.getMotor().size()];
int j = 0;
for (MotorNeuron m : b.getMotor()) {
double bo = m.getOutput();
Color c;
if (bo < 0.5)
c = Color.Blue;
else
c = Color.Red;
Rect re = new Rect(RectShape.Ellipse);
re.color(c);
o[j++] = re;
}
outputRect.add(new ColRect(0.01, o));
}
public void randomizeInputs() {
if (nextOutputs == null) {
nextOutputs = new double[b.getSense().size()];
}
for (int i = 0; i < b.getSense().size(); i++) {
nextOutputs[i] = Maths.random(-1, 1);
}
}
double inputMomentum = 0.98;
public void updateInputs() {
int i = 0;
for (SenseNeuron s : b.getSense()) {
s.senseInput = (inputMomentum * s.senseInput) + ((1.0 - inputMomentum) * nextOutputs[i++]);
}
}
public Color getNeuronColor(double a, double b) {
a = (a + 1.0) * 0.5;
b = (b + 1.0) * 0.5;
return new Color(a, 0, b);
}
public static void main(String[] args) {
ArdorSpacetime.newWindow(new DemoBrainz());
}
}
| lgpl-3.0 |
ninazeina/SXP | src/main/java/protocol/impl/blockChain/BlockChainEstablisher.java | 5916 | package protocol.impl.blockChain;
import net.jxta.pipe.PipeMsgEvent;
import network.api.ContractService;
import network.api.Messages;
import network.impl.jxta.JxtaService;
import network.impl.messages.ContractMessage;
import network.impl.messages.SignatureMessage;
import network.impl.messages.WishMessage;
import protocol.api.Status;
import protocol.api.Wish;
/**
*
* @author soriano
*
*/
public class BlockChainEstablisher extends JxtaService implements ContractService {
private EthereumImpl eth = new EthereumImpl() ;
private Wish w;
private Status s;
private ContractMessage contract = null;
private boolean contractOwner;
private String establisherOwner;
public static final String NAME = "establisher";
private String signatureAutrePartie = "false";
public BlockChainEstablisher ()
{
this.name = NAME;
}
/**
* initialise le contrat
* Ajoute Les peers de la source et de la destinnation
* Ajoute les service gerant le contrat des peer de source et destination
* Permet d'envoyer et de voir(depuis la source) les réponses du destinataire
* Met le voeux a neutre et le status a nul part
* @param source
* PeerId du peer source du contrat
* @param dest
* PeerId du peer de destination
* @param srcService
* service du peer source
* @param destService
* serice du peer destination
*/
public void initialize(boolean contractOwner, String name) {
setContractOwner(contractOwner);
setEstablisherOwner(name);
w = Wish.NEUTRAL;
s = Status.NOWHERE;
setSignatureAutrePartie("false");
setContract(null);
}
public void displayContract()
{
System.out.println("Contract de :"+getEstablisherOwner());
System.out.println(contract.getMessage("title"));
System.out.println(contract.getMessage("itemVoulu"));
System.out.println(contract.getMessage("itemAEchanger"));
System.out.println("Voeux : "+getWish());
System.out.println("Status : "+getStatus());
System.out.println("signature : "+getSignatureAutrePartie()+"\n");
}
/**
*
* @param c
*/
public void setContract(ContractMessage c)
{
this.contract = c;
}
/**
*
* @return
*/
public ContractMessage getContract() {
return contract;
}
/**
*
* @param w
*/
public void setWish(Wish w) {
this.w = w;
}
/**
*
* @return
*/
public Wish getWish() {
return w;
}
/**
*
* @param status
*/
public void setStatus(Status status)
{
this.s = status;
}
/**
*
* @return
*/
public Status getStatus() {
return s;
}
@Override
public ContractMessage sendContract(String title, String who, String itemVoulu, String itemAEchanger,
String... uris) {
ContractMessage m = new ContractMessage();
m.setTitle(title);
m.setWho(who);
m.setDest(this.peerUri);
m.setItemAEchanger(itemAEchanger);
m.setItemVoulu(itemVoulu);
this.sendMessages(m, uris);
this.contract = m;
setWish(Wish.ACCEPT);
return m;
}
public void sendSignature(String signe, String who, String... uris)
{
SignatureMessage m = new SignatureMessage();
m.setSigne(signe);
m.setWho(who);
this.sendMessages(m, uris);
//Send signature on BlockChain
//new Thread(eth.new signContract()).start();
}
@Override
public void sendWish(Wish w, String who, String... uris) {
if(w.equals(Wish.ACCEPT))
{
setStatus(Status.SIGNING);
}
else if(w.equals(Wish.REFUSE))
{
setStatus(Status.CANCELLED);
}
WishMessage m = new WishMessage();
m.SetWish(w.toString());
m.setWho(who);
this.sendMessages(m, uris);
setWish(w);
}
@Override
public void pipeMsgEvent(PipeMsgEvent event) {
Messages message = toMessages(event.getMessage());
if(message.getMessage("type").equals("wish"))
{
System.out.println("Mr. "+getEstablisherOwner());
System.out.println("Voeux reçu");
System.out.println(message.getMessage("wish")+"\n");
if(message.getMessage("wish").equals("ACCEPT"))
{
if(getWish().equals(Wish.ACCEPT))
{
System.out.println("Contrat accepté par les deux partie !");
//Deploye contract on Ropsten
//new Thread(eth.new deployContract()).run();
setStatus(Status.SIGNING);
}
}
else if(message.getMessage("wish").equals("REFUSE"))
{
setStatus(Status.CANCELLED);
System.out.println("status refusé contrat abandonné");
}
super.pipeMsgEvent(event);
return;
}
if(message.getMessage("type").equals("contracts"))
{
this.initialize(false, "utilisateur2");
System.out.println("Mr. "+getEstablisherOwner());
System.out.println("vous avez reçu un contrat :");
super.pipeMsgEvent(event);
System.out.println("Acceptez vous les clauses ?\n");
ContractMessage contractMessage = new ContractMessage();
contractMessage.setItemAEchanger(message.getMessage("itemAEchanger"));
contractMessage.setTitle(message.getMessage("title"));
contractMessage.setItemVoulu(message.getMessage("itemVoulu"));
contractMessage.setWho(message.getMessage("WHO"));
contractMessage.setDest(message.getMessage("source"));
this.contract = contractMessage;
return;
}
if(message.getMessage("type").equals("signature"))
{
setSignatureAutrePartie(message.getMessage("signature"));
super.pipeMsgEvent(event);
return;
}
super.pipeMsgEvent(event);
//this.sendMessages(getResponseMessage(message), message.getMessage("source"));
}
public String getEstablisherOwner() {
return establisherOwner;
}
public void setEstablisherOwner(String establisherOwner) {
this.establisherOwner = establisherOwner;
}
public boolean isContractOwner() {
return contractOwner;
}
public void setContractOwner(boolean contractOwner) {
this.contractOwner = contractOwner;
}
public String getSignatureAutrePartie() {
return signatureAutrePartie;
}
public void setSignatureAutrePartie(String signatureAutrePartie) {
this.signatureAutrePartie = signatureAutrePartie;
}
}
| lgpl-3.0 |
Alfresco/activiti-android-app | activiti-app/src/main/java/com/activiti/android/platform/intent/RequestCode.java | 1002 | /*
* Copyright (C) 2005-2015 Alfresco Software Limited.
*
* This file is part of Alfresco Activiti Mobile for Android.
*
* Alfresco Activiti Mobile for Android 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 Activiti Mobile for Android 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 com.activiti.android.platform.intent;
public interface RequestCode
{
// REQUEST CODE
int TEXT_TO_SPEECH = 25;
int PICK_CONTACT = 35;
}
| lgpl-3.0 |
marsglorious/NewNations | src/newnations/invites/InviteManager.java | 6883 | package newnations.invites;
import java.util.ArrayList;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import newnations.Alliance;
import newnations.Nation;
import newnations.NewNations;
import newnations.Town;
public class InviteManager
{
private ArrayList<TownUserInvite> townUserInvites = new ArrayList<TownUserInvite>();
private ArrayList<NationTownInvite> nationTownInvites = new ArrayList<NationTownInvite>();
private ArrayList<AllianceNationInvite> allianceInvites = new ArrayList<AllianceNationInvite>();
private NewNations plugin;
public InviteManager(NewNations plugin)
{
this.plugin = plugin;
}
public InviteManager(NewNations plugin, JSONObject obj)
{
this.plugin = plugin;
//load the townuser invites
JSONArray townUserArray = (JSONArray) obj.get("townUserInvites");
for(int i = 0; i < townUserArray.size(); i++)
{
TownUserInvite inv = new TownUserInvite(plugin, (JSONObject)townUserArray.get(i));
if(inv.isValid()) townUserInvites.add(inv);
}
JSONArray nationTownArray = (JSONArray) obj.get("nationTownInvites");
for(int i = 0; i < nationTownArray.size(); i++)
{
NationTownInvite inv = new NationTownInvite(plugin, (JSONObject)nationTownArray.get(i));
if(inv.isValid()) nationTownInvites.add(inv);
}
JSONArray allianceNationArray = (JSONArray) obj.get("allianceNationInvites");
for(int i = 0; i < allianceNationArray.size(); i++)
{
AllianceNationInvite inv = new AllianceNationInvite(plugin, (JSONObject)allianceNationArray.get(i));
if(inv.isValid()) allianceInvites.add(inv);
}
}
public JSONObject save()
{
JSONObject inviteman = new JSONObject();
JSONArray townusersarray = new JSONArray();
for(TownUserInvite inv : townUserInvites)
if(inv.update()) townusersarray.add(inv.save());
JSONArray nationtownsarray = new JSONArray();
for(NationTownInvite inv : nationTownInvites)
if(inv.update()) nationtownsarray.add(inv.save());
JSONArray alliancearray = new JSONArray();
for(AllianceNationInvite inv : allianceInvites)
if(inv.update()) alliancearray.add(inv.save());
inviteman.put("townUserInvites", townusersarray);
inviteman.put("nationTownInvites", nationtownsarray);
inviteman.put("allianceNationInvites", alliancearray);
return inviteman;
}
public boolean inviteUserToTown(Town town, String username)
{
for(TownUserInvite oldInv : getTownInvitesForUser(username))
{
if(oldInv.getSendingTown() == town && oldInv.isValid())
{
oldInv.resetExpire();
return true;
}
}
TownUserInvite newInvite = new TownUserInvite(plugin, town, username);
if(newInvite.isValid())
{
townUserInvites.add(newInvite);
return true;
}
return false;
}
public boolean inviteTownToNation(Nation nation, Town town)
{
for(NationTownInvite oldInv : getNationInvitesForTown(town))
{
if(oldInv.getSendingNation() == nation && oldInv.isValid())
{
oldInv.resetExpire();
return true;
}
}
NationTownInvite newInvite = new NationTownInvite(plugin, nation, town);
if(newInvite.isValid())
{
nationTownInvites.add(newInvite);
return true;
}
return false;
}
public boolean inviteNationToAlliance(Alliance alliance, Nation nation )
{
for(AllianceNationInvite oldInv : getAllianceInvitesForNation(nation))
{
if(oldInv.getSendingAllaince() == alliance && oldInv.isValid())
{
oldInv.resetExpire();
return true;
}
}
AllianceNationInvite newInvite = new AllianceNationInvite(plugin, alliance, nation);
if(newInvite.isValid())
{
allianceInvites.add(newInvite);
return true;
}
return false;
}
//get the invites sent TO a user FROM a town
public ArrayList<TownUserInvite> getTownInvitesForUser(String username)
{
ArrayList<TownUserInvite> thislist = new ArrayList<TownUserInvite>();
for(TownUserInvite inv : townUserInvites)
if(inv.update() && inv.getReceivingUserName().equalsIgnoreCase(username)) thislist.add(inv);
return thislist;
}
//returns the invite sent TO a town FROM a nation
public ArrayList<NationTownInvite> getNationInvitesForTown(Town town)
{
ArrayList<NationTownInvite> thislist = new ArrayList<NationTownInvite>();
for(NationTownInvite inv : nationTownInvites)
if(inv.update() && inv.getReceivingTown() == town) thislist.add(inv);
return thislist;
}
//returns the invites sent TO a nation FROM an alliance
public ArrayList<AllianceNationInvite> getAllianceInvitesForNation(Nation nation)
{
ArrayList<AllianceNationInvite> thislist = new ArrayList<AllianceNationInvite>();
for(AllianceNationInvite inv : allianceInvites)
if(inv.update() && inv.getReceivingNation() == nation) thislist.add(inv);
return thislist;
}
//
///
///
///
//
public ArrayList<TownUserInvite> getUserInvitesForTown(Town town)
{
ArrayList<TownUserInvite> thislist = new ArrayList<TownUserInvite>();
for(TownUserInvite inv : townUserInvites)
{
if(inv.update() && inv.getSendingTown() == town) thislist.add(inv);
}
return thislist;
}
public ArrayList<NationTownInvite> getTownInvitesForNation(Nation nation)
{
ArrayList<NationTownInvite> thislist = new ArrayList<NationTownInvite>();
for(NationTownInvite inv : nationTownInvites)
{
if(inv.update() && inv.getSendingNation() == nation) thislist.add(inv);
}
return thislist;
}
public ArrayList<AllianceNationInvite> getNationInvitesForAlliance(Alliance alliance)
{
ArrayList<AllianceNationInvite> thislist = new ArrayList<AllianceNationInvite>();
for(AllianceNationInvite inv : allianceInvites)
{
if(inv.update() && inv.getSendingAllaince() == alliance ) thislist.add(inv);
}
return thislist;
}
///
///
//
///
public boolean removeUserInviteFromTown(Town town, String userToRemove)
{
boolean found = false;
ArrayList<TownUserInvite> invitelist = getUserInvitesForTown(town);
for(TownUserInvite inv : invitelist)
{
if(inv.getReceivingUserName().equalsIgnoreCase(userToRemove))
{
inv.invalidate();
found = true;
}
}
return found;
}
public void removeInviteContaining(Object object)
{
for(int i = townUserInvites.size() -1; i >= 0; i--)
{
TownUserInvite inv = townUserInvites.get(i);
if(inv.getSendingTown().equals(object) || inv.getReceivingUserName().equals(object)) townUserInvites.remove(i);
}
for(int i = nationTownInvites.size() -1; i >= 0; i--)
{
NationTownInvite inv = nationTownInvites.get(i);
if(inv.getSendingNation().equals(object) || inv.getReceivingTown().equals(object)) townUserInvites.remove(i);
}
for(int i = allianceInvites.size() -1; i >= 0; i--)
{
AllianceNationInvite inv = allianceInvites.get(i);
if(inv.getSendingAllaince().equals(object) || inv.getReceivingNation().equals(object)) townUserInvites.remove(i);
}
}
public void cull()
{
//TODO: do this method
}
}
| lgpl-3.0 |
MichaelRoeder/Grph | src/main/java/grph/algo/TopologicalSortingAlgorithm.java | 2062 | /*
* (C) Copyright 2009-2013 CNRS.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* 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.
*
* Contributors:
Luc Hogie (CNRS, I3S laboratory, University of Nice-Sophia Antipolis)
Aurelien Lancin (Coati research team, Inria)
Christian Glacet (LaBRi, Bordeaux)
David Coudert (Coati research team, Inria)
Fabien Crequis (Coati research team, Inria)
Grégory Morel (Coati research team, Inria)
Issam Tahiri (Coati research team, Inria)
Julien Fighiera (Aoste research team, Inria)
Laurent Viennot (Gang research-team, Inria)
Michel Syska (I3S, University of Nice-Sophia Antipolis)
Nathann Cohen (LRI, Saclay)
*/
package grph.algo;
import grph.Grph;
import grph.GrphAlgorithm;
import java.util.Iterator;
import com.carrotsearch.hppc.IntArrayList;
import com.carrotsearch.hppc.cursors.IntCursor;
/**
* topological sort.
* @author lhogie
*
*/
public class TopologicalSortingAlgorithm extends GrphAlgorithm<IntArrayList>
{
@Override
public IntArrayList compute(Grph g)
{
IntArrayList vertices = IntArrayList.from(g.getVertices().toIntArray());
IntArrayList res = new IntArrayList();
IntArrayList inDegrees = g.getAllInEdgeDegrees();
while (!vertices.isEmpty())
{
Iterator<IntCursor> i = vertices.iterator();
while (i.hasNext())
{
IntCursor c = i.next();
if (inDegrees.get(c.value) == 0)
{
res.add(c.value);
i.remove();
for (IntCursor n : g.getOutNeighbors(c.value))
{
inDegrees.set(n.value, inDegrees.get(n.value) - 1);
}
}
}
}
return res;
}
}
| lgpl-3.0 |
OpenSoftwareSolutions/PDFReporter | pdfreporter-core/src/org/oss/pdfreporter/engine/type/HorizontalAlignEnum.java | 2364 | /*
* JasperReports - Free Java Reporting Library.
* Copyright (C) 2001 - 2011 Jaspersoft Corporation. All rights reserved.
* http://www.jaspersoft.com
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is part of JasperReports.
*
* JasperReports 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.
*
* JasperReports 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 JasperReports. If not, see <http://www.gnu.org/licenses/>.
*/
package org.oss.pdfreporter.engine.type;
import org.oss.pdfreporter.engine.JRConstants;
/**
* @author Teodor Danciu (teodord@users.sourceforge.net)
* @version $Id: HorizontalAlignEnum.java 4595 2011-09-08 15:55:10Z teodord $
*/
public enum HorizontalAlignEnum implements JREnum
{
/**
*
*/
LEFT((byte)1, "Left"),
/**
*
*/
CENTER((byte)2, "Center"),
/**
*
*/
RIGHT((byte)3, "Right"),
/**
*
*/
JUSTIFIED((byte)4, "Justified");
/**
*
*/
private static final long serialVersionUID = JRConstants.SERIAL_VERSION_UID;
private final transient byte value;
private final transient String name;
private HorizontalAlignEnum(byte value, String enumName)
{
this.value = value;
this.name = enumName;
}
/**
*
*/
public Byte getValueByte()
{
return new Byte(value);
}
/**
*
*/
public final byte getValue()
{
return value;
}
/**
*
*/
public String getName()
{
return name;
}
/**
*
*/
public static HorizontalAlignEnum getByName(String enumName)
{
return (HorizontalAlignEnum)EnumUtil.getByName(values(), enumName);
}
/**
*
*/
public static HorizontalAlignEnum getByValue(Byte value)
{
return (HorizontalAlignEnum)EnumUtil.getByValue(values(), value);
}
/**
*
*/
public static HorizontalAlignEnum getByValue(byte value)
{
return getByValue(new Byte(value));
}
}
| lgpl-3.0 |
RuedigerMoeller/kontraktor | modules/kontraktor-reallive/src/main/java/org/nustaq/reallive/impl/storage/OffHeapRecordStorage.java | 5643 | package org.nustaq.reallive.impl.storage;
import org.nustaq.kontraktor.Spore;
import org.nustaq.kontraktor.util.Log;
import org.nustaq.offheap.FSTAsciiStringOffheapMap;
import org.nustaq.offheap.FSTBinaryOffheapMap;
import org.nustaq.offheap.FSTSerializedOffheapMap;
import org.nustaq.reallive.api.*;
import org.nustaq.serialization.FSTConfiguration;
import org.nustaq.serialization.simpleapi.DefaultCoder;
import org.nustaq.serialization.simpleapi.FSTCoder;
import org.nustaq.serialization.util.FSTUtil;
import java.io.*;
import java.util.Iterator;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/**
* Created by moelrue on 05.08.2015.
*/
public class OffHeapRecordStorage implements RecordStorage {
private static final boolean DEBUG = false;
OutputStream protocol;
FSTCoder coder;
FSTSerializedOffheapMap<String,Record> store;
int keyLen;
protected OffHeapRecordStorage() {}
public OffHeapRecordStorage(int maxKeyLen, int sizeMB, int estimatedNumRecords) {
keyLen = maxKeyLen;
init(null, sizeMB, estimatedNumRecords, maxKeyLen, false, Record.class );
}
public OffHeapRecordStorage(String file, int maxKeyLen, int sizeMB, int estimatedNumRecords) {
keyLen = maxKeyLen;
if ( DEBUG ) {
try {
protocol = new FileOutputStream(new File(file+"_prot") );
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
init(file, sizeMB, estimatedNumRecords, maxKeyLen, true, Record.class );
}
protected void init(String tableFile, int sizeMB, int estimatedNumRecords, int keyLen, boolean persist, Class... toReg) {
this.keyLen = keyLen;
coder = new DefaultCoder();
if ( toReg != null )
coder.getConf().registerClass(toReg);
if ( persist ) {
try {
store = createPersistentMap(tableFile, sizeMB, estimatedNumRecords, keyLen);
} catch (Exception e) {
FSTUtil.rethrow(e);
}
}
else
store = createMemMap(sizeMB, estimatedNumRecords, keyLen);
}
protected FSTSerializedOffheapMap<String,Record> createMemMap(int sizeMB, int estimatedNumRecords, int keyLen) {
return new FSTAsciiStringOffheapMap<Record>(keyLen, FSTBinaryOffheapMap.MB*sizeMB,estimatedNumRecords, coder);
}
protected FSTSerializedOffheapMap<String,Record> createPersistentMap(String tableFile, int sizeMB, int estimatedNumRecords, int keyLen) throws Exception {
return new FSTAsciiStringOffheapMap(tableFile, keyLen, FSTBinaryOffheapMap.MB*sizeMB,estimatedNumRecords, coder);
}
public StorageStats getStats() {
StorageStats stats = new StorageStats()
.name(store.getFileName())
.capacity(store.getCapacityMB())
.freeMem(store.getFreeMem())
.usedMem(store.getUsedMem())
.numElems(store.getSize());
return stats;
}
@Override
public RecordStorage put(String key, Record value) {
value.internal_updateLastModified();
return _put(key,value);
}
public RecordStorage _put(String key, Record value) {
if ( protocol != null ) {
try {
FSTConfiguration.getDefaultConfiguration().encodeToStream(protocol,new Object[] {"putRecord",key,value});
protocol.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
store.put(key,value);
return this;
}
Thread _t;
void checkThread() {
if ( _t == null ) {
_t = Thread.currentThread();
} else if ( _t != Thread.currentThread() ){
throw new RuntimeException("Unexpected MultiThreading");
}
}
@Override
public Record get(String key) {
checkThread();
return store.get(key);
}
@Override
public Record remove(String key) {
if ( protocol != null ) {
try {
FSTConfiguration.getDefaultConfiguration().encodeToStream(protocol,new Object[] {"remove",key});
protocol.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
Record v = get(key);
if ( v != null ) {
store.remove(key);
v.internal_updateLastModified();
}
return v;
}
@Override
public long size() {
return store.getSize();
}
@Override
public Stream<Record> stream() {
return StreamSupport.stream(
Spliterators.spliteratorUnknownSize(store.values(), Spliterator.IMMUTABLE),
false);
}
@Override
public void resizeIfLoadFactorLarger(double loadFactor, long maxGrow) {
double lf = (double)store.getUsedMem()/(double)(store.getUsedMem()+store.getFreeMem());
if ( lf >= loadFactor ) {
store.resizeStore(store.getCapacityMB()*1024l*1024l * 2,maxGrow);
}
}
@Override
public <T> void forEachWithSpore(Spore<Record, T> spore) {
for (Iterator iterator = store.values(); iterator.hasNext(); ) {
Record record = (Record) iterator.next();
try {
spore.remote(record);
} catch ( Throwable ex ) {
Log.Warn(this, ex, "exception in spore " + spore);
throw ex;
}
if ( spore.isFinished() )
break;
}
spore.finish();
}
}
| lgpl-3.0 |
Godin/sonar | sonar-plugin-api/src/main/java/org/sonar/api/security/ExternalGroupsProvider.java | 2352 | /*
* 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.api.security;
import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
/**
* Note that prefix "do" for names of methods is reserved for future enhancements, thus should not be used in subclasses.
*
* @see SecurityRealm
* @since 2.14
*/
public abstract class ExternalGroupsProvider {
/**
* @return list of groups associated with specified user, or null if such user doesn't exist
* @throws RuntimeException in case of unexpected error such as connection failure
* @deprecated replaced by {@link #doGetGroups(org.sonar.api.security.ExternalGroupsProvider.Context)} since v. 5.2
*/
@Deprecated
public Collection<String> doGetGroups(String username) {
return null;
}
/**
* Override this method in order to load user group information.
*
* @return list of groups associated with specified user, or null if such user doesn't exist
* @throws RuntimeException in case of unexpected error such as connection failure
* @since 5.2
*/
public Collection<String> doGetGroups(Context context) {
return doGetGroups(context.getUsername());
}
public static final class Context {
private String username;
private HttpServletRequest request;
public Context(String username, HttpServletRequest request) {
this.username = username;
this.request = request;
}
public String getUsername() {
return username;
}
public HttpServletRequest getRequest() {
return request;
}
}
}
| lgpl-3.0 |
radkovo/jStyleParser | src/test/java/test/PageTest.java | 3505 | package test;
import cz.vutbr.web.css.*;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Date;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class PageTest {
private static final Logger log = LoggerFactory.getLogger(PageTest.class);
public static final TermFactory tf = CSSFactory.getTermFactory();
public static final String TEST_STRING1 =
"@page {\n" +
"@top-left-corner { content: \" \"; border: solid green; }" +
"}";
public static final String TEST_STRING2 = "@page :left { margin: 1cm; }";
public static final String TEST_STRING3 = "@page :right { margin: 2cm; }";
public static final String TEST_STRING4 = "@page :first { margin: 3cm; }";
public static final String TEST_STRING5 = "@page :hover { margin: 4cm; }"; // Invalid
@BeforeClass
public static void init() {
log.info("\n\n\n == PageTest test at {} == \n\n\n", new Date());
}
@Test
public void testMarginRule() throws IOException, CSSException {
log.info("input:\n\n\n" + TEST_STRING1 + "\n\n\n");
StyleSheet ss;
ss = CSSFactory.parseString(TEST_STRING1, null);
assertEquals("One rule is set", 1, ss.size());
RulePage rule = (RulePage) ss.get(0);
assertEquals("Rule contains 1 declaration ", 1, rule.size());
RuleMargin margin = (RuleMargin) rule.get(0);
assertEquals("Margin rule is @top-left-corner", RuleMargin.MarginArea.TOPLEFTCORNER, margin.getMarginArea());
assertEquals("Margin rule contains 2 declarations", 2, margin.size());
}
@Test
public void testLeftPseudo() throws IOException, CSSException {
StyleSheet ss = CSSFactory.parseString(TEST_STRING2, null);
assertEquals("One rule is set", 1, ss.size());
RulePage rule = (RulePage) ss.get(0);
assertNotNull("Rule has a pseudo-class ", rule.getPseudo());
assertEquals("Rule has :left pseudo-class ", Selector.PseudoPageType.LEFT, rule.getPseudo().getType());
assertEquals("Rule contains 1 declaration ", 1, rule.size());
}
@Test
public void testRightPseudo() throws IOException, CSSException {
StyleSheet ss = CSSFactory.parseString(TEST_STRING3, null);
assertEquals("One rule is set", 1, ss.size());
RulePage rule = (RulePage) ss.get(0);
assertNotNull("Rule has a pseudo-class ", rule.getPseudo());
assertEquals("Rule has :right pseudo-class ", Selector.PseudoPageType.RIGHT, rule.getPseudo().getType());
assertEquals("Rule contains 1 declaration ", 1, rule.size());
}
@Test
public void testFirstPseudo() throws IOException, CSSException {
StyleSheet ss = CSSFactory.parseString(TEST_STRING4, null);
assertEquals("One rule is set", 1, ss.size());
RulePage rule = (RulePage) ss.get(0);
assertNotNull("Rule has a pseudo-class ", rule.getPseudo());
assertEquals("Rule has :first pseudo-class ", Selector.PseudoPageType.FIRST, rule.getPseudo().getType());
assertEquals("Rule contains 1 declaration ", 1, rule.size());
}
@Test
public void testInvalidPseudo() throws IOException, CSSException {
StyleSheet ss = CSSFactory.parseString(TEST_STRING5, null);
assertEquals("No rules are set", 0, ss.size());
}
}
| lgpl-3.0 |
pmaingi/auction_manager | SVN_LOCAL/web/src/com/bryma/auction_manager/web/beans/Broadcast.java | 958 | package com.bryma.auction_manager.web.beans;
public class Broadcast {
private long id;
private String msisdn;
private String message;
/**
* @param id
* @param msisdn
* @param message
*/
public Broadcast(long id, String msisdn, String message) {
super();
this.id = id;
this.msisdn = msisdn;
this.message = message;
}
/**
* @return the id
*/
public long getId() {
return id;
}
/**
* @param id
* the id to set
*/
public void setId(long id) {
this.id = id;
}
/**
* @return the msisdn
*/
public String getMsisdn() {
return msisdn;
}
/**
* @param msisdn
* the msisdn to set
*/
public void setMsisdn(String msisdn) {
this.msisdn = msisdn;
}
/**
* @return the message
*/
public String getMessage() {
return message;
}
/**
* @param message
* the message to set
*/
public void setMessage(String message) {
this.message = message;
}
}
| lgpl-3.0 |
zhangyueshan/nirvana-push | push-protocol/src/main/java/com/nirvana/push/protocol/PayloadPart.java | 889 | package com.nirvana.push.protocol;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import java.nio.charset.Charset;
/**
* Base包的实际负载传输字节。
* Created by Nirvana on 2017/8/9.
*/
public class PayloadPart extends AbstractOutputable {
protected PayloadPart() {
}
public PayloadPart(Outputable outputable) {
byteBuf = outputable.getByteBuf();
}
public PayloadPart(ByteBuf buf) {
this.byteBuf = buf;
}
public PayloadPart(byte[] bytes) {
byteBuf = Unpooled.wrappedBuffer(bytes);
}
public PayloadPart(byte[] bytes, int offset, int length) {
byteBuf = Unpooled.wrappedBuffer(bytes, offset, length);
}
@Override
public String toString() {
return "PayloadPart{" +
"buf=" + byteBuf.toString(Charset.defaultCharset()) +
'}';
}
}
| lgpl-3.0 |
danrien/projectBlue | projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/stored/sync/GivenSynchronizingLibraries/AndAStoredFileWriteErrorOccurs/WhenSynchronizing.java | 5719 | package com.lasthopesoftware.bluewater.client.stored.sync.GivenSynchronizingLibraries.AndAStoredFileWriteErrorOccurs;
import androidx.test.core.app.ApplicationProvider;
import com.annimon.stream.Stream;
import com.lasthopesoftware.AndroidContext;
import com.lasthopesoftware.bluewater.client.browsing.library.access.ILibraryProvider;
import com.lasthopesoftware.bluewater.client.browsing.library.repository.Library;
import com.lasthopesoftware.bluewater.client.stored.library.items.files.job.StoredFileJobState;
import com.lasthopesoftware.bluewater.client.stored.library.items.files.job.StoredFileJobStatus;
import com.lasthopesoftware.bluewater.client.stored.library.items.files.job.exceptions.StoredFileWriteException;
import com.lasthopesoftware.bluewater.client.stored.library.items.files.repository.StoredFile;
import com.lasthopesoftware.bluewater.client.stored.library.sync.ControlLibrarySyncs;
import com.lasthopesoftware.bluewater.client.stored.sync.StoredFileSynchronization;
import com.lasthopesoftware.resources.FakeMessageBus;
import com.namehillsoftware.handoff.promises.Promise;
import org.junit.Test;
import java.io.File;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import io.reactivex.Observable;
import static com.lasthopesoftware.bluewater.client.stored.sync.StoredFileSynchronization.onFileDownloadedEvent;
import static com.lasthopesoftware.bluewater.client.stored.sync.StoredFileSynchronization.onFileDownloadingEvent;
import static com.lasthopesoftware.bluewater.client.stored.sync.StoredFileSynchronization.onFileQueuedEvent;
import static com.lasthopesoftware.bluewater.client.stored.sync.StoredFileSynchronization.onFileWriteErrorEvent;
import static com.lasthopesoftware.bluewater.client.stored.sync.StoredFileSynchronization.storedFileEventKey;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class WhenSynchronizing extends AndroidContext {
private static final Random random = new Random();
private static final StoredFile[] storedFiles = new StoredFile[] {
new StoredFile().setId(random.nextInt()).setServiceId(1).setLibraryId(4),
new StoredFile().setId(random.nextInt()).setServiceId(2).setLibraryId(4),
new StoredFile().setId(random.nextInt()).setServiceId(4).setLibraryId(4),
new StoredFile().setId(random.nextInt()).setServiceId(5).setLibraryId(4),
new StoredFile().setId(random.nextInt()).setServiceId(7).setLibraryId(4),
new StoredFile().setId(random.nextInt()).setServiceId(114).setLibraryId(4),
new StoredFile().setId(random.nextInt()).setServiceId(92).setLibraryId(4)
};
private static final List<StoredFile> expectedStoredFileJobs = Stream.of(storedFiles).filter(f -> f.getServiceId() != 7).toList();
private static final FakeMessageBus fakeMessageSender = new FakeMessageBus(ApplicationProvider.getApplicationContext());
@Override
public void before() {
final ILibraryProvider libraryProvider = mock(ILibraryProvider.class);
when(libraryProvider.getAllLibraries())
.thenReturn(new Promise<>(Collections.singletonList(new Library().setId(4))));
final ControlLibrarySyncs librarySyncHandler = mock(ControlLibrarySyncs.class);
when(librarySyncHandler.observeLibrarySync(any()))
.thenReturn(Observable.concat(
Observable
.fromArray(storedFiles)
.filter(f -> f.getServiceId() != 7)
.flatMap(f -> Observable.just(
new StoredFileJobStatus(mock(File.class), f, StoredFileJobState.Queued),
new StoredFileJobStatus(mock(File.class), f, StoredFileJobState.Downloading),
new StoredFileJobStatus(mock(File.class), f, StoredFileJobState.Downloaded))),
Observable
.fromArray(storedFiles)
.filter(f -> f.getServiceId() == 7)
.flatMap(f ->
Observable.concat(Observable.just(
new StoredFileJobStatus(mock(File.class), f, StoredFileJobState.Queued),
new StoredFileJobStatus(mock(File.class), f, StoredFileJobState.Downloading)),
Observable.error(new StoredFileWriteException(mock(File.class), f))), true)));
final StoredFileSynchronization synchronization = new StoredFileSynchronization(
libraryProvider,
fakeMessageSender,
librarySyncHandler);
synchronization.streamFileSynchronization().blockingAwait();
}
@Test
public void thenTheStoredFilesAreBroadcastAsQueued() {
assertThat(Stream.of(fakeMessageSender.getRecordedIntents())
.filter(i -> onFileQueuedEvent.equals(i.getAction()))
.map(i -> i.getIntExtra(storedFileEventKey, -1))
.toList()).isSubsetOf(Stream.of(storedFiles).map(StoredFile::getId).toList());
}
@Test
public void thenTheStoredFilesAreBroadcastAsDownloading() {
assertThat(Stream.of(fakeMessageSender.getRecordedIntents())
.filter(i -> onFileDownloadingEvent.equals(i.getAction()))
.map(i -> i.getIntExtra(storedFileEventKey, -1))
.toList()).isSubsetOf(Stream.of(storedFiles).map(StoredFile::getId).toList());
}
@Test
public void thenTheWriteErrorsIsBroadcast() {
assertThat(Stream.of(fakeMessageSender.getRecordedIntents())
.filter(i -> onFileWriteErrorEvent.equals(i.getAction()))
.map(i -> i.getIntExtra(storedFileEventKey, -1))
.toList()).containsExactlyElementsOf(Stream.of(storedFiles).filter(f -> f.getServiceId() == 7).map(StoredFile::getId).toList());
}
@Test
public void thenTheStoredFilesAreBroadcastAsDownloaded() {
assertThat(Stream.of(fakeMessageSender.getRecordedIntents())
.filter(i -> onFileDownloadedEvent.equals(i.getAction()))
.map(i -> i.getIntExtra(storedFileEventKey, -1))
.toList()).isSubsetOf(Stream.of(expectedStoredFileJobs).map(StoredFile::getId).toList());
}
}
| lgpl-3.0 |
gudenau/Delver-Loader | source/com/gudenau/delverLoader/DelverLoader.java | 2793 | package com.gudenau.delverLoader;
import java.io.File;
import java.io.FilenameFilter;
import java.lang.reflect.Method;
import java.security.Policy;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.gudenau.delverLoader.classloading.ClassLoadingHandler;
import com.gudenau.delverLoader.classloading.DelverClassLoader;
import com.gudenau.delverLoader.mods.ActorModification;
import com.gudenau.delverLoader.mods.EntityModification;
import com.gudenau.delverLoader.mods.GameModification;
import com.gudenau.delverLoader.util.LoggerUtils;
import com.gudenau.pluginloader.PluginContainer;
import com.gudenau.pluginloader.PluginLoader;
import com.gudenau.pluginloader.PluginPolicy;
public class DelverLoader {
private Logger primaryLogger;
private List<PluginContainer> modContainers = new ArrayList<PluginContainer>();
protected DelverLoader(){
primaryLogger = LoggerUtils.getPrimaryLogger();
}
protected void main(String[] args) throws Throwable {
DelverClassLoader loader = (DelverClassLoader) getClass().getClassLoader();
primaryLogger.log(Level.FINEST, "Creating policy");
Policy.setPolicy(new PluginPolicy());
primaryLogger.log(Level.FINEST, "Creating security manager");
System.setSecurityManager(new SecurityManager());
primaryLogger.log(Level.FINEST, "Adding base modifications");
loader.addClassLoadingHandler(new GameModification());
loader.addClassLoadingHandler(new EntityModification());
loader.addClassLoadingHandler(new ActorModification());
primaryLogger.log(Level.FINEST, "Loading mods");
loadMods(loader);
primaryLogger.log(Level.FINEST, "Loading DesktopStarter");
Class<?> DesktopStarter = loader.loadClass("com.interrupt.dungeoneer.DesktopStarter");
primaryLogger.log(Level.FINEST, "Getting main");
Method main = DesktopStarter.getDeclaredMethod("main", String[].class);
primaryLogger.log(Level.FINEST, "Starting Delver");
main.invoke(null, new Object[]{new String[]{}});
}
private void loadMods(ClassLoader classLoader) {
File modsDir = new File("./mods");
if(!modsDir.exists()){
modsDir.mkdirs();
}
File[] modsList = modsDir.listFiles(new FilenameFilter(){
@Override
public boolean accept(File file, String name) {
return name.endsWith(".jar") && file.isFile();
}
});
primaryLogger.log(Level.FINEST, "Found " + modsList.length + " jars");
for(File mod : modsList){
try {
primaryLogger.log(Level.FINEST, "Loading mod \"" + mod.getName() + "\"");
PluginContainer plugin = PluginLoader.loadPlugin(mod, classLoader);
modContainers.add(plugin);
} catch (Exception e) {
primaryLogger.log(Level.INFO, "Mod \"" + mod.getName() + "\" has caused an exception", e);
}
}
}
}
| lgpl-3.0 |
ceharris/SchemaCrawler | schemacrawler-api/src/main/java/schemacrawler/crawl/AbstractProperty.java | 2877 | /*
*
* SchemaCrawler
* http://www.schemacrawler.com
* Copyright (c) 2000-2015, Sualeh Fatehi.
*
* This library is free software; you can redistribute it and/or modify it under the terms
* of the GNU Lesser General Public License as published by the Free Software Foundation;
* either version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307, USA.
*
*/
package schemacrawler.crawl;
import static sf.util.Utility.isBlank;
import java.io.Serializable;
import java.util.Arrays;
import schemacrawler.schema.Property;
abstract class AbstractProperty
implements Property
{
private static final long serialVersionUID = -7150431683440256142L;
private final String name;
private final Serializable value;
AbstractProperty(final String name, final Serializable value)
{
if (isBlank(name))
{
throw new IllegalArgumentException("No property name provided");
}
this.name = name.trim();
if (value != null && value.getClass().isArray())
{
this.value = (Serializable) Arrays.asList((Object[]) value);
}
else
{
this.value = value;
}
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public final boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (!(obj instanceof AbstractProperty))
{
return false;
}
final AbstractProperty other = (AbstractProperty) obj;
if (name == null)
{
if (other.name != null)
{
return false;
}
}
else if (!name.equals(other.name))
{
return false;
}
if (value == null)
{
if (other.value != null)
{
return false;
}
}
else if (!value.equals(other.value))
{
return false;
}
return true;
}
/**
* {@inheritDoc}
*/
@Override
public final String getName()
{
return name;
}
/**
* {@inheritDoc}
*/
@Override
public Serializable getValue()
{
return value;
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#hashCode()
*/
@Override
public final int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (name == null? 0: name.hashCode());
result = prime * result + (value == null? 0: value.hashCode());
return result;
}
}
| lgpl-3.0 |
anandswarupv/DataCleaner | engine/core/src/main/java/org/datacleaner/descriptors/SimpleDescriptorProvider.java | 6988 | /**
* DataCleaner (community edition)
* 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.datacleaner.descriptors;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.datacleaner.api.Analyzer;
import org.datacleaner.api.Filter;
import org.datacleaner.api.Renderer;
import org.datacleaner.api.Transformer;
/**
* A simple descriptor provider with a method signature suitable externalizing
* class names of analyzer and transformer beans. For example, if you're using
* the Spring Framework you initialize this descriptor provider as follows:
*
* <pre>
* <bean id="descriptorProvider" class="org.datacleaner.descriptors.SimpleDescriptorProvider">
* <property name="analyzerClassNames">
* <list>
* <value>org.datacleaner.beans.StringAnalyzer</value>
* <value>org.datacleaner.beans.valuedist.ValueDistributionAnalyzer</value>
* ...
* </list>
* </property>
* <property name="transformerClassNames">
* <list>
* <value>org.datacleaner.beans.TokenizerTransformer</value>
* ...
* </list>
* </property>
* <property name="rendererClassNames">
* <list>
* <value>org.datacleaner.result.renderer.DefaultTextRenderer</value>
* ...
* </list>
* </property>
* </bean>
* </pre>
*
*
*/
public class SimpleDescriptorProvider extends AbstractDescriptorProvider {
private List<AnalyzerDescriptor<?>> _analyzerBeanDescriptors = new ArrayList<AnalyzerDescriptor<?>>();
private List<TransformerDescriptor<?>> _transformerBeanDescriptors = new ArrayList<TransformerDescriptor<?>>();
private List<RendererBeanDescriptor<?>> _rendererBeanDescriptors = new ArrayList<RendererBeanDescriptor<?>>();
private List<FilterDescriptor<?, ?>> _filterBeanDescriptors = new ArrayList<FilterDescriptor<?, ?>>();
public SimpleDescriptorProvider() {
this(true);
}
public SimpleDescriptorProvider(boolean autoDiscover) {
super(autoDiscover);
}
public void addAnalyzerBeanDescriptor(AnalyzerDescriptor<?> analyzerBeanDescriptor) {
_analyzerBeanDescriptors.add(analyzerBeanDescriptor);
}
public void addTransformerBeanDescriptor(TransformerDescriptor<?> transformerBeanDescriptor) {
_transformerBeanDescriptors.add(transformerBeanDescriptor);
}
public void addRendererBeanDescriptor(RendererBeanDescriptor<?> rendererBeanDescriptor) {
_rendererBeanDescriptors.add(rendererBeanDescriptor);
}
public void addFilterBeanDescriptor(FilterDescriptor<?, ?> descriptor) {
_filterBeanDescriptors.add(descriptor);
}
@Override
public List<AnalyzerDescriptor<?>> getAnalyzerDescriptors() {
return _analyzerBeanDescriptors;
}
public void setAnalyzerBeanDescriptors(List<AnalyzerDescriptor<?>> descriptors) {
_analyzerBeanDescriptors = descriptors;
}
@Override
public List<TransformerDescriptor<?>> getTransformerDescriptors() {
return _transformerBeanDescriptors;
}
public void setTransformerBeanDescriptors(List<TransformerDescriptor<?>> transformerBeanDescriptors) {
_transformerBeanDescriptors = transformerBeanDescriptors;
}
@Override
public List<RendererBeanDescriptor<?>> getRendererBeanDescriptors() {
return _rendererBeanDescriptors;
}
public void setRendererBeanDescriptors(List<RendererBeanDescriptor<?>> rendererBeanDescriptors) {
_rendererBeanDescriptors = rendererBeanDescriptors;
}
@Override
public Collection<FilterDescriptor<?, ?>> getFilterDescriptors() {
return _filterBeanDescriptors;
}
public void setFilterBeanDescriptors(List<FilterDescriptor<?, ?>> filterBeanDescriptors) {
_filterBeanDescriptors = filterBeanDescriptors;
}
public void setAnalyzerClassNames(Collection<String> classNames) throws ClassNotFoundException {
for (String className : classNames) {
@SuppressWarnings("unchecked")
Class<? extends Analyzer<?>> c = (Class<? extends Analyzer<?>>) Class.forName(className);
AnalyzerDescriptor<?> descriptor = getAnalyzerDescriptorForClass(c);
if (descriptor == null || !_analyzerBeanDescriptors.contains(descriptor)) {
addAnalyzerBeanDescriptor(Descriptors.ofAnalyzer(c));
}
}
}
public void setTransformerClassNames(Collection<String> classNames) throws ClassNotFoundException {
for (String className : classNames) {
@SuppressWarnings("unchecked")
Class<? extends Transformer> c = (Class<? extends Transformer>) Class.forName(className);
TransformerDescriptor<?> descriptor = getTransformerDescriptorForClass(c);
if (descriptor == null || !_transformerBeanDescriptors.contains(descriptor)) {
addTransformerBeanDescriptor(Descriptors.ofTransformer(c));
}
}
}
public void setRendererClassNames(Collection<String> classNames) throws ClassNotFoundException {
for (String className : classNames) {
@SuppressWarnings("unchecked")
Class<? extends Renderer<?, ?>> c = (Class<? extends Renderer<?, ?>>) Class.forName(className);
RendererBeanDescriptor<?> descriptor = getRendererBeanDescriptorForClass(c);
if (descriptor == null || !_rendererBeanDescriptors.contains(descriptor)) {
addRendererBeanDescriptor(Descriptors.ofRenderer(c));
}
}
}
public void setFilterClassNames(Collection<String> classNames) throws ClassNotFoundException {
for (String className : classNames) {
@SuppressWarnings("unchecked")
Class<? extends Filter<?>> c = (Class<? extends Filter<?>>) Class.forName(className);
FilterDescriptor<?, ?> descriptor = getFilterBeanDescriptorForClassUnbounded(c);
if (descriptor == null || !_filterBeanDescriptors.contains(descriptor)) {
addFilterBeanDescriptor(Descriptors.ofFilterUnbound(c));
}
}
}
}
| lgpl-3.0 |
mshonle/Arcum | src/edu/ucsd/arcum/interpreter/query/TraitValue.java | 3032 | package edu.ucsd.arcum.interpreter.query;
import static edu.ucsd.arcum.util.StringUtil.separate;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import edu.ucsd.arcum.exceptions.ArcumError;
import edu.ucsd.arcum.interpreter.ast.FormalParameter;
import edu.ucsd.arcum.interpreter.ast.TraitSignature;
import edu.ucsd.arcum.interpreter.satisfier.BindingMap;
import edu.ucsd.arcum.interpreter.satisfier.BindingsSet;
public class TraitValue
{
private final String traitName;
private final TraitSignature traitType;
private final Set<EntityTuple> entities;
private final boolean isStatic;
private final boolean isNested;
public TraitValue(String traitName, TraitSignature tupleSetType) {
this(traitName, tupleSetType, false, false);
}
public TraitValue(String traitName, TraitSignature tupleSetType, boolean isStatic,
boolean isNested)
{
this.traitName = traitName;
this.traitType = tupleSetType;
this.entities = Sets.newTreeSet();
this.isStatic = isStatic;
this.isNested = isNested;
}
public EntityTuple getSingleton() {
if (entities.size() != 1) {
ArcumError.fatalError("Non-singleton");
}
return entities.iterator().next();
}
public List<EntityTuple> getEntities() {
return Lists.newArrayList(entities);
}
// Returns true if this set did not already contain the specified element
public boolean addTuple(EntityTuple entityTuple) {
return entities.add(entityTuple);
}
@Override public String toString() {
return String.format("{%s}", separate(entities, String.format("%n ")));
}
public String getTraitName() {
return traitName;
}
public TraitSignature getTraitType() {
return traitType;
}
public boolean isStatic() {
return isStatic;
}
public boolean isNested() {
return isNested;
}
public Collection<String> getNamesOfDeclaredFormals() {
return traitType.getNamesOfDeclaredFormals();
}
// An arg in the "args" list is either a program entity or a VariablePlaceholder.
// Arguments are assumed to be in order.
public BindingsSet getMatches(List<Object> args, BindingMap in) {
List<FormalParameter> formals = traitType.getFormals();
BindingsSet result = BindingsSet.newEmptySet();
for (EntityTuple entity : entities) {
BindingMap theta = entity.matches(formals, args);
if (theta != null) {
result.addEntry(theta);
}
}
for (BindingMap bindingMap : result) {
// We add these later so that addEntry doesn't have to compare as many
// items
bindingMap.addBindings(in);
}
return result;
}
} | lgpl-3.0 |
xinghuangxu/xinghuangxu.sonarqube | sonar-core/src/main/java/org/sonar/core/dashboard/WidgetMapper.java | 991 | /*
* 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.core.dashboard;
public interface WidgetMapper {
void insert(WidgetDto widgetDto);
}
| lgpl-3.0 |
yangjiandong/appjruby | app-deprecated/src/main/java/org/sonar/api/checks/templates/CheckTemplate.java | 3216 | /*
* Sonar, open source software quality management tool.
* Copyright (C) 2009 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* Sonar 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.
*
* Sonar 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 Sonar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.api.checks.templates;
import org.sonar.check.IsoCategory;
import org.sonar.check.Priority;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
/**
* @since 2.1 (experimental)
* @deprecated since 2.3
*/
@Deprecated
public abstract class CheckTemplate {
protected String key;
protected String configKey;
protected Priority priority;
protected IsoCategory isoCategory;
protected List<CheckTemplateProperty> properties;
public CheckTemplate(String key) {
this.key = key;
}
public CheckTemplate() {
}
public String getKey() {
return key;
}
public void setKey(String s) {
this.key = s;
}
public Priority getPriority() {
return priority;
}
public void setPriority(Priority p) {
this.priority = p;
}
public IsoCategory getIsoCategory() {
return isoCategory;
}
public void setIsoCategory(IsoCategory c) {
this.isoCategory = c;
}
public String getConfigKey() {
return configKey;
}
public void setConfigKey(String configKey) {
this.configKey = configKey;
}
public abstract String getTitle(Locale locale);
public abstract String getDescription(Locale locale);
public abstract String getMessage(Locale locale, String key, Object... params);
public List<CheckTemplateProperty> getProperties() {
if (properties==null) {
return Collections.emptyList();
}
return properties;
}
public void addProperty(CheckTemplateProperty p) {
if (properties==null) {
properties = new ArrayList<CheckTemplateProperty>();
}
properties.add(p);
}
public CheckTemplateProperty getProperty(String key) {
if (properties!=null) {
for (CheckTemplateProperty property : properties) {
if (property.getKey().equals(key)) {
return property;
}
}
}
return null;
}
/**
* Checks are equal within the same plugin. Two plugins can have two different checks with the same key.
*/
@Override
public final boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof CheckTemplate)) {
return false;
}
CheckTemplate checkTemplate = (CheckTemplate) o;
return key.equals(checkTemplate.key);
}
@Override
public final int hashCode() {
return key.hashCode();
}
} | lgpl-3.0 |
btrplace/scheduler-UCC-15 | simgrid/src/main/java/org/btrplace/simgrid/SimgridModelBuilder.java | 15368 | /*
* Copyright (c) 2014 University Nice Sophia Antipolis
*
* This file is part of btrplace.
* 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.
*
* 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 program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.btrplace.simgrid;
import org.btrplace.model.DefaultModel;
import org.btrplace.model.Model;
import org.btrplace.model.Node;
import org.btrplace.model.view.NamingService;
import org.btrplace.model.view.ShareableResource;
import org.btrplace.model.view.net.NetworkView;
import org.btrplace.model.view.net.Port;
import org.btrplace.model.view.net.StaticRouting;
import org.btrplace.model.view.net.Switch;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
/**
* Default implementation for a {@link org.btrplace.model.Model}.
*
* @author Vincent Kherbache
*/
public class SimgridModelBuilder {
private NamingService<Node> nsNodes;
private NamingService<Switch> nsSwitches;
private ShareableResource rcCPU;
private List<Node> nodes;
private Map<String, List<Port>> links;
public Model build(File xml) {
nodes = new ArrayList<>();
links = new HashMap<>();
Model mo = new DefaultModel();
// Create and attach the nodes' namingService view
nsNodes = NamingService.newNodeNS();
mo.attach(nsNodes);
// Create and attach the switches' namingService view
nsSwitches = NamingService.newSwitchNS();
mo.attach(nsSwitches);
// Create and attach the shareableResource view
rcCPU = new ShareableResource("core", 1, 1);
mo.attach(rcCPU);
// Import nodes from Simgrid XML file
try {
importNodes(mo, xml);
} catch(Exception e) {
System.err.println("Error during Simgrid nodes import: " + e.toString());
e.printStackTrace();
}
// Create and attach the network view
NetworkView netView = new NetworkView(new StaticRouting());
mo.attach(netView);
// Import routes from Simgrid XML file
try {
importRoutes(netView, xml);
} catch(Exception e) {
System.err.println("Error during Simgrid routes import: " + e.toString());
e.printStackTrace();
}
return mo;
}
private void importNodes(Model mo, File xml) throws Exception {
if (!xml.exists()) throw new FileNotFoundException("File '" + xml.getName() + "' not found");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xml);
doc.getDocumentElement().normalize();
// Root is on the first AS (id='grid5000.fr')
Element root = (Element) doc.getElementsByTagName("AS").item(0);
// Get the list of sites
NodeList sitesList = root.getElementsByTagName("AS");
// For all sites
for (int i=0; i<sitesList.getLength(); i++) {
org.w3c.dom.Node nSite = sitesList.item(i);
if (nSite.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
org.w3c.dom.Element eSite = (org.w3c.dom.Element) nSite;
String siteId = eSite.getAttribute("id");
// Parse host to assign names on provided nodes
NodeList hostsList = eSite.getElementsByTagName("host");
for (int j = 0; j < hostsList.getLength(); j++) {
org.w3c.dom.Node node = hostsList.item(j);
if (node.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
org.w3c.dom.Element host = (org.w3c.dom.Element) node;
// Create a new node with the right name
String id = host.getAttribute("id").replace("." + siteId, "");
int core = Integer.valueOf(host.getAttribute("core"));
double power = Double.valueOf(host.getAttribute("power"));
Node n = mo.newNode();
nsNodes.register(n, id);
nodes.add(n);
// Set cpu capacity
rcCPU.setCapacity(n, core);
}
}
}
}
}
private void importRoutes(NetworkView nv, File xml) throws Exception {
if (!xml.exists()) throw new FileNotFoundException("File '" + xml.getName() + "' not found");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xml);
doc.getDocumentElement().normalize();
// Root is on the first AS (id='grid5000.fr')
Element root = (Element) doc.getElementsByTagName("AS").item(0);
// Get the list of sites
NodeList sitesList = root.getElementsByTagName("AS");
// For all sites
for (int i=0; i<sitesList.getLength(); i++) {
org.w3c.dom.Node nSite = sitesList.item(i);
if (nSite.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
Element eSite = (Element) nSite;
String siteId = eSite.getAttribute("id");
boolean found;
// Parse router as a switch
NodeList routersList = eSite.getElementsByTagName("router");
for (int j=0; j<routersList.getLength(); j++) {
org.w3c.dom.Node nRouter = routersList.item(j);
if (nRouter.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
Element eRouter = (Element) nRouter;
// Create the new switch
String id = eRouter.getAttribute("id").replace("." + siteId, "");
Switch sw = nv.newSwitch();
nsSwitches.register(sw, id);
}
}
// Parse links
NodeList linksList = eSite.getElementsByTagName("link");
for (int j = 0; j < linksList.getLength(); j++) {
org.w3c.dom.Node nLink = linksList.item(j);
if (nLink.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
Element eLink = (Element) nLink;
// Connect elements
String id = eLink.getAttribute("id");
String src = id.split("_")[0].replace("." + siteId, "");
String dst = id.split("_")[1].replace("." + siteId, "");
int bandwidth = (int) (Long.valueOf(eLink.getAttribute("bandwidth")) / 1000000);
double latency = Double.valueOf(eLink.getAttribute("latency"));
//TODO: just a temporary patch (doublon: already declared in root links)
if (src.contains("renater") || dst.contains("renater")) { continue; }
// Create a new switch if detected (switch entry does not exists)
if (src.contains("-sw") || src.contains("force10") || src.contains("mxl1")
|| src.contains("edgeiron") || src.contains("sgriffon") || src.contains("sgraphene")) {
if (nsSwitches.resolve(src) == null) {
Switch sw = nv.newSwitch();
nsSwitches.register(sw, src);
}
}
if (dst.contains("-sw") || dst.contains("force10") || dst.contains("mxl1")
|| dst.contains("edgeiron") || dst.contains("sgriffon") || dst.contains("sgraphene")) {
if (nsSwitches.resolve(dst) == null) {
Switch sw = nv.newSwitch();
nsSwitches.register(sw, dst);
}
}
if (nsSwitches.resolve(src) != null) {
// Connect two switches
if (nsSwitches.resolve(dst) != null) {
nsSwitches.resolve(src).connect(bandwidth, nsSwitches.resolve(dst));
links.put(id, Arrays.asList(
nsSwitches.resolve(src).getPorts().get(nsSwitches.resolve(src).getPorts().size() - 1),
nsSwitches.resolve(dst).getPorts().get(nsSwitches.resolve(dst).getPorts().size() - 1))
);
}
// Switch to node
else {
nsSwitches.resolve(src).connect(bandwidth, nsNodes.resolve(dst));
links.put(id, Arrays.asList(
nsSwitches.resolve(src).getPorts().get(nsSwitches.resolve(src).getPorts().size() - 1),
nv.getSwitchInterface(nsNodes.resolve(dst)))
);
}
} else if (nsSwitches.resolve(dst) != null) {
// Node to switch
nsSwitches.resolve(dst).connect(bandwidth, nsNodes.resolve(src));
links.put(id, Arrays.asList(
nv.getSwitchInterface(nsNodes.resolve(src)),
nsSwitches.resolve(dst).getPorts().get(nsSwitches.resolve(dst).getPorts().size() - 1))
);
}
}
}
/* TODO: routes that are not between two end nodes are useless
// Parse routes
NodeList routesList = site.getElementsByTagName("route");
for (int j=0; j<routesList.getLength(); j++) {
org.w3c.dom.Node nRoute = routesList.item(j);
if (nRoute.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
Element route = (Element) nRoute;
String src = route.getAttribute("src").replace("."+siteId, "");
String dst = route.getAttribute("dst").replace("."+siteId, "");
org.btrplace.model.Element srcElt = null, dstElt = null;
for (String n : nodes.keySet()) {
if (n.equals(src)) { srcElt = nodes.get(n); break; }
}
if (srcElt == null) {
for (String n : switches.keySet()) {
if (n.equals(src)) { srcElt = switches.get(n); break; }
}
if (srcElt == null) throw new Exception("Cannot find the id '"+ src +"'");
}
for (String n : nodes.keySet()) {
if (n.equals(dst)) { dstElt = nodes.get(n); break; }
}
if (dstElt == null) {
for (String n : switches.keySet()) {
if (n.equals(dst)) { dstElt = switches.get(n); break; }
}
if (dstElt == null) throw new Exception("Cannot find the id '"+ dst +"'");
}
NodesMap nodesMap = new NodesMap(srcElt, dstElt);
List<Port> ports = new ArrayList<>();
// Parse route's links
NodeList linksList = route.getElementsByTagName("link_ctn");
for (int k=0; k<linksList.getLength(); k++) {
Element link = (Element) linksList.item(k);
String id = link.getAttribute("id");
// Get all the link's ports
found = false;
for (String l : links.keySet()) {
if (l.equals(id)) { ports.addAll(links.get(l)); found = true; break; }
}
if (!found) throw new Exception("Cannot find the link with id '"+ id +"'");
}
// Add the new route to the view
((StaticRouting)netView.getRouting()).addStaticRoute(nodesMap, ports);
}
}
*/
}
}
// Add inter-sites links
NodeList linksList = root.getElementsByTagName("link");
// For all sites
for (int i=0; i<linksList.getLength(); i++) {
org.w3c.dom.Node nLink = linksList.item(i);
// Only look at first child
if (root.equals(nLink.getParentNode()) && nLink.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
Element eLink = (Element) nLink;
// Connect root switches
String id = eLink.getAttribute("id");
String src = id.split("_")[0].contains("gw-") ? id.split("_")[0].split("\\.")[0] : id.split("_")[0];
String dst = id.split("_")[1].contains("gw-") ? id.split("_")[1].split("\\.")[0] : id.split("_")[1];
int bandwidth = (int) (Long.valueOf(eLink.getAttribute("bandwidth")) / 1000000);
double latency = Double.valueOf(eLink.getAttribute("latency"));
// Replace '.' by '-' for consistency
if (src.contains("renater")) src = src.replace(".", "-");
if (dst.contains("renater")) dst = dst.replace(".", "-");
// We assumes they are all switches
if (nsSwitches.resolve(src) == null) {
Switch sw = nv.newSwitch();
nsSwitches.register(sw, src);
}
if (nsSwitches.resolve(dst) == null) {
Switch sw = nv.newSwitch();
nsSwitches.register(sw, dst);
}
// Connect them together
nsSwitches.resolve(src).connect(bandwidth, nsSwitches.resolve(dst));
links.put(id, Arrays.asList(
nsSwitches.resolve(src).getPorts().get(nsSwitches.resolve(src).getPorts().size() - 1),
nsSwitches.resolve(dst).getPorts().get(nsSwitches.resolve(dst).getPorts().size() - 1))
);
}
}
}
}
| lgpl-3.0 |
awltech/eclipse-optimus | net.atos.optimus.m2m.engine.sdk.parent/net.atos.optimus.m2m.engine.sdk.tom.diagram/src/main/java/net/atos/optimus/m2m/engine/sdk/tom/diagram/edit/policies/TransformationSetExtensionTransformationSetExtensionCompartmentItemSemanticEditPolicy.java | 1063 | package net.atos.optimus.m2m.engine.sdk.tom.diagram.edit.policies;
import net.atos.optimus.m2m.engine.sdk.tom.diagram.edit.commands.Transformation2CreateCommand;
import net.atos.optimus.m2m.engine.sdk.tom.diagram.providers.TransformationDependencyElementTypes;
import org.eclipse.gef.commands.Command;
import org.eclipse.gmf.runtime.emf.type.core.requests.CreateElementRequest;
/**
* @generated
*/
public class TransformationSetExtensionTransformationSetExtensionCompartmentItemSemanticEditPolicy extends
TransformationDependencyBaseItemSemanticEditPolicy {
/**
* @generated
*/
public TransformationSetExtensionTransformationSetExtensionCompartmentItemSemanticEditPolicy() {
super(TransformationDependencyElementTypes.TransformationSetExtension_2005);
}
/**
* @generated
*/
protected Command getCreateCommand(CreateElementRequest req) {
if (TransformationDependencyElementTypes.Transformation_3004 == req.getElementType()) {
return getGEFWrapper(new Transformation2CreateCommand(req));
}
return super.getCreateCommand(req);
}
}
| lgpl-3.0 |
SergiyKolesnikov/fuji | examples/AHEAD/ast/VlstEscape.java | 371 |
import java.io.PrintWriter;
//**************************************************
// VlstEscape extension class
//**************************************************
public class VlstEscape
implements EscapeMarker, IsList {
public void reduce2ast( AstProperties props ) {
reduce2astEscape( props, "AST_VarDecl" );
}
}
| lgpl-3.0 |
xinghuangxu/xinghuangxu.sonarqube | sonar-core/src/main/java/org/sonar/core/graph/graphson/GraphsonMode.java | 1508 | /*
* 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.core.graph.graphson;
/**
* Modes of operation of the GraphSONUtility.
*
* @author Stephen Mallette
*/
public enum GraphsonMode {
/**
* COMPACT constructs GraphSON on the assumption that all property keys
* are fair game for exclusion including _type, _inV, _outV, _label and _id.
* It is possible to write GraphSON that cannot be read back into Graph,
* if some or all of these keys are excluded.
*/
COMPACT,
/**
* NORMAL includes the _type field and JSON data typing.
*/
NORMAL,
/**
* EXTENDED includes the _type field and explicit data typing.
*/
EXTENDED
}
| lgpl-3.0 |
green-vulcano/gv-legacy | gvlegacy/gvdatahandler/src/main/java/it/greenvulcano/gvesb/datahandling/IDBO.java | 4685 | /*******************************************************************************
* Copyright (c) 2009, 2016 GreenVulcano ESB Open Source Project.
* All rights reserved.
*
* This file is part of GreenVulcano ESB.
*
* GreenVulcano ESB 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.
*
* GreenVulcano ESB 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 GreenVulcano ESB. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************/
package it.greenvulcano.gvesb.datahandling;
import java.io.OutputStream;
import java.sql.Connection;
import java.util.Map;
import org.w3c.dom.Node;
/**
* Interface implemented from classes that interact with the DB.
*
* @version 3.0.0 Mar 30, 2010
* @author GreenVulcano Developer Team
*
*
*/
public interface IDBO
{
/**
*
*/
public static final String MODE_CALLER = "caller";
/**
*
*/
public static final String MODE_XML2DB = "xml2db";
/**
*
*/
public static final String MODE_DB2XML = "db2xml";
/**
*
*/
public static final String MODE_CALL = "call";
/**
* Method to implement to configure the object that implements this
* interface.
*
* @param config
* XML node that contains configuration parameters.
* @throws DBOException
* whenever the configuration is wrong.
*/
public void init(Node config) throws DBOException;
/**
* Method <i>execute</i> implemented by IDBO classes having update
* interaction with DB.
*
* @param input
* data to insert or update on DB.
* @param conn
* connection towards the DB.
* @param props
* parameters to substitute in the SQL statement to execute.
* @throws DBOException
* if any error occurs.
*/
public void execute(Object input, Connection conn, Map<String, Object> props, Object object) throws DBOException,
InterruptedException;
/**
* Method <i>execute</i> implemented by IDBO classes having read interaction
* with DB.
*
* @param data
* data returned from the DB.
* @param conn
* connection towards the DB.
* @param props
* parameters to substitute in the SQL statement to execute.
* @throws DBOException
* if any error occurs.
*/
public void execute(OutputStream data, Connection conn, Map<String, Object> props) throws DBOException,
InterruptedException;
/**
* @param dataIn
* @param dataOut
* @param conn
* @param props
* @throws DBOException
*/
public void execute(Object dataIn, OutputStream dataOut, Connection conn, Map<String, Object> props)
throws DBOException, InterruptedException;
/**
* @return the configured name of this IDBO
*/
public String getName();
/**
* Sets the transaction state of the operation. If false, the IDBO object
* must internally handle errors occurred in case of inserting or updating.
*
* @param transacted
*
*/
public void setTransacted(boolean transacted);
/**
* Returns the transformation's name to execute.
*
* @return the transformation's name to execute.
*/
public String getTransformation();
/**
* Executes cleanup operations.
*/
public void cleanup();
/**
* Executes finalization operations.
*/
public void destroy();
/**
* @param serviceName
*/
public void setServiceName(String serviceName);
/**
* @param connectionName
*/
public void setJdbcConnectionName(String connectionName);
/**
* @return the input data name
*/
public String getInputDataName();
/**
* @return the output data name
*/
public String getOutputDataName();
/**
* @return if forced mode enabled
*/
public String getForcedMode();
/**
* @return the execution result
*/
public DHResult getExecutionResult();
/**
* @return if returns data.
*/
public boolean isReturnData();
}
| lgpl-3.0 |
kroghnet/jawn | jawn-core/src/test/java/app/controllers/testing/more/CakeFrostingsController.java | 170 | package app.controllers.testing.more;
import net.javapla.jawn.core.Controller;
public class CakeFrostingsController extends Controller {
public void getBuns(){}
}
| lgpl-3.0 |
eark-project/db-preservation-toolkit | dbptk-model/src/main/java/com/databasepreservation/model/data/Row.java | 1472 | /**
*
*/
package com.databasepreservation.model.data;
import java.util.ArrayList;
import java.util.List;
/**
* A table data row container.
*
* @author Luis Faria
*/
public class Row {
private long index;
private List<Cell> cells;
/**
* Empty TableStructure data row constructor
*/
public Row() {
this.cells = new ArrayList<Cell>();
}
/**
* TableStructure data row constructor
*
* @param index
* the sequence number of the row in the table
* @param cells
* the list of cell within this row
*/
public Row(long index, List<Cell> cells) {
this.index = index;
this.cells = cells;
}
/**
* @return the sequence number of the row in the table
*/
public long getIndex() {
return index;
}
/**
* @param index
* the sequence number of the row in the table
*/
public void setIndex(long index) {
this.index = index;
}
/**
* @return the list of cell within this row
*/
public List<Cell> getCells() {
return cells;
}
/**
* @param cells
* the list of cell within this row
*/
public void setCells(List<Cell> cells) {
this.cells = cells;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Row [index=");
builder.append(index);
builder.append(", cells=");
builder.append(cells);
builder.append("]");
return builder.toString();
}
}
| lgpl-3.0 |
runescapejon/AdventureBackpack2 | src/main/java/com/darkona/adventurebackpack/fluids/effects/MelonJuiceEffect.java | 998 | package com.darkona.adventurebackpack.fluids.effects;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.world.World;
import com.darkona.adventurebackpack.init.ModFluids;
import com.darkona.adventurebackpack.util.Utils;
import adventurebackpack.api.FluidEffect;
/**
* Created by Darkona on 12/10/2014.
*/
public class MelonJuiceEffect extends FluidEffect
{
public MelonJuiceEffect()
{
super(ModFluids.melonJuice, 30);
}
@Override
public void affectDrinker(World world, Entity entity)
{
if (entity instanceof EntityPlayer)
{
EntityPlayer player = (EntityPlayer) entity;
player.addPotionEffect(new PotionEffect(Potion.digSpeed.getId(), timeInTicks, 0));
player.addPotionEffect(new PotionEffect(Potion.regeneration.id, Utils.secondsToTicks(timeInSeconds), 0));
}
}
} | lgpl-3.0 |
marissaDubbelaar/GOAD3.1.1 | molgenis-platform-integration-tests/src/test/java/org/molgenis/integrationtest/platform/datatypeediting/FileTypeEditing.java | 2509 | package org.molgenis.integrationtest.platform.datatypeediting;
import org.molgenis.data.DataService;
import org.molgenis.data.EntityManager;
import org.molgenis.data.MolgenisDataException;
import org.molgenis.data.elasticsearch.index.job.IndexService;
import org.molgenis.data.meta.MetaDataService;
import org.molgenis.data.meta.model.AttributeFactory;
import org.molgenis.data.meta.model.EntityType;
import org.molgenis.data.meta.model.EntityTypeFactory;
import org.molgenis.integrationtest.platform.PlatformITConfig;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.annotations.Test;
import static org.molgenis.data.meta.AttributeType.FILE;
import static org.molgenis.data.meta.AttributeType.STRING;
import static org.molgenis.data.meta.model.EntityType.AttributeRole.ROLE_ID;
import static org.molgenis.file.model.FileMetaMetaData.FILE_META;
import static org.molgenis.security.core.runas.RunAsSystemProxy.runAsSystem;
import static org.slf4j.LoggerFactory.getLogger;
@ContextConfiguration(classes = { PlatformITConfig.class })
public class FileTypeEditing extends AbstractTestNGSpringContextTests
{
private final Logger LOG = getLogger(FileTypeEditing.class);
@Autowired
IndexService indexService;
@Autowired
AttributeFactory attributeFactory;
@Autowired
EntityTypeFactory entityTypeFactory;
@Autowired
DataService dataService;
@Autowired
EntityManager entityManager;
@Autowired
MetaDataService metaDataService;
@Test(expectedExceptions = MolgenisDataException.class, expectedExceptionsMessageRegExp = "Attribute data type update from \\[FILE\\] to \\[STRING\\] not allowed, allowed types are \\[\\]")
public void testNoConversionsAllowed()
{
EntityType entityType = entityTypeFactory.create("FileEntity");
entityType.setName("FileEntity");
entityType.setBackend("PostgreSQL");
entityType.addAttribute(attributeFactory.create().setName("id").setIdAttribute(true), ROLE_ID);
entityType.addAttribute(attributeFactory.create().setName("fileRef").setDataType(FILE)
.setRefEntity(dataService.getEntityType(FILE_META)));
runAsSystem(() ->
{
metaDataService.addEntityType(entityType);
entityType.getAttribute("fileRef").setDataType(STRING);
entityType.getAttribute("fileRef").setRefEntity(null);
metaDataService.updateEntityType(entityType);
});
}
}
| lgpl-3.0 |
Godin/sonar | server/sonar-server/src/main/java/org/sonar/server/branch/pr/ws/PullRequestsWs.java | 2175 | /*
* 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.server.branch.pr.ws;
import org.sonar.api.server.ws.WebService;
import static java.util.Arrays.stream;
import static org.sonar.server.branch.pr.ws.PullRequestsWsParameters.PARAM_PROJECT;
import static org.sonar.server.branch.pr.ws.PullRequestsWsParameters.PARAM_PULL_REQUEST;
import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
public class PullRequestsWs implements WebService {
private final PullRequestWsAction[] actions;
public PullRequestsWs(PullRequestWsAction... actions) {
this.actions = actions;
}
@Override
public void define(Context context) {
NewController controller = context.createController("api/project_pull_requests")
.setSince("7.1")
.setDescription("Manage pull request (only available when the Branch plugin is installed)");
stream(actions).forEach(action -> action.define(controller));
controller.done();
}
static void addProjectParam(NewAction action) {
action
.createParam(PARAM_PROJECT)
.setDescription("Project key")
.setExampleValue(KEY_PROJECT_EXAMPLE_001)
.setRequired(true);
}
static void addPullRequestParam(NewAction action) {
action
.createParam(PARAM_PULL_REQUEST)
.setDescription("Pull request id")
.setExampleValue("1543")
.setRequired(true);
}
}
| lgpl-3.0 |
jbpt/codebase | jbpt-bpm/src/main/java/org/jbpt/pm/AlternativGateway.java | 555 | /**
*
*/
package org.jbpt.pm;
/**
* Class for all {@link IGateway}s that do not match any of the other behaviors.
*
* @author Tobias Hoppe
*
*/
public class AlternativGateway extends Gateway implements IGateway {
/**
* Create a new gateway with self defined behavior.
*/
public AlternativGateway() {
super();
}
/**
* Create a new gateway with self defined behavior and the given name.
* @param name of this {@link AlternativGateway}
*/
public AlternativGateway(String name) {
super(name);
}
}
| lgpl-3.0 |
lukelast/jelenium | src/main/java/net/ghue/jelenium/impl/suite/WebDriverSessionBase.java | 852 | package net.ghue.jelenium.impl.suite;
import java.util.Objects;
import org.openqa.selenium.remote.RemoteWebDriver;
import net.ghue.jelenium.api.suite.WebDriverSession;
public class WebDriverSessionBase implements WebDriverSession {
protected final RemoteWebDriver driver;
public WebDriverSessionBase( RemoteWebDriver driver ) {
this.driver = Objects.requireNonNull( driver );
}
@Override
public void close() {
// https://stackoverflow.com/questions/15067107/difference-between-webdriver-dispose-close-and-quit
this.driver.quit();
}
@Override
public String getName() {
if ( driver.getClass() == RemoteWebDriver.class ) {
return "remote";
}
return driver.getClass().getSimpleName();
}
@Override
public RemoteWebDriver getWebDriver() {
return this.driver;
}
}
| lgpl-3.0 |
orgicus/ftd2xxj | eclipseFTD2XXJ/ftd2xxj/src/application/com/ftdichip/ftd2xx/ui/eeprom/EEPROMViewer.java | 3473 | package com.ftdichip.ftd2xx.ui.eeprom;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableColumn;
import com.ftdichip.ftd2xx.Device;
import com.ftdichip.ftd2xx.FTD2xxException;
import com.ftdichip.ftd2xx.ui.DeviceInformationViewer;
/**
* @author Mike Werner
*/
public class EEPROMViewer extends JPanel implements DeviceInformationViewer {
/**
* The <code>serialVersionUID</code>.
*/
private static final long serialVersionUID = 1L;
private JScrollPane jScrollPane = null;
private JTable dataTable = null;
private EEPROMTableModel dataTableModel = new EEPROMTableModel();
/**
* Creates a new <code>EEPROMViewer</code>.
*/
public EEPROMViewer() {
initialize();
}
/**
* This method initializes this
*/
private void initialize() {
this.setLayout(new BorderLayout());
this.add(getJScrollPane(), java.awt.BorderLayout.CENTER);
}
/**
* Updates the data table model with the EEPROM data from a particular
* device.
*
* @param device
* the device.
* @throws FTD2xxException
* if the data can no be read from the device.
*/
public void update(Device device) throws FTD2xxException {
dataTableModel.update(device.getEEPROM());
}
/**
* Clears the data table.
*/
public void clear() {
dataTableModel.clear();
}
/**
* This method initializes jScrollPane
*
* @return javax.swing.JScrollPane
*/
private JScrollPane getJScrollPane() {
if (jScrollPane == null) {
jScrollPane = new JScrollPane();
jScrollPane.setViewportView(getDataTable());
}
return jScrollPane;
}
/**
* Retrieves the table component showing the EEPROM data. If the table does
* not exist it will be created first.
*
* @return javax.swing.JTable
*/
JTable getDataTable() {
if (dataTable == null) {
dataTable = new JTable();
dataTable
.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_LAST_COLUMN);
dataTable.setRowHeight(20);
dataTable.setRowSelectionAllowed(true);
dataTable.setCellSelectionEnabled(true);
dataTable
.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
dataTable.setModel(dataTableModel);
dataTable.setDefaultRenderer(Long.class,
new EEPROMTableCellRenderer());
dataTable.getTableHeader().setReorderingAllowed(false);
// update the ASCII columns minimum width to be the preferred one
dataTableModel.addTableModelListener(new TableModelListener() {
public void tableChanged(TableModelEvent e) {
if (e.getType() == TableModelEvent.UPDATE) {
TableColumn column = getDataTable().getColumnModel()
.getColumn(EEPROMTableModel.ASCII_COLUMN_INDEX);
column.setMinWidth(column.getPreferredWidth());
}
}
});
}
return dataTable;
}
} // @jve:decl-index=0:visual-constraint="10,10"
| lgpl-3.0 |
raffaeleconforti/ResearchCode | bpmn-util/src/main/java/com/raffaeleconforti/bpmn/util/BPMNModifier.java | 7522 | /*
* Copyright (C) 2018 Raffaele Conforti (www.raffaeleconforti.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, see <http://www.gnu.org/licenses/>.
*/
package com.raffaeleconforti.bpmn.util;
import org.eclipse.collections.impl.map.mutable.UnifiedMap;
import org.eclipse.collections.impl.set.mutable.UnifiedSet;
import org.processmining.models.graphbased.AttributeMap;
import org.processmining.models.graphbased.directed.bpmn.BPMNDiagram;
import org.processmining.models.graphbased.directed.bpmn.BPMNNode;
import org.processmining.models.graphbased.directed.bpmn.elements.*;
import java.util.Map;
import java.util.Set;
/**
* Created by Raffaele Conforti (conforti.raffaele@gmail.com) on 16/02/15.
*/
public class BPMNModifier {
public static BPMNDiagram removeUnecessaryLabels(BPMNDiagram diagram) {
for(Event event : diagram.getEvents()) {
if(event.getEventType().equals(Event.EventType.START) || event.getEventType().equals(Event.EventType.END)) {
event.getAttributeMap().put(AttributeMap.LABEL, "");
}
}
for(Gateway gateway : diagram.getGateways()) {
gateway.getAttributeMap().put(AttributeMap.LABEL, "");
}
return diagram;
}
public static BPMNDiagram insertSubProcess(BPMNDiagram mainProcess, BPMNDiagram subProcessDiagram, SubProcess subProcess) {
Set<SubProcess> eventSub = new UnifiedSet<>();
Map<SubProcess, SubProcess> mappingSubProcesses = new UnifiedMap<>(subProcessDiagram.getSubProcesses().size());
for (SubProcess subSub : subProcessDiagram.getSubProcesses()) {
SubProcess sub;
if (subSub.getTriggeredByEvent()) {
sub = mainProcess.addSubProcess(subSub.getLabel(), false, false, false, false, subSub.isBCollapsed(), subSub.getTriggeredByEvent());
eventSub.add(sub);
} else {
sub = mainProcess.addSubProcess(subSub.getLabel(), subSub.isBLooped(), subSub.isBAdhoc(), subSub.isBCompensation(), subSub.isBMultiinstance(), subSub.isBCollapsed(), subSub.getTriggeredByEvent());
}
if (subSub.getParentSubProcess() == null) {
sub.setParentSubprocess(subProcess);
} else {
sub.setParentSubprocess(mappingSubProcesses.get(subSub.getParentSubProcess()));
}
mappingSubProcesses.put(subSub, sub);
}
for (Activity actSub : subProcessDiagram.getActivities()) {
Activity act = mainProcess.addActivity(actSub.getLabel(), actSub.isBLooped(), actSub.isBAdhoc(), actSub.isBCompensation(), actSub.isBMultiinstance(), actSub.isBCollapsed());
if (actSub.getParentSubProcess() == null) {
act.setParentSubprocess(subProcess);
} else {
act.setParentSubprocess(mappingSubProcesses.get(actSub.getParentSubProcess()));
}
}
for (Event evtSub : subProcessDiagram.getEvents()) {
Activity activity = null;
Activity boundary = evtSub.getBoundingNode();
if (boundary != null) {
for (SubProcess subProcess1 : subProcessDiagram.getSubProcesses()) {
if (boundary.getLabel().equals(subProcess1.getLabel())) {
activity = subProcess1;
break;
}
}
}
Event evt;
if (evtSub.getEventType().equals(Event.EventType.START) && evtSub.getParentSubProcess() != null && eventSub.contains(mappingSubProcesses.get(evtSub.getParentSubProcess()))) {
evt = mainProcess.addEvent(evtSub.getLabel(), evtSub.getEventType(), evtSub.getEventTrigger(), evtSub.getEventUse(), false, activity);
} else if (evtSub.getEventType().equals(Event.EventType.START) && evtSub.getParentSubProcess() == null && subProcess.getTriggeredByEvent()) {
evt = mainProcess.addEvent(evtSub.getLabel(), evtSub.getEventType(), evtSub.getEventTrigger(), evtSub.getEventUse(), false, activity);
} else {
evt = mainProcess.addEvent(evtSub.getLabel(), evtSub.getEventType(), evtSub.getEventTrigger(), evtSub.getEventUse(), true, activity);
}
if (evtSub.getParentSubProcess() == null) {
evt.setParentSubprocess(subProcess);
} else {
evt.setParentSubprocess(mappingSubProcesses.get(evtSub.getParentSubProcess()));
}
}
for (Gateway gatSub : subProcessDiagram.getGateways()) {
Gateway gat;
BPMNNode node = getNodeWithEqualLabel(mainProcess, gatSub);
if (node == null) {
gat = mainProcess.addGateway(gatSub.getLabel(), gatSub.getGatewayType());
} else {
gat = (Gateway) node;
}
if (gatSub.getParentSubProcess() == null) {
gat.setParentSubprocess(subProcess);
} else {
gat.setParentSubprocess(mappingSubProcesses.get(gatSub.getParentSubProcess()));
}
}
for (Flow flow : subProcessDiagram.getFlows()) {
mainProcess.addFlow(getNodeWithEqualLabel(mainProcess, flow.getSource()), getNodeWithEqualLabel(mainProcess, flow.getTarget()), "");
}
return mainProcess;
}
public static BPMNNode getNodeWithEqualLabel(BPMNDiagram mainProcess, BPMNNode node) {
for (BPMNNode actSub : mainProcess.getNodes()) {
if (actSub.getLabel().equals(node.getLabel())) return actSub;
}
return null;
}
public static Gateway addGateway(BPMNDiagram diagram, String name, Gateway.GatewayType type) {
return diagram.addGateway(name, type);
}
public static Flow addFlow(BPMNDiagram model, BPMNNode source, BPMNNode target) {
Flow flow = null;
for (Flow f : model.getFlows()) {
if (f.getSource().equals(source) && f.getTarget().equals(target)) {
flow = f;
break;
}
}
if (flow == null) {
flow = model.addFlow(source, target, "");
}
return flow;
}
public static Activity addActivity(BPMNDiagram model, String name) {
return model.addActivity(name, false, false, false, false, false);
}
public static Event addEvent(BPMNDiagram model, String name) {
return model.addEvent(name, Event.EventType.INTERMEDIATE, Event.EventTrigger.NONE, null, true, null);
}
public static Event addStartEvent(BPMNDiagram model, String name) {
return model.addEvent(name, Event.EventType.START, Event.EventTrigger.NONE, null, true, null);
}
public static Event addEndEvent(BPMNDiagram model, String name) {
return model.addEvent(name, Event.EventType.END, Event.EventTrigger.NONE, null, true, null);
}
}
| lgpl-3.0 |
nbzwt/lanterna | src/main/java/com/googlecode/lanterna/terminal/IOSafeTerminalAdapter.java | 12681 | /*
* This file is part of lanterna (http://code.google.com/p/lanterna/).
*
* lanterna 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/>.
*
* Copyright (C) 2010-2016 Martin
*/
package com.googlecode.lanterna.terminal;
import com.googlecode.lanterna.SGR;
import com.googlecode.lanterna.TerminalPosition;
import com.googlecode.lanterna.TerminalSize;
import com.googlecode.lanterna.TextColor;
import com.googlecode.lanterna.graphics.TextGraphics;
import com.googlecode.lanterna.input.KeyStroke;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
/**
* This class exposes methods for converting a terminal into an IOSafeTerminal. There are two options available, either
* one that will convert any IOException to a RuntimeException (and re-throw it) or one that will silently swallow any
* IOException (and return null in those cases the method has a non-void return type).
* @author Martin
*/
public class IOSafeTerminalAdapter implements IOSafeTerminal {
private interface ExceptionHandler {
void onException(IOException e);
}
private static class ConvertToRuntimeException implements ExceptionHandler {
@Override
public void onException(IOException e) {
throw new RuntimeException(e);
}
}
private static class DoNothingAndOrReturnNull implements ExceptionHandler {
@Override
public void onException(IOException e) { }
}
/**
* Creates a wrapper around a Terminal that exposes it as a IOSafeTerminal. If any IOExceptions occur, they will be
* wrapped by a RuntimeException and re-thrown.
* @param terminal Terminal to wrap
* @return IOSafeTerminal wrapping the supplied terminal
*/
public static IOSafeTerminal createRuntimeExceptionConvertingAdapter(Terminal terminal) {
if (terminal instanceof ExtendedTerminal) { // also handle Runtime-type:
return createRuntimeExceptionConvertingAdapter((ExtendedTerminal)terminal);
} else {
return new IOSafeTerminalAdapter(terminal, new ConvertToRuntimeException());
}
}
/**
* Creates a wrapper around an ExtendedTerminal that exposes it as a IOSafeExtendedTerminal.
* If any IOExceptions occur, they will be wrapped by a RuntimeException and re-thrown.
* @param terminal Terminal to wrap
* @return IOSafeTerminal wrapping the supplied terminal
*/
public static IOSafeExtendedTerminal createRuntimeExceptionConvertingAdapter(ExtendedTerminal terminal) {
return new IOSafeTerminalAdapter.Extended(terminal, new ConvertToRuntimeException());
}
/**
* Creates a wrapper around a Terminal that exposes it as a IOSafeTerminal. If any IOExceptions occur, they will be
* silently ignored and for those method with a non-void return type, null will be returned.
* @param terminal Terminal to wrap
* @return IOSafeTerminal wrapping the supplied terminal
*/
public static IOSafeTerminal createDoNothingOnExceptionAdapter(Terminal terminal) {
if (terminal instanceof ExtendedTerminal) { // also handle Runtime-type:
return createDoNothingOnExceptionAdapter((ExtendedTerminal)terminal);
} else {
return new IOSafeTerminalAdapter(terminal, new DoNothingAndOrReturnNull());
}
}
/**
* Creates a wrapper around an ExtendedTerminal that exposes it as a IOSafeExtendedTerminal.
* If any IOExceptions occur, they will be silently ignored and for those method with a
* non-void return type, null will be returned.
* @param terminal Terminal to wrap
* @return IOSafeTerminal wrapping the supplied terminal
*/
public static IOSafeExtendedTerminal createDoNothingOnExceptionAdapter(ExtendedTerminal terminal) {
return new IOSafeTerminalAdapter.Extended(terminal, new DoNothingAndOrReturnNull());
}
private final Terminal backend;
final ExceptionHandler exceptionHandler;
@SuppressWarnings("WeakerAccess")
public IOSafeTerminalAdapter(Terminal backend, ExceptionHandler exceptionHandler) {
this.backend = backend;
this.exceptionHandler = exceptionHandler;
}
@Override
public void enterPrivateMode() {
try {
backend.enterPrivateMode();
}
catch(IOException e) {
exceptionHandler.onException(e);
}
}
@Override
public void exitPrivateMode() {
try {
backend.exitPrivateMode();
}
catch(IOException e) {
exceptionHandler.onException(e);
}
}
@Override
public void clearScreen() {
try {
backend.clearScreen();
}
catch(IOException e) {
exceptionHandler.onException(e);
}
}
@Override
public void setCursorPosition(int x, int y) {
try {
backend.setCursorPosition(x, y);
}
catch(IOException e) {
exceptionHandler.onException(e);
}
}
@Override
public void setCursorPosition(TerminalPosition position) {
try {
backend.setCursorPosition(position);
}
catch(IOException e) {
exceptionHandler.onException(e);
}
}
@Override
public TerminalPosition getCursorPosition() {
try {
return backend.getCursorPosition();
}
catch(IOException e) {
exceptionHandler.onException(e);
}
return null;
}
@Override
public void setCursorVisible(boolean visible) {
try {
backend.setCursorVisible(visible);
}
catch(IOException e) {
exceptionHandler.onException(e);
}
}
@Override
public void putCharacter(char c) {
try {
backend.putCharacter(c);
}
catch(IOException e) {
exceptionHandler.onException(e);
}
}
@Override
public TextGraphics newTextGraphics() {
try {
return backend.newTextGraphics();
}
catch(IOException e) {
exceptionHandler.onException(e);
}
return null;
}
@Override
public void enableSGR(SGR sgr) {
try {
backend.enableSGR(sgr);
}
catch(IOException e) {
exceptionHandler.onException(e);
}
}
@Override
public void disableSGR(SGR sgr) {
try {
backend.disableSGR(sgr);
}
catch(IOException e) {
exceptionHandler.onException(e);
}
}
@Override
public void resetColorAndSGR() {
try {
backend.resetColorAndSGR();
}
catch(IOException e) {
exceptionHandler.onException(e);
}
}
@Override
public void setForegroundColor(TextColor color) {
try {
backend.setForegroundColor(color);
}
catch(IOException e) {
exceptionHandler.onException(e);
}
}
@Override
public void setBackgroundColor(TextColor color) {
try {
backend.setBackgroundColor(color);
}
catch(IOException e) {
exceptionHandler.onException(e);
}
}
@Override
public void addResizeListener(TerminalResizeListener listener) {
backend.addResizeListener(listener);
}
@Override
public void removeResizeListener(TerminalResizeListener listener) {
backend.removeResizeListener(listener);
}
@Override
public TerminalSize getTerminalSize() {
try {
return backend.getTerminalSize();
}
catch(IOException e) {
exceptionHandler.onException(e);
}
return null;
}
@Override
public byte[] enquireTerminal(int timeout, TimeUnit timeoutUnit) {
try {
return backend.enquireTerminal(timeout, timeoutUnit);
}
catch(IOException e) {
exceptionHandler.onException(e);
}
return null;
}
@Override
public void bell() {
try {
backend.bell();
}
catch(IOException e) {
exceptionHandler.onException(e);
}
}
@Override
public void flush() {
try {
backend.flush();
}
catch(IOException e) {
exceptionHandler.onException(e);
}
}
@Override
public void close() {
try {
backend.close();
}
catch(IOException e) {
exceptionHandler.onException(e);
}
}
@Override
public KeyStroke pollInput() {
try {
return backend.pollInput();
}
catch(IOException e) {
exceptionHandler.onException(e);
}
return null;
}
@Override
public KeyStroke readInput() {
try {
return backend.readInput();
}
catch(IOException e) {
exceptionHandler.onException(e);
}
return null;
}
/**
* This class exposes methods for converting an extended terminal into an IOSafeExtendedTerminal.
*/
public static class Extended extends IOSafeTerminalAdapter implements IOSafeExtendedTerminal {
private final ExtendedTerminal backend;
public Extended(ExtendedTerminal backend, ExceptionHandler exceptionHandler) {
super(backend, exceptionHandler);
this.backend = backend;
}
@Override
public void setTerminalSize(int columns, int rows) {
try {
backend.setTerminalSize(columns, rows);
}
catch(IOException e) {
exceptionHandler.onException(e);
}
}
@Override
public void setTitle(String title) {
try {
backend.setTitle(title);
}
catch(IOException e) {
exceptionHandler.onException(e);
}
}
@Override
public void pushTitle() {
try {
backend.pushTitle();
}
catch(IOException e) {
exceptionHandler.onException(e);
}
}
@Override
public void popTitle() {
try {
backend.popTitle();
}
catch(IOException e) {
exceptionHandler.onException(e);
}
}
@Override
public void iconify() {
try {
backend.iconify();
}
catch(IOException e) {
exceptionHandler.onException(e);
}
}
@Override
public void deiconify() {
try {
backend.deiconify();
}
catch(IOException e) {
exceptionHandler.onException(e);
}
}
@Override
public void maximize() {
try {
backend.maximize();
}
catch(IOException e) {
exceptionHandler.onException(e);
}
}
@Override
public void unmaximize() {
try {
backend.unmaximize();
}
catch(IOException e) {
exceptionHandler.onException(e);
}
}
@Override
public void setMouseCaptureMode(MouseCaptureMode mouseCaptureMode) {
try {
backend.setMouseCaptureMode(mouseCaptureMode);
}
catch(IOException e) {
exceptionHandler.onException(e);
}
}
@Override
public void scrollLines(int firstLine, int lastLine, int distance) {
try {
backend.scrollLines(firstLine, lastLine, distance);
}
catch(IOException e) {
exceptionHandler.onException(e);
}
}
}
}
| lgpl-3.0 |
jhclark/bigfatlm | src/bigfat/step5/InterpolateOrdersInfo.java | 877 | package bigfat.step5;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.apache.hadoop.io.Writable;
import bigfat.util.SerializationPrecision;
/**
* @author jhclark
*/
public class InterpolateOrdersInfo implements Writable {
private double p;
private double bo;
public double getInterpolatedProb() {
return p;
}
public double getBackoffWeight() {
return bo;
}
public void setInfo(double p, double bo) {
this.bo = bo;
this.p = p;
}
@Override
public void write(DataOutput out) throws IOException {
SerializationPrecision.writeReal(out, p);
SerializationPrecision.writeReal(out, bo);
}
@Override
public void readFields(DataInput in) throws IOException {
p = SerializationPrecision.readReal(in);
bo = SerializationPrecision.readReal(in);
}
public String toString() {
return p +" " + bo;
}
}
| lgpl-3.0 |
OpenSoftwareSolutions/PDFReporter-Studio | com.jaspersoft.studio.data.mongodb/src/com/jaspersoft/studio/data/mongodb/MongoDBCreator.java | 2297 | /*******************************************************************************
* Copyright (C) 2005 - 2014 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com.
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
******************************************************************************/
package com.jaspersoft.studio.data.mongodb;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.jaspersoft.mongodb.adapter.MongoDbDataAdapterImpl;
import com.jaspersoft.studio.data.DataAdapterDescriptor;
import com.jaspersoft.studio.data.adapter.IDataAdapterCreator;
/**
* Creator to build a JSS MongoDB data adapter from the xml definition of an iReport MongoDB
* data adapter
*
* @author Orlandin Marco
*/
public class MongoDBCreator implements IDataAdapterCreator {
@Override
public DataAdapterDescriptor buildFromXML(Document docXML) {
MongoDbDataAdapterImpl result = new MongoDbDataAdapterImpl();
NamedNodeMap rootAttributes = docXML.getChildNodes().item(0).getAttributes();
String connectionName = rootAttributes.getNamedItem("name").getTextContent();
result.setName(connectionName);
NodeList children = docXML.getChildNodes().item(0).getChildNodes();
for(int i=0; i<children.getLength(); i++){
Node node = children.item(i);
if (node.getNodeName().equals("connectionParameter")){
String paramName = node.getAttributes().getNamedItem("name").getTextContent();
if (paramName.equals("username")) result.setUsername(node.getTextContent()) ;
if (paramName.equals("MongoDB URI")) result.setMongoURI(node.getTextContent());
if (paramName.equals("password")) result.setPassword(node.getTextContent());
}
}
MongoDbDataAdapterDescriptor desc = new MongoDbDataAdapterDescriptor();
desc.setDataAdapter(result);
return desc;
}
@Override
public String getID() {
return "com.jaspersoft.ireport.mongodb.connection.MongoDbConnection";
}
}
| lgpl-3.0 |
jsebtes/java-rf24 | src/main/java/fr/jstessier/rf24/exceptions/RF24Exception.java | 3751 | package fr.jstessier.rf24.exceptions;
/*
* Copyright (C) 2015 J.S. TESSIER
*
* This file is part of java-rf24.
*
* java-rf24 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.
*
* java-rf24 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 java-rf24. If not, see <http://www.gnu.org/licenses/lgpl-3.0.html>.
*/
/**
* Generic exception for RF24.
*
* @author J.S. TESSIER
*/
public class RF24Exception extends Exception {
private static final long serialVersionUID = 4577413219808441594L;
/**
* Constructs a new exception with {@code null} as its detail message.
* The cause is not initialized, and may subsequently be initialized by a
* call to {@link #initCause}.
*/
public RF24Exception() {
super();
}
/**
* Constructs a new exception with the specified detail message.
* The cause is not initialized.
*
* @param message the detail message. The detail message is saved for
* later retrieval by the {@link #getMessage()} method.
*/
public RF24Exception(String message) {
super(message);
}
/**
* Constructs a new exception with the specified cause and a detail
* message of <tt>(cause==null ? null : cause.toString())</tt> (which
* typically contains the class and detail message of <tt>cause</tt>).
* This constructor is useful for exceptions that are little more than
* wrappers for other throwables (for example, {@link
* java.security.PrivilegedActionException}).
*
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A <tt>null</tt> value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
*/
public RF24Exception(Throwable cause) {
super(cause);
}
/**
* Constructs a new exception with the specified detail message and
* cause. <p>Note that the detail message associated with
* {@code cause} is <i>not</i> automatically incorporated in
* this exception's detail message.
*
* @param message the detail message (which is saved for later retrieval
* by the {@link #getMessage()} method).
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A <tt>null</tt> value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
*/
public RF24Exception(String message, Throwable cause) {
super(message, cause);
}
/**
* Constructs a new exception with the specified detail message,
* cause, suppression enabled or disabled, and writable stack
* trace enabled or disabled.
*
* @param message the detail message.
* @param cause the cause. (A {@code null} value is permitted,
* and indicates that the cause is nonexistent or unknown.)
* @param enableSuppression whether or not suppression is enabled
* or disabled
* @param writableStackTrace whether or not the stack trace should
* be writable
*/
protected RF24Exception(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
| lgpl-3.0 |
hy2708/hy2708-repository | java/commons/commons-algorithm/src/main/java/com/hy/commons/algorithm/leetcode/e/PalindromePartitioningII020_Hard.java | 1303 | package leetcode151withexplain;
/**
* http://blog.csdn.net/doc_sgl/article/details/13418125
* ±¾ÌâÌâÒ⣺½²Ò»¸ö¸ø¶¨µÄ×Ö·û´®±ä³Éÿ¸ö×Ó´®¶¼ÊÇ»ØÎÄ£¬×îÉÙÒªÇзֶàÉÙ´Î
*
*/
public class PalindromePartitioningII020_Hard {
public int minCut(String s) {
int n=s.length();
//²ÉÓö¯Ì¬¹æ»®µÄ˼Ï룺dp[i]±íʾ´Óiµ½nµÄ×îСÇзִÎÊý
int[] dp=new int[n+1];
//ÊÇ·ñÊÇ»ØÎĵĶ¯Ì¬¹æ»®ÎÊÌâ pos[i][j]´ú±í×Ö·û´®´Óiµ½jÊÇ·ñÊÇһλ»ØÎÄ
boolean[][] pos=new boolean[n][n];
//ÊÇ·ñΪ»ØÎĵijõʼ»¯¹ý³Ì
int i,j;
for(i=0; i<n; i++)
for(j=0 ; j<n;j++)
pos[i][j]=false;
for(i = 0; i < n; i++){
pos[i][i] = true;
}
//dp³õʼ»¯ ³õʼ»¯ÎªºóÃæµÄ×Ö·û´®×î¶à¿ÉÒÔÇзֶàÉÙ´Î
//D[i] = Çø¼ä[i,n]Ö®¼ä×îСµÄcutÊý£¬nΪ×Ö·û´®³¤¶È£¬ Ôò,
//D[i] = min(1+D[j+1] ) i<=j <n
for(i = 0; i<=n; i++){
dp[i]=n-i;
}
for (i=n-1;i>-1;i--)
for(j=i;j < n;j++)
if(s.substring(i,i+1).equals(s.substring(j,j+1)) && (j-i<2 || pos[i+1][j-1]))
{
pos[i][j]=true;
dp[i] = dp[j+1]+1 > dp[i] ? dp[i]:(dp[j+1]+1);
}
int min=dp[0];
return min-1;
}
}
| lgpl-3.0 |
jjm223/MyPet | modules/API/src/main/java/de/Keyle/MyPet/api/util/animation/Animation.java | 4400 | /*
* This file is part of mypet-api_main
*
* Copyright (C) 2011-2016 Keyle
* mypet-api_main is licensed under the GNU Lesser General Public License.
*
* mypet-api_main 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.
*
* mypet-api_main is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.Keyle.MyPet.api.util.animation;
import de.Keyle.MyPet.MyPetApi;
import de.Keyle.MyPet.api.util.location.LocationHolder;
import org.bukkit.Bukkit;
import org.bukkit.Location;
public abstract class Animation {
int taskID = -1;
protected int framesPerTick = 1;
protected int frame = 0;
protected int length = 0;
protected int loops = 0;
protected LocationHolder locationHolder;
public Animation(int length, LocationHolder locationHolder) {
this.length = length;
this.locationHolder = locationHolder;
}
public abstract void tick(int frame, Location location);
public void reset() {
frame = 0;
}
public int getFramesPerTick() {
return framesPerTick;
}
public void setFramesPerTick(int framesPerTick) {
this.framesPerTick = Math.max(1, framesPerTick);
}
public void once() {
if (!running()) {
taskID = Bukkit.getScheduler().scheduleSyncRepeatingTask(MyPetApi.getPlugin(), new Runnable() {
@Override
public void run() {
if (locationHolder.isValid()) {
for (int i = 0; i < framesPerTick; i++) {
tick(frame, locationHolder.getLocation());
if (++frame >= length) {
stop();
break;
}
}
} else {
stop();
}
}
}, 0, 1);
}
}
public void stop() {
if (taskID != -1) {
Bukkit.getScheduler().cancelTask(taskID);
taskID = -1;
onStop();
}
}
public boolean running() {
return taskID != -1;
}
public void loop() {
if (!running()) {
taskID = Bukkit.getScheduler().scheduleSyncRepeatingTask(MyPetApi.getPlugin(), new Runnable() {
@Override
public void run() {
if (locationHolder.isValid()) {
for (int i = 0; i < framesPerTick; i++) {
tick(frame, locationHolder.getLocation());
if (++frame >= length) {
reset();
break;
}
}
} else {
stop();
}
}
}, 0, 1);
}
}
public void loop(int quantity) {
if (!running()) {
this.loops = quantity;
taskID = Bukkit.getScheduler().scheduleSyncRepeatingTask(MyPetApi.getPlugin(), new Runnable() {
@Override
public void run() {
if (locationHolder.isValid()) {
for (int i = 0; i < framesPerTick; i++) {
tick(frame, locationHolder.getLocation());
if (++frame >= length) {
if (--Animation.this.loops > 0) {
reset();
} else {
stop();
}
break;
}
}
} else {
stop();
}
}
}, 0, 1);
}
}
public void onStop() {
}
} | lgpl-3.0 |
clstoulouse/motu | motu-web/src/main/java/fr/cls/atoll/motu/web/dal/request/netcdf/data/VarData.java | 6810 | /*
* Motu, a high efficient, robust and Standard compliant Web Server for Geographic
* Data Dissemination.
*
* http://cls-motu.sourceforge.net/
*
* (C) Copyright 2009-2010, by CLS (Collecte Localisation Satellites) -
* http://www.cls.fr - and Contributors
*
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
package fr.cls.atoll.motu.web.dal.request.netcdf.data;
import fr.cls.atoll.motu.web.dal.request.netcdf.metadata.ParameterMetaData;
/**
* Data parameter (variable) class.
*
* (C) Copyright 2009-2010, by CLS (Collecte Localisation Satellites)
*
* @version $Revision: 1.1 $ - $Date: 2009-03-18 12:18:22 $
* @author <a href="mailto:dearith@cls.fr">Didier Earith</a>
*/
public class VarData {
/**
* Default constructor.
*/
public VarData() {
}
/**
* Constructor.
*
* @param name name of the variable.
*/
public VarData(String name) {
setVarName(name);
setOutputName(name);
}
// CSOFF: StrictDuplicateCode : normal duplication code.
/**
* Name of the variable.
*
* @uml.property name="name"
*/
private String name = "";
/**
* Getter of the property <tt>name</tt>.
*
* @return Returns the name.
* @uml.property name="name"
*/
public String getVarName() {
return this.name;
}
/**
* Setter of the property <tt>name</tt>.
*
* @param value The name to set.
* @uml.property name="name"
*/
public void setVarName(String value) {
this.name = value.trim();
}
/**
* Name of the variable.
*
* @uml.property name="standardName"
*/
private String standardName = "";
/**
* Getter of the property <tt>standardName</tt>.
*
* @return Returns the name.
* @uml.property name="standardName"
*/
public String getStandardName() {
return this.standardName;
}
/**
* Setter of the property <tt>standardName</tt>.
*
* @param standardName The standardName to set.
* @uml.property name="standardName"
*/
public void setStandardName(String standardName) {
this.standardName = standardName.trim();
}
// CSON: StrictDuplicateCode
/**
* Output name of the variable.
*
* @uml.property name="outputName"
*/
private String outputName = "";
/**
* Getter of the property <tt>outputName</tt>.
*
* @return Returns the outputName.
* @uml.property name="outputName"
*/
public String getOutputName() {
return this.outputName;
}
/**
* Setter of the property <tt>outputName</tt>.
*
* @param outputName The outputName to set.
* @uml.property name="outputName"
*/
public void setOutputName(String outputName) {
this.outputName = outputName.trim();
}
/**
* Output dimension of the variable.
*
* @uml.property name="outputDimension"
*/
private String outputDimension = "";
/**
* Getter of the property <tt>outputDimension</tt>.
*
* @return Returns the outputDimension.
* @uml.property name="outputDimension"
*/
public String getOutputDimension() {
return this.outputDimension;
}
/**
* Setter of the property <tt>outputDimension</tt>.
*
* @param outputDimension The outputDimension to set.
* @uml.property name="outputDimension"
*/
public void setOutputDimension(String outputDimension) {
this.outputDimension = outputDimension;
}
/**
* It can be one of the following: - None: no statistical calculation (default). - Average - Variance -
* Sum - Min. - Max.
*
* @uml.property name="statisticalCalculation"
*/
private String statisticalCalculation = "";
/**
* Getter of the property <tt>computeMode</tt>.
*
* @return Returns the computeMode.
* @uml.property name="statisticalCalculation"
*/
public String getStatisticalCalculation() {
return this.statisticalCalculation;
}
/**
* Setter of the property <tt>computeMode</tt>.
*
* @param statisticalCalculation The statisticalCalculation to set.
* @uml.property name="statisticalCalculation"
*/
public void setStatisticalCalculation(String statisticalCalculation) {
this.statisticalCalculation = statisticalCalculation;
}
/**
* Expression of the variable. It can the variable itself or a formula to compute the variable (with
* functions, arithmetical operators, other variables of the product). The result of the formula
* (mathematical expression) is always of type 'double'.
*
* @uml.property name="mathExpression"
*/
private String mathExpression;
/**
* Getter of the property <tt>Expression</tt>.
*
* @return Returns the expression.
* @uml.property name="mathExpression"
*/
public String getMathExpression() {
return this.mathExpression;
}
/**
* Setter of the property <tt>Expression</tt>.
*
* @param mathExpression The expression to set.
* @uml.property name="mathExpression"
*/
public void setMathExpression(String mathExpression) {
this.mathExpression = mathExpression;
}
/**
* Creates the from.
*
* @param parameterMetaData the parameter meta data
* @return the var data
*/
public static VarData createFrom(ParameterMetaData parameterMetaData) {
if (parameterMetaData == null) {
return null;
}
VarData varData = new VarData(parameterMetaData.getName());
varData.setStandardName(parameterMetaData.getStandardName().trim());
return varData;
}
@Override
public String toString() {
return "VarData [" + (name != null ? "name=" + name + ", " : "") + (outputName != null ? "outputName=" + outputName + ", " : "")
+ (standardName != null ? "standardName=" + standardName : "") + "]";
}
}
| lgpl-3.0 |
avbravo/hecas | hecas/src/main/java/com/cruta/hecas/Alertascomentarios.java | 4210 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.cruta.hecas;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author avbravo
*/
@Entity
@Table(name = "alertascomentarios")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Alertascomentarios.findAll", query = "SELECT a FROM Alertascomentarios a"),
@NamedQuery(name = "Alertascomentarios.findByIdalertascomentarios", query = "SELECT a FROM Alertascomentarios a WHERE a.idalertascomentarios = :idalertascomentarios"),
@NamedQuery(name = "Alertascomentarios.findByFecha", query = "SELECT a FROM Alertascomentarios a WHERE a.fecha = :fecha")})
public class Alertascomentarios implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@Column(name = "idalertascomentarios")
private Integer idalertascomentarios;
@Basic(optional = false)
@NotNull
@Lob
@Size(min = 1, max = 65535)
@Column(name = "comentario")
private String comentario;
@Basic(optional = false)
@NotNull
@Column(name = "fecha")
@Temporal(TemporalType.DATE)
private Date fecha;
@JoinColumn(name = "idalerta", referencedColumnName = "idalerta")
@ManyToOne(optional = false)
private Alertas idalerta;
@JoinColumn(name = "email", referencedColumnName = "email")
@ManyToOne(optional = false)
private Usuarios email;
public Alertascomentarios() {
}
public Alertascomentarios(Integer idalertascomentarios) {
this.idalertascomentarios = idalertascomentarios;
}
public Alertascomentarios(Integer idalertascomentarios, String comentario, Date fecha) {
this.idalertascomentarios = idalertascomentarios;
this.comentario = comentario;
this.fecha = fecha;
}
public Integer getIdalertascomentarios() {
return idalertascomentarios;
}
public void setIdalertascomentarios(Integer idalertascomentarios) {
this.idalertascomentarios = idalertascomentarios;
}
public String getComentario() {
return comentario;
}
public void setComentario(String comentario) {
this.comentario = comentario;
}
public Date getFecha() {
return fecha;
}
public void setFecha(Date fecha) {
this.fecha = fecha;
}
public Alertas getIdalerta() {
return idalerta;
}
public void setIdalerta(Alertas idalerta) {
this.idalerta = idalerta;
}
public Usuarios getEmail() {
return email;
}
public void setEmail(Usuarios email) {
this.email = email;
}
@Override
public int hashCode() {
int hash = 0;
hash += (idalertascomentarios != null ? idalertascomentarios.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Alertascomentarios)) {
return false;
}
Alertascomentarios other = (Alertascomentarios) object;
if ((this.idalertascomentarios == null && other.idalertascomentarios != null) || (this.idalertascomentarios != null && !this.idalertascomentarios.equals(other.idalertascomentarios))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.cruta.hecas.Alertascomentarios[ idalertascomentarios=" + idalertascomentarios + " ]";
}
}
| lgpl-3.0 |
andreoid/testing | brjs-core/src/test/java/org/bladerunnerjs/model/navigation/BRJSNavigationTest.java | 3408 | package org.bladerunnerjs.model.navigation;
import static org.junit.Assert.*;
import java.io.File;
import org.bladerunnerjs.logging.Logger;
import org.bladerunnerjs.model.App;
import org.bladerunnerjs.model.BRJS;
import org.bladerunnerjs.model.DirNode;
import org.bladerunnerjs.model.JsLib;
import org.bladerunnerjs.model.NamedDirNode;
import org.bladerunnerjs.model.NodeTesterFactory;
import org.bladerunnerjs.model.TestModelAccessor;
import org.bladerunnerjs.testing.utility.LogMessageStore;
import org.bladerunnerjs.testing.utility.TestLoggerFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class BRJSNavigationTest extends TestModelAccessor
{
private NodeTesterFactory<BRJS> nodeTesterFactory;
private final File testBase = new File("src/test/resources/BRJSTest");
private BRJS brjs;
@Before
public void setup() throws Exception
{
brjs = createModel(testBase, new TestLoggerFactory(new LogMessageStore()));
nodeTesterFactory = new NodeTesterFactory<>(brjs, BRJS.class);
}
@After
public void teardown()
{
brjs.close();
}
@Test
public void userApps()
{
nodeTesterFactory.createSetTester(App.class, "userApps", "userApp")
.addChild("a1", "apps/a1")
.addChild("a2", "apps/a2")
.addChild("a3", "apps/a3")
.assertModelIsOK();
}
@Test
public void systemApps()
{
nodeTesterFactory.createSetTester(App.class, "systemApps", "systemApp")
.addChild("sa1", "sdk/system-applications/sa1")
.addChild("sa2", "sdk/system-applications/sa2")
.assertModelIsOK();
}
@Test
public void sdkLibsDir()
{
nodeTesterFactory.createItemTester(DirNode.class, "sdkJsLibsDir", "sdk/libs/javascript")
.assertModelIsOK();
}
@Test
public void sdkLib()
{
nodeTesterFactory.createSetTester(JsLib.class, "sdkLibs", "sdkLib")
.addChild("br", "sdk/libs/javascript/br")
.addChild("brlib2", "sdk/libs/javascript/brlib2")
.addChild("thirdparty-l1", "sdk/libs/javascript/thirdparty-l1")
.addChild("thirdparty-l2", "sdk/libs/javascript/thirdparty-l2")
.assertModelIsOK();
}
@Test
public void jsPatches()
{
nodeTesterFactory.createItemTester(DirNode.class, "jsPatches", "js-patches")
.assertModelIsOK();
}
@Test
public void templates()
{
nodeTesterFactory.createSetTester(NamedDirNode.class, "templates", "template")
.addChild("t1", "sdk/templates/t1-template")
.addChild("t2", "sdk/templates/t2-template")
.assertModelIsOK();
}
@Test
public void testResults()
{
nodeTesterFactory.createItemTester(DirNode.class, "testResults", "sdk/test-results")
.assertModelIsOK();
}
@Test
public void appJars()
{
nodeTesterFactory.createItemTester(DirNode.class, "appJars", "sdk/libs/java/application")
.assertModelIsOK();
}
@Test
public void systemJars()
{
nodeTesterFactory.createItemTester(DirNode.class, "systemJars", "sdk/libs/java/system")
.assertModelIsOK();
}
@Test
public void testJars()
{
nodeTesterFactory.createItemTester(DirNode.class, "testJars", "sdk/libs/java/testRunner")
.assertModelIsOK();
}
@Test
public void userJars()
{
nodeTesterFactory.createItemTester(DirNode.class, "userJars", "conf/java")
.assertModelIsOK();
}
@Test
public void testGettingLoggerForClass() throws Exception
{
Logger logger = brjs.logger(this.getClass());
assertEquals("org.bladerunnerjs.model.navigation", logger.getName());
}
}
| lgpl-3.0 |
RedhawkSDR/burstioInterfaces | src/java/burstio/InPortImpl.java | 6848 | /*
* This file is protected by Copyright. Please refer to the COPYRIGHT file
* distributed with this source distribution.
*
* This file is part of REDHAWK burstioInterfaces.
*
* REDHAWK burstioInterfaces 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.
*
* REDHAWK burstioInterfaces 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 burstio;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
import burstio.stats.ReceiverStatistics;
import burstio.traits.BurstTraits;
public class InPortImpl<E> implements InPort<E>
{
public static final int DEFAULT_QUEUE_THRESHOLD = 100;
private BurstTraits<E,?> traits_;
private final String name_;
private int queueThreshold_ = DEFAULT_QUEUE_THRESHOLD;
private boolean started_ = false;
private ReceiverStatistics statistics_;
private boolean blockOccurred_ = false;
private Set<String> streamIDs_ = new HashSet<String>();
private Queue<E> queue_ = new LinkedList<E>();
protected InPortImpl (final String name, BurstTraits<E,?> traits)
{
this.name_ = name;
this.traits_ = traits;
this.statistics_ = new ReceiverStatistics(this.name_, this.traits_.byteSize() * 8);
}
public String getName ()
{
return this.name_;
}
public void start ()
{
synchronized (queue_) {
this.started_ = true;
}
}
public void stop ()
{
synchronized (queue_) {
if (this.started_) {
this.started_ = false;
this.queue_.notifyAll();
}
}
}
public int getQueueThreshold ()
{
return queueThreshold_;
}
public void setQueueThreshold (int count)
{
synchronized (queue_) {
if (count > queueThreshold_) {
queue_.notifyAll();
}
queueThreshold_ = count;
}
}
public BULKIO.PortUsageType state()
{
synchronized(this.queue_) {
if (this.queue_.isEmpty()) {
return BULKIO.PortUsageType.IDLE;
} else if (this.queue_.size() < this.queueThreshold_) {
return BULKIO.PortUsageType.ACTIVE;
} else {
return BULKIO.PortUsageType.BUSY;
}
}
}
public BULKIO.PortStatistics statistics()
{
synchronized(this.queue_) {
BULKIO.PortStatistics stats = this.statistics_.retrieve();
stats.streamIDs = this.streamIDs_.toArray(new String[this.streamIDs_.size()]);
return stats;
}
}
public void pushBursts(E[] bursts)
{
long start = System.nanoTime();
synchronized (this.queue_) {
// Calculate queue depth based on state at invocation; this makes it
// easy to tell if a consumer is keeping up (average = 0, or at least
// doesn't grow) or blocking (average >= 100).
float queue_depth = queue_.size() / (float)queueThreshold_;
// Only set the block flag once to avoid multiple notifications
boolean block_reported = false;
// Wait until the queue is below the blocking threshold
while (started_ && (queue_.size() >= queueThreshold_)) {
// Report that this call blocked
if (!block_reported) {
block_reported = true;
blockOccurred_ = true;
}
try {
queue_.wait();
} catch (final InterruptedException ex) {
return;
}
}
// Discard bursts if processing is not started
if (!started_) {
return;
}
// Add bursts to queue and notify waiters
queue_.addAll(Arrays.asList(bursts));
queue_.notifyAll();
// Count total elements
int total_elements = 0;
for (E burst : bursts) {
total_elements += this.traits_.burstLength(burst);
final String stream_id = this.traits_.sri(burst).streamID;
this.streamIDs_.add(stream_id);
}
// Record total time spent in pushBursts for latency measurement
double elapsed = (System.nanoTime() - start) * 1e-9;
this.statistics_.record(bursts.length, total_elements, queue_depth, elapsed);
}
}
public boolean blockOccurred ()
{
synchronized (this.queue_) {
boolean retval = this.blockOccurred_;
this.blockOccurred_ = false;
return retval;
}
}
public int getQueueDepth ()
{
synchronized (this.queue_) {
return this.queue_.size();
}
}
public void flush ()
{
synchronized (this.queue_) {
this.statistics_.flushOccurred(this.queue_.size());
this.queue_.clear();
this.queue_.notifyAll();
}
}
public E getBurst (float timeout)
{
synchronized (this.queue_) {
if (!this.waitBurst(timeout)) {
return null;
}
if (queue_.size() <= queueThreshold_) {
queue_.notifyAll();
}
E burst = queue_.remove();
if (this.traits_.eos(burst)) {
final String stream_id = this.traits_.sri(burst).streamID;
this.streamIDs_.remove(stream_id);
}
return burst;
}
}
public E[] getBursts (float timeout)
{
synchronized (this.queue_) {
this.waitBurst(timeout);
E[] bursts = this.traits_.toArray(this.queue_);
queue_.clear();
queue_.notifyAll();
return bursts;
}
}
protected boolean waitBurst (float timeout)
{
if (started_ && queue_.isEmpty() && timeout != 0.0 ) {
try {
if ( timeout < 0.0 ) timeout = 0.0f;
queue_.wait(Math.round(timeout));
} catch (final InterruptedException ex) {
return false;
}
}
return !queue_.isEmpty();
}
}
| lgpl-3.0 |
Jezza/Lava | src/main/java/me/jezza/lava/LuaUserdata.java | 2880 | /**
* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject
* to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package me.jezza.lava;
/**
* Models an arbitrary Java reference as a Lua value.
* This class provides a facility that is equivalent to the userdata
* facility provided by the PUC-Rio implementation. It has two primary
* uses: the first is when you wish to store an arbitrary Java reference
* in a Lua table; the second is when you wish to create a new Lua type
* by defining an opaque object with metamethods. The former is
* possible because a <code>LuaUserdata</code> can be stored in tables,
* and passed to functions, just like any other Lua value. The latter
* is possible because each <code>LuaUserdata</code> supports a
* metatable.
*/
public final class LuaUserdata {
private final Object userdata;
private LuaTable metatable;
private LuaTable env;
/**
* Wraps an arbitrary Java reference. To retrieve the reference that
* was wrapped, use {@link Lua#toUserdata}.
*
* @param o The Java reference to wrap.
*/
public LuaUserdata(Object o) {
userdata = o;
}
/**
* Getter for userdata.
*
* @return the userdata that was passed to the constructor of this
* instance.
*/
Object userdata() {
return userdata;
}
/**
* Getter for metatable.
*
* @return the metatable.
*/
LuaTable metatable() {
return metatable;
}
/**
* Setter for metatable.
*
* @param metatable The metatable.
*/
LuaUserdata metatable(LuaTable metatable) {
this.metatable = metatable;
return this;
}
/**
* Getter for environment.
*
* @return The environment.
*/
LuaTable env() {
return env;
}
/**
* Setter for environment.
*
* @param env The environment.
*/
LuaUserdata env(LuaTable env) {
this.env = env;
return this;
}
}
| lgpl-3.0 |
OpsResearchLLC/or-objects | src/com/opsresearch/orobjects/lib/mp/NumericalException.java | 988 | /* ***** BEGIN LICENSE BLOCK *****
*
* Copyright (C) 2012 OpsResearch LLC (a Delaware company)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License, version 3,
* 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 program. If not, see <http://www.gnu.org/licenses/>.
*
* ***** END LICENSE BLOCK ***** */
package com.opsresearch.orobjects.lib.mp;
public class NumericalException extends MpException {
private static final long serialVersionUID = 1L;
public NumericalException() {
}
public NumericalException(String s) {
super(s);
}
}
| lgpl-3.0 |
changshengmen/secureManagementSystem | src/main/java/net/jeeshop/web/action/front/orders/CartInfo.java | 2560 | package net.jeeshop.web.action.front.orders;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;
import net.jeeshop.core.dao.page.ClearBean;
import net.jeeshop.core.dao.page.PagerModel;
import net.jeeshop.services.front.product.bean.Product;
/**
* 购物车对象,独立出此对象是为了以后的方便操作,当业务进行扩展的时候不会导致系统混乱。
*
* @author huangf
*
*/
public class CartInfo extends PagerModel implements Serializable {
static final java.text.DecimalFormat df =new java.text.DecimalFormat("#.00");
private List<Product> productList;// 购物车中商品列表
// private String productTotal;//商品总金额
private String amount;// 合计总金额,也就是用户最终需要支付的金额
private int totalExchangeScore;//总计所需积分
private String defaultAddessID;//用户的默认地址ID
public List<Product> getProductList() {
if(productList==null){
productList = new LinkedList<Product>();
}
return productList;
}
public void setProductList(List<Product> productList) {
this.productList = productList;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
/**
* 购物车汇总计算总金额
* @return
*/
public void totalCacl(){
double _amount = 0;
int _totalExchangeScore = 0;
for(int i=0;i<getProductList().size();i++){
Product p = getProductList().get(i);
//积分商城的商品不参与金额计算
if(p.getExchangeScore() > 0){
_totalExchangeScore += p.getExchangeScore() * p.getBuyCount();
continue;
}
// _productTotal += Double.valueOf(p.getNowPrice()) * p.getBuyCount();
_amount += Double.valueOf(p.getNowPrice()) * p.getBuyCount();
}
this.totalExchangeScore = _totalExchangeScore;
// this.productTotal = df.format(_productTotal);
if(_amount!=0){
this.amount = df.format(_amount);
}else{
this.amount = "0.00";
}
}
@Override
public void clear() {
if(productList!=null){
for(int i=0;i<productList.size();i++){
productList.get(i).clear();
}
productList.clear();
productList = null;
}
amount = null;
}
public String getDefaultAddessID() {
return defaultAddessID;
}
public void setDefaultAddessID(String defaultAddessID) {
this.defaultAddessID = defaultAddessID;
}
public int getTotalExchangeScore() {
return totalExchangeScore;
}
public void setTotalExchangeScore(int totalExchangeScore) {
this.totalExchangeScore = totalExchangeScore;
}
}
| lgpl-3.0 |