repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
tharindum/opennms_dashboard | opennms-qosdaemon/src/main/java/org/openoss/opennms/spring/qosd/jmx/QoSD.java | 6133 | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2006-2011 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2011 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.openoss.opennms.spring.qosd.jmx;
import org.opennms.core.utils.ThreadCategory;
import org.opennms.netmgt.daemon.AbstractServiceDaemon;
import org.springframework.beans.factory.access.BeanFactoryLocator;
import org.springframework.beans.factory.access.BeanFactoryReference;
import org.springframework.context.ApplicationContext;
import org.springframework.context.access.DefaultLocatorFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* This JMX bean loads the QoSD daemon as a spring bean using the
* qosd-context.xml file.
*
* @author ranger
* @version $Id: $
*/
public class QoSD extends AbstractServiceDaemon implements QoSDMBean {
/**
* <p>Constructor for QoSD.</p>
*/
public QoSD() {
super(NAME);
}
private static final String NAME = org.openoss.opennms.spring.qosd.QoSDimpl2.NAME;
private ClassPathXmlApplicationContext m_context;
// used only for testing
ApplicationContext getContext() {
return m_context;
}
/**
* <p>onInit</p>
*/
protected void onInit() {}
/**
* <p>onStart</p>
*/
protected void onStart() {
//TODO REMOVE EXAMPLE IMPORTER CODE
// ThreadCategory.setPrefix(ImporterService.NAME);
// m_status = Fiber.STARTING;
// ThreadCategory.getInstance().debug("SPRING: thread.classLoader="+Thread.currentThread().getContextClassLoader());
// BeanFactoryLocator bfl = DefaultLocatorFactory.getInstance();
// BeanFactoryReference bf = bfl.useBeanFactory("daoContext");
// ApplicationContext daoContext = (ApplicationContext) bf.getFactory();
// m_context = new ClassPathXmlApplicationContext(new String[] { "/org/opennms/netmgt/importer/importer-context.xml" }, daoContext);
// ThreadCategory.getInstance().debug("SPRING: context.classLoader="+m_context.getClassLoader());
// m_status = Fiber.RUNNING;
ThreadCategory.getInstance().debug("SPRING: thread.classLoader="+Thread.currentThread().getContextClassLoader());
// finds the already instantiated OpenNMS daoContext
BeanFactoryLocator bfl = DefaultLocatorFactory.getInstance();
BeanFactoryReference bf = bfl.useBeanFactory("daoContext");
ApplicationContext daoContext = (ApplicationContext) bf.getFactory();
// this chooses if we expect AlarmMonitor to run in seperate j2ee container ( Jboss ) or in local
// OpenNMS spring container
String qosdj2ee=System.getProperty("qosd.usej2ee");
ThreadCategory.getInstance().info("QoSD System Property qosd.usej2ee=" + qosdj2ee );
if ("true".equals(qosdj2ee)){
ThreadCategory.getInstance().debug("QoSD using /org/openoss/opennms/spring/qosd/qosd-j2ee-context.xml");
m_context = new ClassPathXmlApplicationContext(new String[] { "/org/openoss/opennms/spring/qosd/qosd-j2ee-context.xml" },daoContext);
}
else {
ThreadCategory.getInstance().debug("QoSD using /org/openoss/opennms/spring/qosd/qosd-spring-context.xml");
m_context = new ClassPathXmlApplicationContext(new String[] { "/org/openoss/opennms/spring/qosd/qosd-spring-context.xml" },daoContext);
}
ThreadCategory.getInstance().debug("SPRING: context.classLoader="+m_context.getClassLoader());
getQoSD().init();
getQoSD().start();
// TODO remove original code
// ThreadCategory.setPrefix(QoSD.NAME);
// m_status = Fiber.STARTING;
// ThreadCategory.getInstance().debug("SPRING: thread.classLoader="+Thread.currentThread().getContextClassLoader());
// // this chooses if we expect AlarmMonitor to run in seperate j2ee container ( Jboss ) or in local
// // OpenNMS spring container
// String qosdj2ee=System.getProperty("qosd.usej2ee");
// ThreadCategory.getInstance().info("QoSD System Property qosd.usej2ee=" + qosdj2ee );
// if ("true".equals(qosdj2ee)){
// ThreadCategory.getInstance().debug("QoSD using /org/openoss/opennms/spring/qosd/qosd-j2ee-context.xml");
// m_context = new ClassPathXmlApplicationContext(new String[] { "/org/openoss/opennms/spring/qosd/qosd-j2ee-context.xml" });
// }
// else {
// ThreadCategory.getInstance().debug("QoSD using /org/openoss/opennms/spring/qosd/qosd-spring-context.xml");
// m_context = new ClassPathXmlApplicationContext(new String[] { "/org/openoss/opennms/spring/qosd/qosd-spring-context.xml" });
// }
// ThreadCategory.getInstance().debug("SPRING: context.classLoader="+m_context.getClassLoader());
// getQoSD().init();
// getQoSD().start();
// m_status = Fiber.RUNNING;
}
/**
* <p>onStop</p>
*/
protected void onStop() {
getQoSD().stop();
m_context.close();
}
/**
* <p>getStats</p>
*
* @return a {@link java.lang.String} object.
*/
public String getStats() {
return getQoSD().getStats();
}
/**
* Returns the qosd singleton
* @return qosd
*/
private org.openoss.opennms.spring.qosd.QoSD getQoSD() {
org.openoss.opennms.spring.qosd.QoSD qosd = (org.openoss.opennms.spring.qosd.QoSD)m_context.getBean("QoSD");
qosd.setApplicationContext(m_context); // pass in local spring application context
return qosd;
}
}
| gpl-2.0 |
arodchen/MaxSim | maxine/com.oracle.max.vm/src/com/sun/max/vm/heap/gcx/rset/ctbl/CardTableRSet.java | 30106 | /*
* Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.max.vm.heap.gcx.rset.ctbl;
import static com.sun.max.vm.heap.HeapSchemeAdaptor.*;
import java.util.*;
import com.sun.cri.ci.CiAddress.Scale;
import com.sun.cri.ci.*;
import com.sun.cri.xir.*;
import com.sun.cri.xir.CiXirAssembler.XirConstant;
import com.sun.cri.xir.CiXirAssembler.XirOperand;
import com.sun.max.annotate.*;
import com.sun.max.memory.*;
import com.sun.max.platform.*;
import com.sun.max.unsafe.*;
import com.sun.max.vm.*;
import com.sun.max.vm.MaxineVM.Phase;
import com.sun.max.vm.code.*;
import com.sun.max.vm.compiler.*;
import com.sun.max.vm.heap.*;
import com.sun.max.vm.heap.HeapScheme.BootRegionMappingConstraint;
import com.sun.max.vm.heap.gcx.*;
import com.sun.max.vm.heap.gcx.rset.*;
import com.sun.max.vm.hosted.*;
import com.sun.max.vm.layout.*;
import com.sun.max.vm.reference.*;
import com.sun.max.vm.runtime.*;
/**
* Card-table based remembered set.
*/
public final class CardTableRSet extends DeadSpaceListener implements HeapManagementMemoryRequirement {
/**
* Log2 of a card size in bytes.
*/
static public final int LOG2_CARD_SIZE = 9;
/**
* Number of bytes per card.
*/
static final int CARD_SIZE = 1 << LOG2_CARD_SIZE;
static final int LOG2_NUM_WORDS_PER_CARD = LOG2_CARD_SIZE - Word.widthValue().log2numberOfBytes;
static final int NUM_WORDS_PER_CARD = 1 << LOG2_NUM_WORDS_PER_CARD;
static public final int NO_CARD_INDEX = -1;
static final Address CARD_ADDRESS_MASK = Address.fromInt(CARD_SIZE - 1).not();
private static boolean TraceCardTableRSet = false;
static {
if (MaxineVM.isDebug()) {
VMOptions.addFieldOption("-XX:", "TraceCardTableRSet", CardTableRSet.class, "Enables CardTableRSet Debugging Traces", Phase.PRISTINE);
}
}
@INLINE
public static boolean traceCardTableRSet() {
return MaxineVM.isDebug() && TraceCardTableRSet;
}
public static void setTraceCardTableRSet(boolean flag) {
TraceCardTableRSet = flag;
}
/**
* Contiguous regions of virtual memory holding the remembered set data (both the card table and the FOT).
* Mostly used to feed the inspector.
*/
@INSPECTED
final MemoryRegion tablesMemory;
/**
* The table recording card state. The table is updated by compiler-generated write-barrier execution and explicitly by the GC.
*/
@INSPECTED
public final CardTable cardTable;
/**
* The table recording the first object overlapping with every card.
* The table is updated by allocators and free space reclamation.
*/
@INSPECTED
public final CardFirstObjectTable cfoTable;
/**
* CiConstant holding the card table's biased address in boot code region and used for all XirSnippets implementing the write barrier.
* Biased card table address XirConstant are initialized with this CiConstant which holds a WrappedWord object with a dummy address.
* The WrappedWord object can be used during the serializing phase of boot image generation to identify easily the literal locations
* in the boot code region that hold the biased card table address. A table of these location is added in the boot image and used at
* VM startup to patch them with the actual biased card table address once this one is known.
* See {@link #patchBootCodeLiterals()}
*/
@HOSTED_ONLY
private CiConstant biasedCardTableAddressCiConstant;
@HOSTED_ONLY
private List<XirConstant> xirConstants = new ArrayList<XirConstant>(16);
/**
* List of XIR constants representing the biased card table address.
* The list is used at startup to initialize the "startup-time" constant value.
*/
private XirBiasedCardTableConstant [] biasedCardTableAddressXirConstants = new XirBiasedCardTableConstant[0];
@HOSTED_ONLY
ReferenceLiteralLocationRecorder literalRecorder;
/**
* Table holding all the locations in the boot code region of reference literals to the biased card table.
* This allows to patch these literals with the actual correct value of the biased card table, known only at
* heap scheme pristine initialization.
* The index are word indexes relative to the start of the boot code region.
*/
private int [] bootCardTableLiterals;
private void patchBootCodeLiterals() {
final Pointer base = Code.bootCodeRegion().start().asPointer();
final Address biasedTableAddress = cardTable.biasedTableAddress;
for (int literalPos : bootCardTableLiterals) {
base.setWord(literalPos, biasedTableAddress);
}
}
public CardTableRSet() {
cardTable = new CardTable();
cfoTable = new CardFirstObjectTable();
tablesMemory = new MemoryRegion("Card and FOT tables");
}
/**
* Initialization of the card-table remembered set according to VM initialization phase.
*
* @param phase the initializing phase the VM is initializing for
*/
public void initialize(MaxineVM.Phase phase) {
if (MaxineVM.isHosted()) {
if (phase == Phase.SERIALIZING_IMAGE) {
// Build a table of indexes to reference literals that point to the card table.
assert biasedCardTableAddressCiConstant != null;
literalRecorder = new ReferenceLiteralLocationRecorder(Code.bootCodeRegion(), biasedCardTableAddressCiConstant.asObject());
bootCardTableLiterals = literalRecorder.getLiteralLocations();
biasedCardTableAddressXirConstants = xirConstants.toArray(biasedCardTableAddressXirConstants);
} else if (phase == MaxineVM.Phase.WRITING_IMAGE) {
literalRecorder.fillLiteralLocations();
}
} else if (phase == MaxineVM.Phase.PRIMORDIAL) {
// We need to initialize the card table to cover the boot region before hitting any write barriers.
// If heap size is specified by the end user, it can only be known at PRISTINE time. We need to initialize the card table to a valid memory address
// before that as some write barrier may be exercised before the heap is even allocated (e.g., to initialize a VMOption in the boot region for instance).
// To this end, we initialize at PRIMORDIAL time the card table with enough memory to cover the boot region.
// This card table is temporary and will be replaced with the table covering the heap once this one is allocated (typically in PRISTINE initialization).
// FIXME: this for now assume that the heap scheme using the card table has (i) reserved enough virtual space to hold the boot region and the
// temporary card table, and (ii), has mapped the boot region at the start of this reserved space.
// The following relies on these assumption to use the end of the reserved virtual space for the temporary card table.
final Size reservedSpace = Size.K.times(VMConfiguration.vmConfig().heapScheme().reservedVirtualSpaceKB());
final Size bootCardTableSize = memoryRequirement(Heap.bootHeapRegion.size()).roundedUpBy(Platform.platform().pageSize);
final Address bootCardTableStart = Heap.bootHeapRegion.start().plus(reservedSpace).minus(bootCardTableSize);
FatalError.check(reservedSpace.greaterThan(bootCardTableSize.plus(Heap.bootHeapRegion.size())) &&
VMConfiguration.vmConfig().heapScheme().bootRegionMappingConstraint().equals(BootRegionMappingConstraint.AT_START),
"card table remembered set initialization invariant violated");
initialize(Heap.bootHeapRegion.start(), Heap.bootHeapRegion.size(), bootCardTableStart, bootCardTableSize);
}
}
/**
* Initialize a card table based remembered set to cover a contiguous range of virtual addresses.
* The memory for the remembered set tables (card and FOT tables) must be provided by the caller as the
* caller may want to enforce some constraints on the location of these tables in memory with respect to the covered heap addresses.
* The amount of memory needed by remembered set's tables for a given area to cover is computed using {@link #memoryRequirement(Size)}.
*
* @param coveredAreaStart start of the contiguous range of heap covered by the remembered set
* @param coveredAreaSize end of the contiguous range of heap covered by the remembered set
* @param tablesDataStart start of the memory regions reserved for the remembered set's tables
* @param tablesDataSize end of the memory regions reserved for the remembered set's tables
*/
public void initialize(Address coveredAreaStart, Size coveredAreaSize, Address tablesDataStart, Size tablesDataSize) {
tablesMemory.setStart(tablesDataStart);
tablesMemory.setSize(tablesDataSize);
cardTable.initialize(coveredAreaStart, coveredAreaSize, tablesDataStart);
final Address cfoTableStart = tablesDataStart.plus(cardTable.tableSize(coveredAreaSize).wordAligned());
cfoTable.initialize(coveredAreaStart, coveredAreaSize, cfoTableStart);
if (bootCardTableLiterals != null) {
patchBootCodeLiterals();
}
}
static class XirBiasedCardTableConstant extends CiXirAssembler.XirConstant {
XirBiasedCardTableConstant(CiXirAssembler asm, CiConstant value) {
super(asm, "Card Table biased-address", value);
asm.recordConstant(this);
}
void setStartupValue(CiConstant startupValue) {
value = startupValue;
}
}
/**
* Set the constant values representing the biased address of the card table in XIR snippets.
* Must be done once, after the final card table is initialized and before the compiler generates code using these XIR snippets.
* Typically, this is called at the end of the PRISTINE initialization of the heap scheme.
*/
public void initializeXirStartupConstants() {
final CiConstant biasedCardTableCiConstant = CiConstant.forLong(cardTable.biasedTableAddress.toLong());
for (XirBiasedCardTableConstant c : biasedCardTableAddressXirConstants) {
c.setStartupValue(biasedCardTableCiConstant);
}
}
@HOSTED_ONLY
private XirConstant biasedCardTableAddressXirConstant(CiXirAssembler asm) {
if (biasedCardTableAddressCiConstant == null) {
biasedCardTableAddressCiConstant = WordUtil.wrappedConstant(Address.fromLong(123456789L));
}
XirConstant constant = new XirBiasedCardTableConstant(asm, biasedCardTableAddressCiConstant);
xirConstants.add(constant);
return constant;
}
@HOSTED_ONLY
public void genTuplePostWriteBarrier(CiXirAssembler asm, XirOperand tupleCell) {
final XirOperand temp = asm.createTemp("temp", WordUtil.archKind());
asm.shr(temp, tupleCell, asm.i(CardTableRSet.LOG2_CARD_SIZE));
// Watch out: this create a reference literal that will not point to an object!
// The GC will need to carefully skip reference table entries holding the biased base of the card table.
// final XirConstant biasedCardTableAddress = asm.createConstant(CiConstant.forObject(dummyCardTable));
final XirConstant biasedCardTableAddress = biasedCardTableAddressXirConstant(asm);
asm.pstore(CiKind.Byte, biasedCardTableAddress, temp, asm.i(CardState.DIRTY_CARD.value()), false);
// FIXME: remove this temp debug code
if (MaxineVM.isDebug()) {
// Just so that we get the address of the card entry in a register when inspecting...
asm.lea(temp, biasedCardTableAddress, temp, 0, Scale.Times1);
}
}
@HOSTED_ONLY
public void genArrayPostWriteBarrier(CiXirAssembler asm, XirOperand arrayCell, XirOperand elemIndex) {
final XirOperand temp = asm.createTemp("temp", WordUtil.archKind());
final Scale scale = Scale.fromInt(Word.size());
final int disp = Layout.referenceArrayLayout().getElementOffsetInCell(0).toInt();
asm.lea(temp, arrayCell, elemIndex, disp, scale);
asm.shr(temp, temp, asm.i(CardTableRSet.LOG2_CARD_SIZE));
// final XirConstant biasedCardTableAddress = asm.createConstant(CiConstant.forObject(dummyCardTable));
final XirConstant biasedCardTableAddress = biasedCardTableAddressXirConstant(asm);
asm.pstore(CiKind.Byte, biasedCardTableAddress, temp, asm.i(CardState.DIRTY_CARD.value()), false);
}
/**
* Record update to a reference slot of a cell.
* @param ref the cell whose reference is updated
* @param offset the offset from the origin of the cell to the updated reference.
*/
public void record(Reference ref, Offset offset) {
cardTable.dirtyCovered(ref.toOrigin().plus(offset));
}
/**
* Record update to a reference slot of a cell.
* @param ref the cell whose reference is updated
* @param displacement a displacement from the origin of the cell
* @param index a word index to the updated reference
*/
public void record(Reference ref, int displacement, int index) {
cardTable.dirtyCovered(ref.toOrigin().plus(Address.fromInt(index).shiftedLeft(Word.widthValue().log2numberOfBytes).plus(displacement)));
}
/**
* Visit the cells that overlap a card.
*
* @param cardIndex index of the card
* @param cellVisitor the logic to apply to the visited cell
*/
private void visitCard(int cardIndex, OverlappingCellVisitor cellVisitor) {
visitCards(cardIndex, cardIndex + 1, cellVisitor);
}
/**
* Visit all the cells that overlap the specified range of cards.
* The range of visited cards extends from the card startCardIndex, inclusive, to the
* card endCardIndex, exclusive.
*
* @param cellVisitor the logic to apply to the visited cell
*/
private void visitCards(int startCardIndex, int endCardIndex, OverlappingCellVisitor cellVisitor) {
final Address start = cardTable.rangeStart(startCardIndex);
final Address end = cardTable.rangeStart(endCardIndex);
Pointer cell = cfoTable.cellStart(startCardIndex).asPointer();
do {
cell = cellVisitor.visitCell(cell, start, end);
if (MaxineVM.isDebug()) {
// FIXME: this is too strong, because DeadSpaceCardTableUpdater may leave a FOT entry temporarily out-dated by up
// to minObjectSize() words when the HeapFreeChunkHeader of the space the allocator was refill with is immediately
// before a card boundary.
// I 'm leaving this as is now to see whether we ever run into this case, but this
// should really be cell.plus(minObjectSize()).greaterThan(start);
FatalError.check(cell.plus(HeapSchemeAdaptor.minObjectSize()).greaterThan(start), "visited cell must overlap visited card.");
}
} while (cell.lessThan(end));
}
private void traceVisitedCard(int startCardIndex, int endCardIndex, CardState cardState) {
Log.print("Visiting ");
Log.print(cardState.name());
Log.print(" cards [");
Log.print(startCardIndex);
Log.print(", ");
Log.print(endCardIndex);
Log.print("] (");
Log.print(cardTable.rangeStart(startCardIndex));
Log.print(", ");
Log.print(cardTable.rangeStart(endCardIndex));
Log.println(")");
}
public void checkNoCardInState(Address start, Address end, CardState cardState) {
final int endOfRange = cardTable.tableEntryIndex(end);
int cardIndex = cardTable.first(cardTable.tableEntryIndex(start), endOfRange, cardState);
if (cardIndex < endOfRange) {
Log.print("Unexpected state for card #");
Log.print(cardIndex);
Log.print(" [");
Log.print(cardTable.rangeStart(cardIndex));
Log.print(", ");
Log.print(cardTable.rangeStart(cardIndex + 1));
Log.println(" ]");
FatalError.breakpoint();
FatalError.crash("invariant violation");
}
}
public int countCardInState(Address start, Address end, CardState cardState) {
final int endOfRange = cardTable.tableEntryIndex(end);
int count = 0;
int cardIndex = cardTable.first(cardTable.tableEntryIndex(start), endOfRange, cardState);
while (cardIndex < endOfRange) {
count++;
cardIndex = cardTable.first(++cardIndex, endOfRange, cardState);
}
return count;
}
public void setCards(Address start, Address end, CardState cardState) {
cardTable.fill(cardTable.tableEntryIndex(start), cardTable.tableEntryIndex(end), cardState.value);
}
public static abstract class CardRangeVisitor {
abstract public void visitCards(Address start, Address end);
}
public void cleanAndVisitCards(Address start, Address end, CardRangeVisitor cardRangeVisitor) {
final int endOfRange = cardTable.tableEntryIndex(end);
int startCardIndex = cardTable.first(cardTable.tableEntryIndex(start), endOfRange, CardState.DIRTY_CARD);
while (startCardIndex < endOfRange) {
int endCardIndex = cardTable.firstNot(startCardIndex + 1, endOfRange, CardState.DIRTY_CARD);
if (traceCardTableRSet()) {
traceVisitedCard(startCardIndex, endCardIndex, CardState.DIRTY_CARD);
}
cardTable.clean(startCardIndex, endCardIndex);
cardRangeVisitor.visitCards(cardTable.rangeStart(startCardIndex), cardTable.rangeStart(endCardIndex));
if (++endCardIndex >= endOfRange) {
return;
}
startCardIndex = cardTable.first(endCardIndex, endOfRange, CardState.DIRTY_CARD);
}
}
/**
* Iterate over cells that overlap the specified region and comprises recorded reference locations.
* @param start
* @param end
* @param cellVisitor
*/
public void cleanAndVisitCards(Address start, Address end, OverlappingCellVisitor cellVisitor) {
final int endOfRange = cardTable.tableEntryIndex(end);
int startCardIndex = cardTable.first(cardTable.tableEntryIndex(start), endOfRange, CardState.DIRTY_CARD);
while (startCardIndex < endOfRange) {
int endCardIndex = cardTable.firstNot(startCardIndex + 1, endOfRange, CardState.DIRTY_CARD);
if (traceCardTableRSet()) {
traceVisitedCard(startCardIndex, endCardIndex, CardState.DIRTY_CARD);
}
cardTable.clean(startCardIndex, endCardIndex);
visitCards(startCardIndex, endCardIndex, cellVisitor);
if (++endCardIndex >= endOfRange) {
return;
}
startCardIndex = cardTable.first(endCardIndex, endOfRange, CardState.DIRTY_CARD);
}
}
public void visitCards(Address start, Address end, CardState cardState, OverlappingCellVisitor cellVisitor) {
final int endOfRange = cardTable.tableEntryIndex(end);
int startCardIndex = cardTable.first(cardTable.tableEntryIndex(start), endOfRange, cardState);
while (startCardIndex < endOfRange) {
int endCardIndex = cardTable.firstNot(startCardIndex + 1, endOfRange, cardState);
if (traceCardTableRSet()) {
traceVisitedCard(startCardIndex, endCardIndex, cardState);
}
visitCards(startCardIndex, endCardIndex, cellVisitor);
if (++endCardIndex >= endOfRange) {
return;
}
startCardIndex = cardTable.first(endCardIndex, endOfRange, cardState);
}
}
/**
* Returns the amount of memory needed by the card table to cover a contiguous range of memory of the specified size.
* @param maxCoveredAreaSize the size of the contiguous range of memory that the card table should cover
* @return the number of bytes needed by the card table remembered set
*/
@Override
public Size memoryRequirement(Size maxCoveredAreaSize) {
return cardTable.tableSize(maxCoveredAreaSize).plus(cfoTable.tableSize(maxCoveredAreaSize));
}
/**
* Contiguous region of memory used by the remembered set.
* @return a non-null {@link MemoryRegion}
*/
public MemoryRegion memory() {
return tablesMemory;
}
private void updateForFreeSpace(Address start, Address end) {
// Note: this doesn't invalid subsequent entries of the FOT table.
cfoTable.set(start, end);
// Clean cards that are completely overlapped by the free space only.
cardTable.setCardsInRange(start, end, CardState.CLEAN_CARD);
}
/**
* Update the remembered set to take into account the newly freed space.
* @param start address to the first word of the freed chunk
* @param size size of the freed chunk
*/
public void updateForFreeSpace(Address start, Size size) {
updateForFreeSpace(start, start.plus(size));
}
public static Address alignUpToCard(Address coveredAddress) {
return coveredAddress.plus(CARD_SIZE).and(CARD_ADDRESS_MASK);
}
public static Address alignDownToCard(Address coveredAddress) {
return coveredAddress.and(CARD_ADDRESS_MASK);
}
// Allocation may occur while iterating over dirty cards to evacuate young objects. Such allocations may temporarily invalidate
// the FOT for cards overlapping with the allocator, and may break the ability to walk over these cards.
// One solution is keep all the FOT entries covering the allocation space up to date at every allocation.
// Every time an allocation occurs it splits the allocation space in two. Each side forms a new cell for which FOT entries need to be
// updated.
//
// Another solution is to make the last card of the free chunk used by the allocator independent of FOT updates required by the split.
// The last card is the only one that may be dirtied, and therefore the only one that can be walked over during evacuation.
//
// Let s and e be the start and end of a free chunk.
// Let c be the top-most card address such that c >= e, and C be the card starting at c, with FOT(C) denoting the entry
// of the FOT for card C.
// If e == c, whatever objects are allocated between s and e, FOT(C) == 0, i.e., allocations never invalidate FOT(C).
// Thus C is iterable at all time by a dirty card walker.
//
// If e > c, then FOT(C) might be invalidated by allocation.
// We may avoid this by formatting the space delimited by [c,e] as a dead object embedded in the heap free chunk.
// This will allow FOT(C) to be zero, and not be invalidated by any allocation of space before C.
// Formatting [c,e] has however several corner cases:
// 1. [c,e] may be smaller than the minimum object size, so we can't format it.
// Instead, we can format [x,e], such x < e and [x,e] is the min object size. In this case, FOT(C) = x - e.
// [x,e] can only be overwritten by the last allocation from the buffer,
// so FOT(C) doesn't need to be updated until that last allocation,
// which is always special cased (see why below).
// 2. s + sizeof(free chunk header) > c, i.e., the head of the free space chunk overlap C.
// Don't reformat the heap chunk. FOT(C) will be updated correctly since the allocator
// always set the FOT table for the newly allocated cells.
//
// This function decide whether the last card of the dead space need to be split and formatted as a
// dead objects at card boundary to avoid updating the FOT entries covering the right-hand side of an allocation split.
// If it return Address.zero() then the chunks remains as a single object, otherwise, it's tail was reformated as a dead object
// and the FOT must be updated accordingly.
// In both case, subsequent split event on this dead space only need to update the left-hand side of the allocation split (using the set() method).
private Address splitLastCard(Address deadSpace, Size numDeadBytes) {
if (numDeadBytes.greaterEqual(CARD_SIZE)) {
final Address end = deadSpace.plus(numDeadBytes);
final Address lastCardStart = alignDownToCard(end);
if (lastCardStart.minus(deadSpace).greaterThan(HeapFreeChunk.heapFreeChunkHeaderSize())) {
// Format the end of the heap free chunk as a dead object.
Address deadObjectAddress = lastCardStart;
Size deadObjectSize = end.minus(deadObjectAddress).asSize();
if (deadObjectSize.lessThan(minObjectSize())) {
deadObjectAddress = end.minus(minObjectSize());
}
if (MaxineVM.isDebug() && CardFirstObjectTable.TraceFOT) {
Log.print("Split last card of Dead Space [");
Log.print(deadSpace); Log.print(", ");
Log.print(end);
Log.print("] @ ");
Log.print(deadObjectAddress);
Log.print(" card # ");
Log.println(cardTable.tableEntryIndex(deadObjectAddress));
}
// Here we don't use dark matter as we're formatting allocatable space.
HeapSchemeAdaptor.fillWithDeadObject(deadObjectAddress, end);
return deadObjectAddress;
}
}
return Address.zero();
}
/**
* Prepare an contiguous range of heap space to be used for allocation (i.e., split live operations).
* See comments for {@link #splitLastCard(Address, Size)}.
*
* @param deadSpace address to the first byte of the dead space
* @param numDeadBytes number of bytes
*/
private void prepareForSplitLive(Address deadSpace, Size numDeadBytes) {
// Same as above, except that the dead space may need reformatted similar to coalescing.
final Address deadObjectAddress = splitLastCard(deadSpace, numDeadBytes);
if (deadObjectAddress.isNotZero()) {
cfoTable.set(deadSpace, deadObjectAddress);
cfoTable.set(deadObjectAddress, deadSpace.plus(numDeadBytes));
} else {
// Otherwise, the free chunk is either smaller than a card, or it is smaller than two cards and its header spawn the two cards.
cfoTable.set(deadSpace, numDeadBytes);
}
}
@INLINE
@Override
public void notifyCoalescing(Address deadSpace, Size numDeadBytes) {
final Address deadObjectAddress = splitLastCard(deadSpace, numDeadBytes);
if (deadObjectAddress.isNotZero()) {
updateForFreeSpace(deadSpace, deadObjectAddress);
updateForFreeSpace(deadObjectAddress, deadSpace.plus(numDeadBytes));
} else {
// Otherwise, the free chunk is either smaller than a card, or it is smaller than two cards and its header spawn the two cards.
updateForFreeSpace(deadSpace, numDeadBytes);
}
}
@INLINE
@Override
public void notifySplitLive(Address start, Size leftSize, Address end) {
// We only have to set the FOT for the left-hand side of the split. The right-hand side is formatted to avoid update to its FOT.
// See notifyCoalescing and notifyRetireFreeSpace.
cfoTable.set(start, leftSize);
}
@INLINE
@Override
public void notifySplitDead(Address start, Size leftSize, Address end) {
Address splitBound = start.plus(leftSize);
// We need each of the split free space to be formatted as if each were just coalesced
prepareForSplitLive(start, leftSize);
prepareForSplitLive(splitBound, end.minus(splitBound).asSize());
}
@INLINE
@Override
public void notifyRefill(Address deadSpace, Size numDeadBytes) {
// We don't need to do anything as dead space are already formatted correctly during coalescing and retire events.
}
@INLINE
@Override
public void notifyRetireDeadSpace(Address deadSpace, Size numDeadBytes) {
// Retired space is unoccupied space left-over by an allocator.
// We only need to update the FOT table to form a single contiguous dead space.
// Don't reset the card table overlapping it (as is done in notifyCoalescing): cards that completely overlap with
// the dead space were already cleaned in the coalescing event that formed the dead space this retired dead
// space was originally a part of.
// Cards that partially overlap with live objects (i.e., at the bounds of the dead space) must be left untouched.
cfoTable.set(deadSpace, numDeadBytes);
}
@INLINE
@Override
public void notifyRetireFreeSpace(Address deadSpace, Size numDeadBytes) {
prepareForSplitLive(deadSpace, numDeadBytes);
}
}
| gpl-2.0 |
jbjonesjr/geoproponis | external/odfdom-java-0.8.10-incubating-sources/org/odftoolkit/odfdom/dom/element/db/DbOrderStatementElement.java | 4460 | /************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* Copyright 2008, 2010 Oracle and/or its affiliates. All rights reserved.
*
* Use is subject to license terms.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0. You can also
* obtain a copy of the License at http://odftoolkit.org/docs/license.txt
*
* 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.
*
************************************************************************/
/*
* This file is automatically generated.
* Don't edit manually.
*/
package org.odftoolkit.odfdom.dom.element.db;
import org.odftoolkit.odfdom.pkg.OdfElement;
import org.odftoolkit.odfdom.pkg.ElementVisitor;
import org.odftoolkit.odfdom.pkg.OdfFileDom;
import org.odftoolkit.odfdom.pkg.OdfName;
import org.odftoolkit.odfdom.dom.OdfDocumentNamespace;
import org.odftoolkit.odfdom.dom.DefaultElementVisitor;
import org.odftoolkit.odfdom.dom.attribute.db.DbApplyCommandAttribute;
import org.odftoolkit.odfdom.dom.attribute.db.DbCommandAttribute;
/**
* DOM implementation of OpenDocument element {@odf.element db:order-statement}.
*
*/
public class DbOrderStatementElement extends OdfElement {
public static final OdfName ELEMENT_NAME = OdfName.newName(OdfDocumentNamespace.DB, "order-statement");
/**
* Create the instance of <code>DbOrderStatementElement</code>
*
* @param ownerDoc The type is <code>OdfFileDom</code>
*/
public DbOrderStatementElement(OdfFileDom ownerDoc) {
super(ownerDoc, ELEMENT_NAME);
}
/**
* Get the element name
*
* @return return <code>OdfName</code> the name of element {@odf.element db:order-statement}.
*/
public OdfName getOdfName() {
return ELEMENT_NAME;
}
/**
* Receives the value of the ODFDOM attribute representation <code>DbApplyCommandAttribute</code> , See {@odf.attribute db:apply-command}
*
* @return - the <code>Boolean</code> , the value or <code>null</code>, if the attribute is not set and no default value defined.
*/
public Boolean getDbApplyCommandAttribute() {
DbApplyCommandAttribute attr = (DbApplyCommandAttribute) getOdfAttribute(OdfDocumentNamespace.DB, "apply-command");
if (attr != null) {
return Boolean.valueOf(attr.booleanValue());
}
return Boolean.valueOf(DbApplyCommandAttribute.DEFAULT_VALUE);
}
/**
* Sets the value of ODFDOM attribute representation <code>DbApplyCommandAttribute</code> , See {@odf.attribute db:apply-command}
*
* @param dbApplyCommandValue The type is <code>Boolean</code>
*/
public void setDbApplyCommandAttribute(Boolean dbApplyCommandValue) {
DbApplyCommandAttribute attr = new DbApplyCommandAttribute((OdfFileDom) this.ownerDocument);
setOdfAttribute(attr);
attr.setBooleanValue(dbApplyCommandValue.booleanValue());
}
/**
* Receives the value of the ODFDOM attribute representation <code>DbCommandAttribute</code> , See {@odf.attribute db:command}
*
* Attribute is mandatory.
*
* @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set and no default value defined.
*/
public String getDbCommandAttribute() {
DbCommandAttribute attr = (DbCommandAttribute) getOdfAttribute(OdfDocumentNamespace.DB, "command");
if (attr != null) {
return String.valueOf(attr.getValue());
}
return null;
}
/**
* Sets the value of ODFDOM attribute representation <code>DbCommandAttribute</code> , See {@odf.attribute db:command}
*
* @param dbCommandValue The type is <code>String</code>
*/
public void setDbCommandAttribute(String dbCommandValue) {
DbCommandAttribute attr = new DbCommandAttribute((OdfFileDom) this.ownerDocument);
setOdfAttribute(attr);
attr.setValue(dbCommandValue);
}
@Override
public void accept(ElementVisitor visitor) {
if (visitor instanceof DefaultElementVisitor) {
DefaultElementVisitor defaultVisitor = (DefaultElementVisitor) visitor;
defaultVisitor.visit(this);
} else {
visitor.visit(this);
}
}
}
| gpl-2.0 |
openjdk/jdk7u | jdk/src/share/classes/sun/java2d/pipe/BufferedRenderPipe.java | 20907 | /*
* Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.java2d.pipe;
import java.awt.BasicStroke;
import java.awt.Polygon;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Arc2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Path2D;
import java.awt.geom.IllegalPathStateException;
import java.awt.geom.PathIterator;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;
import sun.java2d.SunGraphics2D;
import sun.java2d.loops.ProcessPath;
import static sun.java2d.pipe.BufferedOpCodes.*;
/**
* Base class for enqueuing rendering operations in a single-threaded
* rendering environment. Instead of each operation being rendered
* immediately by the underlying graphics library, the operation will be
* added to the provided RenderQueue, which will be processed at a later
* time by a single thread.
*
* This class provides implementations of drawLine(), drawRect(), drawPoly(),
* fillRect(), draw(Shape), and fill(Shape), which are useful for a
* hardware-accelerated renderer. The other draw*() and fill*() methods
* simply delegate to draw(Shape) and fill(Shape), respectively.
*/
public abstract class BufferedRenderPipe
implements PixelDrawPipe, PixelFillPipe, ShapeDrawPipe, ParallelogramPipe
{
ParallelogramPipe aapgrampipe = new AAParallelogramPipe();
static final int BYTES_PER_POLY_POINT = 8;
static final int BYTES_PER_SCANLINE = 12;
static final int BYTES_PER_SPAN = 16;
protected RenderQueue rq;
protected RenderBuffer buf;
private BufferedDrawHandler drawHandler;
public BufferedRenderPipe(RenderQueue rq) {
this.rq = rq;
this.buf = rq.getBuffer();
this.drawHandler = new BufferedDrawHandler();
}
public ParallelogramPipe getAAParallelogramPipe() {
return aapgrampipe;
}
/**
* Validates the state in the provided SunGraphics2D object and sets up
* any special resources for this operation (e.g. enabling gradient
* shading).
*/
protected abstract void validateContext(SunGraphics2D sg2d);
protected abstract void validateContextAA(SunGraphics2D sg2d);
public void drawLine(SunGraphics2D sg2d,
int x1, int y1, int x2, int y2)
{
int transx = sg2d.transX;
int transy = sg2d.transY;
rq.lock();
try {
validateContext(sg2d);
rq.ensureCapacity(20);
buf.putInt(DRAW_LINE);
buf.putInt(x1 + transx);
buf.putInt(y1 + transy);
buf.putInt(x2 + transx);
buf.putInt(y2 + transy);
} finally {
rq.unlock();
}
}
public void drawRect(SunGraphics2D sg2d,
int x, int y, int width, int height)
{
rq.lock();
try {
validateContext(sg2d);
rq.ensureCapacity(20);
buf.putInt(DRAW_RECT);
buf.putInt(x + sg2d.transX);
buf.putInt(y + sg2d.transY);
buf.putInt(width);
buf.putInt(height);
} finally {
rq.unlock();
}
}
public void fillRect(SunGraphics2D sg2d,
int x, int y, int width, int height)
{
rq.lock();
try {
validateContext(sg2d);
rq.ensureCapacity(20);
buf.putInt(FILL_RECT);
buf.putInt(x + sg2d.transX);
buf.putInt(y + sg2d.transY);
buf.putInt(width);
buf.putInt(height);
} finally {
rq.unlock();
}
}
public void drawRoundRect(SunGraphics2D sg2d,
int x, int y, int width, int height,
int arcWidth, int arcHeight)
{
draw(sg2d, new RoundRectangle2D.Float(x, y, width, height,
arcWidth, arcHeight));
}
public void fillRoundRect(SunGraphics2D sg2d,
int x, int y, int width, int height,
int arcWidth, int arcHeight)
{
fill(sg2d, new RoundRectangle2D.Float(x, y, width, height,
arcWidth, arcHeight));
}
public void drawOval(SunGraphics2D sg2d,
int x, int y, int width, int height)
{
draw(sg2d, new Ellipse2D.Float(x, y, width, height));
}
public void fillOval(SunGraphics2D sg2d,
int x, int y, int width, int height)
{
fill(sg2d, new Ellipse2D.Float(x, y, width, height));
}
public void drawArc(SunGraphics2D sg2d,
int x, int y, int width, int height,
int startAngle, int arcAngle)
{
draw(sg2d, new Arc2D.Float(x, y, width, height,
startAngle, arcAngle,
Arc2D.OPEN));
}
public void fillArc(SunGraphics2D sg2d,
int x, int y, int width, int height,
int startAngle, int arcAngle)
{
fill(sg2d, new Arc2D.Float(x, y, width, height,
startAngle, arcAngle,
Arc2D.PIE));
}
protected void drawPoly(final SunGraphics2D sg2d,
final int[] xPoints, final int[] yPoints,
final int nPoints, final boolean isClosed)
{
if (xPoints == null || yPoints == null) {
throw new NullPointerException("coordinate array");
}
if (xPoints.length < nPoints || yPoints.length < nPoints) {
throw new ArrayIndexOutOfBoundsException("coordinate array");
}
if (nPoints < 2) {
// render nothing
return;
} else if (nPoints == 2 && !isClosed) {
// render a simple line
drawLine(sg2d, xPoints[0], yPoints[0], xPoints[1], yPoints[1]);
return;
}
rq.lock();
try {
validateContext(sg2d);
int pointBytesRequired = nPoints * BYTES_PER_POLY_POINT;
int totalBytesRequired = 20 + pointBytesRequired;
if (totalBytesRequired <= buf.capacity()) {
if (totalBytesRequired > buf.remaining()) {
// process the queue first and then enqueue the points
rq.flushNow();
}
buf.putInt(DRAW_POLY);
// enqueue parameters
buf.putInt(nPoints);
buf.putInt(isClosed ? 1 : 0);
buf.putInt(sg2d.transX);
buf.putInt(sg2d.transY);
// enqueue the points
buf.put(xPoints, 0, nPoints);
buf.put(yPoints, 0, nPoints);
} else {
// queue is too small to accommodate all points; perform the
// operation directly on the queue flushing thread
rq.flushAndInvokeNow(new Runnable() {
public void run() {
drawPoly(xPoints, yPoints,
nPoints, isClosed,
sg2d.transX, sg2d.transY);
}
});
}
} finally {
rq.unlock();
}
}
protected abstract void drawPoly(int[] xPoints, int[] yPoints,
int nPoints, boolean isClosed,
int transX, int transY);
public void drawPolyline(SunGraphics2D sg2d,
int[] xPoints, int[] yPoints,
int nPoints)
{
drawPoly(sg2d, xPoints, yPoints, nPoints, false);
}
public void drawPolygon(SunGraphics2D sg2d,
int[] xPoints, int[] yPoints,
int nPoints)
{
drawPoly(sg2d, xPoints, yPoints, nPoints, true);
}
public void fillPolygon(SunGraphics2D sg2d,
int[] xPoints, int[] yPoints,
int nPoints)
{
fill(sg2d, new Polygon(xPoints, yPoints, nPoints));
}
private class BufferedDrawHandler
extends ProcessPath.DrawHandler
{
BufferedDrawHandler() {
// these are bogus values; the caller will use validate()
// to ensure that they are set properly prior to each usage
super(0, 0, 0, 0);
}
/**
* This method needs to be called prior to each draw/fillPath()
* operation to ensure the clip bounds are up to date.
*/
void validate(SunGraphics2D sg2d) {
Region clip = sg2d.getCompClip();
setBounds(clip.getLoX(), clip.getLoY(),
clip.getHiX(), clip.getHiY(),
sg2d.strokeHint);
}
/**
* drawPath() support...
*/
public void drawLine(int x1, int y1, int x2, int y2) {
// assert rq.lock.isHeldByCurrentThread();
rq.ensureCapacity(20);
buf.putInt(DRAW_LINE);
buf.putInt(x1);
buf.putInt(y1);
buf.putInt(x2);
buf.putInt(y2);
}
public void drawPixel(int x, int y) {
// assert rq.lock.isHeldByCurrentThread();
rq.ensureCapacity(12);
buf.putInt(DRAW_PIXEL);
buf.putInt(x);
buf.putInt(y);
}
/**
* fillPath() support...
*/
private int scanlineCount;
private int scanlineCountIndex;
private int remainingScanlines;
private void resetFillPath() {
buf.putInt(DRAW_SCANLINES);
scanlineCountIndex = buf.position();
buf.putInt(0);
scanlineCount = 0;
remainingScanlines = buf.remaining() / BYTES_PER_SCANLINE;
}
private void updateScanlineCount() {
buf.putInt(scanlineCountIndex, scanlineCount);
}
/**
* Called from fillPath() to indicate that we are about to
* start issuing drawScanline() calls.
*/
public void startFillPath() {
rq.ensureCapacity(20); // to ensure room for at least a scanline
resetFillPath();
}
public void drawScanline(int x1, int x2, int y) {
if (remainingScanlines == 0) {
updateScanlineCount();
rq.flushNow();
resetFillPath();
}
buf.putInt(x1);
buf.putInt(x2);
buf.putInt(y);
scanlineCount++;
remainingScanlines--;
}
/**
* Called from fillPath() to indicate that we are done
* issuing drawScanline() calls.
*/
public void endFillPath() {
updateScanlineCount();
}
}
protected void drawPath(SunGraphics2D sg2d,
Path2D.Float p2df, int transx, int transy)
{
rq.lock();
try {
validateContext(sg2d);
drawHandler.validate(sg2d);
ProcessPath.drawPath(drawHandler, p2df, transx, transy);
} finally {
rq.unlock();
}
}
protected void fillPath(SunGraphics2D sg2d,
Path2D.Float p2df, int transx, int transy)
{
rq.lock();
try {
validateContext(sg2d);
drawHandler.validate(sg2d);
drawHandler.startFillPath();
ProcessPath.fillPath(drawHandler, p2df, transx, transy);
drawHandler.endFillPath();
} finally {
rq.unlock();
}
}
private native int fillSpans(RenderQueue rq, long buf,
int pos, int limit,
SpanIterator si, long iterator,
int transx, int transy);
protected void fillSpans(SunGraphics2D sg2d, SpanIterator si,
int transx, int transy)
{
rq.lock();
try {
validateContext(sg2d);
rq.ensureCapacity(24); // so that we have room for at least a span
int newpos = fillSpans(rq, buf.getAddress(),
buf.position(), buf.capacity(),
si, si.getNativeIterator(),
transx, transy);
buf.position(newpos);
} finally {
rq.unlock();
}
}
public void fillParallelogram(SunGraphics2D sg2d,
double ux1, double uy1,
double ux2, double uy2,
double x, double y,
double dx1, double dy1,
double dx2, double dy2)
{
rq.lock();
try {
validateContext(sg2d);
rq.ensureCapacity(28);
buf.putInt(FILL_PARALLELOGRAM);
buf.putFloat((float) x);
buf.putFloat((float) y);
buf.putFloat((float) dx1);
buf.putFloat((float) dy1);
buf.putFloat((float) dx2);
buf.putFloat((float) dy2);
} finally {
rq.unlock();
}
}
public void drawParallelogram(SunGraphics2D sg2d,
double ux1, double uy1,
double ux2, double uy2,
double x, double y,
double dx1, double dy1,
double dx2, double dy2,
double lw1, double lw2)
{
rq.lock();
try {
validateContext(sg2d);
rq.ensureCapacity(36);
buf.putInt(DRAW_PARALLELOGRAM);
buf.putFloat((float) x);
buf.putFloat((float) y);
buf.putFloat((float) dx1);
buf.putFloat((float) dy1);
buf.putFloat((float) dx2);
buf.putFloat((float) dy2);
buf.putFloat((float) lw1);
buf.putFloat((float) lw2);
} finally {
rq.unlock();
}
}
private class AAParallelogramPipe implements ParallelogramPipe {
public void fillParallelogram(SunGraphics2D sg2d,
double ux1, double uy1,
double ux2, double uy2,
double x, double y,
double dx1, double dy1,
double dx2, double dy2)
{
rq.lock();
try {
validateContextAA(sg2d);
rq.ensureCapacity(28);
buf.putInt(FILL_AAPARALLELOGRAM);
buf.putFloat((float) x);
buf.putFloat((float) y);
buf.putFloat((float) dx1);
buf.putFloat((float) dy1);
buf.putFloat((float) dx2);
buf.putFloat((float) dy2);
} finally {
rq.unlock();
}
}
public void drawParallelogram(SunGraphics2D sg2d,
double ux1, double uy1,
double ux2, double uy2,
double x, double y,
double dx1, double dy1,
double dx2, double dy2,
double lw1, double lw2)
{
rq.lock();
try {
validateContextAA(sg2d);
rq.ensureCapacity(36);
buf.putInt(DRAW_AAPARALLELOGRAM);
buf.putFloat((float) x);
buf.putFloat((float) y);
buf.putFloat((float) dx1);
buf.putFloat((float) dy1);
buf.putFloat((float) dx2);
buf.putFloat((float) dy2);
buf.putFloat((float) lw1);
buf.putFloat((float) lw2);
} finally {
rq.unlock();
}
}
}
public void draw(SunGraphics2D sg2d, Shape s) {
if (sg2d.strokeState == sg2d.STROKE_THIN) {
if (s instanceof Polygon) {
if (sg2d.transformState < sg2d.TRANSFORM_TRANSLATESCALE) {
Polygon p = (Polygon)s;
drawPolygon(sg2d, p.xpoints, p.ypoints, p.npoints);
return;
}
}
Path2D.Float p2df;
int transx, transy;
if (sg2d.transformState <= sg2d.TRANSFORM_INT_TRANSLATE) {
if (s instanceof Path2D.Float) {
p2df = (Path2D.Float)s;
} else {
p2df = new Path2D.Float(s);
}
transx = sg2d.transX;
transy = sg2d.transY;
} else {
p2df = new Path2D.Float(s, sg2d.transform);
transx = 0;
transy = 0;
}
drawPath(sg2d, p2df, transx, transy);
} else if (sg2d.strokeState < sg2d.STROKE_CUSTOM) {
ShapeSpanIterator si = LoopPipe.getStrokeSpans(sg2d, s);
try {
fillSpans(sg2d, si, 0, 0);
} finally {
si.dispose();
}
} else {
fill(sg2d, sg2d.stroke.createStrokedShape(s));
}
}
public void fill(SunGraphics2D sg2d, Shape s) {
int transx, transy;
if (sg2d.strokeState == sg2d.STROKE_THIN) {
// Here we are able to use fillPath() for
// high-quality fills.
Path2D.Float p2df;
if (sg2d.transformState <= sg2d.TRANSFORM_INT_TRANSLATE) {
if (s instanceof Path2D.Float) {
p2df = (Path2D.Float)s;
} else {
p2df = new Path2D.Float(s);
}
transx = sg2d.transX;
transy = sg2d.transY;
} else {
p2df = new Path2D.Float(s, sg2d.transform);
transx = 0;
transy = 0;
}
fillPath(sg2d, p2df, transx, transy);
return;
}
AffineTransform at;
if (sg2d.transformState <= sg2d.TRANSFORM_INT_TRANSLATE) {
// Transform (translation) will be done by FillSpans (we could
// delegate to fillPolygon() here, but most hardware accelerated
// libraries cannot handle non-convex polygons, so we will use
// the FillSpans approach by default)
at = null;
transx = sg2d.transX;
transy = sg2d.transY;
} else {
// Transform will be done by the PathIterator
at = sg2d.transform;
transx = transy = 0;
}
ShapeSpanIterator ssi = LoopPipe.getFillSSI(sg2d);
try {
// Subtract transx/y from the SSI clip to match the
// (potentially untranslated) geometry fed to it
Region clip = sg2d.getCompClip();
ssi.setOutputAreaXYXY(clip.getLoX() - transx,
clip.getLoY() - transy,
clip.getHiX() - transx,
clip.getHiY() - transy);
ssi.appendPath(s.getPathIterator(at));
fillSpans(sg2d, ssi, transx, transy);
} finally {
ssi.dispose();
}
}
}
| gpl-2.0 |
AlanGuerraQuispe/SisAtuxPerfumeria | atux-jrcp/src/main/java/com/aw/core/report/RptPdfDataSection.java | 6113 | package com.aw.core.report;
import com.aw.core.report.custom.RptField;
import com.aw.core.report.custom.RptRenderer;
import com.aw.core.view.IColumnInfo;
import org.springframework.util.StringUtils;
import java.util.List;
/**
* User: JCM
* Date: 20/11/2007
*/
public class RptPdfDataSection extends RptDataSectionImpl {
protected void loadBuffer(RptRenderer.PgInfo pgInfo, LineGroup header, LineGroup data) throws Exception {
List<IColumnInfo> cols = getCustomColumnInfo() ;
int colsCharsSize[] = new int[cols.size()];
// Calcular headers
///////////////////
int colWidthSum = 0;
int fixedSizeColsSum = 0;
for (IColumnInfo col : cols) {
if (col.getReportCharsSize()!=-1)
fixedSizeColsSum += col.getReportCharsSize();
else
colWidthSum += col.getWidth();
}
if (fixedSizeColsSum>0){
// use fixed cols width
fixedSizeColsSum += (cols.size() -1);// add separator spaces
int fixedSizeColsRemaining = pgInfo.getColumnWidth() -fixedSizeColsSum;
for (int i = 0; i < cols.size(); i++) {
IColumnInfo col = cols.get(i);
int colWidth = (int) (1.0* col.getWidth() * fixedSizeColsRemaining / colWidthSum);
colsCharsSize[i] = col.getReportCharsSize()==-1?colWidth:col.getReportCharsSize();
}
}else{
// additional width used to place single spaces between fields
double addditionalWidth = (cols.size() -1)* pgInfo.getColumnCharWidth(colWidthSum);
colWidthSum += addditionalWidth;
for (int i = 0; i < cols.size(); i++) {
IColumnInfo col = cols.get(i);
int colWidth = pgInfo.translateX(col.getWidth(), colWidthSum);
colsCharsSize[i] = colWidth;
}
}
// Imprimir headers
///////////////////
int printedLines = 0;
if (titulo!=null){
header.writeX(RptField.b("BC"+pgInfo.getColumnWidth(), titulo ));
header.writeln();
printedLines++;
}
for (int i = 0; i < cols.size(); i++) {
if (i>0) header.writeX(RptField.fillLine(' ',1)); //separator
IColumnInfo col = cols.get(i);
String text = col.getPdfColumnHeader();
if (!StringUtils.hasText(text)){
text = col.getColumnHeader();
}
header.writeX(RptField.b("BC"+colsCharsSize[i], text ));
}
header.writeln();
printedLines++;
// for (int i = 0; i < cols.size(); i++) {
// if (i>0) header.writeX(RptField.fillLine(' ',1)); //separator
// IColumnInfo col = cols.get(i);
// header.writeX(RptField.fillLine('=', colsCharsSize[i]));
// //renderer.writeBold(FillerFormat.fill("", '=', colsCharsSize[i], FillerFormat.ALG_LEFT));
// }
// header.writeln();
// printedLines++;
List values = getCustomValues();
for (int i = valuesPrinted; i < values.size() /*&& printedLines < maxLines*/; i++) {
Object row = values.get(i);
for (int j = 0; j < cols.size(); j++) {
IColumnInfo col = cols.get(j);
if (j>0) data.writeX(RptField.fillLine(' ',1)); //separator
Object colValue = col.getValueDDRFormated(row, j);
String text = colValue == null ? "" : colValue.toString();
int width = colsCharsSize[j];
char alig= 'L';
if (col.getAlignment() == IColumnInfo.LEFT)
alig= 'L';//text = renderer.left(text, width);
else if (col.getAlignment() == IColumnInfo.CENTER)
alig= 'C';//text = renderer.center(text, width);
else if (col.getAlignment() == IColumnInfo.RIGHT)
alig= 'R';//text = renderer.right(text, width);
data.writeX( RptField.b("N"+alig+width, text ) );
}
data.writeln();
printedLines++;
valuesPrinted++;
}
//boolean rowsPrinted = valuesPrinted >= values.size();
// include summary
//boolean summaryPrintedIfNecessary = summaryRow==null;
//if (rowsPrinted && printedLines < maxLines && summaryRow!=null){
// summaryPrintedIfNecessary = true;
if (summaryRow!=null){
for (int j = 0; j < cols.size(); j++) {
if (j>0) data.writeX(RptField.fillLine(' ',1)); //separator
IColumnInfo col = cols.get(j);
ColFunction colFunction = summaryRow.get(j);
Object colValue = colFunction==null?null:colFunction.getValue(cols, j, values);
String text = colValue == null ? "" : colValue.toString();
int width = colsCharsSize[j];
int alignment = colFunction!=null&& colFunction.isAlignmentOverride()
? colFunction.getOverrideAlignment() : col.getAlignment();
// if (alignment == ColumnInfo.LEFT)
// text = renderer.left(text, width);
// else if (alignment == ColumnInfo.CENTER)
// text = renderer.center(text, width);
// else if (alignment == ColumnInfo.RIGHT)
// text = renderer.right(text, width);
char alig= 'L';
if (col.getAlignment() == IColumnInfo.LEFT)
alig= 'L';//text = renderer.left(text, width);
else if (col.getAlignment() == IColumnInfo.CENTER)
alig= 'C';//text = renderer.center(text, width);
else if (col.getAlignment() == IColumnInfo.RIGHT)
alig= 'R';//text = renderer.right(text, width);
// renderer.writeBold(text);
data.writeX( RptField.b("B"+alig+width, text ) );
}
data.writeln();
printedLines++;
valuesPrinted++;
}
}
} | gpl-2.0 |
arodchen/MaxSim | maxine/com.oracle.max.tele.vm/src/com/sun/max/tele/debug/darwin/DarwinMachO.java | 17129 | /*
* Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.max.tele.debug.darwin;
import java.io.*;
import java.nio.*;
/**
* (Limited) Access to Mach_O 64-bit format files. See /usr/include/mach-o/*.h for source.
* Note that a file may (unusually) contain multiple binaries for different architectures,
* see /usr/include/mach-o/fat.h. Such a file is called a universal binary file, (cf an archive file).
*
*/
public class DarwinMachO {
/**
* Encapsulates whether the MachO file is embedded in a universal binary file.
*/
public static class MachORandomAccessFile extends RandomAccessFile {
/**
* If non-zero, offset to start of architecture-specific MachO file in FAT file.
*/
private int fatOffset;
private MachORandomAccessFile(String path) throws FileNotFoundException {
super(path, "r");
}
@Override
public void seek(long filePos) throws IOException {
super.seek(filePos + fatOffset);
}
@Override
public long getFilePointer() throws IOException {
long fp = super.getFilePointer();
return fp - fatOffset;
}
}
public final MachORandomAccessFile raf;
private Header header;
private LoadCommand[] loadCommands;
public DarwinMachO(String path) throws FileNotFoundException, IOException {
raf = new MachORandomAccessFile(path);
header = new Header();
}
private class FatArch {
final static int X86_64 = 0x01000007;
int cputype;
int cpusubtype;
int offset;
int size;
int align;
private FatArch() throws IOException {
cputype = raf.readInt();
cpusubtype = raf.readInt();
offset = raf.readInt();
size = raf.readInt();
align = raf.readInt();
}
}
public class Header {
private static final int FAT_MAGIC = 0xcafebabe;
public final int magic;
public final int cputype;
public final int cpusubtype;
public final int filetype;
public final int ncmds;
public final int sizeofcmds;
public final int flags;
public final int reserved;
private Header() throws IOException {
int magic = raf.readInt();
boolean found = false;
if (magic == FAT_MAGIC) {
// find our architecture subfile
int nFatArch = raf.readInt();
for (int i = 0; i < nFatArch; i++) {
FatArch fatArch = new FatArch();
if (fatArch.cputype == FatArch.X86_64) {
found = true;
raf.seek(fatArch.offset);
raf.fatOffset = fatArch.offset;
magic = readInt();
break;
}
}
assert found : "failed to find X86_64 architecture in MachO FAT file";
}
this.magic = magic;
cputype = readInt();
cpusubtype = readInt();
filetype = readInt();
ncmds = readInt();
sizeofcmds = readInt();
flags = readInt();
reserved = readInt();
}
}
public Header getHeader() throws IOException {
if (header == null) {
header = new Header();
}
return header;
}
/**
* Common base class for all Mach-O load command types.
*/
public class LoadCommand {
public static final int LC_SEGMENT_64 = 0x19;
public static final int LC_THREAD = 0x4;
public static final int LC_SYMTAB = 0x2;
public final int cmd;
public final int cmdsize;
protected LoadCommand() throws IOException {
this.cmd = readInt();
this.cmdsize = readInt();
}
public String typeName() {
switch (cmd) {
case LC_SEGMENT_64:
return "LC_SEGMENT_64";
case LC_THREAD:
return "LC_THREAD";
case LC_SYMTAB:
return "LC_SYMTAB";
default:
return "LC #" + cmd;
}
}
}
/**
* Reads a load command structure starting at the current file position, invoking
* the appropriate subclass {@code read} command, based on the {@code cmd} field.
* Leaves the file pointer at the next load command (if any).
*
* @return instance of the appropriate subclass for discovered command type
* @throws IOException
*/
private LoadCommand readNextLoadCommand() throws IOException {
LoadCommand result = null;
final long ptr = raf.getFilePointer();
final int cmd = readInt();
final int cmdsize = readInt();
raf.seek(ptr);
switch (cmd) {
case LoadCommand.LC_SEGMENT_64:
result = new Segment64LoadCommand();
break;
case LoadCommand.LC_THREAD:
result = new ThreadLoadCommand();
break;
case LoadCommand.LC_SYMTAB:
result = new SymTabLoadCommand();
break;
default:
result = new LoadCommand();
}
// skip over entire command
raf.seek(ptr + cmdsize);
return result;
}
public LoadCommand[] getLoadCommands() throws IOException {
if (loadCommands == null) {
getHeader();
loadCommands = new LoadCommand[header.ncmds];
for (int i = 0; i < header.ncmds; i++) {
loadCommands[i] = readNextLoadCommand();
}
}
return loadCommands;
}
public final class Segment64LoadCommand extends LoadCommand {
public final String segName;
public final long vmaddr;
public final long vmsize;
public final long fileoff;
public final long filesize;
public final int maxprot;
public final int initprot;
public final int nsects;
public final int flags;
public final Section64[] sections;
private Segment64LoadCommand() throws IOException {
final byte[] segname = new byte[16];
for (int i = 0; i < 16; i++) {
segname[i] = raf.readByte();
}
segName = new String(segname);
vmaddr = readLong();
vmsize = readLong();
fileoff = readLong();
filesize = readLong();
maxprot = readInt();
initprot = readInt();
nsects = readInt();
flags = readInt();
sections = new Section64[nsects];
for (int i = 0; i < nsects; i++) {
sections[i] = new Section64(this);
}
}
}
public class Section64 {
public final String sectname;
public final String segname;
public final long addr;
public final long size;
public final int offset;
public final int align;
public final int reloff;
public final int nreloc;
public final int flags;
public final int reserved1;
public final int reserved2;
public final int reserved3;
public final Segment64LoadCommand owningSegment;
private Section64(Segment64LoadCommand segment64) throws IOException {
owningSegment = segment64;
sectname = readName();
segname = readName();
addr = readLong();
size = readLong();
offset = readInt();
align = readInt();
reloff = readInt();
nreloc = readInt();
flags = readInt();
reserved1 = readInt();
reserved2 = readInt();
reserved3 = readInt();
}
private String readName() throws IOException {
byte[] nameBytes = new byte[16];
int length = 0;
for (int i = 0; i < nameBytes.length; i++) {
nameBytes[i] = raf.readByte();
if (nameBytes[i] != 0) {
length++;
}
}
return new String(nameBytes, 0, length);
}
public boolean isText() {
return segname.equals("__TEXT");
}
}
public class ThreadLoadCommand extends LoadCommand {
public final ThreadRegState regstate;
public final ThreadFPRegState fpregstate;
public final ThreadExceptionState exstate;
ThreadLoadCommand() throws IOException {
regstate = new ThreadRegState();
fpregstate = new ThreadFPRegState();
exstate = new ThreadExceptionState();
}
}
public class ThreadState {
public final int flavor;
public final int count;
protected ThreadState() throws IOException {
flavor = readInt();
count = readInt();
}
}
public class ThreadRegState extends ThreadState {
public final int tsh_flavor;
public final int tsh_count;
public final ByteBuffer regbytes; // we also store registers as a directly allocated ByteBuffer for passing to native code
public final long rax;
public final long rbx;
public final long rcx;
public final long rdx;
public final long rdi;
public final long rsi;
public final long rbp;
public final long rsp;
public final long r8;
public final long r9;
public final long r10;
public final long r11;
public final long r12;
public final long r13;
public final long r14;
public final long r15;
public final long rip;
public final long rflags;
public final long cs;
public final long fs;
public final long gs;
ThreadRegState() throws IOException {
tsh_flavor = readInt();
tsh_count = readInt();
final long ptr = raf.getFilePointer();
rax = readLong();
rbx = readLong();
rcx = readLong();
rdx = readLong();
rdi = readLong();
rsi = readLong();
rbp = readLong();
rsp = readLong();
r8 = readLong();
r9 = readLong();
r10 = readLong();
r11 = readLong();
r12 = readLong();
r13 = readLong();
r14 = readLong();
r15 = readLong();
rip = readLong();
rflags = readLong();
cs = readLong();
fs = readLong();
gs = readLong();
raf.seek(ptr);
// read and store again as byte array
regbytes = ByteBuffer.allocateDirect(tsh_count * 4);
for (int i = 0; i < tsh_count * 4; i++) {
regbytes.put(raf.readByte());
}
}
}
public class ThreadFPRegState extends ThreadState {
public final int fsh_flavor;
public final int fsh_count;
ByteBuffer regbytes; // way too complex for individual declarations; do it all via native code
ThreadFPRegState() throws IOException {
fsh_flavor = readInt();
fsh_count = readInt();
regbytes = ByteBuffer.allocateDirect(fsh_count * 4);
for (int i = 0; i < fsh_count * 4; i++) {
regbytes.put(raf.readByte());
}
}
}
public class ThreadExceptionState extends ThreadState {
public final int esh_flavor;
public final int esh_count;
public final int trapno;
public final int err;
public final long faultvaddr;
ThreadExceptionState() throws IOException {
super();
esh_flavor = readInt();
esh_count = readInt();
trapno = readInt();
err = readInt();
faultvaddr = readLong();
}
}
public class SymTabLoadCommand extends LoadCommand {
public final int symoff;
public final int nsyms;
public final int stroff;
public final int strsize;
/**
* Lazily created string table.
*/
private byte[] stringTable;
/**
* Lazily created symbol table.
*/
private NList64[] symbolTable;
SymTabLoadCommand() throws IOException {
super();
symoff = readInt();
nsyms = readInt();
stroff = readInt();
strsize = readInt();
}
public NList64[] getSymbolTable() throws IOException {
if (symbolTable != null) {
return symbolTable;
}
stringTable = new byte[strsize];
raf.seek(stroff);
for (int i = 0; i < strsize; i++) {
stringTable[i] = raf.readByte();
}
symbolTable = new NList64[nsyms];
raf.seek(symoff);
for (int i = 0; i < nsyms; i++) {
symbolTable[i] = new NList64();
}
return symbolTable;
}
public String getSymbolName(NList64 nlist64) {
String symbol = "";
if (nlist64.strx != 0) {
byte sb = stringTable[nlist64.strx];
int sl = 0;
while (sb != 0) {
sb = stringTable[nlist64.strx + sl];
sl++;
}
// remove leading/trailing underscores which bracket all symbols
symbol = new String(stringTable, nlist64.strx + 1, sl - 2);
}
return symbol;
}
}
public class NList64 {
public static final int STAB = 0xe0;
public static final int PEXT = 0x10;
public static final int TYPE = 0xe;
public static final int EXT = 0x1;
public static final int UNDF = 0x0;
public static final int ABS = 0x2;
public static final int SECT = 0xe;
public static final int PBUD = 0xc;
public static final int INDR = 0xa;
public final int strx;
public final byte type;
public final byte sect;
public final short desc;
public final long value;
NList64() throws IOException {
strx = readInt();
type = raf.readByte();
sect = raf.readByte();
desc = readShort();
value = readLong();
}
}
/**
* Locates a given section within a given array of load commands.
* Sections are numbered from 1 as they occur within SEGMENT_64 commands.
* @param loadCommands
* @param sectToFind
*/
public static Section64 getSection(LoadCommand[] loadCommands, int sectToFind) {
int sect = 1;
for (int i = 0; i < loadCommands.length; i++) {
if (loadCommands[i].cmd == LoadCommand.LC_SEGMENT_64) {
Segment64LoadCommand slc = (Segment64LoadCommand) loadCommands[i];
if (sectToFind < sect + slc.nsects) {
return slc.sections[sectToFind - sect];
}
sect += slc.nsects;
}
}
return null;
}
public short readShort() throws IOException {
final int b1 = raf.read();
final int b2 = raf.read();
return (short) (((b2 << 8) | b1) & 0xFFFF);
}
public int readInt() throws IOException {
final int b1 = raf.read();
final int b2 = raf.read();
final int b3 = raf.read();
final int b4 = raf.read();
return (b4 << 24) | (b3 << 16) | (b2 << 8) | b1;
}
public long readLong() throws IOException {
final long lw = readInt();
final long hw = readInt();
return hw << 32 | (lw & 0xFFFFFFFFL);
}
}
| gpl-2.0 |
mbshopM/openconcerto | OpenConcerto/src/koala/dynamicjava/tree/OrExpression.java | 2774 | /*
* DynamicJava - Copyright (C) 1999 Dyade
*
* 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 DYADE 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.
*
* Except as contained in this notice, the name of Dyade shall not be used in advertising or
* otherwise to promote the sale, use or other dealings in this Software without prior written
* authorization from Dyade.
*/
package koala.dynamicjava.tree;
import koala.dynamicjava.tree.visitor.Visitor;
/**
* This class represents the or expression nodes of the syntax tree
*
* @author Stephane Hillion
* @version 1.0 - 1999/04/26
*/
public class OrExpression extends BinaryExpression {
/**
* Initializes the expression
*
* @param lexp the LHS expression
* @param rexp the RHS expression
* @exception IllegalArgumentException if lexp is null or rexp is null
*/
public OrExpression(final Expression lexp, final Expression rexp) {
this(lexp, rexp, null, 0, 0, 0, 0);
}
/**
* Initializes the expression
*
* @param lexp the LHS expression
* @param rexp the RHS expression
* @param fn the filename
* @param bl the begin line
* @param bc the begin column
* @param el the end line
* @param ec the end column
* @exception IllegalArgumentException if lexp is null or rexp is null
*/
public OrExpression(final Expression lexp, final Expression rexp, final String fn, final int bl, final int bc, final int el, final int ec) {
super(lexp, rexp, fn, bl, bc, el, ec);
}
/**
* Allows a visitor to traverse the tree
*
* @param visitor the visitor to accept
*/
@Override
public Object acceptVisitor(final Visitor visitor) {
return visitor.visit(this);
}
}
| gpl-3.0 |
0359xiaodong/twidere | src/twitter4j/internal/json/TranslationResultJSONImpl.java | 3161 | package twitter4j.internal.json;
import static twitter4j.internal.util.InternalParseUtil.getLong;
import static twitter4j.internal.util.InternalParseUtil.getRawString;
import static twitter4j.internal.util.InternalParseUtil.getUnescapedString;
import org.json.JSONObject;
import twitter4j.TranslationResult;
import twitter4j.TwitterException;
import twitter4j.conf.Configuration;
import twitter4j.http.HttpResponse;
public class TranslationResultJSONImpl extends TwitterResponseImpl implements TranslationResult {
private static final long serialVersionUID = 2923323223626332587L;
private long id;
private String lang;
private String translatedLang;
private String translationType;
private String text;
/* package */TranslationResultJSONImpl(final HttpResponse res, final Configuration conf) throws TwitterException {
super(res);
final JSONObject json = res.asJSONObject();
init(json);
}
/* package */TranslationResultJSONImpl(final JSONObject json) throws TwitterException {
super();
init(json);
}
@Override
public boolean equals(final Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (!(obj instanceof TranslationResultJSONImpl)) return false;
final TranslationResultJSONImpl other = (TranslationResultJSONImpl) obj;
if (id != other.id) return false;
if (lang == null) {
if (other.lang != null) return false;
} else if (!lang.equals(other.lang)) return false;
if (text == null) {
if (other.text != null) return false;
} else if (!text.equals(other.text)) return false;
if (translatedLang == null) {
if (other.translatedLang != null) return false;
} else if (!translatedLang.equals(other.translatedLang)) return false;
if (translationType == null) {
if (other.translationType != null) return false;
} else if (!translationType.equals(other.translationType)) return false;
return true;
}
@Override
public long getId() {
return id;
}
@Override
public String getLang() {
return lang;
}
@Override
public String getText() {
return text;
}
@Override
public String getTranslatedLong() {
return translatedLang;
}
@Override
public String getTranslationType() {
return translationType;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (id ^ id >>> 32);
result = prime * result + (lang == null ? 0 : lang.hashCode());
result = prime * result + (text == null ? 0 : text.hashCode());
result = prime * result + (translatedLang == null ? 0 : translatedLang.hashCode());
result = prime * result + (translationType == null ? 0 : translationType.hashCode());
return result;
}
@Override
public String toString() {
return "TranslationResultJSONImpl{id=" + id + ", lang=" + lang + ", translatedLang=" + translatedLang
+ ", translationType=" + translationType + ", text=" + text + "}";
}
private void init(final JSONObject json) {
id = getLong("id", json);
lang = getRawString("lang", json);
translatedLang = getRawString("translated_lang", json);
translationType = getRawString("translation_type", json);
text = getUnescapedString("text", json);
}
}
| gpl-3.0 |
marksreeves/wcomponents | wcomponents-core/src/test/java/com/github/bordertech/wcomponents/WButton_Test.java | 25128 | package com.github.bordertech.wcomponents;
import com.github.bordertech.wcomponents.WButton.ImagePosition;
import com.github.bordertech.wcomponents.util.mock.MockRequest;
import java.io.Serializable;
import junit.framework.Assert;
import org.junit.Test;
/**
* Unit tests for {@link WButton}.
*
* @author Ming Gao
* @since 1.0.0
*/
public class WButton_Test extends AbstractWComponentTestCase {
private static final String SHARED_VALUE = "shared value";
private static final String USER_VALUE = "user value";
private static final String SHARED_TEXT = "shared text";
private static final String USER_TEXT = "user text";
private static final String BEAN_VALUE = "bean value";
@Test
public void testConstructors() {
final String text = "WButton_Test.testConstructors";
final char accessKey = 'W';
WButton button = new WButton(text);
Assert.assertEquals("Incorrect button text", text, button.getText());
Assert.assertNull("Accesskey should not be set", button.getAccessKeyAsString());
button = new WButton(text, accessKey);
Assert.assertEquals("Incorrect button text", text, button.getText());
Assert.assertEquals("Incorrect access key returned", accessKey, button.getAccessKey());
}
@Test
public void testAccessKeyHandling() {
String buttonText = "ABCDE abcde";
WButton button = new WButton(buttonText);
button.setAccessKey('E');
// reset shared button text. Access key should be automatically reset.
button.setText("Test");
// override tool tip.
String myToolTip = "My ToolTip";
button.setToolTip(myToolTip);
Assert.assertEquals("Unexpected ToolTip text", myToolTip, button.getToolTip());
}
@Test
public void testSetPressed() {
WButton button = new WButton("Test");
button.setLocked(true);
setActiveContext(createUIContext());
button.setPressed(true, new MockRequest());
Assert.assertTrue("Button should be pressed", button.isPressed());
Assert.assertFalse("Button should not be in default state", button.isDefaultState());
button.setPressed(false, new MockRequest());
Assert.assertFalse("Button should be pressed", button.isPressed());
button.setDisabled(true);
button.setPressed(true, new MockRequest());
Assert.assertTrue("Button should be disabled", button.isDisabled());
Assert.assertFalse("Button should be pressed when disabled", button.isPressed());
}
@Test
public void testActionSetPressed() {
WButton button = new WButton("Test");
button.setLocked(true);
UIContext uic = createUIContext();
setActiveContext(uic);
uic.setUI(button);
TestAction testAction = new TestAction();
testAction.reset();
button.setAction(testAction);
button.setPressed(true, new MockRequest());
Assert.assertEquals("Button was not pressed", true, button.isPressed());
}
@Test
public void testSetActionCommand() {
String text = "WButton_Test.text";
String sharedValue = "WButton_Test.sharedValue";
String value = "WButton_Test.value";
UIContext uic1 = new UIContextImpl();
WButton button = new WButton(text);
button.setLocked(true);
Assert.assertEquals("Default action command should be button text", text, button.
getActionCommand());
button.setActionCommand(sharedValue);
Assert.assertEquals("Incorrect shared action command returned", sharedValue, button.
getActionCommand());
setActiveContext(uic1);
button.setActionCommand(value);
Assert.assertEquals("Uic 1 action command should be returned for uic 1", value, button.
getActionCommand());
Assert.
assertFalse("Button should not be in default state for uic1", button.
isDefaultState());
resetContext();
Assert.assertEquals("Incorrect shared action command returned", sharedValue, button.
getActionCommand());
}
@Test
public void testSetActionObject() {
Serializable actionObject = "testSetActionObject.actionObject1";
WButton button = new WButton();
button.setLocked(true);
setActiveContext(createUIContext());
button.setActionObject(actionObject);
Assert.assertSame("Incorrect action object", actionObject, button.getActionObject());
resetContext();
Assert.assertNull("Action object should be null by default", button.getActionObject());
}
@Test
public void testSetImageUrl() {
WButton button = new WButton();
button.setLocked(true);
String imageUrl = "http://127.0.0.1/image.jpg";
setActiveContext(createUIContext());
button.setImageUrl(imageUrl);
button.setLocked(true);
Assert.assertEquals("Uic 1 image url should be returned for uic 1", imageUrl, button.
getImageUrl());
Assert.
assertFalse("Button should not be in default state for uic1", button.
isDefaultState());
resetContext();
Assert.assertNull("Default image url should be null", button.getImageUrl());
}
@Test
public void testSetImagePosition() {
WButton button = new WButton();
button.setLocked(true);
setActiveContext(createUIContext());
button.setImagePosition(ImagePosition.EAST);
button.setLocked(true);
Assert.assertEquals("Uic 1 image position should be returned for uic 1", ImagePosition.EAST,
button.getImagePosition());
Assert.
assertFalse("Button should not be in default state for uic1", button.
isDefaultState());
resetContext();
Assert.assertNull("Default image position should be null", button.getImagePosition());
}
@Test
public void testPopupTrigger() {
WButton button = new WButton("Test");
button.setLocked(true);
setActiveContext(createUIContext());
Assert.assertFalse("Should not be a popup trigger by default", button.isPopupTrigger());
button.setPopupTrigger(true);
Assert.assertTrue("Button should be a popup trigger", button.isPopupTrigger());
resetContext();
Assert.assertFalse("Default popup trigger status should not have changed", button.
isPopupTrigger());
}
@Test
public void testGetText() {
Assert.assertNull("Incorrect text for button with nothing",
getButtonText(false, false, false, false, false, false));
Assert.assertEquals("Incorrect text for button with Shared text",
SHARED_TEXT,
getButtonText(true, false, false, false, false, false));
Assert.assertEquals("Incorrect text for button with User text",
USER_TEXT,
getButtonText(false, true, false, false, false, false));
Assert.assertEquals("Incorrect text for button with User + shared text",
USER_TEXT,
getButtonText(true, true, false, false, false, false));
Assert.assertEquals("Incorrect text for button with Shared value only",
SHARED_VALUE,
getButtonText(false, false, true, false, false, false));
Assert.assertEquals("Incorrect text for button with Shared text, shared value",
SHARED_TEXT,
getButtonText(true, false, true, false, false, false));
Assert.assertEquals("Incorrect text for button with User text, shared value",
USER_TEXT,
getButtonText(false, true, true, false, false, false));
Assert.assertEquals("Incorrect text for button with Shared + user text, shared value",
USER_TEXT,
getButtonText(true, true, true, false, false, false));
Assert.assertEquals("Incorrect text for button with User value only",
USER_VALUE,
getButtonText(false, false, false, true, false, false));
Assert.assertEquals("Incorrect text for button with Shared text, user value",
SHARED_TEXT,
getButtonText(true, false, false, true, false, false));
Assert.assertEquals("Incorrect text for button with User text, user value",
USER_TEXT,
getButtonText(false, true, false, true, false, false));
Assert.assertEquals("Incorrect text for button with Shared + user text, user value",
USER_TEXT,
getButtonText(true, true, false, true, false, false));
Assert.assertEquals("Incorrect text for button with Shared + user value",
USER_VALUE,
getButtonText(false, false, true, true, false, false));
Assert.assertEquals("Incorrect text for button with Shared text, shared + user value",
SHARED_TEXT,
getButtonText(true, false, true, true, false, false));
Assert.assertEquals("Incorrect text for button with User text, shared + user value",
USER_TEXT,
getButtonText(false, true, true, true, false, false));
Assert.
assertEquals(
"Incorrect text for button with Shared + user text, shared + user value",
USER_TEXT,
getButtonText(true, true, true, true, false, false));
Assert.assertNull("Incorrect text for button with null bean only",
getButtonText(false, false, false, false, true, true));
Assert.assertEquals("Incorrect text for button with null bean, Shared text",
SHARED_TEXT,
getButtonText(true, false, false, false, true, true));
Assert.assertEquals("Incorrect text for button with null bean, User text",
USER_TEXT,
getButtonText(false, true, false, false, true, true));
Assert.assertEquals("Incorrect text for button with null bean, User + shared text",
USER_TEXT,
getButtonText(true, true, false, false, true, true));
Assert.assertEquals("Incorrect text for button with null bean, Shared value only",
SHARED_VALUE,
getButtonText(false, false, true, false, true, true));
Assert.assertEquals("Incorrect text for button with null bean, Shared text, shared value",
SHARED_TEXT,
getButtonText(true, false, true, false, true, true));
Assert.assertEquals("Incorrect text for button with null bean, User text, shared value",
USER_TEXT,
getButtonText(false, true, true, false, true, true));
Assert.assertEquals(
"Incorrect text for button with null bean, Shared + user text, shared value",
USER_TEXT,
getButtonText(true, true, true, false, true, true));
Assert.assertEquals("Incorrect text for button with null bean, User value only",
USER_VALUE,
getButtonText(false, false, false, true, true, true));
Assert.assertEquals("Incorrect text for button with null bean, Shared text, user value",
SHARED_TEXT,
getButtonText(true, false, false, true, true, true));
Assert.assertEquals("Incorrect text for button with null bean, User text, user value",
USER_TEXT,
getButtonText(false, true, false, true, true, true));
Assert.assertEquals(
"Incorrect text for button with null bean, Shared + user text, user value",
USER_TEXT,
getButtonText(true, true, false, true, true, true));
Assert.assertEquals("Incorrect text for button with null bean, Shared + user value",
USER_VALUE,
getButtonText(false, false, true, true, true, true));
Assert.assertEquals(
"Incorrect text for button with null bean, Shared text, shared + user value",
SHARED_TEXT,
getButtonText(true, false, true, true, true, true));
Assert.assertEquals(
"Incorrect text for button with null bean, User text, shared + user value",
USER_TEXT,
getButtonText(false, true, true, true, true, true));
Assert.assertEquals(
"Incorrect text for button with null bean, Shared + user text, shared + user value",
USER_TEXT,
getButtonText(true, true, true, true, true, true));
Assert.assertEquals("Incorrect text for button with Bean only",
BEAN_VALUE,
getButtonText(false, false, false, false, true, false));
Assert.assertEquals("Incorrect text for button with bean, Shared text",
SHARED_TEXT,
getButtonText(true, false, false, false, true, false));
Assert.assertEquals("Incorrect text for button with bean, User text",
USER_TEXT,
getButtonText(false, true, false, false, true, false));
Assert.assertEquals("Incorrect text for button with bean, User + shared text",
USER_TEXT,
getButtonText(true, true, false, false, true, false));
Assert.assertEquals("Incorrect text for button with bean, Shared value only",
BEAN_VALUE,
getButtonText(false, false, true, false, true, false));
Assert.assertEquals("Incorrect text for button with bean, Shared text, shared value",
SHARED_TEXT,
getButtonText(true, false, true, false, true, false));
Assert.assertEquals("Incorrect text for button with bean, User text, shared value",
USER_TEXT,
getButtonText(false, true, true, false, true, false));
Assert.assertEquals("Incorrect text for button with bean, Shared + user text, shared value",
USER_TEXT,
getButtonText(true, true, true, false, true, false));
Assert.assertEquals("Incorrect text for button with bean, User value only",
USER_VALUE,
getButtonText(false, false, false, true, true, false));
Assert.assertEquals("Incorrect text for button with bean, Shared text, user value",
SHARED_TEXT,
getButtonText(true, false, false, true, true, false));
Assert.assertEquals("Incorrect text for button with bean, User text, user value",
USER_TEXT,
getButtonText(false, true, false, true, true, false));
Assert.assertEquals("Incorrect text for button with bean, Shared + user text, user value",
USER_TEXT,
getButtonText(true, true, false, true, true, false));
Assert.assertEquals("Incorrect text for button with bean, Shared + user value",
USER_VALUE,
getButtonText(false, false, true, true, true, false));
Assert.assertEquals("Incorrect text for button with bean, Shared text, shared + user value",
SHARED_TEXT,
getButtonText(true, false, true, true, true, false));
Assert.assertEquals("Incorrect text for button with bean, User text, shared + user value",
USER_TEXT,
getButtonText(false, true, true, true, true, false));
Assert.assertEquals(
"Incorrect text for button with bean, Shared + user text, shared + user value",
USER_TEXT,
getButtonText(true, true, true, true, true, false));
}
@Test
public void testGetValue() {
Assert.assertEquals("Incorrect value for button with nothing",
WButton.NO_VALUE,
getButtonValue(false, false, false, false, false, false));
Assert.assertEquals("Incorrect value for button with Shared text",
SHARED_TEXT,
getButtonValue(true, false, false, false, false, false));
Assert.assertEquals("Incorrect value for button with User text",
USER_TEXT,
getButtonValue(false, true, false, false, false, false));
Assert.assertEquals("Incorrect value for button with User + shared text",
USER_TEXT,
getButtonValue(true, true, false, false, false, false));
Assert.assertEquals("Incorrect value for button with Shared value only",
SHARED_VALUE,
getButtonValue(false, false, true, false, false, false));
Assert.assertEquals("Incorrect value for button with Shared text, shared value",
SHARED_VALUE,
getButtonValue(true, false, true, false, false, false));
Assert.assertEquals("Incorrect value for button with User text, shared value",
SHARED_VALUE,
getButtonValue(false, true, true, false, false, false));
Assert.assertEquals("Incorrect value for button with Shared + user text, shared value",
SHARED_VALUE,
getButtonValue(true, true, true, false, false, false));
Assert.assertEquals("Incorrect value for button with User value only",
USER_VALUE,
getButtonValue(false, false, false, true, false, false));
Assert.assertEquals("Incorrect value for button with Shared text, user value",
USER_VALUE,
getButtonValue(true, false, false, true, false, false));
Assert.assertEquals("Incorrect value for button with User text, user value",
USER_VALUE,
getButtonValue(false, true, false, true, false, false));
Assert.assertEquals("Incorrect value for button with Shared + user text, user value",
USER_VALUE,
getButtonValue(true, true, false, true, false, false));
Assert.assertEquals("Incorrect value for button with Shared + user value",
USER_VALUE,
getButtonValue(false, false, true, true, false, false));
Assert.assertEquals("Incorrect value for button with Shared text, shared + user value",
USER_VALUE,
getButtonValue(true, false, true, true, false, false));
Assert.assertEquals("Incorrect value for button with User text, shared + user value",
USER_VALUE,
getButtonValue(false, true, true, true, false, false));
Assert.assertEquals(
"Incorrect value for button with Shared + user text, shared + user value",
USER_VALUE,
getButtonValue(true, true, true, true, false, false));
Assert.assertEquals("Incorrect value for button with null bean only",
WButton.NO_VALUE,
getButtonValue(false, false, false, false, true, true));
Assert.assertEquals("Incorrect value for button with null bean, Shared text",
SHARED_TEXT,
getButtonValue(true, false, false, false, true, true));
Assert.assertEquals("Incorrect value for button with null bean, User text",
USER_TEXT,
getButtonValue(false, true, false, false, true, true));
Assert.assertEquals("Incorrect value for button with null bean, User + shared text",
USER_TEXT,
getButtonValue(true, true, false, false, true, true));
Assert.assertEquals("Incorrect value for button with null bean, Shared value only",
SHARED_VALUE,
getButtonValue(false, false, true, false, true, true));
Assert.assertEquals("Incorrect value for button with null bean, Shared text, shared value",
SHARED_VALUE,
getButtonValue(true, false, true, false, true, true));
Assert.assertEquals("Incorrect value for button with null bean, User text, shared value",
SHARED_VALUE,
getButtonValue(false, true, true, false, true, true));
Assert.assertEquals(
"Incorrect value for button with null bean, Shared + user text, shared value",
SHARED_VALUE,
getButtonValue(true, true, true, false, true, true));
Assert.assertEquals("Incorrect value for button with null bean, User value only",
USER_VALUE,
getButtonValue(false, false, false, true, true, true));
Assert.assertEquals("Incorrect value for button with null bean, Shared text, user value",
USER_VALUE,
getButtonValue(true, false, false, true, true, true));
Assert.assertEquals("Incorrect value for button with null bean, User text, user value",
USER_VALUE,
getButtonValue(false, true, false, true, true, true));
Assert.assertEquals(
"Incorrect value for button with null bean, Shared + user text, user value",
USER_VALUE,
getButtonValue(true, true, false, true, true, true));
Assert.assertEquals("Incorrect value for button with null bean, Shared + user value",
USER_VALUE,
getButtonValue(false, false, true, true, true, true));
Assert.assertEquals(
"Incorrect value for button with null bean, Shared text, shared + user value",
USER_VALUE,
getButtonValue(true, false, true, true, true, true));
Assert.assertEquals(
"Incorrect value for button with null bean, User text, shared + user value",
USER_VALUE,
getButtonValue(false, true, true, true, true, true));
Assert.assertEquals(
"Incorrect value for button with null bean, Shared + user text, shared + user value",
USER_VALUE,
getButtonValue(true, true, true, true, true, true));
Assert.assertEquals("Incorrect value for button with Bean only",
BEAN_VALUE,
getButtonValue(false, false, false, false, true, false));
Assert.assertEquals("Incorrect value for button with bean, Shared text",
BEAN_VALUE,
getButtonValue(true, false, false, false, true, false));
Assert.assertEquals("Incorrect value for button with bean, User text",
BEAN_VALUE,
getButtonValue(false, true, false, false, true, false));
Assert.assertEquals("Incorrect value for button with bean, User + shared text",
BEAN_VALUE,
getButtonValue(true, true, false, false, true, false));
Assert.assertEquals("Incorrect value for button with bean, Shared value only",
BEAN_VALUE,
getButtonValue(false, false, true, false, true, false));
Assert.assertEquals("Incorrect value for button with bean, Shared text, shared value",
BEAN_VALUE,
getButtonValue(true, false, true, false, true, false));
Assert.assertEquals("Incorrect value for button with bean, User text, shared value",
BEAN_VALUE,
getButtonValue(false, true, true, false, true, false));
Assert.
assertEquals(
"Incorrect value for button with bean, Shared + user text, shared value",
BEAN_VALUE,
getButtonValue(true, true, true, false, true, false));
Assert.assertEquals("Incorrect value for button with bean, User value only",
USER_VALUE,
getButtonValue(false, false, false, true, true, false));
Assert.assertEquals("Incorrect value for button with bean, Shared text, user value",
USER_VALUE,
getButtonValue(true, false, false, true, true, false));
Assert.assertEquals("Incorrect value for button with bean, User text, user value",
USER_VALUE,
getButtonValue(false, true, false, true, true, false));
Assert.assertEquals("Incorrect value for button with bean, Shared + user text, user value",
USER_VALUE,
getButtonValue(true, true, false, true, true, false));
Assert.assertEquals("Incorrect value for button with bean, Shared + user value",
USER_VALUE,
getButtonValue(false, false, true, true, true, false));
Assert.
assertEquals(
"Incorrect value for button with bean, Shared text, shared + user value",
USER_VALUE,
getButtonValue(true, false, true, true, true, false));
Assert.assertEquals("Incorrect value for button with bean, User text, shared + user value",
USER_VALUE,
getButtonValue(false, true, true, true, true, false));
Assert.assertEquals(
"Incorrect value for button with bean, Shared + user text, shared + user value",
USER_VALUE,
getButtonValue(true, true, true, true, true, false));
}
@Test
public void testClientCommandOnlyAccessors() {
assertAccessorsCorrect(new WButton("client"), "clientCommandOnly", false, true, false);
}
/**
* Returns the text for a button created with the given data.
*
* @param useSharedText true if the button should have shared text
* @param useUserText true if the button should have user text
* @param useSharedValue true if the button should have a shared value
* @param useUserValue true if the button should have a user value
* @param useBeanValue true if the button should have a bean provider
* @param nullBean true if the provided bean should be null
*
* @return the button text that will be displayed to the user.
*/
private String getButtonText(final boolean useSharedText, final boolean useUserText,
final boolean useSharedValue, final boolean useUserValue,
final boolean useBeanValue, final boolean nullBean) {
WButton button = createButton(useSharedText, useUserText, useSharedValue, useUserValue,
useBeanValue, nullBean);
setActiveContext(createUIContext());
try {
button.preparePaintComponent(new MockRequest());
return button.getText();
} finally {
UIContextHolder.reset();
}
}
/**
* Returns the value for a button created with the given data.
*
* @param useSharedText true if the button should have shared text
* @param useUserText true if the button should have user text
* @param useSharedValue true if the button should have a shared value
* @param useUserValue true if the button should have a user value
* @param useBeanValue true if the button should have a bean provider
* @param nullBean true if the provided bean should be null
*
* @return the button value will be used for a user.
*/
private String getButtonValue(final boolean useSharedText, final boolean useUserText,
final boolean useSharedValue, final boolean useUserValue,
final boolean useBeanValue, final boolean nullBean) {
WButton button = createButton(useSharedText, useUserText, useSharedValue, useUserValue,
useBeanValue, nullBean);
setActiveContext(createUIContext());
try {
button.preparePaintComponent(new MockRequest());
return button.getValue();
} finally {
UIContextHolder.reset();
}
}
/**
* Creates a button configured to have the given data.
*
* @param useSharedText true if the button should have shared text
* @param useUserText true if the button should have user text
* @param useSharedValue true if the button should have a shared value
* @param useUserValue true if the button should have a user value
* @param useBeanValue true if the button should have a bean provider
* @param nullBean true if the provided bean should be null
*
* @return the button.
*/
private WButton createButton(final boolean useSharedText, final boolean useUserText,
final boolean useSharedValue, final boolean useUserValue,
final boolean useBeanValue, final boolean nullBean) {
final WButton button = new WButton() {
@Override
protected void preparePaintComponent(final Request request) {
if (!isInitialised()) {
if (useUserValue) {
setValue(USER_VALUE);
}
if (useUserText) {
setText(USER_TEXT);
}
setInitialised(true);
}
super.preparePaintComponent(request);
}
};
if (useSharedText) {
button.setText(SHARED_TEXT);
}
if (useSharedValue) {
button.setValue(SHARED_VALUE);
}
if (useBeanValue) {
button.setBeanProvider(new BeanProvider() {
@Override
public Object getBean(final BeanProviderBound beanProviderBound) {
return nullBean ? null : BEAN_VALUE;
}
});
}
return button;
}
}
| gpl-3.0 |
nishanttotla/predator | cpachecker/src/org/sosy_lab/cpachecker/pcc/propertychecker/NoTargetStateChecker.java | 1567 | /*
* CPAchecker is a tool for configurable software verification.
* This file is part of CPAchecker.
*
* Copyright (C) 2007-2014 Dirk Beyer
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* CPAchecker web page:
* http://cpachecker.sosy-lab.org
*/
package org.sosy_lab.cpachecker.pcc.propertychecker;
import org.sosy_lab.cpachecker.core.interfaces.AbstractState;
import org.sosy_lab.cpachecker.core.interfaces.Targetable;
/**
* Implementation of a property checker which does not accept abstract states representing some kind of "target" or
* "error" abstract state. Accepts every abstract state which is not a target abstract state and every set of
* states which does not contain a target abstract state.
*/
public class NoTargetStateChecker extends PerElementPropertyChecker {
@Override
public boolean satisfiesProperty(AbstractState pElemToCheck) throws UnsupportedOperationException {
return (!(pElemToCheck instanceof Targetable) || !((Targetable) pElemToCheck).isTarget());
}
}
| gpl-3.0 |
AthenaEventEngine/AthenaCore | src/main/java/com/github/athenaengine/core/model/template/SkillTemplate.java | 1485 | package com.github.athenaengine.core.model.template;
public class SkillTemplate {
private int mId;
private int mLevel;
private boolean mIsDebuff;
private boolean mIsDamage;
public int getId() {
return mId;
}
private void setId(int id) {
mId = id;
}
public int getLevel() {
return mLevel;
}
private void setLevel(int level) {
mLevel = level;
}
public boolean isDebuff() {
return mIsDebuff;
}
private void setIsDebuff(boolean isDebuff) {
mIsDebuff = isDebuff;
}
public boolean isDamage() {
return mIsDamage;
}
private void setIsDamage(boolean isDamage) {
mIsDamage = isDamage;
}
public static class Builder {
private final SkillTemplate mSkill = new SkillTemplate();
public static Builder newInstance() {
return new Builder();
}
public Builder setId(int id) {
mSkill.setId(id);
return this;
}
public Builder setLevel(int level) {
mSkill.setLevel(level);
return this;
}
public Builder setIsDamage(boolean value) {
mSkill.setIsDamage(value);
return this;
}
public Builder setIsDebuff(boolean value) {
mSkill.setIsDebuff(value);
return this;
}
public SkillTemplate build() {
return mSkill;
}
}
}
| gpl-3.0 |
thewisecity/declarehome-android | app/src/main/java/com/wisecityllc/cookedapp/views/ExtendedEditText.java | 1922 | package com.wisecityllc.cookedapp.views;
import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import com.wisecityllc.cookedapp.App;
/**
* This class overrides the onKeyPreIme method to dispatch a key event if the
* KeyEvent passed to onKeyPreIme has a key code of KeyEvent.KEYCODE_BACK.
* This allows key event listeners to detect that the soft keyboard was
* dismissed.
*
*/
public class ExtendedEditText extends EditText {
private OnBackButtonPressedWhileHasFocusListener mListener;
public ExtendedEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public ExtendedEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ExtendedEditText(Context context) {
super(context);
}
@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
if (hasFocus() && event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
// User has pressed Back key. So hide the keyboard InputMethodManager
InputMethodManager mgr = (InputMethodManager) App.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(this.getWindowToken(), 0);
// TODO: Hide your view as you do it in your activity
//dispatchKeyEvent(event);
if(mListener != null)
mListener.pressedBackWithFocus();
return true;
}
return super.onKeyPreIme(keyCode, event);
}
public void setListener(OnBackButtonPressedWhileHasFocusListener listener){
mListener = listener;
}
public interface OnBackButtonPressedWhileHasFocusListener {
public void pressedBackWithFocus();
}
} | gpl-3.0 |
steve111MV/Mosungi | Android/app/src/main/java/com/fongwama/mosungi/ui/adapter/SpinnerAdapter.java | 2157 | package com.fongwama.mosungi.ui.adapter;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
import com.fongwama.mosungi.R;
import com.fongwama.mosungi.model.Patient;
/**
* Created by Karl on 28/07/2016.
*/
public class SpinnerAdapter extends BaseAdapter{
Context context;
List<Patient> listPatient;
LayoutInflater layoutInflater;
private int lastPosition = -1;
public SpinnerAdapter(Context context, List<Patient> listPatient) {
this.context = context;
this.listPatient = listPatient;
layoutInflater = layoutInflater.from(context);
}
public void setListPatient(List<Patient> list)
{
if(list!=null)
this.listPatient = list;
}
@Override
public int getCount() {
return listPatient.size();
}
@Override
public Object getItem(int position) {
return listPatient.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
static class ViewHolder
{
TextView id;
TextView nomPrenom;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null)
{
convertView = layoutInflater.inflate(R.layout.item_spinner, null);
holder = new ViewHolder();
//initialisation des vues
holder.id = (TextView) convertView.findViewById(R.id.id_item);
holder.nomPrenom = (TextView) convertView.findViewById(R.id.nom_prenom_item);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
}
Patient patient = listPatient.get(position);
holder.id.setText(patient.getIdPatient());
holder.nomPrenom.setText(patient.getNom()+" "+patient.getPrenom());
lastPosition = position;
return convertView;
}
}
| gpl-3.0 |
saulhidalgoaular/luas-pos | src-pos/com/openbravo/pos/sales/shared/JTicketsBagShared.java | 8820 | // Openbravo POS is a point of sales application designed for touch screens.
// Copyright (C) 2007-2009 Openbravo, S.L.
// http://www.openbravo.com/product/pos
//
// This file is part of Openbravo POS.
//
// Openbravo POS 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.
//
// Openbravo POS 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 Openbravo POS. If not, see <http://www.gnu.org/licenses/>.
package com.openbravo.pos.sales.shared;
import com.openbravo.pos.ticket.TicketInfo;
import java.util.*;
import javax.swing.*;
import com.openbravo.basic.BasicException;
import com.openbravo.data.gui.MessageInf;
import com.openbravo.pos.sales.*;
import com.openbravo.pos.forms.*;
public class JTicketsBagShared extends JTicketsBag {
private String m_sCurrentTicket = null;
private DataLogicReceipts dlReceipts = null;
/** Creates new form JTicketsBagShared */
public JTicketsBagShared(AppView app, TicketsEditor panelticket) {
super(app, panelticket);
dlReceipts = (DataLogicReceipts) app.getBean("com.openbravo.pos.sales.DataLogicReceipts");
initComponents();
}
public void activate() {
// precondicion es que no tenemos ticket activado ni ticket en el panel
m_sCurrentTicket = null;
selectValidTicket();
// Authorization
m_jDelTicket.setEnabled(m_App.getAppUserView().getUser().hasPermission("com.openbravo.pos.sales.JPanelTicketEdits"));
// postcondicion es que tenemos ticket activado aqui y ticket en el panel
}
public boolean deactivate() {
// precondicion es que tenemos ticket activado aqui y ticket en el panel
saveCurrentTicket();
m_sCurrentTicket = null;
m_panelticket.setActiveTicket(null, null);
return true;
// postcondicion es que no tenemos ticket activado ni ticket en el panel
}
public void deleteTicket() {
m_sCurrentTicket = null;
selectValidTicket();
}
protected JComponent getBagComponent() {
return this;
}
protected JComponent getNullComponent() {
return new JPanel();
}
private void saveCurrentTicket() {
// save current ticket, if exists,
if (m_sCurrentTicket != null) {
try {
dlReceipts.insertSharedTicket(m_sCurrentTicket, m_panelticket.getActiveTicket());
} catch (BasicException e) {
new MessageInf(e).show(this);
}
}
}
private void setActiveTicket(String id) throws BasicException{
// BEGIN TRANSACTION
TicketInfo ticket = dlReceipts.getSharedTicket(id);
if (ticket == null) {
// Does not exists ???
throw new BasicException(AppLocal.getIntString("message.noticket"));
} else {
dlReceipts.deleteSharedTicket(id);
m_sCurrentTicket = id;
m_panelticket.setActiveTicket(ticket, null);
}
// END TRANSACTION
}
private void selectValidTicket() {
try {
List<SharedTicketInfo> l = dlReceipts.getSharedTicketList();
if (l.size() == 0) {
newTicket();
} else {
setActiveTicket(l.get(0).getId());
}
} catch (BasicException e) {
new MessageInf(e).show(this);
newTicket();
}
}
private void newTicket() {
saveCurrentTicket();
TicketInfo ticket = new TicketInfo();
m_sCurrentTicket = UUID.randomUUID().toString(); // m_fmtid.format(ticket.getId());
m_panelticket.setActiveTicket(ticket, null);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
m_jNewTicket = new javax.swing.JButton();
m_jDelTicket = new javax.swing.JButton();
m_jListTickets = new javax.swing.JButton();
setLayout(new java.awt.BorderLayout());
m_jNewTicket.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/editnew.png")));
m_jNewTicket.setFocusPainted(false);
m_jNewTicket.setFocusable(false);
m_jNewTicket.setMargin(new java.awt.Insets(8, 14, 8, 14));
m_jNewTicket.setRequestFocusEnabled(false);
m_jNewTicket.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
m_jNewTicketActionPerformed(evt);
}
});
jPanel1.add(m_jNewTicket);
m_jDelTicket.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/editdelete.png")));
m_jDelTicket.setFocusPainted(false);
m_jDelTicket.setFocusable(false);
m_jDelTicket.setMargin(new java.awt.Insets(8, 14, 8, 14));
m_jDelTicket.setRequestFocusEnabled(false);
m_jDelTicket.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
m_jDelTicketActionPerformed(evt);
}
});
jPanel1.add(m_jDelTicket);
m_jListTickets.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/unsortedList.png")));
m_jListTickets.setFocusPainted(false);
m_jListTickets.setFocusable(false);
m_jListTickets.setMargin(new java.awt.Insets(8, 14, 8, 14));
m_jListTickets.setRequestFocusEnabled(false);
m_jListTickets.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
m_jListTicketsActionPerformed(evt);
}
});
jPanel1.add(m_jListTickets);
add(jPanel1, java.awt.BorderLayout.WEST);
}// </editor-fold>//GEN-END:initComponents
private void m_jListTicketsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_jListTicketsActionPerformed
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
List<SharedTicketInfo> l = dlReceipts.getSharedTicketList();
JTicketsBagSharedList listDialog = JTicketsBagSharedList.newJDialog(JTicketsBagShared.this);
String id = listDialog.showTicketsList(l);
if (id != null) {
saveCurrentTicket();
setActiveTicket(id);
}
} catch (BasicException e) {
new MessageInf(e).show(JTicketsBagShared.this);
newTicket();
}
}
});
}//GEN-LAST:event_m_jListTicketsActionPerformed
private void m_jDelTicketActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_jDelTicketActionPerformed
int res = JOptionPane.showConfirmDialog(this, AppLocal.getIntString("message.wannadelete"), AppLocal.getIntString("title.editor"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (res == JOptionPane.YES_OPTION) {
deleteTicket();
}
}//GEN-LAST:event_m_jDelTicketActionPerformed
private void m_jNewTicketActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_jNewTicketActionPerformed
newTicket();
}//GEN-LAST:event_m_jNewTicketActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel jPanel1;
private javax.swing.JButton m_jDelTicket;
private javax.swing.JButton m_jListTickets;
private javax.swing.JButton m_jNewTicket;
// End of variables declaration//GEN-END:variables
}
| gpl-3.0 |
zeydbilal/AITJevisPrivate | src/main/java/org/jevis/jeconfig/plugin/object/CopyObjectDialog.java | 13214 | /**
* Copyright (C) 2014 Envidatec GmbH <info@envidatec.com>
*
* This file is part of JEApplication.
*
* JEApplication 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 in version 3.
*
* JEApplication 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
* JEApplication. If not, see <http://www.gnu.org/licenses/>.
*
* JEApplication is part of the OpenJEVis project, further project information
* are published at <http://www.OpenJEVis.org/>.
*/
package org.jevis.jeconfig.plugin.object;
import java.math.BigDecimal;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.geometry.VPos;
import javafx.scene.Cursor;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.Separator;
import javafx.scene.control.TextField;
import javafx.scene.control.Toggle;
import javafx.scene.control.ToggleGroup;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import org.jevis.api.JEVisClass;
import org.jevis.api.JEVisException;
import org.jevis.api.JEVisObject;
import org.jevis.application.resource.ResourceLoader;
import org.jevis.commons.CommonClasses;
import org.jevis.jeconfig.tool.NumberSpinner;
/**
*
* @author fs
*/
public class CopyObjectDialog {
public static String ICON = "1403555565_stock_folder-move.png";
private JEVisClass createClass;
private String infoText = "";
private TextField nameField = new TextField();
private int createCount = 1;
final Button ok = new Button("OK");
final RadioButton move = new RadioButton("Move");
final RadioButton link = new RadioButton("Link");
final RadioButton copy = new RadioButton("Copy");
final RadioButton clone = new RadioButton("Clone");
public static enum Response {
MOVE, LINK, CANCEL, CLONE, COPY
};
private Response response = Response.CANCEL;
public JEVisClass getCreateClass() {
return createClass;
}
public String getCreateName() {
return nameField.getText();
}
public int getCreateCount() {
if (createCount > 0 && createCount < 100) {
return createCount;
} else {
return 1;
}
}
/**
*
* @param owner
* @param object
* @param newParent
* @param fixClass
* @param objName
* @return
*/
public Response show(Stage owner, final JEVisObject object, final JEVisObject newParent) {
final Stage stage = new Stage();
final BooleanProperty isOK = new SimpleBooleanProperty(false);
stage.setTitle("Move/Link Object");
stage.initModality(Modality.APPLICATION_MODAL);
stage.initOwner(owner);
// BorderPane root = new BorderPane();
VBox root = new VBox();
Scene scene = new Scene(root);
stage.setScene(scene);
stage.setWidth(450);
stage.setHeight(350);
stage.initStyle(StageStyle.UTILITY);
stage.setResizable(false);
scene.setCursor(Cursor.DEFAULT);
BorderPane header = new BorderPane();
header.setStyle("-fx-background-color: linear-gradient(#e2e2e2,#eeeeee);");
header.setPadding(new Insets(10, 10, 10, 10));
Label topTitle = new Label("Choose Action");
topTitle.setTextFill(Color.web("#0076a3"));
topTitle.setFont(Font.font("Cambria", 25));
ImageView imageView = ResourceLoader.getImage(ICON, 64, 64);
stage.getIcons().add(imageView.getImage());
VBox vboxLeft = new VBox();
VBox vboxRight = new VBox();
vboxLeft.getChildren().add(topTitle);
vboxLeft.setAlignment(Pos.CENTER_LEFT);
vboxRight.setAlignment(Pos.CENTER_LEFT);
vboxRight.getChildren().add(imageView);
header.setLeft(vboxLeft);
header.setRight(vboxRight);
HBox buttonPanel = new HBox();
ok.setDefaultButton(true);
ok.setDisable(true);
Button cancel = new Button("Cancel");
cancel.setCancelButton(true);
buttonPanel.getChildren().addAll(ok, cancel);
buttonPanel.setAlignment(Pos.CENTER_RIGHT);
buttonPanel.setPadding(new Insets(10, 10, 10, 10));
buttonPanel.setSpacing(10);
buttonPanel.setMaxHeight(25);
GridPane gp = new GridPane();
gp.setPadding(new Insets(10));
gp.setHgap(10);
gp.setVgap(5);
final ToggleGroup group = new ToggleGroup();
move.setMaxWidth(Double.MAX_VALUE);
move.setMinWidth(120);
link.setMaxWidth(Double.MAX_VALUE);
copy.setMaxWidth(Double.MAX_VALUE);
clone.setMaxWidth(Double.MAX_VALUE);
link.setToggleGroup(group);
move.setToggleGroup(group);
copy.setToggleGroup(group);
clone.setToggleGroup(group);
nameField.setPromptText("Name of the new object(s)");
final Label nameLabel = new Label("Name:");
final Label countLabel = new Label("Count:");
final NumberSpinner count = new NumberSpinner(BigDecimal.valueOf(1), BigDecimal.valueOf(1));
final Label info = new Label("Test");
info.wrapTextProperty().setValue(true);
// info.setPrefRowCount(4);
// info.setDisable(true);
info.setMinWidth(1d);
// info.setMaxWidth(200);
// info.setPrefWidth(200);
group.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
@Override
public void changed(ObservableValue<? extends Toggle> ov, Toggle t, Toggle t1) {
if (t1 != null) {
System.out.println("new toggel: " + t1);
if (t1.equals(move)) {
infoText = String.format("Move '%s' into '%s'", object.getName(), newParent.getName());
ok.setDisable(false);
nameField.setDisable(true);
nameLabel.setDisable(true);
countLabel.setDisable(true);
count.setDisable(true);
} else if (t1.equals(link)) {
infoText = String.format("Create an new link of '%s' into '%s'", object.getName(), newParent.getName());
nameField.setDisable(false);
count.setDisable(true);
nameLabel.setDisable(false);
countLabel.setDisable(true);
checkName();
} else if (t1.equals(copy)) {
infoText = String.format("Copy '%s' into '%s' without data", object.getName(), newParent.getName());
// infoText = String.format("<html>Copy <font color=\"#DB6A6A\">'%s'</font> into <font color=\"#DB6A6A\">'%s'</font> without data</html>", object.getName(), newParent.getName());
nameField.setDisable(false);
count.setDisable(false);
nameLabel.setDisable(false);
countLabel.setDisable(false);
nameField.setText("Copy of " + object.getName());
checkName();
} else if (t1.equals(clone)) {
infoText = String.format("Clone '%s' into '%s' with all data", object.getName(), newParent.getName());
nameField.setDisable(false);
count.setDisable(false);
nameLabel.setDisable(false);
countLabel.setDisable(false);
nameField.setText("Copy of " + object.getName());
checkName();
}
Platform.runLater(new Runnable() {
@Override
public void run() {
info.setText(infoText);
}
});
}
}
});
try {
System.out.println("-> Object: " + object.getJEVisClass());
System.out.println("newParent: " + newParent.getJEVisClass());
System.out.println("Is allowed under target: " + object.isAllowedUnder(newParent));
System.out.println("");
if (newParent.getJEVisClass().getName().equals("View Directory") || newParent.getJEVisClass().getName().equals(CommonClasses.LINK.NAME)) {
link.setDisable(false);
} else {
link.setDisable(true);
}
if (object.isAllowedUnder(newParent)) {
move.setDisable(false);
copy.setDisable(false);
clone.setDisable(false);
} else {
move.setDisable(true);
copy.setDisable(true);
clone.setDisable(true);
}
if (!link.isDisable()) {
group.selectToggle(link);
nameField.setText(object.getName());
ok.setDisable(false);
} else if (!move.isDisable()) {
group.selectToggle(move);
}
} catch (JEVisException ex) {
Logger.getLogger(CopyObjectDialog.class.getName()).log(Level.SEVERE, null, ex);
}
HBox nameBox = new HBox(5);
nameBox.getChildren().setAll(nameLabel, nameField);
nameBox.setAlignment(Pos.CENTER_LEFT);
HBox countBox = new HBox(5);
countBox.getChildren().setAll(countLabel, count);
countBox.setAlignment(Pos.CENTER_LEFT);
Separator s1 = new Separator(Orientation.HORIZONTAL);
GridPane.setMargin(s1, new Insets(5, 0, 10, 0));
//check allowed
int x = 0;
gp.add(link, 0, x);
gp.add(move, 0, ++x);
gp.add(copy, 0, ++x);
gp.add(clone, 0, ++x);
gp.add(new Separator(Orientation.VERTICAL), 1, 0, 1, 4);
gp.add(s1, 0, ++x, 3, 1);
gp.add(nameBox, 0, ++x, 3, 1);
gp.add(countBox, 0, ++x, 3, 1);
gp.add(info, 2, 0, 1, 4);
GridPane.setHgrow(info, Priority.ALWAYS);
GridPane.setVgrow(info, Priority.ALWAYS);
GridPane.setHalignment(info, HPos.LEFT);
GridPane.setValignment(info, VPos.TOP);
Separator sep = new Separator(Orientation.HORIZONTAL);
sep.setMinHeight(10);
root.getChildren().addAll(header, new Separator(Orientation.HORIZONTAL), gp, buttonPanel);
VBox.setVgrow(gp, Priority.ALWAYS);
VBox.setVgrow(buttonPanel, Priority.NEVER);
VBox.setVgrow(header, Priority.NEVER);
ok.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
stage.close();
if (group.getSelectedToggle().equals(move)) {
response = Response.MOVE;
} else if (group.getSelectedToggle().equals(link)) {
response = Response.LINK;
} else if (group.getSelectedToggle().equals(copy)) {
response = Response.COPY;
} else if (group.getSelectedToggle().equals(clone)) {
response = Response.CLONE;
}
}
});
cancel.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
stage.close();
response = Response.CANCEL;
}
});
nameField.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent t) {
if (nameField.getText() != null && !nameField.getText().equals("")) {
ok.setDisable(false);
}
}
});
stage.showAndWait();
return response;
}
private void checkName() {
if (nameField.getText() != null && !nameField.getText().isEmpty()) {
ok.setDisable(false);
} else {
ok.setDisable(true);
}
}
}
| gpl-3.0 |
ecemandirac/FlightTracker | Local Storage Module/src/java/generated/CustomerType.java | 2946 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.01.12 at 11:00:29 AM EET
//
package generated;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for customerType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="customerType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="id" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="contactInfo" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "customerType", propOrder = {
"id",
"name",
"contactInfo"
})
public class CustomerType {
@XmlElement(required = true)
protected String id;
@XmlElement(required = true)
protected String name;
@XmlElement(required = true)
protected String contactInfo;
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the contactInfo property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getContactInfo() {
return contactInfo;
}
/**
* Sets the value of the contactInfo property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setContactInfo(String value) {
this.contactInfo = value;
}
}
| gpl-3.0 |
benkonrath/gwt-glom | src/test/java/org/glom/web/client/place/GwtTestReportPlace.java | 2212 | package org.glom.web.client.place;
import static org.junit.Assert.*;
import org.junit.Test;
import com.googlecode.gwt.test.GwtModule;
import com.googlecode.gwt.test.GwtTest;
@GwtModule("org.glom.web.OnlineGlom")
public class GwtTestReportPlace extends GwtTest {
public GwtTestReportPlace() {
}
@Test
public void testGetPlaceNoParameters() {
checkTokenWithoutParameters("");
checkTokenWithoutParameters("something");
checkTokenWithoutParameters("list:a=1");
checkTokenWithoutParameters("value1=123");
}
@Test
public void testGetPlaceParameters() {
// Create a ReportPlace, testing getPlace():
final String documentId = "somedocument";
final String tableName = "sometable";
final String reportName = "somereport";
ReportPlace place = getReportPlaceFromToken("document=" + documentId + "&table=" + tableName + "&report=" + reportName);
checkParameters(place, documentId, tableName, reportName);
// Recreate it, testing getToken(),
// checking that the same parameters are read back:
final ReportPlace.Tokenizer tokenizer = new ReportPlace.Tokenizer();
final String token = tokenizer.getToken(place);
place = getReportPlaceFromToken(token);
checkParameters(place, documentId, tableName, reportName);
}
private void checkParameters(final ReportPlace place, final String documentID, final String tableName, final String reportName) {
assertTrue(place != null);
assertEquals(documentID, place.getDocumentID());
assertEquals(tableName, place.getTableName());
assertEquals(reportName, place.getReportName());
}
private ReportPlace getReportPlaceFromToken(final String token) {
final ReportPlace.Tokenizer tokenizer = new ReportPlace.Tokenizer();
final ReportPlace place = tokenizer.getPlace(token);
assertTrue(place != null);
return place;
}
private void checkTokenWithoutParameters(final String token) {
final ReportPlace place = getReportPlaceFromToken(token);
assertTrue(place.getDocumentID() != null);
assertTrue(place.getDocumentID().isEmpty());
assertTrue(place.getTableName() != null);
assertTrue(place.getTableName().isEmpty());
assertTrue(place.getReportName() != null);
assertTrue(place.getReportName().isEmpty());
}
}
| gpl-3.0 |
jackyzonewen/tomahawk-android | src/org/tomahawk/libtomahawk/hatchet/TrackInfo.java | 2564 | /* == This file is part of Tomahawk Player - <http://tomahawk-player.org> ===
*
* Copyright 2013, Enno Gottschalk <mrmaffen@googlemail.com>
*
* Tomahawk 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.
*
* Tomahawk 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 Tomahawk. If not, see <http://www.gnu.org/licenses/>.
*/
package org.tomahawk.libtomahawk.hatchet;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
/**
* Author Enno Gottschalk <mrmaffen@googlemail.com> Date: 20.04.13
*/
public class TrackInfo implements Info {
private final static String TAG = TrackInfo.class.getName();
public static final String TRACKINFO_KEY_ARTIST = "Artist";
public static final String TRACKINFO_KEY_ID = "Id";
public static final String TRACKINFO_KEY_NAME = "Name";
public static final String TRACKINFO_KEY_URL = "Url";
private ArtistInfo mArtist;
private String mId;
private String mName;
private String mUrl;
@Override
public void parseInfo(JSONObject rawInfo) {
try {
if (!rawInfo.isNull(TRACKINFO_KEY_ARTIST)) {
JSONObject rawArtistInfo = rawInfo.getJSONObject(TRACKINFO_KEY_ARTIST);
mArtist = new ArtistInfo();
mArtist.parseInfo(rawArtistInfo);
}
if (!rawInfo.isNull(TRACKINFO_KEY_ID)) {
mId = rawInfo.getString(TRACKINFO_KEY_ID);
}
if (!rawInfo.isNull(TRACKINFO_KEY_NAME)) {
mName = rawInfo.getString(TRACKINFO_KEY_NAME);
}
if (!rawInfo.isNull(TRACKINFO_KEY_URL)) {
mUrl = rawInfo.getString(TRACKINFO_KEY_URL);
}
} catch (JSONException e) {
Log.e(TAG, "parseInfo: " + e.getClass() + ": " + e.getLocalizedMessage());
}
}
public ArtistInfo getArtist() {
return mArtist;
}
public String getId() {
return mId;
}
public String getName() {
return mName;
}
public String getUrl() {
return mUrl;
}
}
| gpl-3.0 |
Free-Software-for-Android/AdAway | app/src/main/java/org/adaway/util/RegexUtils.java | 4483 | /*
* Copyright (C) 2011-2012 Dominik Schürmann <dominik@dominikschuermann.de>
*
* This file is part of AdAway.
*
* AdAway 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.
*
* AdAway 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 AdAway. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.adaway.util;
import com.google.common.net.InetAddresses;
import com.google.common.net.InternetDomainName;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import timber.log.Timber;
public class RegexUtils {
private static final Pattern WILDCARD_PATTERN = Pattern.compile("[*?]");
/**
* Check whether a hostname is valid.
*
* @param hostname The hostname to validate.
* @return return {@code true} if hostname is valid, {@code false} otherwise.
*/
public static boolean isValidHostname(String hostname) {
return InternetDomainName.isValid(hostname);
}
/**
* Check whether a wildcard hostname is valid.
* Wildcard hostname is an hostname with one of the following wildcard:
* <ul>
* <li>{@code *} for any character sequence,</li>
* <li>{@code ?} for any character</li>
* </ul>
* <p/>
* Wildcard validation is quite tricky, because wildcards can be placed anywhere and can match with
* anything. To make sure we don't dismiss certain valid wildcard host names, we trim wildcards
* or replace them with an alphanumeric character for further validation.<br/>
* We only reject whitelist host names which cannot match against valid host names under any circumstances.
*
* @param hostname The wildcard hostname to validate.
* @return return {@code true} if wildcard hostname is valid, {@code false} otherwise.
*/
public static boolean isValidWildcardHostname(String hostname) {
// Clear wildcards from host name then validate it
Matcher matcher = WILDCARD_PATTERN.matcher(hostname);
String clearedHostname = matcher.replaceAll("");
// Replace wildcards from host name by an alphanumeric character
String replacedHostname = matcher.replaceAll("a");
// Check if any hostname is valid
return isValidHostname(clearedHostname) || isValidHostname(replacedHostname);
}
/**
* Check if an IP address is valid.
*
* @param ip The IP to validate.
* @return {@code true} if the IP is valid, {@code false} otherwise.
*/
public static boolean isValidIP(String ip) {
try {
InetAddresses.forString(ip);
return true;
} catch (IllegalArgumentException exception) {
Timber.d(exception, "Invalid IP address: %s.", ip);
return false;
}
}
/*
* Transforms String with * and ? characters to regex String, convert "example*.*" to regex
* "^example.*\\..*$", from http://www.rgagnon.com/javadetails/java-0515.html
*/
public static String wildcardToRegex(String wildcard) {
StringBuilder regex = new StringBuilder(wildcard.length());
regex.append('^');
for (int i = 0, is = wildcard.length(); i < is; i++) {
char c = wildcard.charAt(i);
switch (c) {
case '*':
regex.append(".*");
break;
case '?':
regex.append(".");
break;
// escape special regex-characters
case '(':
case ')':
case '[':
case ']':
case '$':
case '^':
case '.':
case '{':
case '}':
case '|':
case '\\':
regex.append("\\");
regex.append(c);
break;
default:
regex.append(c);
break;
}
}
regex.append('$');
return regex.toString();
}
}
| gpl-3.0 |
ckaestne/LEADT | workspace/argouml_critics/argouml-core-model-mdr/build/java/org/omg/uml/behavioralelements/statemachines/AStateExit.java | 2513 | package org.omg.uml.behavioralelements.statemachines;
/**
* A_state_exit association proxy interface.
*
* <p><em><strong>Note:</strong> This type should not be subclassed or implemented
* by clients. It is generated from a MOF metamodel and automatically implemented
* by MDR (see <a href="http://mdr.netbeans.org/">mdr.netbeans.org</a>).</em></p>
*/
public interface AStateExit extends javax.jmi.reflect.RefAssociation {
/**
* Queries whether a link currently exists between a given pair of instance
* objects in the associations link set.
* @param state Value of the first association end.
* @param exit Value of the second association end.
* @return Returns true if the queried link exists.
*/
public boolean exists(org.omg.uml.behavioralelements.statemachines.State state, org.omg.uml.behavioralelements.commonbehavior.Action exit);
/**
* Queries the instance object that is related to a particular instance object
* by a link in the current associations link set.
* @param exit Required value of the second association end.
* @return Related object or <code>null</code> if none exists.
*/
public org.omg.uml.behavioralelements.statemachines.State getState(org.omg.uml.behavioralelements.commonbehavior.Action exit);
/**
* Queries the instance object that is related to a particular instance object
* by a link in the current associations link set.
* @param state Required value of the first association end.
* @return Related object or <code>null</code> if none exists.
*/
public org.omg.uml.behavioralelements.commonbehavior.Action getExit(org.omg.uml.behavioralelements.statemachines.State state);
/**
* Creates a link between the pair of instance objects in the associations
* link set.
* @param state Value of the first association end.
* @param exit Value of the second association end.
*/
public boolean add(org.omg.uml.behavioralelements.statemachines.State state, org.omg.uml.behavioralelements.commonbehavior.Action exit);
/**
* Removes a link between a pair of instance objects in the current associations
* link set.
* @param state Value of the first association end.
* @param exit Value of the second association end.
*/
public boolean remove(org.omg.uml.behavioralelements.statemachines.State state, org.omg.uml.behavioralelements.commonbehavior.Action exit);
}
| gpl-3.0 |
urkopineda/distributed-systems-mu-3 | TCPInterceptor/TCPClient/src/edu/mondragon/urkopineda/socket/SocketClient.java | 1340 | package edu.mondragon.urkopineda.socket;
import edu.mondragon.urkopineda.data.Message;
import java.io.IOException;
import java.net.Socket;
/**
* A TCP socket client.
*
* @author urko
*/
public class SocketClient {
private Socket socket;
private SocketUtils utils;
private String address;
private int port;
public SocketClient(String address, int port) {
this.address = address;
this.port = port;
}
public void start() {
Message message;
try {
connect();
utils = new SocketUtils(socket);
utils.createIO();
message = new Message("gcd", 1, 2);
System.out.println("Client sends: " + message.toString());
utils.write(message);
System.out.println("Server response: " + utils.read());
message = new Message("lcm", 5, 20);
System.out.println("Client sends: " + message.toString());
utils.write(message);
System.out.println("Server response: " + utils.read());
} catch (IOException e) {
System.out.println("ERROR: " + e.getMessage());
}
}
public void connect() throws IOException {
socket = new Socket(address, port);
}
public void close() throws IOException {
utils.close();
}
}
| gpl-3.0 |
OpenSilk/SyncthingAndroid | app/src/main/java/syncthing/api/Credentials.java | 3958 | /*
* Copyright (c) 2015 OpenSilk Productions LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package syncthing.api;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.NonNull;
/**
* Created by drew on 3/6/15.
*/
public class Credentials implements Parcelable {
public static final Credentials NONE = builder().build();
public final String alias;
public final String id;
public final String url;
public final String apiKey;
public final String caCert;
public Credentials(String alias, String id, String url, String apiKey, String caCert) {
this.alias = alias;
this.id = id;
this.url = url;
this.apiKey = apiKey;
this.caCert = caCert;
}
public Builder buildUpon() {
return new Builder(this);
}
public static Builder builder() {
return new Builder();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Credentials that = (Credentials) o;
if (id != null ? !id.equals(that.id) : that.id != null) return false;
return true;
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(alias);
dest.writeString(id);
dest.writeString(url);
dest.writeString(apiKey);
dest.writeString(caCert);
}
public static final Creator<Credentials> CREATOR = new Creator<Credentials>() {
@Override
public Credentials createFromParcel(Parcel source) {
return new Credentials(
source.readString(),
source.readString(),
source.readString(),
source.readString(),
source.readString()
);
}
@Override
public Credentials[] newArray(int size) {
return new Credentials[size];
}
};
public static class Builder {
private String alias;
private String id;
private String url;
private String apiKey;
private String caCert;
private Builder() {
}
private Builder(@NonNull Credentials credentials) {
alias = credentials.alias;
id = credentials.id;
url = credentials.url;
apiKey = credentials.apiKey;
caCert = credentials.caCert;
}
public Builder setAlias(String alias) {
this.alias = alias;
return this;
}
public Builder setId(String id) {
this.id = id;
return this;
}
public Builder setUrl(String url) {
this.url = url;
return this;
}
public Builder setApiKey(String apiKey) {
this.apiKey = apiKey;
return this;
}
public Builder setCaCert(String caCert) {
this.caCert = caCert;
return this;
}
public Credentials build() {
return new Credentials(alias, id, url, apiKey, caCert);
}
}
}
| gpl-3.0 |
sk89q/CraftBook | src/main/java/com/sk89q/craftbook/mechanics/cauldron/legacy/Cauldron.java | 11899 | package com.sk89q.craftbook.mechanics.cauldron.legacy;
// $Id$
/*
* CraftBook Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
* License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not,
* see <http://www.gnu.org/licenses/>.
*/
import com.sk89q.craftbook.AbstractCraftBookMechanic;
import com.sk89q.craftbook.CraftBookPlayer;
import com.sk89q.craftbook.bukkit.BukkitCraftBookPlayer;
import com.sk89q.craftbook.bukkit.CraftBookPlugin;
import com.sk89q.craftbook.util.BlockSyntax;
import com.sk89q.craftbook.util.EventUtil;
import com.sk89q.craftbook.util.ProtectionUtil;
import com.sk89q.util.yaml.YAMLProcessor;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.world.block.BlockStateHolder;
import com.sk89q.worldedit.world.block.BlockTypes;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* Handler for cauldrons.
*
* @author sk89q
* @deprecated Use {@link com.sk89q.craftbook.mechanics.cauldron.ImprovedCauldron} instead
*/
@Deprecated
public class Cauldron extends AbstractCraftBookMechanic {
public boolean isACauldron(Block block) {
Material below = block.getRelative(0, -1, 0).getType();
Material below2 = block.getRelative(0, -2, 0).getType();
Block s1 = block.getRelative(1, 0, 0);
Block s3 = block.getRelative(-1, 0, 0);
Block s2 = block.getRelative(0, 0, 1);
Block s4 = block.getRelative(0, 0, -1);
BlockStateHolder blockItem = cauldronBlock;
// stop strange lava ids
// Preliminary check so we don't waste CPU cycles
return (below == Material.LAVA || below2 == Material.LAVA)
&& (blockItem.equalsFuzzy(BukkitAdapter.adapt(s1.getBlockData()))
|| blockItem.equalsFuzzy(BukkitAdapter.adapt(s2.getBlockData()))
|| blockItem.equalsFuzzy(BukkitAdapter.adapt(s3.getBlockData()))
|| blockItem.equalsFuzzy(BukkitAdapter.adapt(s4.getBlockData())));
}
protected CauldronCookbook recipes;
@Override
public boolean enable() {
recipes = new CauldronCookbook();
return recipes.size() > 0;
}
@EventHandler(priority = EventPriority.HIGH)
public void onRightClick(PlayerInteractEvent event) {
if (!EventUtil.passesFilter(event))
return;
if(event.getAction() != Action.RIGHT_CLICK_BLOCK || event.getHand() != EquipmentSlot.HAND) return;
if(!isACauldron(event.getClickedBlock())) return;
CraftBookPlayer localPlayer = CraftBookPlugin.inst().wrapPlayer(event.getPlayer());
if (!localPlayer.hasPermission("craftbook.mech.cauldron")) {
if(CraftBookPlugin.inst().getConfiguration().showPermissionMessages)
localPlayer.printError("mech.use-permission");
return;
}
if(!ProtectionUtil.canUse(event.getPlayer(), event.getClickedBlock().getLocation(), event.getBlockFace(), event.getAction())) {
if(CraftBookPlugin.inst().getConfiguration().showPermissionMessages)
localPlayer.printError("area.use-permissions");
return;
}
if (!localPlayer.isHoldingBlock()) {
performCauldron(localPlayer, event.getPlayer().getWorld(), event.getClickedBlock().getRelative(0, event.getClickedBlock().getRelative(0, -1, 0).getType() == Material.LAVA ? 1 : 0, 0));
event.setCancelled(true);
}
}
/**
* Attempt to perform a cauldron recipe.
*
* @param player
* @param world
* @param block
*/
private void performCauldron(CraftBookPlayer player, World world, Block block) {
// Gotta start at a root Y then find our orientation
int rootY = block.getY();
Player p = ((BukkitCraftBookPlayer)player).getPlayer();
BlockStateHolder blockItem = cauldronBlock;
// Used to store cauldron blocks -- walls are counted
Map<Location, BlockStateHolder> visited = new HashMap<>();
// The following attempts to recursively find adjacent blocks so
// that it can find all the blocks used within the cauldron
findCauldronContents(player, world, block, rootY - 1, rootY, visited);
// We want cauldrons of a specific shape and size, and 24 is just
// the right number of blocks that the cauldron we want takes up --
// nice and cheap check
if (visited.size() != 24) {
player.printError("mech.cauldron.too-small");
return;
}
// Key is the block ID and the value is the amount
Map<BlockStateHolder, Integer> contents = new HashMap<>();
// Now we have to ignore cauldron blocks so that we get the real
// contents of the cauldron
for (Map.Entry<Location, BlockStateHolder> entry : visited.entrySet()) {
if (!entry.getValue().equals(blockItem))
if (!contents.containsKey(entry.getValue())) {
contents.put(entry.getValue(), 1);
} else {
contents.put(entry.getValue(), contents.get(entry.getValue()) + 1);
}
}
CraftBookPlugin.logDebugMessage("Ingredients: " + contents.keySet().toString(), "legacy-cauldron.ingredients");
// Find the recipe
CauldronCookbook.Recipe recipe = recipes.find(contents);
if (recipe != null) {
String[] groups = recipe.getGroups();
if (groups != null) {
boolean found = false;
for (String group : groups) {
if (CraftBookPlugin.inst().inGroup(p, group)) {
found = true;
break;
}
}
if (!found) {
player.printError("mech.cauldron.legacy-not-in-group");
return;
}
}
player.print(player.translate("mech.cauldron.legacy-create") + " " + recipe.getName() + ".");
List<BlockStateHolder> ingredients = new ArrayList<>(recipe.getIngredients());
//List<BlockWorldVector> removeQueue = new ArrayList<BlockWorldVector>();
// Get rid of the blocks in world
for (Map.Entry<Location, BlockStateHolder> entry : visited.entrySet())
// This is not a fast operation, but we should not have
// too many ingredients
{
if (ingredients.contains(entry.getValue())) {
// Some blocks need to removed first otherwise they will
// drop an item, so let's remove those first
// if
// (!BlockID.isBottomDependentBlock(entry.getValue())) {
// removeQueue.add(entry.getKey());
// } else {
world.getBlockAt(entry.getKey().getBlockX(), entry.getKey().getBlockY(),
entry.getKey().getBlockZ()).setType(Material.AIR);
// }
ingredients.remove(entry.getValue());
}
}
/*
for (BlockWorldVector v : removeQueue) {
world.getBlockAt(v.getBlockX(), v.getBlockY(), v.getBlockZ()).setTypeId(BlockID.AIR);
}
*/
// Give results
for (BlockStateHolder id : recipe.getResults()) {
HashMap<Integer, ItemStack> map = p.getInventory().addItem(new ItemStack(BukkitAdapter.adapt(id.getBlockType().getItemType()), 1));
for (Entry<Integer, ItemStack> i : map.entrySet()) {
world.dropItem(p.getLocation(), i.getValue());
}
}
p.updateInventory();
// Didn't find a recipe
} else {
player.printError("mech.cauldron.legacy-not-a-recipe");
}
}
/**
* Recursively expand the search area so we can define the number of blocks that are in the cauldron. The search
* will not exceed 24 blocks as no
* pot will ever use up that many blocks. The Y are bounded both directions so we don't ever search the lava or
* anything above, although in the
* case of non-wall blocks, we also make sure that there is standing lava underneath.
*
* @param world
* @param block
* @param minY
* @param maxY
* @param visited
*/
public void findCauldronContents(CraftBookPlayer player, World world, Block block, int minY, int maxY, Map<Location, BlockStateHolder> visited) {
BlockStateHolder blockID = cauldronBlock;
// Don't want to go too low or high
if (block.getY() < minY) return;
if (block.getY() > maxY) return;
// There is likely a leak in the cauldron (or this isn't a cauldron)
if (visited.size() > 24) {
player.printError("mech.cauldron.leaky");
return;
}
// Prevent infinite looping
if (visited.containsKey(block.getLocation())) return;
Material type = block.getType();
visited.put(block.getLocation(), BukkitAdapter.adapt(block.getBlockData()));
// It's a wall -- we only needed to remember that we visited it but
// we don't need to recurse
if (BukkitAdapter.equals(blockID.getBlockType(), type)) return;
// Must have a lava floor
Block lavaPos = recurse(0, block.getY() - minY + 1, 0, block);
if (world.getBlockAt(lavaPos.getX(), lavaPos.getY(), lavaPos.getZ()).getType() == Material.LAVA) {
player.printError("mech.cauldron.no-lava");
return;
}
// Now we recurse!
findCauldronContents(player, world, recurse(1, 0, 0, block), minY, maxY, visited);
findCauldronContents(player, world, recurse(-1, 0, 0, block), minY, maxY, visited);
findCauldronContents(player, world, recurse(0, 0, 1, block), minY, maxY, visited);
findCauldronContents(player, world, recurse(0, 0, -1, block), minY, maxY, visited);
findCauldronContents(player, world, recurse(0, 1, 0, block), minY, maxY, visited);
findCauldronContents(player, world, recurse(0, -1, 0, block), minY, maxY, visited);
}
/**
* Returns a new BlockWorldVector with i, j, and k added to pt's x, y and z.
*
* @param x
* @param y
* @param z
* @param block
*/
private Block recurse(int x, int y, int z, Block block) {
return block.getRelative(x, y, z);
}
public BlockStateHolder cauldronBlock;
@Override
public void loadConfiguration (YAMLProcessor config, String path) {
config.setComment(path + "block", "The block to use as the casing for the legacy cauldron.");
cauldronBlock = BlockSyntax.getBlock(config.getString(path + "block", BlockTypes.STONE.getId()), true);
}
} | gpl-3.0 |
Limezero/libreoffice | bean/com/sun/star/comp/beans/OfficeConnection.java | 2225 | /*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
package com.sun.star.comp.beans;
import java.awt.Container;
import com.sun.star.lang.XComponent;
import com.sun.star.uno.XComponentContext;
/**
* This abstract class represents a connection to the office
* application.
*/
@Deprecated
public interface OfficeConnection
extends XComponent
{
/**
* Sets a connection URL.
*
* @param url This is UNO URL which describes the type of a connection.
*/
void setUnoUrl(String url)
throws java.net.MalformedURLException;
/**
* Sets an AWT container catory.
*
* @param containerFactory This is a application provided AWT container
* factory.
*/
void setContainerFactory(ContainerFactory containerFactory);
/**
* Retrieves the UNO component context.
* Establishes a connection if necessary and initialises the
* UNO service manager if it has not already been initialised.
*
* @return The office UNO component context.
*/
XComponentContext getComponentContext();
/**
* Creates an office window.
* The window is either a sub-class of java.awt.Canvas (local) or
* java.awt.Container (RVP).
*
* This method does not add the office window to its container.
*
* @param container This is an AWT container.
* @return The office window instance.
*/
OfficeWindow createOfficeWindow(Container container);
}
| gpl-3.0 |
lionelliang/zorka | zorka-core/src/main/java/com/jitlogic/zorka/core/spy/MethodCallCounter.java | 4090 | /**
* Copyright 2012-2015 Rafal Lewczuk <rafal.lewczuk@jitlogic.com>
* <p/>
* This 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.
* <p/>
* 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 General Public License for more details.
* <p/>
* You should have received a copy of the GNU General Public License
* along with this software. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jitlogic.zorka.core.spy;
import com.jitlogic.zorka.common.tracedata.MethodCallCounterRecord;
import java.util.ArrayList;
import java.util.List;
public class MethodCallCounter {
private static final int INITIAL_SIZE = 64;
private long keys[], vals[];
private long initialTime = 0L;
private int numEntries = 0, maxEntries = 0;
private static final long FREE = 0;
private static final long MASK = 0x1fffffL;
public MethodCallCounter() {
keys = new long[INITIAL_SIZE];
vals = new long[INITIAL_SIZE];
numEntries = 0;
maxEntries = INITIAL_SIZE * 3 / 4;
}
public void logCall(int classId, int methodId, int signatureId, long tstamp) {
logCalls(classId, methodId, signatureId, tstamp, 1);
}
public void logCalls(int classId, int methodId, int signatureId, long tstamp, long nCalls) {
long key = classId | (((long) methodId) << 21) | (((long) signatureId) << 42);
if (initialTime == tstamp) {
initialTime = tstamp;
}
if (numEntries > maxEntries) {
rehash(maxEntries * 2);
}
int idx = index(key);
if (keys[idx] == FREE) {
keys[idx] = key;
vals[idx] = nCalls;
numEntries++;
} else {
vals[idx] += nCalls;
}
}
public List<MethodCallCounterRecord> getRecords() {
List<MethodCallCounterRecord> ret = new ArrayList<MethodCallCounterRecord>();
for (int i = 0; i < keys.length; i++) {
long key = keys[i];
if (key != FREE) {
ret.add(new MethodCallCounterRecord((int) (key & MASK), (int) ((key >> 21) & MASK), (int) ((key >> 42) & MASK), vals[i]));
}
}
return ret;
}
public void sum(MethodCallCounter mcc) {
long[] mkeys = mcc.keys;
long[] mvals = mcc.vals;
long tst = mcc.initialTime;
for (int i = 0; i < mkeys.length; i++) {
long key = mkeys[i];
if (key != FREE) {
logCalls((int) (key & MASK), (int) ((key >> 21) & MASK), (int) ((key >> 42) & MASK), tst, mvals[i]);
}
}
}
public void clear() {
initialTime = 0L;
numEntries = 0;
for (int i = 0; i < keys.length; i++) {
keys[i] = 0;
}
}
private int lhash(long l) {
int v = (int) (l ^ (l >> 32));
return v >= 0 ? v : -v;
}
private void rehash(int capacity) {
int olen = keys.length;
long[] okeys = keys;
long[] ovals = vals;
long[] nkeys = new long[capacity];
long[] nvals = new long[capacity];
keys = nkeys;
vals = nvals;
maxEntries = capacity * 3 / 4;
for (int i = 0; i < olen; i++) {
long key = okeys[i];
int idx = index(key);
nkeys[idx] = key;
nvals[idx] = ovals[i];
}
}
private int index(long key) {
long[] keys = this.keys;
int length = keys.length;
int hash = lhash(key);
int i = hash % length;
if (i < 0) {
System.out.println("kurwa!");
}
while (keys[i] != FREE && keys[i] != key) {
i = (i > 0) ? i - 1 : length - 1;
}
return i;
}
}
| gpl-3.0 |
nishanttotla/predator | cpachecker/src/org/sosy_lab/cpachecker/util/predicates/interpolation/strategy/package-info.java | 521 | /**
* Different strategies to compute interpolants for a sequence of path formulae.
* Some analyses depend on special strategies, e.g.
* predicate analysis needs an inductive sequence of interpolation and
* the analysis of recursive procedures with BAM and predicate analysis uses tree interpolation.
* There are also strategies that directly ask the SMT solver for a complete solution
* instead of querying every interpolant separately.
*/
package org.sosy_lab.cpachecker.util.predicates.interpolation.strategy;
| gpl-3.0 |
waynedyck/wsdot-android-app | app/src/main/java/gov/wa/wsdot/android/wsdot/service/TopicViewModel.java | 1162 | package gov.wa.wsdot.android.wsdot.service;
import java.util.List;
import javax.inject.Inject;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import gov.wa.wsdot.android.wsdot.database.notifications.NotificationTopicEntity;
import gov.wa.wsdot.android.wsdot.repository.NotificationTopicsRepository;
import gov.wa.wsdot.android.wsdot.util.network.ResourceStatus;
public class TopicViewModel extends ViewModel {
private static String TAG = TopicViewModel.class.getSimpleName();
private MutableLiveData<ResourceStatus> mStatus;
private NotificationTopicsRepository topicsRepo;
private LiveData<List<NotificationTopicEntity>> topics;
@Inject
public TopicViewModel(NotificationTopicsRepository topicsRepo) {
this.mStatus = new MutableLiveData<>();
this.topicsRepo = topicsRepo;
}
public void init() {
this.topics = topicsRepo.loadTopics(mStatus);
}
public LiveData<ResourceStatus> getResourceStatus() { return this.mStatus; }
public LiveData<List<NotificationTopicEntity>> getTopics() {
return topics;
}
} | gpl-3.0 |
tbrooks8/quasar | quasar-core/src/main/java/co/paralleluniverse/common/monitoring/ForkJoinPoolMXBean.java | 932 | /*
* Copyright (c) 2011-2014, Parallel Universe Software Co. All rights reserved.
*
* This program and the accompanying materials are dual-licensed under
* either the terms of the Eclipse Public License v1.0 as published by
* the Eclipse Foundation
*
* or (per the licensee's choosing)
*
* under the terms of the GNU Lesser General Public License version 3.0
* as published by the Free Software Foundation.
*/
package co.paralleluniverse.common.monitoring;
/**
*
* @author pron
*/
public interface ForkJoinPoolMXBean {
boolean getAsyncMode();
int getParallelism();
int getPoolSize();
ForkJoinPoolMonitor.Status getStatus();
int getActiveThreadCount();
int getRunningThreadCount();
int getQueuedSubmissionCount();
long getQueuedTaskCount();
long getStealCount();
long[] getLatency();
ForkJoinInfo getInfo();
void shutdown();
void shutdownNow();
}
| gpl-3.0 |
prisonerjohn/ezjlibs | dev/src/net/silentlycrashing/gestures/preset/VShake.java | 986 | /*
This file is part of the ezGestures project.
http://www.silentlycrashing.net/ezgestures/
Copyright (c) 2007-08 Elie Zananiri
ezGestures 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.
ezGestures 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
ezGestures. If not, see <http://www.gnu.org/licenses/>.
*/
package net.silentlycrashing.gestures.preset;
/**
* Holds the regex pattern for a vertical shake.
*/
/* $Id$ */
public interface VShake {
public static final String VS_PATTERN = "^(?:U?(?:DU)+D?|D?(?:UD)+U?)$";
}
| gpl-3.0 |
RobbiNespu/moloko | src/dev/drsoran/moloko/sync/elements/OutSyncTask.java | 28182 | /*
* Copyright (c) 2011 Ronny Röhricht
*
* This file is part of Moloko.
*
* Moloko 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.
*
* Moloko 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 Moloko. If not, see <http://www.gnu.org/licenses/>.
*
* Contributors:
* Ronny Röhricht - implementation
*/
package dev.drsoran.moloko.sync.elements;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentProviderOperation;
import android.net.Uri;
import android.provider.BaseColumns;
import com.mdt.rtm.data.RtmTask;
import com.mdt.rtm.data.RtmTaskList;
import com.mdt.rtm.data.RtmTaskSeries;
import com.mdt.rtm.data.RtmTimeline;
import dev.drsoran.moloko.MolokoApp;
import dev.drsoran.moloko.content.CreationsProviderPart;
import dev.drsoran.moloko.content.Modification;
import dev.drsoran.moloko.content.ModificationSet;
import dev.drsoran.moloko.content.ModificationsProviderPart;
import dev.drsoran.moloko.sync.operation.ContentProviderSyncOperation;
import dev.drsoran.moloko.sync.operation.IContentProviderSyncOperation;
import dev.drsoran.moloko.sync.operation.IServerSyncOperation;
import dev.drsoran.moloko.sync.operation.ServerSyncOperation;
import dev.drsoran.moloko.sync.operation.TaskServerSyncOperation;
import dev.drsoran.moloko.sync.syncable.IServerSyncable;
import dev.drsoran.moloko.sync.util.SyncProperties;
import dev.drsoran.moloko.sync.util.SyncUtils;
import dev.drsoran.moloko.sync.util.SyncUtils.SyncResultDirection;
import dev.drsoran.moloko.util.MolokoDateUtils;
import dev.drsoran.moloko.util.Queries;
import dev.drsoran.moloko.util.Strings;
import dev.drsoran.provider.Rtm.RawTasks;
import dev.drsoran.provider.Rtm.TaskSeries;
public class OutSyncTask extends SyncTaskBase implements
IServerSyncable< OutSyncTask, RtmTaskList >
{
public final static LessIdComperator< OutSyncTask > LESS_ID = new LessIdComperator< OutSyncTask >();
public OutSyncTask( RtmTaskSeries taskSeries, RtmTask task )
{
super( taskSeries, task );
}
public OutSyncTask( RtmTaskSeries taskSeries, String taskId )
{
super( taskSeries, taskId );
}
public OutSyncTask( RtmTaskSeries taskSeries )
{
super( taskSeries );
}
public final static List< OutSyncTask > fromTaskSeries( RtmTaskSeries taskSeries )
{
final List< OutSyncTask > result = new ArrayList< OutSyncTask >();
for ( final RtmTask task : taskSeries.getTasks() )
result.add( new OutSyncTask( taskSeries, task ) );
return result;
}
@Override
public boolean hasModification( ModificationSet modificationSet )
{
return modificationSet.hasModification( Queries.contentUriWithId( TaskSeries.CONTENT_URI,
taskSeries.getId() ) )
|| modificationSet.hasModification( Queries.contentUriWithId( RawTasks.CONTENT_URI,
task.getId() ) );
}
public IContentProviderSyncOperation handleAfterServerInsert( OutSyncTask serverElement )
{
final ContentProviderSyncOperation.Builder operation = ContentProviderSyncOperation.newUpdate();
/**
* Change the ID of the local taskseries to the ID of the server taskseries. Referencing entities will also be
* changed by a DB trigger.
**/
operation.add( ContentProviderOperation.newUpdate( Queries.contentUriWithId( TaskSeries.CONTENT_URI,
taskSeries.getId() ) )
.withValue( BaseColumns._ID,
serverElement.taskSeries.getId() )
.build() );
/** Change the ID of the local rawtask to the ID of the server rawtask. **/
operation.add( ContentProviderOperation.newUpdate( Queries.contentUriWithId( RawTasks.CONTENT_URI,
task.getId() ) )
.withValue( BaseColumns._ID,
serverElement.task.getId() )
.build() );
/** Remove the old task IDs from the creations table, marking this task as send **/
operation.add( CreationsProviderPart.deleteCreation( TaskSeries.CONTENT_URI,
taskSeries.getId() ) );
operation.add( CreationsProviderPart.deleteCreation( RawTasks.CONTENT_URI,
task.getId() ) );
/** Remove all modifications with the old task IDs **/
operation.add( ModificationsProviderPart.getRemoveModificationOps( TaskSeries.CONTENT_URI,
taskSeries.getId() ) );
operation.add( ModificationsProviderPart.getRemoveModificationOps( RawTasks.CONTENT_URI,
task.getId() ) );
return operation.build();
}
/**
* This stores only outgoing differences between the local task and the server task as modification.
*
* This is needed due to the fact that add a task on RTM side is no single operation and may be interrupted.
*/
public IContentProviderSyncOperation computeServerInsertModification( OutSyncTask serverElement )
{
final ContentProviderSyncOperation.Builder operation = ContentProviderSyncOperation.newUpdate();
/** RtmTaskSeries **/
{
// All differences to the new server element will be added as modification. The Modification.newValue
// is the local task value and the Modification.syncedValue is the value from the new inserted task
// from RTM side.
final Uri newUri = Queries.contentUriWithId( TaskSeries.CONTENT_URI,
serverElement.taskSeries.getId() );
// Recurrence
if ( SyncUtils.hasChanged( taskSeries.getRecurrence(),
serverElement.taskSeries.getRecurrence() ) )
operation.add( Modification.newModificationOperation( newUri,
TaskSeries.RECURRENCE,
taskSeries.getRecurrence(),
serverElement.taskSeries.getRecurrence() ) );
// Tags
if ( SyncUtils.hasChanged( taskSeries.getTagsJoined(),
serverElement.taskSeries.getTagsJoined() ) )
operation.add( Modification.newModificationOperation( newUri,
TaskSeries.TAGS,
taskSeries.getTagsJoined(),
serverElement.taskSeries.getTagsJoined() ) );
// Location
if ( SyncUtils.hasChanged( taskSeries.getLocationId(),
serverElement.taskSeries.getLocationId() ) )
operation.add( Modification.newModificationOperation( newUri,
TaskSeries.LOCATION_ID,
taskSeries.getLocationId(),
serverElement.taskSeries.getLocationId() ) );
// URL
if ( SyncUtils.hasChanged( taskSeries.getURL(),
serverElement.taskSeries.getURL() ) )
operation.add( Modification.newModificationOperation( newUri,
TaskSeries.URL,
taskSeries.getURL(),
serverElement.taskSeries.getURL() ) );
}
/** RtmTask **/
{
// All differences to the new server element will be added as modification
final Uri newUri = Queries.contentUriWithId( RawTasks.CONTENT_URI,
serverElement.task.getId() );
// Priority
if ( SyncUtils.hasChanged( task.getPriority(),
serverElement.task.getPriority() ) )
operation.add( Modification.newModificationOperation( newUri,
RawTasks.PRIORITY,
RtmTask.convertPriority( task.getPriority() ),
RtmTask.convertPriority( serverElement.task.getPriority() ) ) );
// Completed date
if ( SyncUtils.hasChanged( task.getCompleted(),
serverElement.task.getCompleted() ) )
operation.add( Modification.newModificationOperation( newUri,
RawTasks.COMPLETED_DATE,
MolokoDateUtils.getTime( task.getCompleted() ),
MolokoDateUtils.getTime( serverElement.task.getCompleted() ) ) );
// Due date
if ( SyncUtils.hasChanged( task.getDue(), serverElement.task.getDue() ) )
operation.add( Modification.newModificationOperation( newUri,
RawTasks.DUE_DATE,
MolokoDateUtils.getTime( task.getDue() ),
MolokoDateUtils.getTime( serverElement.task.getDue() ) ) );
// Has due time
if ( SyncUtils.hasChanged( task.getHasDueTime(),
serverElement.task.getHasDueTime() ) )
operation.add( Modification.newModificationOperation( newUri,
RawTasks.HAS_DUE_TIME,
task.getHasDueTime(),
serverElement.task.getHasDueTime() ) );
// Estimate
if ( SyncUtils.hasChanged( task.getEstimate(),
serverElement.task.getEstimate() ) )
operation.add( Modification.newModificationOperation( newUri,
RawTasks.ESTIMATE,
task.getEstimate(),
serverElement.task.getEstimate() ) );
/**
* Postponed can not be synced. Otherwise we had to store the initial due date on local task creation of the
* task and set this initial date after creation of the task on RTM side. After this, we could call postpone
* 1..n times. This is not supported atm.
**/
}
return operation.build();
}
@Override
public IServerSyncOperation< RtmTaskList > computeServerUpdateOperation( RtmTimeline timeline,
ModificationSet modifications,
OutSyncTask serverElement )
{
final TaskServerSyncOperation.Builder< RtmTaskList > operation = ServerSyncOperation.newUpdate();
// In case we have no server element (incremental sync)
if ( serverElement == null )
serverElement = this;
/** RtmTaskSeries **/
{
final SyncProperties properties = SyncProperties.newInstance( serverElement == this
? null
: serverElement.getModifiedDate(),
getModifiedDate(),
Queries.contentUriWithId( TaskSeries.CONTENT_URI,
taskSeries.getId() ),
modifications );
// ListId
if ( SyncUtils.getSyncDirection( properties,
TaskSeries.LIST_ID,
serverElement.taskSeries.getListId(),
taskSeries.getListId(),
String.class ) == SyncResultDirection.SERVER )
{
String oldListId = null;
// In case we have no server element (incremental sync), we look for the modification
if ( serverElement == this )
{
final Modification modification = modifications.find( Queries.contentUriWithId( TaskSeries.CONTENT_URI,
taskSeries.getId() ),
TaskSeries.LIST_ID );
if ( modification != null )
oldListId = modification.getSyncedValue();
}
else
{
oldListId = serverElement.taskSeries.getListId();
}
operation.add( timeline.tasks_moveTo( oldListId,
taskSeries.getListId(),
taskSeries.getId(),
task.getId() ),
properties.getModification( TaskSeries.LIST_ID ) );
}
// Name
if ( SyncUtils.getSyncDirection( properties,
TaskSeries.TASKSERIES_NAME,
serverElement.taskSeries.getName(),
taskSeries.getName(),
String.class ) == SyncResultDirection.SERVER )
{
operation.add( timeline.tasks_setName( taskSeries.getListId(),
taskSeries.getId(),
task.getId(),
taskSeries.getName() ),
properties.getModification( TaskSeries.TASKSERIES_NAME ) );
}
// Recurrence
if ( SyncUtils.getSyncDirection( properties,
TaskSeries.RECURRENCE,
serverElement.taskSeries.getRecurrence(),
taskSeries.getRecurrence(),
String.class ) == SyncResultDirection.SERVER )
{
// The RTM API needs the repeat parameter as sentence, not pattern.
final String repeat = taskSeries.getRecurrenceSentence();
operation.add( timeline.tasks_setRecurrence( taskSeries.getListId(),
taskSeries.getId(),
task.getId(),
repeat ),
properties.getModification( TaskSeries.RECURRENCE ) );
}
// Tags
if ( SyncUtils.getSyncDirection( properties,
TaskSeries.TAGS,
serverElement.taskSeries.getTagsJoined(),
taskSeries.getTagsJoined(),
String.class ) == SyncResultDirection.SERVER )
{
operation.add( timeline.tasks_setTags( taskSeries.getListId(),
taskSeries.getId(),
task.getId(),
taskSeries.getTags() ),
properties.getModification( TaskSeries.TAGS ) );
}
// Location
if ( SyncUtils.getSyncDirection( properties,
TaskSeries.LOCATION_ID,
serverElement.taskSeries.getLocationId(),
taskSeries.getLocationId(),
String.class ) == SyncResultDirection.SERVER )
{
operation.add( timeline.tasks_setLocation( taskSeries.getListId(),
taskSeries.getId(),
task.getId(),
taskSeries.getLocationId() ),
properties.getModification( TaskSeries.LOCATION_ID ) );
}
// URL
if ( SyncUtils.getSyncDirection( properties,
TaskSeries.URL,
serverElement.taskSeries.getURL(),
taskSeries.getURL(),
String.class ) == SyncResultDirection.SERVER )
{
operation.add( timeline.tasks_setURL( taskSeries.getListId(),
taskSeries.getId(),
task.getId(),
Strings.emptyIfNull( taskSeries.getURL() ) ),
properties.getModification( TaskSeries.URL ) );
}
}
/** RtmTask **/
{
final SyncProperties properties = SyncProperties.newInstance( serverElement == this
? null
: serverElement.getModifiedDate(),
getModifiedDate(),
Queries.contentUriWithId( RawTasks.CONTENT_URI,
task.getId() ),
modifications );
// Priority
if ( SyncUtils.getSyncDirection( properties,
RawTasks.PRIORITY,
RtmTask.convertPriority( serverElement.task.getPriority() ),
RtmTask.convertPriority( task.getPriority() ),
String.class ) == SyncResultDirection.SERVER )
{
operation.add( timeline.tasks_setPriority( taskSeries.getListId(),
taskSeries.getId(),
task.getId(),
task.getPriority() ),
properties.getModification( RawTasks.PRIORITY ) );
}
// Completed date
if ( SyncUtils.getSyncDirection( properties,
RawTasks.COMPLETED_DATE,
MolokoDateUtils.getTime( serverElement.task.getCompleted() ),
MolokoDateUtils.getTime( task.getCompleted() ),
Long.class ) == SyncResultDirection.SERVER )
{
if ( task.getCompleted() != null )
operation.add( timeline.tasks_complete( taskSeries.getListId(),
taskSeries.getId(),
task.getId() ),
properties.getModification( RawTasks.COMPLETED_DATE ) );
else
operation.add( timeline.tasks_uncomplete( taskSeries.getListId(),
taskSeries.getId(),
task.getId() ),
properties.getModification( RawTasks.COMPLETED_DATE ) );
}
// Due date
if ( SyncUtils.getSyncDirection( properties,
RawTasks.DUE_DATE,
MolokoDateUtils.getTime( serverElement.task.getDue() ),
MolokoDateUtils.getTime( task.getDue() ),
Long.class ) == SyncResultDirection.SERVER
|| SyncUtils.getSyncDirection( properties,
RawTasks.HAS_DUE_TIME,
serverElement.task.getHasDueTime(),
task.getHasDueTime(),
Integer.class ) == SyncResultDirection.SERVER )
{
final Modification dueMod = properties.getModification( RawTasks.DUE_DATE );
final Modification hasTimeMod = properties.getModification( RawTasks.HAS_DUE_TIME );
final List< Modification > modsList = new ArrayList< Modification >( 2 );
if ( dueMod != null )
modsList.add( dueMod );
if ( hasTimeMod != null )
modsList.add( hasTimeMod );
operation.add( timeline.tasks_setDueDate( taskSeries.getListId(),
taskSeries.getId(),
task.getId(),
task.getDue(),
task.getHasDueTime() != 0
? true
: false ),
modsList );
}
// Estimate
if ( SyncUtils.getSyncDirection( properties,
RawTasks.ESTIMATE,
serverElement.task.getEstimate(),
task.getEstimate(),
String.class ) == SyncResultDirection.SERVER )
{
operation.add( timeline.tasks_setEstimate( taskSeries.getListId(),
taskSeries.getId(),
task.getId(),
Strings.emptyIfNull( task.getEstimate() ) ),
properties.getModification( RawTasks.ESTIMATE ) );
}
// Postponed
{
final int localPostponed = task.getPostponed();
if ( SyncUtils.getSyncDirection( properties,
RawTasks.POSTPONED,
serverElement.task.getPostponed(),
localPostponed,
Integer.class ) == SyncResultDirection.SERVER )
{
final int serverPostponed;
// In case we have no server element (incremental sync), we look for the modification
if ( serverElement == this )
{
final Modification modification = modifications.find( Queries.contentUriWithId( RawTasks.CONTENT_URI,
task.getId() ),
RawTasks.POSTPONED );
if ( modification != null )
serverPostponed = modification.getSyncedValue( Integer.class );
else
{
serverPostponed = localPostponed;
MolokoApp.Log.e( getClass(),
"Expected postponed modification" );
}
}
else
{
serverPostponed = serverElement.task.getPostponed();
}
// Postpone the task "the difference between local and server" times.
final int diffPostponed = localPostponed - serverPostponed;
// Check that on server side the task was not also postponed.
if ( diffPostponed > 0 )
{
for ( int i = 0; i < diffPostponed; i++ )
{
operation.add( timeline.tasks_postpone( taskSeries.getListId(),
taskSeries.getId(),
task.getId() ),
// Only the last method invocation clears the modification
i + 1 == diffPostponed
? properties.getModification( RawTasks.POSTPONED )
: null );
}
}
}
}
}
return operation.build( TaskServerSyncOperation.class );
}
@Override
public IServerSyncOperation< RtmTaskList > computeServerDeleteOperation( RtmTimeline timeLine )
{
return ServerSyncOperation.newDelete( timeLine.tasks_delete( taskSeries.getListId(),
taskSeries.getId(),
task.getId() ) )
.build( TaskServerSyncOperation.class );
}
}
| gpl-3.0 |
eicherj/subframe | src/example/example1/SortEvaluation.java | 5862 | /*
* SUBFRAME - Simple Java Benchmarking Framework
* Copyright (C) 2012 - 2016 Fabian Prasser and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package example1;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import de.linearbits.objectselector.Selector;
import de.linearbits.subframe.analyzer.Analyzer;
import de.linearbits.subframe.graph.Field;
import de.linearbits.subframe.graph.Labels;
import de.linearbits.subframe.graph.Plot;
import de.linearbits.subframe.graph.PlotHistogram;
import de.linearbits.subframe.graph.PlotLinesClustered;
import de.linearbits.subframe.graph.Series3D;
import de.linearbits.subframe.io.CSVFile;
import de.linearbits.subframe.render.GnuPlotParams;
import de.linearbits.subframe.render.GnuPlotParams.KeyPos;
import de.linearbits.subframe.render.LaTeX;
import de.linearbits.subframe.render.PlotGroup;
/**
* Example benchmark
* @author Fabian Prasser
*/
public class SortEvaluation {
/**
* Main
* @param args
* @throws IOException
* @throws ParseException
*/
public static void main(String[] args) throws IOException, ParseException {
CSVFile file = new CSVFile(new File("src/example/example1/sort.csv"));
List<PlotGroup> groups = new ArrayList<PlotGroup>();
groups.add(getGroup1(file));
groups.add(getGroup2(file));
LaTeX.plot(groups, "src/example/example1/sort");
}
/**
* Returns the first plot group
* @param file
* @return
* @throws ParseException
*/
private static PlotGroup getGroup1(CSVFile file) throws ParseException{
Series3D series = getSeriesForLinesPlot(file, "JavaQuickSort");
series.append(getSeriesForLinesPlot(file, "ColtQuickSort"));
series.append(getSeriesForLinesPlot(file, "ColtMergeSort"));
List<Plot<?>> plots = new ArrayList<Plot<?>>();
plots.add(new PlotLinesClustered("Sorting Arrays",
new Labels("Size", "Execution time [ns]"),
series));
GnuPlotParams params = new GnuPlotParams();
params.rotateXTicks = -90;
params.keypos = KeyPos.TOP_LEFT;
params.size = 0.6d;
return new PlotGroup("Comparison of algorithms", plots, params, 1.0d);
}
/**
* Returns the second plot group
* @param file
* @return
* @throws ParseException
*/
private static PlotGroup getGroup2(CSVFile file) throws ParseException{
List<Plot<?>> plots = new ArrayList<Plot<?>>();
Series3D series;
series = getSeriesForHistogram(file, "JavaQuickSort");
plots.add(new PlotHistogram("JavaQuickSort",
new Labels("Size", "Execution time [ns]"),
series));
series = getSeriesForHistogram(file, "ColtQuickSort");
plots.add(new PlotHistogram("ColtQuickSort",
new Labels("Size", "Execution time [ns]"),
series));
series = getSeriesForHistogram(file, "ColtMergeSort");
plots.add(new PlotHistogram("ColtMergeSort",
new Labels("Size", "Execution time [ns]"),
series));
GnuPlotParams params = new GnuPlotParams();
params.rotateXTicks = -90;
params.keypos = KeyPos.TOP_LEFT;
params.size = 0.6d;
params.minY = 0d;
return new PlotGroup("Individual execution times", plots, params, 1.0d);
}
/**
* Returns a series that can be clustered by size
* @param file
* @param method
* @return
* @throws ParseException
*/
private static Series3D getSeriesForHistogram(CSVFile file, String method) throws ParseException {
Selector<String[]> selector = file.getSelectorBuilder()
.field("Method").equals(method)
.build();
Series3D series = new Series3D(file, selector,
new Field("Size"),
new Field("Time", Analyzer.ARITHMETIC_MEAN),
new Field("Time", Analyzer.STANDARD_DEVIATION));
return series;
}
/**
* Returns a series that can be clustered by size
* @param file
* @param method
* @return
* @throws ParseException
*/
private static Series3D getSeriesForLinesPlot(CSVFile file, String method) throws ParseException {
Selector<String[]> selector = file.getSelectorBuilder()
.field("Method").equals(method)
.build();
Series3D series = new Series3D(file, selector,
new Field("Size"),
new Field("Method"),
new Field("Time", Analyzer.ARITHMETIC_MEAN));
return series;
}
}
| gpl-3.0 |
Team-RTG/Appalachia | src/main/java/appalachia/block/fencegates/BlockFenceGateBlackgum01.java | 366 | package appalachia.block.fencegates;
import appalachia.block.IAppalachiaBlock;
public class BlockFenceGateBlackgum01 extends AppalachiaBlockFenceGate implements IAppalachiaBlock {
public BlockFenceGateBlackgum01() {
super("fence.gate.blackgum.01");
}
@Override
public String registryName() {
return super.registryName();
}
} | gpl-3.0 |
clarin-eric/oai-harvest-manager | src/main/java/nl/mpi/oai/harvester/harvesting/OAIHelper.java | 4649 | package nl.mpi.oai.harvester.harvesting;
import java.util.logging.Level;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import com.ctc.wstx.exc.WstxUnexpectedCharException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import nl.mpi.oai.harvester.utils.DocumentSource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.codehaus.stax2.XMLInputFactory2;
import org.codehaus.stax2.XMLStreamReader2;
import org.codehaus.stax2.evt.XMLEvent2;
/**
* <br> Helper implementing operations on documents transported by OAI
*
* @author Kees Jan van de Looij (Max Planck Institute for Psycholinguistics)
*/
public class OAIHelper {
private static Logger logger = LogManager.getLogger(OAIHelper.class);
// only keep one XPath object for querying
static public XPath xpath = null;
/**
* <br> Get the metadata prefixes referenced in a document <br><br>
*
* Note: since the metadata itself might not contain a reference to the
* prefix, the document needs to be an OAI envelope.
*
* @param document the document
* @return the metadata prefix
*/
static public String getPrefix (DocumentSource document){
// metadata prefix
String prefix = null;
if (document.hasDocument()) {
// node in the document
Node node = null;
if (xpath == null){
// set up XPath querying
XPathFactory xpf = XPathFactory.newInstance();
xpath = xpf.newXPath();
}
// look for the prefix in the request node
try {
node = (Node) xpath.evaluate(
"//*[local-name()='request']",
document.getDocument(), XPathConstants.NODE);
} catch (XPathExpressionException e) {
e.printStackTrace();
}
if (node == null){
// no request node, no metadata prefix
prefix = null;
} else {
// found the request node, get the prefix attribute value
if (node.getAttributes().getNamedItem("metadataPrefix") == null){
prefix = null; // no metadata prefix
} else {
prefix = node.getAttributes().getNamedItem("metadataPrefix").getNodeValue();
}
}
} else {
int state = 1; // 1:START 0:STOP -1:ERROR
try {
XMLInputFactory2 xmlif = (XMLInputFactory2) XMLInputFactory2.newInstance();
xmlif.configureForConvenience();
XMLStreamReader2 xmlr = (XMLStreamReader2) xmlif.createXMLStreamReader(document.getStream());
while (state > 0) {
int eventType = xmlr.getEventType();
switch (state) {
case 1://START
switch (eventType) {
case XMLEvent2.START_ELEMENT:
QName qn = xmlr.getName();
if (qn.getLocalPart().equals("request")) {
prefix = xmlr.getAttributeValue(null,"metadataPrefix");
if (prefix != null)
state = 0;//STOP
}
break;
}
break;
}
outer:
if (xmlr.hasNext())
try {
xmlr.next();
} catch (WstxUnexpectedCharException ex) {
logger.info("Invalid char found in XML, skipping the current one and look for next one");
}
else
state = state == 1? 0: -1;// if START then STOP else ERROR
}
} catch (XMLStreamException ex) {
logger.error("problem finding prefix in the XML stream!",ex);
state = -1;//ERROR
}
if (state < 0 || prefix == null)
logger.debug("couldn't find prefix in the XML stream!");
else
logger.debug("found prefix["+prefix+"] in the XML stream!");
}
return prefix;
}
}
| gpl-3.0 |
ZsoltMolnarrr/ClassesOfWarcraft | battlegear mod src/minecraft/mods/battlegear2/heraldry/TileEntityFlagPole.java | 4609 | package mods.battlegear2.heraldry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import mods.battlegear2.api.heraldry.IFlagHolder;
import mods.battlegear2.items.HeraldryCrest;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.network.play.server.S35PacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import java.util.ArrayList;
import java.util.List;
/**
* User: nerd-boy
* Date: 2/08/13
* Time: 2:33 PM
*/
public class TileEntityFlagPole extends TileEntity implements IFlagHolder{
private static final int MAX_FLAGS = 4;
private ArrayList<ItemStack> flags;
public boolean receiveUpdates = false;
public int side;
public TileEntityFlagPole(){
flags = new ArrayList<ItemStack>(MAX_FLAGS);
}
@Override
@SideOnly(Side.CLIENT)
public AxisAlignedBB getRenderBoundingBox()
{
switch (side){
case 0:
return AxisAlignedBB.getBoundingBox(
xCoord - flags.size(),
yCoord,
zCoord,
xCoord + flags.size()+1,
yCoord + 1, zCoord + 1);
case 1:
case 2:
return AxisAlignedBB.getBoundingBox(
xCoord,
yCoord - flags.size(),
zCoord,
xCoord+1,
yCoord+ flags.size()+1, zCoord + 1);
}
return AxisAlignedBB.getBoundingBox(
xCoord - flags.size(),
yCoord,
zCoord,
xCoord + flags.size()+1,
yCoord + 1, zCoord + 1);
}
@Override
public void readFromNBT(NBTTagCompound par1NBTTagCompound) {
super.readFromNBT(par1NBTTagCompound);
side = par1NBTTagCompound.getInteger("orientation");
flags = new ArrayList<ItemStack>(MAX_FLAGS);
for(int i = 0; i < MAX_FLAGS; i++){
if(par1NBTTagCompound.hasKey("flag"+i)){
flags.add(ItemStack.loadItemStackFromNBT(par1NBTTagCompound.getCompoundTag("flag"+i)));
}
}
receiveUpdates = par1NBTTagCompound.getBoolean("hasUpdate");
}
@Override
public void writeToNBT(NBTTagCompound par1NBTTagCompound) {
super.writeToNBT(par1NBTTagCompound);
par1NBTTagCompound.setInteger("orientation", side);
for(int i = 0; i < flags.size(); i++){
NBTTagCompound flagCompound = new NBTTagCompound();
flags.get(i).writeToNBT(flagCompound);
par1NBTTagCompound.setTag("flag"+i, flagCompound);
}
par1NBTTagCompound.setBoolean("hasUpdate", receiveUpdates);
}
@Override
public Packet getDescriptionPacket() {
NBTTagCompound flagCompound = new NBTTagCompound();
writeToNBT(flagCompound);
return new S35PacketUpdateTileEntity(xCoord, yCoord, zCoord, 0, flagCompound);
}
@Override
public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt){
readFromNBT(pkt.func_148857_g());
}
@Override
public void clearFlags() {
flags.clear();
}
@Override
public boolean addFlag(ItemStack flag) {
if(flag.getItem() instanceof HeraldryCrest && flags.size() < MAX_FLAGS){
this.flags.add(flag);
return true;
}
return false;
}
@Override
public List<ItemStack> getFlags() {
return flags;
}
@Override
public float getTextureDimensions(int metadata, int section) {
return ((BlockFlagPole)this.getBlockType()).getTextDim(metadata, section);
}
@Override
public int getOrientation(int metadata) {
return side;
}
@Override
public boolean canUpdate(){
return receiveUpdates;
}
@Override
public void updateEntity() {
if(!getWorldObj().isRemote && canUpdate() && getWorldObj().rand.nextInt(100) == 0){
List entities = getWorldObj().getEntitiesWithinAABB(EntityLivingBase.class, AxisAlignedBB.getBoundingBox(xCoord-3, yCoord, zCoord-3, xCoord + 3, yCoord + 1, zCoord + 3));
if(entities.isEmpty())
spawnUnit();
}
}
public void spawnUnit(){
//getWorldObj().spawnEntityInWorld(new EntityMBUnit(getWorldObj()));
}
}
| gpl-3.0 |
hub187/opensourcedea-lib | branches/testBranch/DeaSolver/UnitTests/tests/LibraryCallExample.java | 5146 | package tests;
import static org.junit.Assert.assertArrayEquals;
//import static org.junit.Assert.assertTrue;
import org.junit.BeforeClass;
import org.junit.Test;
import dea.*;
public class LibraryCallExample {
//Create some array for the DMU and Variable Names, types and the Data Matrix
static String[] TestDMUNames = new String[7];
static String[] TestVariableNames = new String [3];
static DEAVariableType[] TestVariableTypes = new DEAVariableType[3];
static double[] [] TestDataMatrix = new double[7] [3];
@BeforeClass
public static void setUpBeforeClass()
{
//Set up the DMU Names
TestDMUNames[0] = "DMU A";
TestDMUNames[1] = "DMU B";
TestDMUNames[2] = "DMU C";
TestDMUNames[3] = "DMU D";
TestDMUNames[4] = "DMU E";
TestDMUNames[5] = "DMU F";
TestDMUNames[6] = "DMU G";
//Set up the Variable Names
TestVariableNames[0] = "Wood";
TestVariableNames[1] = "Twigs";
TestVariableNames[2] = "Fire";
//Set up the Data Matrix
TestDataMatrix [0] [0] = 4;
TestDataMatrix [0] [1] = 3;
TestDataMatrix [0] [2] = 1;
TestDataMatrix [1] [0] = 7;
TestDataMatrix [1] [1] = 3;
TestDataMatrix [1] [2] = 1;
TestDataMatrix [2] [0] = 8;
TestDataMatrix [2] [1] = 1;
TestDataMatrix [2] [2] = 1;
TestDataMatrix [3] [0] = 4;
TestDataMatrix [3] [1] = 2;
TestDataMatrix [3] [2] = 1;
TestDataMatrix [4] [0] = 2;
TestDataMatrix [4] [1] = 4;
TestDataMatrix [4] [2] = 1;
TestDataMatrix [5] [0] = 10;
TestDataMatrix [5] [1] = 1;
TestDataMatrix [5] [2] = 1;
TestDataMatrix [6] [0] = 3;
TestDataMatrix [6] [1] = 7;
TestDataMatrix [6] [2] = 1;
//Set up the variable types
TestVariableTypes[0] = DEAVariableType.Input;
TestVariableTypes[1] = DEAVariableType.Input;
TestVariableTypes[2] = DEAVariableType.Output;
}
@Test
public void exampleUnitTest() {
//Create a DEAProblem and specify number of DMUs (7) and number of variables (3).
DEAProblem tester = new DEAProblem(7, 3);
//Set the DEA Problem Model Type (CCR).
tester.setModelType(DEAModelType.CCR);
//Set the DEA Problem DMU Names where TestDMUName is a double[].
tester.setDMUNames(TestDMUNames);
//Set the DEA problem Model Orientation (Input Oriented).
tester.setModelOrientation(DEAModelOrientation.InputOriented);
//Set the DEA Problem Variable Names where TestVariableName is a String[].
tester.setVariableNames(TestVariableNames);
//Set the DEA Problem Variable Types where TestVariableType is a DEAVariableType[].
tester.setVariableTypes(TestVariableTypes);
/* Set the DEA Problem Data Matrix where TestDataMatrix is a double[] [].
* Each row of the Matrix corresponds to the DMU in the DMUNames array.
* Each Column of the Matrix corresponds to the Variable in the Variables Arrays.*/
tester.setDataMatrix(TestDataMatrix);
//Solve the DEA Problem
tester.solve();
//Get the solution Objectives
double[] Objectives = tester.getObjectives();
// /* Get the solution Lambdas.
// * The first array corresponds to the DMUs.
// * The second nested array corresponds to the Lambda values.*/
// double[] [] Lambdas = tester.getLambdas();
//
// /* Get the solution Slacks.
// * The first array corresponds to the DMUs.
// * The second nested array corresponds to the Slack values.*/
// double[] [] Slacks = tester.getSlacks();
//
// /* Get the solution Projections.
// * The first array corresponds to the DMUs.
// * The second nested array corresponds to the Projection values.*/
// double[] [] Projections = tester.getProjections();
//
// /* Get the solution Weights.
// * The first array corresponds to the DMUs.
// * The second nested array corresponds to the Weight values.*/
// double[] [] Weights = tester.getWeight();
//
// /* Get the DMU ranks.
// * The boolean confirms that the Highest DMU score is ranked first.
// * The STANDARD ranking type confirms that the ranking is standard.
// * This means that if they are two DMUs with an efficiency score of 1 both will be ranked first.
// * However, the following DMU will only be ranked 3rd as they are two DMUs which score better than it.
// * Conversely, a DENSE RankingType will have given the following (3rd) DMU the ranking of second.*/
// int[] Ranks = tester.getRanks(true, RankingType.STANDARD);
//Get the objective values for the CCR-I model
double[] ObjectivesTarget = getTargetObjectives();
//AssertArrayEquals
assertArrayEquals(Objectives, ObjectivesTarget,0.0000000001);
}
private double[] getTargetObjectives() {
double[] ObjectivesTarget = new double[7];
ObjectivesTarget[0] = 0.8571428571428571;
ObjectivesTarget[1] = 0.6315789473684215;
ObjectivesTarget[2] = 0.9999999999999999;
ObjectivesTarget[3] = 0.9999999999999999;
ObjectivesTarget[4] = 0.9999999999999999;
ObjectivesTarget[5] = 0.9999999999999999;
ObjectivesTarget[6] = 0.6666666666666671;
return ObjectivesTarget;
}
}
| gpl-3.0 |
Distrotech/libreoffice | qadevOOo/tests/java/mod/_sc/ScFunctionDescriptionObj.java | 3720 | /*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
package mod._sc;
import java.io.PrintWriter;
import java.util.Random;
import lib.StatusException;
import lib.TestCase;
import lib.TestEnvironment;
import lib.TestParameters;
import util.SOfficeFactory;
import com.sun.star.container.XNameAccess;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.sheet.XSpreadsheetDocument;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XInterface;
public class ScFunctionDescriptionObj extends TestCase {
private XSpreadsheetDocument xSheetDoc = null;
@Override
protected void initialize( TestParameters tParam, PrintWriter log ) {
SOfficeFactory SOF = SOfficeFactory.getFactory( tParam.getMSF() );
try {
log.println( "creating a Spreadsheet document" );
xSheetDoc = SOF.createCalcDoc(null);
} catch ( com.sun.star.uno.Exception e ) {
// Some exception occurs.FAILED
e.printStackTrace( log );
throw new StatusException( "Couldn't create document", e );
}
}
@Override
protected void cleanup( TestParameters tParam, PrintWriter log ) {
log.println( " disposing xSheetDoc " );
XComponent oComp = UnoRuntime.
queryInterface (XComponent.class, xSheetDoc) ;
util.DesktopTools.closeDoc(oComp);
}
/**
* creating a Testenvironment for the interfaces to be tested
*/
@Override
public synchronized TestEnvironment createTestEnvironment(
TestParameters Param, PrintWriter log )
throws StatusException {
XInterface oObj = null;
// creation of testobject here
// first we write what we are intend to do to log file
log.println( "Creating a test environment" );
try {
log.println("Getting test object ") ;
XMultiServiceFactory oDocMSF = Param.getMSF();
XInterface FDs = (XInterface)oDocMSF.
createInstance("com.sun.star.sheet.FunctionDescriptions");
XNameAccess NA = UnoRuntime.queryInterface
(XNameAccess.class, FDs);
String names[] = NA.getElementNames();
Random rnd = new Random();
int idx = rnd.nextInt(names.length);
oObj = (XInterface)NA.getByName(names[idx]);
log.println("Creating object - " +
((oObj == null) ? "FAILED" : "OK"));
} catch (Exception e) {
e.printStackTrace(log) ;
throw new StatusException
("Error getting test object from spreadsheet document",e) ;
}
TestEnvironment tEnv = new TestEnvironment( oObj );
// Other parameters required for interface tests
return tEnv;
}
}
| gpl-3.0 |
obiba/mica2 | mica-search/src/main/java/org/obiba/mica/search/reports/generators/DatasetVariableDtosCsvReportGenerator.java | 5527 | /*
* Copyright (c) 2018 OBiBa. All rights reserved.
*
* This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.obiba.mica.search.reports.generators;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.obiba.core.translator.Translator;
import org.obiba.mica.web.model.Mica;
import org.obiba.mica.web.model.MicaSearch;
import au.com.bytecode.opencsv.CSVWriter;
public class DatasetVariableDtosCsvReportGenerator extends CsvReportGenerator {
private static final String NOT_EXISTS = "-";
private List<String> columnsToHide;
private List<Mica.DatasetVariableResolverDto> datasetVariableDtos;
private Translator translator;
public DatasetVariableDtosCsvReportGenerator(MicaSearch.JoinQueryResultDto queryResult, List<String> columnsToHide, Translator translator) {
this.columnsToHide = columnsToHide;
this.datasetVariableDtos = queryResult.getVariableResultDto().getExtension(MicaSearch.DatasetVariableResultDto.result).getSummariesList();
this.translator = translator;
}
@Override
protected void writeHeader(CSVWriter writer) {
List<String> line = new ArrayList<>();
line.add("name");
line.add("search.variable.label");
if(mustShow("showVariablesAnnotationsColumn"))
line.add("client.label.variable.annotations");
if (mustShow("showVariablesUnitColumn"))
line.add("client.label.variable.unit");
if (mustShow("showVariablesValueTypeColumn"))
line.add("variable_taxonomy.vocabulary.valueType.title");
if (mustShow("showVariablesCategoriesColumn"))
line.add("client.label.variable.categories");
if (mustShow("showVariablesTypeColumn"))
line.add("type");
if (mustShow("showVariablesStudiesColumn")) {
line.add("search.study.label");
line.add("search.study.population-name");
line.add("search.study.dce-name");
}
if (mustShow("showVariablesDatasetsColumn"))
line.add("search.dataset.label");
String[] translatedLine = line.stream().map(key -> translator.translate(key)).toArray(String[]::new);
writer.writeNext(translatedLine);
}
@Override
protected void writeEachLine(CSVWriter writer) {
for (Mica.DatasetVariableResolverDto datasetVariableDto : datasetVariableDtos) {
List<String> lineContent = generateLineContent(datasetVariableDto);
writer.writeNext(lineContent.toArray(new String[lineContent.size()]));
}
}
private List<String> generateLineContent(Mica.DatasetVariableResolverDto datasetVariableDto) {
List<String> line = new ArrayList<>();
line.add(datasetVariableDto.getName());
line.add(datasetVariableDto.getVariableLabelCount()>0 ? datasetVariableDto.getVariableLabel(0).getValue() : "");
if (mustShow("showVariablesAnnotationsColumn"))
line.add(datasetVariableDto.getAnnotationsList().stream().map(annotationDto -> annotationDto.getTaxonomy() + "::" + annotationDto.getVocabulary() + "::" + annotationDto.getValue()).collect(Collectors.joining(" | ")));
if (mustShow("showVariablesUnitColumn"))
line.add(datasetVariableDto.getUnit());
if (mustShow("showVariablesValueTypeColumn")) {
if (datasetVariableDto.hasValueType())
line.add(translator.translate(
String.format("variable_taxonomy.vocabulary.valueType.term.%s.title", datasetVariableDto.getValueType())));
else line.add("");
}
if (mustShow("showVariablesCategoriesColumn")) {
if (datasetVariableDto.getCategoriesCount()>0)
line.add(datasetVariableDto.getCategoriesList().stream().map(cat -> {
String rval = cat.getName();
Optional<Mica.AttributeDto> lblAttrOpt = cat.getAttributesList().stream().filter(attr -> attr.getName().equals("label")).findFirst();
if (lblAttrOpt.isPresent() && !lblAttrOpt.get().getValuesList().isEmpty()) {
rval = rval + ": " + lblAttrOpt.get().getValuesList().get(0).getValue();
}
return rval;
}).collect(Collectors.joining(" | ")));
else line.add("");
}
if (mustShow("showVariablesTypeColumn"))
line.add(translator.translate(
String.format("variable_taxonomy.vocabulary.variableType.term.%s.title", datasetVariableDto.getVariableType())));
if (mustShow("showVariablesStudiesColumn")) {
line.add(getStudyOrNetworkName(datasetVariableDto));
if (datasetVariableDto.getPopulationNameCount() > 0) line.add(datasetVariableDto.getPopulationName(0).getValue());
else line.add(datasetVariableDto.getPopulationId());
if (datasetVariableDto.getDceNameCount() > 0) line.add(datasetVariableDto.getDceName(0).getValue());
else line.add("");
}
if (mustShow("showVariablesDatasetsColumn"))
line.add(datasetVariableDto.getDatasetAcronym(0).getValue());
return line;
}
private String getStudyOrNetworkName(Mica.DatasetVariableResolverDto datasetVariableDto) {
if (datasetVariableDto.getStudyAcronymCount() > 0)
return datasetVariableDto.getStudyAcronym(0).getValue();
else if (datasetVariableDto.getNetworkAcronymCount() > 0)
return datasetVariableDto.getNetworkAcronym(0).getValue();
else
return NOT_EXISTS;
}
private boolean mustShow(String column) {
return !columnsToHide.contains(column);
}
}
| gpl-3.0 |
imperial-modaclouds/modaclouds-sda-weka | src/main/java/imperial/modaclouds/monitoring/sda/basic/Env.java | 1821 | package imperial.modaclouds.monitoring.sda.basic;
public class Env {
public static final String MODACLOUDS_TOWER4CLOUDS_MANAGER_IP = "MODACLOUDS_TOWER4CLOUDS_MANAGER_IP";
public static final String MODACLOUDS_TOWER4CLOUDS_MANAGER_PORT = "MODACLOUDS_TOWER4CLOUDS_MANAGER_PORT";
public static final String MODACLOUDS_TOWER4CLOUDS_DC_SYNC_PERIOD = "MODACLOUDS_TOWER4CLOUDS_DC_SYNC_PERIOD";
public static final String MODACLOUDS_TOWER4CLOUDS_RESOURCES_KEEP_ALIVE_PERIOD = "MODACLOUDS_TOWER4CLOUDS_RESOURCES_KEEP_ALIVE_PERIOD";
public static final String MODACLOUDS_TOWER4CLOUDS_CLOUD_PROVIDER_ID = "MODACLOUDS_TOWER4CLOUDS_CLOUD_PROVIDER_ID";
public static final String MODACLOUDS_TOWER4CLOUDS_CLOUD_PROVIDER_TYPE = "MODACLOUDS_TOWER4CLOUDS_CLOUD_PROVIDER_TYPE";
public static final String MODACLOUDS_TOWER4CLOUDS_PAAS_SERVICE_ID = "MODACLOUDS_TOWER4CLOUDS_PAAS_SERVICE_ID";
public static final String MODACLOUDS_TOWER4CLOUDS_PAAS_SERVICE_TYPE = "MODACLOUDS_TOWER4CLOUDS_PAAS_SERVICE_TYPE";
public static final String MODACLOUDS_TOWER4CLOUDS_VM_ID = "MODACLOUDS_TOWER4CLOUDS_VM_ID";
public static final String MODACLOUDS_TOWER4CLOUDS_VM_TYPE = "MODACLOUDS_TOWER4CLOUDS_VM_TYPE";
public static final String MODACLOUDS_TOWER4CLOUDS_LOCATION_ID = "MODACLOUDS_TOWER4CLOUDS_LOCATION_ID";
public static final String MODACLOUDS_TOWER4CLOUDS_LOCATION_TYPE = "MODACLOUDS_TOWER4CLOUDS_LOCATION_TYPE";
public static final String MODACLOUDS_TOWER4CLOUDS_INTERNAL_COMPONENT_ID = "MODACLOUDS_TOWER4CLOUDS_INTERNAL_COMPONENT_ID";
public static final String MODACLOUDS_TOWER4CLOUDS_INTERNAL_COMPONENT_TYPE = "MODACLOUDS_TOWER4CLOUDS_INTERNAL_COMPONENT_TYPE";
public static final String MODACLOUDS_JAVA_SDA_IP = "MODACLOUDS_JAVA_SDA_IP";
public static final String MODACLOUDS_JAVA_SDA_PORT = "MODACLOUDS_JAVA_SDA_PORT";
}
| gpl-3.0 |
JupiterDevelopmentTeam/JupiterDevelopmentTeam | src/main/java/cn/nukkit/Server.java | 103621 | package cn.nukkit;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import com.google.common.base.Preconditions;
import cn.nukkit.ai.AI;
import cn.nukkit.block.Block;
import cn.nukkit.blockentity.BlockEntity;
import cn.nukkit.blockentity.BlockEntityBanner;
import cn.nukkit.blockentity.BlockEntityBeacon;
import cn.nukkit.blockentity.BlockEntityBrewingStand;
import cn.nukkit.blockentity.BlockEntityCauldron;
import cn.nukkit.blockentity.BlockEntityChest;
import cn.nukkit.blockentity.BlockEntityCommandBlock;
import cn.nukkit.blockentity.BlockEntityDispenser;
import cn.nukkit.blockentity.BlockEntityDropper;
import cn.nukkit.blockentity.BlockEntityEnchantTable;
import cn.nukkit.blockentity.BlockEntityEnderChest;
import cn.nukkit.blockentity.BlockEntityFlowerPot;
import cn.nukkit.blockentity.BlockEntityFurnace;
import cn.nukkit.blockentity.BlockEntityItemFrame;
import cn.nukkit.blockentity.BlockEntityMobSpawner;
import cn.nukkit.blockentity.BlockEntityShulkerBox;
import cn.nukkit.blockentity.BlockEntitySign;
import cn.nukkit.blockentity.BlockEntitySkull;
import cn.nukkit.command.Command;
import cn.nukkit.command.CommandReader;
import cn.nukkit.command.CommandSender;
import cn.nukkit.command.ConsoleCommandSender;
import cn.nukkit.command.PluginIdentifiableCommand;
import cn.nukkit.command.SimpleCommandMap;
import cn.nukkit.entity.Attribute;
import cn.nukkit.entity.Entity;
import cn.nukkit.entity.EntityHuman;
import cn.nukkit.entity.data.Skin;
import cn.nukkit.entity.item.EntityArmorStand;
import cn.nukkit.entity.item.EntityBoat;
import cn.nukkit.entity.item.EntityEnderCrystal;
import cn.nukkit.entity.item.EntityFallingBlock;
import cn.nukkit.entity.item.EntityMinecartChest;
import cn.nukkit.entity.item.EntityMinecartEmpty;
import cn.nukkit.entity.item.EntityMinecartHopper;
import cn.nukkit.entity.item.EntityMinecartTNT;
import cn.nukkit.entity.item.EntityPainting;
import cn.nukkit.entity.item.EntityPrimedTNT;
import cn.nukkit.entity.item.EntityXPOrb;
import cn.nukkit.entity.mob.EntityBlaze;
import cn.nukkit.entity.mob.EntityCaveSpider;
import cn.nukkit.entity.mob.EntityCreeper;
import cn.nukkit.entity.mob.EntityElderGuardian;
import cn.nukkit.entity.mob.EntityEnderDragon;
import cn.nukkit.entity.mob.EntityEnderman;
import cn.nukkit.entity.mob.EntityEndermite;
import cn.nukkit.entity.mob.EntityEvoker;
import cn.nukkit.entity.mob.EntityGhast;
import cn.nukkit.entity.mob.EntityGuardian;
import cn.nukkit.entity.mob.EntityHask;
import cn.nukkit.entity.mob.EntityMagmaCube;
import cn.nukkit.entity.mob.EntityShulker;
import cn.nukkit.entity.mob.EntitySilverfish;
import cn.nukkit.entity.mob.EntitySkeleton;
import cn.nukkit.entity.mob.EntitySlime;
import cn.nukkit.entity.mob.EntitySpider;
import cn.nukkit.entity.mob.EntityStray;
import cn.nukkit.entity.mob.EntityVex;
import cn.nukkit.entity.mob.EntityVindicator;
import cn.nukkit.entity.mob.EntityWitch;
import cn.nukkit.entity.mob.EntityWither;
import cn.nukkit.entity.mob.EntityWitherSkeleton;
import cn.nukkit.entity.mob.EntityZombie;
import cn.nukkit.entity.mob.EntityZombiePigman;
import cn.nukkit.entity.mob.EntityZombieVillager;
import cn.nukkit.entity.passive.EntityBat;
import cn.nukkit.entity.passive.EntityChicken;
import cn.nukkit.entity.passive.EntityCow;
import cn.nukkit.entity.passive.EntityDonkey;
import cn.nukkit.entity.passive.EntityHorse;
import cn.nukkit.entity.passive.EntityIronGolem;
import cn.nukkit.entity.passive.EntityLlama;
import cn.nukkit.entity.passive.EntityMooshroom;
import cn.nukkit.entity.passive.EntityMule;
import cn.nukkit.entity.passive.EntityOcelot;
import cn.nukkit.entity.passive.EntityParrot;
import cn.nukkit.entity.passive.EntityPig;
import cn.nukkit.entity.passive.EntityPolarBear;
import cn.nukkit.entity.passive.EntityRabbit;
import cn.nukkit.entity.passive.EntitySheep;
import cn.nukkit.entity.passive.EntitySkeletonHorse;
import cn.nukkit.entity.passive.EntitySnowGolem;
import cn.nukkit.entity.passive.EntitySquid;
import cn.nukkit.entity.passive.EntityVillager;
import cn.nukkit.entity.passive.EntityWolf;
import cn.nukkit.entity.passive.EntityZombieHorse;
import cn.nukkit.entity.projectile.EntityArrow;
import cn.nukkit.entity.projectile.EntityDragonFireball;
import cn.nukkit.entity.projectile.EntityEgg;
import cn.nukkit.entity.projectile.EntityEnderPearl;
import cn.nukkit.entity.projectile.EntityExpBottle;
import cn.nukkit.entity.projectile.EntityFireball;
import cn.nukkit.entity.projectile.EntityFireworkRocket;
import cn.nukkit.entity.projectile.EntityFishingHook;
import cn.nukkit.entity.projectile.EntityPotion;
import cn.nukkit.entity.projectile.EntityPotionLingering;
import cn.nukkit.entity.projectile.EntityShulkerBullet;
import cn.nukkit.entity.projectile.EntitySnowball;
import cn.nukkit.entity.weather.EntityLightning;
import cn.nukkit.event.HandlerList;
import cn.nukkit.event.level.LevelInitEvent;
import cn.nukkit.event.level.LevelLoadEvent;
import cn.nukkit.event.server.QueryRegenerateEvent;
import cn.nukkit.inventory.CraftingManager;
import cn.nukkit.inventory.FurnaceRecipe;
import cn.nukkit.inventory.Recipe;
import cn.nukkit.inventory.ShapedRecipe;
import cn.nukkit.inventory.ShapelessRecipe;
import cn.nukkit.item.Item;
import cn.nukkit.item.enchantment.Enchantment;
import cn.nukkit.lang.BaseLang;
import cn.nukkit.lang.TextContainer;
import cn.nukkit.level.Level;
import cn.nukkit.level.Position;
import cn.nukkit.level.format.LevelProvider;
import cn.nukkit.level.format.LevelProviderManager;
import cn.nukkit.level.format.anvil.Anvil;
import cn.nukkit.level.format.leveldb.LevelDB;
import cn.nukkit.level.format.mcregion.McRegion;
import cn.nukkit.level.generator.Flat;
import cn.nukkit.level.generator.Generator;
import cn.nukkit.level.generator.Nether;
import cn.nukkit.level.generator.Normal;
import cn.nukkit.level.generator.biome.Biome;
import cn.nukkit.math.NukkitMath;
import cn.nukkit.metadata.EntityMetadataStore;
import cn.nukkit.metadata.LevelMetadataStore;
import cn.nukkit.metadata.PlayerMetadataStore;
import cn.nukkit.nbt.NBTIO;
import cn.nukkit.nbt.tag.CompoundTag;
import cn.nukkit.nbt.tag.DoubleTag;
import cn.nukkit.nbt.tag.FloatTag;
import cn.nukkit.nbt.tag.ListTag;
import cn.nukkit.network.CompressBatchedTask;
import cn.nukkit.network.Network;
import cn.nukkit.network.RakNetInterface;
import cn.nukkit.network.SourceInterface;
import cn.nukkit.network.protocol.BatchPacket;
import cn.nukkit.network.protocol.CraftingDataPacket;
import cn.nukkit.network.protocol.DataPacket;
import cn.nukkit.network.protocol.PlayerListPacket;
import cn.nukkit.network.protocol.ProtocolInfo;
import cn.nukkit.network.query.QueryHandler;
import cn.nukkit.network.rcon.RCON;
import cn.nukkit.permission.BanEntry;
import cn.nukkit.permission.BanList;
import cn.nukkit.permission.DefaultPermissions;
import cn.nukkit.permission.Permissible;
import cn.nukkit.plugin.JavaPluginLoader;
import cn.nukkit.plugin.Plugin;
import cn.nukkit.plugin.PluginCompiler;
import cn.nukkit.plugin.PluginLoadOrder;
import cn.nukkit.plugin.PluginManager;
import cn.nukkit.plugin.service.NKServiceManager;
import cn.nukkit.plugin.service.ServiceManager;
import cn.nukkit.potion.Effect;
import cn.nukkit.potion.Potion;
import cn.nukkit.resourcepacks.ResourcePackManager;
import cn.nukkit.scheduler.FileWriteTask;
import cn.nukkit.scheduler.ServerScheduler;
import cn.nukkit.utils.Binary;
import cn.nukkit.utils.Config;
import cn.nukkit.utils.ConfigSection;
import cn.nukkit.utils.FastAppender;
import cn.nukkit.utils.LevelException;
import cn.nukkit.utils.MainLogger;
import cn.nukkit.utils.ServerException;
import cn.nukkit.utils.ServerKiller;
import cn.nukkit.utils.TextFormat;
import cn.nukkit.utils.Utils;
import cn.nukkit.utils.Zlib;
import cn.nukkit.window.ServerSettingsWindow;
import co.aikar.timings.Timings;
/**
* @author MagicDroidX
* @author Box
*/
public class Server {
public static final String BROADCAST_CHANNEL_ADMINISTRATIVE = "nukkit.broadcast.admin";
public static final String BROADCAST_CHANNEL_USERS = "nukkit.broadcast.user";
private static Server instance = null;
private AI ai = null;
private BanList banByName = null;
private BanList banByIP = null;
private Config operators = null;
private Config whitelist = null;
private boolean isRunning = true;
private boolean hasStopped = false;
private PluginManager pluginManager = null;
private int profilingTickrate = 20;
private ServerScheduler scheduler = null;
private int tickCounter;
private long nextTick;
private final float[] tickAverage = {20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20};
private final float[] useAverage = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
private float maxTick = 20;
private float maxUse = 0;
private int sendUsageTicker = 0;
private boolean dispatchSignals = false;
private final MainLogger logger;
private final CommandReader console;
private SimpleCommandMap commandMap;
private CraftingManager craftingManager;
private ResourcePackManager resourcePackManager;
private ConsoleCommandSender consoleSender;
private int maxPlayers;
private boolean autoSave;
private RCON rcon;
private EntityMetadataStore entityMetadata;
private PlayerMetadataStore playerMetadata;
private LevelMetadataStore levelMetadata;
private Network network;
private boolean networkCompressionAsync = true;
public int networkCompressionLevel = 7;
private boolean autoTickRate = true;
private int autoTickRateLimit = 20;
private boolean alwaysTickPlayers = false;
private int baseTickRate = 1;
private Boolean getAllowFlight = null;
private int autoSaveTicker = 0;
private int autoSaveTicks = 6000;
private BaseLang baseLang;
private boolean forceLanguage = false;
private UUID serverID;
private final String filePath;
private final String dataPath;
private final String pluginPath;
private String defaultplugin = null;
private final Set<UUID> uniquePlayers = new HashSet<>();
private QueryHandler queryHandler;
private QueryRegenerateEvent queryRegenerateEvent;
private Config properties;
private Config config;
private final Map<String, Player> players = new HashMap<>();
private final Map<UUID, Player> playerList = new HashMap<>();
private final Map<Integer, String> identifier = new HashMap<>();
private final Map<Integer, Level> levels = new HashMap<>();
private final ServiceManager serviceManager = new NKServiceManager();
private Level defaultLevel = null;
private Thread currentThread;
private Map<String, Object> jupiterconfig;
private List<Player> loggedInPlayers = new ArrayList<>();
private LinkedHashMap<Integer, ServerSettingsWindow> defaultServerSettings = new LinkedHashMap<>();
private boolean printPackets = false;
@SuppressWarnings("unchecked")
Server(MainLogger logger, final String filePath, String dataPath, String pluginPath) {
Preconditions.checkState(instance == null, "Already initialized!");
currentThread = Thread.currentThread(); // Saves the current thread instance as a reference, used in Server#isPrimaryThread()
instance = this;
this.logger = logger;
this.console = new CommandReader();
this.logger.info("");
this.logger.info(FastAppender.get(TextFormat.BLUE, "Jupiter", TextFormat.WHITE, " by JupiterDevelopmentTeam"));
this.logger.info("");
this.logger.info("");
this.filePath = filePath;
if (!new File(dataPath + "worlds/").exists()) {
new File(dataPath + "worlds/").mkdirs();
this.logger.info(FastAppender.get(TextFormat.AQUA, dataPath, "worlds/ を作成しました。"));
}
if (!new File(dataPath + "players/").exists()) {
new File(dataPath + "players/").mkdirs();
this.logger.info(FastAppender.get(TextFormat.AQUA, dataPath, "players/ を作成しました。"));
}
if (!new File(pluginPath).exists()) {
new File(pluginPath).mkdirs();
this.logger.info(FastAppender.get(TextFormat.AQUA, dataPath, "plugins/ を作成しました。"));
}
if (!new File(pluginPath).exists()) {
new File(pluginPath).mkdirs();
this.logger.info(FastAppender.get(TextFormat.AQUA, pluginPath, " を作成しました。"));
}
if (!new File(dataPath + "unpackedPlugins/").exists()) {
new File(dataPath + "unpackedPlugins/").mkdirs();
this.logger.info(FastAppender.get(TextFormat.AQUA, pluginPath, "unpackedPlugins/ を作成しました。"));
}
if (!new File(dataPath + "compileOrder/").exists()) {
new File(dataPath + "compileOrder/").mkdirs();
this.logger.info(FastAppender.get(TextFormat.AQUA, pluginPath, "compileOrder/ を作成しました。"));
}
if (!new File(dataPath + "makeOrder/").exists()) {
new File(dataPath + "makeOrder/").mkdirs();
this.logger.info(FastAppender.get(TextFormat.AQUA, pluginPath, "makeOrder/ を作成しました。"));
}
this.dataPath = new File(dataPath).getAbsolutePath() + "/";
this.pluginPath = new File(pluginPath).getAbsolutePath() + "/";
if (!new File(this.dataPath + "nukkit.yml").exists()) {
this.getLogger().info(FastAppender.get(TextFormat.GREEN, "ようこそ。言語を選択してください。"));
try {
String[] lines = Utils.readFile(this.getClass().getClassLoader().getResourceAsStream("lang/language.list")).split("\n");
for (String line : lines) {
this.logger.info(line);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
String fallback = BaseLang.FALLBACK_LANGUAGE;
String language = null;
while (language == null) {
String lang = this.console.readLine();
InputStream conf = this.getClass().getClassLoader().getResourceAsStream("lang/" + lang + "/lang.ini");
if (conf != null) {
language = lang;
}
}
InputStream advacedConf = this.getClass().getClassLoader().getResourceAsStream("lang/" + language + "/nukkit.yml");
if (advacedConf == null) {
advacedConf = this.getClass().getClassLoader().getResourceAsStream("lang/" + fallback + "/nukkit.yml");
}
try {
Utils.writeFile(this.dataPath + "nukkit.yml", advacedConf);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
this.console.start();
this.logger.info(FastAppender.get(TextFormat.GREEN, "nukkit.yml", TextFormat.WHITE, "を読み込んでいます..."));
this.config = new Config(this.dataPath + "nukkit.yml", Config.YAML);
this.logger.info(FastAppender.get(TextFormat.GREEN, "server.properties", TextFormat.WHITE, "を読み込んでいます..."));
this.properties = new Config(this.dataPath + "server.properties", Config.PROPERTIES, new ConfigSection() {
{
put("motd", "Jupiter Server For Minecraft: BE");
put("sub-motd", "Powered by Jupiter");
put("server-port", 19132);
put("server-ip", "0.0.0.0");
put("view-distance", 10);
put("white-list", false);
put("achievements", true);
put("announce-player-achievements", true);
put("spawn-protection", 16);
put("max-players", 20);
put("allow-flight", false);
put("spawn-animals", true);
put("spawn-mobs", true);
put("gamemode", 0);
put("force-gamemode", false);
put("hardcore", false);
put("pvp", true);
put("difficulty", 1);
put("generator-settings", "");
put("level-name", "world");
put("level-seed", "");
put("level-type", "DEFAULT");
put("enable-query", true);
put("enable-rcon", false);
put("rcon.password", Base64.getEncoder().encodeToString(UUID.randomUUID().toString().replace("-", "").getBytes()).substring(3, 13));
put("auto-save", true);
put("force-resources", false);
}
});
this.logger.info(FastAppender.get(TextFormat.GREEN, "jupiter.yml", TextFormat.WHITE, "を読み込んでいます..."));
if (!new File(this.dataPath + "jupiter.yml").exists()) {
BufferedInputStream advacedConf = new BufferedInputStream(this.getClass().getClassLoader().getResourceAsStream("lang/jpn/jupiter.yml"));
try {
Utils.writeFile(this.dataPath + "jupiter.yml", advacedConf);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
this.loadJupiterConfig();
/*
if(this.getJupiterConfigBoolean("destroy-block-particle")){
Level.sendDestroyParticle = true;
}else{
Level.sendDestroyParticle = false;
}
*/
this.forceLanguage = (Boolean) this.getConfig("settings.force-language", false);
this.baseLang = new BaseLang((String) this.getConfig("settings.language", BaseLang.FALLBACK_LANGUAGE));
this.logger.info(this.getLanguage().translateString("language.selected", new String[]{getLanguage().getName(), getLanguage().getLang()}));
this.logger.info(this.getLanguage().translateString("nukkit.server.start", FastAppender.get(TextFormat.AQUA, this.getVersion(), TextFormat.WHITE)));
Object poolSize = this.getConfig("settings.async-workers", "auto");
if (!(poolSize instanceof Integer)) {
try {
poolSize = Integer.valueOf((String) poolSize);
} catch (Exception e) {
poolSize = Math.max(Runtime.getRuntime().availableProcessors() + 1, 4);
}
}
ServerScheduler.WORKERS = (int) poolSize;
this.networkCompressionLevel = (int) this.getConfig("network.compression-level", 7);
this.networkCompressionAsync = (boolean) this.getConfig("network.async-compression", true);
this.networkCompressionLevel = (int) this.getConfig("network.compression-level", 7);
this.networkCompressionAsync = (boolean) this.getConfig("network.async-compression", true);
this.autoTickRate = (boolean) this.getConfig("level-settings.auto-tick-rate", true);
this.autoTickRateLimit = (int) this.getConfig("level-settings.auto-tick-rate-limit", 20);
this.alwaysTickPlayers = (boolean) this.getConfig("level-settings.always-tick-players", false);
this.baseTickRate = (int) this.getConfig("level-settings.base-tick-rate", 1);
this.scheduler = new ServerScheduler();
if (this.getPropertyBoolean("enable-rcon", false)) {
this.rcon = new RCON(this, this.getPropertyString("rcon.password", ""), (!this.getIp().equals("")) ? this.getIp() : "0.0.0.0", this.getPropertyInt("rcon.port", this.getPort()));
}
this.entityMetadata = new EntityMetadataStore();
this.playerMetadata = new PlayerMetadataStore();
this.levelMetadata = new LevelMetadataStore();
this.operators = new Config(this.dataPath + "ops.txt", Config.ENUM);
this.whitelist = new Config(this.dataPath + "white-list.txt", Config.ENUM);
this.banByName = new BanList(this.dataPath + "banned-players.json");
this.banByName.load();
this.banByIP = new BanList(this.dataPath + "banned-ips.json");
this.banByIP.load();
this.maxPlayers = this.getPropertyInt("max-players", 20);
this.setAutoSave(this.getPropertyBoolean("auto-save", true));
if (this.getPropertyBoolean("hardcore", false) && this.getDifficulty() < 3) {
this.setPropertyInt("difficulty", 3);
}
Nukkit.DEBUG = (int) this.getConfig("debug.level", 1);
if (this.logger instanceof MainLogger) {
this.logger.setLogDebug(Nukkit.DEBUG > 1);
}
this.logger.info(this.getLanguage().translateString("nukkit.server.networkStart", new String[]{this.getIp().equals("") ? "*" : this.getIp(), String.valueOf(this.getPort())}));
this.serverID = UUID.randomUUID();
this.network = new Network(this);
this.network.setName(this.getMotd());
this.network.setSubName(this.getSubMotd());
this.logger.info(this.getLanguage().translateString("nukkit.server.license", this.getName()));
this.consoleSender = new ConsoleCommandSender();
this.commandMap = new SimpleCommandMap(this);
this.registerEntities();
this.registerBlockEntities();
Block.init();
Enchantment.init();
Item.init();
Biome.init();
Effect.init();
Potion.init();
Attribute.init();
/* TODO AI
this.ai = new AI(this);
ai.initAI();
*/
this.craftingManager = new CraftingManager();
this.resourcePackManager = new ResourcePackManager(new File(Nukkit.DATA_PATH, "resource_packs"));
this.pluginManager = new PluginManager(this, this.commandMap);
this.pluginManager.subscribeToPermission(Server.BROADCAST_CHANNEL_ADMINISTRATIVE, this.consoleSender);
this.pluginManager.registerInterface(JavaPluginLoader.class);
this.queryRegenerateEvent = new QueryRegenerateEvent(this, 5);
this.network.registerInterface(new RakNetInterface(this));
this.printPackets = this.getJupiterConfigBoolean("print-packets");
Calendar now = Calendar.getInstance();
int y = now.get(Calendar.YEAR);
int mo = now.get(Calendar.MONTH) + 1;
int d = now.get(Calendar.DATE);
int h = now.get(Calendar.HOUR_OF_DAY);
int m = now.get(Calendar.MINUTE);
int s = now.get(Calendar.SECOND);
this.logger.info("");
this.logger.info(FastAppender.get("日時: \t\t\t", TextFormat.BLUE, y, "/", mo, "/", d, " ", h, "時", m, "分", s, "秒"));
this.logger.info(FastAppender.get("サーバー名: \t\t", TextFormat.GREEN, this.getMotd()));
this.logger.info(FastAppender.get("IP: \t\t\t", TextFormat.GREEN, this.getIp()));
this.logger.info(FastAppender.get("ポート: \t\t", TextFormat.GREEN, this.getPort()));
this.logger.info(FastAppender.get("Jupiterバージョン: \t", TextFormat.GREEN, this.getJupiterVersion()));
this.logger.info(FastAppender.get("Nukkitバージョン: \t", TextFormat.GREEN, this.getNukkitVersion()));
this.logger.info(FastAppender.get("APIバージョン: \t", TextFormat.GREEN, this.getApiVersion()));
this.logger.info(FastAppender.get("コードネーム: \t\t", TextFormat.GREEN, this.getCodename()));
this.logger.info("");
if(this.getJupiterConfigBoolean("jupiter-compiler-mode")){
this.logger.info(FastAppender.get(TextFormat.AQUA, "コンパイルしています..."));
File f = new File(dataPath + "compileOrder/");
File[] list = f.listFiles();
int len = list.length;
for(int i = 0; i < len; i++){
if(new PluginCompiler().Compile(list[i]))
this.logger.info(FastAppender.get(list[i].toPath().toString(), " :", TextFormat.GREEN, "完了"));
else
this.logger.info(FastAppender.get(list[i].toPath().toString(), " :", TextFormat.RED, "失敗"));
}
this.logger.info("");
}
this.logger.info(FastAppender.get(TextFormat.AQUA, "プラグインを読み込んでいます..."));
this.pluginManager.loadPlugins(this.pluginPath);
this.enablePlugins(PluginLoadOrder.STARTUP);
this.logger.info("");
LevelProviderManager.addProvider(this, Anvil.class);
LevelProviderManager.addProvider(this, McRegion.class);
LevelProviderManager.addProvider(this, LevelDB.class);
Generator.addGenerator(Flat.class, "flat", Generator.TYPE_FLAT);
Generator.addGenerator(Normal.class, "normal", Generator.TYPE_INFINITE);
Generator.addGenerator(Normal.class, "default", Generator.TYPE_INFINITE);
Generator.addGenerator(Nether.class, "nether", Generator.TYPE_NETHER);
//todo: add old generator and hell generator
for (String name : ((Map<String, Object>) this.getConfig("worlds", new HashMap<>())).keySet()) {
if (!this.loadLevel(name)) {
long seed;
try {
seed = ((Integer) this.getConfig(FastAppender.get("worlds.", name, ".seed"))).longValue();
} catch (Exception e) {
seed = System.currentTimeMillis();
}
Map<String, Object> options = new HashMap<>();
String[] opts = ((String) this.getConfig(FastAppender.get("worlds.", name, ".generator"), Generator.getGenerator("default").getSimpleName())).split(":");
Class<? extends Generator> generator = Generator.getGenerator(opts[0]);
int len = opts.length;
if (len > 1) {
String preset = "";
for (int i = 1; i < len; i++) {
preset += opts[i] + ":";
}
preset = preset.substring(0, preset.length() - 1);
options.put("preset", preset);
}
this.generateLevel(name, seed, generator, options);
}
}
try {
this.getDefaultLevel().getName();
}catch (NullPointerException ex) {
String defaultName = this.getPropertyString("level-name", "world");
if (defaultName == null || "".equals(defaultName.trim())) {
this.logger.warning("level-name cannot be null, using default");
defaultName = "world";
this.setPropertyString("level-name", defaultName);
}
if (!this.loadLevel(defaultName)) {
long seed;
String seedString = String.valueOf(this.getProperty("level-seed", System.currentTimeMillis()));
try {
seed = Long.valueOf(seedString);
} catch (NumberFormatException e) {
seed = seedString.hashCode();
}
this.generateLevel(defaultName, seed == 0 ? System.currentTimeMillis() : seed);
}
this.setDefaultLevel(this.getLevelByName(defaultName));
}
this.properties.save(true);
try{
this.getDefaultLevel().getName();
}catch (NullPointerException e) {
this.logger.emergency(this.getLanguage().translateString("nukkit.level.defaultError"));
this.forceShutdown();
return;
}
if ((int) this.getConfig("ticks-per.autosave", 6000) > 0) {
this.autoSaveTicks = (int) this.getConfig("ticks-per.autosave", 6000);
}
this.logger.info("");
this.enablePlugins(PluginLoadOrder.POSTWORLD);
this.logger.info("");
this.start();
}
/**
* サーバーにいる人全員にメッセージを送ります。
* <br>ミュート状態では表示されません。
* (ミュート状態...isMuted()の戻り値)
* @see "ミュート状態でも表示したい場合"
* @see Player#sendImportantMessage(String) sendImportantMessage
* @see Player#isMuted() isMuted()
* @param message 送る文
* @return int
*/
public int broadcastMessage(String message) {
return this.broadcast(message, BROADCAST_CHANNEL_USERS);
}
/**
* サーバーにいる人全員にメッセージを送ります。
* <br>ミュート状態では表示されません。
* (ミュート状態...isMuted()の戻り値)
* @see "ミュート状態でも表示したい場合"
* @see Player#sendImportantMessage(String) sendImportantMessage
* @see Player#isMuted() isMuted()
* @param message 送る文
* @return int
*/
public int broadcastMessage(TextContainer message) {
return this.broadcast(message, BROADCAST_CHANNEL_USERS);
}
public int broadcastMessage(String message, CommandSender[] recipients) {
for (CommandSender recipient : recipients) {
recipient.sendMessage(message);
}
return recipients.length;
}
public int broadcastMessage(String message, Collection<CommandSender> recipients) {
for (CommandSender recipient : recipients) {
recipient.sendMessage(message);
}
return recipients.size();
}
public int broadcastMessage(TextContainer message, Collection<CommandSender> recipients) {
for (CommandSender recipient : recipients) {
recipient.sendMessage(message);
}
return recipients.size();
}
/**
* サーバーにいる人全員にポップアップを送ります。
* <br>ミュート状態では表示されません。
* (ミュート状態...isMuted()の戻り値)
* @param message 送る文
* @return int
*/
public int broadcastPopup(String message) {
return this.broadcastPopup(message, BROADCAST_CHANNEL_USERS);
}
/**
* サーバーにいる人全員にチップを送ります。
* <br>ミュート状態では表示されません。
* @param message 送る文
* @return int
*/
public int broadcastTip(String message) {
return this.broadcastPopup(message, BROADCAST_CHANNEL_USERS);
}
/**
* サーバーにいる人全員にタイトルを送ります。
* <br>ミュート状態では表示されません。
* @param message 送るタイトル
* @return int
*/
public int broadcastTitle(String message) {
return this.broadcastTitle(message, BROADCAST_CHANNEL_USERS);
}
/**
* サーバーにいる人全員にメサブタイトルを送ります。
* <br>ミュート状態では表示されません。
* @param message 送る文
* @return int
*/
public int broadcastSubtitle(String message) {
return this.broadcastSubtitle(message, BROADCAST_CHANNEL_USERS);
}
/**
* サーバーにいる人全員にメッセージを送ります。
* <br>ミュート状態でも表示されます。
* (ミュート状態...isMuted()の戻り値)
* @see Player#isMuted() isMuted()
* @param message 送る文
* @return int
* @author Itsu
*/
public int broadcastImportantMessage(String message) {
return this.broadcastImportantMessage(message, BROADCAST_CHANNEL_USERS);
}
public int broadcast(String message, String permissions) {
Set<CommandSender> recipients = new HashSet<>();
for (String permission : permissions.split(";")) {
for (Permissible permissible : this.pluginManager.getPermissionSubscriptions(permission)) {
if (permissible instanceof CommandSender && permissible.hasPermission(permission)) {
recipients.add((CommandSender) permissible);
}
}
}
for (CommandSender recipient : recipients) {
recipient.sendMessage(message);
}
return recipients.size();
}
public int broadcast(TextContainer message, String permissions) {
Set<CommandSender> recipients = new HashSet<>();
for (String permission : permissions.split(";")) {
for (Permissible permissible : this.pluginManager.getPermissionSubscriptions(permission)) {
if (permissible instanceof CommandSender && permissible.hasPermission(permission)) {
recipients.add((CommandSender) permissible);
}
}
}
for (CommandSender recipient : recipients) {
recipient.sendMessage(message);
}
return recipients.size();
}
public int broadcastPopup(String message, String permissions) {
Set<Player> recipients = new HashSet<>();
for (String permission : permissions.split(";")) {
for (Permissible permissible : this.pluginManager.getPermissionSubscriptions(permission)) {
if (permissible instanceof Player && permissible.hasPermission(permission)) {
recipients.add((Player) permissible);
}
}
}
for (Player recipient : recipients) {
recipient.sendPopup(message);
}
return recipients.size();
}
public int broadcastTip(String message, String permissions) {
Set<Player> recipients = new HashSet<>();
for (String permission : permissions.split(";")) {
for (Permissible permissible : this.pluginManager.getPermissionSubscriptions(permission)) {
if (permissible instanceof Player && permissible.hasPermission(permission)) {
recipients.add((Player) permissible);
}
}
}
for (Player recipient : recipients) {
recipient.sendTip(message);
}
return recipients.size();
}
public int broadcastTitle(String message, String permissions) {
Set<Player> recipients = new HashSet<>();
for (String permission : permissions.split(";")) {
for (Permissible permissible : this.pluginManager.getPermissionSubscriptions(permission)) {
if (permissible instanceof Player && permissible.hasPermission(permission)) {
recipients.add((Player) permissible);
}
}
}
for (Player recipient : recipients) {
recipient.sendTitle(message);
}
return recipients.size();
}
public int broadcastSubtitle(String message, String permissions) {
Set<Player> recipients = new HashSet<>();
for (String permission : permissions.split(";")) {
for (Permissible permissible : this.pluginManager.getPermissionSubscriptions(permission)) {
if (permissible instanceof Player && permissible.hasPermission(permission)) {
recipients.add((Player) permissible);
}
}
}
for (Player recipient : recipients) {
recipient.setSubtitle(message);
}
return recipients.size();
}
public int broadcastImportantMessage(String message, String permissions) {
Set<CommandSender> recipients = new HashSet<>();
for (String permission : permissions.split(";")) {
for (Permissible permissible : this.pluginManager.getPermissionSubscriptions(permission)) {
if (permissible instanceof CommandSender && permissible.hasPermission(permission)) {
recipients.add((CommandSender) permissible);
}
}
}
for (CommandSender recipient : recipients) {
recipient.sendImportantMessage(message);
}
return recipients.size();
}
/**
* サーバーにいる人全員にパケットを送ります。
* @param players プレイヤー
* @param packet 送るパケット
* @return void
*/
public static void broadcastPacket(Collection<Player> players, DataPacket packet) {
broadcastPacket(players.stream().toArray(Player[]::new), packet);
}
/**
* サーバーにいる人全員にパケットを送ります。
* @param players プレイヤー
* @param packet 送るパケット
* @return void
*/
public static void broadcastPacket(Player[] players, DataPacket packet) {
packet.encode();
packet.isEncoded = true;
for (Player player : players) {
player.dataPacket(packet);
}
if (packet.encapsulatedPacket != null) {
packet.encapsulatedPacket = null;
}
}
public void batchPackets(Player[] players, DataPacket[] packets) {
this.batchPackets(players, packets, false);
}
public void batchPackets(Player[] players, DataPacket[] packets, boolean forceSync) {
if (players == null || packets == null || players.length == 0 || packets.length == 0) {
return;
}
Timings.playerNetworkSendTimer.startTiming();
byte[][] payload = new byte[packets.length * 2][];
for (int i = 0; i < packets.length; i++) {
DataPacket p = packets[i];
if (!p.isEncoded) {
p.encode();
}
byte[] buf = p.getBuffer();
payload[i * 2] = Binary.writeUnsignedVarInt(buf.length);
payload[i * 2 + 1] = buf;
}
byte[] data;
data = Binary.appendBytes(payload);
List<String> targets = new ArrayList<>();
for (Player p : players) {
if (p.isConnected()) {
targets.add(this.identifier.get(p.rawHashCode()));
}
}
if (!forceSync && this.networkCompressionAsync) {
this.getScheduler().scheduleAsyncTask(new CompressBatchedTask(data, targets, this.networkCompressionLevel));
} else {
try {
this.broadcastPacketsCallback(Zlib.deflate(data, this.networkCompressionLevel), targets);
//this.broadcastPacketsCallback(data, targets); 非圧縮
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Timings.playerNetworkSendTimer.stopTiming();
}
public void broadcastPacketsCallback(byte[] data, List<String> identifiers) {
BatchPacket pk = new BatchPacket();
pk.payload = data;
for (String i : identifiers) {
if (this.players.containsKey(i)) {
this.players.get(i).dataPacket(pk);
}
}
}
public void enablePlugins(PluginLoadOrder type) {
for (Plugin plugin : new ArrayList<>(this.pluginManager.getPlugins().values())) {
if (!plugin.isEnabled() && type == plugin.getDescription().getOrder()) {
this.enablePlugin(plugin);
}
}
if (type == PluginLoadOrder.POSTWORLD) {
this.commandMap.registerServerAliases();
DefaultPermissions.registerCorePermissions();
}
}
/**
* 引数で指定したプラグインを有効にします。
* @param plugin 有効にするプラグイン
*/
public void enablePlugin(Plugin plugin) {
this.pluginManager.enablePlugin(plugin);
}
/**
* 全てのプラグインを無効にします。
*/
public void disablePlugins() {
this.pluginManager.disablePlugins();
}
/**
* コマンドを実行します。
* @param sender 対象のCommandSender
* @param commandLine 送るパケット
* @return boolean trueが完了/falseが失敗
*/
public boolean dispatchCommand(CommandSender sender, String commandLine) throws ServerException {
// First we need to check if this command is on the main thread or not, if not, warn the user
if (!this.isPrimaryThread()) {
getLogger().warning("Command Dispatched Async: " + commandLine);
getLogger().warning("Please notify author of plugin causing this execution to fix this bug!", new Throwable());
// TODO: We should sync the command to the main thread too!
}
if (sender == null) {
throw new ServerException("CommandSender is not valid");
}
if (this.commandMap.dispatch(sender, commandLine)) {
return true;
}
sender.sendMessage(TextFormat.RED + this.getLanguage().translateString("commands.generic.notFound"));
return false;
}
//todo: use ticker to check console
public ConsoleCommandSender getConsoleSender() {
return consoleSender;
}
/**
* サーバーを再読み込みさせます。
* @return void
*/
public void reload() {
this.logger.info("再読み込み中...");
this.logger.info("ワールドを保存しています...");
for (Level level : this.levels.values()) {
level.save();
}
this.pluginManager.disablePlugins();
this.pluginManager.clearPlugins();
this.commandMap.clearCommands();
this.logger.info("server.propertiesを再読み込みしています...");
this.properties.reload();
this.maxPlayers = this.getPropertyInt("max-players", 20);
if (this.getPropertyBoolean("hardcore", false) && this.getDifficulty() < 3) {
this.setPropertyInt("difficulty", 3);
}
this.banByIP.load();
this.banByName.load();
this.reloadWhitelist();
this.operators.reload();
for (BanEntry entry : this.getIPBans().getEntires().values()) {
this.getNetwork().blockAddress(entry.getName(), -1);
}
this.pluginManager.registerInterface(JavaPluginLoader.class);
this.pluginManager.loadPlugins(this.pluginPath);
this.enablePlugins(PluginLoadOrder.STARTUP);
this.enablePlugins(PluginLoadOrder.POSTWORLD);
Timings.reset();
}
/**
* サーバーを終了させます。
* @return void
*/
public void shutdown() {
if (this.isRunning) {
ServerKiller killer = new ServerKiller(90);
killer.start();
}
this.isRunning = false;
}
public void forceShutdown() {
if (this.hasStopped) {
return;
}
try {
if (!this.isRunning) {
//todo sendUsage
}
// clean shutdown of console thread asap
this.console.shutdown();
this.hasStopped = true;
this.shutdown();
if (this.rcon != null) {
this.rcon.close();
}
this.getLogger().debug("Disabling all plugins");
this.pluginManager.disablePlugins();
for (Player player : new ArrayList<>(this.players.values())) {
player.close(player.getLeaveMessage(), (String) this.getConfig("settings.shutdown-message", "Server closed"));
}
this.getLogger().debug("Unloading all levels");
for (Level level : new ArrayList<>(this.getLevels().values())) {
this.unloadLevel(level, true);
}
this.getLogger().debug("Removing event handlers");
HandlerList.unregisterAll();
this.getLogger().debug("Stopping all tasks");
this.scheduler.cancelAllTasks();
this.scheduler.mainThreadHeartbeat(Integer.MAX_VALUE);
this.getLogger().debug("Closing console");
this.console.interrupt();
this.getLogger().debug("Stopping network interfaces");
for (SourceInterface interfaz : this.network.getInterfaces()) {
interfaz.shutdown();
this.network.unregisterInterface(interfaz);
}
this.getLogger().debug("Disabling timings");
Timings.stopServer();
//todo other things
} catch (Exception e) {
this.logger.logException(e); //todo remove this?
this.logger.emergency("Exception happened while shutting down, exit the process");
System.exit(1);
}
}
/**
* サーバーを開始させます。
* @return void
*/
public void start() {
if (this.getPropertyBoolean("enable-query", true)) {
this.queryHandler = new QueryHandler();
}
for (BanEntry entry : this.getIPBans().getEntires().values()) {
this.network.blockAddress(entry.getName(), -1);
}
//todo send usage setting
this.tickCounter = 0;
this.logger.info(this.getLanguage().translateString("nukkit.server.defaultGameMode", getGamemodeString(this.getDefaultGamemode())));
this.logger.info(this.getLanguage().translateString("nukkit.server.startFinished", String.valueOf((double) (System.currentTimeMillis() - Nukkit.START_TIME) / 1000)));
this.tickProcessor();
this.forceShutdown();
}
public void handlePacket(String address, int port, byte[] payload) {
try {
if (payload.length > 2 && Arrays.equals(Binary.subBytes(payload, 0, 2), new byte[]{(byte) 0xfe, (byte) 0xfd}) && this.queryHandler != null) {
this.queryHandler.handle(address, port, payload);
}
} catch (Exception e) {
this.logger.logException(e);
this.getNetwork().blockAddress(address, 600);
}
}
public void tickProcessor() {
this.nextTick = System.currentTimeMillis();
try {
while (this.isRunning) {
try {
this.tick();
long next = this.nextTick;
long current = System.currentTimeMillis();
if (next - 0.1 > current) {
Thread.sleep(next - current - 1, 900000);
}
} catch (RuntimeException e) {
this.getLogger().logException(e);
}
}
} catch (Throwable e) {
this.logger.emergency("Exception happened while ticking server");
this.logger.alert(Utils.getExceptionMessage(e));
this.logger.alert(Utils.getAllThreadDumps());
}
}
public void onPlayerCompleteLoginSequence(Player player) {
this.sendFullPlayerListData(player);
}
public void onPlayerLogin(Player player) {
if (this.sendUsageTicker > 0) {
this.uniquePlayers.add(player.getUniqueId());
this.loggedInPlayers.add(player);
}
}
/*
public void onPlayerCompleteLoginSequence(Player player){
this.sendFullPlayerListData(player);
player.dataPacket(this.craftingManager.getCraftingDataPacket());
}
*/
public void onPlayerLogout(Player player){
this.loggedInPlayers.remove(player.getUniqueId());
}
public void addPlayer(String identifier, Player player) {
this.players.put(identifier, player);
this.identifier.put(player.rawHashCode(), identifier);
}
public void addOnlinePlayer(Player player) {
this.playerList.put(player.getUniqueId(), player);
this.updatePlayerListData(player.getUniqueId(), player.getId(), player.getDisplayName(), player.getSkin(), player.getLoginChainData().getXUID());
}
public void removeOnlinePlayer(Player player) {
if (this.playerList.containsKey(player.getUniqueId())) {
this.playerList.remove(player.getUniqueId());
/*
PlayerListPacket pk = new PlayerListPacket();
pk.type = PlayerListPacket.TYPE_REMOVE;
pk.entries = new PlayerListPacket.Entry[]{new PlayerListPacket.Entry(player.getUniqueId())};
Server.broadcastPacket(this.playerList.values(), pk);
*/
this.removePlayerListData(player.getUniqueId());
}
}
public void updatePlayerListData(UUID uuid, long entityId, String name, Skin skin) {
this.updatePlayerListData(uuid, entityId, name, skin, "", this.playerList.values());
}
public void updatePlayerListData(UUID uuid, long entityId, String name, Skin skin, String xboxUserId) {
this.updatePlayerListData(uuid, entityId, name, skin, xboxUserId, this.playerList.values());
}
public void updatePlayerListData(UUID uuid, long entityId, String name, Skin skin, Player[] players) {
this.updatePlayerListData(uuid, entityId, name, skin, "", players);
}
public void updatePlayerListData(UUID uuid, long entityId, String name, Skin skin, String xboxUserId, Player[] players) {
PlayerListPacket pk = new PlayerListPacket();
pk.type = PlayerListPacket.TYPE_ADD;
pk.entries = new PlayerListPacket.Entry[]{new PlayerListPacket.Entry(uuid, entityId, name, skin, xboxUserId)};
Server.broadcastPacket(players, pk);
}
public void updatePlayerListData(UUID uuid, long entityId, String name, Skin skin, String xboxUserId, Collection<Player> players) {
this.updatePlayerListData(uuid, entityId, name, skin, xboxUserId,
players.stream()
.filter(p -> !p.getUniqueId().equals(uuid))
.toArray(Player[]::new));
}
public void removePlayerListData(UUID uuid) {
this.removePlayerListData(uuid, this.playerList.values());
}
public void removePlayerListData(UUID uuid, Player[] players) {
PlayerListPacket pk = new PlayerListPacket();
pk.type = PlayerListPacket.TYPE_REMOVE;
pk.entries = new PlayerListPacket.Entry[]{new PlayerListPacket.Entry(uuid)};
Server.broadcastPacket(players, pk);
}
public void removePlayerListData(UUID uuid, Collection<Player> players) {
this.removePlayerListData(uuid, players.stream().toArray(Player[]::new));
}
public void sendFullPlayerListData(Player player) {
PlayerListPacket pk = new PlayerListPacket();
pk.type = PlayerListPacket.TYPE_ADD;
pk.entries = this.playerList.values().stream()
.map(p -> new PlayerListPacket.Entry(
p.getUniqueId(),
p.getId(),
p.getDisplayName(),
p.getSkin(),
p.getLoginChainData().getXUID()))
.toArray(PlayerListPacket.Entry[]::new);
player.dataPacket(pk);
}
public void sendRecipeList(Player player) {
CraftingDataPacket pk = new CraftingDataPacket();
pk.cleanRecipes = true;
for (Recipe recipe : this.getCraftingManager().getRecipes().values()) {
if (recipe instanceof ShapedRecipe) {
pk.addShapedRecipe((ShapedRecipe) recipe);
} else if (recipe instanceof ShapelessRecipe) {
pk.addShapelessRecipe((ShapelessRecipe) recipe);
}
}
for (FurnaceRecipe recipe : this.getCraftingManager().getFurnaceRecipes().values()) {
pk.addFurnaceRecipe(recipe);
}
player.dataPacket(pk);
}
private void checkTickUpdates(int currentTick, long tickTime) {
for (Player p : new ArrayList<>(this.players.values())) {
/*if (!p.loggedIn && (tickTime - p.creationTime) >= 10000 && p.kick(PlayerKickEvent.Reason.LOGIN_TIMEOUT, "Login timeout")) {
continue;
}
client freezes when applying resource packs
todo: fix*/
if (this.alwaysTickPlayers) {
p.onUpdate(currentTick);
}
}
//Do level ticks
for (Level level : this.getLevels().values()) {
if (level.getTickRate() > this.baseTickRate && --level.tickRateCounter > 0) {
continue;
}
try {
long levelTime = System.currentTimeMillis();
level.doTick(currentTick);
int tickMs = (int) (System.currentTimeMillis() - levelTime);
level.tickRateTime = tickMs;
if (this.autoTickRate) {
if (tickMs < 50 && level.getTickRate() > this.baseTickRate) {
int r;
level.setTickRate(r = level.getTickRate() - 1);
if (r > this.baseTickRate) {
level.tickRateCounter = level.getTickRate();
}
this.getLogger().debug("Raising level \"" + level.getName() + "\" tick rate to " + level.getTickRate() + " ticks");
} else if (tickMs >= 50) {
if (level.getTickRate() == this.baseTickRate) {
level.setTickRate((int) Math.max(this.baseTickRate + 1, Math.min(this.autoTickRateLimit, Math.floor(tickMs / 50))));
this.getLogger().debug("Level \"" + level.getName() + "\" took " + NukkitMath.round(tickMs, 2) + "ms, setting tick rate to " + level.getTickRate() + " ticks");
} else if ((tickMs / level.getTickRate()) >= 50 && level.getTickRate() < this.autoTickRateLimit) {
level.setTickRate(level.getTickRate() + 1);
this.getLogger().debug("Level \"" + level.getName() + "\" took " + NukkitMath.round(tickMs, 2) + "ms, setting tick rate to " + level.getTickRate() + " ticks");
}
level.tickRateCounter = level.getTickRate();
}
}
} catch (Exception e) {
if (Nukkit.DEBUG > 1 && this.logger != null) {
this.logger.logException(e);
}
this.logger.critical(this.getLanguage().translateString("nukkit.level.tickError", new String[]{level.getName(), e.toString()}));
this.logger.logException(e);
}
}
}
public void doAutoSave() {
if (this.getAutoSave()) {
Timings.levelSaveTimer.startTiming();
for (Player player : new ArrayList<>(this.players.values())) {
if (player.isOnline()) {
player.save(true);
} else if (!player.isConnected()) {
this.removePlayer(player);
}
}
for (Level level : this.getLevels().values()) {
level.save();
}
Timings.levelSaveTimer.stopTiming();
}
}
private boolean tick() {
long tickTime = System.currentTimeMillis();
long tickTimeNano = System.nanoTime();
if ((tickTime - this.nextTick) < -25) {
return false;
}
Timings.fullServerTickTimer.startTiming();
++this.tickCounter;
Timings.connectionTimer.startTiming();
this.network.processInterfaces();
if (this.rcon != null) {
this.rcon.check();
}
Timings.connectionTimer.stopTiming();
Timings.schedulerTimer.startTiming();
this.scheduler.mainThreadHeartbeat(this.tickCounter);
Timings.schedulerTimer.stopTiming();
this.checkTickUpdates(this.tickCounter, tickTime);
for (Player player : new ArrayList<>(this.players.values())) {
player.checkNetwork();
}
if ((this.tickCounter & 0b1111) == 0) {
this.maxTick = 20;
this.maxUse = 0;
if ((this.tickCounter & 0b111111111) == 0) {
try {
this.getPluginManager().callEvent(this.queryRegenerateEvent = new QueryRegenerateEvent(this, 5));
if (this.queryHandler != null) {
this.queryHandler.regenerateInfo();
}
} catch (Exception e) {
this.logger.logException(e);
}
}
this.getNetwork().updateName();
}
if (this.autoSave && ++this.autoSaveTicker >= this.autoSaveTicks) {
this.autoSaveTicker = 0;
this.doAutoSave();
}
if (this.sendUsageTicker > 0 && --this.sendUsageTicker == 0) {
this.sendUsageTicker = 6000;
//todo sendUsage
}
if (this.tickCounter % 100 == 0) {
for (Level level : this.levels.values()) {
level.clearCache();
level.doChunkGarbageCollection();
}
}
Timings.fullServerTickTimer.stopTiming();
//long now = System.currentTimeMillis();
long nowNano = System.nanoTime();
//float tick = Math.min(20, 1000 / Math.max(1, now - tickTime));
//float use = Math.min(1, (now - tickTime) / 50);
float tick = (float) Math.min(20, 1000000000 / Math.max(1000000, ((double) nowNano - tickTimeNano)));
float use = (float) Math.min(1, ((double) (nowNano - tickTimeNano)) / 50000000);
if (this.maxTick > tick) {
this.maxTick = tick;
}
if (this.maxUse < use) {
this.maxUse = use;
}
System.arraycopy(this.tickAverage, 1, this.tickAverage, 0, this.tickAverage.length - 1);
this.tickAverage[this.tickAverage.length - 1] = tick;
System.arraycopy(this.useAverage, 1, this.useAverage, 0, this.useAverage.length - 1);
this.useAverage[this.useAverage.length - 1] = use;
if ((this.nextTick - tickTime) < -1000) {
this.nextTick = tickTime;
} else {
this.nextTick += 50;
}
return true;
}
public QueryRegenerateEvent getQueryInformation() {
return this.queryRegenerateEvent;
}
/**
* サーバーの名前を取得します。
* @return String どんな場合でも"Jupiter"が返ってきます。
*/
public String getName() {
return "Jupiter";
}
public boolean isRunning() {
return isRunning;
}
/**
* Nukkitのバージョンを取得します。
* @return String Nukkitバージョン
*/
public String getNukkitVersion() {
return Nukkit.VERSION;
}
/**
* コードネームを取得します。
* @return String コードネーム
*/
public String getCodename() {
return Nukkit.CODENAME;
}
/**
* マインクラフトPEのバージョンを取得します。
* @return String Minecraftバージョン
*/
public String getVersion() {
return ProtocolInfo.MINECRAFT_VERSION;
}
/**
* APIバージョンを取得します。
* @return String APIバージョン
*/
public String getApiVersion() {
return Nukkit.API_VERSION;
}
/**
* Jupiterバージョンを取得します。
* @return String Jupiterバージョン
*/
public String getJupiterVersion() {
return Nukkit.JUPITER_VERSION;
}
/**
* ファイルパスを取得します。
* @return String ファイルパス
*/
public String getFilePath() {
return filePath;
}
/**
* データパスを取得します。
* <br>この場合、jarがあるディレクトリのパスです。
* @return String データパス
*/
public String getDataPath() {
return dataPath;
}
/**
* pluginsのパスを取得します。
* <br>この場合、getDataPath()の戻り値に/pluginsがついたものとなります。
* @return String プラグインフォルダのパス
* @see Server#getDataPath()
*/
public String getPluginPath() {
return pluginPath;
}
public String getDefaultplugins(){
return defaultplugin;
}
/**
* サーバーの最大参加可能人数を取得します。
* @return int 最大参加可能人数
*/
public int getMaxPlayers() {
return maxPlayers;
}
/**
* サーバーのポートを取得します。
* <br>server.propertiesのserver-portの値です。
* @return int ポート
*/
public int getPort() {
return this.getPropertyInt("server-port", 19132);
}
/**
* サーバーの描画距離を取得します。
* <br>server.propertiesのview-distancetの値です。
* @return int 描画距離
*/
public int getViewDistance() {
return this.getPropertyInt("view-distance", 10);
}
/**
* サーバーのIPアドレスを取得します。
* <br>server.propertiesのserver-ipの値です。
* @return String IPアドレス
*/
public String getIp() {
return this.getPropertyString("server-ip", "0.0.0.0");
}
public UUID getServerUniqueId() {
return this.serverID;
}
/**
* サーバーのオートセーブが有効かどうかを取得します。
* @return boolean trueが有効/falseが無効
*/
public boolean getAutoSave() {
return this.autoSave;
}
/**
* サーバーのオートセーブを設定します。
* @param autoSave trueが有効/falseが無効
*/
public void setAutoSave(boolean autoSave) {
this.autoSave = autoSave;
for (Level level : this.getLevels().values()) {
level.setAutoSave(this.autoSave);
}
}
/**
* サーバーのワールドタイプを取得します。
* <br>server.propertiesのlevel-typeの値です。
* <br>
* <br>[ワールドタイプ]
* <br>FLAT フラットワールド
* <br>DEFAULT デフォルトワールド
* @return String ワールドタイプ
*/
public String getLevelType() {
return this.getPropertyString("level-type", "DEFAULT");
}
public boolean getGenerateStructures() {
return this.getPropertyBoolean("generate-structures", true);
}
public boolean getForceGamemode() {
return this.getPropertyBoolean("force-gamemode", false);
}
/**
* サーバーのゲームモードを名前で取得します。
* <br>server.propertiesのgamemodeの値です。
* <br>
* <br>[戻ってくる名前:ゲームモード(入力した番号)]
* <br>サバイバルモード(0)
* <br>クリエイティブモード(1)
* <br>アドベンチャーモード(2)
* <br>スペクテイターモード(3)
* <br>UNKNOWN(0-3以外の数値を入力した場合)
* @param mode 名前に変換したいゲームモードの番号(0, 1, 2, 3)
* @param direct ダイレクトかどうか
* @return String ゲームモード
*/
public static String getGamemodeString(int mode) {
return getGamemodeString(mode, false);
}
public static String getGamemodeString(int mode, boolean direct) {
switch (mode) {
case Player.SURVIVAL:
return direct ? "Survival" : "%gameMode.survival";
case Player.CREATIVE:
return direct ? "Creative" : "%gameMode.creative";
case Player.ADVENTURE:
return direct ? "Adventure" : "%gameMode.adventure";
case Player.SPECTATOR:
return direct ? "Spectator" : "%gameMode.spectator";
}
return "UNKNOWN";
}
public static int getGamemodeFromString(String str) {
switch (str.trim().toLowerCase()) {
case "0":
case "survival":
case "s":
return Player.SURVIVAL;
case "1":
case "creative":
case "c":
return Player.CREATIVE;
case "2":
case "adventure":
case "a":
return Player.ADVENTURE;
case "3":
case "spectator":
case "spc":
case "view":
case "v":
return Player.SPECTATOR;
}
return -1;
}
public static int getDifficultyFromString(String str) {
switch (str.trim().toLowerCase()) {
case "0":
case "peaceful":
case "p":
return 0;
case "1":
case "easy":
case "e":
return 1;
case "2":
case "normal":
case "n":
return 2;
case "3":
case "hard":
case "h":
return 3;
}
return -1;
}
/**
* サーバーの難易度を取得します。
* <br>server.propertiesのdifficultyの値です。
* @return int 難易度
*/
public int getDifficulty() {
return this.getPropertyInt("difficulty", 1);
}
/**
* サーバーがホワイトリスト状態かどうかを取得します。
* <br>server.propertiesのwhite-listの値です。
* @return boolean trueが有効/falseが無効
*/
public boolean hasWhitelist() {
return this.getPropertyBoolean("white-list", false);
}
/**
* スポーン地点から半径何ブロックが破壊できないかを取得します。
* <br>server.propertiesのspawn-protectionの値です。
* @return int 半径
*/
public int getSpawnRadius() {
return this.getPropertyInt("spawn-protection", 16);
}
public boolean getAllowFlight() {
if (getAllowFlight == null) {
getAllowFlight = this.getPropertyBoolean("allow-flight", false);
}
return getAllowFlight;
}
/**
* サーバーがハードコア状態かどうかを取得します。
* <br>server.propertiesのhardcoreの値です。
* @return boolean trueが有効/falseが無効
*/
public boolean isHardcore() {
return this.getPropertyBoolean("hardcore", false);
}
/**
* サーバーのデフォルトのゲームモードを取得します。
* <br>server.propertiesのgamemodeの値です。
* <br>
* <br>[ゲームモード]
* <br>0:サバイバルモード
* <br>1:クリエイティブモード
* <br>2:アドベンチャーモード
* <br>3:スペクテイターモード
* @return int ゲームモード
*/
public int getDefaultGamemode() {
return this.getPropertyInt("gamemode", 0);
}
/**
* サーバー名を取得します。
* <br>server.propertiesのmotdの値です。
* @return String サーバー名
*/
public String getMotd() {
return this.getPropertyString("motd", "Nukkit Server For Minecraft: BE");
}
/**
* サブサーバー名を取得します。
* <br>server.propertiesのmotdの値です。
* @return String サブサーバー名
*/
public String getSubMotd() {
return this.getPropertyString("sub-motd", "Powered by Jupiter");
}
public boolean getForceResources() {
return this.getPropertyBoolean("force-resources", false);
}
/**
* MainLoggerオブジェクトを取得します。
* @return MainLogger
*/
public MainLogger getLogger() {
return this.logger;
}
public EntityMetadataStore getEntityMetadata() {
return entityMetadata;
}
public PlayerMetadataStore getPlayerMetadata() {
return playerMetadata;
}
public LevelMetadataStore getLevelMetadata() {
return levelMetadata;
}
/**
* プラグインマネージャを取得します。
* <br>
* <br>[Itsuのメモ: イベント登録]
* <br>(Listenerインターフェースを実装/PluginBaseクラスを継承している場合)
* <br>
* <br>{@code this.getLogger().getPluginManager().registerEvents(this, this);}
* @return PluginManager
* @see PluginManager#registerEvents(cn.nukkit.event.Listener, Plugin)
*/
public PluginManager getPluginManager() {
return this.pluginManager;
}
/**
* クラフティングマネージャを取得します。
* @return CraftingManager
*/
public CraftingManager getCraftingManager() {
return craftingManager;
}
/**
* リソースパックマネージャを取得します。
* @return ResourcePackManager
*/
public ResourcePackManager getResourcePackManager() {
return resourcePackManager;
}
/**
* スケジューラを取得します。
* <br>
* <br>[Itsuのメモ: スケジューラの使い方]
* <pre>
* ・繰り返し
* {@code
* TaskHandler th;
* th = this.getServer().getScheduler().scheduleRepeatingTask(null, new Runnable(){
* //繰り返す処理
* };, 間隔tick(int));
*
*
* ・遅延してから繰り返し
* TaskHandler th;
* th = this.getServer().getScheduler().scheduleDelayedRepeatingTask(null, new Runnable(){
* //繰り返す処理
* };, 遅延tick(int), 間隔tick(int));
*
*
* ・スケジューラを止める
* th.cancel();
* </pre>
* [豆知識]
* <br>20tick = 1秒です!
* @return ServerScheduler
*/
public ServerScheduler getScheduler() {
return scheduler;
}
public int getTick() {
return tickCounter;
}
public float getTicksPerSecond() {
return ((float) Math.round(this.maxTick * 100)) / 100;
}
public float getTicksPerSecondAverage() {
float sum = 0;
int count = this.tickAverage.length;
for (float aTickAverage : this.tickAverage) {
sum += aTickAverage;
}
return (float) NukkitMath.round(sum / count, 2);
}
public float getTickUsage() {
return (float) NukkitMath.round(this.maxUse * 100, 2);
}
public float getTickUsageAverage() {
float sum = 0;
int count = this.useAverage.length;
for (float aUseAverage : this.useAverage) {
sum += aUseAverage;
}
return ((float) Math.round(sum / count * 100)) / 100;
}
public SimpleCommandMap getCommandMap() {
return commandMap;
}
public Map<UUID, Player> getOnlinePlayers() {
return new HashMap<>(playerList);
}
public void addRecipe(Recipe recipe) {
this.craftingManager.registerRecipe(recipe);
}
public IPlayer getOfflinePlayer(String name) {
IPlayer result = this.getPlayerExact(name.toLowerCase());
if (result == null) {
return new OfflinePlayer(this, name);
}
return result;
}
public CompoundTag getOfflinePlayerData(String name) {
name = name.toLowerCase();
String path = this.getDataPath() + "players/";
File file = new File(FastAppender.get(path, name, ".dat"));
if (this.shouldSavePlayerData() && file.exists()) {
try {
return NBTIO.readCompressed(new FileInputStream(file));
} catch (Exception e) {
file.renameTo(new File(FastAppender.get(path, name, ".dat.bak")));
this.logger.notice(this.getLanguage().translateString("nukkit.data.playerCorrupted", name));
}
} else {
this.logger.notice(this.getLanguage().translateString("nukkit.data.playerNotFound", name));
}
Position spawn = this.getDefaultLevel().getSafeSpawn();
CompoundTag nbt = new CompoundTag()
.putLong("firstPlayed", System.currentTimeMillis() / 1000)
.putLong("lastPlayed", System.currentTimeMillis() / 1000)
.putList(new ListTag<DoubleTag>("Pos")
.add(new DoubleTag("0", spawn.x))
.add(new DoubleTag("1", spawn.y))
.add(new DoubleTag("2", spawn.z)))
.putString("Level", this.getDefaultLevel().getName())
.putList(new ListTag<>("Inventory"))
.putCompound("Achievements", new CompoundTag())
.putInt("playerGameType", this.getDefaultGamemode())
.putList(new ListTag<DoubleTag>("Motion")
.add(new DoubleTag("0", 0))
.add(new DoubleTag("1", 0))
.add(new DoubleTag("2", 0)))
.putList(new ListTag<FloatTag>("Rotation")
.add(new FloatTag("0", 0))
.add(new FloatTag("1", 0)))
.putFloat("FallDistance", 0)
.putShort("Fire", 0)
.putShort("Air", 300)
.putBoolean("OnGround", true)
.putBoolean("Invulnerable", false)
.putString("NameTag", name);
this.saveOfflinePlayerData(name, nbt);
return nbt;
}
public void saveOfflinePlayerData(String name, CompoundTag tag) {
this.saveOfflinePlayerData(name, tag, false);
}
public void saveOfflinePlayerData(String name, CompoundTag tag, boolean async) {
if (this.shouldSavePlayerData()) {
try {
if (async) {
this.getScheduler().scheduleAsyncTask(new FileWriteTask(FastAppender.get(this.getDataPath() + "players/", name.toLowerCase(), ".dat"), NBTIO.writeGZIPCompressed(tag, ByteOrder.BIG_ENDIAN)));
} else {
Utils.writeFile(FastAppender.get(this.getDataPath(), "players/", name.toLowerCase(), ".dat"), new ByteArrayInputStream(NBTIO.writeGZIPCompressed(tag, ByteOrder.BIG_ENDIAN)));
}
} catch (Exception e) {
this.logger.critical(this.getLanguage().translateString("nukkit.data.saveError", new String[]{name, e.getMessage()}));
if (Nukkit.DEBUG > 1) {
this.logger.logException(e);
}
}
}
}
/**
* プレイヤーオブジェクトを名前から取得します。
* @param name 取得したいプレイヤーの名前
* @return Player 取得したプレイヤー
*/
public Player getPlayer(String name) {
Player found = null;
name = name.toLowerCase();
int delta = Integer.MAX_VALUE;
for (Player player : this.getOnlinePlayers().values()) {
if (player.getName().toLowerCase().startsWith(name)) {
int curDelta = player.getName().length() - name.length();
if (curDelta < delta) {
found = player;
delta = curDelta;
}
if (curDelta == 0) {
break;
}
}
}
return found;
}
public Player getPlayerExact(String name) {
name = name.toLowerCase();
for (Player player : this.getOnlinePlayers().values()) {
if (player.getName().toLowerCase().equals(name)) {
return player;
}
}
return null;
}
public Player[] matchPlayer(String partialName) {
partialName = partialName.toLowerCase();
List<Player> matchedPlayer = new ArrayList<>();
for (Player player : this.getOnlinePlayers().values()) {
if (player.getName().toLowerCase().equals(partialName)) {
return new Player[]{player};
} else if (player.getName().toLowerCase().contains(partialName)) {
matchedPlayer.add(player);
}
}
return matchedPlayer.toArray(new Player[matchedPlayer.size()]);
}
public void removePlayer(Player player) {
if (this.identifier.containsKey(player.rawHashCode())) {
String identifier = this.identifier.get(player.rawHashCode());
this.players.remove(identifier);
this.identifier.remove(player.rawHashCode());
return;
}
for (String identifier : new ArrayList<>(this.players.keySet())) {
Player p = this.players.get(identifier);
if (player == p) {
this.players.remove(identifier);
this.identifier.remove(player.rawHashCode());
break;
}
}
}
public Map<Integer, Level> getLevels() {
return levels;
}
/**
* デフォルトで設定されているワールドのオブジェクトを取得します。
* @return Level デフォルトで設定されているワールドのオブジェクト
*/
public Level getDefaultLevel() {
return defaultLevel;
}
public void setDefaultLevel(Level defaultLevel) {
if (defaultLevel == null || (this.isLevelLoaded(defaultLevel.getFolderName()) && defaultLevel != this.defaultLevel)) {
this.defaultLevel = defaultLevel;
}
}
public boolean isLevelLoaded(String name) {
return this.getLevelByName(name) != null;
}
public Level getLevel(int levelId) {
if (this.levels.containsKey(levelId)) {
return this.levels.get(levelId);
}
return null;
}
/**
* ワールドオブジェクトを名前から取得します。
* @param name 取得したいワールドの名前
* @return Level 取得したワールドオブジェクト
*/
public Level getLevelByName(String name) {
for (Level level : this.getLevels().values()) {
if (level.getFolderName().equals(name)) {
return level;
}
}
return null;
}
public boolean unloadLevel(Level level) {
return this.unloadLevel(level, false);
}
public boolean unloadLevel(Level level, boolean forceUnload) {
if (level == this.getDefaultLevel() && !forceUnload) {
throw new IllegalStateException("The default level cannot be unloaded while running, please switch levels.");
}
return level.unload(forceUnload);
}
public boolean loadLevel(String name) {
if (Objects.equals(name.trim(), "")) {
throw new LevelException("Invalid empty level name");
}
if (this.isLevelLoaded(name)) {
return true;
} else if (!this.isLevelGenerated(name)) {
this.logger.notice(this.getLanguage().translateString("nukkit.level.notFound", name));
return false;
}
String path;
if (name.contains("/") || name.contains("\\")) {
path = name;
} else {
path = FastAppender.get(this.getDataPath(), "worlds/", name, "/");
}
Class<? extends LevelProvider> provider = LevelProviderManager.getProvider(path);
if (provider == null) {
this.logger.error(this.getLanguage().translateString("nukkit.level.loadError", new String[]{name, "Unknown provider"}));
return false;
}
Level level;
try {
level = new Level(this, name, path, provider);
} catch (Exception e) {
this.logger.error(this.getLanguage().translateString("nukkit.level.loadError", new String[]{name, e.getMessage()}));
this.logger.logException(e);
return false;
}
this.levels.put(level.getId(), level);
level.initLevel();
this.getPluginManager().callEvent(new LevelLoadEvent(level));
level.setTickRate(this.baseTickRate);
return true;
}
public boolean generateLevel(String name) {
return this.generateLevel(name, new java.util.Random().nextLong());
}
public boolean generateLevel(String name, long seed) {
return this.generateLevel(name, seed, null);
}
public boolean generateLevel(String name, long seed, Class<? extends Generator> generator) {
return this.generateLevel(name, seed, generator, new HashMap<>());
}
public boolean generateLevel(String name, long seed, Class<? extends Generator> generator, Map<String, Object> options) {
return generateLevel(name, seed, generator, options, null);
}
public boolean generateLevel(String name, long seed, Class<? extends Generator> generator, Map<String, Object> options, Class<? extends LevelProvider> provider) {
if (Objects.equals(name.trim(), "") || this.isLevelGenerated(name)) {
return false;
}
if (!options.containsKey("preset")) {
options.put("preset", this.getPropertyString("generator-settings", ""));
}
if (generator == null) {
generator = Generator.getGenerator(this.getLevelType());
}
if (provider == null) {
if ((provider = LevelProviderManager.getProviderByName
((String) this.getConfig("level-settings.default-format", "anvil"))) == null) {
provider = LevelProviderManager.getProviderByName("anvil");
}
}
String path;
if (name.contains("/") || name.contains("\\")) {
path = name;
} else {
path = FastAppender.get(this.getDataPath(), "worlds/", name, "/");
}
Level level;
try {
provider.getMethod("generate", String.class, String.class, long.class, Class.class, Map.class).invoke(null, path, name, seed, generator, options);
level = new Level(this, name, path, provider);
this.levels.put(level.getId(), level);
level.initLevel();
level.setTickRate(this.baseTickRate);
} catch (Exception e) {
this.logger.error(this.getLanguage().translateString("nukkit.level.generationError", new String[]{name, e.getMessage()}));
this.logger.logException(e);
return false;
}
this.getPluginManager().callEvent(new LevelInitEvent(level));
this.getPluginManager().callEvent(new LevelLoadEvent(level));
/*this.getLogger().notice(this.getLanguage().translateString("nukkit.level.backgroundGeneration", name));
int centerX = (int) level.getSpawnLocation().getX() >> 4;
int centerZ = (int) level.getSpawnLocation().getZ() >> 4;
TreeMap<String, Integer> order = new TreeMap<>();
for (int X = -3; X <= 3; ++X) {
for (int Z = -3; Z <= 3; ++Z) {
int distance = X * X + Z * Z;
int chunkX = X + centerX;
int chunkZ = Z + centerZ;
order.put(Level.chunkHash(chunkX, chunkZ), distance);
}
}
List<Map.Entry<String, Integer>> sortList = new ArrayList<>(order.entrySet());
Collections.sort(sortList, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return o2.getValue() - o1.getValue();
}
});
for (String index : order.keySet()) {
Chunk.Entry entry = Level.getChunkXZ(index);
level.populateChunk(entry.chunkX, entry.chunkZ, true);
}*/
return true;
}
public boolean isLevelGenerated(String name) {
if (Objects.equals(name.trim(), "")) {
return false;
}
String path = FastAppender.get(this.getDataPath(), "worlds/", name, "/");
if (this.getLevelByName(name) == null) {
if (LevelProviderManager.getProvider(path) == null) {
return false;
}
}
return true;
}
public BaseLang getLanguage() {
return baseLang;
}
public boolean isLanguageForced() {
return forceLanguage;
}
public Network getNetwork() {
return network;
}
//Revising later...
public Config getConfig() {
return this.config;
}
public Object getConfig(String variable) {
return this.getConfig(variable, null);
}
public Object getConfig(String variable, Object defaultValue) {
Object value = this.config.get(variable);
return value == null ? defaultValue : value;
}
/**
* server.propertiesのオブジェクト(Config)を取得します。
* @return Config プロパティーのオブジェクト
*/
public Config getProperties() {
return this.properties;
}
/**
* server.propertiesの引数で指定したキーの値を取得します。
* <br>比較などするときは、適切にキャストする必要があります。
* @param variable キー
* @return Object 取得した値
*/
public Object getProperty(String variable) {
return this.getProperty(variable, null);
}
public Object getProperty(String variable, Object defaultValue) {
return this.properties.exists(variable) ? this.properties.get(variable) : defaultValue;
}
/**
* server.propertiesの引数で指定したキーの値をString型で設定します。
* @param variable キー
* @param value 値
* @return void
*/
public void setPropertyString(String variable, String value) {
this.properties.set(variable, value);
this.properties.save();
}
/**
* server.propertiesの引数で指定したキーの値をString型で取得します。
* @param variable キー
* @return String 取得した値
*/
public String getPropertyString(String variable) {
return this.getPropertyString(variable, null);
}
public String getPropertyString(String variable, String defaultValue) {
return this.properties.exists(variable) ? (String) this.properties.get(variable) : defaultValue;
}
/**
* server.propertiesの引数で指定したキーの値をint型で取得します。
* @param variable キー
* @return int 取得した値
*/
public int getPropertyInt(String variable) {
return this.getPropertyInt(variable, null);
}
public int getPropertyInt(String variable, Integer defaultValue) {
return this.properties.exists(variable) ? (!this.properties.get(variable).equals("") ? Integer.parseInt(String.valueOf(this.properties.get(variable))) : defaultValue) : defaultValue;
}
/**
* server.propertiesの引数で指定したキーの値をint型で設定します。
* @param variable キー
* @param value 値
* @return void
*/
public void setPropertyInt(String variable, int value) {
this.properties.set(variable, value);
this.properties.save();
}
/**
* server.propertiesの引数で指定したキーの値をboolean型で取得します。
* @param variable キー
* @return boolean 取得した値
*/
public boolean getPropertyBoolean(String variable) {
return this.getPropertyBoolean(variable, null);
}
/**
* server.propertiesの引数で指定したキーの値をboolean型で取得します。
* <br>第二引数はデフォルトの値です。
* @param variable キー
* @param defaultValue デフォルトの値
* @return boolean 取得した値
*/
public boolean getPropertyBoolean(String variable, Object defaultValue) {
Object value = this.properties.exists(variable) ? this.properties.get(variable) : defaultValue;
if (value instanceof Boolean) {
return (Boolean) value;
}
switch (String.valueOf(value)) {
case "on":
case "true":
case "1":
case "yes":
return true;
}
return false;
}
/**
* server.propertiesの引数で指定したキーの値をboolean型で設定します。
* @param variable キー
* @param value 値
* @return void
*/
public void setPropertyBoolean(String variable, boolean value) {
this.properties.set(variable, value ? "1" : "0");
this.properties.save();
}
/**
* jupiter.ymlのオブジェクト(Config)を取得します。
* @return Config jupiter.ymlのオブジェクト
*/
public Config getJupiterConfig(){
return new Config(this.getDataPath() + "jupiter.yml");
}
/**
* jupiter.ymlが読み込まれているかを取得します。
* <br>!(getJupiterConfig().isEmpty())の戻り値と同等です。
* @return boolean
*/
public boolean isLoadedJupiterConfig(){
return !this.jupiterconfig.isEmpty();
}
/**
* jupiter.ymlをロードします。
* @return void
*/
public void loadJupiterConfig(){
this.jupiterconfig = new HashMap<String, Object>(this.getJupiterConfig().getAll());
}
/**
* jupiter.ymlの引数で指定したキーの値をString型で取得します。
* @param key キー
* @return String 取得した値
*/
public String getJupiterConfigString(String key){
return (String) this.jupiterconfig.get(key);
}
/**
* jupiter.ymlの引数で指定したキーの値をint型で取得します。
* @param key キー
* @return int 取得した値
*/
public int getJupiterConfigInt(String key){
return (int) this.jupiterconfig.get(key);
}
/**
* jupiter.ymlの引数で指定したキーの値をBoolean型で取得します。
* <br>デフォルトではtrueが返ります。
* @param key キー
* @return boolean 取得した値
*/
public Boolean getJupiterConfigBoolean(String key){
return this.getJupiterConfigBoolean(key, null);
}
/**
* jupiter.ymlの引数で指定したキーの値をBoolean型で取得します。
* <br>第二引数はデフォルトの値です。
* @param key キー
* @param defaultValue キーが存在しない場合に返すもの
* @return boolean 取得した値
*/
public boolean getJupiterConfigBoolean(String variable, Object defaultValue) {
Object value = this.jupiterconfig.containsKey(variable) ? this.jupiterconfig.get(variable) : defaultValue;
if (value instanceof Boolean) {
return (Boolean) value;
}
switch (String.valueOf(value)) {
case "on":
case "true":
case "1":
case "yes":
return true;
}
return false;
}
public PluginIdentifiableCommand getPluginCommand(String name) {
Command command = this.commandMap.getCommand(name);
if (command instanceof PluginIdentifiableCommand) {
return (PluginIdentifiableCommand) command;
} else {
return null;
}
}
/**
* 名前Banされた人のリストを取得します。
* @return BanList 名前Banリスト
*/
public BanList getNameBans() {
return this.banByName;
}
/**
* IPBanされた人のリストを取得します。
* @return BanList IPBanリスト
*/
public BanList getIPBans() {
return this.banByIP;
}
/**
* 引数で指定した名前のプレイヤーをOPにします。
* @param name OPにしたいプレイヤーの名前
* @return void
*/
public void addOp(String name) {
this.operators.set(name.toLowerCase(), true);
Player player = this.getPlayerExact(name);
if (player != null) {
player.recalculatePermissions();
}
this.operators.save(true);
}
/**
* 引数で指定した名前のプレイヤーのOP権を剥奪します。
* @param name OPを剥奪したいプレイヤーの名前
* @return void
*/
public void removeOp(String name) {
this.operators.remove(name.toLowerCase());
Player player = this.getPlayerExact(name);
if (player != null) {
player.recalculatePermissions();
}
this.operators.save();
}
/**
* 引数で指定した名前のプレイヤーをホワイトリストに追加にします。
* @param name ホワイトリストに追加したいプレイヤーの名前
* @return void
*/
public void addWhitelist(String name) {
this.whitelist.set(name.toLowerCase(), true);
this.whitelist.save(true);
}
/**
* 引数で指定した名前のプレイヤーをホワイトリストから外します。
* @param name ホワイトリストから外したいプレイヤーの名前
* @return void
*/
public void removeWhitelist(String name) {
this.whitelist.remove(name.toLowerCase());
this.whitelist.save(true);
}
/**
* 引数で指定した名前のプレイヤーがホワイトリストに追加されているかどうかを取得します。
* @param name 調べたい人の名前
* @return boolean trueが追加されている/falseが追加されていない
*/
public boolean isWhitelisted(String name) {
return !this.hasWhitelist() || this.operators.exists(name, true) || this.whitelist.exists(name, true);
}
/**
* 引数で指定した名前のプレイヤーがOPかどうかを取得します。
* @param name 調べたい人の名前
* @return boolean trueがOP/falseが非OP
*/
public boolean isOp(String name) {
return this.operators.exists(name, true);
}
/**
* ホワイトリストをコンフィグから取得します。
* @return Config サーバーのホワイトリストのメンバー
*/
public Config getWhitelist() {
return whitelist;
}
/**
* OPをコンフィグから取得します。
* @return Config サーバーのOPメンバー
*/
public Config getOps() {
return operators;
}
/**
* ホワリスをリロードします。
* @return void
*/
public void reloadWhitelist() {
this.whitelist.reload();
}
public ServiceManager getServiceManager() {
return serviceManager;
}
@SuppressWarnings("unchecked")
public Map<String, List<String>> getCommandAliases() {
Object section = this.getConfig("aliases");
Map<String, List<String>> result = new LinkedHashMap<>();
if (section instanceof Map) {
for (Map.Entry entry : (Set<Map.Entry>) ((Map) section).entrySet()) {
List<String> commands = new ArrayList<>();
String key = (String) entry.getKey();
Object value = entry.getValue();
if (value instanceof List) {
for (String string : (List<String>) value) {
commands.add(string);
}
} else {
commands.add((String) value);
}
result.put(key, commands);
}
}
return result;
}
public boolean shouldSavePlayerData() {
return (Boolean) this.getConfig("player.save-player-data", true);
}
public LinkedHashMap<Integer, ServerSettingsWindow> getDefaultServerSettings() {
return this.defaultServerSettings;
}
public void addDefaultServerSettings(ServerSettingsWindow window) {
this.defaultServerSettings.put(window.getId(), window);
}
/**
* Checks the current thread against the expected primary thread for the server.
*
* <b>Note:</b> this method should not be used to indicate the current synchronized state of the runtime. A current thread matching the main thread indicates that it is synchronized, but a mismatch does not preclude the same assumption.
* @return true if the current thread matches the expected primary thread, false otherwise
*/
public boolean isPrimaryThread() {
return (Thread.currentThread() == currentThread);
}
private void registerEntities() {
//mob
Entity.registerEntity("Blaze", EntityBlaze.class);
Entity.registerEntity("CaveSpider", EntityCaveSpider.class);
Entity.registerEntity("Creeper", EntityCreeper.class);
Entity.registerEntity("Enderman", EntityEnderman.class);
Entity.registerEntity("Endermite", EntityEndermite.class);
Entity.registerEntity("Evoker", EntityEvoker.class);
Entity.registerEntity("Ghast", EntityGhast.class);
Entity.registerEntity("Guardian", EntityGuardian.class);
Entity.registerEntity("Hask", EntityHask.class);
Entity.registerEntity("MagmaCube", EntityMagmaCube.class);
Entity.registerEntity("Shulker", EntityShulker.class);
Entity.registerEntity("Silverfish", EntitySilverfish.class);
Entity.registerEntity("Skeleton", EntitySkeleton.class);
Entity.registerEntity("Slime", EntitySlime.class);
Entity.registerEntity("Spider", EntitySpider.class);
Entity.registerEntity("Stray", EntityStray.class);
Entity.registerEntity("Vex", EntityVex.class);
Entity.registerEntity("Vindicator", EntityVindicator.class);
Entity.registerEntity("Witch", EntityWitch.class);
Entity.registerEntity("WitherSkeleton", EntityWitherSkeleton.class);
Entity.registerEntity("Zombie", EntityZombie.class);
Entity.registerEntity("ZombiePigman", EntityZombiePigman.class);
Entity.registerEntity("ZombieVillager", EntityZombieVillager.class);
//passive
Entity.registerEntity("Bat", EntityBat.class);
Entity.registerEntity("Chicken", EntityChicken.class);
Entity.registerEntity("Cow", EntityCow.class);
Entity.registerEntity("Donkey", EntityDonkey.class);
Entity.registerEntity("Horse", EntityHorse.class);
Entity.registerEntity("IronGolem", EntityIronGolem.class);
Entity.registerEntity("Llama", EntityLlama.class);
Entity.registerEntity("Mooshroom", EntityMooshroom.class);
Entity.registerEntity("Mule", EntityMule.class);
Entity.registerEntity("Ocelot", EntityOcelot.class);
Entity.registerEntity("Parrot", EntityParrot.class);
Entity.registerEntity("Pig", EntityPig.class);
Entity.registerEntity("PolarBear", EntityPolarBear.class);
Entity.registerEntity("Rabbit", EntityRabbit.class);
Entity.registerEntity("Sheep", EntitySheep.class);
Entity.registerEntity("SkeletonHorse", EntitySkeletonHorse.class);
Entity.registerEntity("SnowGolem", EntitySnowGolem.class);
Entity.registerEntity("Squid", EntitySquid.class);
Entity.registerEntity("Villager", EntityVillager.class);
Entity.registerEntity("Wolf", EntityWolf.class);
Entity.registerEntity("ZombieHorse", EntityZombieHorse.class);
//Bosses
Entity.registerEntity("ElderGuardian", EntityElderGuardian.class);
Entity.registerEntity("EnderDragon", EntityEnderDragon.class);
Entity.registerEntity("EnderWither", EntityWither.class);
//item
Entity.registerEntity("ArmorStand", EntityArmorStand.class);
Entity.registerEntity("EnderCrystal", EntityEnderCrystal.class);
Entity.registerEntity("FallingSand", EntityFallingBlock.class);
Entity.registerEntity("PrimedTnt", EntityPrimedTNT.class);
Entity.registerEntity("Painting", EntityPainting.class);
Entity.registerEntity("XpOrb", EntityXPOrb.class);
Entity.registerEntity("MinecartRideable", EntityMinecartEmpty.class);
Entity.registerEntity("MinecartChest", EntityMinecartChest.class);
Entity.registerEntity("MinecartHopper", EntityMinecartHopper.class);
Entity.registerEntity("MinecartTnt", EntityMinecartTNT.class);
Entity.registerEntity("Boat", EntityBoat.class);
//projectile
Entity.registerEntity("Arrow", EntityArrow.class);
Entity.registerEntity("DragonFireball", EntityDragonFireball.class);
Entity.registerEntity("Egg", EntityEgg.class);
Entity.registerEntity("EnderPearl", EntityEnderPearl.class);
Entity.registerEntity("ThrownExpBottle", EntityExpBottle.class);
Entity.registerEntity("Fireball", EntityFireball.class);
Entity.registerEntity("FireworkRocket", EntityFireworkRocket.class);
Entity.registerEntity("FishingHook", EntityFishingHook.class);
Entity.registerEntity("ThrownPotion", EntityPotion.class);
Entity.registerEntity("ThrownLingeringPotion", EntityPotionLingering.class);
Entity.registerEntity("ShulkerBullet", EntityShulkerBullet.class);
Entity.registerEntity("Snowball", EntitySnowball.class);
//weather
Entity.registerEntity("Lightning", EntityLightning.class);
//other
Entity.registerEntity("Human", EntityHuman.class, true);
}
private void registerBlockEntities() {
BlockEntity.registerBlockEntity(BlockEntity.FURNACE, BlockEntityFurnace.class);
BlockEntity.registerBlockEntity(BlockEntity.CHEST, BlockEntityChest.class);
BlockEntity.registerBlockEntity(BlockEntity.SIGN, BlockEntitySign.class);
BlockEntity.registerBlockEntity(BlockEntity.ENCHANT_TABLE, BlockEntityEnchantTable.class);
BlockEntity.registerBlockEntity(BlockEntity.SKULL, BlockEntitySkull.class);
BlockEntity.registerBlockEntity(BlockEntity.FLOWER_POT, BlockEntityFlowerPot.class);
BlockEntity.registerBlockEntity(BlockEntity.BREWING_STAND, BlockEntityBrewingStand.class);
BlockEntity.registerBlockEntity(BlockEntity.ITEM_FRAME, BlockEntityItemFrame.class);
BlockEntity.registerBlockEntity(BlockEntity.CAULDRON, BlockEntityCauldron.class);
BlockEntity.registerBlockEntity(BlockEntity.ENDER_CHEST, BlockEntityEnderChest.class);
BlockEntity.registerBlockEntity(BlockEntity.BEACON, BlockEntityBeacon.class);
BlockEntity.registerBlockEntity(BlockEntity.SHULKER_BOX, BlockEntityShulkerBox.class);
BlockEntity.registerBlockEntity(BlockEntity.MOB_SPAWNER, BlockEntityMobSpawner.class);
BlockEntity.registerBlockEntity(BlockEntity.DISPENSER, BlockEntityDispenser.class);
BlockEntity.registerBlockEntity(BlockEntity.DROPPER, BlockEntityDropper.class);
BlockEntity.registerBlockEntity(BlockEntity.COMMAND_BLOCK, BlockEntityCommandBlock.class);
BlockEntity.registerBlockEntity(BlockEntity.BANNER, BlockEntityBanner.class);
}
/**
* サーバーのインスタンスを取得します。
* @return Server サーバーのインスタンス
*/
public static Server getInstance() {
return instance;
}
/**
* GUI機能を使うかどうかを取得します。
* @return boolean 使う場合はtrue、使わない場合はfalse
*/
public boolean checkingUsingGUI(){
return this.getJupiterConfigBoolean("using-gui", true);
}
/**
* 送受信しているパケットを表示するかどうかを取得します。
* @return boolean する場合はtrue、しない場合はfalse
*/
public boolean printPackets(){
return this.printPackets;
}
/*TODO getAI()
public AI getAI() {
return this.ai;
}
*/
}
| gpl-3.0 |
Shappiro/GEOFRAME | PROJECTS/oms3.proj.richards1d/src/JAVA/parallelcolt-code/test/cern/colt/matrix/tlong/LongMatrix1DTest.java | 13407 | package cern.colt.matrix.tlong;
import java.util.Random;
import junit.framework.TestCase;
import org.junit.Test;
import cern.colt.function.tlong.LongProcedure;
import cern.colt.list.tint.IntArrayList;
import cern.colt.list.tlong.LongArrayList;
import cern.jet.math.tlong.LongFunctions;
import edu.emory.mathcs.utils.ConcurrencyUtils;
public abstract class LongMatrix1DTest extends TestCase {
/**
* Matrix to test
*/
protected LongMatrix1D A;
/**
* Matrix of the same size as a
*/
protected LongMatrix1D B;
protected int SIZE = 2 * 17 * 5;
protected Random rand = new Random(0);
/**
* Constructor for LongMatrix1DTest
*/
public LongMatrix1DTest(String arg0) {
super(arg0);
}
protected void setUp() throws Exception {
createMatrices();
populateMatrices();
}
protected abstract void createMatrices() throws Exception;
protected void populateMatrices() {
ConcurrencyUtils.setThreadsBeginN_1D(1);
for (int i = 0; i < (int) A.size(); i++) {
A.setQuick(i, Math.max(1, rand.nextLong() % A.size()));
}
for (int i = 0; i < (int) B.size(); i++) {
B.setQuick(i, Math.max(1, rand.nextLong() % A.size()));
}
}
protected void tearDown() throws Exception {
A = B = null;
}
public void testAggregateLongLongFunctionLongFunction() {
long expected = 0;
for (int i = 0; i < (int) A.size(); i++) {
long elem = A.getQuick(i);
expected += elem * elem;
}
long result = A.aggregate(LongFunctions.plus, LongFunctions.square);
assertEquals(expected, result);
}
public void testAggregateLongLongFunctionLongFunctionIntArrayList() {
IntArrayList indexList = new IntArrayList();
for (int i = 0; i < (int) A.size(); i++) {
indexList.add(i);
}
long expected = 0;
for (int i = 0; i < (int) A.size(); i++) {
long elem = A.getQuick(i);
expected += elem * elem;
}
long result = A.aggregate(LongFunctions.plus, LongFunctions.square, indexList);
assertEquals(expected, result);
}
public void testAggregateLongMatrix2DLongLongFunctionLongLongFunction() {
long expected = 0;
for (int i = 0; i < (int) A.size(); i++) {
long elemA = A.getQuick(i);
long elemB = B.getQuick(i);
expected += elemA * elemB;
}
long result = A.aggregate(B, LongFunctions.plus, LongFunctions.mult);
assertEquals(expected, result);
}
public void testAssignLong() {
long value = rand.nextLong();
A.assign(value);
for (int i = 0; i < (int) A.size(); i++) {
assertEquals(value, A.getQuick(i));
}
}
public void testAssignLongArray() {
long[] expected = new long[(int) A.size()];
for (int i = 0; i < (int) A.size(); i++) {
expected[i] = rand.nextLong();
}
A.assign(expected);
for (int i = 0; i < (int) A.size(); i++) {
assertEquals(expected[i], A.getQuick(i));
}
}
public void testAssignLongFunction() {
LongMatrix1D Acopy = A.copy();
A.assign(LongFunctions.neg);
for (int i = 0; i < (int) A.size(); i++) {
long expected = -Acopy.getQuick(i);
assertEquals(expected, A.getQuick(i));
}
}
public void testAssignLongMatrix1D() {
A.assign(B);
assertTrue(A.size() == B.size());
for (int i = 0; i < (int) A.size(); i++) {
assertEquals(B.getQuick(i), A.getQuick(i));
}
}
public void testAssignLongMatrix1DLongLongFunction() {
LongMatrix1D Acopy = A.copy();
A.assign(B, LongFunctions.plus);
for (int i = 0; i < (int) A.size(); i++) {
assertEquals(Acopy.getQuick(i) + B.getQuick(i), A.getQuick(i));
}
}
public void testAssignLongProcedureLong() {
LongProcedure procedure = new LongProcedure() {
public boolean apply(long element) {
if (Math.abs(element) > 1) {
return true;
} else {
return false;
}
}
};
LongMatrix1D Acopy = A.copy();
A.assign(procedure, -1);
for (int i = 0; i < (int) A.size(); i++) {
if (Math.abs(Acopy.getQuick(i)) > 1) {
assertEquals(-1, A.getQuick(i));
} else {
assertEquals(Acopy.getQuick(i), A.getQuick(i));
}
}
}
public void testAssignLongProcedureLongFunction() {
LongProcedure procedure = new LongProcedure() {
public boolean apply(long element) {
if (Math.abs(element) > 1) {
return true;
} else {
return false;
}
}
};
LongMatrix1D Acopy = A.copy();
A.assign(procedure, LongFunctions.neg);
for (int i = 0; i < (int) A.size(); i++) {
if (Math.abs(Acopy.getQuick(i)) > 1) {
assertEquals(-Acopy.getQuick(i), A.getQuick(i));
} else {
assertEquals(Acopy.getQuick(i), A.getQuick(i));
}
}
}
public void testCardinality() {
int card = A.cardinality();
int expected = 0;
for (int i = 0; i < A.size(); i++) {
if (A.getQuick(i) != 0)
expected++;
}
assertEquals(expected, card);
}
public void testEqualsLong() {
long value = 1;
A.assign(value);
boolean eq = A.equals(value);
assertTrue(eq);
eq = A.equals(2);
assertFalse(eq);
}
public void testEqualsObject() {
boolean eq = A.equals(A);
assertTrue(eq);
eq = A.equals(B);
assertFalse(eq);
}
public void testMaxLocation() {
A.assign(0);
A.setQuick((int) A.size() / 3, 7);
A.setQuick((int) A.size() / 2, 1);
long[] maxAndLoc = A.getMaxLocation();
assertEquals(7, maxAndLoc[0]);
assertEquals((int) A.size() / 3, (int) maxAndLoc[1]);
}
public void testMinLocation() {
A.assign(0);
A.setQuick((int) A.size() / 3, -7);
A.setQuick((int) A.size() / 2, -1);
long[] minAndLoc = A.getMinLocation();
assertEquals(-7, minAndLoc[0]);
assertEquals((int) A.size() / 3, (int) minAndLoc[1]);
}
public void testGetNegativeValuesIntArrayListLongArrayList() {
A.assign(0);
A.setQuick((int) A.size() / 3, -7);
A.setQuick((int) A.size() / 2, -1);
IntArrayList indexList = new IntArrayList();
LongArrayList valueList = new LongArrayList();
A.getNegativeValues(indexList, valueList);
assertEquals(2, indexList.size());
assertEquals(2, valueList.size());
assertTrue(indexList.contains((int) A.size() / 3));
assertTrue(indexList.contains((int) A.size() / 2));
assertTrue(valueList.contains(-7));
assertTrue(valueList.contains(-1));
}
public void testGetNonZerosIntArrayListLongArrayList() {
A.assign(0);
A.setQuick((int) A.size() / 3, 7);
A.setQuick((int) A.size() / 2, 1);
IntArrayList indexList = new IntArrayList();
LongArrayList valueList = new LongArrayList();
A.getNonZeros(indexList, valueList);
assertEquals(2, indexList.size());
assertEquals(2, valueList.size());
assertTrue(indexList.contains((int) A.size() / 3));
assertTrue(indexList.contains((int) A.size() / 2));
assertTrue(valueList.contains(7));
assertTrue(valueList.contains(1));
}
public void testGetPositiveValuesIntArrayListLongArrayList() {
A.assign(0);
A.setQuick((int) A.size() / 3, 7);
A.setQuick((int) A.size() / 2, 1);
IntArrayList indexList = new IntArrayList();
LongArrayList valueList = new LongArrayList();
A.getPositiveValues(indexList, valueList);
assertEquals(2, indexList.size());
assertEquals(2, valueList.size());
assertTrue(indexList.contains((int) A.size() / 3));
assertTrue(indexList.contains((int) A.size() / 2));
assertTrue(valueList.contains(7));
assertTrue(valueList.contains(1));
}
public void testToArray() {
long[] array = A.toArray();
assertTrue((int) A.size() == array.length);
for (int i = 0; i < (int) A.size(); i++) {
assertEquals(array[i], A.getQuick(i));
}
}
public void testToArrayLongArray() {
long[] array = new long[(int) A.size()];
A.toArray(array);
for (int i = 0; i < (int) A.size(); i++) {
assertEquals(A.getQuick(i), array[i]);
}
}
public void testReshapeIntInt() {
int rows = 10;
int columns = 17;
LongMatrix2D B = A.reshape(rows, columns);
int idx = 0;
for (int c = 0; c < columns; c++) {
for (int r = 0; r < rows; r++) {
assertEquals(A.getQuick(idx++), B.getQuick(r, c));
}
}
}
public void testReshapeIntIntInt() {
int slices = 2;
int rows = 5;
int columns = 17;
LongMatrix3D B = A.reshape(slices, rows, columns);
int idx = 0;
for (int s = 0; s < slices; s++) {
for (int c = 0; c < columns; c++) {
for (int r = 0; r < rows; r++) {
assertEquals(A.getQuick(idx++), B.getQuick(s, r, c));
}
}
}
}
public void testSwap() {
LongMatrix1D Acopy = A.copy();
LongMatrix1D Bcopy = B.copy();
A.swap(B);
for (int i = 0; i < (int) A.size(); i++) {
assertEquals(Bcopy.getQuick(i), A.getQuick(i));
assertEquals(Acopy.getQuick(i), B.getQuick(i));
}
}
public void testViewFlip() {
LongMatrix1D b = A.viewFlip();
assertEquals((int) A.size(), b.size());
for (int i = 0; i < (int) A.size(); i++) {
assertEquals(A.getQuick(i), b.getQuick((int) A.size() - 1 - i));
}
}
public void testViewPart() {
LongMatrix1D b = A.viewPart(15, 11);
for (int i = 0; i < 11; i++) {
assertEquals(A.getQuick(15 + i), b.getQuick(i));
}
}
public void testViewSelectionLongProcedure() {
LongMatrix1D b = A.viewSelection(new LongProcedure() {
public boolean apply(long element) {
return element % 2 == 0;
}
});
for (int i = 0; i < b.size(); i++) {
long el = b.getQuick(i);
if (el % 2 != 0) {
fail();
}
}
}
public void testViewSelectionIntArray() {
int[] indexes = new int[] { 5, 11, 22, 37, 101 };
LongMatrix1D b = A.viewSelection(indexes);
for (int i = 0; i < indexes.length; i++) {
assertEquals(A.getQuick(indexes[i]), b.getQuick(i));
}
}
public void testViewSorted() {
LongMatrix1D b = A.viewSorted();
for (int i = 0; i < (int) A.size() - 1; i++) {
assertTrue(b.getQuick(i + 1) >= b.getQuick(i));
}
}
public void testViewStrides() {
int stride = 3;
LongMatrix1D b = A.viewStrides(stride);
for (int i = 0; i < b.size(); i++) {
assertEquals(A.getQuick(i * stride), b.getQuick(i));
}
}
public void testZDotProductLongMatrix1D() {
long product = A.zDotProduct(B);
long expected = 0;
for (int i = 0; i < (int) A.size(); i++) {
expected += A.getQuick(i) * B.getQuick(i);
}
assertEquals(expected, product);
}
public void testZDotProductLongMatrix1DIntInt() {
long product = A.zDotProduct(B, 5, (int) B.size() - 10);
long expected = 0;
for (int i = 5; i < (int) A.size() - 5; i++) {
expected += A.getQuick(i) * B.getQuick(i);
}
assertEquals(expected, product);
}
@Test
public void testZDotProductLongMatrix1DIntIntIntArrayList() {
IntArrayList indexList = new IntArrayList();
LongArrayList valueList = new LongArrayList();
B.getNonZeros(indexList, valueList);
long product = A.zDotProduct(B, 5, (int) B.size() - 10, indexList);
long expected = 0;
for (int i = 5; i < (int) A.size() - 5; i++) {
expected += A.getQuick(i) * B.getQuick(i);
}
assertEquals(expected, product);
}
public void testZSum() {
long sum = A.zSum();
long expected = 0;
for (int i = 0; i < (int) A.size(); i++) {
expected += A.getQuick(i);
}
assertEquals(expected, sum);
}
}
| gpl-3.0 |
ariesteam/thinklab | plugins/org.integratedmodelling.thinklab.core/src/org/integratedmodelling/utils/Function1.java | 1078 | /**
* Copyright 2011 The ARIES Consortium (http://www.ariesonline.org) and
* www.integratedmodelling.org.
This file is part of Thinklab.
Thinklab 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.
Thinklab 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 Thinklab. If not, see <http://www.gnu.org/licenses/>.
*/
// author: Robert Keller
// purpose: Interface Function1 of polya package
package org.integratedmodelling.utils;
/**
* Function1 is an interface defining the function argument to map
**/
public interface Function1
{
Object apply(Object x);
}
| gpl-3.0 |
martinmladenov/SoftUni-Solutions | Software Technologies/Exam Prep 2 - TODO List/Java/src/main/java/todolist/bindingModel/TaskBindingModel.java | 411 | package todolist.bindingModel;
public class TaskBindingModel {
private String title;
private String comments;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
}
| gpl-3.0 |
cywong0827/test | src/com/watabou/pixeldungeon/levels/SewerBossLevel.java | 5853 | /*
* Pixel Dungeon
* Copyright (C) 2012-2014 Oleg Dolya
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.watabou.pixeldungeon.levels;
import java.util.ArrayList;
import java.util.List;
import com.watabou.noosa.Scene;
import com.watabou.pixeldungeon.Assets;
import com.watabou.pixeldungeon.Bones;
import com.watabou.pixeldungeon.Dungeon;
import com.watabou.pixeldungeon.actors.Actor;
import com.watabou.pixeldungeon.actors.mobs.Bestiary;
import com.watabou.pixeldungeon.actors.mobs.Mob;
import com.watabou.pixeldungeon.items.Heap;
import com.watabou.pixeldungeon.items.Item;
import com.watabou.pixeldungeon.levels.Room.Type;
import com.watabou.pixeldungeon.scenes.GameScene;
import com.watabou.utils.Bundle;
import com.watabou.utils.Graph;
import com.watabou.utils.Random;
public class SewerBossLevel extends RegularLevel {
{
color1 = 0x48763c;
color2 = 0x59994a;
}
private int stairs = 0;
@Override
public String tilesTex() {
return Assets.TILES_SEWERS;
}
@Override
public String waterTex() {
return Assets.WATER_SEWERS;
}
@Override
protected boolean build() {
initRooms();
int distance;
int retry = 0;
int minDistance = (int)Math.sqrt( rooms.size() );
do {
int innerRetry = 0;
do {
if (innerRetry++ > 10) {
return false;
}
roomEntrance = Random.element( rooms );
} while (roomEntrance.width() < 4 || roomEntrance.height() < 4);
innerRetry = 0;
do {
if (innerRetry++ > 10) {
return false;
}
roomExit = Random.element( rooms );
} while (roomExit == roomEntrance || roomExit.width() < 6 || roomExit.height() < 6 || roomExit.top == 0);
Graph.buildDistanceMap( rooms, roomExit );
distance = roomEntrance.distance();
if (retry++ > 10) {
return false;
}
} while (distance < minDistance);
roomEntrance.type = Type.ENTRANCE;
roomExit.type = Type.BOSS_EXIT;
Graph.buildDistanceMap( rooms, roomExit );
List<Room> path = Graph.buildPath( rooms, roomEntrance, roomExit );
Graph.setPrice( path, roomEntrance.distance );
Graph.buildDistanceMap( rooms, roomExit );
path = Graph.buildPath( rooms, roomEntrance, roomExit );
Room room = roomEntrance;
for (Room next : path) {
room.connect( next );
room = next;
}
room = (Room)roomExit.connected.keySet().toArray()[0];
if (roomExit.top == room.bottom) {
return false;
}
for (Room r : rooms) {
if (r.type == Type.NULL && r.connected.size() > 0) {
r.type = Type.TUNNEL;
}
}
ArrayList<Room> candidates = new ArrayList<Room>();
for (Room r : roomExit.neigbours) {
if (!roomExit.connected.containsKey( r ) &&
(roomExit.left == r.right || roomExit.right == r.left || roomExit.bottom == r.top)) {
candidates.add( r );
}
}
if (candidates.size() > 0) {
Room kingsRoom = Random.element( candidates );
kingsRoom.connect( roomExit );
kingsRoom.type = Room.Type.RAT_KING;
}
paint();
paintWater();
paintGrass();
placeTraps();
return true;
}
protected boolean[] water() {
return Patch.generate( 0.5f, 5 );
}
protected boolean[] grass() {
return Patch.generate( 0.40f, 4 );
}
@Override
protected void decorate() {
int start = roomExit.top * WIDTH + roomExit.left + 1;
int end = start + roomExit.width() - 1;
for (int i=start; i < end; i++) {
if (i != exit) {
map[i] = Terrain.WALL_DECO;
map[i + WIDTH] = Terrain.WATER;
} else {
map[i + WIDTH] = Terrain.EMPTY;
}
}
while (true) {
int pos = roomEntrance.random();
if (pos != entrance) {
map[pos] = Terrain.SIGN;
break;
}
}
}
@Override
public void addVisuals( Scene scene ) {
SewerLevel.addVisuals( this, scene );
}
@Override
protected void createMobs() {
Mob mob = Bestiary.mob( Dungeon.depth );
mob.pos = roomExit.random();
mobs.add( mob );
}
public Actor respawner() {
return null;
}
@Override
protected void createItems() {
Item item = Bones.get();
if (item != null) {
int pos;
do {
pos = roomEntrance.random();
} while (pos == entrance || map[pos] == Terrain.SIGN);
drop( item, pos ).type = Heap.Type.SKELETON;
}
}
public void seal() {
if (entrance != 0) {
set( entrance, Terrain.WATER_TILES );
GameScene.updateMap( entrance );
GameScene.ripple( entrance );
stairs = entrance;
entrance = 0;
}
}
public void unseal() {
if (stairs != 0) {
entrance = stairs;
stairs = 0;
set( entrance, Terrain.ENTRANCE );
GameScene.updateMap( entrance );
}
}
private static final String STAIRS = "stairs";
@Override
public void storeInBundle( Bundle bundle ) {
super.storeInBundle( bundle );
bundle.put( STAIRS, stairs );
}
@Override
public void restoreFromBundle( Bundle bundle ) {
super.restoreFromBundle( bundle );
stairs = bundle.getInt( STAIRS );
}
@Override
public String tileName( int tile ) {
switch (tile) {
case Terrain.WATER:
return "Murky water";
default:
return super.tileName( tile );
}
}
@Override
public String tileDesc( int tile ) {
switch (tile) {
case Terrain.EMPTY_DECO:
return "Wet yellowish moss covers the floor.";
default:
return super.tileDesc( tile );
}
}
}
| gpl-3.0 |
renqingyou/VirtualApp | VirtualApp/app/src/main/java/io/virtualapp/widgets/showcase/IDetachedListener.java | 163 | package io.virtualapp.widgets.showcase;
public interface IDetachedListener {
void onShowcaseDetached(MaterialShowcaseView showcaseView, boolean wasDismissed);
}
| gpl-3.0 |
stefano-bragaglia/XHAIL | src/test/java/xhail/core/terms/SchemeTest.java | 4286 | /**
*
*/
package xhail.core.terms;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.BeforeClass;
import org.junit.Test;
import xhail.core.terms.Placemarker.Type;
/**
* @author stefano
*
*/
public class SchemeTest {
private static final String FLUENT = "fluent";
private static final String FLUENT_V1 = "fluent(V1)";
private static final String HAPPENS = "happens";
private static final String HOLDS_AT = "holdsAt";
private static Scheme scheme1;
private static Scheme scheme2;
private static final String SUGAR = "sugar";
private static final String SUGAR_V1 = "sugar(V1)";
private static final String TIME = "time";
private static final String TIME_V2 = "time(V2)";
private static final String USE = "use";
private static final String V1 = "V1";
private static final String V2 = "V2";
/**
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception {
// #modeh happens(use($sugar), +time).
scheme1 = new Scheme.Builder(HAPPENS) //
.addTerm(new Scheme.Builder(USE).addTerm(//
new Placemarker.Builder(SUGAR).setType(Type.CONSTANT).build()).build()) //
.addTerm(new Placemarker.Builder(TIME).setType(Type.INPUT).build()) //
.build();
// #modeb holdsAt($fluent, +time).
scheme2 = new Scheme.Builder(HOLDS_AT) //
.addTerm(new Placemarker.Builder(FLUENT).setType(Type.CONSTANT).build()) //
.addTerm(new Placemarker.Builder(TIME).setType(Type.INPUT).build()) //
.build();
}
@Test
public void testPlacemarkers1() {
Placemarker[] result = scheme1.getPlacemarkers();
assertNotNull("Scheme1: placemarkers can not be null", result);
assertEquals("Scheme1: placemarkers must have size 2", 2, result.length);
assertEquals("Scheme1: first placemarker must be CONSTANT", Type.CONSTANT, result[0].getType());
assertEquals("Scheme1: first placemarker must be 'sugar'", SUGAR, result[0].getIdentifier());
assertEquals("Scheme1: second placemarker must be CONSTANT", Type.INPUT, result[1].getType());
assertEquals("Scheme1: second placemarker must be 'time'", TIME, result[1].getIdentifier());
}
@Test
public void testPlacemarkers2() {
Placemarker[] result = scheme2.getPlacemarkers();
assertNotNull("Scheme2: placemarkers can not be null", result);
assertEquals("Scheme2: placemarkers must have size 2", 2, result.length);
assertEquals("Scheme2: first placemarker must be CONSTANT", Type.CONSTANT, result[0].getType());
assertEquals("Scheme2: first placemarker must be 'fluent'", FLUENT, result[0].getIdentifier());
assertEquals("Scheme2: second placemarker must be CONSTANT", Type.INPUT, result[1].getType());
assertEquals("Scheme2: second placemarker must be 'time'", TIME, result[1].getIdentifier());
}
@Test
public void testTypes1() {
String[] result = scheme1.getTypes();
assertNotNull("Scheme1: types can not be null", result);
assertEquals("Scheme1: types must have size 2", 2, result.length);
assertEquals("Scheme1: first type must be 'sugar(V1)'", SUGAR_V1, result[0]);
assertEquals("Scheme1: second type must be 'time(V2)'", TIME_V2, result[1]);
}
@Test
public void testTypes2() {
String[] result = scheme2.getTypes();
assertNotNull("Scheme2: types can not be null", result);
assertEquals("Scheme2: types must have size 2", 2, result.length);
assertEquals("Scheme2: first type must be 'fluent(V1)'", FLUENT_V1, result[0]);
assertEquals("Scheme2: second type must be 'time(V2)'", TIME_V2, result[1]);
}
@Test
public void testVariables1() {
String[] result = scheme1.getVariables();
assertNotNull("Scheme1: variables can not be null", result);
assertEquals("Scheme1: variables must have size 2", 2, result.length);
assertEquals("Scheme1: first variable must be 'V1'", V1, result[0]);
assertEquals("Scheme1: second variable must be 'V2'", V2, result[1]);
}
@Test
public void testVariables2() {
String[] result = scheme2.getVariables();
assertNotNull("Scheme2: variables can not be null", result);
assertEquals("Scheme2: variables must have size 2", 2, result.length);
assertEquals("Scheme2: first variable must be 'V1'", V1, result[0]);
assertEquals("Scheme2: second variable must be 'V2'", V2, result[1]);
}
}
| gpl-3.0 |
alexescalonafernandez/GsonForRestful | GsonForRestfulWebService/src/rest/ws/gson/deserializer/request/delete/DeleteRequestDeserializer.java | 1451 | /*
* 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 rest.ws.gson.deserializer.request.delete;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonElement;
import static rest.ws.gson.GsonUtils.*;
import rest.ws.gson.deserializer.entity.EntityMetadata;
import rest.ws.gson.deserializer.request.RequestDeserializer;
import rest.ws.gson.message.Message;
import static rest.gson.common.MessageReservedWord.*;
import java.lang.reflect.Type;
import javax.persistence.EntityManager;
import javax.servlet.ServletContext;
import javax.ws.rs.core.UriInfo;
/**
*
* @author alexander.escalona
*/
public class DeleteRequestDeserializer extends RequestDeserializer{
public DeleteRequestDeserializer(EntityManager entityManager, UriInfo uriInfo, ServletContext servletContext) {
super(entityManager, uriInfo, servletContext);
}
@Override
public String getOperationErrorType() {
return DELETE_FAIL;
}
@Override
public Message getResponse(JsonElement je, Type type, JsonDeserializationContext jdc) {
EntityMetadata entityMetadata = entityClass2EntityMetadata(entityClass);
return buildDeleteEntityRequestDeserializer(
entityClass, dataType, entityManager, entityMetadata).deserialize(je, type, jdc);
}
}
| gpl-3.0 |
abmindiarepomanager/ABMOpenMainet | Mainet1.1/MainetBRMS/Mainet_BRMS_BPMN/src/main/java/com/abm/mainet/brms/entity/TbComparentDetEntity.java | 9206 | /*
* Created on 6 Aug 2015 ( Time 16:35:19 )
* Generated by Telosys Tools Generator ( version 2.1.1 )
*/
// This Bean has a basic Primary Key (not composite)
package com.abm.mainet.brms.entity;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
/**
* Persistent class for entity stored in table "TB_COMPARENT_DET"
*
* @author Telosys Tools Generator
*
*/
@Entity
@Table(name="TB_COMPARENT_DET")
// Define named queries here
@NamedQueries ( {
@NamedQuery ( name="TbComparentDetEntity.countAll", query="SELECT COUNT(x) FROM TbComparentDetEntity x" )
} )
public class TbComparentDetEntity implements Serializable {
private static final long serialVersionUID = 1L;
//----------------------------------------------------------------------
// ENTITY PRIMARY KEY ( BASED ON A SINGLE FIELD )
//----------------------------------------------------------------------
@Id
@Column(name="COD_ID", nullable=false)
private Long codId ;
//----------------------------------------------------------------------
// ENTITY DATA FIELDS
//----------------------------------------------------------------------
@Column(name="COD_DESC", nullable=false)
private String codDesc ;
@Column(name="COD_VALUE", nullable=false)
private String codValue ;
@Column(name="ORGID", nullable=false)
private Long orgid ;
@Column(name="USER_ID", nullable=false)
private Long userId ;
@Column(name="LANG_ID", nullable=false)
private Long langId ;
@Temporal(TemporalType.TIMESTAMP)
@Column(name="LMODDATE", nullable=false)
private Date lmoddate ;
@Column(name="UPDATED_BY")
private Long updatedBy ;
@Temporal(TemporalType.TIMESTAMP)
@Column(name="UPDATED_DATE")
private Date updatedDate ;
@Column(name="CPD_DEFAULT", length=1)
private String cpdDefault ;
@Column(name="COD_STATUS")
private String codStatus ;
@Column(name="COD_DESC_MAR")
private String codDescMar ;
@Column(name="LG_IP_MAC", length=100)
private String lgIpMac ;
@Column(name="LG_IP_MAC_UPD", length=100)
private String lgIpMacUpd ;
// "comId" (column "COM_ID") is not defined by itself because used as FK in a link
// "parentId" (column "PARENT_ID") is not defined by itself because used as FK in a link
//----------------------------------------------------------------------
// ENTITY LINKS ( RELATIONSHIP )
//----------------------------------------------------------------------
@ManyToOne
@JoinColumn(name="PARENT_ID", referencedColumnName="COD_ID")
private TbComparentDetEntity tbComparentDet;
@ManyToOne
@JoinColumn(name="COM_ID", referencedColumnName="COM_ID")
private TbComparentMasEntity tbComparentMas;
@OneToMany(mappedBy="tbComparentDet", targetEntity=TbComparentDetEntity.class)
private List<TbComparentDetEntity> listOfTbComparentDet;
@Transient
private long tempId;
//----------------------------------------------------------------------
// CONSTRUCTOR(S)
//----------------------------------------------------------------------
public TbComparentDetEntity() {
super();
}
//----------------------------------------------------------------------
// GETTER & SETTER FOR THE KEY FIELD
//----------------------------------------------------------------------
public void setCodId( Long codId ) {
this.codId = codId ;
}
public Long getCodId() {
return this.codId;
}
//----------------------------------------------------------------------
// GETTERS & SETTERS FOR FIELDS
//----------------------------------------------------------------------
//--- DATABASE MAPPING : COD_DESC ( NVARCHAR2 )
public void setCodDesc( String codDesc ) {
this.codDesc = codDesc;
}
public String getCodDesc() {
return this.codDesc;
}
//--- DATABASE MAPPING : COD_VALUE ( NVARCHAR2 )
public void setCodValue( String codValue ) {
this.codValue = codValue;
}
public String getCodValue() {
return this.codValue;
}
//--- DATABASE MAPPING : ORGID ( NUMBER )
public void setOrgid( Long orgid ) {
this.orgid = orgid;
}
public Long getOrgid() {
return this.orgid;
}
//--- DATABASE MAPPING : USER_ID ( NUMBER )
public void setUserId( Long userId ) {
this.userId = userId;
}
public Long getUserId() {
return this.userId;
}
//--- DATABASE MAPPING : LANG_ID ( NUMBER )
public void setLangId( Long langId ) {
this.langId = langId;
}
public Long getLangId() {
return this.langId;
}
//--- DATABASE MAPPING : LMODDATE ( DATE )
public void setLmoddate( Date lmoddate ) {
this.lmoddate = lmoddate;
}
public Date getLmoddate() {
return this.lmoddate;
}
//--- DATABASE MAPPING : UPDATED_BY ( NUMBER )
public void setUpdatedBy( Long updatedBy ) {
this.updatedBy = updatedBy;
}
public Long getUpdatedBy() {
return this.updatedBy;
}
//--- DATABASE MAPPING : UPDATED_DATE ( DATE )
public void setUpdatedDate( Date updatedDate ) {
this.updatedDate = updatedDate;
}
public Date getUpdatedDate() {
return this.updatedDate;
}
//--- DATABASE MAPPING : CPD_DEFAULT ( CHAR )
public void setCpdDefault( String cpdDefault ) {
this.cpdDefault = cpdDefault;
}
public String getCpdDefault() {
return this.cpdDefault;
}
//--- DATABASE MAPPING : COD_STATUS ( NVARCHAR2 )
public void setCodStatus( String codStatus ) {
this.codStatus = codStatus;
}
public String getCodStatus() {
return this.codStatus;
}
//--- DATABASE MAPPING : COD_DESC_MAR ( NVARCHAR2 )
public void setCodDescMar( String codDescMar ) {
this.codDescMar = codDescMar;
}
public String getCodDescMar() {
return this.codDescMar;
}
//--- DATABASE MAPPING : LG_IP_MAC ( VARCHAR2 )
public void setLgIpMac( String lgIpMac ) {
this.lgIpMac = lgIpMac;
}
public String getLgIpMac() {
return this.lgIpMac;
}
//--- DATABASE MAPPING : LG_IP_MAC_UPD ( VARCHAR2 )
public void setLgIpMacUpd( String lgIpMacUpd ) {
this.lgIpMacUpd = lgIpMacUpd;
}
public String getLgIpMacUpd() {
return this.lgIpMacUpd;
}
//----------------------------------------------------------------------
// GETTERS & SETTERS FOR LINKS
//----------------------------------------------------------------------
public void setTbComparentDet( TbComparentDetEntity tbComparentDet ) {
this.tbComparentDet = tbComparentDet;
}
public TbComparentDetEntity getTbComparentDet() {
return this.tbComparentDet;
}
public void setTbComparentMas( TbComparentMasEntity tbComparentMas ) {
this.tbComparentMas = tbComparentMas;
}
public TbComparentMasEntity getTbComparentMas() {
return this.tbComparentMas;
}
public void setListOfTbComparentDet( List<TbComparentDetEntity> listOfTbComparentDet ) {
this.listOfTbComparentDet = listOfTbComparentDet;
}
public List<TbComparentDetEntity> getListOfTbComparentDet() {
return this.listOfTbComparentDet;
}
public long getTempId() {
return tempId;
}
public void setTempId(long tempId) {
this.tempId = tempId;
}
//----------------------------------------------------------------------
// toString METHOD
//----------------------------------------------------------------------
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("[");
sb.append(codId);
sb.append("]:");
sb.append(codDesc);
sb.append("|");
sb.append(codValue);
sb.append("|");
sb.append(orgid);
sb.append("|");
sb.append(userId);
sb.append("|");
sb.append(langId);
sb.append("|");
sb.append(lmoddate);
sb.append("|");
sb.append(updatedBy);
sb.append("|");
sb.append(updatedDate);
sb.append("|");
sb.append(cpdDefault);
sb.append("|");
sb.append(codStatus);
sb.append("|");
sb.append(codDescMar);
sb.append("|");
sb.append(lgIpMac);
sb.append("|");
sb.append(lgIpMacUpd);
return sb.toString();
}
public String[] getPkValues() {
return new String[] { "COM", "TB_COMPARENT_DET", "COD_ID" };
}
}
| gpl-3.0 |
idega/platform2 | src/se/idega/idegaweb/commune/accounting/regulations/business/LowIncomeException.java | 590 | /*
* Copyright (C) 2003 Idega software. All Rights Reserved.
*
* This software is the proprietary information of Idega software.
* Use is subject to license terms.
*
*/
package se.idega.idegaweb.commune.accounting.regulations.business;
import se.idega.idegaweb.commune.accounting.business.AccountingException;
/**
* @author palli
*/
public class LowIncomeException extends AccountingException {
/**
* @see se.idega.idegaweb.commune.accounting.business.AccountingException
*/
public LowIncomeException(String textKey, String defaultText) {
super(textKey, defaultText);
}
} | gpl-3.0 |
Mrkwtkr/shinsei | src/main/java/com/megathirio/shinsei/item/tool/SwordShinsei.java | 1342 | package com.megathirio.shinsei.item.tool;
import com.megathirio.shinsei.init.ShinseiTabs;
import com.megathirio.shinsei.reference.Reference;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.item.ItemSword;
import net.minecraft.item.ItemStack;
public class SwordShinsei extends ItemSword {
//Default Axe Properties
public SwordShinsei(ToolMaterial material) {
super(material);
setCreativeTab(ShinseiTabs.TOOLS_TAB);
}
@Override
public String getUnlocalizedName(){
return String.format("item.%s%s", Reference.RESOURCE_PREFIX, getUnwrappedUnlocalizedName(super.getUnlocalizedName()));
}
@Override
public String getUnlocalizedName(ItemStack istack){
return String.format("item.%s%s", Reference.RESOURCE_PREFIX, getUnwrappedUnlocalizedName(super.getUnlocalizedName()));
}
protected String getUnwrappedUnlocalizedName(String unlocalizedName){
return unlocalizedName.substring(unlocalizedName.indexOf(".") + 1);
}
//Set Axe Texture
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IIconRegister iconRegister){
itemIcon = iconRegister.registerIcon(this.getUnlocalizedName().substring(this.getUnlocalizedName().indexOf(".") + 1));
}
} | gpl-3.0 |
sensiasoft/sensorhub-core | sensorhub-service-swe/src/main/java/org/sensorhub/impl/service/sos/SOSServiceConfig.java | 2180 | /***************************** BEGIN LICENSE BLOCK ***************************
The contents of this file are subject to the Mozilla Public License, v. 2.0.
If a copy of the MPL was not distributed with this file, You can obtain one
at http://mozilla.org/MPL/2.0/.
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.
Copyright (C) 2012-2015 Sensia Software LLC. All Rights Reserved.
******************************* END LICENSE BLOCK ***************************/
package org.sensorhub.impl.service.sos;
import java.util.ArrayList;
import java.util.List;
import org.sensorhub.api.config.DisplayInfo;
import org.sensorhub.api.persistence.StorageConfig;
import org.sensorhub.impl.service.ogc.OGCServiceConfig;
/**
* <p>
* Configuration class for the SOS service module
* </p>
*
* @author Alex Robin <alex.robin@sensiasoftware.com>
* @since Sep 7, 2013
*/
public class SOSServiceConfig extends OGCServiceConfig
{
@DisplayInfo(desc="Set to true to enable transactional operation support")
public boolean enableTransactional = false;
@DisplayInfo(label="Max Observations Returned", desc="Maximum number of observations returned by a historical GetObservation request (for each selected offering)")
public int maxObsCount = 100;
@DisplayInfo(label="Max Records Returned", desc="Maximum number of result records returned by a historical GetResult request")
public int maxRecordCount = 100000;
@DisplayInfo(desc="Storage configuration to use for newly registered sensors")
public StorageConfig newStorageConfig;
@DisplayInfo(label="Offerings", desc="Configuration of data providers for SOS offerings")
public List<SOSProviderConfig> dataProviders = new ArrayList<SOSProviderConfig>();
@DisplayInfo(desc="Configuration of data consumers for SOS offerings created by SOS-T")
public List<SOSConsumerConfig> dataConsumers = new ArrayList<SOSConsumerConfig>();
}
| mpl-2.0 |
tingstad/collections | collections-core/src/test/java/com/rictin/test/transitive/HasDates.java | 345 | /* Copyright 2014 Richard H. Tingstad
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.rictin.test.transitive;
public interface HasDates {
HasYearOfBirth getDates();
}
| mpl-2.0 |
ydautremay/seed | metrics-support/src/it/java/org/seedstack/seed/metrics/internal/InjectedHealthCheck.java | 825 | /**
* Copyright (c) 2013-2015 by The SeedStack authors. All rights reserved.
*
* This file is part of SeedStack, An enterprise-oriented full development stack.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.seedstack.seed.metrics.internal;
import com.codahale.metrics.health.HealthCheck;
import org.seedstack.seed.core.api.DiagnosticManager;
import javax.inject.Inject;
public class InjectedHealthCheck extends HealthCheck {
@Inject
DiagnosticManager diagnosticManager;
@Override
protected Result check() throws Exception {
return diagnosticManager == null ? Result.unhealthy("not injected") : Result.healthy();
}
}
| mpl-2.0 |
webdetails/cdc | cdc-pentaho-base/src/pt/webdetails/cdc/plugin/CdcLifeCycleListener.java | 5043 | /*!
* Copyright 2002 - 2014 Webdetails, a Pentaho company. All rights reserved.
*
* This software was developed by Webdetails and is provided under the terms
* of the Mozilla Public License, Version 2.0, or any later version. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to http://mozilla.org/MPL/2.0/. The Initial Developer is Webdetails.
*
* Software distributed under the Mozilla Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
* the license for the specific language governing your rights and limitations.
*/
package pt.webdetails.cdc.plugin;
import java.util.List;
import java.util.Locale;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.pentaho.platform.api.engine.IPentahoSession;
import org.pentaho.platform.api.engine.IPluginLifecycleListener;
import org.pentaho.platform.api.engine.PluginLifecycleException;
import org.pentaho.platform.engine.core.system.PentahoSystem;
import org.pentaho.platform.plugin.action.mondrian.catalog.IMondrianCatalogService;
import org.pentaho.platform.util.messages.LocaleHelper;
import pt.webdetails.cdc.core.HazelcastManager;
import pt.webdetails.cdc.core.ICdcConfig;
import pt.webdetails.cdc.ws.MondrianCacheCleanService;
/**
* Responsible for setting up distributed cache from configuration.
*/
public class CdcLifeCycleListener implements IPluginLifecycleListener {
private static HazelcastManager hazelcastManager = HazelcastManager.INSTANCE;
static Log logger = LogFactory.getLog( CdcLifeCycleListener.class );
@Override
public void init() throws PluginLifecycleException {
logger.debug( "init" );
}
@Override
public void loaded() throws PluginLifecycleException {
logger.debug( "CDC loaded." );
setHazelcastOptionsFromConfig();
try {
//do we need it to run?
hazelcastManager.configure( CdcConfig.getConfig() );
if ( CdcConfig.getConfig().isMondrianCdcEnabled() || ExternalConfigurationsHelper.isCdaHazelcastEnabled() ) {
hazelcastManager.setMaster( CdcConfig.getConfig().isMaster() );
if ( CdcConfig.getConfig().isAsyncInit() ) {
logger.info( "Initializing Hazelcast in new thread." );
Thread initDaemon = new Thread(
new Runnable() {
@Override
public void run() {
try {
hazelcastManager.init();
listCatalogsInLocales();
} catch ( Exception e ) {
logger.fatal( "CDC init failed.", e );
}
}
}
);
initDaemon.setDaemon( true );
initDaemon.start();
} else {
hazelcastManager.init();
if ( CdcConfig.getConfig().isSyncCacheOnStart() ) {
MondrianCacheCleanService.loadMondrianCatalogs();
hazelcastManager.reloadMondrianCache();
}
listCatalogsInLocales();
}
}
} catch ( Exception e ) {
logger.error( e );
logger.error( "CDC couldn't be properly initialized!" );
}
}
private void listCatalogsInLocales() {
//Trying to ensure all locales are covered
//TODO: explain why are we doing this
List<String> configuredLocales = CdcConfig.getConfig().getLocales();
Locale[] locales;
Locale originalLocale = LocaleHelper.getLocale();
if ( configuredLocales.size() == 1 && "all".equals( configuredLocales.get( 0 ) ) ) {
locales = Locale.getAvailableLocales();
} else {
locales = new Locale[configuredLocales.size()];
for ( int i = 0; i < configuredLocales.size(); i++ ) {
String[] splitLocale = configuredLocales.get( i ).split( "_" );
locales[i] = new Locale( splitLocale[0], splitLocale[1] );
}
}
logger.debug( "Setting schema cache for " + locales.length + " locales." );
IMondrianCatalogService mondrianCatalogService =
PentahoSystem.get( IMondrianCatalogService.class, IMondrianCatalogService.class.getSimpleName(), null );
for ( int i = 0; i < locales.length; i++ ) {
LocaleHelper.setLocale( locales[i] );
mondrianCatalogService.listCatalogs( CdcLifeCycleListener.getSessionForCatalogCache(), true );
}
logger.debug( "Reverting to original locale " + originalLocale );
LocaleHelper.setLocale( originalLocale );
}
@Override
public void unLoaded() throws PluginLifecycleException {
logger.debug( "CDC Unloading..." );
hazelcastManager.tearDown();
logger.debug( "CDC Unloaded." );
}
private void setHazelcastOptionsFromConfig() {
HazelcastManager hazelcastMgr = HazelcastManager.INSTANCE;
ICdcConfig config = CdcConfig.getConfig();
hazelcastMgr.configure( config );
}
private static IPentahoSession getSessionForCatalogCache() {
return PentahoSystem.get( IPentahoSession.class, "systemStartupSession", null );
}
}
| mpl-2.0 |
miloszpiglas/h2mod | src/test/org/h2/test/coverage/Tokenizer.java | 7902 | /*
* Copyright 2004-2013 H2 Group. Multiple-Licensed under the H2 License,
* Version 1.0, and under the Eclipse Public License, Version 1.0
* (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.test.coverage;
import java.io.EOFException;
import java.io.IOException;
import java.io.Reader;
/**
* Helper class for the java file parser.
*/
public class Tokenizer {
/**
* This token type means no more tokens are available.
*/
static final int TYPE_EOF = -1;
private static final int TYPE_WORD = -2;
private static final int TYPE_NOTHING = -3;
private static final byte WHITESPACE = 1;
private static final byte ALPHA = 4;
private static final byte QUOTE = 8;
private StringBuilder buffer;
private Reader reader;
private char[] chars = new char[20];
private int peekChar;
private int line = 1;
private byte[] charTypes = new byte[256];
private int type = TYPE_NOTHING;
private String value;
private Tokenizer() {
wordChars('a', 'z');
wordChars('A', 'Z');
wordChars('0', '9');
wordChars('.', '.');
wordChars('+', '+');
wordChars('-', '-');
wordChars('_', '_');
wordChars(128 + 32, 255);
whitespaceChars(0, ' ');
charTypes['"'] = QUOTE;
charTypes['\''] = QUOTE;
}
Tokenizer(Reader r) {
this();
reader = r;
}
String getString() {
return value;
}
private void wordChars(int low, int hi) {
while (low <= hi) {
charTypes[low++] |= ALPHA;
}
}
private void whitespaceChars(int low, int hi) {
while (low <= hi) {
charTypes[low++] = WHITESPACE;
}
}
private int read() throws IOException {
int i = reader.read();
if (i != -1) {
append(i);
}
return i;
}
/**
* Initialize the tokenizer.
*/
void initToken() {
buffer = new StringBuilder();
}
String getToken() {
buffer.setLength(buffer.length() - 1);
return buffer.toString();
}
private void append(int i) {
buffer.append((char) i);
}
/**
* Read the next token and get the token type.
*
* @return the token type
*/
int nextToken() throws IOException {
byte[] ct = charTypes;
int c;
value = null;
if (type == TYPE_NOTHING) {
c = read();
if (c >= 0) {
type = c;
}
} else {
c = peekChar;
if (c < 0) {
try {
c = read();
if (c >= 0) {
type = c;
}
} catch (EOFException e) {
c = -1;
}
}
}
if (c < 0) {
return type = TYPE_EOF;
}
int charType = c < 256 ? ct[c] : ALPHA;
while ((charType & WHITESPACE) != 0) {
if (c == '\r') {
line++;
c = read();
if (c == '\n') {
c = read();
}
} else {
if (c == '\n') {
line++;
}
c = read();
}
if (c < 0) {
return type = TYPE_EOF;
}
charType = c < 256 ? ct[c] : ALPHA;
}
if ((charType & ALPHA) != 0) {
initToken();
append(c);
int i = 0;
do {
if (i >= chars.length) {
char[] nb = new char[chars.length * 2];
System.arraycopy(chars, 0, nb, 0, chars.length);
chars = nb;
}
chars[i++] = (char) c;
c = read();
charType = c < 0 ? WHITESPACE : c < 256 ? ct[c] : ALPHA;
} while ((charType & ALPHA) != 0);
peekChar = c;
value = String.copyValueOf(chars, 0, i);
return type = TYPE_WORD;
}
if ((charType & QUOTE) != 0) {
initToken();
append(c);
type = c;
int i = 0;
// \octal needs a lookahead
peekChar = read();
while (peekChar >= 0 && peekChar != type && peekChar != '\n'
&& peekChar != '\r') {
if (peekChar == '\\') {
c = read();
// to allow \377, but not \477
int first = c;
if (c >= '0' && c <= '7') {
c = c - '0';
int c2 = read();
if ('0' <= c2 && c2 <= '7') {
c = (c << 3) + (c2 - '0');
c2 = read();
if ('0' <= c2 && c2 <= '7' && first <= '3') {
c = (c << 3) + (c2 - '0');
peekChar = read();
} else {
peekChar = c2;
}
} else {
peekChar = c2;
}
} else {
switch (c) {
case 'b':
c = '\b';
break;
case 'f':
c = '\f';
break;
case 'n':
c = '\n';
break;
case 'r':
c = '\r';
break;
case 't':
c = '\t';
break;
default:
}
peekChar = read();
}
} else {
c = peekChar;
peekChar = read();
}
if (i >= chars.length) {
char[] nb = new char[chars.length * 2];
System.arraycopy(chars, 0, nb, 0, chars.length);
chars = nb;
}
chars[i++] = (char) c;
}
if (peekChar == type) {
// keep \n or \r intact in peekChar
peekChar = read();
}
value = String.copyValueOf(chars, 0, i);
return type;
}
if (c == '/') {
c = read();
if (c == '*') {
int prevChar = 0;
while ((c = read()) != '/' || prevChar != '*') {
if (c == '\r') {
line++;
c = read();
if (c == '\n') {
c = read();
}
} else {
if (c == '\n') {
line++;
c = read();
}
}
if (c < 0) {
return type = TYPE_EOF;
}
prevChar = c;
}
peekChar = read();
return nextToken();
} else if (c == '/') {
while ((c = read()) != '\n' && c != '\r' && c >= 0) {
// nothing
}
peekChar = c;
return nextToken();
} else {
peekChar = c;
return type = '/';
}
}
peekChar = read();
return type = c;
}
int getLine() {
return line;
}
}
| mpl-2.0 |
decoit/siem-gui-imonitor | src/main/java/de/decoit/siemgui/service/converter/DateConverter.java | 2939 | /*
* Copyright (C) 2015 DECOIT GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.decoit.siemgui.service.converter;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.Date;
import org.springframework.stereotype.Service;
/**
* Utility class to convert between old school date API objects and the new Java 8 date API objects.
*
* @author Thomas Rix (rix@decoit.de)
*/
@Service
public class DateConverter {
/**
* Convert a Date object to a Java 8 LocalDateTime object.
*
* @param input The Date object
* @return The converted LocalDateTime object, null if input was null
*/
public LocalDateTime dateToLocalDateTime(Date input) {
if (input != null) {
// The date objects is similar to an Instant, thus apply local time zone to the Instant and convert that to LocalDateTime
return input.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
}
else {
return null;
}
}
/**
* Convert a Date object to a Java 8 LocalDateTime object.
* This method is able to convert Date objects that contain a GMT timestamp instead
* of a local time. Information stored in Date is always treated as local time, thus
* some additional work is required to get the correct LocalDateTime object.
*
* @param input The Date object with GMT time
* @return The converted LocalDateTime object, null if input was null
*/
public LocalDateTime gmtDateToLocalDateTime(Date input) {
if (input != null) {
// Date objects always represent time at local time zone. If the Date object contains a UTC time,
// we have to do some juggling with time zones to get the correct local time after conversion.
return input.toInstant().atZone(ZoneId.systemDefault()).withZoneSameLocal(ZoneOffset.UTC).withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime();
}
else {
return null;
}
}
/**
* Convert a LocalDateTime to an old school Date object.
*
* @param input The LocalDateTime object
* @return The converted Date object, null if input was null
*/
public Date localDateTimeToDate(LocalDateTime input) {
if (input != null) {
Instant instant = input.atZone(ZoneId.systemDefault()).toInstant();
return Date.from(instant);
}
else {
return null;
}
}
}
| agpl-3.0 |
openhealthcare/openMAXIMS | openmaxims_workspace/ValueObjects/src/ims/therapies/vo/DrivingAspectVoCollection.java | 8288 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.therapies.vo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import ims.framework.enumerations.SortOrder;
/**
* Linked to therapies.workLeisureDriving.DrivingAspect business object (ID: 1019100077).
*/
public class DrivingAspectVoCollection extends ims.vo.ValueObjectCollection implements ims.vo.ImsCloneable, Iterable<DrivingAspectVo>
{
private static final long serialVersionUID = 1L;
private ArrayList<DrivingAspectVo> col = new ArrayList<DrivingAspectVo>();
public String getBoClassName()
{
return "ims.therapies.workleisuredriving.domain.objects.DrivingAspect";
}
public boolean add(DrivingAspectVo value)
{
if(value == null)
return false;
if(this.col.indexOf(value) < 0)
{
return this.col.add(value);
}
return false;
}
public boolean add(int index, DrivingAspectVo value)
{
if(value == null)
return false;
if(this.col.indexOf(value) < 0)
{
this.col.add(index, value);
return true;
}
return false;
}
public void clear()
{
this.col.clear();
}
public void remove(int index)
{
this.col.remove(index);
}
public int size()
{
return this.col.size();
}
public int indexOf(DrivingAspectVo instance)
{
return col.indexOf(instance);
}
public DrivingAspectVo get(int index)
{
return this.col.get(index);
}
public boolean set(int index, DrivingAspectVo value)
{
if(value == null)
return false;
this.col.set(index, value);
return true;
}
public void remove(DrivingAspectVo instance)
{
if(instance != null)
{
int index = indexOf(instance);
if(index >= 0)
remove(index);
}
}
public boolean contains(DrivingAspectVo instance)
{
return indexOf(instance) >= 0;
}
public Object clone()
{
DrivingAspectVoCollection clone = new DrivingAspectVoCollection();
for(int x = 0; x < this.col.size(); x++)
{
if(this.col.get(x) != null)
clone.col.add((DrivingAspectVo)this.col.get(x).clone());
else
clone.col.add(null);
}
return clone;
}
public boolean isValidated()
{
for(int x = 0; x < col.size(); x++)
if(!this.col.get(x).isValidated())
return false;
return true;
}
public String[] validate()
{
return validate(null);
}
public String[] validate(String[] existingErrors)
{
if(col.size() == 0)
return null;
java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>();
if(existingErrors != null)
{
for(int x = 0; x < existingErrors.length; x++)
{
listOfErrors.add(existingErrors[x]);
}
}
for(int x = 0; x < col.size(); x++)
{
String[] listOfOtherErrors = this.col.get(x).validate();
if(listOfOtherErrors != null)
{
for(int y = 0; y < listOfOtherErrors.length; y++)
{
listOfErrors.add(listOfOtherErrors[y]);
}
}
}
int errorCount = listOfErrors.size();
if(errorCount == 0)
return null;
String[] result = new String[errorCount];
for(int x = 0; x < errorCount; x++)
result[x] = (String)listOfErrors.get(x);
return result;
}
public DrivingAspectVoCollection sort()
{
return sort(SortOrder.ASCENDING);
}
public DrivingAspectVoCollection sort(boolean caseInsensitive)
{
return sort(SortOrder.ASCENDING, caseInsensitive);
}
public DrivingAspectVoCollection sort(SortOrder order)
{
return sort(new DrivingAspectVoComparator(order));
}
public DrivingAspectVoCollection sort(SortOrder order, boolean caseInsensitive)
{
return sort(new DrivingAspectVoComparator(order, caseInsensitive));
}
@SuppressWarnings("unchecked")
public DrivingAspectVoCollection sort(Comparator comparator)
{
Collections.sort(col, comparator);
return this;
}
public ims.therapies.workleisuredriving.vo.DrivingAspectRefVoCollection toRefVoCollection()
{
ims.therapies.workleisuredriving.vo.DrivingAspectRefVoCollection result = new ims.therapies.workleisuredriving.vo.DrivingAspectRefVoCollection();
for(int x = 0; x < this.col.size(); x++)
{
result.add(this.col.get(x));
}
return result;
}
public DrivingAspectVo[] toArray()
{
DrivingAspectVo[] arr = new DrivingAspectVo[col.size()];
col.toArray(arr);
return arr;
}
public Iterator<DrivingAspectVo> iterator()
{
return col.iterator();
}
@Override
protected ArrayList getTypedCollection()
{
return col;
}
private class DrivingAspectVoComparator implements Comparator
{
private int direction = 1;
private boolean caseInsensitive = true;
public DrivingAspectVoComparator()
{
this(SortOrder.ASCENDING);
}
public DrivingAspectVoComparator(SortOrder order)
{
if (order == SortOrder.DESCENDING)
{
direction = -1;
}
}
public DrivingAspectVoComparator(SortOrder order, boolean caseInsensitive)
{
if (order == SortOrder.DESCENDING)
{
direction = -1;
}
this.caseInsensitive = caseInsensitive;
}
public int compare(Object obj1, Object obj2)
{
DrivingAspectVo voObj1 = (DrivingAspectVo)obj1;
DrivingAspectVo voObj2 = (DrivingAspectVo)obj2;
return direction*(voObj1.compareTo(voObj2, this.caseInsensitive));
}
public boolean equals(Object obj)
{
return false;
}
}
public ims.therapies.vo.beans.DrivingAspectVoBean[] getBeanCollection()
{
return getBeanCollectionArray();
}
public ims.therapies.vo.beans.DrivingAspectVoBean[] getBeanCollectionArray()
{
ims.therapies.vo.beans.DrivingAspectVoBean[] result = new ims.therapies.vo.beans.DrivingAspectVoBean[col.size()];
for(int i = 0; i < col.size(); i++)
{
DrivingAspectVo vo = ((DrivingAspectVo)col.get(i));
result[i] = (ims.therapies.vo.beans.DrivingAspectVoBean)vo.getBean();
}
return result;
}
public static DrivingAspectVoCollection buildFromBeanCollection(java.util.Collection beans)
{
DrivingAspectVoCollection coll = new DrivingAspectVoCollection();
if(beans == null)
return coll;
java.util.Iterator iter = beans.iterator();
while (iter.hasNext())
{
coll.add(((ims.therapies.vo.beans.DrivingAspectVoBean)iter.next()).buildVo());
}
return coll;
}
public static DrivingAspectVoCollection buildFromBeanCollection(ims.therapies.vo.beans.DrivingAspectVoBean[] beans)
{
DrivingAspectVoCollection coll = new DrivingAspectVoCollection();
if(beans == null)
return coll;
for(int x = 0; x < beans.length; x++)
{
coll.add(beans[x].buildVo());
}
return coll;
}
}
| agpl-3.0 |
open-health-hub/openmaxims-linux | openmaxims_workspace/SpinalInjuries/src/ims/spinalinjuries/domain/impl/SharedNewConcernImpl.java | 4427 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Daniel Laffan using IMS Development Environment (version 1.22 build 50211.900)
// Copyright (C) 1995-2005 IMS MAXIMS plc. All rights reserved.
// 23/03/2005 - AU - Null pointer exception fixed
package ims.spinalinjuries.domain.impl;
import java.util.ArrayList;
import ims.admin.domain.HcpAdmin;
import ims.admin.domain.impl.HcpAdminImpl;
import ims.core.vo.CareContextShortVo;
import ims.core.vo.PatientCurrentConcernVo;
import ims.core.vo.domain.PatientCurrentConcernVoAssembler;
import ims.domain.exceptions.StaleObjectException;
import ims.domain.DomainFactory;
import ims.domain.exceptions.DomainRuntimeException;
import ims.domain.impl.DomainImpl;
import ims.generalmedical.vo.MedicalProbOnAdmisVoCollection;
import ims.generalmedical.vo.domain.MedicalProbOnAdmisVoAssembler;
import ims.spinalinjuries.domain.MedConcernOnAdmis;
import ims.core.clinical.domain.objects.PatientConcern;
import ims.core.clinical.vo.PatientConcernRefVo;
public class SharedNewConcernImpl extends DomainImpl implements ims.spinalinjuries.domain.SharedNewConcern, ims.domain.impl.Transactional
{
public ims.core.vo.PatientCurrentConcernVo saveConcern(ims.core.vo.PatientCurrentConcernVo concern, ims.core.vo.PatientShort patient) throws StaleObjectException
{
if(!concern.isValidated())
{
throw new DomainRuntimeException("PatientCurrentConcern Value Object Alert has not been validated");
}
DomainFactory factory = getDomainFactory();
PatientConcern doConcern = PatientCurrentConcernVoAssembler.extractPatientConcern(factory,concern);
factory.save(doConcern);
return PatientCurrentConcernVoAssembler.create(doConcern);
}
public ims.core.vo.HcpCollection listHcps(ims.core.vo.HcpFilter filter)
{
HcpAdmin impl = (HcpAdmin) getDomainImpl(HcpAdminImpl.class);
return impl.listHCPs(filter);
}
public MedicalProbOnAdmisVoCollection listProbsOnAdmission(CareContextShortVo voClinicalContactShort)
{
DomainFactory factory = getDomainFactory();
String hql = " from PatientProblem medicalProbOnAdmis ";
StringBuffer condStr = new StringBuffer();
String andStr = " ";
ArrayList markers = new ArrayList();
ArrayList values = new ArrayList();
if(voClinicalContactShort != null)
{
condStr.append(andStr + " medicalProbOnAdmis.careContext.id = :id_CareContext");
markers.add("id_CareContext");
values.add(voClinicalContactShort.getID_CareContext());
andStr = " and ";
}
if (andStr.equals(" and "))
hql += " where ";
hql += condStr.toString();
return MedicalProbOnAdmisVoAssembler.createMedicalProbOnAdmisVoCollectionFromPatientProblem(factory.find(hql, markers, values));
}
public PatientCurrentConcernVo getConcern(PatientConcernRefVo concernId) {
MedConcernOnAdmis impl = (MedConcernOnAdmis) getDomainImpl(MedConcernOnAdmisImpl.class);
return impl.getConcern(concernId);
}
}
| agpl-3.0 |
accesstest3/cfunambol | admin-suite/admin/src/com/funambol/admin/ui/SourceManagementPanel.java | 3447 | /*
* Funambol is a mobile platform developed by Funambol, Inc.
* Copyright (C) 2004 - 2007 Funambol, Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by
* the Free Software Foundation with the addition of the following permission
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
* WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
*
* You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
* 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by Funambol" logo. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by Funambol".
*/
package com.funambol.admin.ui;
import java.awt.Font;
import java.io.Serializable;
import javax.swing.JPanel;
import com.funambol.framework.engine.source.SyncSource;
import com.funambol.admin.AdminException;
/**
* Rapresents the base class for the SyncSources management panels
*
* @version $Id: SourceManagementPanel.java,v 1.5 2007-11-28 10:28:18 nichele Exp $
*/
public abstract class SourceManagementPanel
extends ManagementObjectPanel
implements Serializable {
// --------------------------------------------------------------- Constants
// These are the possible states of the SourceManagementPanel
public static final int STATE_INSERT = 0;
public static final int STATE_UPDATE = 1;
// -------------------------------------------------------------- Properties
/**
* Current state of the panel
*/
private int state = STATE_INSERT;
/**
* Sets property state
* @beaninfo
* description: current state of the SourceManagementPanel
* displayName: state
*/
public void setState(int state) {
this.state = state;
}
public int getState() {
return state;
}
// ------------------------------------------------------------ Constructors
/**
* Constructs a new SourceManagementPanel
*/
public SourceManagementPanel() {
super();
}
// ------------------------------------------------------- Protected Methods
public SyncSource getSyncSource() {
if (mo == null) {
return null;
}
return (SyncSource)mo.getObject();
}
}
| agpl-3.0 |
FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/ValueObjects/src/ims/core/vo/lookups/ProcedureEndoscopyTypeCollection.java | 5052 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.core.vo.lookups;
import ims.framework.cn.data.TreeModel;
import ims.framework.cn.data.TreeNode;
import ims.vo.LookupInstanceCollection;
import ims.vo.LookupInstVo;
public class ProcedureEndoscopyTypeCollection extends LookupInstanceCollection implements ims.vo.ImsCloneable, TreeModel
{
private static final long serialVersionUID = 1L;
public void add(ProcedureEndoscopyType value)
{
super.add(value);
}
public int indexOf(ProcedureEndoscopyType instance)
{
return super.indexOf(instance);
}
public boolean contains(ProcedureEndoscopyType instance)
{
return indexOf(instance) >= 0;
}
public ProcedureEndoscopyType get(int index)
{
return (ProcedureEndoscopyType)super.getIndex(index);
}
public void remove(ProcedureEndoscopyType instance)
{
if(instance != null)
{
int index = indexOf(instance);
if(index >= 0)
remove(index);
}
}
public Object clone()
{
ProcedureEndoscopyTypeCollection newCol = new ProcedureEndoscopyTypeCollection();
ProcedureEndoscopyType item;
for (int i = 0; i < super.size(); i++)
{
item = this.get(i);
newCol.add(new ProcedureEndoscopyType(item.getID(), item.getText(), item.isActive(), item.getParent(), item.getImage(), item.getColor(), item.getOrder()));
}
for (int i = 0; i < newCol.size(); i++)
{
item = newCol.get(i);
if (item.getParent() != null)
{
int parentIndex = this.indexOf(item.getParent());
if(parentIndex >= 0)
item.setParent(newCol.get(parentIndex));
else
item.setParent((ProcedureEndoscopyType)item.getParent().clone());
}
}
return newCol;
}
public ProcedureEndoscopyType getInstance(int instanceId)
{
return (ProcedureEndoscopyType)super.getInstanceById(instanceId);
}
public TreeNode[] getRootNodes()
{
LookupInstVo[] roots = super.getRoots();
TreeNode[] nodes = new TreeNode[roots.length];
System.arraycopy(roots, 0, nodes, 0, roots.length);
return nodes;
}
public ProcedureEndoscopyType[] toArray()
{
ProcedureEndoscopyType[] arr = new ProcedureEndoscopyType[this.size()];
super.toArray(arr);
return arr;
}
public static ProcedureEndoscopyTypeCollection buildFromBeanCollection(java.util.Collection beans)
{
ProcedureEndoscopyTypeCollection coll = new ProcedureEndoscopyTypeCollection();
if(beans == null)
return coll;
java.util.Iterator iter = beans.iterator();
while(iter.hasNext())
{
coll.add(ProcedureEndoscopyType.buildLookup((ims.vo.LookupInstanceBean)iter.next()));
}
return coll;
}
public static ProcedureEndoscopyTypeCollection buildFromBeanCollection(ims.vo.LookupInstanceBean[] beans)
{
ProcedureEndoscopyTypeCollection coll = new ProcedureEndoscopyTypeCollection();
if(beans == null)
return coll;
for(int x = 0; x < beans.length; x++)
{
coll.add(ProcedureEndoscopyType.buildLookup(beans[x]));
}
return coll;
}
}
| agpl-3.0 |
FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/Clinical/src/ims/clinical/domain/impl/PatientDiagnosisDialogImpl.java | 2300 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Calin Perebiceanu using IMS Development Environment (version 1.71 build 3642.24101)
// Copyright (C) 1995-2010 IMS MAXIMS. All rights reserved.
package ims.clinical.domain.impl;
import ims.clinical.domain.base.impl.BasePatientDiagnosisDialogImpl;
public class PatientDiagnosisDialogImpl extends BasePatientDiagnosisDialogImpl
{
private static final long serialVersionUID = 1L;
}
| agpl-3.0 |
FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/ValueObjects/src/ims/core/vo/domain/NeedsAssessmentComponentScoreVoAssembler.java | 19231 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
/*
* This code was generated
* Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved.
* IMS Development Environment (version 1.80 build 5589.25814)
* WARNING: DO NOT MODIFY the content of this file
* Generated on 12/10/2015, 13:24
*
*/
package ims.core.vo.domain;
import ims.vo.domain.DomainObjectMap;
import java.util.HashMap;
import org.hibernate.proxy.HibernateProxy;
/**
* @author Vasile Purdila
*/
public class NeedsAssessmentComponentScoreVoAssembler
{
/**
* Copy one ValueObject to another
* @param valueObjectDest to be updated
* @param valueObjectSrc to copy values from
*/
public static ims.core.vo.NeedsAssessmentComponentScoreVo copy(ims.core.vo.NeedsAssessmentComponentScoreVo valueObjectDest, ims.core.vo.NeedsAssessmentComponentScoreVo valueObjectSrc)
{
if (null == valueObjectSrc)
{
return valueObjectSrc;
}
valueObjectDest.setID_NeedsAssessmentComponentScore(valueObjectSrc.getID_NeedsAssessmentComponentScore());
valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE());
// Score
valueObjectDest.setScore(valueObjectSrc.getScore());
// ComponentType
valueObjectDest.setComponentType(valueObjectSrc.getComponentType());
return valueObjectDest;
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* This is a convenience method only.
* It is intended to be used when one called to an Assembler is made.
* If more than one call to an Assembler is made then #createNeedsAssessmentComponentScoreVoCollectionFromNeedsAssessmentComponentScore(DomainObjectMap, Set) should be used.
* @param domainObjectSet - Set of ims.clinical.domain.objects.NeedsAssessmentComponentScore objects.
*/
public static ims.core.vo.NeedsAssessmentComponentScoreVoCollection createNeedsAssessmentComponentScoreVoCollectionFromNeedsAssessmentComponentScore(java.util.Set domainObjectSet)
{
return createNeedsAssessmentComponentScoreVoCollectionFromNeedsAssessmentComponentScore(new DomainObjectMap(), domainObjectSet);
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectSet - Set of ims.clinical.domain.objects.NeedsAssessmentComponentScore objects.
*/
public static ims.core.vo.NeedsAssessmentComponentScoreVoCollection createNeedsAssessmentComponentScoreVoCollectionFromNeedsAssessmentComponentScore(DomainObjectMap map, java.util.Set domainObjectSet)
{
ims.core.vo.NeedsAssessmentComponentScoreVoCollection voList = new ims.core.vo.NeedsAssessmentComponentScoreVoCollection();
if ( null == domainObjectSet )
{
return voList;
}
int rieCount=0;
int activeCount=0;
java.util.Iterator iterator = domainObjectSet.iterator();
while( iterator.hasNext() )
{
ims.clinical.domain.objects.NeedsAssessmentComponentScore domainObject = (ims.clinical.domain.objects.NeedsAssessmentComponentScore) iterator.next();
ims.core.vo.NeedsAssessmentComponentScoreVo vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param domainObjectList - List of ims.clinical.domain.objects.NeedsAssessmentComponentScore objects.
*/
public static ims.core.vo.NeedsAssessmentComponentScoreVoCollection createNeedsAssessmentComponentScoreVoCollectionFromNeedsAssessmentComponentScore(java.util.List domainObjectList)
{
return createNeedsAssessmentComponentScoreVoCollectionFromNeedsAssessmentComponentScore(new DomainObjectMap(), domainObjectList);
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectList - List of ims.clinical.domain.objects.NeedsAssessmentComponentScore objects.
*/
public static ims.core.vo.NeedsAssessmentComponentScoreVoCollection createNeedsAssessmentComponentScoreVoCollectionFromNeedsAssessmentComponentScore(DomainObjectMap map, java.util.List domainObjectList)
{
ims.core.vo.NeedsAssessmentComponentScoreVoCollection voList = new ims.core.vo.NeedsAssessmentComponentScoreVoCollection();
if ( null == domainObjectList )
{
return voList;
}
int rieCount=0;
int activeCount=0;
for (int i = 0; i < domainObjectList.size(); i++)
{
ims.clinical.domain.objects.NeedsAssessmentComponentScore domainObject = (ims.clinical.domain.objects.NeedsAssessmentComponentScore) domainObjectList.get(i);
ims.core.vo.NeedsAssessmentComponentScoreVo vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ims.clinical.domain.objects.NeedsAssessmentComponentScore set from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.Set extractNeedsAssessmentComponentScoreSet(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.NeedsAssessmentComponentScoreVoCollection voCollection)
{
return extractNeedsAssessmentComponentScoreSet(domainFactory, voCollection, null, new HashMap());
}
public static java.util.Set extractNeedsAssessmentComponentScoreSet(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.NeedsAssessmentComponentScoreVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectSet == null)
{
domainObjectSet = new java.util.HashSet();
}
java.util.Set newSet = new java.util.HashSet();
for(int i=0; i<size; i++)
{
ims.core.vo.NeedsAssessmentComponentScoreVo vo = voCollection.get(i);
ims.clinical.domain.objects.NeedsAssessmentComponentScore domainObject = NeedsAssessmentComponentScoreVoAssembler.extractNeedsAssessmentComponentScore(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
//Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add)
if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject);
newSet.add(domainObject);
}
java.util.Set removedSet = new java.util.HashSet();
java.util.Iterator iter = domainObjectSet.iterator();
//Find out which objects need to be removed
while (iter.hasNext())
{
ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next();
if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o))
{
removedSet.add(o);
}
}
iter = removedSet.iterator();
//Remove the unwanted objects
while (iter.hasNext())
{
domainObjectSet.remove(iter.next());
}
return domainObjectSet;
}
/**
* Create the ims.clinical.domain.objects.NeedsAssessmentComponentScore list from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.List extractNeedsAssessmentComponentScoreList(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.NeedsAssessmentComponentScoreVoCollection voCollection)
{
return extractNeedsAssessmentComponentScoreList(domainFactory, voCollection, null, new HashMap());
}
public static java.util.List extractNeedsAssessmentComponentScoreList(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.NeedsAssessmentComponentScoreVoCollection voCollection, java.util.List domainObjectList, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectList == null)
{
domainObjectList = new java.util.ArrayList();
}
for(int i=0; i<size; i++)
{
ims.core.vo.NeedsAssessmentComponentScoreVo vo = voCollection.get(i);
ims.clinical.domain.objects.NeedsAssessmentComponentScore domainObject = NeedsAssessmentComponentScoreVoAssembler.extractNeedsAssessmentComponentScore(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
int domIdx = domainObjectList.indexOf(domainObject);
if (domIdx == -1)
{
domainObjectList.add(i, domainObject);
}
else if (i != domIdx && i < domainObjectList.size())
{
Object tmp = domainObjectList.get(i);
domainObjectList.set(i, domainObjectList.get(domIdx));
domainObjectList.set(domIdx, tmp);
}
}
//Remove all ones in domList where index > voCollection.size() as these should
//now represent the ones removed from the VO collection. No longer referenced.
int i1=domainObjectList.size();
while (i1 > size)
{
domainObjectList.remove(i1-1);
i1=domainObjectList.size();
}
return domainObjectList;
}
/**
* Create the ValueObject from the ims.clinical.domain.objects.NeedsAssessmentComponentScore object.
* @param domainObject ims.clinical.domain.objects.NeedsAssessmentComponentScore
*/
public static ims.core.vo.NeedsAssessmentComponentScoreVo create(ims.clinical.domain.objects.NeedsAssessmentComponentScore domainObject)
{
if (null == domainObject)
{
return null;
}
DomainObjectMap map = new DomainObjectMap();
return create(map, domainObject);
}
/**
* Create the ValueObject from the ims.clinical.domain.objects.NeedsAssessmentComponentScore object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param domainObject
*/
public static ims.core.vo.NeedsAssessmentComponentScoreVo create(DomainObjectMap map, ims.clinical.domain.objects.NeedsAssessmentComponentScore domainObject)
{
if (null == domainObject)
{
return null;
}
// check if the domainObject already has a valueObject created for it
ims.core.vo.NeedsAssessmentComponentScoreVo valueObject = (ims.core.vo.NeedsAssessmentComponentScoreVo) map.getValueObject(domainObject, ims.core.vo.NeedsAssessmentComponentScoreVo.class);
if ( null == valueObject )
{
valueObject = new ims.core.vo.NeedsAssessmentComponentScoreVo(domainObject.getId(), domainObject.getVersion());
map.addValueObject(domainObject, valueObject);
valueObject = insert(map, valueObject, domainObject);
}
return valueObject;
}
/**
* Update the ValueObject with the Domain Object.
* @param valueObject to be updated
* @param domainObject ims.clinical.domain.objects.NeedsAssessmentComponentScore
*/
public static ims.core.vo.NeedsAssessmentComponentScoreVo insert(ims.core.vo.NeedsAssessmentComponentScoreVo valueObject, ims.clinical.domain.objects.NeedsAssessmentComponentScore domainObject)
{
if (null == domainObject)
{
return valueObject;
}
DomainObjectMap map = new DomainObjectMap();
return insert(map, valueObject, domainObject);
}
/**
* Update the ValueObject with the Domain Object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param valueObject to be updated
* @param domainObject ims.clinical.domain.objects.NeedsAssessmentComponentScore
*/
public static ims.core.vo.NeedsAssessmentComponentScoreVo insert(DomainObjectMap map, ims.core.vo.NeedsAssessmentComponentScoreVo valueObject, ims.clinical.domain.objects.NeedsAssessmentComponentScore domainObject)
{
if (null == domainObject)
{
return valueObject;
}
if (null == map)
{
map = new DomainObjectMap();
}
valueObject.setID_NeedsAssessmentComponentScore(domainObject.getId());
valueObject.setIsRIE(domainObject.getIsRIE());
// If this is a recordedInError record, and the domainObject
// value isIncludeRecord has not been set, then we return null and
// not the value object
if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord())
return null;
// If this is not a recordedInError record, and the domainObject
// value isIncludeRecord has been set, then we return null and
// not the value object
if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord())
return null;
// Score
valueObject.setScore(domainObject.getScore());
// ComponentType
ims.domain.lookups.LookupInstance instance2 = domainObject.getComponentType();
if ( null != instance2 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance2.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance2.getImage().getImageId(), instance2.getImage().getImagePath());
}
color = instance2.getColor();
if (color != null)
color.getValue();
ims.core.vo.lookups.UserDefinedAssessmentType voLookup2 = new ims.core.vo.lookups.UserDefinedAssessmentType(instance2.getId(),instance2.getText(), instance2.isActive(), null, img, color);
ims.core.vo.lookups.UserDefinedAssessmentType parentVoLookup2 = voLookup2;
ims.domain.lookups.LookupInstance parent2 = instance2.getParent();
while (parent2 != null)
{
if (parent2.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent2.getImage().getImageId(), parent2.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent2.getColor();
if (color != null)
color.getValue();
parentVoLookup2.setParent(new ims.core.vo.lookups.UserDefinedAssessmentType(parent2.getId(),parent2.getText(), parent2.isActive(), null, img, color));
parentVoLookup2 = parentVoLookup2.getParent();
parent2 = parent2.getParent();
}
valueObject.setComponentType(voLookup2);
}
return valueObject;
}
/**
* Create the domain object from the value object.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param valueObject - extract the domain object fields from this.
*/
public static ims.clinical.domain.objects.NeedsAssessmentComponentScore extractNeedsAssessmentComponentScore(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.NeedsAssessmentComponentScoreVo valueObject)
{
return extractNeedsAssessmentComponentScore(domainFactory, valueObject, new HashMap());
}
public static ims.clinical.domain.objects.NeedsAssessmentComponentScore extractNeedsAssessmentComponentScore(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.NeedsAssessmentComponentScoreVo valueObject, HashMap domMap)
{
if (null == valueObject)
{
return null;
}
Integer id = valueObject.getID_NeedsAssessmentComponentScore();
ims.clinical.domain.objects.NeedsAssessmentComponentScore domainObject = null;
if ( null == id)
{
if (domMap.get(valueObject) != null)
{
return (ims.clinical.domain.objects.NeedsAssessmentComponentScore)domMap.get(valueObject);
}
// ims.core.vo.NeedsAssessmentComponentScoreVo ID_NeedsAssessmentComponentScore field is unknown
domainObject = new ims.clinical.domain.objects.NeedsAssessmentComponentScore();
domMap.put(valueObject, domainObject);
}
else
{
String key = (valueObject.getClass().getName() + "__" + valueObject.getID_NeedsAssessmentComponentScore());
if (domMap.get(key) != null)
{
return (ims.clinical.domain.objects.NeedsAssessmentComponentScore)domMap.get(key);
}
domainObject = (ims.clinical.domain.objects.NeedsAssessmentComponentScore) domainFactory.getDomainObject(ims.clinical.domain.objects.NeedsAssessmentComponentScore.class, id );
//TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up.
if (domainObject == null)
return null;
domMap.put(key, domainObject);
}
domainObject.setVersion(valueObject.getVersion_NeedsAssessmentComponentScore());
domainObject.setScore(valueObject.getScore());
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value2 = null;
if ( null != valueObject.getComponentType() )
{
value2 =
domainFactory.getLookupInstance(valueObject.getComponentType().getID());
}
domainObject.setComponentType(value2);
return domainObject;
}
}
| agpl-3.0 |
rapidminer/rapidminer-5 | src/com/rapidminer/example/table/FloatSparseArrayDataRow.java | 2881 | /*
* RapidMiner
*
* Copyright (C) 2001-2014 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.example.table;
/**
* Implementation of DataRow that is backed by primitive arrays. Should always
* be used if more than 50% of the data is sparse. As fast (or even faster than
* map implementation) but needs considerably less memory. This implementation uses
* float arrays instead of double arrays which might reduce the used memory even more.
*
* @author Ingo Mierswa, Shevek
*/
public class FloatSparseArrayDataRow extends AbstractSparseArrayDataRow {
private static final long serialVersionUID = -2445500346242180129L;
/** Stores the used attribute values. */
private float[] values;
/** Creates an empty sparse array data row with size 0. */
public FloatSparseArrayDataRow() {
this(0);
}
/** Creates a sparse array data row of the given size. */
public FloatSparseArrayDataRow(int size) {
super(size);
values = new float[size];
}
@Override
protected void swapValues(int a, int b) {
float tt = values[a];
values[a] = values[b];
values[b] = tt;
}
@Override
public void resizeValues(int length) {
float[] d = new float[length];
System.arraycopy(values, 0, d, 0, Math.min(values.length, length));
values = d;
}
@Override
public void removeValue(int index) {
System.arraycopy(values, index + 1, values, index, (values.length - (index + 1)));
}
/** Returns the desired data for the given attribute. */
@Override
public double getValue(int index) {
return values[index];
}
/** Sets the given data for the given attribute. */
@Override
public void setValue(int index, double v) {
values[index] = (float)v;
}
@Override
protected double[] getAllValues() {
double[] result = new double[this.values.length];
for (int i = 0; i < result.length; i++)
result[i] = this.values[i];
return result;
}
@Override
public int getType() {
return DataRowFactory.TYPE_FLOAT_SPARSE_ARRAY;
}
}
| agpl-3.0 |
open-health-hub/openmaxims-linux | openmaxims_workspace/ValueObjects/src/ims/core/vo/domain/InpatientEpisodeForPendingDischargesVoAssembler.java | 18041 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
/*
* This code was generated
* Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved.
* IMS Development Environment (version 1.80 build 5007.25751)
* WARNING: DO NOT MODIFY the content of this file
* Generated on 16/04/2014, 12:32
*
*/
package ims.core.vo.domain;
import ims.vo.domain.DomainObjectMap;
import java.util.HashMap;
import org.hibernate.proxy.HibernateProxy;
/**
* @author Ander Telleria
*/
public class InpatientEpisodeForPendingDischargesVoAssembler
{
/**
* Copy one ValueObject to another
* @param valueObjectDest to be updated
* @param valueObjectSrc to copy values from
*/
public static ims.core.vo.InpatientEpisodeForPendingDischargesVo copy(ims.core.vo.InpatientEpisodeForPendingDischargesVo valueObjectDest, ims.core.vo.InpatientEpisodeForPendingDischargesVo valueObjectSrc)
{
if (null == valueObjectSrc)
{
return valueObjectSrc;
}
valueObjectDest.setID_InpatientEpisode(valueObjectSrc.getID_InpatientEpisode());
valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE());
// pasEvent
valueObjectDest.setPasEvent(valueObjectSrc.getPasEvent());
// Bed
valueObjectDest.setBed(valueObjectSrc.getBed());
// EstDischargeDate
valueObjectDest.setEstDischargeDate(valueObjectSrc.getEstDischargeDate());
// isConfirmedDischarge
valueObjectDest.setIsConfirmedDischarge(valueObjectSrc.getIsConfirmedDischarge());
return valueObjectDest;
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* This is a convenience method only.
* It is intended to be used when one called to an Assembler is made.
* If more than one call to an Assembler is made then #createInpatientEpisodeForPendingDischargesVoCollectionFromInpatientEpisode(DomainObjectMap, Set) should be used.
* @param domainObjectSet - Set of ims.core.admin.pas.domain.objects.InpatientEpisode objects.
*/
public static ims.core.vo.InpatientEpisodeForPendingDischargesVoCollection createInpatientEpisodeForPendingDischargesVoCollectionFromInpatientEpisode(java.util.Set domainObjectSet)
{
return createInpatientEpisodeForPendingDischargesVoCollectionFromInpatientEpisode(new DomainObjectMap(), domainObjectSet);
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectSet - Set of ims.core.admin.pas.domain.objects.InpatientEpisode objects.
*/
public static ims.core.vo.InpatientEpisodeForPendingDischargesVoCollection createInpatientEpisodeForPendingDischargesVoCollectionFromInpatientEpisode(DomainObjectMap map, java.util.Set domainObjectSet)
{
ims.core.vo.InpatientEpisodeForPendingDischargesVoCollection voList = new ims.core.vo.InpatientEpisodeForPendingDischargesVoCollection();
if ( null == domainObjectSet )
{
return voList;
}
int rieCount=0;
int activeCount=0;
java.util.Iterator iterator = domainObjectSet.iterator();
while( iterator.hasNext() )
{
ims.core.admin.pas.domain.objects.InpatientEpisode domainObject = (ims.core.admin.pas.domain.objects.InpatientEpisode) iterator.next();
ims.core.vo.InpatientEpisodeForPendingDischargesVo vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param domainObjectList - List of ims.core.admin.pas.domain.objects.InpatientEpisode objects.
*/
public static ims.core.vo.InpatientEpisodeForPendingDischargesVoCollection createInpatientEpisodeForPendingDischargesVoCollectionFromInpatientEpisode(java.util.List domainObjectList)
{
return createInpatientEpisodeForPendingDischargesVoCollectionFromInpatientEpisode(new DomainObjectMap(), domainObjectList);
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectList - List of ims.core.admin.pas.domain.objects.InpatientEpisode objects.
*/
public static ims.core.vo.InpatientEpisodeForPendingDischargesVoCollection createInpatientEpisodeForPendingDischargesVoCollectionFromInpatientEpisode(DomainObjectMap map, java.util.List domainObjectList)
{
ims.core.vo.InpatientEpisodeForPendingDischargesVoCollection voList = new ims.core.vo.InpatientEpisodeForPendingDischargesVoCollection();
if ( null == domainObjectList )
{
return voList;
}
int rieCount=0;
int activeCount=0;
for (int i = 0; i < domainObjectList.size(); i++)
{
ims.core.admin.pas.domain.objects.InpatientEpisode domainObject = (ims.core.admin.pas.domain.objects.InpatientEpisode) domainObjectList.get(i);
ims.core.vo.InpatientEpisodeForPendingDischargesVo vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ims.core.admin.pas.domain.objects.InpatientEpisode set from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.Set extractInpatientEpisodeSet(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.InpatientEpisodeForPendingDischargesVoCollection voCollection)
{
return extractInpatientEpisodeSet(domainFactory, voCollection, null, new HashMap());
}
public static java.util.Set extractInpatientEpisodeSet(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.InpatientEpisodeForPendingDischargesVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectSet == null)
{
domainObjectSet = new java.util.HashSet();
}
java.util.Set newSet = new java.util.HashSet();
for(int i=0; i<size; i++)
{
ims.core.vo.InpatientEpisodeForPendingDischargesVo vo = voCollection.get(i);
ims.core.admin.pas.domain.objects.InpatientEpisode domainObject = InpatientEpisodeForPendingDischargesVoAssembler.extractInpatientEpisode(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
//Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add)
if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject);
newSet.add(domainObject);
}
java.util.Set removedSet = new java.util.HashSet();
java.util.Iterator iter = domainObjectSet.iterator();
//Find out which objects need to be removed
while (iter.hasNext())
{
ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next();
if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o))
{
removedSet.add(o);
}
}
iter = removedSet.iterator();
//Remove the unwanted objects
while (iter.hasNext())
{
domainObjectSet.remove(iter.next());
}
return domainObjectSet;
}
/**
* Create the ims.core.admin.pas.domain.objects.InpatientEpisode list from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.List extractInpatientEpisodeList(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.InpatientEpisodeForPendingDischargesVoCollection voCollection)
{
return extractInpatientEpisodeList(domainFactory, voCollection, null, new HashMap());
}
public static java.util.List extractInpatientEpisodeList(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.InpatientEpisodeForPendingDischargesVoCollection voCollection, java.util.List domainObjectList, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectList == null)
{
domainObjectList = new java.util.ArrayList();
}
for(int i=0; i<size; i++)
{
ims.core.vo.InpatientEpisodeForPendingDischargesVo vo = voCollection.get(i);
ims.core.admin.pas.domain.objects.InpatientEpisode domainObject = InpatientEpisodeForPendingDischargesVoAssembler.extractInpatientEpisode(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
int domIdx = domainObjectList.indexOf(domainObject);
if (domIdx == -1)
{
domainObjectList.add(i, domainObject);
}
else if (i != domIdx && i < domainObjectList.size())
{
Object tmp = domainObjectList.get(i);
domainObjectList.set(i, domainObjectList.get(domIdx));
domainObjectList.set(domIdx, tmp);
}
}
//Remove all ones in domList where index > voCollection.size() as these should
//now represent the ones removed from the VO collection. No longer referenced.
int i1=domainObjectList.size();
while (i1 > size)
{
domainObjectList.remove(i1-1);
i1=domainObjectList.size();
}
return domainObjectList;
}
/**
* Create the ValueObject from the ims.core.admin.pas.domain.objects.InpatientEpisode object.
* @param domainObject ims.core.admin.pas.domain.objects.InpatientEpisode
*/
public static ims.core.vo.InpatientEpisodeForPendingDischargesVo create(ims.core.admin.pas.domain.objects.InpatientEpisode domainObject)
{
if (null == domainObject)
{
return null;
}
DomainObjectMap map = new DomainObjectMap();
return create(map, domainObject);
}
/**
* Create the ValueObject from the ims.core.admin.pas.domain.objects.InpatientEpisode object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param domainObject
*/
public static ims.core.vo.InpatientEpisodeForPendingDischargesVo create(DomainObjectMap map, ims.core.admin.pas.domain.objects.InpatientEpisode domainObject)
{
if (null == domainObject)
{
return null;
}
// check if the domainObject already has a valueObject created for it
ims.core.vo.InpatientEpisodeForPendingDischargesVo valueObject = (ims.core.vo.InpatientEpisodeForPendingDischargesVo) map.getValueObject(domainObject, ims.core.vo.InpatientEpisodeForPendingDischargesVo.class);
if ( null == valueObject )
{
valueObject = new ims.core.vo.InpatientEpisodeForPendingDischargesVo(domainObject.getId(), domainObject.getVersion());
map.addValueObject(domainObject, valueObject);
valueObject = insert(map, valueObject, domainObject);
}
return valueObject;
}
/**
* Update the ValueObject with the Domain Object.
* @param valueObject to be updated
* @param domainObject ims.core.admin.pas.domain.objects.InpatientEpisode
*/
public static ims.core.vo.InpatientEpisodeForPendingDischargesVo insert(ims.core.vo.InpatientEpisodeForPendingDischargesVo valueObject, ims.core.admin.pas.domain.objects.InpatientEpisode domainObject)
{
if (null == domainObject)
{
return valueObject;
}
DomainObjectMap map = new DomainObjectMap();
return insert(map, valueObject, domainObject);
}
/**
* Update the ValueObject with the Domain Object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param valueObject to be updated
* @param domainObject ims.core.admin.pas.domain.objects.InpatientEpisode
*/
public static ims.core.vo.InpatientEpisodeForPendingDischargesVo insert(DomainObjectMap map, ims.core.vo.InpatientEpisodeForPendingDischargesVo valueObject, ims.core.admin.pas.domain.objects.InpatientEpisode domainObject)
{
if (null == domainObject)
{
return valueObject;
}
if (null == map)
{
map = new DomainObjectMap();
}
valueObject.setID_InpatientEpisode(domainObject.getId());
valueObject.setIsRIE(domainObject.getIsRIE());
// If this is a recordedInError record, and the domainObject
// value isIncludeRecord has not been set, then we return null and
// not the value object
if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord())
return null;
// If this is not a recordedInError record, and the domainObject
// value isIncludeRecord has been set, then we return null and
// not the value object
if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord())
return null;
// pasEvent
valueObject.setPasEvent(ims.core.vo.domain.PasEventVoAssembler.create(map, domainObject.getPasEvent()) );
// Bed
valueObject.setBed(ims.core.vo.domain.BedSpaceStateVoAssembler.create(map, domainObject.getBed()) );
// EstDischargeDate
java.util.Date EstDischargeDate = domainObject.getEstDischargeDate();
if ( null != EstDischargeDate )
{
valueObject.setEstDischargeDate(new ims.framework.utils.Date(EstDischargeDate) );
}
// isConfirmedDischarge
valueObject.setIsConfirmedDischarge( domainObject.isIsConfirmedDischarge() );
return valueObject;
}
/**
* Create the domain object from the value object.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param valueObject - extract the domain object fields from this.
*/
public static ims.core.admin.pas.domain.objects.InpatientEpisode extractInpatientEpisode(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.InpatientEpisodeForPendingDischargesVo valueObject)
{
return extractInpatientEpisode(domainFactory, valueObject, new HashMap());
}
public static ims.core.admin.pas.domain.objects.InpatientEpisode extractInpatientEpisode(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.InpatientEpisodeForPendingDischargesVo valueObject, HashMap domMap)
{
if (null == valueObject)
{
return null;
}
Integer id = valueObject.getID_InpatientEpisode();
ims.core.admin.pas.domain.objects.InpatientEpisode domainObject = null;
if ( null == id)
{
if (domMap.get(valueObject) != null)
{
return (ims.core.admin.pas.domain.objects.InpatientEpisode)domMap.get(valueObject);
}
// ims.core.vo.InpatientEpisodeForPendingDischargesVo ID_InpatientEpisode field is unknown
domainObject = new ims.core.admin.pas.domain.objects.InpatientEpisode();
domMap.put(valueObject, domainObject);
}
else
{
String key = (valueObject.getClass().getName() + "__" + valueObject.getID_InpatientEpisode());
if (domMap.get(key) != null)
{
return (ims.core.admin.pas.domain.objects.InpatientEpisode)domMap.get(key);
}
domainObject = (ims.core.admin.pas.domain.objects.InpatientEpisode) domainFactory.getDomainObject(ims.core.admin.pas.domain.objects.InpatientEpisode.class, id );
//TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up.
if (domainObject == null)
return null;
domMap.put(key, domainObject);
}
domainObject.setVersion(valueObject.getVersion_InpatientEpisode());
domainObject.setPasEvent(ims.core.vo.domain.PasEventVoAssembler.extractPASEvent(domainFactory, valueObject.getPasEvent(), domMap));
domainObject.setBed(ims.core.vo.domain.BedSpaceStateVoAssembler.extractBedSpaceState(domainFactory, valueObject.getBed(), domMap));
java.util.Date value3 = null;
ims.framework.utils.Date date3 = valueObject.getEstDischargeDate();
if ( date3 != null )
{
value3 = date3.getDate();
}
domainObject.setEstDischargeDate(value3);
domainObject.setIsConfirmedDischarge(valueObject.getIsConfirmedDischarge());
return domainObject;
}
}
| agpl-3.0 |
open-health-hub/openmaxims-linux | openmaxims_workspace/OCRR/src/ims/ocrr/domain/base/impl/BaseOrderPriorityDialogImpl.java | 1978 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.ocrr.domain.base.impl;
import ims.domain.impl.DomainImpl;
public abstract class BaseOrderPriorityDialogImpl extends DomainImpl implements ims.ocrr.domain.OrderPriorityDialog, ims.domain.impl.Transactional
{
private static final long serialVersionUID = 1L;
}
| agpl-3.0 |
zhangdakun/funasyn | externals/java-sdk/pim/src/main/java-se/com/funambol/common/pim/model/contact/PersonalDetail.java | 9634 | /*
* Funambol is a mobile platform developed by Funambol, Inc.
* Copyright (C) 2003 - 2007 Funambol, Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by
* the Free Software Foundation with the addition of the following permission
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
* WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
*
* You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
* 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by Funambol" logo. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by Funambol".
*/
package com.funambol.common.pim.model.contact;
import com.funambol.common.pim.model.common.Property;
import com.funambol.common.pim.model.common.TypifiedPluralProperty;
import com.funambol.util.Base64;
import java.util.ArrayList;
import java.util.List;
/**
* An object containing the personal details of a contact
*/
public class PersonalDetail extends ContactDetail {
private List<TypifiedPluralProperty> photos;
private Property geo;
private String spouse;
private String children;
private String anniversary;
private String birthday;
private String gender;
private String hobbies;
/**
* Creates an empty list of personal details
*/
public PersonalDetail() {
super();
photos = new ArrayList<TypifiedPluralProperty>();
geo = new Property();
spouse = null;
children = null;
anniversary = null;
birthday = null;
gender = null;
hobbies = null;
}
/**
* Returns the geo for this Personal Detail
*
* @return the geo for this Personal Detail
*/
public Property getGeo() {
return geo;
}
/**
* Returns the spouse for this Personal Detail
*
* @return the spouse for this Personal Detail
*/
public String getSpouse() {
return spouse;
}
/**
* Returns the children for this Personal Detail
*
* @return the children for this Personal Detail
*/
public String getChildren() {
return children;
}
/**
* Returns the anniversary for this Personal Detail
*
* @return the anniversary for this Personal Detail
*/
public String getAnniversary() {
return anniversary;
}
/**
* Returns the birthday for this Personal Detail
*
* @return the birthday for this Personal Detail
*/
public String getBirthday() {
return birthday;
}
/**
* Returns the gender for this Personal Detail
*
* @return the gender for this Personal Detail
*/
public String getGender() {
return gender;
}
/**
* Returns the photos for this Personal Detail
*
* @return the photos for this Personal Detail
* @deprecated Since v65, use getPhotoObjects and setPhotoObjects
*/
public List<TypifiedPluralProperty> getPhotos() {
return photos;
}
/**
* Returns the photos as <code>Photo</code> and not just as Property
* @return the photo for this Personal Detail
*/
public List<Photo> getPhotoObjects() {
if (photos == null || photos.isEmpty()) {
return null;
}
List<Photo> photoObjects = new ArrayList<Photo>();
for(TypifiedPluralProperty photo : photos) {
if(photo != null) {
Photo photoObject = new Photo();
photoObject.setPreferred(photo.isPreferred());
String type = photo.getPropertyType();
String value = photo.getPropertyValueAsString();
if (value == null || value.length() == 0) {
photoObjects.add(photoObject);
continue;
}
photoObject.setType(type);
String encoding = photo.getEncoding();
String valueType = photo.getValue();
Object oValue = null;
if ("B".equalsIgnoreCase(encoding) ||
"BASE64".equalsIgnoreCase(encoding)) {
if (value != null && value.length() > 0) {
oValue = Base64.decode(value);
} else {
oValue = new byte[0];
}
} else {
oValue = value;
}
if ("URL".equalsIgnoreCase(valueType)) {
if (oValue instanceof byte[]) {
//
// really strange....an url sent in base 64
//
photoObject.setUrl(new String((byte[])oValue));
} else {
photoObject.setUrl((String)oValue);
}
} else {
photoObject.setImage((byte[])oValue);
}
photoObjects.add(photoObject);
}
}
return photoObjects;
}
/**
* Sets the geo for this Personal Detail
*
* @param geo the geo to set
*/
public void setGeo(Property geo) {
this.geo = geo;
}
/**
* Sets the spouse for this Personal Detail
*
* @param spouse the spouse to set
*/
public void setSpouse (String spouse) {
this.spouse = spouse;
}
/**
* Sets the children for this Personal Detail
*
* @param children the children to set
*/
public void setChildren (String children) {
this.children = children;
}
/**
* Sets the anniversary for this Personal Detail
*
* @param anniversary the anniversary to set
*/
public void setAnniversary (String anniversary) {
this.anniversary = anniversary;
}
/**
* Sets the birthday for this Personal Detail
*
* @param birthday the spouse to set
*/
public void setBirthday (String birthday) {
this.birthday = birthday;
}
/**
* Sets the gender for this Personal Detail
*
* @param gender the gender to set
*/
public void setGender (String gender) {
this.gender = gender;
}
/**
* Getter for property hobbies.
* @return Value of property hobbies.
*/
public java.lang.String getHobbies() {
return hobbies;
}
/**
* Setter for property hobbies.
* @param hobbies New value of property hobbies.
*/
public void setHobbies(java.lang.String hobbies) {
this.hobbies = hobbies;
}
/**
* Sets the photos
* @param photo New value of property photo.
*/
public void setPhotos(List<TypifiedPluralProperty> photos) {
this.photos = photos;
}
/**
* Add a new photo
* @param photo New value of property photo.
*/
public void addPhoto(TypifiedPluralProperty photo) {
if (photo == null) {
return;
}
photos.add(photo);
}
/**
* Add a new Photo object
* @param photo New value of property photo.
*/
public void addPhotoObject(Photo photoObject) {
if (photoObject == null) {
return;
}
TypifiedPluralProperty photo = new TypifiedPluralProperty();
photo.setType(photoObject.getType());
photo.setPreferred(photoObject.isPreferred());
if (photoObject.getUrl() != null && photoObject.getUrl().length() > 0) {
photo.setValue("URL");
photo.setPropertyValue(photoObject.getUrl());
} else {
if (photoObject.getImage() != null && photoObject.getImage().length > 0) {
String b64 = new String(Base64.encode(photoObject.getImage()));
photo.setPropertyValue(b64);
photo.setEncoding("BASE64");
//
// The charset must be null since:
// 1. it is useless since the content is in base64
// 2. on some Nokia phone it doesn't work since for some reason the phone
// adds a new photo and the result is that a contact has two photos
// Examples of wrong phones: Nokia N91, 7610, 6630
//
photo.setCharset(null);
} else {
photo.setPropertyValue("");
}
}
addPhoto(photo);
}
}
| agpl-3.0 |
kerr-huang/openss7 | src/java/javax/sip/header/TimeStampHeader.java | 6210 | /*
@(#) src/java/javax/sip/header/TimeStampHeader.java <p>
Copyright © 2008-2015 Monavacon Limited <a href="http://www.monavacon.com/"><http://www.monavacon.com/></a>. <br>
Copyright © 2001-2008 OpenSS7 Corporation <a href="http://www.openss7.com/"><http://www.openss7.com/></a>. <br>
Copyright © 1997-2001 Brian F. G. Bidulock <a href="mailto:bidulock@openss7.org"><bidulock@openss7.org></a>. <p>
All Rights Reserved. <p>
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, version 3 of the license. <p>
This program is distributed in the hope that it will be useful, but <b>WITHOUT
ANY WARRANTY</b>; without even the implied warranty of <b>MERCHANTABILITY</b>
or <b>FITNESS FOR A PARTICULAR PURPOSE</b>. See the GNU Affero General Public
License for more details. <p>
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see
<a href="http://www.gnu.org/licenses/"><http://www.gnu.org/licenses/></a>,
or write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA
02139, USA. <p>
<em>U.S. GOVERNMENT RESTRICTED RIGHTS</em>. If you are licensing this
Software on behalf of the U.S. Government ("Government"), the following
provisions apply to you. If the Software is supplied by the Department of
Defense ("DoD"), it is classified as "Commercial Computer Software" under
paragraph 252.227-7014 of the DoD Supplement to the Federal Acquisition
Regulations ("DFARS") (or any successor regulations) and the Government is
acquiring only the license rights granted herein (the license rights
customarily provided to non-Government users). If the Software is supplied to
any unit or agency of the Government other than DoD, it is classified as
"Restricted Computer Software" and the Government's rights in the Software are
defined in paragraph 52.227-19 of the Federal Acquisition Regulations ("FAR")
(or any successor regulations) or, in the cases of NASA, in paragraph
18.52.227-86 of the NASA Supplement to the FAR (or any successor regulations). <p>
Commercial licensing and support of this software is available from OpenSS7
Corporation at a fee. See
<a href="http://www.openss7.com/">http://www.openss7.com/</a>
*/
package javax.sip.header;
import javax.sip.*;
/**
The Timestamp header field describes when the UAC sent the request to the UAS. When a 100
(Trying) response is generated, any Timestamp header field present in the request MUST be copied
into this 100 (Trying) response. If there is a delay in generating the response, the UAS SHOULD
add a delay value into the Timestamp value in the response. This value MUST contain the
difference between the time of sending of the response and receipt of the request, measured in
seconds. Although there is no normative behavior defined here that makes use of the header, it
allows for extensions or SIP applications to obtain RTT estimates, that may be used to adjust
the timeout value for retransmissions. <p> For Example: <br> <code> Timestamp: 54 </code>
@version 1.2.2
@author Monavacon Limited
*/
public interface TimeStampHeader extends Header {
/**
Name of TimeStampHeader.
*/
static final java.lang.String NAME = "Timestamp";
/**
@deprecated This method is replaced with setTimeStamp(float). Sets the timestamp value of
this TimeStampHeader to the new timestamp value passed to this method.
@param timeStamp The new float timestamp value.
@exception InvalidArgumentException Thrown when the timestamp value argument is a negative
value.
*/
void setTimeStamp(float timeStamp) throws InvalidArgumentException;
/**
@deprecated This method is replaced with getTime(). Gets the timestamp value of this
TimeStampHeader.
@return The timestamp value of this TimeStampHeader.
*/
float getTimeStamp();
/**
Gets the timestamp value of this TimeStampHeader.
@return The timestamp value of this TimeStampHeader.
@since v1.2
*/
long getTime();
/**
Sets the timestamp value of this TimeStampHeader to the new timestamp value passed to this
method. This method allows applications to conveniantly use System.currentTimeMillis to set
the timeStamp value.
@param timeStamp The new long timestamp value.
@exception InvalidArgumentException Thrown when the timestamp value argument is a negative
value.
@since v1.2
*/
void setTime(long timeStamp) throws InvalidArgumentException;
/**
@deprecated This method is replaced with getTimeDelay(). Gets delay of TimeStampHeader.
This method returns -1 if the delay parameter is not set.
@return The delay value of this TimeStampHeader
*/
float getDelay();
/**
@deprecated This method is replaced with setTimeDelay(int). Sets the new delay value of the
TimestampHeader to the delay parameter passed to this method
@param delay The new float delay value.
@exception InvalidArgumentException Thrown when the delay value argumenmt is a negative
value other than the default value -1.
*/
void setDelay(float delay) throws InvalidArgumentException;
/**
Gets delay of TimeStampHeader. This method returns -1 if the delay parameter is not set.
@return The delay value of this TimeStampHeader as an integer.
@since v1.2
*/
int getTimeDelay();
/**
Sets the new delay value of the TimestampHeader to the delay parameter passed to this method
@param delay The new int delay value.
@exception InvalidArgumentException Thrown when the delay value argumenmt is a negative
value other than the default value -1.
@since v1.2
*/
void setTimeDelay(int delay) throws InvalidArgumentException;
}
// vim: sw=4 et tw=72 com=srO\:/**,mb\:*,ex\:*/,srO\:/*,mb\:*,ex\:*/,b\:TRANS,\://,b\:#,\:%,\:XCOMM,n\:>,fb\:-
| agpl-3.0 |
IMS-MAXIMS/openMAXIMS | Source Library/openmaxims_workspace/Core/src/ims/core/domain/impl/SelectFormImpl.java | 3248 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Ander Telleria using IMS Development Environment (version 1.70 build 3425.24971)
// Copyright (C) 1995-2009 IMS MAXIMS plc. All rights reserved.
package ims.core.domain.impl;
import java.util.List;
import ims.admin.vo.AppFormVoCollection;
import ims.admin.vo.domain.AppFormVoAssembler;
import ims.core.configuration.domain.objects.AppForm;
import ims.core.domain.base.impl.BaseSelectFormImpl;
import ims.domain.DomainFactory;
import ims.domain.hibernate3.IMSCriteria;
public class SelectFormImpl extends BaseSelectFormImpl
{
private static final long serialVersionUID = 1L;
public ims.admin.vo.AppFormVoCollection listForms(String form, Boolean includeAliases, Boolean includeDialogs)
{
DomainFactory factory = getDomainFactory();
IMSCriteria imsc = new IMSCriteria(AppForm.class,factory);
imsc.like(AppForm.FieldNames.Name, "%" + form + "%");
// Include aliases
if (!Boolean.TRUE.equals(includeAliases))
{
imsc.equal(AppForm.FieldNames.IsAlias, false);
}
// Include dialogs
if (!Boolean.TRUE.equals(includeDialogs))
{
imsc.equal(AppForm.FieldNames.IsDialog, false);
}
List<AppForm> forms = imsc.find();
if (forms != null && forms.size() > 0)
return AppFormVoAssembler.createAppFormVoCollectionFromAppForm(forms);
return null;
}
}
| agpl-3.0 |
open-health-hub/openmaxims-linux | openmaxims_workspace/Nursing/src/ims/nursing/domain/CarePlanReviewDialog.java | 2281 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.nursing.domain;
// Generated from form domain impl
public interface CarePlanReviewDialog extends ims.domain.DomainInterface
{
// Generated from form domain interface definition
/**
* Get a care plan
*/
public ims.nursing.vo.CarePlan getCarePlan(ims.nursing.vo.CarePlan voCarePlan) throws ims.domain.exceptions.DomainInterfaceException;
// Generated from form domain interface definition
/**
* Saves a care plan
*/
public ims.nursing.vo.CarePlan saveCarePlan(ims.nursing.vo.CarePlan carePlan) throws ims.domain.exceptions.StaleObjectException;
}
| agpl-3.0 |
youribonnaffe/scheduling | scheduler/scheduler-server/src/test/java/functionaltests/service/SchedulingServiceTest8.java | 3462 | package functionaltests.service;
import java.util.Map;
import org.ow2.proactive.scheduler.common.SchedulerEvent;
import org.ow2.proactive.scheduler.common.exception.UnknownJobException;
import org.ow2.proactive.scheduler.common.exception.UnknownTaskException;
import org.ow2.proactive.scheduler.common.job.JobId;
import org.ow2.proactive.scheduler.common.job.TaskFlowJob;
import org.ow2.proactive.scheduler.common.task.JavaTask;
import org.ow2.proactive.scheduler.common.task.TaskId;
import org.ow2.proactive.scheduler.descriptor.EligibleTaskDescriptor;
import org.ow2.proactive.scheduler.descriptor.JobDescriptor;
import org.ow2.proactive.scheduler.job.JobIdImpl;
import org.ow2.proactive.scheduler.task.TaskResultImpl;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class SchedulingServiceTest8 extends BaseServiceTest {
private TaskFlowJob createTestJob() throws Exception {
TaskFlowJob job = new TaskFlowJob();
job.setName(this.getClass().getSimpleName());
JavaTask task1 = new JavaTask();
task1.setName("javaTask");
task1.setExecutableClassName("class");
job.addTask(task1);
return job;
}
@Test
public void testTaskPreempt() throws Exception {
service.submitJob(createJob(createTestJob()));
listener.assertEvents(SchedulerEvent.JOB_SUBMITTED);
JobDescriptor jobDesc = startTask();
try {
service.preemptTask(jobDesc.getJobId(), "invalid task name", 100);
Assert.fail();
} catch (UnknownTaskException e) {
}
try {
service.preemptTask(JobIdImpl.makeJobId("1234567"), "javaTask", 100);
Assert.fail();
} catch (UnknownJobException e) {
}
service.preemptTask(jobDesc.getJobId(), "javaTask", 100);
listener.assertEvents(SchedulerEvent.JOB_PENDING_TO_RUNNING, SchedulerEvent.TASK_PENDING_TO_RUNNING,
SchedulerEvent.TASK_WAITING_FOR_RESTART);
infrastructure.assertRequests(1);
startTask();
service.preemptTask(jobDesc.getJobId(), "javaTask", 100);
listener
.assertEvents(SchedulerEvent.TASK_PENDING_TO_RUNNING, SchedulerEvent.TASK_WAITING_FOR_RESTART);
infrastructure.assertRequests(1);
startTask();
TaskId taskId = jobDesc.getInternal().getTask("javaTask").getId();
service.taskTerminatedWithResult(taskId, new TaskResultImpl(taskId, "OK", null, 0));
listener.assertEvents(SchedulerEvent.TASK_PENDING_TO_RUNNING,
SchedulerEvent.TASK_RUNNING_TO_FINISHED, SchedulerEvent.JOB_RUNNING_TO_FINISHED);
infrastructure.assertRequests(1);
try {
service.preemptTask(jobDesc.getJobId(), "javaTask", 100);
Assert.fail();
} catch (UnknownJobException e) {
}
}
private JobDescriptor startTask() throws Exception {
Map<JobId, JobDescriptor> jobsMap;
JobDescriptor jobDesc;
jobsMap = service.lockJobsToSchedule();
assertEquals(1, jobsMap.size());
jobDesc = jobsMap.values().iterator().next();
Assert.assertEquals(1, jobDesc.getEligibleTasks().size());
for (EligibleTaskDescriptor taskDesc : jobDesc.getEligibleTasks()) {
taskStarted(jobDesc, taskDesc);
}
service.unlockJobsToSchedule(jobsMap.values());
return jobDesc;
}
}
| agpl-3.0 |
cgi-eoss/fstep | fs-tep-api/src/main/java/com/cgi/eoss/fstep/api/security/ApiSecurityConfig.java | 4589 | package com.cgi.eoss.fstep.api.security;
import com.cgi.eoss.fstep.security.FstepUserDetailsService;
import com.cgi.eoss.fstep.security.FstepWebAuthenticationDetailsSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler;
import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler;
import org.springframework.security.acls.AclPermissionEvaluator;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.access.ExceptionTranslationFilter;
import org.springframework.security.web.authentication.Http403ForbiddenEntryPoint;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider;
import org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter;
@Configuration
@ConditionalOnProperty(value = "fstep.api.security.mode", havingValue = "SSO")
@EnableWebSecurity
@EnableGlobalAuthentication
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class ApiSecurityConfig {
@Bean
public WebSecurityConfigurerAdapter webSecurityConfigurerAdapter(
@Value("${fstep.api.security.username-request-header:REMOTE_USER}") String usernameRequestHeader,
@Value("${fstep.api.security.email-request-header:REMOTE_EMAIL}") String emailRequestHeader) {
return new WebSecurityConfigurerAdapter() {
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
// Extracts the shibboleth user id from the request
RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
filter.setAuthenticationManager(authenticationManager());
filter.setPrincipalRequestHeader(usernameRequestHeader);
filter.setAuthenticationDetailsSource(new FstepWebAuthenticationDetailsSource(emailRequestHeader));
// Handles any authentication exceptions, and translates to a simple 403
// There is no login redirection as we are expecting pre-auth
ExceptionTranslationFilter exceptionTranslationFilter = new ExceptionTranslationFilter(new Http403ForbiddenEntryPoint());
httpSecurity
.addFilterBefore(exceptionTranslationFilter, RequestHeaderAuthenticationFilter.class)
.addFilter(filter)
.authorizeRequests()
.anyRequest().authenticated();
httpSecurity
.csrf().disable();
httpSecurity
.cors();
httpSecurity
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
};
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth, FstepUserDetailsService fstepUserDetailsService) {
PreAuthenticatedAuthenticationProvider authenticationProvider = new PreAuthenticatedAuthenticationProvider();
authenticationProvider.setPreAuthenticatedUserDetailsService(fstepUserDetailsService);
auth.authenticationProvider(authenticationProvider);
}
@Bean
public MethodSecurityExpressionHandler createExpressionHandler(AclPermissionEvaluator aclPermissionEvaluator) {
DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler();
expressionHandler.setPermissionEvaluator(aclPermissionEvaluator);
return expressionHandler;
}
}
| agpl-3.0 |
erdincay/ejb | src/com/lp/server/artikel/ejb/Artikelreservierung.java | 4729 | /*******************************************************************************
* HELIUM V, Open Source ERP software for sustained success
* at small and medium-sized enterprises.
* Copyright (C) 2004 - 2015 HELIUM V IT-Solutions GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of theLicense, or
* (at your option) any later version.
*
* According to sec. 7 of the GNU Affero General Public License, version 3,
* the terms of the AGPL are supplemented with the following terms:
*
* "HELIUM V" and "HELIUM 5" are registered trademarks of
* HELIUM V IT-Solutions GmbH. The licensing of the program under the
* AGPL does not imply a trademark license. Therefore any rights, title and
* interest in our trademarks remain entirely with us. If you want to propagate
* modified versions of the Program under the name "HELIUM V" or "HELIUM 5",
* you may only do so if you have a written permission by HELIUM V IT-Solutions
* GmbH (to acquire a permission please contact HELIUM V IT-Solutions
* at trademark@heliumv.com).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact: developers@heliumv.com
******************************************************************************/
package com.lp.server.artikel.ejb;
import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
@NamedQueries( {
@NamedQuery(name = "ArtikelreservierungfindAll", query = "SELECT OBJECT(o) FROM Artikelreservierung o"),
@NamedQuery(name = "ArtikelreservierungfindByArtikelIId", query = "SELECT OBJECT(C) FROM Artikelreservierung c WHERE c.artikelIId = ?1"),
@NamedQuery(name = "ArtikelreservierungfindByBelegartCNrIBelegartpositionid", query = "SELECT OBJECT(C) FROM Artikelreservierung c WHERE c.cBelegartnr = ?1 AND c.iBelegartpositionid = ?2") })
@Entity
@Table(name = "WW_ARTIKELRESERVIERUNG")
public class Artikelreservierung implements Serializable {
@Id
@Column(name = "I_ID")
private Integer iId;
@Column(name = "I_BELEGARTPOSITIONID")
private Integer iBelegartpositionid;
@Column(name = "T_LIEFERTERMIN")
private Timestamp tLiefertermin;
@Column(name = "N_MENGE")
private BigDecimal nMenge;
@Column(name = "C_BELEGARTNR")
private String cBelegartnr;
@Column(name = "ARTIKEL_I_ID")
private Integer artikelIId;
private static final long serialVersionUID = 1L;
public Artikelreservierung() {
super();
}
public Artikelreservierung(Integer belegartpositionid,
Integer artikelIId,
Timestamp liefertermin,
String belegartnr,
Integer id) {
setIBelegartpositionid(belegartpositionid);
setArtikelIId(artikelIId);
setTLiefertermin(liefertermin);
setCBelegartnr(belegartnr);
setIId(id);
//F_MENGE - Default 0
setNMenge(new BigDecimal(0));
}
public Artikelreservierung(Integer id,
String belegartnr,
Integer belegartpositionid,
Integer artikelIId,
Timestamp liefertermin,
BigDecimal menge) {
setIBelegartpositionid(belegartpositionid);
setArtikelIId(artikelIId);
setTLiefertermin(liefertermin);
setCBelegartnr(belegartnr);
setIId(id);
setNMenge(menge);
}
public Integer getIId() {
return this.iId;
}
public void setIId(Integer iId) {
this.iId = iId;
}
public Integer getIBelegartpositionid() {
return this.iBelegartpositionid;
}
public void setIBelegartpositionid(Integer iBelegartpositionid) {
this.iBelegartpositionid = iBelegartpositionid;
}
public Timestamp getTLiefertermin() {
return this.tLiefertermin;
}
public void setTLiefertermin(Timestamp tLiefertermin) {
this.tLiefertermin = tLiefertermin;
}
public BigDecimal getNMenge() {
return this.nMenge;
}
public void setNMenge(BigDecimal nMenge) {
this.nMenge = nMenge;
}
public String getCBelegartnr() {
return this.cBelegartnr;
}
public void setCBelegartnr(String cBelegartnr) {
this.cBelegartnr = cBelegartnr;
}
public Integer getArtikelIId() {
return this.artikelIId;
}
public void setArtikelIId(Integer artikelIId) {
this.artikelIId = artikelIId;
}
}
| agpl-3.0 |
open-health-hub/openmaxims-linux | openmaxims_workspace/ValueObjects/src/ims/core/vo/BedSpaceStateVoCollection.java | 8178 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.core.vo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import ims.framework.enumerations.SortOrder;
/**
* Linked to core.admin.pas.BedSpaceState business object (ID: 1014100009).
*/
public class BedSpaceStateVoCollection extends ims.vo.ValueObjectCollection implements ims.vo.ImsCloneable, Iterable<BedSpaceStateVo>
{
private static final long serialVersionUID = 1L;
private ArrayList<BedSpaceStateVo> col = new ArrayList<BedSpaceStateVo>();
public String getBoClassName()
{
return "ims.core.admin.pas.domain.objects.BedSpaceState";
}
public boolean add(BedSpaceStateVo value)
{
if(value == null)
return false;
if(this.col.indexOf(value) < 0)
{
return this.col.add(value);
}
return false;
}
public boolean add(int index, BedSpaceStateVo value)
{
if(value == null)
return false;
if(this.col.indexOf(value) < 0)
{
this.col.add(index, value);
return true;
}
return false;
}
public void clear()
{
this.col.clear();
}
public void remove(int index)
{
this.col.remove(index);
}
public int size()
{
return this.col.size();
}
public int indexOf(BedSpaceStateVo instance)
{
return col.indexOf(instance);
}
public BedSpaceStateVo get(int index)
{
return this.col.get(index);
}
public boolean set(int index, BedSpaceStateVo value)
{
if(value == null)
return false;
this.col.set(index, value);
return true;
}
public void remove(BedSpaceStateVo instance)
{
if(instance != null)
{
int index = indexOf(instance);
if(index >= 0)
remove(index);
}
}
public boolean contains(BedSpaceStateVo instance)
{
return indexOf(instance) >= 0;
}
public Object clone()
{
BedSpaceStateVoCollection clone = new BedSpaceStateVoCollection();
for(int x = 0; x < this.col.size(); x++)
{
if(this.col.get(x) != null)
clone.col.add((BedSpaceStateVo)this.col.get(x).clone());
else
clone.col.add(null);
}
return clone;
}
public boolean isValidated()
{
for(int x = 0; x < col.size(); x++)
if(!this.col.get(x).isValidated())
return false;
return true;
}
public String[] validate()
{
return validate(null);
}
public String[] validate(String[] existingErrors)
{
if(col.size() == 0)
return null;
java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>();
if(existingErrors != null)
{
for(int x = 0; x < existingErrors.length; x++)
{
listOfErrors.add(existingErrors[x]);
}
}
for(int x = 0; x < col.size(); x++)
{
String[] listOfOtherErrors = this.col.get(x).validate();
if(listOfOtherErrors != null)
{
for(int y = 0; y < listOfOtherErrors.length; y++)
{
listOfErrors.add(listOfOtherErrors[y]);
}
}
}
int errorCount = listOfErrors.size();
if(errorCount == 0)
return null;
String[] result = new String[errorCount];
for(int x = 0; x < errorCount; x++)
result[x] = (String)listOfErrors.get(x);
return result;
}
public BedSpaceStateVoCollection sort()
{
return sort(SortOrder.ASCENDING);
}
public BedSpaceStateVoCollection sort(boolean caseInsensitive)
{
return sort(SortOrder.ASCENDING, caseInsensitive);
}
public BedSpaceStateVoCollection sort(SortOrder order)
{
return sort(new BedSpaceStateVoComparator(order));
}
public BedSpaceStateVoCollection sort(SortOrder order, boolean caseInsensitive)
{
return sort(new BedSpaceStateVoComparator(order, caseInsensitive));
}
@SuppressWarnings("unchecked")
public BedSpaceStateVoCollection sort(Comparator comparator)
{
Collections.sort(col, comparator);
return this;
}
public ims.core.admin.pas.vo.BedSpaceStateRefVoCollection toRefVoCollection()
{
ims.core.admin.pas.vo.BedSpaceStateRefVoCollection result = new ims.core.admin.pas.vo.BedSpaceStateRefVoCollection();
for(int x = 0; x < this.col.size(); x++)
{
result.add(this.col.get(x));
}
return result;
}
public BedSpaceStateVo[] toArray()
{
BedSpaceStateVo[] arr = new BedSpaceStateVo[col.size()];
col.toArray(arr);
return arr;
}
public Iterator<BedSpaceStateVo> iterator()
{
return col.iterator();
}
@Override
protected ArrayList getTypedCollection()
{
return col;
}
private class BedSpaceStateVoComparator implements Comparator
{
private int direction = 1;
private boolean caseInsensitive = true;
public BedSpaceStateVoComparator()
{
this(SortOrder.ASCENDING);
}
public BedSpaceStateVoComparator(SortOrder order)
{
if (order == SortOrder.DESCENDING)
{
direction = -1;
}
}
public BedSpaceStateVoComparator(SortOrder order, boolean caseInsensitive)
{
if (order == SortOrder.DESCENDING)
{
direction = -1;
}
this.caseInsensitive = caseInsensitive;
}
public int compare(Object obj1, Object obj2)
{
BedSpaceStateVo voObj1 = (BedSpaceStateVo)obj1;
BedSpaceStateVo voObj2 = (BedSpaceStateVo)obj2;
return direction*(voObj1.compareTo(voObj2, this.caseInsensitive));
}
public boolean equals(Object obj)
{
return false;
}
}
public ims.core.vo.beans.BedSpaceStateVoBean[] getBeanCollection()
{
return getBeanCollectionArray();
}
public ims.core.vo.beans.BedSpaceStateVoBean[] getBeanCollectionArray()
{
ims.core.vo.beans.BedSpaceStateVoBean[] result = new ims.core.vo.beans.BedSpaceStateVoBean[col.size()];
for(int i = 0; i < col.size(); i++)
{
BedSpaceStateVo vo = ((BedSpaceStateVo)col.get(i));
result[i] = (ims.core.vo.beans.BedSpaceStateVoBean)vo.getBean();
}
return result;
}
public static BedSpaceStateVoCollection buildFromBeanCollection(java.util.Collection beans)
{
BedSpaceStateVoCollection coll = new BedSpaceStateVoCollection();
if(beans == null)
return coll;
java.util.Iterator iter = beans.iterator();
while (iter.hasNext())
{
coll.add(((ims.core.vo.beans.BedSpaceStateVoBean)iter.next()).buildVo());
}
return coll;
}
public static BedSpaceStateVoCollection buildFromBeanCollection(ims.core.vo.beans.BedSpaceStateVoBean[] beans)
{
BedSpaceStateVoCollection coll = new BedSpaceStateVoCollection();
if(beans == null)
return coll;
for(int x = 0; x < beans.length; x++)
{
coll.add(beans[x].buildVo());
}
return coll;
}
}
| agpl-3.0 |
open-health-hub/openmaxims-linux | openmaxims_workspace/Core/src/ims/core/forms/patientdocumentstatus/GenForm.java | 25209 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.core.forms.patientdocumentstatus;
import ims.framework.*;
import ims.framework.controls.*;
import ims.framework.enumerations.*;
import ims.framework.utils.RuntimeAnchoring;
public class GenForm extends FormBridge
{
private static final long serialVersionUID = 1L;
public boolean canProvideData(IReportSeed[] reportSeeds)
{
return new ReportDataProvider(reportSeeds, this.getFormReportFields()).canProvideData();
}
public boolean hasData(IReportSeed[] reportSeeds)
{
return new ReportDataProvider(reportSeeds, this.getFormReportFields()).hasData();
}
public IReportField[] getData(IReportSeed[] reportSeeds)
{
return getData(reportSeeds, false);
}
public IReportField[] getData(IReportSeed[] reportSeeds, boolean excludeNulls)
{
return new ReportDataProvider(reportSeeds, this.getFormReportFields(), excludeNulls).getData();
}
public static class cmbStatusComboBox extends ComboBoxBridge
{
private static final long serialVersionUID = 1L;
public void newRow(ims.core.vo.lookups.DocumentStatus value, String text)
{
super.control.newRow(value, text);
}
public void newRow(ims.core.vo.lookups.DocumentStatus value, String text, ims.framework.utils.Image image)
{
super.control.newRow(value, text, image);
}
public void newRow(ims.core.vo.lookups.DocumentStatus value, String text, ims.framework.utils.Color textColor)
{
super.control.newRow(value, text, textColor);
}
public void newRow(ims.core.vo.lookups.DocumentStatus value, String text, ims.framework.utils.Image image, ims.framework.utils.Color textColor)
{
super.control.newRow(value, text, image, textColor);
}
public boolean removeRow(ims.core.vo.lookups.DocumentStatus value)
{
return super.control.removeRow(value);
}
public ims.core.vo.lookups.DocumentStatus getValue()
{
return (ims.core.vo.lookups.DocumentStatus)super.control.getValue();
}
public void setValue(ims.core.vo.lookups.DocumentStatus value)
{
super.control.setValue(value);
}
}
private void validateContext(ims.framework.Context context)
{
if(context == null)
return;
}
private void validateMandatoryContext(Context context)
{
if(new ims.framework.ContextVariable("Core.PatientCorrespondence", "_cv_Core.PatientCorrespondence").getValueIsNull(context))
throw new ims.framework.exceptions.FormMandatoryContextMissingException("The required context data 'Core.PatientCorrespondence' is not available.");
}
public boolean supportsRecordedInError()
{
return false;
}
public ims.vo.ValueObject getRecordedInErrorVo()
{
return null;
}
protected void setContext(FormLoader loader, Form form, ims.framework.interfaces.IAppForm appForm, UIFactory factory, Context context) throws Exception
{
setContext(loader, form, appForm, factory, context, Boolean.FALSE, new Integer(0), null, null, new Integer(0));
}
protected void setContext(FormLoader loader, Form form, ims.framework.interfaces.IAppForm appForm, UIFactory factory, Context context, Boolean skipContextValidation) throws Exception
{
setContext(loader, form, appForm, factory, context, skipContextValidation, new Integer(0), null, null, new Integer(0));
}
protected void setContext(FormLoader loader, Form form, ims.framework.interfaces.IAppForm appForm, UIFactory factory, ims.framework.Context context, Boolean skipContextValidation, Integer startControlID, ims.framework.utils.SizeInfo runtimeSize, ims.framework.Control control, Integer startTabIndex) throws Exception
{
if(loader == null); // this is to avoid eclipse warning only.
if(factory == null); // this is to avoid eclipse warning only.
if(runtimeSize == null); // this is to avoid eclipse warning only.
if(appForm == null)
throw new RuntimeException("Invalid application form");
if(startControlID == null)
throw new RuntimeException("Invalid startControlID");
if(control == null); // this is to avoid eclipse warning only.
if(startTabIndex == null)
throw new RuntimeException("Invalid startTabIndex");
this.context = context;
this.componentIdentifier = startControlID.toString();
this.formInfo = form.getFormInfo();
this.globalContext = new GlobalContext(context);
if(skipContextValidation == null || !skipContextValidation.booleanValue())
{
validateContext(context);
validateMandatoryContext(context);
}
super.setContext(form);
ims.framework.utils.SizeInfo designSize = new ims.framework.utils.SizeInfo(448, 128);
if(runtimeSize == null)
runtimeSize = designSize;
form.setWidth(runtimeSize.getWidth());
form.setHeight(runtimeSize.getHeight());
super.setGlobalContext(ContextBridgeFlyweightFactory.getInstance().create(GlobalContextBridge.class, context, false));
// Label Controls
RuntimeAnchoring anchoringHelper1 = new RuntimeAnchoring(designSize, runtimeSize, 8, 42, 106, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT);
super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1000), new Integer(anchoringHelper1.getX()), new Integer(anchoringHelper1.getY()), new Integer(anchoringHelper1.getWidth()), new Integer(anchoringHelper1.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Document Status:", new Integer(1), null, new Integer(0)}));
// Button Controls
RuntimeAnchoring anchoringHelper2 = new RuntimeAnchoring(designSize, runtimeSize, 224, 96, 75, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT);
super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1001), new Integer(anchoringHelper2.getX()), new Integer(anchoringHelper2.getY()), new Integer(anchoringHelper2.getWidth()), new Integer(anchoringHelper2.getHeight()), new Integer(startTabIndex.intValue() + 3), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT, "Cancel", Boolean.FALSE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default }));
RuntimeAnchoring anchoringHelper3 = new RuntimeAnchoring(designSize, runtimeSize, 149, 96, 72, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT);
super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1002), new Integer(anchoringHelper3.getX()), new Integer(anchoringHelper3.getY()), new Integer(anchoringHelper3.getWidth()), new Integer(anchoringHelper3.getHeight()), new Integer(startTabIndex.intValue() + 2), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT, "Ok", Boolean.FALSE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default }));
// ComboBox Controls
RuntimeAnchoring anchoringHelper4 = new RuntimeAnchoring(designSize, runtimeSize, 120, 40, 312, 21, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT);
ComboBox m_cmbStatusTemp = (ComboBox)factory.getControl(ComboBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1003), new Integer(anchoringHelper4.getX()), new Integer(anchoringHelper4.getY()), new Integer(anchoringHelper4.getWidth()), new Integer(anchoringHelper4.getHeight()), new Integer(startTabIndex.intValue() + 1), ControlState.ENABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT ,Boolean.TRUE, Boolean.FALSE, SortOrder.NONE, Boolean.FALSE, new Integer(1), null, Boolean.TRUE, new Integer(-1)});
addControl(m_cmbStatusTemp);
cmbStatusComboBox cmbStatus = (cmbStatusComboBox)ComboBoxFlyweightFactory.getInstance().createComboBoxBridge(cmbStatusComboBox.class, m_cmbStatusTemp);
super.addComboBox(cmbStatus);
}
public Button btnCancel()
{
return (Button)super.getControl(1);
}
public Button btnOk()
{
return (Button)super.getControl(2);
}
public cmbStatusComboBox cmbStatus()
{
return (cmbStatusComboBox)super.getComboBox(0);
}
public GlobalContext getGlobalContext()
{
return this.globalContext;
}
public static class GlobalContextBridge extends ContextBridge
{
private static final long serialVersionUID = 1L;
}
private IReportField[] getFormReportFields()
{
if(this.context == null)
return null;
if(this.reportFields == null)
this.reportFields = new ReportFields(this.context, this.formInfo, this.componentIdentifier).getReportFields();
return this.reportFields;
}
private class ReportFields
{
public ReportFields(Context context, ims.framework.FormInfo formInfo, String componentIdentifier)
{
this.context = context;
this.formInfo = formInfo;
this.componentIdentifier = componentIdentifier;
}
public IReportField[] getReportFields()
{
String prefix = formInfo.getLocalVariablesPrefix();
IReportField[] fields = new IReportField[99];
fields[0] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ID", "ID_Patient");
fields[1] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-SEX", "Sex");
fields[2] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-DOB", "Dob");
fields[3] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-DOD", "Dod");
fields[4] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-RELIGION", "Religion");
fields[5] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ISACTIVE", "IsActive");
fields[6] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ETHNICORIGIN", "EthnicOrigin");
fields[7] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-MARITALSTATUS", "MaritalStatus");
fields[8] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-SCN", "SCN");
fields[9] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-SOURCEOFINFORMATION", "SourceOfInformation");
fields[10] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-TIMEOFDEATH", "TimeOfDeath");
fields[11] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ISQUICKREGISTRATIONPATIENT", "IsQuickRegistrationPatient");
fields[12] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-CURRENTRESPONSIBLECONSULTANT", "CurrentResponsibleConsultant");
fields[13] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientFilter", "BO-1001100000-ID", "ID_Patient");
fields[14] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientFilter", "BO-1001100000-SEX", "Sex");
fields[15] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientFilter", "BO-1001100000-DOB", "Dob");
fields[16] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-ID", "ID_ClinicalContact");
fields[17] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-SPECIALTY", "Specialty");
fields[18] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-CONTACTTYPE", "ContactType");
fields[19] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-STARTDATETIME", "StartDateTime");
fields[20] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-ENDDATETIME", "EndDateTime");
fields[21] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-CARECONTEXT", "CareContext");
fields[22] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-ISCLINICALNOTECREATED", "IsClinicalNoteCreated");
fields[23] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ID", "ID_Hcp");
fields[24] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-HCPTYPE", "HcpType");
fields[25] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ISACTIVE", "IsActive");
fields[26] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ISHCPARESPONSIBLEHCP", "IsHCPaResponsibleHCP");
fields[27] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ISARESPONSIBLEEDCLINICIAN", "IsAResponsibleEDClinician");
fields[28] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ID", "ID_CareContext");
fields[29] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-CONTEXT", "Context");
fields[30] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ORDERINGHOSPITAL", "OrderingHospital");
fields[31] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ESTIMATEDDISCHARGEDATE", "EstimatedDischargeDate");
fields[32] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-STARTDATETIME", "StartDateTime");
fields[33] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ENDDATETIME", "EndDateTime");
fields[34] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-LOCATIONTYPE", "LocationType");
fields[35] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-RESPONSIBLEHCP", "ResponsibleHCP");
fields[36] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-ID", "ID_EpisodeOfCare");
fields[37] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-CARESPELL", "CareSpell");
fields[38] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-SPECIALTY", "Specialty");
fields[39] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-RELATIONSHIP", "Relationship");
fields[40] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-STARTDATE", "StartDate");
fields[41] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-ENDDATE", "EndDate");
fields[42] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ID", "ID_ClinicalNotes");
fields[43] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-CLINICALNOTE", "ClinicalNote");
fields[44] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-NOTETYPE", "NoteType");
fields[45] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-DISCIPLINE", "Discipline");
fields[46] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-CLINICALCONTACT", "ClinicalContact");
fields[47] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ISDERIVEDNOTE", "IsDerivedNote");
fields[48] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-FORREVIEW", "ForReview");
fields[49] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-FORREVIEWDISCIPLINE", "ForReviewDiscipline");
fields[50] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-REVIEWINGDATETIME", "ReviewingDateTime");
fields[51] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ISCORRECTED", "IsCorrected");
fields[52] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ISTRANSCRIBED", "IsTranscribed");
fields[53] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-SOURCEOFNOTE", "SourceOfNote");
fields[54] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-RECORDINGDATETIME", "RecordingDateTime");
fields[55] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-INHOSPITALREPORT", "InHospitalReport");
fields[56] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-CARECONTEXT", "CareContext");
fields[57] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-NOTECLASSIFICATION", "NoteClassification");
fields[58] = new ims.framework.ReportField(this.context, "_cvp_STHK.AvailableBedsListFilter", "BO-1014100009-ID", "ID_BedSpaceState");
fields[59] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingEmergencyAdmissionsFilter", "BO-1014100011-ID", "ID_PendingEmergencyAdmission");
fields[60] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingEmergencyAdmissionsFilter", "BO-1014100011-ADMISSIONSTATUS", "AdmissionStatus");
fields[61] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingDischargesListFilter", "BO-1014100000-ID", "ID_InpatientEpisode");
fields[62] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingDischargesListFilter", "BO-1014100000-ESTDISCHARGEDATE", "EstDischargeDate");
fields[63] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-ID", "ID_ClinicalNotes");
fields[64] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-FORREVIEW", "ForReview");
fields[65] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-FORREVIEWDISCIPLINE", "ForReviewDiscipline");
fields[66] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-NOTECLASSIFICATION", "NoteClassification");
fields[67] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-CARECONTEXT", "CareContext");
fields[68] = new ims.framework.ReportField(this.context, "_cvp_Core.PasEvent", "BO-1014100003-ID", "ID_PASEvent");
fields[69] = new ims.framework.ReportField(this.context, "_cvp_Correspondence.CorrespondenceDetails", "BO-1052100001-ID", "ID_CorrespondenceDetails");
fields[70] = new ims.framework.ReportField(this.context, "_cvp_CareUk.CatsReferral", "BO-1004100035-ID", "ID_CatsReferral");
fields[71] = new ims.framework.ReportField(this.context, "_cv_Core.PatientCorrespondence", "BO-1068100001-ID", "ID_PatientDocument");
fields[72] = new ims.framework.ReportField(this.context, "_cv_Core.PatientCorrespondence", "BO-1068100001-PATIENT", "Patient");
fields[73] = new ims.framework.ReportField(this.context, "_cv_Core.PatientCorrespondence", "BO-1068100001-EPISODEOFCARE", "EpisodeofCare");
fields[74] = new ims.framework.ReportField(this.context, "_cv_Core.PatientCorrespondence", "BO-1068100001-CARECONTEXT", "CareContext");
fields[75] = new ims.framework.ReportField(this.context, "_cv_Core.PatientCorrespondence", "BO-1068100001-CLINICALCONTACT", "ClinicalContact");
fields[76] = new ims.framework.ReportField(this.context, "_cv_Core.PatientCorrespondence", "BO-1068100001-REFERRAL", "Referral");
fields[77] = new ims.framework.ReportField(this.context, "_cv_Core.PatientCorrespondence", "BO-1068100001-NAME", "Name");
fields[78] = new ims.framework.ReportField(this.context, "_cv_Core.PatientCorrespondence", "BO-1068100001-CREATIONTYPE", "CreationType");
fields[79] = new ims.framework.ReportField(this.context, "_cv_Core.PatientCorrespondence", "BO-1068100001-CATEGORY", "Category");
fields[80] = new ims.framework.ReportField(this.context, "_cv_Core.PatientCorrespondence", "BO-1068100001-STATUS", "Status");
fields[81] = new ims.framework.ReportField(this.context, "_cv_Core.PatientCorrespondence", "BO-1068100001-RECORDINGUSER", "RecordingUser");
fields[82] = new ims.framework.ReportField(this.context, "_cv_Core.PatientCorrespondence", "BO-1068100001-RECORDINGDATETIME", "RecordingDateTime");
fields[83] = new ims.framework.ReportField(this.context, "_cv_Core.PatientCorrespondence", "BO-1068100001-AUTHORINGHCP", "AuthoringHCP");
fields[84] = new ims.framework.ReportField(this.context, "_cv_Core.PatientCorrespondence", "BO-1068100001-AUTHORINGDATETIME", "AuthoringDateTime");
fields[85] = new ims.framework.ReportField(this.context, "_cv_Core.PatientCorrespondence", "BO-1068100001-SPECIALTY", "Specialty");
fields[86] = new ims.framework.ReportField(this.context, "_cv_Core.PatientCorrespondence", "BO-1068100001-CORRESPONDENCESTATUS", "CorrespondenceStatus");
fields[87] = new ims.framework.ReportField(this.context, "_cv_Core.PatientCorrespondence", "BO-1068100001-DOCUMENTDATE", "DocumentDate");
fields[88] = new ims.framework.ReportField(this.context, "_cv_Core.PatientCorrespondence", "BO-1068100001-CLINIC", "Clinic");
fields[89] = new ims.framework.ReportField(this.context, "_cv_Core.PatientCorrespondence", "BO-1068100001-ISLOCKEDFOREDITING", "IsLockedForEditing");
fields[90] = new ims.framework.ReportField(this.context, "_cv_Core.PatientCorrespondence", "BO-1068100001-LOCKEDBYUSER", "LockedByUser");
fields[91] = new ims.framework.ReportField(this.context, "_cv_Core.PatientCorrespondence", "BO-1068100001-LOCKEDONDATETIME", "LockedOnDateTime");
fields[92] = new ims.framework.ReportField(this.context, "_cv_Core.PatientCorrespondence", "BO-1068100001-RESPONSIBLEHCP", "ResponsibleHCP");
fields[93] = new ims.framework.ReportField(this.context, "_cv_Core.PatientCorrespondence", "BO-1068100001-NOOFCOPIES", "NoOfCopies");
fields[94] = new ims.framework.ReportField(this.context, "_cv_Core.PatientCorrespondence", "BO-1068100001-HISTORICALFILENAME", "HistoricalFileName");
fields[95] = new ims.framework.ReportField(this.context, "_cv_Core.PatientCorrespondence", "BO-1068100001-HISTORICDOCID", "HistoricDocId");
fields[96] = new ims.framework.ReportField(this.context, "_cv_Core.PatientCorrespondence", "BO-1068100001-WASPRINTED", "WasPrinted");
fields[97] = new ims.framework.ReportField(this.context, "_cv_Core.PatientCorrespondence", "BO-1068100001-EMAILSTATUS", "EmailStatus");
fields[98] = new ims.framework.ReportField(this.context, "_cv_Core.PatientCorrespondence", "BO-1068100001-COPYPATIENTONCORRESPONDENCE", "CopyPatientOnCorrespondence");
return fields;
}
protected Context context = null;
protected ims.framework.FormInfo formInfo;
protected String componentIdentifier;
}
public String getUniqueIdentifier()
{
return null;
}
private Context context = null;
private ims.framework.FormInfo formInfo = null;
private String componentIdentifier;
private GlobalContext globalContext = null;
private IReportField[] reportFields = null;
}
| agpl-3.0 |
pleku/ion-training-diary | vaadin-cdi/src/test/java/com/vaadin/cdi/uis/WithAnnotationRegisteredView.java | 1725 | /*
* Copyright 2000-2013 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.cdi.uis;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.PostConstruct;
import com.vaadin.cdi.CDIView;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.Label;
import com.vaadin.ui.VerticalLayout;
/**
*/
@CDIView(value = "withAnnotationRegisteredView")
public class WithAnnotationRegisteredView extends CustomComponent implements
View {
private final static AtomicInteger COUNTER = new AtomicInteger(0);
@PostConstruct
public void initialize() {
COUNTER.incrementAndGet();
}
@Override
public void enter(ViewChangeEvent event) {
VerticalLayout layout = new VerticalLayout();
layout.setSizeFull();
setCompositionRoot(layout);
Label label = new Label("ViewLabel");
label.setId("label");
layout.addComponent(label);
}
public static int getNumberOfInstances() {
return COUNTER.get();
}
public static void resetCounter() {
COUNTER.set(0);
}
}
| agpl-3.0 |
IMS-MAXIMS/openMAXIMS | Source Library/openmaxims_workspace/ValueObjects/src/ims/therapies/vo/beans/RemedialActivityVoBean.java | 8638 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.therapies.vo.beans;
public class RemedialActivityVoBean extends ims.vo.ValueObjectBean
{
public RemedialActivityVoBean()
{
}
public RemedialActivityVoBean(ims.therapies.vo.RemedialActivityVo vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.activity = vo.getActivity() == null ? null : (ims.vo.LookupInstanceBean)vo.getActivity().getBean();
this.patientposition = vo.getPatientPosition() == null ? null : (ims.vo.LookupInstanceBean)vo.getPatientPosition().getBean();
this.activityposition = vo.getActivityPosition() == null ? null : (ims.vo.LookupInstanceBean)vo.getActivityPosition().getBean();
this.sequence = vo.getSequence() == null ? null : (ims.vo.LookupInstanceBean)vo.getSequence().getBean();
this.duration = vo.getDuration();
this.activityheight = vo.getActivityHeight();
this.numberpauses = vo.getNumberPauses();
this.restperiod = vo.getRestPeriod();
this.averagepause = vo.getAveragePause();
this.independence = vo.getIndependence() == null ? null : (ims.vo.LookupInstanceBean)vo.getIndependence().getBean();
this.subjectiveobs = vo.getSubjectiveObs() == null ? null : (ims.vo.LookupInstanceBean)vo.getSubjectiveObs().getBean();
this.technique = vo.getTechnique() == null ? null : vo.getTechnique().getBeanCollection();
this.material = vo.getMaterial() == null ? null : vo.getMaterial().getBeanCollection();
}
public void populate(ims.vo.ValueObjectBeanMap map, ims.therapies.vo.RemedialActivityVo vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.activity = vo.getActivity() == null ? null : (ims.vo.LookupInstanceBean)vo.getActivity().getBean();
this.patientposition = vo.getPatientPosition() == null ? null : (ims.vo.LookupInstanceBean)vo.getPatientPosition().getBean();
this.activityposition = vo.getActivityPosition() == null ? null : (ims.vo.LookupInstanceBean)vo.getActivityPosition().getBean();
this.sequence = vo.getSequence() == null ? null : (ims.vo.LookupInstanceBean)vo.getSequence().getBean();
this.duration = vo.getDuration();
this.activityheight = vo.getActivityHeight();
this.numberpauses = vo.getNumberPauses();
this.restperiod = vo.getRestPeriod();
this.averagepause = vo.getAveragePause();
this.independence = vo.getIndependence() == null ? null : (ims.vo.LookupInstanceBean)vo.getIndependence().getBean();
this.subjectiveobs = vo.getSubjectiveObs() == null ? null : (ims.vo.LookupInstanceBean)vo.getSubjectiveObs().getBean();
this.technique = vo.getTechnique() == null ? null : vo.getTechnique().getBeanCollection();
this.material = vo.getMaterial() == null ? null : vo.getMaterial().getBeanCollection();
}
public ims.therapies.vo.RemedialActivityVo buildVo()
{
return this.buildVo(new ims.vo.ValueObjectBeanMap());
}
public ims.therapies.vo.RemedialActivityVo buildVo(ims.vo.ValueObjectBeanMap map)
{
ims.therapies.vo.RemedialActivityVo vo = null;
if(map != null)
vo = (ims.therapies.vo.RemedialActivityVo)map.getValueObject(this);
if(vo == null)
{
vo = new ims.therapies.vo.RemedialActivityVo();
map.addValueObject(this, vo);
vo.populate(map, this);
}
return vo;
}
public Integer getId()
{
return this.id;
}
public void setId(Integer value)
{
this.id = value;
}
public int getVersion()
{
return this.version;
}
public void setVersion(int value)
{
this.version = value;
}
public ims.vo.LookupInstanceBean getActivity()
{
return this.activity;
}
public void setActivity(ims.vo.LookupInstanceBean value)
{
this.activity = value;
}
public ims.vo.LookupInstanceBean getPatientPosition()
{
return this.patientposition;
}
public void setPatientPosition(ims.vo.LookupInstanceBean value)
{
this.patientposition = value;
}
public ims.vo.LookupInstanceBean getActivityPosition()
{
return this.activityposition;
}
public void setActivityPosition(ims.vo.LookupInstanceBean value)
{
this.activityposition = value;
}
public ims.vo.LookupInstanceBean getSequence()
{
return this.sequence;
}
public void setSequence(ims.vo.LookupInstanceBean value)
{
this.sequence = value;
}
public Integer getDuration()
{
return this.duration;
}
public void setDuration(Integer value)
{
this.duration = value;
}
public Integer getActivityHeight()
{
return this.activityheight;
}
public void setActivityHeight(Integer value)
{
this.activityheight = value;
}
public String getNumberPauses()
{
return this.numberpauses;
}
public void setNumberPauses(String value)
{
this.numberpauses = value;
}
public Integer getRestPeriod()
{
return this.restperiod;
}
public void setRestPeriod(Integer value)
{
this.restperiod = value;
}
public Integer getAveragePause()
{
return this.averagepause;
}
public void setAveragePause(Integer value)
{
this.averagepause = value;
}
public ims.vo.LookupInstanceBean getIndependence()
{
return this.independence;
}
public void setIndependence(ims.vo.LookupInstanceBean value)
{
this.independence = value;
}
public ims.vo.LookupInstanceBean getSubjectiveObs()
{
return this.subjectiveobs;
}
public void setSubjectiveObs(ims.vo.LookupInstanceBean value)
{
this.subjectiveobs = value;
}
public java.util.Collection getTechnique()
{
return this.technique;
}
public void setTechnique(java.util.Collection value)
{
this.technique = value;
}
public void addTechnique(java.util.Collection value)
{
if(this.technique == null)
this.technique = new java.util.ArrayList();
this.technique.add(value);
}
public ims.therapies.vo.beans.RemedialMaterialVoBean[] getMaterial()
{
return this.material;
}
public void setMaterial(ims.therapies.vo.beans.RemedialMaterialVoBean[] value)
{
this.material = value;
}
private Integer id;
private int version;
private ims.vo.LookupInstanceBean activity;
private ims.vo.LookupInstanceBean patientposition;
private ims.vo.LookupInstanceBean activityposition;
private ims.vo.LookupInstanceBean sequence;
private Integer duration;
private Integer activityheight;
private String numberpauses;
private Integer restperiod;
private Integer averagepause;
private ims.vo.LookupInstanceBean independence;
private ims.vo.LookupInstanceBean subjectiveobs;
private java.util.Collection technique;
private ims.therapies.vo.beans.RemedialMaterialVoBean[] material;
}
| agpl-3.0 |
CannibalVox/DimDoors | src/main/java/StevenDimDoors/mod_pocketDim/saving/DDSaveHandler.java | 14607 | package StevenDimDoors.mod_pocketDim.saving;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import net.minecraftforge.common.DimensionManager;
import StevenDimDoors.mod_pocketDim.Point3D;
import StevenDimDoors.mod_pocketDim.mod_pocketDim;
import StevenDimDoors.mod_pocketDim.core.DimLink;
import StevenDimDoors.mod_pocketDim.core.DimensionType;
import StevenDimDoors.mod_pocketDim.core.LinkType;
import StevenDimDoors.mod_pocketDim.core.NewDimData;
import StevenDimDoors.mod_pocketDim.core.PocketManager;
import StevenDimDoors.mod_pocketDim.dungeon.DungeonData;
import StevenDimDoors.mod_pocketDim.helpers.DungeonHelper;
import StevenDimDoors.mod_pocketDim.util.DDLogger;
import StevenDimDoors.mod_pocketDim.util.FileFilters;
import StevenDimDoors.mod_pocketDim.util.Point4D;
import com.google.common.io.Files;
public class DDSaveHandler
{
public static boolean loadAll()
{
// SenseiKiwi: Loading up our save data is not as simple as just reading files.
// To properly restore dimensions, we need to make sure we always load
// a dimension's parent and root before trying to load it. We'll use
// topological sorting to determine the order in which to recreate the
// dimension objects such that we respect those dependencies.
// Links must be loaded after instantiating all the dimensions and must
// be checked against our dimension blacklist.
// Don't surround this code with try-catch. Our mod should crash if an error
// occurs at this level, since it could lead to some nasty problems.
DDLogger.startTimer("Loading data");
String basePath = DimensionManager.getCurrentSaveRootDirectory() + "/DimensionalDoors/data/";
File dataDirectory = new File(basePath);
// Check if the folder exists. If it doesn't, just return.
if (!dataDirectory.exists())
{
return true;
}
// Load the dimension blacklist
File blacklistFile = new File(basePath+"blacklist.txt");
if(blacklistFile.exists())
{
BlacklistProcessor blacklistReader = new BlacklistProcessor();
List<Integer> blacklist = readBlacklist(blacklistFile,blacklistReader);
PocketManager.createAndRegisterBlacklist(blacklist);
}
// Load the personal pockets mapping
File personalPocketMap = new File(basePath+"personalPockets.txt");
HashMap<String, Integer> ppMap = new HashMap<String, Integer>();
if(personalPocketMap.exists())
{
PersonalPocketMappingProcessor ppMappingProcessor = new PersonalPocketMappingProcessor();
ppMap = readPersonalPocketsMapping(personalPocketMap,ppMappingProcessor);
}
// List any dimension data files and read each dimension
DimDataProcessor reader = new DimDataProcessor();
HashMap<Integer, PackedDimData> packedDims = new HashMap<Integer, PackedDimData>();
FileFilter dataFileFilter = new FileFilters.RegexFileFilter("dim_-?\\d+\\.txt");
File[] dataFiles = dataDirectory.listFiles(dataFileFilter);
for (File dataFile : dataFiles)
{
PackedDimData packedDim = readDimension(dataFile, reader);
if(packedDim == null)
{
throw new IllegalStateException("The DD data for "+dataFile.getName().replace(".txt", "")+" at "+dataFile.getPath()+" is corrupted. Please report this on the MCF or on the DD github issues tracker.");
}
packedDims.put(packedDim.ID,packedDim);
}
List<PackedLinkData> linksToUnpack = new ArrayList<PackedLinkData>();
//get the grand list of all links to unpack
for(PackedDimData packedDim : packedDims.values())
{
linksToUnpack.addAll(packedDim.Links);
}
unpackDimData(packedDims);
unpackLinkData(linksToUnpack);
HashMap<String, NewDimData> personalPocketsMap = new HashMap<String, NewDimData>();
for(Entry<String, Integer> pair : ppMap.entrySet())
{
personalPocketsMap.put(pair.getKey(), PocketManager.getDimensionData(pair.getValue()));
}
PocketManager.setPersonalPocketsMapping(personalPocketsMap);
return true;
}
/**
* Takes a list of packedDimData and rebuilds the DimData for it
* @param packedDims
* @return
*/
public static boolean unpackDimData(HashMap<Integer,PackedDimData> packedDims)
{
LinkedList<Integer> dimsToRegister = new LinkedList<Integer>();
for(PackedDimData packedDim : packedDims.values())
{
//fix pockets without parents
verifyParents(packedDim, packedDims);
//Load roots first by inserting them in the LinkedList first.
if(packedDim.RootID==packedDim.ID)
{
dimsToRegister.addFirst(packedDim.ID);
}
}
//load the children for each root
while(!dimsToRegister.isEmpty())
{
Integer childID = dimsToRegister.pop();
PackedDimData data = packedDims.get(childID);
dimsToRegister.addAll(verifyChildren(data, packedDims));
PocketManager.registerPackedDimData(data);
}
return true;
}
/**
* Fixes the case where a child of a parent has been deleted.
* -removes the child from parent
*
* @param packedDim
* @param packedDims
* @return
*/
private static ArrayList<Integer> verifyChildren(PackedDimData packedDim,HashMap<Integer,PackedDimData> packedDims)
{
ArrayList<Integer> children = new ArrayList<Integer>();
children.addAll(packedDim.ChildIDs);
boolean isMissing = false;
for(Integer childID : packedDim.ChildIDs)
{
if(!packedDims.containsKey(childID))
{
children.remove(childID);
isMissing=true;
}
}
if(isMissing)
{
packedDim=(new PackedDimData(packedDim.ID, packedDim.Depth, packedDim.PackDepth, packedDim.ParentID, packedDim.RootID, packedDim.Orientation, DimensionType.getTypeFromIndex(packedDim.DimensionType), packedDim.IsFilled, packedDim.DungeonData, packedDim.Origin, children, packedDim.Links, packedDim.Tails));
packedDims.put(packedDim.ID, packedDim);
}
return children;
}
/**
* Fixes the case where a child had its parent deleted OR where a parent forgot about its child
* -Changes the missing parent to the dims root if its original parent is gone.
* -Finds the new parent and adds it to its list of children or reminds the old parent if it forgot its child
*
* @param packedDim
* @param packedDims
*/
public static void verifyParents(PackedDimData packedDim,HashMap<Integer,PackedDimData> packedDims)
{
ArrayList<Integer> fosterChildren = new ArrayList<Integer>();
fosterChildren.add(packedDim.ID);
DimensionType type = DimensionType.getTypeFromIndex(packedDim.DimensionType);
//fix pockets without parents
if(!packedDims.containsKey(packedDim.ParentID))
{
//Fix the orphan by changing its root to its parent, re-connecting it to the list
packedDim=(new PackedDimData(packedDim.ID, 1, packedDim.PackDepth, packedDim.RootID, packedDim.RootID, packedDim.Orientation,type, packedDim.IsFilled, packedDim.DungeonData, packedDim.Origin, packedDim.ChildIDs, packedDim.Links, packedDim.Tails));
packedDims.put(packedDim.ID, packedDim);
}
//fix pockets whose parents have forgotten about them
PackedDimData fosterParent = packedDims.get(packedDim.ParentID);
if(!fosterParent.ChildIDs.contains(packedDim.ID)&&packedDim.ID!=packedDim.RootID)
{
//find the root, and fix it by adding the orphan's ID to its children
fosterChildren.addAll(fosterParent.ChildIDs);
fosterParent=(new PackedDimData(fosterParent.ID, fosterParent.Depth, fosterParent.PackDepth, fosterParent.ParentID, fosterParent.RootID, fosterParent.Orientation, type, fosterParent.IsFilled, fosterParent.DungeonData, fosterParent.Origin, fosterChildren, fosterParent.Links, fosterParent.Tails));
packedDims.put(fosterParent.ID, fosterParent);
}
}
public static boolean unpackLinkData(List<PackedLinkData> linksToUnpack)
{
Point3D fakePoint = new Point3D(-1,-1,-1);
List<PackedLinkData> unpackedLinks = new ArrayList<PackedLinkData>();
/**
* sort through the list, unpacking links that do not have parents.
*/
//TODO- what we have a loop of links?
for(PackedLinkData packedLink : linksToUnpack)
{
if(packedLink.parent.equals(fakePoint))
{
NewDimData data = PocketManager.getDimensionData(packedLink.source.getDimension());
LinkType linkType = LinkType.getLinkTypeFromIndex(packedLink.tail.linkType);
DimLink link = data.createLink(packedLink.source, linkType, packedLink.orientation, packedLink.lock);
Point4D destination = packedLink.tail.destination;
if(destination!=null)
{
PocketManager.createDimensionDataDangerously(destination.getDimension()).setLinkDestination(link, destination.getX(),destination.getY(),destination.getZ());
}
unpackedLinks.add(packedLink);
}
}
linksToUnpack.removeAll(unpackedLinks);
//unpack remaining children
while(!linksToUnpack.isEmpty())
{
for(PackedLinkData packedLink : linksToUnpack)
{
NewDimData data = PocketManager.createDimensionDataDangerously(packedLink.source.getDimension());
if(data.getLink(packedLink.parent)!=null)
{
data.createChildLink(packedLink.source, data.getLink(packedLink.parent), packedLink.lock);
}
unpackedLinks.add(packedLink);
}
linksToUnpack.removeAll(unpackedLinks);
}
return true;
}
private static PackedDimData readDimension(File dataFile, DimDataProcessor reader)
{
try
{
return reader.readFromFile(dataFile);
}
catch (Exception e)
{
System.err.println("Could not read dimension data from: " + dataFile.getAbsolutePath());
System.err.println("The following error occurred:");
printException(e, false);
return null;
}
}
public static boolean saveAll(Iterable<? extends IPackable<PackedDimData>> dimensions,
List<Integer> blacklist, boolean checkModified) throws IOException
{
// Create the data directory for our dimensions
// Don't catch exceptions here. If we can't create this folder,
// the mod should crash to let the user know early on.
// Get the save directory path
File saveDirectory = new File(mod_pocketDim.instance.getCurrentSavePath() + "/DimensionalDoors/data/");
String savePath = saveDirectory.getAbsolutePath();
String baseSavePath = savePath + "/dim_";
File backupDirectory = new File(savePath + "/backup");
String baseBackupPath = backupDirectory.getAbsolutePath() + "/dim_";
if (!saveDirectory.exists())
{
// Create the save directory
Files.createParentDirs(saveDirectory);
saveDirectory.mkdir();
}
if (!backupDirectory.exists())
{
// Create the backup directory
backupDirectory.mkdir();
}
// Create and write the blackList
writeBlacklist(blacklist, savePath);
//create and write personal pocket mapping
writePersonalPocketMap(PocketManager.getPersonalPocketMapping(), savePath);
// Write the dimension save data
boolean succeeded = true;
DimDataProcessor writer = new DimDataProcessor();
for (IPackable<PackedDimData> dimension : dimensions)
{
// Check if the dimension should be saved
if (!checkModified || dimension.isModified())
{
if (writeDimension(dimension, writer, baseSavePath, baseBackupPath))
{
dimension.clearModified();
}
else
{
succeeded = false;
}
}
}
return succeeded;
}
private static boolean writeBlacklist(List<Integer> blacklist, String savePath)
{
try
{
BlacklistProcessor writer = new BlacklistProcessor();
File tempFile = new File(savePath + "/blacklist.tmp");
File saveFile = new File(savePath + "/blacklist.txt");
writer.writeToFile(tempFile, blacklist);
saveFile.delete();
tempFile.renameTo(saveFile);
return true;
}
catch (Exception e)
{
System.err.println("Could not save blacklist. The following error occurred:");
printException(e, true);
return false;
}
}
private static boolean writePersonalPocketMap(HashMap<String, NewDimData> hashMap, String savePath)
{
try
{
HashMap<String, Integer> ppMap = new HashMap<String, Integer>();
for(Entry<String, NewDimData> pair : hashMap.entrySet())
{
ppMap.put(pair.getKey(), pair.getValue().id());
}
PersonalPocketMappingProcessor writer = new PersonalPocketMappingProcessor();
File tempFile = new File(savePath + "/personalPockets.tmp");
File saveFile = new File(savePath + "/personalPockets.txt");
writer.writeToFile(tempFile, ppMap);
saveFile.delete();
tempFile.renameTo(saveFile);
return true;
}
catch (Exception e)
{
System.err.println("Could not save personal pockets mapping. The following error occurred:");
printException(e, true);
return false;
}
}
private static boolean writeDimension(IPackable<PackedDimData> dimension, DimDataProcessor writer, String basePath, String backupPath)
{
try
{
File saveFile = new File(basePath + dimension.name() + ".txt");
// If the save file already exists, back it up.
if (saveFile.exists())
{
Files.move(saveFile, new File(backupPath + dimension.name() + ".txt"));
}
writer.writeToFile(saveFile, dimension.pack());
return true;
}
catch (Exception e)
{
System.err.println("Could not save data for dimension #" + dimension.name() + ". The following error occurred:");
printException(e, true);
return false;
}
}
private static void printException(Exception e, boolean verbose)
{
if (e.getCause() == null)
{
if (verbose)
{
e.printStackTrace();
}
else
{
System.err.println(e.getMessage());
}
}
else
{
System.out.println(e.getMessage());
System.err.println("Caused by an underlying error:");
if (verbose)
{
e.getCause().printStackTrace();
}
else
{
System.err.println(e.getCause().getMessage());
}
}
}
//TODO - make this more robust
public static DungeonData unpackDungeonData(PackedDungeonData packedDungeon)
{
for(DungeonData data : DungeonHelper.instance().getRegisteredDungeons())
{
if(data.schematicName().equals(packedDungeon.SchematicName))
{
return data;
}
}
return null;
}
public static List<Integer> readBlacklist(File blacklistFile, BlacklistProcessor reader)
{
try
{
List<Integer> list = reader.readFromFile(blacklistFile);
if (list == null)
return new ArrayList<Integer>(0);
return list;
}
catch (Exception e)
{
e.printStackTrace();
return new ArrayList<Integer>(0);
}
}
public static HashMap<String,Integer> readPersonalPocketsMapping(File ppMap, PersonalPocketMappingProcessor reader)
{
try
{
return reader.readFromFile(ppMap);
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
}
| lgpl-2.1 |
ilanKeshet/checkstyle | src/test/java/com/puppycrawl/tools/checkstyle/utils/CheckUtilsTest.java | 5292 | ////////////////////////////////////////////////////////////////////////////////
// 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.utils;
import static com.puppycrawl.tools.checkstyle.internal.TestUtils.assertUtilsClassHasPrivateConstructor;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Assert;
import org.junit.Test;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
public class CheckUtilsTest {
@Test
public void testIsProperUtilsClass() throws ReflectiveOperationException {
assertUtilsClassHasPrivateConstructor(CheckUtils.class);
}
@Test
public void testParseDoubleWithIncorrectToken() {
final double parsedDouble = CheckUtils.parseDouble("1_02", TokenTypes.ASSIGN);
assertEquals(0.0, parsedDouble, 0.0);
}
@Test
public void testElseWithCurly() {
final DetailAST ast = new DetailAST();
ast.setType(TokenTypes.ASSIGN);
ast.setText("ASSIGN");
Assert.assertFalse(CheckUtils.isElseIf(ast));
final DetailAST parentAst = new DetailAST();
parentAst.setType(TokenTypes.LCURLY);
parentAst.setText("LCURLY");
final DetailAST ifAst = new DetailAST();
ifAst.setType(TokenTypes.LITERAL_IF);
ifAst.setText("IF");
parentAst.addChild(ifAst);
Assert.assertFalse(CheckUtils.isElseIf(ifAst));
final DetailAST parentAst2 = new DetailAST();
parentAst2.setType(TokenTypes.SLIST);
parentAst2.setText("SLIST");
parentAst2.addChild(ifAst);
Assert.assertFalse(CheckUtils.isElseIf(ifAst));
final DetailAST elseAst = new DetailAST();
elseAst.setType(TokenTypes.LITERAL_ELSE);
elseAst.setFirstChild(ifAst);
Assert.assertTrue(CheckUtils.isElseIf(ifAst));
}
@Test
public void testEquals() {
final DetailAST litStatic = new DetailAST();
litStatic.setType(TokenTypes.LITERAL_STATIC);
final DetailAST modifiers = new DetailAST();
modifiers.setType(TokenTypes.MODIFIERS);
modifiers.addChild(litStatic);
final DetailAST metDef = new DetailAST();
metDef.setType(TokenTypes.METHOD_DEF);
metDef.addChild(modifiers);
Assert.assertFalse(CheckUtils.isEqualsMethod(metDef));
metDef.removeChildren();
final DetailAST metName = new DetailAST();
metName.setType(TokenTypes.IDENT);
metName.setText("equals");
metDef.addChild(metName);
final DetailAST modifiers2 = new DetailAST();
modifiers2.setType(TokenTypes.MODIFIERS);
metDef.addChild(modifiers2);
final DetailAST parameter1 = new DetailAST();
final DetailAST parameter2 = new DetailAST();
final DetailAST parameters = new DetailAST();
parameters.setType(TokenTypes.PARAMETERS);
parameters.addChild(parameter2);
parameters.addChild(parameter1);
metDef.addChild(parameters);
Assert.assertFalse(CheckUtils.isEqualsMethod(metDef));
}
@Test
public void testGetAccessModifierFromModifiersTokenWrongTokenType() {
final DetailAST modifiers = new DetailAST();
modifiers.setType(TokenTypes.METHOD_DEF);
try {
CheckUtils.getAccessModifierFromModifiersToken(modifiers);
fail(IllegalArgumentException.class.getSimpleName() + " was expected.");
}
catch (IllegalArgumentException exc) {
final String expectedExceptionMsg = "expected non-null AST-token with type 'MODIFIERS'";
final String actualExceptionMsg = exc.getMessage();
assertEquals(expectedExceptionMsg, actualExceptionMsg);
}
}
@Test
public void testGetAccessModifierFromModifiersTokenWithNullParameter() {
try {
CheckUtils.getAccessModifierFromModifiersToken(null);
fail(IllegalArgumentException.class.getSimpleName() + " was expected.");
}
catch (IllegalArgumentException exc) {
final String expectedExceptionMsg = "expected non-null AST-token with type 'MODIFIERS'";
final String actualExceptionMsg = exc.getMessage();
assertEquals(expectedExceptionMsg, actualExceptionMsg);
}
}
}
| lgpl-2.1 |
trixmot/mod1 | build/tmp/recompileMc/sources/net/minecraft/world/chunk/storage/RegionFileCache.java | 2660 | package net.minecraft.world.chunk.storage;
import com.google.common.collect.Maps;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
public class RegionFileCache
{
/** A map containing Files as keys and RegionFiles as values */
private static final Map regionsByFilename = Maps.newHashMap();
private static final String __OBFID = "CL_00000383";
public static synchronized RegionFile createOrLoadRegionFile(File worldDir, int chunkX, int chunkZ)
{
File file2 = new File(worldDir, "region");
File file3 = new File(file2, "r." + (chunkX >> 5) + "." + (chunkZ >> 5) + ".mca");
RegionFile regionfile = (RegionFile)regionsByFilename.get(file3);
if (regionfile != null)
{
return regionfile;
}
else
{
if (!file2.exists())
{
file2.mkdirs();
}
if (regionsByFilename.size() >= 256)
{
clearRegionFileReferences();
}
RegionFile regionfile1 = new RegionFile(file3);
regionsByFilename.put(file3, regionfile1);
return regionfile1;
}
}
/**
* clears region file references
*/
public static synchronized void clearRegionFileReferences()
{
Iterator iterator = regionsByFilename.values().iterator();
while (iterator.hasNext())
{
RegionFile regionfile = (RegionFile)iterator.next();
try
{
if (regionfile != null)
{
regionfile.close();
}
}
catch (IOException ioexception)
{
ioexception.printStackTrace();
}
}
regionsByFilename.clear();
}
/**
* Returns an input stream for the specified chunk. Args: worldDir, chunkX, chunkZ
*/
public static DataInputStream getChunkInputStream(File worldDir, int chunkX, int chunkZ)
{
RegionFile regionfile = createOrLoadRegionFile(worldDir, chunkX, chunkZ);
return regionfile.getChunkDataInputStream(chunkX & 31, chunkZ & 31);
}
/**
* Returns an output stream for the specified chunk. Args: worldDir, chunkX, chunkZ
*/
public static DataOutputStream getChunkOutputStream(File worldDir, int chunkX, int chunkZ)
{
RegionFile regionfile = createOrLoadRegionFile(worldDir, chunkX, chunkZ);
return regionfile.getChunkDataOutputStream(chunkX & 31, chunkZ & 31);
}
} | lgpl-2.1 |
makerbot/RXTX-devel | Rewrite2010/src/java/main/gnu/io/ParallelPortImpl.java | 11203 | /*-------------------------------------------------------------------------
| RXTX License v 2.1 - LGPL v 2.1 + Linking Over Controlled Interface.
| RXTX is a native interface to serial ports in java.
| Copyright 1997-2007 by Trent Jarvi tjarvi@qbang.org and others who
| actually wrote it. See individual source files for more information.
|
| A copy of the LGPL v 2.1 may be found at
| http://www.gnu.org/licenses/lgpl.txt on March 4th 2007. A copy is
| here for your convenience.
|
| 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.
|
| An executable that contains no derivative of any portion of RXTX, but
| is designed to work with RXTX by being dynamically linked with it,
| is considered a "work that uses the Library" subject to the terms and
| conditions of the GNU Lesser General Public License.
|
| The following has been added to the RXTX License to remove
| any confusion about linking to RXTX. We want to allow in part what
| section 5, paragraph 2 of the LGPL does not permit in the special
| case of linking over a controlled interface. The intent is to add a
| Java Specification Request or standards body defined interface in the
| future as another exception but one is not currently available.
|
| http://www.fsf.org/licenses/gpl-faq.html#LinkingOverControlledInterface
|
| As a special exception, the copyright holders of RXTX give you
| permission to link RXTX with independent modules that communicate with
| RXTX solely through the Sun Microsytems CommAPI interface version 2,
| regardless of the license terms of these independent modules, and to copy
| and distribute the resulting combined work under terms of your choice,
| provided that every copy of the combined work is accompanied by a complete
| copy of the source code of RXTX (the version of RXTX used to produce the
| combined work), being distributed under the terms of the GNU Lesser General
| Public License plus this exception. An independent module is a
| module which is not derived from or based on RXTX.
|
| Note that people who make modified versions of RXTX are not obligated
| to grant this special exception for their modified versions; it is
| their choice whether to do so. The GNU Lesser General Public License
| gives permission to release a modified version without this exception; this
| exception also makes it possible to release a modified version which
| carries forward this exception.
|
| You should have received a copy of the GNU Lesser General Public
| License along with this library; if not, write to the Free
| Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
| All trademarks belong to their respective owners.
--------------------------------------------------------------------------*/
package gnu.io;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.TooManyListenersException;
/**
* A <code>ParallelPort</code> implementation.
*
* <dl>
* <dt><b>Thread-safe:</b></dt>
* <dd>This class may be used in multi-threaded applications.</dd>
* </dl>
* @author <a href="http://www.rxtx.org">The RXTX Project</a>
*/
public final class ParallelPortImpl extends ParallelPort {
private final static Dispatcher dispatch = Dispatcher.getInstance();
private final ParallelPortEventHandler eventHandler;
public ParallelPortImpl(CommPortIdentifier cpi, int portHandle) {
super(cpi, portHandle);
this.eventHandler = new ParallelPortEventHandler(this);
}
protected synchronized void abort() {
this.eventHandler.removeEventListener();
super.abort();
}
public synchronized void addEventListener(ParallelPortEventListener listener) throws TooManyListenersException {
checkStatus();
this.eventHandler.addEventListener(listener);
}
public synchronized void close() {
this.eventHandler.removeEventListener();
super.close();
}
public synchronized void disableReceiveFraming() {
checkStatus();
this.receiveFramingEnabled = false;
}
public synchronized void disableReceiveThreshold() {
checkStatus();
this.receiveThresholdEnabled = false;
}
public synchronized void disableReceiveTimeout() {
checkStatus();
this.receiveTimeoutEnabled = false;
}
public synchronized void enableReceiveFraming(int framingByte) throws UnsupportedCommOperationException {
checkStatus();
this.receiveFramingEnabled = true;
this.receiveFramingByte = framingByte;
}
public synchronized void enableReceiveThreshold(int threshold) throws UnsupportedCommOperationException {
checkStatus();
this.receiveThresholdEnabled = true;
this.receiveThreshold = threshold;
}
public synchronized void enableReceiveTimeout(int receiveTimeout) throws UnsupportedCommOperationException {
checkStatus();
this.receiveTimeoutEnabled = true;
this.receiveTimeout = receiveTimeout;
}
public synchronized int getInputBufferSize() {
checkStatus();
try {
return dispatch.getInputBufferSize(this.portHandle);
} catch (IOException e) {
abort(e);
return 0;
}
}
public synchronized InputStream getInputStream() throws IOException {
checkStatus();
if (this.inputStream == null) {
if (!dispatch.isPortReadable(this.portHandle)) {
return null;
}
this.inputStream = new PortInputStream(this);
}
return this.inputStream;
}
public synchronized int getMode() {
checkStatus();
try {
return dispatch.getMode(this.portHandle);
} catch (IOException e) {
abort(e);
return 0;
}
}
public synchronized int getOutputBufferFree() {
checkStatus();
try {
return dispatch.getOutputBufferFree(this.portHandle);
} catch (IOException e) {
abort(e);
return 0;
}
}
public synchronized int getOutputBufferSize() {
checkStatus();
try {
return dispatch.getOutputBufferSize(this.portHandle);
} catch (IOException e) {
abort(e);
return 0;
}
}
public synchronized OutputStream getOutputStream() throws IOException {
checkStatus();
if (this.outputStream == null) {
if (!dispatch.isPortWritable(this.portHandle)) {
return null;
}
this.outputStream = new PortOutputStream(this);
}
return this.outputStream;
}
public synchronized int getReceiveFramingByte() {
checkStatus();
return this.receiveFramingByte;
}
public synchronized int getReceiveThreshold() {
checkStatus();
return this.receiveThreshold;
}
public synchronized int getReceiveTimeout() {
checkStatus();
return this.receiveTimeout;
}
public synchronized boolean isPaperOut() {
checkStatus();
try {
return dispatch.isPaperOut(this.portHandle);
} catch (IOException e) {
abort(e);
return false;
}
}
/**
* Returns <code>true</code> if the output buffer is empty.
* @return <code>true</code> if the output buffer is empty.
*/
public synchronized boolean isOutputBufferEmpty() {
checkStatus();
try {
return dispatch.isOutputBufferEmpty(this.portHandle);
} catch (IOException e) {
abort(e);
return false;
}
}
public synchronized boolean isPrinterBusy() {
checkStatus();
try {
return dispatch.isPrinterBusy(this.portHandle);
} catch (IOException e) {
abort(e);
return false;
}
}
public synchronized boolean isPrinterError() {
checkStatus();
try {
return dispatch.isPrinterError(this.portHandle);
} catch (IOException e) {
abort(e);
return false;
}
}
public synchronized boolean isPrinterSelected() {
checkStatus();
try {
return dispatch.isPrinterSelected(this.portHandle);
} catch (IOException e) {
abort(e);
return false;
}
}
public synchronized boolean isPrinterTimedOut() {
checkStatus();
try {
return dispatch.isPrinterTimedOut(this.portHandle);
} catch (IOException e) {
abort(e);
return false;
}
}
public synchronized boolean isReceiveFramingEnabled() {
checkStatus();
return this.receiveFramingEnabled;
}
public synchronized boolean isReceiveThresholdEnabled() {
checkStatus();
return this.receiveThresholdEnabled;
}
public synchronized boolean isReceiveTimeoutEnabled() {
checkStatus();
return this.receiveTimeoutEnabled;
}
public synchronized void notifyOnBuffer(boolean enable) {
checkStatus();
this.eventHandler.notifyOnBuffer(enable);
}
public synchronized void notifyOnError(boolean enable) {
checkStatus();
this.eventHandler.notifyOnError(enable);
}
public synchronized void removeEventListener() {
checkStatus();
this.eventHandler.removeEventListener();
}
public synchronized void restart() {
checkStatus();
try {
dispatch.restart(this.portHandle);
} catch (IOException e) {
abort(e);
}
}
public synchronized void setInputBufferSize(int size) {
checkStatus();
try {
dispatch.setInputBufferSize(this.portHandle, size);
} catch (IOException e) {
abort(e);
}
}
public synchronized int setMode(int mode) throws UnsupportedCommOperationException {
checkStatus();
try {
return dispatch.setMode(this.portHandle, mode);
} catch (IOException e) {
abort(e);
return 0;
}
}
public synchronized void setOutputBufferSize(int size) {
checkStatus();
try {
dispatch.setOutputBufferSize(this.portHandle, size);
} catch (IOException e) {
abort(e);
}
}
public synchronized void suspend() {
checkStatus();
try {
dispatch.suspend(this.portHandle);
} catch (IOException e) {
abort(e);
}
}
}
| lgpl-2.1 |
simon04/jfreechart | src/main/java/org/jfree/chart/block/BlockParams.java | 4184 | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2016, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* 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.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* ----------------
* BlockParams.java
* ----------------
* (C) Copyright 2005-2008, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes:
* --------
* 19-Apr-2005 : Version 1 (DG);
*
*/
package org.jfree.chart.block;
/**
* A standard parameter object that can be passed to the draw() method defined
* by the {@link Block} class.
*/
public class BlockParams implements EntityBlockParams {
/**
* A flag that controls whether or not the block should generate and
* return chart entities for the items it draws.
*/
private boolean generateEntities;
/**
* The x-translation (used to enable chart entities to use global
* coordinates rather than coordinates that are local to the container
* they are within).
*/
private double translateX;
/**
* The y-translation (used to enable chart entities to use global
* coordinates rather than coordinates that are local to the container
* they are within).
*/
private double translateY;
/**
* Creates a new instance.
*/
public BlockParams() {
this.translateX = 0.0;
this.translateY = 0.0;
this.generateEntities = false;
}
/**
* Returns the flag that controls whether or not chart entities are
* generated.
*
* @return A boolean.
*/
@Override
public boolean getGenerateEntities() {
return this.generateEntities;
}
/**
* Sets the flag that controls whether or not chart entities are generated.
*
* @param generate the flag.
*/
public void setGenerateEntities(boolean generate) {
this.generateEntities = generate;
}
/**
* Returns the translation required to convert local x-coordinates back to
* the coordinate space of the container.
*
* @return The x-translation amount.
*/
public double getTranslateX() {
return this.translateX;
}
/**
* Sets the translation required to convert local x-coordinates into the
* coordinate space of the container.
*
* @param x the x-translation amount.
*/
public void setTranslateX(double x) {
this.translateX = x;
}
/**
* Returns the translation required to convert local y-coordinates back to
* the coordinate space of the container.
*
* @return The y-translation amount.
*/
public double getTranslateY() {
return this.translateY;
}
/**
* Sets the translation required to convert local y-coordinates into the
* coordinate space of the container.
*
* @param y the y-translation amount.
*/
public void setTranslateY(double y) {
this.translateY = y;
}
}
| lgpl-2.1 |
juanmjacobs/kettle | src-ui/org/pentaho/di/ui/core/dialog/Splash.java | 8798 | /*
* Copyright (c) 2007 Pentaho Corporation. All rights reserved.
* This software was developed by Pentaho Corporation and is provided under the terms
* of the GNU Lesser General Public License, Version 2.1. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho
* Data Integration. The Initial Developer is Pentaho Corporation.
*
* Software distributed under the GNU Lesser Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
* the license for the specific language governing your rights and limitations.
*/
package org.pentaho.di.ui.core.dialog;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Calendar;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.mortbay.log.Log;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.laf.BasePropertyHandler;
import org.pentaho.di.ui.util.ImageUtil;
/**
* Displays the Kettle splash screen
*
* @author Matt
* @since 14-mrt-2005
*/
public class Splash {
private Shell splash;
private Image kettle_image;
private Image kettle_icon;
private Image exclamation_image;
private Font verFont;
private Font licFont;
private Font devWarningFont;
private Color versionWarningBackgroundColor;
private Color versionWarningForegroundColor;
private int licFontSize = 8;
private static Class<?> PKG = Splash.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
public Splash(Display display) throws KettleException {
Rectangle displayBounds = display.getPrimaryMonitor().getBounds();
kettle_image = ImageUtil.getImageAsResource(display, BasePropertyHandler.getProperty("splash_image")); // "kettle_splash.png" //$NON-NLS-1$
kettle_icon = ImageUtil.getImageAsResource(display, BasePropertyHandler.getProperty("splash_icon")); // "spoon.ico" //$NON-NLS-1$
exclamation_image = ImageUtil.getImageAsResource(display, BasePropertyHandler
.getProperty("exclamation_image")); // "exclamation.png" //$NON-NLS-1$
verFont = new Font(display, "Helvetica", 11, SWT.BOLD); //$NON-NLS-1$
licFont = new Font(display, "Helvetica", licFontSize, SWT.NORMAL); //$NON-NLS-1$
devWarningFont = new Font(display, "Helvetica", 10, SWT.NORMAL); //$NON-NLS-1$
versionWarningBackgroundColor = new Color(display, 255, 253, 213);
versionWarningForegroundColor = new Color(display, 220, 177, 20);
splash = new Shell(display, SWT.NONE /*SWT.ON_TOP*/);
splash.setImage(kettle_icon);
splash.setText(BaseMessages.getString(PKG, "SplashDialog.Title")); // "Pentaho Data Integration" //$NON-NLS-1$
FormLayout splashLayout = new FormLayout();
splash.setLayout(splashLayout);
Canvas canvas = new Canvas(splash, SWT.NO_BACKGROUND);
FormData fdCanvas = new FormData();
fdCanvas.left = new FormAttachment(0, 0);
fdCanvas.top = new FormAttachment(0, 0);
fdCanvas.right = new FormAttachment(100, 0);
fdCanvas.bottom = new FormAttachment(100, 0);
canvas.setLayoutData(fdCanvas);
canvas.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
String versionText = BaseMessages.getString(PKG, "SplashDialog.Version") + " " + Const.VERSION; //$NON-NLS-1$ //$NON-NLS-2$
StringBuilder sb = new StringBuilder();
String line = null;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(Splash.class.getClassLoader().getResourceAsStream("org/pentaho/di/ui/core/dialog/license/license.txt"))); //$NON-NLS-1$
while((line = reader.readLine()) != null) {
sb.append(line + System.getProperty("line.separator")); //$NON-NLS-1$
}
} catch (Exception ex) {
sb.append(""); //$NON-NLS-1$
Log.warn(BaseMessages.getString(PKG, "SplashDialog.LicenseTextNotFound")); //$NON-NLS-1$
}
Calendar cal = Calendar.getInstance();
String licenseText = String.format(sb.toString(), cal);
e.gc.drawImage(kettle_image, 0, 0);
// If this is a Milestone or RC release, warn the user
if (Const.RELEASE.equals(Const.ReleaseType.MILESTONE)) {
versionText = BaseMessages.getString(PKG, "SplashDialog.DeveloperRelease") + " - " + versionText; //$NON-NLS-1$ //$NON-NLS-2$
drawVersionWarning(e);
} else if (Const.RELEASE.equals(Const.ReleaseType.RELEASE_CANDIDATE)) {
versionText = BaseMessages.getString(PKG, "SplashDialog.ReleaseCandidate") + " - " + versionText; //$NON-NLS-1$//$NON-NLS-2$
}
else if (Const.RELEASE.equals(Const.ReleaseType.PREVIEW)) {
versionText = BaseMessages.getString(PKG, "SplashDialog.PreviewRelease") + " - " + versionText; //$NON-NLS-1$//$NON-NLS-2$
}
else if (Const.RELEASE.equals(Const.ReleaseType.GA)) {
versionText = BaseMessages.getString(PKG, "SplashDialog.GA") + " - " + versionText; //$NON-NLS-1$//$NON-NLS-2$
}
e.gc.setFont(verFont);
e.gc.drawText(versionText, 290, 205, true);
// try using the desired font size for the license text
e.gc.setFont(licFont);
// if the text will not fit the allowed space
while (!willLicenseTextFit(licenseText, e.gc)) {
licFontSize--;
if (licFont != null) {
licFont.dispose();
}
licFont = new Font(e.display, "Helvetica", licFontSize, SWT.NORMAL); //$NON-NLS-1$
e.gc.setFont(licFont);
}
e.gc.drawText(licenseText, 290, 290, true);
}
});
splash.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent arg0) {
kettle_image.dispose();
kettle_icon.dispose();
exclamation_image.dispose();
verFont.dispose();
licFont.dispose();
devWarningFont.dispose();
versionWarningForegroundColor.dispose();
versionWarningBackgroundColor.dispose();
}
});
Rectangle bounds = kettle_image.getBounds();
int x = (displayBounds.width - bounds.width) / 2;
int y = (displayBounds.height - bounds.height) / 2;
splash.setSize(bounds.width, bounds.height);
splash.setLocation(x, y);
splash.open();
}
// determine if the license text will fit the allocated space
private boolean willLicenseTextFit(String licenseText, GC gc) {
Point splashSize = splash.getSize();
Point licenseDrawLocation = new Point(290, 290);
Point requiredSize = gc.textExtent(licenseText);
int width = splashSize.x - licenseDrawLocation.x;
int height = splashSize.y - licenseDrawLocation.y;
boolean fitsVertically = width >= requiredSize.x;
boolean fitsHorizontally = height >= requiredSize.y;
return (fitsVertically && fitsHorizontally);
}
private void drawVersionWarning(PaintEvent e) {
drawVersionWarning(e.gc, e.display);
}
private void drawVersionWarning(GC gc, Display display) {
gc.setBackground(versionWarningBackgroundColor);
gc.setForeground(versionWarningForegroundColor);
gc.fillRectangle(290, 231, 367, 49);
gc.drawRectangle(290, 231, 367, 49);
gc.setForeground(display.getSystemColor(SWT.COLOR_BLACK));
gc.drawImage(exclamation_image, 304, 243);
gc.setFont(devWarningFont);
gc.drawText(BaseMessages.getString(PKG, "SplashDialog.DevelopmentWarning"), 335, 241); //$NON-NLS-1$
}
public void dispose() {
if (!splash.isDisposed())
splash.dispose();
}
public void hide() {
splash.setVisible(false);
}
public void show() {
splash.setVisible(true);
}
}
| lgpl-2.1 |
JKatzwinkel/bts | org.bbaw.bts.ui.corpus/src/org/bbaw/bts/ui/corpus/preferences/LemmaListSettingsPage.java | 8899 | package org.bbaw.bts.ui.corpus.preferences;
import java.util.List;
import java.util.Vector;
import org.bbaw.bts.btsmodel.BTSProject;
import org.bbaw.bts.btsmodel.BTSProjectDBCollection;
import org.bbaw.bts.commons.BTSPluginIDs;
import org.bbaw.bts.core.commons.BTSCoreConstants;
import org.bbaw.bts.core.commons.staticAccess.StaticAccessController;
import org.bbaw.bts.core.controller.generalController.BTSProjectController;
import org.bbaw.bts.ui.main.provider.BTSProjectLabelProvider;
import org.bbaw.bts.ui.main.provider.BTSProjectRemovableContentProvider;
import org.bbaw.bts.ui.main.provider.ListContentProvider;
import org.eclipse.core.runtime.preferences.ConfigurationScope;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.e4.core.contexts.IEclipseContext;
import org.eclipse.e4.core.services.log.Logger;
import org.eclipse.emf.edit.provider.ComposedAdapterFactory;
import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider;
import org.eclipse.jface.preference.FieldEditorPreferencePage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.IWorkbench;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.osgi.service.prefs.BackingStoreException;
import com.richclientgui.toolbox.duallists.DualListComposite;
public class LemmaListSettingsPage extends FieldEditorPreferencePage {
private ComboViewer comboViewer;
private BTSProject selectedProject;
private String main_lemmaList;
private DualListComposite<BTSProject> duallistcomposite;
private IEclipseContext context;
private BTSProjectController projectController;
private List<BTSProject> projects;
private String active_lemmaLists;
private BTSProjectRemovableContentProvider chrosenProvider;
private IEclipsePreferences prefs;
private Logger logger;
private boolean loaded;
/**
* Create the preference page.
*/
public LemmaListSettingsPage() {
super(FLAT);
setTitle("Lemma List Settings");
}
/**
* Create contents of the preference page.
*/
@Override
protected void createFieldEditors() {
Composite container = (Composite) this.getControl();
Label lblSelectYourMain = new Label(container, SWT.NONE);
lblSelectYourMain.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1));
lblSelectYourMain.setText("Select project with your main working lemma list");
comboViewer = new ComboViewer(container, SWT.READ_ONLY);
comboViewer.getControl().setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 1, 1));
ComposedAdapterFactory factory = new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE);
AdapterFactoryLabelProvider labelProvider = new AdapterFactoryLabelProvider(factory);
comboViewer.setContentProvider(new ListContentProvider());
comboViewer.setLabelProvider(labelProvider);
comboViewer.addSelectionChangedListener(new ISelectionChangedListener()
{
@Override
public void selectionChanged(SelectionChangedEvent event)
{
Object o = event.getSelection();
IStructuredSelection sel = (IStructuredSelection) o;
selectedProject = (BTSProject) sel.getFirstElement();
}
});
Group grpFurtherProjectsFrom = new Group(container, SWT.NONE);
grpFurtherProjectsFrom.setLayout(new GridLayout(2, false));
grpFurtherProjectsFrom.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
grpFurtherProjectsFrom.setText("Further projects with lemma lists from which you want to read data");
Label lblAvailableProjects = new Label(grpFurtherProjectsFrom, SWT.NONE);
lblAvailableProjects.setText("Available projects with lemma lists");
Label lblProjectsToBe = new Label(grpFurtherProjectsFrom, SWT.NONE);
lblProjectsToBe.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false, 1, 1));
lblProjectsToBe.setAlignment(SWT.RIGHT);
lblProjectsToBe.setText("Active lemma lists");
duallistcomposite = new DualListComposite<BTSProject>(grpFurtherProjectsFrom, SWT.NONE);
duallistcomposite.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true, 2, 1));
duallistcomposite.setBackground(grpFurtherProjectsFrom.getBackground());
init(null);
}
/**
* Initialize the preference page.
*/
public void init(IWorkbench workbench) {
// BundleContext bundleContext = Platform.getBundle("org.bbaw.bts.ui.main").getBundleContext();
context = StaticAccessController.getContext();
projectController = context.get(BTSProjectController.class);
prefs = ConfigurationScope.INSTANCE.getNode("org.bbaw.bts.app");
main_lemmaList = prefs.get(BTSPluginIDs.PREF_MAIN_LEMMALIST_KEY, prefs.get(BTSPluginIDs.PREF_MAIN_PROJECT_KEY, null));
active_lemmaLists = prefs.get(BTSPluginIDs.PREF_ACTIVE_LEMMALISTS, prefs.get(BTSPluginIDs.PREF_ACTIVE_PROJECTS, null));
logger = context.get(Logger.class);
loadListInput();
}
private void loadListInput()
{
projects = projectController.listProjects(null);
comboViewer.setInput(projects);
List<BTSProject> availableProjects = new Vector<BTSProject>(1);
List<BTSProject> chosenProjects = new Vector<BTSProject>(1);
if (active_lemmaLists != null && active_lemmaLists.trim().length() > 0)
{
String[] pros = active_lemmaLists.split("\\|");
for (BTSProject pp : projects)
{
boolean found = false;
boolean chosen = false;
for (BTSProjectDBCollection col : pp.getDbCollections())
{
if (col.getCollectionName().endsWith("wlist"))
{
found = true;
break;
}
}
if (!found)
{
// no lemma list in project
continue;
}
if (main_lemmaList != null && main_lemmaList.equals(pp.getPrefix()))
{
selectedProject = pp;
comboViewer.setSelection(new StructuredSelection(pp));
}
for (String p : pros)
{
if (p.equals(pp.getPrefix()))
{
chosenProjects.add(pp);
found = true;
chosen = true;
break;
}
}
if (found && !chosen)
{
availableProjects.add(pp);
}
}
}
duallistcomposite.setAvailableContentProvider(new BTSProjectRemovableContentProvider(availableProjects));
duallistcomposite.setAvailableLabelProvider(new BTSProjectLabelProvider());
chrosenProvider = new BTSProjectRemovableContentProvider(chosenProjects);
duallistcomposite.setChosenContentProvider(chrosenProvider);
duallistcomposite.setChosenLabelProvider(new BTSProjectLabelProvider());
loaded = true;
}
private String getActiveProjectSelectionsAsString() {
String string = "";
for (String s : getActiveProjectSelectionsAsStringList())
{
string += s + "|";
}
return string.length() > 2 ? string.substring(0, string.length() - 1) : "";
}
private List<String> getActiveProjectSelectionsAsStringList()
{
List<String> prefixes = new Vector<String>();
if (chrosenProvider == null)
{
return prefixes;
}
List<BTSProject> selections = chrosenProvider.getInputElements();
for (BTSProject project : selections)
{
if (project.getPrefix() != null)
{
prefixes.add(project.getPrefix());
}
}
return prefixes;
}
@Override
public boolean performOk() {
if (!loaded)
{
return super.performOk();
}
boolean saveRequired = false;
if (selectedProject != null && main_lemmaList != null && !main_lemmaList.equals(selectedProject.getPrefix()))
{
prefs.put(BTSPluginIDs.PREF_MAIN_LEMMALIST_KEY, selectedProject.getPrefix());
// update instance scope so that new value is injected
InstanceScope.INSTANCE.getNode("org.bbaw.bts.app").put(BTSPluginIDs.PREF_MAIN_LEMMALIST_KEY, selectedProject.getPrefix());
saveRequired = true;
}
String selectedProjetsString = getActiveProjectSelectionsAsString();
if (selectedProjetsString != null && !selectedProjetsString.equals(active_lemmaLists))
{
prefs.put(BTSPluginIDs.PREF_ACTIVE_LEMMALISTS, selectedProjetsString);
// update instance scope so that new value is injected
InstanceScope.INSTANCE.getNode("org.bbaw.bts.app").put(BTSPluginIDs.PREF_ACTIVE_LEMMALISTS, selectedProjetsString);
saveRequired = true;
}
if (saveRequired)
{
try {
prefs.flush();
} catch (BackingStoreException e) {
logger.error(e);
}
}
return super.performOk();
}
}
| lgpl-3.0 |
SergiyKolesnikov/fuji | examples/Violet/base/com/horstmann/violet/framework/EditorFrame.java | 3586 | /*
Violet - A program for editing UML diagrams.
Copyright (C) 2002 Cay S. Horstmann (http://horstmann.com)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.horstmann.violet.framework;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.beans.DefaultPersistenceDelegate;
import java.beans.Encoder;
import java.beans.ExceptionListener;
import java.beans.Expression;
import java.beans.PersistenceDelegate;
import java.beans.PropertyVetoException;
import java.beans.Statement;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.ResourceBundle;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
/**
This desktop frame contains panes that show graphs.
*/
public class EditorFrame extends JFrame
{
/**
Constructs a blank frame with a desktop pane
but no graph windows.
@param appClassName the fully qualified app class name.
It is expected that the resources are appClassName + "Strings"
and appClassName + "Version" (the latter for version-specific
resources)
*/
public EditorFrame(Class appClass)
{
Dimension screenSize
= Toolkit.getDefaultToolkit().getScreenSize();
int screenWidth = (int)screenSize.getWidth();
int screenHeight = (int)screenSize.getHeight();
setBounds(screenWidth / 16, screenHeight / 16,
screenWidth * 7 / 8, screenHeight * 7 / 8);
setDefaultCloseOperation(EXIT_ON_CLOSE);
desktop = new JDesktopPane();
setContentPane(desktop);
}
protected JDesktopPane desktop;
}
| lgpl-3.0 |
dana-i2cat/mqnaas | extensions/network/network.impl/src/main/java/org/mqnaas/network/impl/Network.java | 5406 | package org.mqnaas.network.impl;
/*
* #%L
* MQNaaS :: Network Implementation
* %%
* Copyright (C) 2007 - 2015 Fundació Privada i2CAT, Internet i
* Innovació a Catalunya
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.util.Collection;
import java.util.List;
import org.mqnaas.core.api.Endpoint;
import org.mqnaas.core.api.ICapability;
import org.mqnaas.core.api.IResource;
import org.mqnaas.core.api.IRootResource;
import org.mqnaas.core.api.IRootResourceAdministration;
import org.mqnaas.core.api.IRootResourceProvider;
import org.mqnaas.core.api.IServiceProvider;
import org.mqnaas.core.api.RootResourceDescriptor;
import org.mqnaas.core.api.Specification;
import org.mqnaas.core.api.Specification.Type;
import org.mqnaas.core.api.credentials.Credentials;
import org.mqnaas.core.api.exceptions.CapabilityNotFoundException;
import org.mqnaas.core.api.exceptions.ResourceNotFoundException;
import org.mqnaas.network.api.exceptions.NetworkCreationException;
import org.mqnaas.network.api.exceptions.NetworkReleaseException;
import org.mqnaas.network.api.request.IRequestBasedNetworkManagement;
import org.mqnaas.network.api.request.IRequestManagement;
import org.mqnaas.network.api.request.IRequestResourceManagement;
import org.mqnaas.network.api.topology.link.ILinkManagement;
import org.mqnaas.network.api.topology.port.INetworkPortManagement;
public class Network implements IRootResourceProvider {
private IResource network;
private IServiceProvider serviceProvider;
public Network(IResource network, IServiceProvider serviceProvider) {
this.network = network;
this.serviceProvider = serviceProvider;
}
private <C extends ICapability> C getCapability(Class<C> capabilityClass) {
try {
return serviceProvider.getCapability(network, capabilityClass);
} catch (CapabilityNotFoundException e) {
throw new RuntimeException("Necessary capability not bound to resource " + network, e);
}
}
public List<IResource> getLinks() {
return getCapability(ILinkManagement.class).getLinks();
}
public List<IResource> getPorts() {
return getCapability(INetworkPortManagement.class).getPorts();
}
public IResource createRequest() {
return getCapability(IRequestManagement.class).createRequest();
}
public IResource getNetworkResource() {
return network;
}
public IRootResource createVirtualNetwork(IResource request) throws NetworkCreationException {
return getCapability(IRequestBasedNetworkManagement.class).createNetwork(request);
}
public void releaseVirtualNetwork(IRootResource virtualNetwork) throws NetworkReleaseException {
getCapability(IRequestBasedNetworkManagement.class).releaseNetwork(virtualNetwork);
}
public IRootResource createResource(Specification spec, List<Endpoint> endpoints) throws InstantiationException, IllegalAccessException {
return getRootResourceAdministration().createRootResource(RootResourceDescriptor.create(spec, endpoints));
}
public IRootResource createResource(Specification spec, List<Endpoint> endpoints, Credentials creds) throws InstantiationException,
IllegalAccessException {
return getRootResourceAdministration().createRootResource(RootResourceDescriptor.create(spec, endpoints, creds));
}
public IResource createRequestResource(Type type) {
return getCapability(IRequestResourceManagement.class).createResource(type);
}
private IRootResourceAdministration getRootResourceAdministration() {
return getCapability(IRootResourceAdministration.class);
}
@Override
public List<IRootResource> getRootResources(Type type, String model, String version) throws ResourceNotFoundException {
return getCapability(IRootResourceProvider.class).getRootResources(type, model, version);
}
@Override
public List<IRootResource> getRootResources() {
return getCapability(IRootResourceProvider.class).getRootResources();
}
@Override
public IRootResource getRootResource(String id) throws ResourceNotFoundException {
return getCapability(IRootResourceProvider.class).getRootResource(id);
}
@Override
public void setRootResources(Collection<IRootResource> rootResources) {
getCapability(IRootResourceProvider.class).setRootResources(rootResources);
}
@Override
public void activate() {
}
public List<IResource> getNetworkSubResources() {
return getRequestResourceManagement().getResources();
}
private IRequestResourceManagement getRequestResourceManagement() {
return getCapability(IRequestResourceManagement.class);
}
public void removeResource(IRootResource resource) throws ResourceNotFoundException {
getRootResourceAdministration().removeRootResource(resource);
}
@Override
public void deactivate() {
}
public IResource createLink() {
return getCapability(ILinkManagement.class).createLink();
}
public void addPort(IResource port) {
getCapability(INetworkPortManagement.class).addPort(port);
}
} | lgpl-3.0 |
mabe02/lanterna | src/main/java/com/googlecode/lanterna/bundle/LocalizedUIBundle.java | 1504 | /*
* This file is part of lanterna (https://github.com/mabe02/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-2020 Martin Berglund
*/
package com.googlecode.lanterna.bundle;
import java.util.Locale;
/**
* This class permits to get easily localized strings about the UI.
* @author silveryocha
*/
public class LocalizedUIBundle extends BundleLocator {
private static final LocalizedUIBundle MY_BUNDLE = new LocalizedUIBundle("multilang.lanterna-ui");
public static String get(String key, String... parameters) {
return get(Locale.getDefault(), key, parameters);
}
public static String get(Locale locale, String key, String... parameters) {
return MY_BUNDLE.getBundleKeyValue(locale, key, (Object[])parameters);
}
private LocalizedUIBundle(final String bundleName) {
super(bundleName);
}
}
| lgpl-3.0 |
isa-group/FaMA | reasoner_choco_3/src/co/icesi/i2t/Choco3Reasoner/simple/questions/Choco3ProductsQuestion.java | 6510 | /**
* This file is part of FaMaTS.
*
* FaMaTS 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.
*
* FaMaTS 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 FaMaTS. If not, see <http://www.gnu.org/licenses/>.
*/
package co.icesi.i2t.Choco3Reasoner.simple.questions;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import solver.Solver;
import solver.search.solution.AllSolutionsRecorder;
import solver.search.solution.ISolutionRecorder;
import solver.search.solution.Solution;
import solver.variables.IntVar;
import solver.variables.Variable;
import co.icesi.i2t.Choco3Reasoner.Choco3PerformanceResult;
import co.icesi.i2t.Choco3Reasoner.simple.Choco3Question;
import co.icesi.i2t.Choco3Reasoner.simple.Choco3Reasoner;
import es.us.isa.FAMA.Benchmarking.PerformanceResult;
import es.us.isa.FAMA.Reasoner.Reasoner;
import es.us.isa.FAMA.Reasoner.questions.ProductsQuestion;
import es.us.isa.FAMA.models.featureModel.GenericFeature;
import es.us.isa.FAMA.models.featureModel.Product;
/**
* Implementation to solve the all products question using the Choco 3 reasoner.
* This operation calculates all valid products that can be
* derived from the feature model with the specified constraints.
*
* Asking this question may cause a memory explosion, thus the reasoner may fail.
*
* @author Andrés Paz, I2T Research Group, Icesi University, Cali - Colombia
* @see es.us.isa.ChocoReasoner.questions.ChocoProductsQuestion Choco 2 implementation for the all products question.
* @version 1.0, June 2014
*/
public class Choco3ProductsQuestion extends Choco3Question implements
ProductsQuestion {
/**
* The products that can be derived with the imposed constraints, if found.
* If no product is found, the list will be empty.
*/
private List<Product> products;
/**
* Returns the number of products found.
*
* @return The number of products found
*
* @see es.us.isa.FAMA.Reasoner.questions.NumberOfProductsQuestion#getNumberOfProducts()
*/
public long getNumberOfProducts() {
if (this.products != null) {
return this.products.size();
}
return 0;
}
/**
* Returns a collection of products that can be derived with the imposed constraints, if found.
* Returns an empty collection if no product was found.
*
* @return A collection of products that can be derived with the imposed constraints, if found.
*
* @see es.us.isa.FAMA.Reasoner.questions.OneProductQuestion#getProduct()
*/
public Collection<Product> getAllProducts() {
return this.products;
}
/* (non-Javadoc)
* @see co.icesi.i2t.Choco3Reasoner.simple.Choco3Question#preAnswer(es.us.isa.FAMA.Reasoner.Reasoner)
*/
@Override
public void preAnswer(Reasoner reasoner) {
this.products = new LinkedList<Product>();
}
/* (non-Javadoc)
* @see co.icesi.i2t.Choco3Reasoner.simple.Choco3Question#answer(es.us.isa.FAMA.Reasoner.Reasoner)
*/
@Override
public PerformanceResult answer(Reasoner reasoner) {
// Cast the reasoner into a Choco 3 Reasoner instance
Choco3Reasoner choco3Reasoner = (Choco3Reasoner) reasoner;
// Get the solver
Solver solver = choco3Reasoner.getSolver();
// Set the heuristic or strategy to be used by the reasoner
// TODO Set heuristic MinDomain
// Use a solution recorder that records all solutions that are found.
// Asking this question may cause a memory explosion, thus the reasoner may fail.
ISolutionRecorder defaultSolutionRecorder = solver.getSolutionRecorder();
solver.set(new AllSolutionsRecorder(solver));
// Reset the search so the CSP can be solved again, if it was previously solved.
solver.getSearchLoop().reset();
// The findAllSolutions method attempts to find all possible solutions to the CSP
// and it returns the number of solutions obtained
long solutionsFound = solver.findAllSolutions();
if (solutionsFound > 0) {
// If at least one solution is found
// Solutions cannot be retrieved directly from the solver
// They are stored by a solution recorder
// Since we're interested in all the solutions we retrieve all solutions
List<Solution> solutions = solver.getSolutionRecorder().getSolutions();
for (Solution solution : solutions) {
// Find the features that will be present in the product represented by the solution
Product product = new Product();
for (int i = 0; i < solver.getNbVars(); i++) {
Variable variable = solver.getVar(i);
// If the current variable is of type IntVar
// We're interested in this type of variables since they are the ones
// that represent features in the CSP
if (variable instanceof IntVar) {
// Check if the variable's value is greater than zero
// This means the feature represented by this variable was selected to be
// present in the product found
if (solution.getIntVal((IntVar) variable) > 0) {
// Search for the feature in the reasoner
GenericFeature feature = choco3Reasoner.searchFeatureByName(variable.getName());
if (feature != null) {
// If the feature was found
// Add the feature to the product
product.addFeature(feature);
}
}
}
}
// Add the product to the list of products if the product
// is not already in the list
if (!this.products.contains(product)) {
this.products.add(product);
}
}
}
// Create and return performance result
Choco3PerformanceResult performanceResult = new Choco3PerformanceResult();
performanceResult.addFields(solver);
// Reset to the default solution recorder.
solver.set(defaultSolutionRecorder);
return performanceResult;
}
/* (non-Javadoc)
* @see co.icesi.i2t.Choco3Reasoner.simple.Choco3Question#postAnswer(es.us.isa.FAMA.Reasoner.Reasoner)
*/
@Override
public void postAnswer(Reasoner reasoner) {
// Not needed
}
}
| lgpl-3.0 |
hubinix/kamike.divide | kamikeDivide/src/com/kamike/divide/KamiSQL.java | 5142 | /*
* 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.kamike.divide;
import com.kamike.db.generic.GenericColumn;
import com.kamike.db.generic.GenericType;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author THiNk
*/
public abstract class KamiSQL implements AutoCloseable {
protected KamiStatement kamiStatement;
protected String tableName;
protected static final String prefix = "__prefix_kami_table_";
protected int waitSecond;
public abstract ArrayList<KamiTable> findTables();
/**
* @return the waitSecond
*/
public int getWaitSecond() {
return waitSecond;
}
/**
* @param waitSecond the waitSecond to set
*/
public void setWaitSecond(int waitSecond) {
this.waitSecond = waitSecond;
}
public KamiSQL(String tableName) {
this.tableName = tableName;
kamiStatement = new KamiStatement(tableName);
this.waitSecond = 60;
}
public KamiSQL() {
}
public void init() {
kamiStatement = new KamiStatement(tableName);
this.waitSecond = 60;
}
public void executeUpdate() {
try {
//查询在哪个库里面的哪个表
long start = System.nanoTime();
ArrayList<KamiTable> tables = this.findTables();
ExecutorService exec = Executors.newCachedThreadPool();
CountDownLatch doneSignal = new CountDownLatch(tables.size());
for (KamiTable t : tables) {
KamiStatement cur = kamiStatement.clone();
cur.setRealTableName(t.getRealName());
cur.setId(t.getDatabaseId());
KamiExecute ce = new KamiExecute(cur, doneSignal);
exec.execute(ce);
}
doneSignal.await(waitSecond, TimeUnit.SECONDS);
exec.shutdownNow();
long elapsed = start - System.nanoTime();
//assertTrue(elapsed <= 300l && elapsed < 500l);
} catch (InterruptedException ex) {
Logger.getLogger(KamiSQL.class.getName()).log(Level.SEVERE, null, ex);
}
}
public String TableName() {
return kamiStatement.getMarkedTableName();
}
@Override
public void close() throws Exception {
kamiStatement.close();
}
/**
* 如果忘记关闭连接池,那么对象自动销毁的时候,也需要归还链接
*/
@Override
public void finalize() {
try {
super.finalize();
} catch (Throwable ex) {
Logger.getLogger(KamiSQL.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void prepareStatement(String sql, int i, int i1) throws SQLException {
kamiStatement.setSql(sql);
kamiStatement.setResultSetOption1(i);
kamiStatement.setResultSetOption2(i1);
}
public void prepareStatement(String sql) throws SQLException {
kamiStatement.setSql(sql);
kamiStatement.setResultSetOption1(ResultSet.TYPE_SCROLL_SENSITIVE);
kamiStatement.setResultSetOption2(ResultSet.CONCUR_UPDATABLE);
}
public void setString(int i, String value) {
GenericColumn column = new GenericColumn();
column.setStrValue(value);
column.setType(GenericType.String);
kamiStatement.getColumns().add(i-1, column);
}
public void setInt(int i, int value) {
GenericColumn column = new GenericColumn();
column.setIntValue(value);
column.setType(GenericType.Int);
kamiStatement.getColumns().add(i-1, column);
}
public void setColumn(int i, GenericColumn column) {
kamiStatement.getColumns().add(i-1, column);
}
public void setTimestamp(int i, Timestamp value) {
GenericColumn column = new GenericColumn();
column.setTimestampValue(value);
column.setType(GenericType.Timestamp);
kamiStatement.getColumns().add(i-1, column);
}
public void setLong(int i, long value) {
GenericColumn column = new GenericColumn();
column.setLongValue(value);
column.setType(GenericType.Long);
kamiStatement.getColumns().add(i-1, column);
}
public void setBoolean(int i, boolean value) {
GenericColumn column = new GenericColumn();
column.setBooleanValue(value);
column.setType(GenericType.Boolean);
kamiStatement.getColumns().add(i-1, column);
}
public void setDouble(int i, double value) {
GenericColumn column = new GenericColumn();
column.setDoubleValue(value);
column.setType(GenericType.Double);
kamiStatement.getColumns().add(i-1, column);
}
}
| lgpl-3.0 |
OldShatterhand77/Portofino | elements/src/main/java/com/manydesigns/elements/Mode.java | 4374 | /*
* Copyright (C) 2005-2015 ManyDesigns srl. All rights reserved.
* http://www.manydesigns.com/
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package com.manydesigns.elements;
import org.apache.commons.lang.builder.ToStringBuilder;
/*
* @author Paolo Predonzani - paolo.predonzani@manydesigns.com
* @author Angelo Lupo - angelo.lupo@manydesigns.com
* @author Giampiero Granatella - giampiero.granatella@manydesigns.com
* @author Alessio Stalla - alessio.stalla@manydesigns.com
*/
public enum Mode {
/**
* create forms: regular inputs
*/
CREATE(8, "CREATE"),
/**
* update forms: regular inputs
*/
EDIT(0, "EDIT"),
/**
* bulk update forms: regular inputs
*/
BULK_EDIT(16, "BULK_EDIT"),
/**
* create preview/confirmation pages: plain text values + hidden inputs
*/
CREATE_PREVIEW(9, "CREATE_PREVIEW"),
/**
* update preview/confirmation pages: plain text values + hidden inputs
*/
PREVIEW(1, "PREVIEW"),
/**
* read/view pages: plain text values, no inputs
*/
VIEW(2, "VIEW"),
/**
* create - no visual display, only hidden inputs.
*/
CREATE_HIDDEN(11, "CREATE_HIDDEN"),
/**
* update - no visual display, only hidden inputs.
*/
HIDDEN(3, "HIDDEN");
private final static int BASE_MODE_MASK = 3;
private final static int CREATE_MASK = 8;
private final static int BULK_MASK = 16;
private final boolean create;
private final boolean bulk;
private final boolean edit;
private final boolean preview;
private final boolean view;
private final boolean hidden;
private final String name;
Mode(int value, String name) {
int baseMode = value & BASE_MODE_MASK;
switch(baseMode) {
case 0:
edit = true;
preview = false;
view = false;
hidden = false;
break;
case 1:
edit = false;
preview = true;
view = false;
hidden = false;
break;
case 2:
edit = false;
preview = false;
view = true;
hidden = false;
break;
case 3:
edit = false;
preview = false;
view = false;
hidden = true;
break;
default:
throw new InternalError("Unrecognized mode: " + value);
}
create = (value & CREATE_MASK) != 0;
bulk = (value & BULK_MASK) != 0;
this.name = name;
}
public boolean isCreate() {
return create;
}
public boolean isBulk() {
return bulk;
}
public boolean isEdit() {
return edit;
}
public boolean isPreview() {
return preview;
}
public boolean isView() {
return view;
}
public boolean isHidden() {
return hidden;
}
public boolean isView(boolean insertable, boolean updatable) {
return view
|| (!hidden && !create && !updatable)
|| (!hidden && create && !insertable)
;
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("name", name)
.append("create", create)
.append("edit", edit)
.append("preview", preview)
.append("view", view)
.append("hidden", hidden)
.toString();
}
}
| lgpl-3.0 |
mhcrnl/tools | Tools/src/tools/swing/AutoCompleteComboBox.java | 5830 | package tools.swing;
//Auto complete or search in a JComboBox
import java.awt.Component;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.TreeSet;
import java.util.Vector;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.plaf.basic.BasicComboBoxEditor;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
public class AutoCompleteComboBox extends JComboBox
{
private static final Locale[] INSTALLED_LOCALES = Locale.getAvailableLocales();
private ComboBoxModel model = null;
public static void main(String[] args)
{
JFrame f = new JFrame("AutoCompleteComboBox");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
AutoCompleteComboBox box = new AutoCompleteComboBox(INSTALLED_LOCALES, false);
f.getContentPane().add(box);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
/**
* Constructor for AutoCompleteComboBox -
* The Default Model is a TreeSet which is alphabetically sorted and doesnt allow duplicates.
* @param items
*/
public AutoCompleteComboBox(Object[] items, boolean caseSensitive)
{
super(items);
model = new ComboBoxModel(items);
setModel(model);
setEditable(true);
setEditor(new AutoCompleteEditor(this, caseSensitive));
}
/**
* Constructor for AutoCompleteComboBox -
* The Default Model is a TreeSet which is alphabetically sorted and doesnt allow
* duplicates.
* @param items
*/
public AutoCompleteComboBox(Vector<Object> items, boolean caseSensitive)
{
super(items);
model = new ComboBoxModel(items);
setModel(model);
setEditable(true);
setEditor(new AutoCompleteEditor(this, caseSensitive));
}
/**
* Constructor for AutoCompleteComboBox -
* This constructor uses JComboBox's Default Model which is a Vector.
* @param caseSensitive
*/
public AutoCompleteComboBox(boolean caseSensitive)
{
super();
setEditable(true);
setEditor(new AutoCompleteEditor(this, caseSensitive));
}
/**
* ComboBoxModel.java
*/
public class ComboBoxModel extends DefaultComboBoxModel
{
/**
* The TreeSet which holds the combobox's data (ordered no duplicates)
*/
private TreeSet<Object> values = null;
public ComboBoxModel(List<Object> items)
{
super();
this.values = new TreeSet<Object>();
int i, c;
for (i = 0, c = items.size(); i < c; i++)
{
values.add(items.get(i).toString());
}
Iterator<Object> it = values.iterator();
while (it.hasNext())
super.addElement(it.next().toString());
}
public ComboBoxModel(final Object items[])
{
this(Arrays.asList(items));
}
}
/**
* AutoCompleteEditor.java
*/
public class AutoCompleteEditor extends BasicComboBoxEditor
{
private JTextField autoCompleteEditor = null;
public AutoCompleteEditor(JComboBox combo, boolean caseSensitive)
{
super();
autoCompleteEditor = new AutoCompleteEditorComponent(combo, caseSensitive);
}
/**
* overrides BasicComboBox's getEditorComponent to return custom TextField
(AutoCompleteEditorComponent)
*/
public Component getEditorComponent()
{
return autoCompleteEditor;
}
}
/**
* AutoCompleteEditorComponent.java
*/
public class AutoCompleteEditorComponent extends JTextField
{
JComboBox combo = null;
boolean caseSensitive = false;
public AutoCompleteEditorComponent(JComboBox combo, boolean caseSensitive)
{
super();
this.combo = combo;
this.caseSensitive = caseSensitive;
}
public void setBorder(Border b)
{
// no border
}
/**
* overwritten to return custom PlainDocument which does the work
*/
protected Document createDefaultModel()
{
return new PlainDocument()
{
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
{
if (str == null || str.length() == 0)
return;
int size = combo.getItemCount();
String text = getText(0, getLength());
for (int i = 0; i < size; i++)
{
String item = combo.getItemAt(i).toString();
if (getLength() + str.length() > item.length())
continue;
if (!caseSensitive)
{
if ((text + str).equalsIgnoreCase(item))
{
combo.setSelectedIndex(i);
//if (!combo.isPopupVisible())
// combo.setPopupVisible(true);
super.remove(0, getLength());
super.insertString(0, item, a);
return;
}
else if (item.substring(0, getLength() + str.length()).equalsIgnoreCase(text + str))
{
combo.setSelectedIndex(i);
if (!combo.isPopupVisible())
combo.setPopupVisible(true);
super.remove(0, getLength());
super.insertString(0, item, a);
return;
}
}
else if (caseSensitive)
{
if ((text + str).equals(item))
{
combo.setSelectedIndex(i);
if (!combo.isPopupVisible())
combo.setPopupVisible(true);
super.remove(0, getLength());
super.insertString(0, item, a);
return;
}
else if (item.substring(0, getLength() + str.length()).equals(text + str))
{
combo.setSelectedIndex(i);
if (!combo.isPopupVisible())
combo.setPopupVisible(true);
super.remove(0, getLength());
super.insertString(0, item, a);
return;
}
}
}
}
};
}
}
}
| lgpl-3.0 |
DJmaxZPL4Y/Photon-API | src/main/java/org/mcphoton/entity/misc/AreaEffectCloud.java | 1784 | /*
* Copyright (c) 2016 MCPhoton <http://mcphoton.org> and contributors.
*
* This file is part of the Photon API <https://github.com/mcphoton/Photon-API>.
*
* The Photon API 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.
*
* The Photon API 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.mcphoton.entity.misc;
import org.mcphoton.entity.Entity;
import org.mcphoton.entity.projectile.ThrownPotion;
/**
* A cloud created by a lingering (persistent) Potion.
*
* @author DJmaxZPLAY
* @author TheElectronWill
*/
public interface AreaEffectCloud extends Entity {
/**
* @return the cloud's radius.
*/
float getRadius();
/**
* Sets the cloud's radius.
*
* @param radius the cloud's radius.
*/
void setRadius(float radius);
/**
* @return the duration (in ticks) which the cloud will exist for.
*/
int getDuration();
/**
* Sets the duration (in ticks) which the cloud will exist for.
*
* @param duration the ticks which the cloud will exist for.
*/
void setDuration(int duration);
/**
* @return the lingering Potion that created this cloud.
*/
ThrownPotion getSource();
/**
* @param source the lingering potion that created this cloud.
*/
void setSource(ThrownPotion source);
}
| lgpl-3.0 |
HATB0T/RuneCraftery | forge/mcp/src/minecraft/net/minecraft/world/gen/feature/WorldGenGlowStone1.java | 2498 | package net.minecraft.world.gen.feature;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.world.World;
public class WorldGenGlowStone1 extends WorldGenerator
{
public boolean generate(World par1World, Random par2Random, int par3, int par4, int par5)
{
if (!par1World.isAirBlock(par3, par4, par5))
{
return false;
}
else if (par1World.getBlockId(par3, par4 + 1, par5) != Block.netherrack.blockID)
{
return false;
}
else
{
par1World.setBlock(par3, par4, par5, Block.glowStone.blockID, 0, 2);
for (int l = 0; l < 1500; ++l)
{
int i1 = par3 + par2Random.nextInt(8) - par2Random.nextInt(8);
int j1 = par4 - par2Random.nextInt(12);
int k1 = par5 + par2Random.nextInt(8) - par2Random.nextInt(8);
if (par1World.getBlockId(i1, j1, k1) == 0)
{
int l1 = 0;
for (int i2 = 0; i2 < 6; ++i2)
{
int j2 = 0;
if (i2 == 0)
{
j2 = par1World.getBlockId(i1 - 1, j1, k1);
}
if (i2 == 1)
{
j2 = par1World.getBlockId(i1 + 1, j1, k1);
}
if (i2 == 2)
{
j2 = par1World.getBlockId(i1, j1 - 1, k1);
}
if (i2 == 3)
{
j2 = par1World.getBlockId(i1, j1 + 1, k1);
}
if (i2 == 4)
{
j2 = par1World.getBlockId(i1, j1, k1 - 1);
}
if (i2 == 5)
{
j2 = par1World.getBlockId(i1, j1, k1 + 1);
}
if (j2 == Block.glowStone.blockID)
{
++l1;
}
}
if (l1 == 1)
{
par1World.setBlock(i1, j1, k1, Block.glowStone.blockID, 0, 2);
}
}
}
return true;
}
}
}
| lgpl-3.0 |
mabe02/jdbw | src/main/java/com/googlecode/jdbw/server/h2/H2DatabaseServer.java | 3399 | /*
* This file is part of jdbw (http://code.google.com/p/jdbw/).
*
* jdbw 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) 2007-2012 Martin Berglund
*/
package com.googlecode.jdbw.server.h2;
import com.googlecode.jdbw.DataSourceFactory;
import com.googlecode.jdbw.DatabaseConnection;
import com.googlecode.jdbw.DatabaseServerType;
import com.googlecode.jdbw.server.AbstractDatabaseServer;
import com.googlecode.jdbw.util.OneSharedConnectionDataSource;
/**
* Base class for all H2 server types
* @see com.googlecode.jdbw.server.h2.H2FileBasedServer
* @see com.googlecode.jdbw.server.h2.H2InMemoryServer
* @see com.googlecode.jdbw.server.h2.H2NetworkServer
* @author Martin Berglund
*/
public abstract class H2DatabaseServer extends AbstractDatabaseServer<H2DatabaseConnectionFactory> {
private final H2ServerType serverType;
private final boolean allowMultipleConnections;
protected H2DatabaseServer(H2ServerType serverType, boolean allowMultipleConnections) {
super(new H2JDBCDriverDescriptor());
this.serverType = serverType;
this.allowMultipleConnections = allowMultipleConnections;
}
/**
* Creates a new DatabaseConnection to this H2 server that is backed by a single connection
* @return DatabaseConnection established to this H2 server
*/
public DatabaseConnection connect() {
return connect(new OneSharedConnectionDataSource.Factory());
}
/**
* Creates a new DatabaseConnection to this H2 server that is backed by a DataSource created by the
* DataSourceFactory parameter supplied. If you need to tweak the connection parameters further, please use the
* newConnectionFactory(..) method instead.
* @param dataSourceFactory Factory implementation that will create the DataSource that backs the DatabaseConnection
* that is to be created
* @return DatabaseConnection established to this H2 server
*/
public DatabaseConnection connect(DataSourceFactory dataSourceFactory) {
if(!isAllowMultipleConnections() && !(dataSourceFactory instanceof OneSharedConnectionDataSource.Factory)) {
throw new IllegalArgumentException("You can't connect to a " + this + " with multiple connections");
}
return newConnectionFactory().connect(dataSourceFactory);
}
@Override
public DatabaseServerType getServerType() {
return serverType;
}
/**
* Can we have multiple concurrent connections to this database server?
* @return {@code true} if we can have multiple open connections
*/
boolean isAllowMultipleConnections() {
return allowMultipleConnections;
}
abstract String getJDBCUrl(H2JDBCDriverDescriptor driverDescriptor);
}
| lgpl-3.0 |
daniel-he/community-edition | projects/repository/source/java/org/alfresco/repo/transfer/Transfer.java | 2608 | /*
* Copyright (C) 2005-2010 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.repo.transfer;
import org.alfresco.service.cmr.transfer.TransferTarget;
import org.alfresco.service.cmr.transfer.TransferVersion;
/**
* Information about a transfer which is in progress.
*
* @author Mark Rogers
*/
public class Transfer
{
private String transferId;
private TransferTarget transferTarget;
private TransferVersion toVersion;
public void setTransferId(String transferId)
{
this.transferId = transferId;
}
public String getTransferId()
{
return transferId;
}
// may also have capabilities of the remote system here (for when we are
// transfering accross versions)
public boolean equals(Object obj)
{
if (obj == null)
{
return false;
}
else if (this == obj)
{
return true;
}
else if (obj instanceof Transfer == false)
{
return false;
}
Transfer that = (Transfer) obj;
return (this.transferId.equals(that.getTransferId()));
}
public int hashCode()
{
return transferId.hashCode();
}
/**
* @param target
*/
public void setTransferTarget(TransferTarget target)
{
this.transferTarget = target;
}
/**
* @return the transferTarget
*/
public TransferTarget getTransferTarget()
{
return transferTarget;
}
public String toString()
{
return "TransferId" + transferId + ", target:" + transferTarget ;
}
public void setToVersion(TransferVersion toVersion)
{
this.toVersion = toVersion;
}
public TransferVersion getToVersion()
{
return toVersion;
}
}
| lgpl-3.0 |
kaspersorensen/DataCleaner | api/src/main/java/org/datacleaner/connection/Datastore.java | 2211 | /**
* DataCleaner (community edition)
* Copyright (C) 2014 Free Software Foundation, Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.datacleaner.connection;
import java.io.Serializable;
import org.apache.metamodel.util.HasName;
/**
* Defines a datastore from which data can be queried.
*
* Datastores are kept in the {@link DatastoreCatalog}.
*/
public interface Datastore extends Serializable, HasName {
/**
* Gets the name of the datastore
*
* @return a String name
*/
@Override
String getName();
/**
* Gets an optional description of the datastore.
*
* @return a String description, or null if no description is available.
*/
String getDescription();
/**
* Sets the description of the datastore.
*
* @param description
* the new description of the datastore.
*/
void setDescription(String description);
/**
* Opens up the connection to the datastore. If the datastore is already
* opened, most times this method will simply share the existing connection.
*
* @see DatastoreConnection
*
* @return a {@link DatastoreConnection} to use for querying and exploring
* the datastore.
*/
DatastoreConnection openConnection();
/**
* Gets the performance characteristics of this datastore.
*
* @return the performance characteristics of this datastore.
*/
PerformanceCharacteristics getPerformanceCharacteristics();
}
| lgpl-3.0 |
teryk/sonarqube | plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/CoverageWidget.java | 1234 | /*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* SonarQube is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.plugins.core.widgets;
import org.sonar.api.web.UserRole;
import org.sonar.api.web.WidgetCategory;
@WidgetCategory("Tests")
@UserRole(UserRole.USER)
public class CoverageWidget extends CoreWidget {
public CoverageWidget() {
super("code_coverage", "Code coverage", "/org/sonar/plugins/core/widgets/coverage.html.erb");
}
}
| lgpl-3.0 |
danielmitterdorfer/elasticsearch | core/src/main/java/org/elasticsearch/search/aggregations/bucket/significant/InternalSignificantTerms.java | 8703 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.search.aggregations.bucket.significant;
import org.elasticsearch.common.io.stream.Streamable;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.search.DocValueFormat;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.InternalAggregation;
import org.elasticsearch.search.aggregations.InternalAggregations;
import org.elasticsearch.search.aggregations.InternalMultiBucketAggregation;
import org.elasticsearch.search.aggregations.bucket.significant.heuristics.SignificanceHeuristic;
import org.elasticsearch.search.aggregations.pipeline.PipelineAggregator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
*
*/
public abstract class InternalSignificantTerms<A extends InternalSignificantTerms, B extends InternalSignificantTerms.Bucket> extends
InternalMultiBucketAggregation<A, B> implements SignificantTerms, ToXContent, Streamable {
protected SignificanceHeuristic significanceHeuristic;
protected int requiredSize;
protected long minDocCount;
protected List<? extends Bucket> buckets;
protected Map<String, Bucket> bucketMap;
protected long subsetSize;
protected long supersetSize;
protected InternalSignificantTerms() {} // for serialization
@SuppressWarnings("PMD.ConstructorCallsOverridableMethod")
public abstract static class Bucket extends SignificantTerms.Bucket {
long bucketOrd;
protected InternalAggregations aggregations;
double score;
final transient DocValueFormat format;
protected Bucket(long subsetSize, long supersetSize, DocValueFormat format) {
// for serialization
super(subsetSize, supersetSize);
this.format = format;
}
protected Bucket(long subsetDf, long subsetSize, long supersetDf, long supersetSize,
InternalAggregations aggregations, DocValueFormat format) {
super(subsetDf, subsetSize, supersetDf, supersetSize);
this.aggregations = aggregations;
this.format = format;
}
@Override
public long getSubsetDf() {
return subsetDf;
}
@Override
public long getSupersetDf() {
return supersetDf;
}
@Override
public long getSupersetSize() {
return supersetSize;
}
@Override
public long getSubsetSize() {
return subsetSize;
}
public void updateScore(SignificanceHeuristic significanceHeuristic) {
score = significanceHeuristic.getScore(subsetDf, subsetSize, supersetDf, supersetSize);
}
@Override
public long getDocCount() {
return subsetDf;
}
@Override
public Aggregations getAggregations() {
return aggregations;
}
public Bucket reduce(List<? extends Bucket> buckets, ReduceContext context) {
long subsetDf = 0;
long supersetDf = 0;
List<InternalAggregations> aggregationsList = new ArrayList<>(buckets.size());
for (Bucket bucket : buckets) {
subsetDf += bucket.subsetDf;
supersetDf += bucket.supersetDf;
aggregationsList.add(bucket.aggregations);
}
InternalAggregations aggs = InternalAggregations.reduce(aggregationsList, context);
return newBucket(subsetDf, subsetSize, supersetDf, supersetSize, aggs);
}
abstract Bucket newBucket(long subsetDf, long subsetSize, long supersetDf, long supersetSize, InternalAggregations aggregations);
@Override
public double getSignificanceScore() {
return score;
}
}
protected DocValueFormat format;
protected InternalSignificantTerms(long subsetSize, long supersetSize, String name, DocValueFormat format, int requiredSize,
long minDocCount, SignificanceHeuristic significanceHeuristic, List<? extends Bucket> buckets,
List<PipelineAggregator> pipelineAggregators, Map<String, Object> metaData) {
super(name, pipelineAggregators, metaData);
this.requiredSize = requiredSize;
this.minDocCount = minDocCount;
this.buckets = buckets;
this.subsetSize = subsetSize;
this.supersetSize = supersetSize;
this.significanceHeuristic = significanceHeuristic;
this.format = Objects.requireNonNull(format);
}
@Override
public Iterator<SignificantTerms.Bucket> iterator() {
Object o = buckets.iterator();
return (Iterator<SignificantTerms.Bucket>) o;
}
@Override
public List<SignificantTerms.Bucket> getBuckets() {
Object o = buckets;
return (List<SignificantTerms.Bucket>) o;
}
@Override
public SignificantTerms.Bucket getBucketByKey(String term) {
if (bucketMap == null) {
bucketMap = new HashMap<>(buckets.size());
for (Bucket bucket : buckets) {
bucketMap.put(bucket.getKeyAsString(), bucket);
}
}
return bucketMap.get(term);
}
@Override
public InternalAggregation doReduce(List<InternalAggregation> aggregations, ReduceContext reduceContext) {
long globalSubsetSize = 0;
long globalSupersetSize = 0;
// Compute the overall result set size and the corpus size using the
// top-level Aggregations from each shard
for (InternalAggregation aggregation : aggregations) {
InternalSignificantTerms<A, B> terms = (InternalSignificantTerms<A, B>) aggregation;
globalSubsetSize += terms.subsetSize;
globalSupersetSize += terms.supersetSize;
}
Map<String, List<InternalSignificantTerms.Bucket>> buckets = new HashMap<>();
for (InternalAggregation aggregation : aggregations) {
InternalSignificantTerms<A, B> terms = (InternalSignificantTerms<A, B>) aggregation;
for (Bucket bucket : terms.buckets) {
List<Bucket> existingBuckets = buckets.get(bucket.getKeyAsString());
if (existingBuckets == null) {
existingBuckets = new ArrayList<>(aggregations.size());
buckets.put(bucket.getKeyAsString(), existingBuckets);
}
// Adjust the buckets with the global stats representing the
// total size of the pots from which the stats are drawn
existingBuckets.add(bucket.newBucket(bucket.getSubsetDf(), globalSubsetSize, bucket.getSupersetDf(), globalSupersetSize, bucket.aggregations));
}
}
significanceHeuristic.initialize(reduceContext);
final int size = Math.min(requiredSize, buckets.size());
BucketSignificancePriorityQueue ordered = new BucketSignificancePriorityQueue(size);
for (Map.Entry<String, List<Bucket>> entry : buckets.entrySet()) {
List<Bucket> sameTermBuckets = entry.getValue();
final Bucket b = sameTermBuckets.get(0).reduce(sameTermBuckets, reduceContext);
b.updateScore(significanceHeuristic);
if ((b.score > 0) && (b.subsetDf >= minDocCount)) {
ordered.insertWithOverflow(b);
}
}
Bucket[] list = new Bucket[ordered.size()];
for (int i = ordered.size() - 1; i >= 0; i--) {
list[i] = (Bucket) ordered.pop();
}
return create(globalSubsetSize, globalSupersetSize, Arrays.asList(list), this);
}
protected abstract A create(long subsetSize, long supersetSize, List<InternalSignificantTerms.Bucket> buckets,
InternalSignificantTerms prototype);
}
| apache-2.0 |
apache/geronimo-yoko | yoko-osgi/src/main/java/org/apache/yoko/osgi/locator/activator/AbstractBundleActivator.java | 3209 | package org.apache.yoko.osgi.locator.activator;
import java.util.ArrayList;
import java.util.List;
import org.apache.yoko.osgi.locator.BundleProviderLoader;
import org.apache.yoko.osgi.locator.Register;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;
public abstract class AbstractBundleActivator implements BundleActivator {
public static class Info {
final String id;
final String className;
final int priority;
public Info(String id, String className, int priority) {
super();
this.id = id;
this.className = className;
this.priority = priority;
}
}
private final Info[] providerInfo;
private final Info[] serviceInfo;
private ServiceTracker<Register, Register> tracker;
private BundleContext context;
private boolean registered;
private final List<BundleProviderLoader> providerLoaders = new ArrayList<BundleProviderLoader>();
private final List<BundleProviderLoader> serviceLoaders = new ArrayList<BundleProviderLoader>();
public AbstractBundleActivator(Info[] providerInfo, Info[] serviceInfo) {
this.providerInfo = providerInfo;
this.serviceInfo = serviceInfo;
}
public void start(final BundleContext context) throws Exception {
this.context = context;
tracker = new ServiceTracker<Register, Register>(context, Register.class, new ServiceTrackerCustomizer<Register, Register>() {
public Register addingService(ServiceReference<Register> reference) {
Register register = context.getService(reference);
register(register);
return register;
}
public void modifiedService(ServiceReference<Register> reference,
Register service) {
// TODO Auto-generated method stub
}
public void removedService(ServiceReference<Register> reference,
Register service) {
// TODO Auto-generated method stub
}
});
tracker.open();
Register register = tracker.getService();
if (register != null) {
register(register);
}
}
private synchronized void register(Register register) {
if (!registered) {
registered = true;
Bundle bundle = context.getBundle();
for (Info classInfo: providerInfo) {
BundleProviderLoader loader = new BundleProviderLoader(classInfo.id, classInfo.className, bundle, classInfo.priority);
providerLoaders.add(loader);
register.registerProvider(loader);
}
for (Info classInfo: serviceInfo) {
BundleProviderLoader loader = new BundleProviderLoader(classInfo.id, classInfo.className, bundle, classInfo.priority);
serviceLoaders.add(loader);
register.registerService(loader);
}
}
}
public void stop(BundleContext context) throws Exception {
Register register = tracker.getService();
tracker.close();
synchronized (this) {
if (register != null && registered) {
for (BundleProviderLoader loader: providerLoaders) {
register.unregisterProvider(loader);
}
for (BundleProviderLoader loader: serviceLoaders) {
register.unregisterService(loader);
}
}
}
}
}
| apache-2.0 |
glubtech/ftpswrap | src/com/glub/secureftp/wrapper/config/Setup.java | 1935 |
//*****************************************************************************
//*
//* (c) Copyright 2005. Glub Tech, Incorporated. All Rights Reserved.
//*
//* $Id: Setup.java 39 2009-05-11 22:50:09Z gary $
//*
//*****************************************************************************
package com.glub.secureftp.wrapper.config;
import com.glub.secureftp.wrapper.*;
import java.io.*;
import java.util.*;
public class Setup {
private BufferedReader stdin = null;
private static PrintStream out = null;
private static CommandDispatcher commandDispatcher = new CommandDispatcher();
public static void main( String[] args ) {
new Setup( args );
}
public Setup( String[] args ) {
out = System.out;
out.println(SecureFTPWrapper.PROGRAM_NAME + " v" + SecureFTPWrapper.VERSION);
out.println(SecureFTPWrapper.COPYRIGHT);
out.println("");
stdin = new BufferedReader(new InputStreamReader(System.in));
CommandParser cp = new CommandParser(stdin, out);
do {
printOptions();
out.print("Please enter a choice (0 - " +
(CommandParser.getCommands().length - 1) + "): ");
} while ( cp.parse() );
}
public static void printOptions() {
Command c[] = CommandParser.getCommands();
for ( int i = 0; i < c.length; i++ ) {
out.println(c[i].getCommandName() + ". " + c[i].getMessage());
}
out.println("");
}
public static CommandDispatcher getCommandDispatcher() {
return commandDispatcher;
}
public static List getServerList() {
return ConfigurationManager.getInstance().getConfiguration();
}
public static void addConfiguration( ServerInfo info ) {
ConfigurationManager.getInstance().addConfiguration( info );
updateConfiguration();
}
public static void updateConfiguration() {
try {
ConfigurationManager.getInstance().writeConfiguration();
}
catch ( IOException ioe ) {}
}
}
| apache-2.0 |
Novartis/EQP-QM | java/source/fastq-source/FastqEntry.java | 6011 | /**File: FastqEntry
Original Author: Sven Schuierer
Date: 13/01/2012
Classes : FastqEntry
$Author: Sven Schuierer $
Copyright 2015 Novartis Institutes for BioMedical Research
Inc.Licensed under the Apache License, Version 2.0 (the "License"); you
may not use this file except in compliance with the License. You may
obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
*/
import java.io.*;
import java.util.*;
/**********************************************************************************
*
* Class FastqEntry
*
**********************************************************************************/
public class FastqEntry {
private static final int debugLevel = 0;
private String fullReadId;
private String readId;
private String fragmentId;
private String sequence;
private String qualities;
private boolean isFastaEntry = false;
private int readIndex;
private int readMultiplicity = 1;
FastqEntry (BufferedReader reader, boolean extractReadMultiplicities) throws IOException {
fullReadId = reader.readLine ();
if (fullReadId == null) {
throw new IOException ("Fastq input complete.");
}
if (! fullReadId.startsWith ("@")) {
if (fullReadId.startsWith (">")) {
isFastaEntry = true;
} else {
throw new IOException ("Read id not found in ." + reader.toString () + " instead: " + fullReadId);
}
}
int spaceIndex = fullReadId.indexOf(" ");
if (spaceIndex != -1) {
readId = fullReadId.substring(0, spaceIndex);
if (extractReadMultiplicities) {
try {
readMultiplicity = Integer.parseInt(fullReadId.substring(spaceIndex + 1));
} catch (NumberFormatException e) {
throw new IOException ("ERROR: Fragment " + fullReadId + " does not contain a number after the first space.");
}
}
} else {
if (extractReadMultiplicities) {
throw new IOException ("ERROR: Fragment " + fullReadId + " does not contain a space separated field with read multiplicities.");
}
readId = fullReadId;
}
readIndex = 1;
if (fullReadId.endsWith("/2")) {
readIndex = 2;
}
fragmentId = readId;
if (fragmentId.endsWith ("/1") || fragmentId.endsWith ("/2")) {
fragmentId = fragmentId.substring(0, fragmentId.length() - 2);
}
if (debugLevel >= 2) {
System.out.println ("Reading: " + reader.toString () + " - " + readId);
}
sequence = reader.readLine ().toUpperCase ();
if (sequence == null) {
throw new IOException ("Sequence not found for the fastq entry of " + fullReadId + " in " + reader.toString ());
}
if (! isFastaEntry) {
String line = reader.readLine ();
if (line == null || ! line.startsWith ("+")) {
throw new IOException ("Second read id not found for the fastq entry of " + fullReadId + " in " + reader.toString ());
}
qualities = reader.readLine ();
if (qualities == null) {
throw new IOException ("Qualities not found for the fastq entry of " + fullReadId + " in " + reader.toString ());
}
}
}
FastqEntry (BufferedReader reader) throws IOException {
this (reader, false);
}
public String getReadId () {
return readId;
}
public String getFragmentId () {
return fragmentId;
}
public String getFullReadId () {
return fullReadId;
}
public String getSequence () {
return sequence;
}
public String getSequenceWithoutChar (String c) {
return sequence.replace(c, "");
}
public String getQualities () {
return qualities;
}
public String toMultiplicityString (Counter fragmentCounter) throws IOException {
fragmentId = "F" + fragmentCounter.getZeroFilledCount ();
return fragmentId + "\t" + readMultiplicity;
}
public boolean equals (Object o) {
if (o == null) {
return false;
}
FastqEntry f = (FastqEntry) o;
return f.getReadId().equals(getReadId ());
}
public int hashCode () {
return getReadId().hashCode();
}
public String toString () {
return
getFullReadId () + "\n" +
getSequence () + "\n" +
"+" + "\n" +
getQualities ();
}
public String toString (int length) {
return
getFullReadId () + "\n" +
getSequence ().substring(0, length) + "\n" +
"+" + "\n" +
getQualities ().substring(0, length) ;
}
public String toString (int length, int inc) {
String sequence = getSequence ();
String qualities = getQualities ();
int seqLength = sequence.length();
String returnString = "";
for (int start = 0; start + length < seqLength; start = start + inc) {
if (start > 0) {
returnString = returnString + "\n";
}
returnString = returnString +
getFragmentId () + "-" + start + "/" + readIndex + "\n" +
sequence.substring (start, start + length) + "\n" +
"+" + "\n" +
qualities.substring (start, start + length);
}
return returnString;
}
public String toString (Counter fragmentCounter, int readIndex) throws IOException {
fragmentId = "@F" + fragmentCounter.getZeroFilledCount ();
readId = fragmentId + "/" + readIndex;
fragmentCounter.inc();
return
readId + "\n" +
getSequence () + "\n" +
"+" + "\n" +
getQualities ();
}
public String toString (String fragmentId, int readIndex) throws IOException {
this.fragmentId = fragmentId;
readId = fragmentId + "/" + readIndex;
return
readId + "\n" +
getSequence () + "\n" +
"+" + "\n" +
getQualities ();
}
}
| apache-2.0 |
viveksb007/pslab-android | app/src/main/java/org/fossasia/pslab/others/ViewGroupUtils.java | 796 | package org.fossasia.pslab.others;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by akarshan on 7/15/17.
*/
public class ViewGroupUtils {
public static ViewGroup getParent(View view) {
return (ViewGroup) view.getParent();
}
public static void removeView(View view) {
ViewGroup parent = getParent(view);
if (parent != null) {
parent.removeView(view);
}
}
public static void replaceView(View currentView, View newView) {
ViewGroup parent = getParent(currentView);
if (parent == null) {
return;
}
final int index = parent.indexOfChild(currentView);
removeView(currentView);
removeView(newView);
parent.addView(newView, index);
}
} | apache-2.0 |