code
stringlengths 5
1.04M
| repo_name
stringlengths 7
108
| path
stringlengths 6
299
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 5
1.04M
|
---|---|---|---|---|---|
/*
* #%L
* Bitmagasin integrationstest
*
* $Id$
* $HeadURL$
* %%
* Copyright (C) 2010 The State and University Library, The Royal Library and The State Archives, Denmark
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
package org.bitrepository.protocol.performancetest;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.bitrepository.bitrepositorymessages.AlarmMessage;
import org.bitrepository.bitrepositorymessages.Message;
import org.bitrepository.common.settings.Settings;
import org.bitrepository.common.settings.TestSettingsProvider;
import org.bitrepository.protocol.MessageContext;
import org.bitrepository.protocol.bus.LocalActiveMQBroker;
import org.bitrepository.protocol.activemq.ActiveMQMessageBus;
import org.bitrepository.protocol.bus.MessageBusConfigurationFactory;
import org.bitrepository.protocol.message.ExampleMessageFactory;
import org.bitrepository.protocol.messagebus.MessageBus;
import org.bitrepository.protocol.messagebus.MessageListener;
import org.bitrepository.protocol.security.DummySecurityManager;
import org.bitrepository.protocol.security.SecurityManager;
import org.bitrepository.settings.repositorysettings.MessageBusConfiguration;
import org.jaccept.structure.ExtendedTestCase;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
* Stress testing of the messagebus.
*
* TODO Important note for testers:
* The number of listeners should be regulated through the 'NUMBER_OF_LISTENERS' constant.
* When using many listeners, the DEFAULT_WAIT_TIME should be increased, e.g. 5000 for 25 listeners
* and 15000 for 100 listeners.
* Otherwise it is not ensured, that all the messagelisteners will receive all the messages before the validation.
*
* Also, the shutdown of the messagelisteners can generate some noise, which will make it impossible to retrieve the
* output data from the console. Therefore the results can be written to a file after the test.
* This is controlled through the variables 'WRITE_RESULTS_TO_FILE', which deternimes whether to write to the file, and
* 'OUTPUT_FILE_NAME' which is the name of the file to write the output results.
*
*/
public class MessageBusNumberOfListenersStressTest extends ExtendedTestCase {
/** The queue name.*/
private static String QUEUE = "TEST-LISTENERS";
/** The default time to wait for a simple communication.*/
private static long DEFAULT_WAIT_TIME = 500;
/** The time for the whole test.*/
private static long TIME_FRAME = 60000L;
/** The number of message listeners in the test.*/
private static int NUMBER_OF_LISTENERS = 10;
/** Whether the results will be written to a file.*/
private static final boolean WRITE_RESULTS_TO_FILE = false;
/** The name of the output file for the results of the tests.*/
private static final String OUTPUT_FILE_NAME = "NumberOfListeners-results.test";
/** The reached correlation ID for the message.*/
private static int idReached = -1;
/** The message to send back and forth over the message bus.*/
private static AlarmMessage alarmMessage;
/** The message bus instance for sending the messages.*/
private static MessageBus bus;
/** The amount of messages received.*/
private static int messageReceived = 0;
/** Whether more messages should be send.*/
private static boolean sendMoreMessages = true;
private Settings settings;
@BeforeMethod
public void initializeSettings() {
settings = TestSettingsProvider.getSettings(getClass().getSimpleName());
}
/**
* Tests the amount of messages send over a message bus, which is not placed locally.
* Requires to send at least five per second.
* @throws Exception
*/
@Test( groups = {"StressTest"} )
public void testManyListenersOnLocalMessageBus() throws Exception {
addDescription("Tests how many messages can be handled within a given timeframe when a given number of "
+ "listeners are receiving them.");
addStep("Define constants", "This should not be possible to fail.");
QUEUE += "-" + (new Date()).getTime();
messageReceived = 0;
idReached = -1;
sendMoreMessages = true;
addStep("Define the message to send.", "Should retrieve the Alarm message from examples and set the To.");
alarmMessage = ExampleMessageFactory.createMessage(AlarmMessage.class);
alarmMessage.setDestination(QUEUE);
addStep("Make configuration for the messagebus.", "Both should be created.");
settings.getRepositorySettings().getProtocolSettings().setMessageBusConfiguration(
MessageBusConfigurationFactory.createEmbeddedMessageBusConfiguration()
);
/** The mocked SecurityManager */
SecurityManager securityManager = new DummySecurityManager();
LocalActiveMQBroker broker = new LocalActiveMQBroker(settings.getMessageBusConfiguration());
try {
addStep("Start the broker and initialise the listeners.",
"Connections should be established.");
broker.start();
bus = new ActiveMQMessageBus(settings, securityManager);
testListeners(settings.getMessageBusConfiguration(), securityManager);
} finally {
if(broker != null) {
broker.stop();
broker = null;
}
}
}
@Test( groups = {"StressTest"} )
public void testManyListenersOnDistributedMessageBus() throws Exception {
addDescription("Tests how many messages can be handled within a given timeframe when a given number of "
+ "listeners are receiving them.");
addStep("Define constants", "This should not be possible to fail.");
QUEUE += "-" + (new Date()).getTime();
messageReceived = 0;
idReached = -1;
sendMoreMessages = true;
addStep("Define the message to send.", "Should retrieve the Alarm message from examples and set the To.");
alarmMessage = ExampleMessageFactory.createMessage(AlarmMessage.class);
alarmMessage.setDestination(QUEUE);
addStep("Make configuration for the messagebus.", "Both should be created.");
MessageBusConfiguration conf = MessageBusConfigurationFactory.createDefaultConfiguration();
/** The mocked SecurityManager */
SecurityManager securityManager = new DummySecurityManager();
addStep("Start the broker and initialise the listeners.",
"Connections should be established.");
bus = new ActiveMQMessageBus(settings, securityManager);
testListeners(conf, securityManager);
}
public void testListeners(MessageBusConfiguration conf, SecurityManager securityManager) throws Exception {
List<NotificationMessageListener> listeners = new ArrayList<>(NUMBER_OF_LISTENERS);
try {
addStep("Initialise the message listeners.", "Should be created and connected to the message bus.");
for(int i = 0; i < NUMBER_OF_LISTENERS; i++) {
listeners.add(new NotificationMessageListener(settings, securityManager));
}
addStep("Wait for setup", "We wait!");
synchronized (this) {
try {
wait(DEFAULT_WAIT_TIME);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
addStep("Send the first message", "Message should be send.");
sendMessageWithId(1);
addStep("Wait for the timeframe on '" + TIME_FRAME + "' milliseconds.",
"We wait!");
synchronized (this) {
try {
wait(TIME_FRAME);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
addStep("Stop sending more messages and await all the messages to be received by all the listeners",
"Should be Ok");
sendMoreMessages = false;
synchronized (this) {
try {
wait(DEFAULT_WAIT_TIME);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
addStep("Verifying the amount of message sent '" + idReached + "' has been received by all '"
+ NUMBER_OF_LISTENERS + "' listeners", "Should be the same amount for each listener, and the same "
+ "amount as the correlation ID of the message");
Assert.assertTrue(idReached * NUMBER_OF_LISTENERS == messageReceived,
"Reached message Id " + idReached + " thus each message of the " + NUMBER_OF_LISTENERS + " listener "
+ "should have received " + idReached + " message, though they have received "
+ messageReceived + " message all together.");
for(NotificationMessageListener listener : listeners) {
Assert.assertTrue((listener.getCount() == idReached),
"Should have received " + idReached + " messages, but has received "
+ listener.getCount());
}
// If too many messagelisteners, then they will create so much noise, that the results cannot be read from
// the console output (due to shutdown 'warnings'). Thus write the results in a file.
if(WRITE_RESULTS_TO_FILE) {
FileOutputStream out = new FileOutputStream(new File(OUTPUT_FILE_NAME), true);
out.write(new String("idReached: " + idReached + ", NumberOfListeners: " + NUMBER_OF_LISTENERS
+ ", messagesReceived: " + messageReceived + " on bus "
+ conf.getURL() + "\n").getBytes());
out.flush();
out.close();
}
} finally {
if(listeners != null) {
for(NotificationMessageListener listener : listeners) {
listener.stop();
}
listeners.clear();
listeners = null;
}
synchronized (this) {
try {
wait(DEFAULT_WAIT_TIME);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**
* Method for sending the Alarm message with a specific ID.
*
* @param id The correlation id for the message to send.
*/
private static void sendMessageWithId(int id) {
if(sendMoreMessages) {
alarmMessage.setCorrelationID("" + id);
bus.sendMessage(alarmMessage);
}
}
/**
* Function for handling the Correlation id of the received messages of the listeners.
* If it is the first time a correlation id is received, then a new message with the subsequent correlation
* id is sent. This ensures that the message is only sent once per Correlation id.
*
* @param receivedId The received correlation id.
*/
public static synchronized void handleMessageDistribution(int receivedId) {
if(receivedId > idReached) {
idReached = receivedId;
sendMessageWithId(idReached + 1);
}
messageReceived++;
}
/**
* Messagelistener which notifies the 'handleMessageDistribution' method with the correlation id whenever
* a message it received.
* Otherwise counts the amount of received messages.
*/
private class NotificationMessageListener implements MessageListener {
/** The message bus.*/
private final MessageBus bus;
/** The amount of messages received.*/
private int count;
/**
* Constructor.
* @param settings The configuration for defining the message bus.
*/
public NotificationMessageListener(Settings settings, SecurityManager securityManager) {
this.bus = new ActiveMQMessageBus(settings, securityManager);
this.count = 0;
bus.addListener(QUEUE, this);
}
/**
* Method for stopping interaction with the message listener.
*/
public void stop() {
bus.removeListener(QUEUE, this);
}
/**
* Retrieval of the amount of messages caught by the listener.
* @return The number of message received by this.
*/
public int getCount() {
return count;
}
@Override
public void onMessage(Message message, MessageContext messageContext) {
count++;
int receivedId = Integer.parseInt(message.getCorrelationID());
handleMessageDistribution(receivedId);
}
}
}
| bitrepository/reference | bitrepository-core/src/test/java/org/bitrepository/protocol/performancetest/MessageBusNumberOfListenersStressTest.java | Java | lgpl-2.1 | 13,656 |
/*
* fb-contrib - Auxiliary detectors for Java programs
* Copyright (C) 2005-2016 Dave Brosius
*
* 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.mebigfatguy.fbcontrib.detect;
import java.util.ArrayDeque;
import java.util.BitSet;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.bcel.Constants;
import org.apache.bcel.classfile.AnnotationEntry;
import org.apache.bcel.classfile.Code;
import org.apache.bcel.classfile.ConstantPool;
import org.apache.bcel.classfile.ConstantUtf8;
import org.apache.bcel.classfile.Field;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.FieldInstruction;
import org.apache.bcel.generic.GETFIELD;
import org.apache.bcel.generic.INVOKESPECIAL;
import org.apache.bcel.generic.INVOKEVIRTUAL;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.ObjectType;
import org.apache.bcel.generic.ReferenceType;
import com.mebigfatguy.fbcontrib.utils.BugType;
import com.mebigfatguy.fbcontrib.utils.SignatureUtils;
import com.mebigfatguy.fbcontrib.utils.ToString;
import com.mebigfatguy.fbcontrib.utils.Values;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.BytecodeScanningDetector;
import edu.umd.cs.findbugs.FieldAnnotation;
import edu.umd.cs.findbugs.SourceLineAnnotation;
import edu.umd.cs.findbugs.ba.BasicBlock;
import edu.umd.cs.findbugs.ba.BasicBlock.InstructionIterator;
import edu.umd.cs.findbugs.ba.CFG;
import edu.umd.cs.findbugs.ba.CFGBuilderException;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.ba.Edge;
/**
* finds fields that are used in a locals only fashion, specifically private fields that are accessed first in each method with a store vs. a load.
*/
public class FieldCouldBeLocal extends BytecodeScanningDetector {
private final BugReporter bugReporter;
private ClassContext clsContext;
private Map<String, FieldInfo> localizableFields;
private CFG cfg;
private ConstantPoolGen cpg;
private BitSet visitedBlocks;
private Map<String, Set<String>> methodFieldModifiers;
private String clsName;
private String clsSig;
/**
* constructs a FCBL detector given the reporter to report bugs on.
*
* @param bugReporter
* the sync of bug reports
*/
public FieldCouldBeLocal(BugReporter bugReporter) {
this.bugReporter = bugReporter;
}
/**
* overrides the visitor to collect localizable fields, and then report those that survive all method checks.
*
* @param classContext
* the context object that holds the JavaClass parsed
*/
@Override
public void visitClassContext(ClassContext classContext) {
try {
localizableFields = new HashMap<>();
visitedBlocks = new BitSet();
clsContext = classContext;
clsName = clsContext.getJavaClass().getClassName();
clsSig = SignatureUtils.classToSignature(clsName);
JavaClass cls = classContext.getJavaClass();
Field[] fields = cls.getFields();
ConstantPool cp = classContext.getConstantPoolGen().getConstantPool();
for (Field f : fields) {
if (!f.isStatic() && !f.isVolatile() && (f.getName().indexOf('$') < 0) && f.isPrivate()) {
FieldAnnotation fa = new FieldAnnotation(cls.getClassName(), f.getName(), f.getSignature(), false);
boolean hasExternalAnnotation = false;
for (AnnotationEntry entry : f.getAnnotationEntries()) {
ConstantUtf8 cutf = (ConstantUtf8) cp.getConstant(entry.getTypeIndex());
if (!cutf.getBytes().startsWith("java")) {
hasExternalAnnotation = true;
break;
}
}
localizableFields.put(f.getName(), new FieldInfo(fa, hasExternalAnnotation));
}
}
if (localizableFields.size() > 0) {
buildMethodFieldModifiers(classContext);
super.visitClassContext(classContext);
for (FieldInfo fi : localizableFields.values()) {
FieldAnnotation fa = fi.getFieldAnnotation();
SourceLineAnnotation sla = fi.getSrcLineAnnotation();
BugInstance bug = new BugInstance(this, BugType.FCBL_FIELD_COULD_BE_LOCAL.name(), NORMAL_PRIORITY).addClass(this).addField(fa);
if (sla != null) {
bug.addSourceLine(sla);
}
bugReporter.reportBug(bug);
}
}
} finally {
localizableFields = null;
visitedBlocks = null;
clsContext = null;
methodFieldModifiers = null;
}
}
/**
* overrides the visitor to navigate basic blocks looking for all first usages of fields, removing those that are read from first.
*
* @param obj
* the context object of the currently parsed method
*/
@Override
public void visitMethod(Method obj) {
if (localizableFields.isEmpty()) {
return;
}
try {
cfg = clsContext.getCFG(obj);
cpg = cfg.getMethodGen().getConstantPool();
BasicBlock bb = cfg.getEntry();
Set<String> uncheckedFields = new HashSet<>(localizableFields.keySet());
visitedBlocks.clear();
checkBlock(bb, uncheckedFields);
} catch (CFGBuilderException cbe) {
localizableFields.clear();
} finally {
cfg = null;
cpg = null;
}
}
/**
* looks for methods that contain a GETFIELD or PUTFIELD opcodes
*
* @param method
* the context object of the current method
* @return if the class uses GETFIELD or PUTFIELD
*/
private boolean prescreen(Method method) {
BitSet bytecodeSet = getClassContext().getBytecodeSet(method);
return (bytecodeSet != null) && (bytecodeSet.get(Constants.PUTFIELD) || bytecodeSet.get(Constants.GETFIELD));
}
/**
* implements the visitor to pass through constructors and static initializers to the byte code scanning code. These methods are not reported, but are used
* to build SourceLineAnnotations for fields, if accessed.
*
* @param obj
* the context object of the currently parsed code attribute
*/
@Override
public void visitCode(Code obj) {
Method m = getMethod();
if (prescreen(m)) {
String methodName = m.getName();
if ("<clinit".equals(methodName) || Values.CONSTRUCTOR.equals(methodName)) {
super.visitCode(obj);
}
}
}
/**
* implements the visitor to add SourceLineAnnotations for fields in constructors and static initializers.
*
* @param seen
* the opcode of the currently visited instruction
*/
@Override
public void sawOpcode(int seen) {
if ((seen == GETFIELD) || (seen == PUTFIELD)) {
String fieldName = getNameConstantOperand();
FieldInfo fi = localizableFields.get(fieldName);
if (fi != null) {
SourceLineAnnotation sla = SourceLineAnnotation.fromVisitedInstruction(this);
fi.setSrcLineAnnotation(sla);
}
}
}
/**
* looks in this basic block for the first access to the fields in uncheckedFields. Once found the item is removed from uncheckedFields, and removed from
* localizableFields if the access is a GETFIELD. If any unchecked fields remain, this method is recursively called on all outgoing edges of this basic
* block.
*
* @param bb
* this basic block
* @param uncheckedFields
* the list of fields to look for
*/
private void checkBlock(BasicBlock bb, Set<String> uncheckedFields) {
Deque<BlockState> toBeProcessed = new ArrayDeque<>();
toBeProcessed.addLast(new BlockState(bb, uncheckedFields));
visitedBlocks.set(bb.getLabel());
while (!toBeProcessed.isEmpty()) {
if (localizableFields.isEmpty()) {
return;
}
BlockState bState = toBeProcessed.removeFirst();
bb = bState.getBasicBlock();
InstructionIterator ii = bb.instructionIterator();
while ((bState.getUncheckedFieldSize() > 0) && ii.hasNext()) {
InstructionHandle ih = ii.next();
Instruction ins = ih.getInstruction();
if (ins instanceof FieldInstruction) {
FieldInstruction fi = (FieldInstruction) ins;
if (fi.getReferenceType(cpg).getSignature().equals(clsSig)) {
String fieldName = fi.getFieldName(cpg);
FieldInfo finfo = localizableFields.get(fieldName);
if ((finfo != null) && localizableFields.get(fieldName).hasAnnotation()) {
localizableFields.remove(fieldName);
} else {
boolean justRemoved = bState.removeUncheckedField(fieldName);
if (ins instanceof GETFIELD) {
if (justRemoved) {
localizableFields.remove(fieldName);
if (localizableFields.isEmpty()) {
return;
}
}
} else if (finfo != null) {
finfo.setSrcLineAnnotation(SourceLineAnnotation.fromVisitedInstruction(clsContext, this, ih.getPosition()));
}
}
}
} else if (ins instanceof INVOKESPECIAL) {
INVOKESPECIAL is = (INVOKESPECIAL) ins;
ReferenceType rt = is.getReferenceType(cpg);
if (Values.CONSTRUCTOR.equals(is.getMethodName(cpg))) {
if ((rt instanceof ObjectType) && ((ObjectType) rt).getClassName().startsWith(clsContext.getJavaClass().getClassName() + '$')) {
localizableFields.clear();
}
} else {
localizableFields.clear();
}
} else if (ins instanceof INVOKEVIRTUAL) {
INVOKEVIRTUAL is = (INVOKEVIRTUAL) ins;
ReferenceType rt = is.getReferenceType(cpg);
if ((rt instanceof ObjectType) && ((ObjectType) rt).getClassName().equals(clsName)) {
String methodDesc = is.getName(cpg) + is.getSignature(cpg);
Set<String> fields = methodFieldModifiers.get(methodDesc);
if (fields != null) {
localizableFields.keySet().removeAll(fields);
}
}
}
}
if (bState.getUncheckedFieldSize() > 0) {
Iterator<Edge> oei = cfg.outgoingEdgeIterator(bb);
while (oei.hasNext()) {
Edge e = oei.next();
BasicBlock cb = e.getTarget();
int label = cb.getLabel();
if (!visitedBlocks.get(label)) {
toBeProcessed.addLast(new BlockState(cb, bState));
visitedBlocks.set(label);
}
}
}
}
}
/**
* builds up the method to field map of what method write to which fields this is one recursively so that if method A calls method B, and method B writes to
* field C, then A modifies F.
*
* @param classContext
* the context object of the currently parsed class
*/
private void buildMethodFieldModifiers(ClassContext classContext) {
FieldModifier fm = new FieldModifier();
fm.visitClassContext(classContext);
methodFieldModifiers = fm.getMethodFieldModifiers();
}
/**
* holds information about a field and it's first usage
*/
private static class FieldInfo {
private final FieldAnnotation fieldAnnotation;
private SourceLineAnnotation srcLineAnnotation;
private final boolean hasAnnotation;
/**
* creates a FieldInfo from an annotation, and assumes no source line information
*
* @param fa
* the field annotation for this field
* @param hasExternalAnnotation
* the field has a non java based annotation
*/
FieldInfo(final FieldAnnotation fa, boolean hasExternalAnnotation) {
fieldAnnotation = fa;
srcLineAnnotation = null;
hasAnnotation = hasExternalAnnotation;
}
/**
* set the source line annotation of first use for this field
*
* @param sla
* the source line annotation
*/
void setSrcLineAnnotation(final SourceLineAnnotation sla) {
if (srcLineAnnotation == null) {
srcLineAnnotation = sla;
}
}
/**
* get the field annotation for this field
*
* @return the field annotation
*/
FieldAnnotation getFieldAnnotation() {
return fieldAnnotation;
}
/**
* get the source line annotation for the first use of this field
*
* @return the source line annotation
*/
SourceLineAnnotation getSrcLineAnnotation() {
return srcLineAnnotation;
}
/**
* gets whether the field has a non java annotation
*
* @return if the field has a non java annotation
*/
boolean hasAnnotation() {
return hasAnnotation;
}
@Override
public String toString() {
return ToString.build(this);
}
}
/**
* holds the parse state of the current basic block, and what fields are left to be checked the fields that are left to be checked are a reference from the
* parent block and a new collection is created on first write to the set to reduce memory concerns.
*/
private static class BlockState {
private final BasicBlock basicBlock;
private Set<String> uncheckedFields;
private boolean fieldsAreSharedWithParent;
/**
* creates a BlockState consisting of the next basic block to parse, and what fields are to be checked
*
* @param bb
* the basic block to parse
* @param fields
* the fields to look for first use
*/
public BlockState(final BasicBlock bb, final Set<String> fields) {
basicBlock = bb;
uncheckedFields = fields;
fieldsAreSharedWithParent = true;
}
/**
* creates a BlockState consisting of the next basic block to parse, and what fields are to be checked
*
* @param bb
* the basic block to parse
* @param parentBlockState
* the basic block to copy from
*/
public BlockState(final BasicBlock bb, BlockState parentBlockState) {
basicBlock = bb;
uncheckedFields = parentBlockState.uncheckedFields;
fieldsAreSharedWithParent = true;
}
/**
* get the basic block to parse
*
* @return the basic block
*/
public BasicBlock getBasicBlock() {
return basicBlock;
}
/**
* returns the number of unchecked fields
*
* @return the number of unchecked fields
*/
public int getUncheckedFieldSize() {
return (uncheckedFields == null) ? 0 : uncheckedFields.size();
}
/**
* return the field from the set of unchecked fields if this occurs make a copy of the set on write to reduce memory usage
*
* @param field
* the field to be removed
*
* @return whether the object was removed.
*/
public boolean removeUncheckedField(String field) {
if ((uncheckedFields == null) || !uncheckedFields.contains(field)) {
return false;
}
if (uncheckedFields.size() == 1) {
uncheckedFields = null;
fieldsAreSharedWithParent = false;
return true;
}
if (fieldsAreSharedWithParent) {
uncheckedFields = new HashSet<>(uncheckedFields);
fieldsAreSharedWithParent = false;
uncheckedFields.remove(field);
} else {
uncheckedFields.remove(field);
}
return true;
}
@Override
public String toString() {
return ToString.build(this);
}
}
private static class FieldModifier extends BytecodeScanningDetector {
private final Map<String, Set<String>> methodCallChain = new HashMap<>();
private final Map<String, Set<String>> mfModifiers = new HashMap<>();
private String clsName;
public Map<String, Set<String>> getMethodFieldModifiers() {
Map<String, Set<String>> modifiers = new HashMap<>(mfModifiers.size());
modifiers.putAll(mfModifiers);
for (Entry<String, Set<String>> method : modifiers.entrySet()) {
modifiers.put(method.getKey(), new HashSet<>(method.getValue()));
}
boolean modified = true;
while (modified) {
modified = false;
for (Map.Entry<String, Set<String>> entry : methodCallChain.entrySet()) {
String methodDesc = entry.getKey();
Set<String> calledMethods = entry.getValue();
for (String calledMethodDesc : calledMethods) {
Set<String> fields = mfModifiers.get(calledMethodDesc);
if (fields != null) {
Set<String> flds = modifiers.get(methodDesc);
if (flds == null) {
flds = new HashSet<>();
modifiers.put(methodDesc, flds);
}
if (flds.addAll(fields)) {
modified = true;
}
}
}
}
}
return modifiers;
}
@Override
public void visitClassContext(ClassContext context) {
clsName = context.getJavaClass().getClassName();
super.visitClassContext(context);
}
@Override
public void sawOpcode(int seen) {
if (seen == PUTFIELD) {
if (clsName.equals(getClassConstantOperand())) {
String methodDesc = getMethodName() + getMethodSig();
Set<String> fields = mfModifiers.get(methodDesc);
if (fields == null) {
fields = new HashSet<>();
mfModifiers.put(methodDesc, fields);
}
fields.add(getNameConstantOperand());
}
} else if ((seen == INVOKEVIRTUAL) && clsName.equals(getClassConstantOperand())) {
String methodDesc = getMethodName() + getMethodSig();
Set<String> methods = methodCallChain.get(methodDesc);
if (methods == null) {
methods = new HashSet<>();
methodCallChain.put(methodDesc, methods);
}
methods.add(getNameConstantOperand() + getSigConstantOperand());
}
}
@Override
public String toString() {
return ToString.build(this);
}
}
}
| mebigfatguy/fb-contrib | src/com/mebigfatguy/fbcontrib/detect/FieldCouldBeLocal.java | Java | lgpl-2.1 | 21,411 |
/**
* A library to interact with Virtual Worlds such as OpenSim
* Copyright (C) 2012 Jitendra Chauhan, Email: [email protected]
*
* 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.ngt.jopenmetaverse.shared.protocol;
import java.util.ArrayList;
import java.util.List;
import com.ngt.jopenmetaverse.shared.types.UUID;
import com.ngt.jopenmetaverse.shared.types.Vector3;
import com.ngt.jopenmetaverse.shared.util.Utils;
public final class TeleportRequestPacket extends Packet
{
/// <exclude/>
public static final class AgentDataBlock extends PacketBlock
{
public UUID AgentID = new UUID();
public UUID SessionID = new UUID();
@Override
public int getLength()
{
{
return 32;
}
}
public AgentDataBlock() { }
public AgentDataBlock(byte[] bytes, int[] i) throws MalformedDataException
{
FromBytes(bytes, i);
}
@Override
public void FromBytes(byte[] bytes, int[] i) throws MalformedDataException
{
try
{
AgentID.FromBytes(bytes, i[0]); i[0] += 16;
SessionID.FromBytes(bytes, i[0]); i[0] += 16;
}
catch (Exception e)
{
throw new MalformedDataException(Utils.getExceptionStackTraceAsString(e));
}
}
@Override
public void ToBytes(byte[] bytes, int[] i)
{
AgentID.ToBytes(bytes, i[0]); i[0] += 16;
SessionID.ToBytes(bytes, i[0]); i[0] += 16;
}
}
/// <exclude/>
public static final class InfoBlock extends PacketBlock
{
public UUID RegionID = new UUID();
public Vector3 Position = new Vector3();
public Vector3 LookAt = new Vector3();
@Override
public int getLength()
{
{
return 40;
}
}
public InfoBlock() { }
public InfoBlock(byte[] bytes, int[] i) throws MalformedDataException
{
FromBytes(bytes, i);
}
@Override
public void FromBytes(byte[] bytes, int[] i) throws MalformedDataException
{
try
{
RegionID.FromBytes(bytes, i[0]); i[0] += 16;
Position.fromBytesLit(bytes, i[0]); i[0] += 12;
LookAt.fromBytesLit(bytes, i[0]); i[0] += 12;
}
catch (Exception e)
{
throw new MalformedDataException(Utils.getExceptionStackTraceAsString(e));
}
}
@Override
public void ToBytes(byte[] bytes, int[] i)
{
RegionID.ToBytes(bytes, i[0]); i[0] += 16;
Position.toBytesLit(bytes, i[0]); i[0] += 12;
LookAt.toBytesLit(bytes, i[0]); i[0] += 12;
}
}
@Override
public int getLength()
{
{
int length = 10;
length += AgentData.getLength();
length += Info.getLength();
return length;
}
}
public AgentDataBlock AgentData;
public InfoBlock Info;
public TeleportRequestPacket()
{
HasVariableBlocks = false;
Type = PacketType.TeleportRequest;
this.header = new Header();
header.Frequency = PacketFrequency.Low;
header.ID = 62;
header.Reliable = true;
AgentData = new AgentDataBlock();
Info = new InfoBlock();
}
public TeleportRequestPacket(byte[] bytes, int[] i) throws MalformedDataException
{
this();
int[] packetEnd = new int[] {bytes.length - 1};
FromBytes(bytes, i, packetEnd, null);
}
@Override
public void FromBytes(byte[] bytes, int[] i, int[] packetEnd, byte[] zeroBuffer) throws MalformedDataException
{
header.FromBytes(bytes, i, packetEnd);
if (header.Zerocoded && zeroBuffer != null)
{
packetEnd[0] = Helpers.ZeroDecode(bytes, packetEnd[0] + 1, zeroBuffer) - 1;
bytes = zeroBuffer;
}
AgentData.FromBytes(bytes, i);
Info.FromBytes(bytes, i);
}
public TeleportRequestPacket(Header head, byte[] bytes, int[] i) throws MalformedDataException
{
this();
int[] packetEnd = new int[] {bytes.length - 1};
FromBytes(head, bytes, i, packetEnd);
}
@Override
public void FromBytes(Header header, byte[] bytes, int[] i, int[] packetEnd) throws MalformedDataException
{
this.header = header;
AgentData.FromBytes(bytes, i);
Info.FromBytes(bytes, i);
}
@Override
public byte[] ToBytes()
{
int length = 10;
length += AgentData.getLength();
length += Info.getLength();
if (header.AckList != null && header.AckList.length > 0) { length += header.AckList.length * 4 + 1; }
byte[] bytes = new byte[length];
int[] i = new int[]{0};
header.ToBytes(bytes, i);
AgentData.ToBytes(bytes, i);
Info.ToBytes(bytes, i);
if (header.AckList != null && header.AckList.length > 0) { header.AcksToBytes(bytes, i); }
return bytes;
}
@Override
public byte[][] ToBytesMultiple()
{
return new byte[][] { ToBytes() };
}
}
/// <exclude/>
| nybbs2003/jopenmetaverse | src/main/java/com/ngt/jopenmetaverse/shared/protocol/TeleportRequestPacket.java | Java | lgpl-2.1 | 6,593 |
package oqube.muse.filter;
import java.util.List;
import oqube.muse.events.CompoundEvent;
import oqube.muse.events.EventSequenceMatcher;
import oqube.muse.events.SinkEvent;
public class StartFilter implements SinkFilter {
private EventSequenceMatcher matcher;
private boolean started;
public StartFilter(EventSequenceMatcher m) {
this.matcher = m;
this.started = false;
}
public SinkEvent filter(SinkEvent event) {
this.matcher.receive(event);
if (this.started)
return event;
else if (this.matcher.matches(false)) {
this.started = true;
return extractBufferedEvents(event);
} else
return SinkEvent.NULL_EVENT;
}
private SinkEvent extractBufferedEvents(SinkEvent event) {
final List<SinkEvent> bufferedEvents = this.matcher.getEvents();
if (bufferedEvents.size() > 1)
return new CompoundEvent(bufferedEvents);
else if (bufferedEvents.size() == 1)
return bufferedEvents.get(0);
else
return event;
}
}
| abailly/muse-parser | muse-parser/src/main/java/oqube/muse/filter/StartFilter.java | Java | lgpl-2.1 | 1,006 |
/*
* Cacheonix Systems licenses this file to You under the LGPL 2.1
* (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.cacheonix.org/products/cacheonix/license-lgpl-2.1.htm
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cacheonix.impl.cache.distributed.partitioned;
import java.io.IOException;
import org.cacheonix.TestUtils;
import org.cacheonix.impl.net.ClusterNodeAddress;
import org.cacheonix.impl.net.serializer.Serializer;
import org.cacheonix.impl.net.serializer.SerializerFactory;
import org.cacheonix.impl.util.logging.Logger;
import junit.framework.TestCase;
/**
* RepartitionAnnouncementTest
* <p/>
*
* @author <a href="mailto:[email protected]">Slava Imeshev</a>
* @since Nov 9, 2009 8:06:51 PM
*/
public final class RepartitionAnnouncementTest extends TestCase {
/**
* Logger.
*
* @noinspection UNUSED_SYMBOL, UnusedDeclaration
*/
private static final Logger LOG = Logger.getLogger(RepartitionAnnouncementTest.class); // NOPMD
private static final ClusterNodeAddress ADDR_1 = TestUtils.createTestAddress(1);
private static final String TEST_CACHE = "test.cache";
private RepartitionAnnouncement announcement;
public void testSerialze() throws IOException {
final Serializer serializer = SerializerFactory.getInstance().getSerializer(Serializer.TYPE_JAVA);
assertEquals(announcement, serializer.deserialize(serializer.serialize(announcement)));
}
protected void setUp() throws Exception {
super.setUp();
announcement = new RepartitionAnnouncement(TEST_CACHE);
announcement.setSender(ADDR_1);
}
}
| cacheonix/cacheonix-core | test/src/org/cacheonix/impl/cache/distributed/partitioned/RepartitionAnnouncementTest.java | Java | lgpl-2.1 | 1,999 |
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.util.Collection;
public class ExtractTest {
@Test
public void testExtracted() {
File extractedDir = new File(System.getProperty("testOutputDir") + "/nodejs/extracted/");
Assert.assertTrue("extractedDir " + extractedDir.getAbsolutePath() + " does not exist", extractedDir.exists());
Collection<File> foundFiles = FileUtils.listFiles(extractedDir, new IOFileFilter() {
@Override
public boolean accept(File file) {
return file.getName().startsWith("node");
}
@Override
public boolean accept(File dir, String name) {
return name.startsWith("node");
}
}, null);
Assert.assertEquals(1, foundFiles.size());
File extractedNodeJsExec = foundFiles.iterator().next();
Assert.assertTrue("extracted node JS executable does not exist", extractedNodeJsExec.exists());
Assert.assertTrue("extracted node JS executable is empty", extractedNodeJsExec.length() > 1000);
Assert.assertTrue("extracted node JS executable did not have executable rights", extractedNodeJsExec.canExecute());
}
}
| skwakman/nodejs-maven-plugin | nodejs-maven-plugin-test/src/test/java/ExtractTest.java | Java | lgpl-2.1 | 1,234 |
//$HeadURL: svn+ssh://[email protected]/deegree/base/trunk/resources/eclipse/files_template.xml $
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2010 by:
- Department of Geography, University of Bonn -
and
- lat/lon GmbH -
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 2.1 of the License, or (at your option)
any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: [email protected]
----------------------------------------------------------------------------*/
package org.deegree.services.csw.getrecords;
import static org.deegree.protocol.csw.CSWConstants.VERSION_202;
import java.net.URI;
import java.util.List;
import org.apache.axiom.om.OMElement;
import org.deegree.commons.tom.ows.Version;
import org.deegree.commons.utils.kvp.InvalidParameterValueException;
import org.deegree.commons.xml.XPath;
import org.deegree.protocol.csw.CSWConstants.ResultType;
import org.deegree.protocol.i18n.Messages;
import org.deegree.services.csw.AbstractCSWRequestXMLAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Abstract base class encapsulating the parsing an {@link GetRecords} XML request.
*
* @author <a href="mailto:[email protected]">Lyn Goltz</a>
* @author last edited by: $Author: lyn $
*
* @version $Revision: $, $Date: $
*/
public abstract class AbstractGetRecordsXMLAdapter extends AbstractCSWRequestXMLAdapter {
private static final Logger LOG = LoggerFactory.getLogger( GetRecordsXMLAdapter.class );
/**
* Parses the {@link GetRecords} XML request by deciding which version has to be parsed because of the requested
* version.
*
* @param version
* @return {@Link GetRecords}
*/
public GetRecords parse( Version version, String defaultOutputFormat, String defaultOutputSchema ) {
if ( version == null ) {
version = Version.parseVersion( getRequiredNodeAsString( rootElement, new XPath( "@version", nsContext ) ) );
}
GetRecords result = null;
if ( VERSION_202.equals( version ) ) {
result = parse202( defaultOutputFormat, defaultOutputSchema );
} else {
String msg = Messages.get( "UNSUPPORTED_VERSION", version, Version.getVersionsString( VERSION_202 ) );
throw new InvalidParameterValueException( msg );
}
return result;
}
/**
* Parses the {@link GetRecords} request on basis of CSW version 2.0.2
*
* @param version
* that is requested, 2.0.2
* @return {@link GetRecords}
*/
private GetRecords parse202( String defaultOutputFormat, String defaultOutputSchema ) {
LOG.debug( rootElement.toString() );
String resultTypeStr = getNodeAsString( rootElement, new XPath( "@resultType", nsContext ),
ResultType.hits.name() );
OMElement holeRequest = getElement( rootElement, new XPath( ".", nsContext ) );
ResultType resultType = ResultType.determineResultType( resultTypeStr );
int maxRecords = getNodeAsInt( rootElement, new XPath( "@maxRecords", nsContext ), 10 );
int startPosition = getNodeAsInt( rootElement, new XPath( "@startPosition", nsContext ), 1 );
String outputFormat = getNodeAsString( rootElement, new XPath( "@outputFormat", nsContext ),
defaultOutputFormat );
String requestId = getNodeAsString( rootElement, new XPath( "@requestId", nsContext ), null );
String outputSchemaString = getNodeAsString( rootElement, new XPath( "@outputSchema", nsContext ),
defaultOutputSchema );
URI outputSchema = URI.create( outputSchemaString );
List<OMElement> getRecordsChildElements = getRequiredElements( rootElement, new XPath( "*", nsContext ) );
return parseSubElements( holeRequest, resultType, maxRecords, startPosition, outputFormat, requestId,
outputSchema, getRecordsChildElements );
}
protected Query parseQuery( OMElement omElement ) {
return Query.getQuery( omElement );
}
protected abstract GetRecords parseSubElements( OMElement holeRequest, ResultType resultType, int maxRecords,
int startPosition, String outputFormat, String requestId,
URI outputSchema, List<OMElement> getRecordsChildElements );
}
| deegree/deegree3 | deegree-services/deegree-services-csw/src/main/java/org/deegree/services/csw/getrecords/AbstractGetRecordsXMLAdapter.java | Java | lgpl-2.1 | 5,425 |
package ch.unibas.cs.hpwc.patus.codegen.backend.assembly.optimize;
import ch.unibas.cs.hpwc.patus.codegen.backend.assembly.InstructionList;
/**
* Interface definition for instruction list optimizers
* @author Matthias-M. Christen
*/
public interface IInstructionListOptimizer
{
/**
* Does an optimization pass on the input instruction list <code>il</code>.
* @param il The instruction list to optimize
* @return The optimized instruction list
*/
public abstract InstructionList optimize (InstructionList il);
}
| intersense/patus-gw | src/ch/unibas/cs/hpwc/patus/codegen/backend/assembly/optimize/IInstructionListOptimizer.java | Java | lgpl-2.1 | 526 |
package carpentersblocks.util.handler;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.imageio.ImageIO;
import net.minecraft.client.Minecraft;
import org.apache.logging.log4j.Level;
import carpentersblocks.CarpentersBlocksCachedResources;
import carpentersblocks.util.ModLogger;
import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class ResourceHandler {
private static final CarpentersBlocksCachedResources modContainer = new CarpentersBlocksCachedResources();
private static ArrayList<BufferedImage> images = new ArrayList<BufferedImage>();
private static ArrayList<String> entries = new ArrayList<String>();
public static void addResource(String name, BufferedImage bufferedImage)
{
images.add(bufferedImage);
entries.add(name);
}
/**
* Creates resource file, loads it, and refreshes resources.
*/
public static void addResources()
{
if (!images.isEmpty()) {
try {
if (createDirectory()) {
createZip(CarpentersBlocksCachedResources.resourceDir, CarpentersBlocksCachedResources.MODID + ".zip");
ModLogger.log(Level.INFO, "Cached " + images.size() + (images.size() != 1 ? " resources" : " resource"));
FMLClientHandler.instance().addModAsResource(modContainer);
Minecraft.getMinecraft().refreshResources();
}
} catch (Exception e) {
ModLogger.log(Level.WARN, "Resource caching failed: " + e.getMessage());
}
}
}
private static boolean createDirectory() throws Exception
{
File dir = new File(CarpentersBlocksCachedResources.resourceDir);
if (!dir.exists()) {
dir.mkdir();
}
return dir.exists();
}
private static void createZip(String dir, String fileName) throws Exception
{
File file = new File(dir, fileName);
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file));
for (BufferedImage image : images) {
out.putNextEntry(new ZipEntry("assets/" + CarpentersBlocksCachedResources.MODID.toLowerCase() + "/textures/blocks/designs/bed/cache/" + entries.get(images.indexOf(image)) + ".png"));
ImageIO.write(image, "png", out);
out.closeEntry();
}
out.flush();
out.close();
}
}
| LorenzoDCC/carpentersblocks | carpentersblocks/util/handler/ResourceHandler.java | Java | lgpl-2.1 | 2,657 |
package soot.toDex;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Map;
import soot.Body;
import soot.BodyTransformer;
import soot.Singletons;
import soot.Trap;
import soot.Unit;
import soot.jimple.Jimple;
/**
* Transformer that splits nested traps for Dalvik which does not support hierarchies of traps. If we have a trap (1-3) with
* handler A and a trap (2) with handler B, we transform them into three new traps: (1) and (3) with A, (2) with A+B.
*
* @author Steven Arzt
*/
public class TrapSplitter extends BodyTransformer {
public TrapSplitter(Singletons.Global g) {
}
public static TrapSplitter v() {
return soot.G.v().soot_toDex_TrapSplitter();
}
private class TrapOverlap {
private Trap t1;
private Trap t2;
private Unit t2Start;
public TrapOverlap(Trap t1, Trap t2, Unit t2Start) {
this.t1 = t1;
this.t2 = t2;
this.t2Start = t2Start;
}
}
@Override
protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
// If we have less then two traps, there's nothing to do here
if (b.getTraps().size() < 2) {
return;
}
// Look for overlapping traps
TrapOverlap to;
while ((to = getNextOverlap(b)) != null) {
// If one of the two traps is empty, we remove it
if (to.t1.getBeginUnit() == to.t1.getEndUnit()) {
b.getTraps().remove(to.t1);
continue;
}
if (to.t2.getBeginUnit() == to.t2.getEndUnit()) {
b.getTraps().remove(to.t2);
continue;
}
// t1start..t2start -> t1'start...t1'end,t2start...
if (to.t1.getBeginUnit() != to.t2Start) {
// We need to split off t1.start - predOf(t2.splitUnit). If both traps
// start at the same statement, this range is empty, so we have checked
// that.
Trap newTrap = Jimple.v().newTrap(to.t1.getException(), to.t1.getBeginUnit(), to.t2Start, to.t1.getHandlerUnit());
safeAddTrap(b, newTrap, to.t1);
to.t1.setBeginUnit(to.t2Start);
}
// (t1start, t2start) ... t1end ... t2end
else if (to.t1.getBeginUnit() == to.t2.getBeginUnit()) {
Unit firstEndUnit = to.t1.getBeginUnit();
while (firstEndUnit != to.t1.getEndUnit() && firstEndUnit != to.t2.getEndUnit()) {
firstEndUnit = b.getUnits().getSuccOf(firstEndUnit);
}
if (firstEndUnit == to.t1.getEndUnit()) {
if (to.t1.getException() != to.t2.getException()) {
Trap newTrap
= Jimple.v().newTrap(to.t2.getException(), to.t1.getBeginUnit(), firstEndUnit, to.t2.getHandlerUnit());
safeAddTrap(b, newTrap, to.t2);
} else if (to.t1.getHandlerUnit() != to.t2.getHandlerUnit()) {
// Traps t1 and t2 catch the same exception, but have different handlers
//
// The JVM specification (2.10 Exceptions) says:
// "At run time, when an exception is thrown, the Java
// Virtual Machine searches the exception handlers of the current method in the order
// that they appear in the corresponding exception handler table in the class file,
// starting from the beginning of that table. Note that the Java Virtual Machine does
// not enforce nesting of or any ordering of the exception table entries of a method.
// The exception handling semantics of the Java programming language are implemented
// only through cooperation with the compiler (3.12)."
//
// 3.12
// "The nesting of catch clauses is represented only in the exception table. The Java
// Virtual Machine does not enforce nesting of or any ordering of the exception table
// entries (2.10). However, because try-catch constructs are structured, a compiler
// can always order the entries of the exception handler table such that, for any thrown
// exception and any program counter value in that method, the first exception handler
// that matches the thrown exception corresponds to the innermost matching catch clause."
//
// t1 is first, so it stays the same.
// t2 is reduced
Trap newTrap
= Jimple.v().newTrap(to.t1.getException(), to.t1.getBeginUnit(), firstEndUnit, to.t1.getHandlerUnit());
safeAddTrap(b, newTrap, to.t1);
}
to.t2.setBeginUnit(firstEndUnit);
} else if (firstEndUnit == to.t2.getEndUnit()) {
if (to.t1.getException() != to.t2.getException()) {
Trap newTrap2
= Jimple.v().newTrap(to.t1.getException(), to.t1.getBeginUnit(), firstEndUnit, to.t1.getHandlerUnit());
safeAddTrap(b, newTrap2, to.t1);
to.t1.setBeginUnit(firstEndUnit);
} else if (to.t1.getHandlerUnit() != to.t2.getHandlerUnit()) {
// If t2 ends first, t2 is useless.
b.getTraps().remove(to.t2);
} else {
to.t1.setBeginUnit(firstEndUnit);
}
}
}
}
}
/**
* Adds a new trap to the given body only if the given trap is not empty
*
* @param b
* The body to which to add the trap
* @param newTrap
* The trap to add
* @param position
* The position after which to insert the trap
*/
private void safeAddTrap(Body b, Trap newTrap, Trap position) {
// Do not create any empty traps
if (newTrap.getBeginUnit() != newTrap.getEndUnit()) {
if (position != null) {
b.getTraps().insertAfter(newTrap, position);
} else {
b.getTraps().add(newTrap);
}
}
}
/**
* Gets two arbitrary overlapping traps in the given method body
*
* @param b
* The body in which to look for overlapping traps
* @return Two overlapping traps if they exist, otherwise null
*/
private TrapOverlap getNextOverlap(Body b) {
for (Trap t1 : b.getTraps()) {
// Look whether one of our trapped statements is the begin
// statement of another trap
for (Unit splitUnit = t1.getBeginUnit(); splitUnit != t1.getEndUnit(); splitUnit = b.getUnits().getSuccOf(splitUnit)) {
for (Trap t2 : b.getTraps()) {
if (t1 != t2 && (t1.getEndUnit() != t2.getEndUnit() || t1.getException() == t2.getException())
&& t2.getBeginUnit() == splitUnit) {
return new TrapOverlap(t1, t2, t2.getBeginUnit());
}
}
}
}
return null;
}
}
| plast-lab/soot | src/main/java/soot/toDex/TrapSplitter.java | Java | lgpl-2.1 | 7,337 |
/* Yougi is a web application conceived to manage user groups or
* communities focused on a certain domain of knowledge, whose members are
* constantly sharing information and participating in social and educational
* events. Copyright (C) 2011 Hildeberto Mendonça.
*
* This application 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 application 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.
*
* There is a full copy of the GNU Lesser General Public License along with
* this library. Look for the file license.txt at the root level. If you do not
* find it, write to the Free Software Foundation, Inc., 59 Temple Place,
* Suite 330, Boston, MA 02111-1307 USA.
* */
package org.yougi.event.web.model;
import org.yougi.event.business.EventBean;
import org.yougi.event.business.EventVenueBean;
import org.yougi.event.business.VenueBean;
import org.yougi.event.entity.Event;
import org.yougi.event.entity.EventVenue;
import org.yougi.event.entity.Venue;
import org.yougi.util.StringUtils;
import org.yougi.annotation.ManagedProperty;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.Serializable;
import java.util.List;
/**
* @author Hildeberto Mendonca - http://www.hildeberto.com
*/
@Named
@RequestScoped
public class EventVenueMBean implements Serializable {
private static final long serialVersionUID = 1L;
@EJB
private EventBean eventBean;
@EJB
private VenueBean venueBean;
@EJB
private EventVenueBean eventVenueBean;
@Inject
@ManagedProperty("#{param.eventId}")
private String eventId;
@Inject
@ManagedProperty("#{param.venueId}")
private String venueId;
private List<Venue> venues;
private List<Event> events;
private String selectedVenue;
private String selectedEvent;
public String getEventId() {
return eventId;
}
public void setEventId(String eventId) {
this.eventId = eventId;
}
public String getVenueId() {
return venueId;
}
public void setVenueId(String venueId) {
this.venueId = venueId;
}
public String getSelectedVenue() {
return selectedVenue;
}
public void setSelectedVenue(String selectedVenue) {
this.selectedVenue = selectedVenue;
}
public String getSelectedEvent() {
return selectedEvent;
}
public void setSelectedEvent(String selectedEvent) {
this.selectedEvent = selectedEvent;
}
public List<Venue> getVenues() {
if(this.venues == null) {
if(StringUtils.isNullOrBlank(this.selectedEvent)) {
this.venues = venueBean.findVenues();
} else {
Event event = new Event(selectedEvent);
this.venues = eventVenueBean.findVenues(event);
}
}
return this.venues;
}
public List<Event> getEvents() {
if(this.events == null) {
if(StringUtils.isNullOrBlank(this.selectedVenue)) {
this.events = eventBean.findParentEvents();
} else {
Venue venue = new Venue(selectedVenue);
this.events = eventVenueBean.findEvents(venue);
}
}
return this.events;
}
@PostConstruct
public void load() {
if (this.eventId != null && !this.eventId.isEmpty()) {
this.selectedEvent = eventId;
}
if (this.venueId != null && !this.venueId.isEmpty()) {
this.selectedVenue = venueId;
}
}
public String save() {
EventVenue eventVenue = new EventVenue();
eventVenue.setEvent(new Event(this.selectedEvent));
eventVenue.setVenue(new Venue(this.selectedVenue));
eventVenueBean.save(eventVenue);
return getNextPage();
}
public String cancel() {
return getNextPage();
}
private String getNextPage() {
if (this.eventId != null && !this.eventId.isEmpty()) {
return "event?faces-redirect=true&tab=5&id="+ this.selectedEvent;
} else {
return "venue?faces-redirect=true&id="+ this.selectedVenue;
}
}
} | luiz158/yougi-javaee7 | java/src/main/java/org/yougi/event/web/model/EventVenueMBean.java | Java | lgpl-2.1 | 4,651 |
package org.areasy.common.data.type.iterator;
/*
* Copyright (c) 2007-2020 AREasy Runtime
*
* This library, AREasy Runtime and API for BMC Remedy AR System, is free software ("Licensed 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;
* including but not limited to, the implied warranty of MERCHANTABILITY, NONINFRINGEMENT,
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*/
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.NoSuchElementException;
/**
* As the wrapped Iterator is traversed, ListIteratorWrapper
* builds a LinkedList of its values, permitting all required
* operations of ListIterator.
*
* @version $Id: ListIteratorWrapper.java,v 1.2 2008/05/14 09:32:40 swd\stefan.damian Exp $
*/
public class ListIteratorWrapper implements ListIterator
{
/**
* Holds value of property "iterator"
*/
private final Iterator iterator;
private final LinkedList list = new LinkedList();
// position of this iterator
private int currentIndex = 0;
// position of the wrapped iterator
// this Iterator should only be used to populate the list
private int wrappedIteratorIndex = 0;
private static final String UNSUPPORTED_OPERATION_MESSAGE = "ListIteratorWrapper does not support optional operations of ListIterator.";
/**
* Constructs a new <code>ListIteratorWrapper</code> that will wrap
* the given iterator.
*
* @param iterator the iterator to wrap
* @throws NullPointerException if the iterator is null
*/
public ListIteratorWrapper(Iterator iterator)
{
super();
if (iterator == null) throw new NullPointerException("Iterator must not be null");
this.iterator = iterator;
}
/**
* Throws {@link UnsupportedOperationException}.
*
* @param o ignored
* @throws UnsupportedOperationException always
*/
public void add(Object o) throws UnsupportedOperationException
{
throw new UnsupportedOperationException(UNSUPPORTED_OPERATION_MESSAGE);
}
/**
* Returns true if there are more elements in the iterator.
*
* @return true if there are more elements
*/
public boolean hasNext()
{
if (currentIndex == wrappedIteratorIndex) return iterator.hasNext();
return true;
}
/**
* Returns true if there are previous elements in the iterator.
*
* @return true if there are previous elements
*/
public boolean hasPrevious()
{
if (currentIndex == 0) return false;
return true;
}
/**
* Returns the next element from the iterator.
*
* @return the next element from the iterator
* @throws NoSuchElementException if there are no more elements
*/
public Object next() throws NoSuchElementException
{
if (currentIndex < wrappedIteratorIndex)
{
++currentIndex;
return list.get(currentIndex - 1);
}
Object retval = iterator.next();
list.add(retval);
++currentIndex;
++wrappedIteratorIndex;
return retval;
}
/**
* Returns in the index of the next element.
*
* @return the index of the next element
*/
public int nextIndex()
{
return currentIndex;
}
/**
* Returns the the previous element.
*
* @return the previous element
* @throws NoSuchElementException if there are no previous elements
*/
public Object previous() throws NoSuchElementException
{
if (currentIndex == 0)
{
throw new NoSuchElementException();
}
--currentIndex;
return list.get(currentIndex);
}
/**
* Returns the index of the previous element.
*
* @return the index of the previous element
*/
public int previousIndex()
{
return currentIndex - 1;
}
/**
* Throws {@link UnsupportedOperationException}.
*
* @throws UnsupportedOperationException always
*/
public void remove() throws UnsupportedOperationException
{
throw new UnsupportedOperationException(UNSUPPORTED_OPERATION_MESSAGE);
}
/**
* Throws {@link UnsupportedOperationException}.
*
* @param o ignored
* @throws UnsupportedOperationException always
*/
public void set(Object o) throws UnsupportedOperationException
{
throw new UnsupportedOperationException(UNSUPPORTED_OPERATION_MESSAGE);
}
}
| stefandmn/AREasy | src/java/org/areasy/common/data/type/iterator/ListIteratorWrapper.java | Java | lgpl-3.0 | 4,594 |
package com.iivan.imbg.dao.model;
public class User {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user.id
*
* @mbggenerated Tue Mar 18 12:06:46 CST 2014
*/
private Integer id;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user.name
*
* @mbggenerated Tue Mar 18 12:06:46 CST 2014
*/
private String name;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user.age
*
* @mbggenerated Tue Mar 18 12:06:46 CST 2014
*/
private Integer age;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user.sex
*
* @mbggenerated Tue Mar 18 12:06:46 CST 2014
*/
private Integer sex;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user.id
*
* @return the value of user.id
*
* @mbggenerated Tue Mar 18 12:06:46 CST 2014
*/
public Integer getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user.id
*
* @param id the value for user.id
*
* @mbggenerated Tue Mar 18 12:06:46 CST 2014
*/
public void setId(Integer id) {
this.id = id;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user.name
*
* @return the value of user.name
*
* @mbggenerated Tue Mar 18 12:06:46 CST 2014
*/
public String getName() {
return name;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user.name
*
* @param name the value for user.name
*
* @mbggenerated Tue Mar 18 12:06:46 CST 2014
*/
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user.age
*
* @return the value of user.age
*
* @mbggenerated Tue Mar 18 12:06:46 CST 2014
*/
public Integer getAge() {
return age;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user.age
*
* @param age the value for user.age
*
* @mbggenerated Tue Mar 18 12:06:46 CST 2014
*/
public void setAge(Integer age) {
this.age = age;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user.sex
*
* @return the value of user.sex
*
* @mbggenerated Tue Mar 18 12:06:46 CST 2014
*/
public Integer getSex() {
return sex;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user.sex
*
* @param sex the value for user.sex
*
* @mbggenerated Tue Mar 18 12:06:46 CST 2014
*/
public void setSex(Integer sex) {
this.sex = sex;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbggenerated Tue Mar 18 12:06:46 CST 2014
*/
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
User other = (User) that;
return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
&& (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName()))
&& (this.getAge() == null ? other.getAge() == null : this.getAge().equals(other.getAge()))
&& (this.getSex() == null ? other.getSex() == null : this.getSex().equals(other.getSex()));
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbggenerated Tue Mar 18 12:06:46 CST 2014
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
result = prime * result + ((getName() == null) ? 0 : getName().hashCode());
result = prime * result + ((getAge() == null) ? 0 : getAge().hashCode());
result = prime * result + ((getSex() == null) ? 0 : getSex().hashCode());
return result;
}
} | ivan-yin/imbg | src/main/java/com/iivan/imbg/dao/model/User.java | Java | lgpl-3.0 | 4,920 |
/* XXL: The eXtensible and fleXible Library for data processing
Copyright (C) 2000-2011 Prof. Dr. Bernhard Seeger
Head of the Database Research Group
Department of Mathematics and Computer Science
University of Marburg
Germany
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; If not, see <http://www.gnu.org/licenses/>.
http://code.google.com/p/xxl/
*/
package xxl.core.io;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import xxl.core.util.WrappingRuntimeException;
/**
* Conversion routines: byte array ↔ short, int, long.
* <br>
* There are some catogories of methods:
* <ul>
* <li>
* Methods with the suffix LE assume little endian byte ordering. Example for 4-Byte integers:<br>
* <code>01 00 00 00 = 1, 00 00 00 01 = 65536, 00 00 00 80 = -2147483648</code>
* </li>
* <li>
* Methods with the suffix BE assume big endian byte ordering (so far not supported!). Example for 4-Byte integers:<br>
* <code>01 00 00 00 = 16777216, 00 00 00 01 = 1, 00 00 00 80 = 128</code>
* </li>
* <li>
* Methods with the suffix Stream use streams to convert the types to byte arrays
* and back. These methode are usually much slower. Java uses big endian byte ordering.
* </li>
* <li>
* Other methods.
* </li>
* </ul>
*/
public class ByteArrayConversions
{
/**
* Do not allow instances of this class
*/
private ByteArrayConversions() {}
/**
* Converts the given byte to a short.
* @param b byte to convert.
* @return short.
*/
public static short conv255(byte b)
{
return (b<0)?(short) (256+b):(short)b;
}
/**
* Converts the given byte to a short.
* @param b byte to convert.
* @return short.
*/
public static short conv127(byte b)
{
return (short) (b&127);
}
/**
* Converts the byte array to a short. It is assumed that the array has a length of 2.
* @param b the byte array to convert.
* @return short.
*/
public static short convShortLE(byte b[])
{
// Variable kostet fast keine Zeit!
int zw = (conv127(b[1])<<8) | conv255(b[0]);
if (b[1]<0) // Vorzeichen
return (short) (zw - (1<<15));
else
return (short) zw;
}
/**
* Converts the byte array to a short. It is assumed that the array has a length of 2.
* @param b the byte array to convert.
* @param offset start if the integer inside the array.
* @return short.
*/
public static short convShortLE(byte b[], int offset)
{
// Variable kostet fast keine Zeit!
int zw = (conv127(b[offset+1])<<8) | conv255(b[offset]);
if (b[offset+1]<0) // Vorzeichen
return (short) (zw - (1<<15));
else
return (short) zw;
}
/**
* Converts the two given byte values to a short.
* @param b0 the 'left' byte value.
* @param b1 the 'right' byte value.
* @return short.
*/
public static short convShortLE(byte b0, byte b1)
{
// Variable kostet fast keine Zeit!
int zw = (conv127(b1)<<8) | conv255(b0);
if (b1 < 0) // Vorzeichen
return (short) (zw - (1<<15));
else
return (short) zw;
}
/**
* Converts the given byte to a short value.
* @param b the byte to convert.
* @return short.
*/
public static short convShortLE(byte b)
{
return conv255(b);
}
/**
* Converts the byte array to a short value.
* @param b the byte array.
* @return short.
*/
public static short convShortStream(byte b[])
{
try
{
ByteArrayOutputStream output = new ByteArrayOutputStream();
DataOutput out = new DataOutputStream(output);
out.write(b,0,b.length);
ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
DataInput in = new DataInputStream(input);
return in.readShort();
}
catch (IOException e) {
throw new WrappingRuntimeException(e);
}
}
/**
* Converts the given byte array to an int value. It is assumed that the byte
* array has a length of 4.
* @param b the byte array.
* @return int.
*/
public static int convIntLE(byte b[])
{
int zw = (((((conv127(b[3])<<8) | conv255(b[2]))<<8) | conv255(b[1]))<<8) | conv255(b[0]);
if (b[3]<0) // Vorzeichen
return zw - (1<<31);
else
return zw;
}
/**
* Converts the given byte array to an int value. It is assumed that the byte
* array has a length of 4.
* @param b the byte array.
* @param offset start offset inside the array.
* @return int.
*/
public static int convIntLE(byte b[], int offset)
{
int zw = (((((conv127(b[offset+3])<<8) | conv255(b[offset+2]))<<8) | conv255(b[offset+1]))<<8) | conv255(b[offset]);
if (b[offset+3]<0) // Vorzeichen
return zw - (1<<31);
else
return zw;
}
/**
* Convert the given bytes to an int value.
* @param b0 the 'outer left' byte value.
* @param b1 the byte value at the right of b0.
* @param b2 the byte value at the right of b1.
* @param b3 the byte value at the right of b2.
* @return int.
*/
public static int convIntLE(byte b0, byte b1, byte b2, byte b3)
{
int zw = (((((conv127(b3)<<8) | conv255(b2))<<8) | conv255(b1))<<8) | conv255(b0);
if (b3<0) // Vorzeichen
return zw - (1<<31);
else
return zw;
}
/**
* Convert the given bytes to an int value.
* @param b0 the 'left' byte value.
* @param b1 the 'right' byte value.
* @return int.
*/
public static int convIntLE(byte b0, byte b1)
{
return ((conv255(b1))<<8) | conv255(b0);
}
/**
* Convert the byte array to an int value.
* @param b the byte array.
* @return int.
*/
public static int convIntStream(byte b[])
{
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
DataOutput out = new DataOutputStream(output);
out.write(b,0,b.length);
ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
DataInput in = new DataInputStream(input);
return in.readInt();
}
catch (IOException e) {
throw new xxl.core.util.WrappingRuntimeException(e);
//return 0;
}
}
/**
* Convert the given byte array to a long value. It is assumed that the
* byte array has a length of 8.
* @param b the byte array.
* @return long.
*/
public static long convLongLE(byte b[])
{
long zw = ((long) conv127(b[7])<<56) | ((long) conv255(b[6])<<48) | ((long) conv255(b[5])<<40) | ((long) conv255(b[4])<<32) |
((long) conv255(b[3])<<24) | ((long) conv255(b[2])<<16) | ((long) conv255(b[1])<<8) | conv255(b[0]);
if (b[7]<0) // Vorzeichen
return zw - (((long) 1)<<63);
else
return zw;
}
/**
* Convert the given byte array to a long value. It is assumed that the
* byte array has a length of 8.
* @param b the byte array.
* @param offset start if the integer inside the array.
* @return long.
*/
public static long convLongLE(byte b[], int offset)
{
long zw = ((long) conv127(b[offset+7])<<56) | ((long) conv255(b[offset+6])<<48) | ((long) conv255(b[offset+5])<<40) | ((long) conv255(b[offset+4])<<32) |
((long) conv255(b[offset+3])<<24) | ((long) conv255(b[offset+2])<<16) | ((long) conv255(b[offset+1])<<8) | conv255(b[offset]);
if (b[offset+7]<0) // Vorzeichen
return zw - (((long) 1)<<63);
else
return zw;
}
/**
* Convert the given byte values to a long value.
* @param b0 the 'outer left' byte value.
* @param b1 the byte value at the right of b0.
* @param b2 the byte value at the right of b1.
* @param b3 the byte value at the right of b2.
* @param b4 the byte value at the right of b3.
* @param b5 the byte value at the right of b4.
* @param b6 the byte value at the right of b5.
* @param b7 the byte value at the right of b6.
* @return long.
*/
public static long convLongLE(byte b0, byte b1, byte b2, byte b3, byte b4, byte b5, byte b6, byte b7)
{
long zw = ((long) conv127(b7)<<56) | ((long) conv255(b6)<<48) | ((long) conv255(b5)<<40) | ((long) conv255(b4)<<32) |
((long) conv255(b3)<<24) | ((long) conv255(b2)<<16) | ((long) conv255(b1)<<8) | conv255(b0);
if (b7<0) // Vorzeichen
return zw - (((long) 1)<<63);
else
return zw;
}
/**
* Convert the given byte values to a long value.
* @param b0 lowest byte (byte 0)
* @param b1 byte 1
* @param b2 byte 2
* @param b3 hightest byte (byte 3)
* @return long.
*/
public static long convLongLE(byte b0, byte b1, byte b2, byte b3)
{
return ((long) conv255(b3)<<24) | ((long) conv255(b2)<<16) | ((long) conv255(b1)<<8) | conv255(b0);
}
/**
* Convert the byte array to an long value.
* @param b the byte array.
* @return long.
*/
public static long convLongStream(byte b[])
{
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
DataOutput out = new DataOutputStream(output);
out.write(b,0,b.length);
ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
DataInput in = new DataInputStream(input);
return in.readLong();
}
catch (IOException e) {
throw new xxl.core.util.WrappingRuntimeException(e);
//return 0;
}
}
/**
* Convert the integer to a byte array.
* @param i the integer value
* @param b array for the output.
*/
public static void convIntToByteArrayLE(int i, byte b[]) {
b[0] = (byte) (i&255);
i>>=8;
b[1] = (byte) (i&255);
i>>=8;
b[2] = (byte) (i&255);
i>>=8;
b[3] = (byte) (i&255);
}
/**
* Convert the integer to a byte array.
* @param i the integer value
* @param b array for the output.
* @param offset determines the location to which the values are written inside the byte array.
*/
public static void convIntToByteArrayLE(int i, byte b[], int offset) {
b[offset++] = (byte) (i&255);
i>>=8;
b[offset++] = (byte) (i&255);
i>>=8;
b[offset++] = (byte) (i&255);
i>>=8;
b[offset] = (byte) (i&255);
}
/**
* Convert the integer to a byte array.
* @param i the integer value
* @return byte array.
*/
public static byte[] convIntToByteArrayLE(int i) {
byte b[] = new byte[4];
convIntToByteArrayLE(i,b);
return b;
}
/**
* Convert the integer to a byte array.
* @param i the integer value
* @return byte array.
*/
public static byte[] convIntToByteArrayStream(int i) {
ByteArrayOutputStream bao = new ByteArrayOutputStream(4);
DataOutputStream dos = new DataOutputStream(bao);
try {
dos.writeInt(i);
dos.flush();
}
catch (IOException e) {
throw new WrappingRuntimeException(e);
}
return bao.toByteArray();
}
/**
* Convert the long to a byte array.
* @param l the long value
* @param b array for the output.
*/
public static void convLongToByteArrayLE(long l, byte b[]) {
b[0] = (byte) (l&255);
l>>=8;
b[1] = (byte) (l&255);
l>>=8;
b[2] = (byte) (l&255);
l>>=8;
b[3] = (byte) (l&255);
l>>=8;
b[4] = (byte) (l&255);
l>>=8;
b[5] = (byte) (l&255);
l>>=8;
b[6] = (byte) (l&255);
l>>=8;
b[7] = (byte) (l&255);
}
/**
* Convert the long to a byte array.
* @param l the long value
* @param b byte array for the output.
* @param offset determines the location to which the values are written inside the byte array.
*/
public static void convLongToByteArrayLE(long l, byte b[], int offset) {
b[offset++] = (byte) (l&255);
l>>=8;
b[offset++] = (byte) (l&255);
l>>=8;
b[offset++] = (byte) (l&255);
l>>=8;
b[offset++] = (byte) (l&255);
l>>=8;
b[offset++] = (byte) (l&255);
l>>=8;
b[offset++] = (byte) (l&255);
l>>=8;
b[offset++] = (byte) (l&255);
l>>=8;
b[offset] = (byte) (l&255);
}
/**
* Convert the long to a byte array.
* @param l the long value
* @return byte array.
*/
public static byte[] convLongToByteArrayLE(long l) {
byte b[] = new byte[8];
convLongToByteArrayLE(l,b);
return b;
}
/**
* Retun the string representation of the byte array. Starting at offset from (inclusive)
* until the index to (exclusive).
* @param b the byte array.
* @param from index (inclusive).
* @param to index (exclusive).
* @return a string representation of the byte array.
*/
public static String byteToString(byte[] b, int from, int to)
{
try {
//return new String(bpb, from, to-from, "US-ASCII");
return new String(b, from, to-from, "ISO-8859-1");
//return new String(bpb, from, from+2, "UTF-8");
//return new String(bpb, from, to-from, "UTF-16BE");
}
catch (UnsupportedEncodingException e) {
throw new WrappingRuntimeException(e);
}
}
/**
* Retun the unicode string representation of the byte array. Starting at
* offset from (inclusive) until the index to (exclusive).
* @param b the byte array.
* @param from index (inclusive).
* @param to index (exclusive).
* @return a unicode string representation of the byte array.
*/
public static String unicodeByteToString(byte[] b, int from, int to)
{
try {
return new String(b, from, to-from, "UTF-16LE");
}
catch (UnsupportedEncodingException e) {
throw new WrappingRuntimeException(e);
}
}
/**
* Converts a litte endian representation into a big endian
* representation and vice versa.
* @param b input byte array.
* @return converted byte array.
*/
public static byte[] endianConversion(byte b[]) {
byte bconv[] = new byte[b.length];
for (int i=0 ; i<b.length ; i++)
bconv[i] = b[b.length-1-i];
return bconv;
}
}
| hannoman/xxl | src/xxl/core/io/ByteArrayConversions.java | Java | lgpl-3.0 | 13,924 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-833
// 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: 2010.06.10 at 04:19:23 PM CEST
//
package nl.b3p.csw.jaxb.filter;
import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;
public class SpatialOps
extends JAXBElement<SpatialOpsType>
{
protected final static QName NAME = new QName("http://www.opengis.net/ogc", "spatialOps");
public SpatialOps(SpatialOpsType value) {
super(NAME, ((Class) SpatialOpsType.class), null, value);
}
public SpatialOps() {
super(NAME, ((Class) SpatialOpsType.class), null, null);
}
}
| B3Partners/b3p-commons-csw | src/main/java/nl/b3p/csw/jaxb/filter/SpatialOps.java | Java | lgpl-3.0 | 838 |
/*
* SchemaCrawler
* http://www.schemacrawler.com
* Copyright (c) 2000-2015, Sualeh Fatehi.
* This library is free software; you can redistribute it and/or modify it under
* the terms
* of the GNU Lesser General Public License as published by the Free Software
* Foundation;
* either version 2.1 of the License, or (at your option) any later version.
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with this
* library; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place, Suite 330,
* Boston, MA 02111-1307, USA.
*/
package schemacrawler.tools.integration.graph;
import static sf.util.Utility.containsWhitespace;
import static sf.util.Utility.readFully;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.logging.Level;
import java.util.logging.Logger;
public final class ProcessExecutor
{
final class StreamReader
implements Callable<String>
{
private final InputStream in;
private StreamReader(final InputStream in)
{
if (in == null)
{
throw new RuntimeException("No input stream provided");
}
this.in = in;
}
@Override
public String call()
throws Exception
{
final Reader reader = new BufferedReader(new InputStreamReader(in));
return readFully(reader);
}
}
private static final Logger LOGGER = Logger.getLogger(ProcessExecutor.class
.getName());
static private String createCommandLine(final List<String> command)
{
final StringBuilder sb = new StringBuilder();
boolean first = true;
for (final String arg: command)
{
if (first)
{
first = false;
}
else
{
sb.append(" ");
}
if (containsWhitespace(arg))
{
sb.append("\"").append(arg).append("\"");
}
else
{
sb.append(arg);
}
}
return sb.toString();
}
private final List<String> command;
private String processOutput;
private String processError;
public ProcessExecutor(final List<String> command)
throws IOException
{
if (command == null || command.isEmpty())
{
throw new RuntimeException("No command provided");
}
this.command = command;
LOGGER.log(Level.CONFIG, command.toString());
}
public int execute()
throws IOException
{
LOGGER.log(Level.CONFIG, "Executing:\n" + createCommandLine(command));
final ExecutorService threadPool = Executors.newFixedThreadPool(2);
try
{
final ProcessBuilder processBuilder = new ProcessBuilder(command);
final Process process = processBuilder.start();
final FutureTask<String> inReaderTask = new FutureTask<>(new StreamReader(process
.getInputStream()));
threadPool.execute(inReaderTask);
final FutureTask<String> errReaderTask = new FutureTask<>(new StreamReader(process
.getErrorStream()));
threadPool.execute(errReaderTask);
final int exitCode = process.waitFor();
processOutput = inReaderTask.get();
processError = errReaderTask.get();
return exitCode;
}
catch (final SecurityException | ExecutionException | InterruptedException e)
{
throw new IOException(e.getMessage(), e);
}
finally
{
threadPool.shutdown();
}
}
public String getProcessError()
{
return processError;
}
public String getProcessOutput()
{
return processOutput;
}
}
| ceharris/SchemaCrawler | schemacrawler-tools/src/main/java/schemacrawler/tools/integration/graph/ProcessExecutor.java | Java | lgpl-3.0 | 4,054 |
/*
* SquirrelID, a UUID library for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) SquirrelID team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.squirrelid.cache;
import com.google.common.collect.ImmutableMap;
import com.sk89q.squirrelid.Profile;
import javax.annotation.Nullable;
import java.util.UUID;
/**
* Stores a "last known" mapping of UUIDs to names.
*/
public interface ProfileCache {
/**
* Store the given name as the last known name for the given UUID.
*
* <p>If the operation fails, an error will be logged but no exception
* will be thrown.</p>
*
* @param profile a profile
*/
void put(Profile profile);
/**
* Store a list of zero or more names.
*
* <p>If the operation fails, an error will be logged but no exception
* will be thrown.</p>
*
* @param profiles an iterable of profiles
*/
void putAll(Iterable<Profile> profiles);
/**
* Query the cache for the name for a given UUID.
*
* <p>If the operation fails, an error will be logged but no exception
* will be thrown.</p>
*
* @param uuid the UUID
* @return the name or {@code null} if it is not known
*/
@Nullable
Profile getIfPresent(UUID uuid);
/**
* Query the cache for the names of the given UUIDs.
*
* <p>If the operation fails, an error will be logged but no exception
* will be thrown.</p>
*
* @param ids a list of UUIDs to query
* @return a map of results, which may not have a key for every given UUID
*/
ImmutableMap<UUID, Profile> getAllPresent(Iterable<UUID> ids);
}
| TealCube/SquirrelID | src/main/java/com/sk89q/squirrelid/cache/ProfileCache.java | Java | lgpl-3.0 | 2,330 |
/* XXL: The eXtensible and fleXible Library for data processing
Copyright (C) 2000-2011 Prof. Dr. Bernhard Seeger
Head of the Database Research Group
Department of Mathematics and Computer Science
University of Marburg
Germany
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; If not, see <http://www.gnu.org/licenses/>.
http://code.google.com/p/xxl/
*/
package xxl.core.io;
import java.io.OutputStream;
/**
* This class provides an output stream pointing to a NULL sink, i.e., all
* output will be suppressed.
*
* @see xxl.core.util.XXLSystem#NULL
*/
public class NullOutputStream extends OutputStream{
/** Provides a ready-to-use {@link java.io.OutputStream OutputStream} representing
* a null device, i.e., a dummy sink.
*
* @see java.lang.System#out
* @see java.lang.System#err
*/
public static final OutputStream NULL = new NullOutputStream();
/**
* Don't let anyone instantiate this class (singleton pattern).
*/
private NullOutputStream(){}
/**
* Closes the stream.
*/
public void close() {}
/**
* Flushes the stream (not necessary to call here).
*/
public void flush() {}
/**
* Writes the byte array to the NullOutputStream.
* @param b
*/
public void write(byte[] b) {}
/**
* Writes the byte array to the NullOutputStream.
* @param b the array
* @param off the offset
* @param len the number of bytes written.
*/
public void write(byte[] b, int off, int len) {}
/**
* Writes the byte to the NullOutputStream.
* @param b the value of the byte.
*/
public void write(int b) {}
}
| hannoman/xxl | src/xxl/core/io/NullOutputStream.java | Java | lgpl-3.0 | 2,203 |
package wangdaye.com.geometricweather.common.basic.models.options._utils;
import android.content.res.Resources;
import androidx.annotation.ArrayRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
public class Utils {
@Nullable
public static String getNameByValue(Resources res, String value,
@ArrayRes int nameArrayId, @ArrayRes int valueArrayId) {
String[] names = res.getStringArray(nameArrayId);
String[] values = res.getStringArray(valueArrayId);
return getNameByValue(value, names, values);
}
@Nullable
private static String getNameByValue(String value,
@NonNull String[] names,
@NonNull String[] values) {
if (names.length != values.length) {
throw new RuntimeException("The length of names and values must be same.");
}
for (int i = 0; i < values.length; i ++) {
if (values[i].equals(value)) {
return names[i];
}
}
return null;
}
}
| WangDaYeeeeee/GeometricWeather | app/src/main/java/wangdaye/com/geometricweather/common/basic/models/options/_utils/Utils.java | Java | lgpl-3.0 | 1,132 |
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2013 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* SonarQube is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.core.issue;
import org.junit.Test;
import org.sonar.api.issue.ActionPlan;
import org.sonar.api.issue.internal.DefaultIssue;
import org.sonar.api.issue.internal.FieldDiffs;
import org.sonar.api.issue.internal.IssueChangeContext;
import org.sonar.api.user.User;
import org.sonar.api.utils.internal.WorkDuration;
import org.sonar.core.user.DefaultUser;
import java.util.Date;
import static org.fest.assertions.Assertions.assertThat;
import static org.sonar.core.issue.IssueUpdater.*;
public class IssueUpdaterTest {
IssueUpdater updater = new IssueUpdater();
DefaultIssue issue = new DefaultIssue();
IssueChangeContext context = IssueChangeContext.createUser(new Date(), "emmerik");
@Test
public void assign() throws Exception {
User user = new DefaultUser().setLogin("emmerik").setName("Emmerik");
boolean updated = updater.assign(issue, user, context);
assertThat(updated).isTrue();
assertThat(issue.assignee()).isEqualTo("emmerik");
assertThat(issue.mustSendNotifications()).isTrue();
FieldDiffs.Diff diff = issue.currentChange().get(ASSIGNEE);
assertThat(diff.oldValue()).isEqualTo(UNUSED);
assertThat(diff.newValue()).isEqualTo("Emmerik");
}
@Test
public void unassign() throws Exception {
issue.setAssignee("morgan");
boolean updated = updater.assign(issue, null, context);
assertThat(updated).isTrue();
assertThat(issue.assignee()).isNull();
assertThat(issue.mustSendNotifications()).isTrue();
FieldDiffs.Diff diff = issue.currentChange().get(ASSIGNEE);
assertThat(diff.oldValue()).isEqualTo(UNUSED);
assertThat(diff.newValue()).isNull();
}
@Test
public void change_assignee() throws Exception {
User user = new DefaultUser().setLogin("emmerik").setName("Emmerik");
issue.setAssignee("morgan");
boolean updated = updater.assign(issue, user, context);
assertThat(updated).isTrue();
assertThat(issue.assignee()).isEqualTo("emmerik");
assertThat(issue.mustSendNotifications()).isTrue();
FieldDiffs.Diff diff = issue.currentChange().get(ASSIGNEE);
assertThat(diff.oldValue()).isEqualTo(UNUSED);
assertThat(diff.newValue()).isEqualTo("Emmerik");
}
@Test
public void not_change_assignee() throws Exception {
User user = new DefaultUser().setLogin("morgan").setName("Morgan");
issue.setAssignee("morgan");
boolean updated = updater.assign(issue, user, context);
assertThat(updated).isFalse();
assertThat(issue.currentChange()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void set_severity() throws Exception {
boolean updated = updater.setSeverity(issue, "BLOCKER", context);
assertThat(updated).isTrue();
assertThat(issue.severity()).isEqualTo("BLOCKER");
assertThat(issue.manualSeverity()).isFalse();
assertThat(issue.mustSendNotifications()).isFalse();
FieldDiffs.Diff diff = issue.currentChange().get(SEVERITY);
assertThat(diff.oldValue()).isNull();
assertThat(diff.newValue()).isEqualTo("BLOCKER");
}
@Test
public void set_past_severity() throws Exception {
issue.setSeverity("BLOCKER");
boolean updated = updater.setPastSeverity(issue, "INFO", context);
assertThat(updated).isTrue();
assertThat(issue.severity()).isEqualTo("BLOCKER");
assertThat(issue.mustSendNotifications()).isFalse();
FieldDiffs.Diff diff = issue.currentChange().get(SEVERITY);
assertThat(diff.oldValue()).isEqualTo("INFO");
assertThat(diff.newValue()).isEqualTo("BLOCKER");
}
@Test
public void update_severity() throws Exception {
issue.setSeverity("BLOCKER");
boolean updated = updater.setSeverity(issue, "MINOR", context);
assertThat(updated).isTrue();
assertThat(issue.severity()).isEqualTo("MINOR");
assertThat(issue.mustSendNotifications()).isFalse();
FieldDiffs.Diff diff = issue.currentChange().get(SEVERITY);
assertThat(diff.oldValue()).isEqualTo("BLOCKER");
assertThat(diff.newValue()).isEqualTo("MINOR");
}
@Test
public void not_change_severity() throws Exception {
issue.setSeverity("MINOR");
boolean updated = updater.setSeverity(issue, "MINOR", context);
assertThat(updated).isFalse();
assertThat(issue.mustSendNotifications()).isFalse();
assertThat(issue.currentChange()).isNull();
}
@Test
public void not_revert_manual_severity() throws Exception {
issue.setSeverity("MINOR").setManualSeverity(true);
try {
updater.setSeverity(issue, "MAJOR", context);
} catch (IllegalStateException e) {
assertThat(e).hasMessage("Severity can't be changed");
}
}
@Test
public void set_manual_severity() throws Exception {
issue.setSeverity("BLOCKER");
boolean updated = updater.setManualSeverity(issue, "MINOR", context);
assertThat(updated).isTrue();
assertThat(issue.severity()).isEqualTo("MINOR");
assertThat(issue.manualSeverity()).isTrue();
assertThat(issue.mustSendNotifications()).isTrue();
FieldDiffs.Diff diff = issue.currentChange().get(SEVERITY);
assertThat(diff.oldValue()).isEqualTo("BLOCKER");
assertThat(diff.newValue()).isEqualTo("MINOR");
}
@Test
public void not_change_manual_severity() throws Exception {
issue.setSeverity("MINOR").setManualSeverity(true);
boolean updated = updater.setManualSeverity(issue, "MINOR", context);
assertThat(updated).isFalse();
assertThat(issue.currentChange()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void set_line() throws Exception {
boolean updated = updater.setLine(issue, 123);
assertThat(updated).isTrue();
assertThat(issue.line()).isEqualTo(123);
assertThat(issue.mustSendNotifications()).isFalse();
// do not save change
assertThat(issue.currentChange()).isNull();
}
@Test
public void set_past_line() throws Exception {
issue.setLine(42);
boolean updated = updater.setPastLine(issue, 123);
assertThat(updated).isTrue();
assertThat(issue.line()).isEqualTo(42);
assertThat(issue.mustSendNotifications()).isFalse();
// do not save change
assertThat(issue.currentChange()).isNull();
}
@Test
public void not_change_line() throws Exception {
issue.setLine(123);
boolean updated = updater.setLine(issue, 123);
assertThat(updated).isFalse();
assertThat(issue.line()).isEqualTo(123);
assertThat(issue.currentChange()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void set_resolution() throws Exception {
boolean updated = updater.setResolution(issue, "OPEN", context);
assertThat(updated).isTrue();
assertThat(issue.resolution()).isEqualTo("OPEN");
FieldDiffs.Diff diff = issue.currentChange().get(RESOLUTION);
assertThat(diff.oldValue()).isNull();
assertThat(diff.newValue()).isEqualTo("OPEN");
assertThat(issue.mustSendNotifications()).isTrue();
}
@Test
public void not_change_resolution() throws Exception {
issue.setResolution("FIXED");
boolean updated = updater.setResolution(issue, "FIXED", context);
assertThat(updated).isFalse();
assertThat(issue.resolution()).isEqualTo("FIXED");
assertThat(issue.currentChange()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void set_status() throws Exception {
boolean updated = updater.setStatus(issue, "OPEN", context);
assertThat(updated).isTrue();
assertThat(issue.status()).isEqualTo("OPEN");
FieldDiffs.Diff diff = issue.currentChange().get(STATUS);
assertThat(diff.oldValue()).isNull();
assertThat(diff.newValue()).isEqualTo("OPEN");
assertThat(issue.mustSendNotifications()).isTrue();
}
@Test
public void not_change_status() throws Exception {
issue.setStatus("CLOSED");
boolean updated = updater.setStatus(issue, "CLOSED", context);
assertThat(updated).isFalse();
assertThat(issue.status()).isEqualTo("CLOSED");
assertThat(issue.currentChange()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void set_new_attribute_value() throws Exception {
boolean updated = updater.setAttribute(issue, "JIRA", "FOO-123", context);
assertThat(updated).isTrue();
assertThat(issue.attribute("JIRA")).isEqualTo("FOO-123");
assertThat(issue.currentChange().diffs()).hasSize(1);
assertThat(issue.currentChange().get("JIRA").oldValue()).isNull();
assertThat(issue.currentChange().get("JIRA").newValue()).isEqualTo("FOO-123");
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void unset_attribute() throws Exception {
issue.setAttribute("JIRA", "FOO-123");
boolean updated = updater.setAttribute(issue, "JIRA", null, context);
assertThat(updated).isTrue();
assertThat(issue.attribute("JIRA")).isNull();
assertThat(issue.currentChange().diffs()).hasSize(1);
assertThat(issue.currentChange().get("JIRA").oldValue()).isEqualTo("FOO-123");
assertThat(issue.currentChange().get("JIRA").newValue()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void not_update_attribute() throws Exception {
issue.setAttribute("JIRA", "FOO-123");
boolean updated = updater.setAttribute(issue, "JIRA", "FOO-123", context);
assertThat(updated).isFalse();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void plan_with_no_existing_plan() throws Exception {
ActionPlan newActionPlan = DefaultActionPlan.create("newName");
boolean updated = updater.plan(issue, newActionPlan, context);
assertThat(updated).isTrue();
assertThat(issue.actionPlanKey()).isEqualTo(newActionPlan.key());
FieldDiffs.Diff diff = issue.currentChange().get(ACTION_PLAN);
assertThat(diff.oldValue()).isEqualTo(UNUSED);
assertThat(diff.newValue()).isEqualTo("newName");
assertThat(issue.mustSendNotifications()).isTrue();
}
@Test
public void plan_with_existing_plan() throws Exception {
issue.setActionPlanKey("formerActionPlan");
ActionPlan newActionPlan = DefaultActionPlan.create("newName").setKey("newKey");
boolean updated = updater.plan(issue, newActionPlan, context);
assertThat(updated).isTrue();
assertThat(issue.actionPlanKey()).isEqualTo(newActionPlan.key());
FieldDiffs.Diff diff = issue.currentChange().get(ACTION_PLAN);
assertThat(diff.oldValue()).isEqualTo(UNUSED);
assertThat(diff.newValue()).isEqualTo("newName");
assertThat(issue.mustSendNotifications()).isTrue();
}
@Test
public void unplan() throws Exception {
issue.setActionPlanKey("formerActionPlan");
boolean updated = updater.plan(issue, null, context);
assertThat(updated).isTrue();
assertThat(issue.actionPlanKey()).isNull();
FieldDiffs.Diff diff = issue.currentChange().get(ACTION_PLAN);
assertThat(diff.oldValue()).isEqualTo(UNUSED);
assertThat(diff.newValue()).isNull();
assertThat(issue.mustSendNotifications()).isTrue();
}
@Test
public void not_plan_again() throws Exception {
issue.setActionPlanKey("existingActionPlan");
ActionPlan newActionPlan = DefaultActionPlan.create("existingActionPlan").setKey("existingActionPlan");
boolean updated = updater.plan(issue, newActionPlan, context);
assertThat(updated).isFalse();
assertThat(issue.currentChange()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void set_effort_to_fix() throws Exception {
boolean updated = updater.setEffortToFix(issue, 3.14, context);
assertThat(updated).isTrue();
assertThat(issue.isChanged()).isTrue();
assertThat(issue.effortToFix()).isEqualTo(3.14);
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void not_set_effort_to_fix_if_unchanged() throws Exception {
issue.setEffortToFix(3.14);
boolean updated = updater.setEffortToFix(issue, 3.14, context);
assertThat(updated).isFalse();
assertThat(issue.isChanged()).isFalse();
assertThat(issue.effortToFix()).isEqualTo(3.14);
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void set_past_effort() throws Exception {
issue.setEffortToFix(3.14);
boolean updated = updater.setPastEffortToFix(issue, 1.0, context);
assertThat(updated).isTrue();
assertThat(issue.effortToFix()).isEqualTo(3.14);
// do not save change
assertThat(issue.currentChange()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void set_past_technical_debt() throws Exception {
WorkDuration newDebt = WorkDuration.createFromValueAndUnit(15, WorkDuration.UNIT.DAYS, 8);
WorkDuration previousDebt = WorkDuration.createFromValueAndUnit(10, WorkDuration.UNIT.DAYS, 8);
issue.setTechnicalDebt(newDebt);
boolean updated = updater.setPastTechnicalDebt(issue, previousDebt, context);
assertThat(updated).isTrue();
assertThat(issue.technicalDebt()).isEqualTo(newDebt);
assertThat(issue.mustSendNotifications()).isFalse();
FieldDiffs.Diff diff = issue.currentChange().get(TECHNICAL_DEBT);
assertThat(diff.oldValue()).isEqualTo(previousDebt.toLong());
assertThat(diff.newValue()).isEqualTo(newDebt.toLong());
}
@Test
public void set_past_technical_debt_without_previous_value() throws Exception {
WorkDuration newDebt = WorkDuration.createFromValueAndUnit(15, WorkDuration.UNIT.DAYS, 8);
issue.setTechnicalDebt(newDebt);
boolean updated = updater.setPastTechnicalDebt(issue, null, context);
assertThat(updated).isTrue();
assertThat(issue.technicalDebt()).isEqualTo(newDebt);
assertThat(issue.mustSendNotifications()).isFalse();
FieldDiffs.Diff diff = issue.currentChange().get(TECHNICAL_DEBT);
assertThat(diff.oldValue()).isNull();
assertThat(diff.newValue()).isEqualTo(newDebt.toLong());
}
@Test
public void set_past_technical_debt_with_null_new_value() throws Exception {
issue.setTechnicalDebt(null);
WorkDuration previousDebt = WorkDuration.createFromValueAndUnit(10, WorkDuration.UNIT.DAYS, 8);
boolean updated = updater.setPastTechnicalDebt(issue, previousDebt, context);
assertThat(updated).isTrue();
assertThat(issue.technicalDebt()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
FieldDiffs.Diff diff = issue.currentChange().get(TECHNICAL_DEBT);
assertThat(diff.oldValue()).isEqualTo(previousDebt.toLong());
assertThat(diff.newValue()).isNull();
}
@Test
public void set_message() throws Exception {
boolean updated = updater.setMessage(issue, "the message", context);
assertThat(updated).isTrue();
assertThat(issue.isChanged()).isTrue();
assertThat(issue.message()).isEqualTo("the message");
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void set_past_message() throws Exception {
issue.setMessage("new message");
boolean updated = updater.setPastMessage(issue, "past message", context);
assertThat(updated).isTrue();
assertThat(issue.message()).isEqualTo("new message");
// do not save change
assertThat(issue.currentChange()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void set_author() throws Exception {
boolean updated = updater.setAuthorLogin(issue, "eric", context);
assertThat(updated).isTrue();
assertThat(issue.authorLogin()).isEqualTo("eric");
FieldDiffs.Diff diff = issue.currentChange().get("author");
assertThat(diff.oldValue()).isNull();
assertThat(diff.newValue()).isEqualTo("eric");
assertThat(issue.mustSendNotifications()).isFalse();
}
}
| xinghuangxu/xinghuangxu.sonarqube | sonar-core/src/test/java/org/sonar/core/issue/IssueUpdaterTest.java | Java | lgpl-3.0 | 16,583 |
/*
* Sonar, open source software quality management tool.
* Copyright (C) 2008-2012 SonarSource
* mailto:contact AT sonarsource DOT com
*
* Sonar is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* Sonar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Sonar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.api.web;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @since 1.11
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface UserRole {
/**
* @deprecated use the constant USER since 1.12.
*/
@Deprecated
String VIEWER = "user";
String USER = "user";
String ADMIN = "admin";
String CODEVIEWER = "codeviewer";
String[] value() default {};
} | jmecosta/sonar | sonar-plugin-api/src/main/java/org/sonar/api/web/UserRole.java | Java | lgpl-3.0 | 1,380 |
/*
* This file is part of RedstoneLamp.
*
* RedstoneLamp 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.
*
* RedstoneLamp 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 RedstoneLamp. If not, see <http://www.gnu.org/licenses/>.
*/
package net.redstonelamp.cmd.defaults;
import net.redstonelamp.Player;
import net.redstonelamp.RedstoneLamp;
import net.redstonelamp.cmd.Command;
import net.redstonelamp.cmd.CommandExecutor;
import net.redstonelamp.cmd.CommandSender;
import net.redstonelamp.utils.TextFormat;
public class KickCommand implements CommandExecutor {
private static final String KICK_PERMISSION = "redstonelamp.command.player.kick";
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if(label.equalsIgnoreCase("kick")) {
if(sender.hasPermission(KICK_PERMISSION)) {
if(args.length >= 1) {
Player player = RedstoneLamp.SERVER.getPlayer(args[0]);
if(player == null) {
sender.sendMessage(TextFormat.RED + "Unable to find the player " + args[0]);
return true;
}
sender.sendMessage("Kicked " + args[0]);
String kickMessage = (args.length >= 2 ? args[1] : "Kicked by an operator");
player.close(" was kicked from the game", kickMessage, true);
return true;
}
return false;
}
else {
sender.sendMessage(TextFormat.DARK_RED + "You do not have permission!");
return true;
}
}
return false;
}
}
| MCPEGamerJPatGitHub/RedstoneLamp | src/main/java/net/redstonelamp/cmd/defaults/KickCommand.java | Java | lgpl-3.0 | 1,924 |
package edu.ucsd.arcum.interpreter.ast;
import edu.ucsd.arcum.exceptions.SourceLocation;
public class MapAmbiguousArgument extends MapNameValueBinding
{
private String body;
public MapAmbiguousArgument(SourceLocation location, String name, String body) {
super(location, name);
this.body = body;
}
@Override
public String toString() {
return getName() + ": \'" + body + "\'";
}
public String getBody() {
return body;
}
@Override
public Object getValue() {
throw new RuntimeException("Value read on an ambiguous element");
}
} | mshonle/Arcum | src/edu/ucsd/arcum/interpreter/ast/MapAmbiguousArgument.java | Java | lgpl-3.0 | 641 |
/*
* This file is part of Gaia Sky, which is released under the Mozilla Public License 2.0.
* See the file LICENSE.md in the project root for full license details.
*/
package gaiasky.interafce;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Graphics.DisplayMode;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.controllers.Controller;
import com.badlogic.gdx.controllers.Controllers;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.EventListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.*;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener.ChangeEvent;
import com.badlogic.gdx.utils.Align;
import com.badlogic.gdx.utils.Array;
import gaiasky.GaiaSky;
import gaiasky.desktop.util.SysUtils;
import gaiasky.event.EventManager;
import gaiasky.event.Events;
import gaiasky.event.IObserver;
import gaiasky.interafce.KeyBindings.ProgramAction;
import gaiasky.interafce.beans.*;
import gaiasky.screenshot.ImageRenderer;
import gaiasky.util.*;
import gaiasky.util.GlobalConf.PostprocessConf.Antialias;
import gaiasky.util.GlobalConf.PostprocessConf.ToneMapping;
import gaiasky.util.GlobalConf.ProgramConf.ShowCriterion;
import gaiasky.util.GlobalConf.SceneConf.ElevationType;
import gaiasky.util.GlobalConf.SceneConf.GraphicsQuality;
import gaiasky.util.GlobalConf.ScreenshotMode;
import gaiasky.util.Logger.Log;
import gaiasky.util.datadesc.DataDescriptor;
import gaiasky.util.datadesc.DataDescriptorUtils;
import gaiasky.util.format.INumberFormat;
import gaiasky.util.format.NumberFormatFactory;
import gaiasky.util.math.MathUtilsd;
import gaiasky.util.parse.Parser;
import gaiasky.util.scene2d.*;
import gaiasky.util.validator.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Locale;
import java.util.Map;
import java.util.TreeSet;
/**
* The default preferences window.
*
* @author tsagrista
*/
public class PreferencesWindow extends GenericDialog implements IObserver {
private static Log logger = Logger.getLogger(PreferencesWindow.class);
// Remember the last tab opened
private static OwnTextIconButton lastTab;
private static boolean lastTabFlag = true;
private Array<Actor> contents;
private Array<OwnLabel> labels;
private IValidator widthValidator, heightValidator, screenshotsSizeValidator, frameoutputSizeValidator, limitfpsValidator;
private INumberFormat nf3, nf1;
private CheckBox fullscreen, windowed, vsync, limitfpsCb, multithreadCb, lodFadeCb, cbAutoCamrec, real, nsl, invertx, inverty, highAccuracyPositions, shadowsCb, hidpiCb, pointerCoords, datasetChooserDefault, datasetChooserAlways, datasetChooserNever, debugInfo, crosshairFocusCb, crosshairClosestCb, crosshairHomeCb, pointerGuidesCb, exitConfirmation;
private OwnSelectBox<DisplayMode> fullscreenResolutions;
private OwnSelectBox<ComboBoxBean> gquality, aa, orbitRenderer, lineRenderer, numThreads, screenshotMode, frameoutputMode, nshadows;
private OwnSelectBox<LangComboBoxBean> lang;
private OwnSelectBox<ElevationComboBoxBean> elevationSb;
private OwnSelectBox<String> theme;
private OwnSelectBox<FileComboBoxBean> controllerMappings;
private OwnTextField widthField, heightField, sswidthField, ssheightField, frameoutputPrefix, frameoutputFps, fowidthField, foheightField, camrecFps, cmResolution, plResolution, plAperture, plAngle, smResolution, limitFps;
private OwnSlider lodTransitions, tessQuality, minimapSize, pointerGuidesWidth;
private OwnTextButton screenshotsLocation, frameoutputLocation;
private ColorPicker pointerGuidesColor;
private DatasetsWidget dw;
private OwnLabel tessQualityLabel;
private Cell noticeHiResCell;
private Table controllersTable;
// Backup values
private ToneMapping toneMappingBak;
private float brightnessBak, contrastBak, hueBak, saturationBak, gammaBak, exposureBak, bloomBak;
private boolean lensflareBak, lightglowBak, debugInfoBak, motionblurBak;
public PreferencesWindow(Stage stage, Skin skin) {
super(I18n.txt("gui.settings") + " - " + GlobalConf.version.version + " - " + I18n.txt("gui.build", GlobalConf.version.build), skin, stage);
this.contents = new Array<>();
this.labels = new Array<>();
this.nf1 = NumberFormatFactory.getFormatter("0.0");
this.nf3 = NumberFormatFactory.getFormatter("0.000");
setAcceptText(I18n.txt("gui.saveprefs"));
setCancelText(I18n.txt("gui.cancel"));
// Build UI
buildSuper();
EventManager.instance.subscribe(this, Events.CONTROLLER_CONNECTED_INFO, Events.CONTROLLER_DISCONNECTED_INFO);
}
@Override
protected void build() {
float contentw = 700f * GlobalConf.UI_SCALE_FACTOR;
float contenth = 700f * GlobalConf.UI_SCALE_FACTOR;
final float tawidth = 600f * GlobalConf.UI_SCALE_FACTOR;
float tabwidth = (GlobalConf.isHiDPI() ? 200f : 200f) * GlobalConf.UI_SCALE_FACTOR;
float textwidth = 65f * GlobalConf.UI_SCALE_FACTOR;
float scrollh = 400f * GlobalConf.UI_SCALE_FACTOR;
float controlsscrollw = 450f * GlobalConf.UI_SCALE_FACTOR;
float controllsscrollh = 250f * GlobalConf.UI_SCALE_FACTOR;
float sliderWidth = textwidth * 3f;
// Create the tab buttons
VerticalGroup group = new VerticalGroup();
group.align(Align.left | Align.top);
final OwnTextIconButton tabGraphics = new OwnTextIconButton(I18n.txt("gui.graphicssettings"), new Image(skin.getDrawable("iconic-bolt")), skin, "toggle-big");
tabGraphics.pad(pad5);
tabGraphics.setWidth(tabwidth);
final OwnTextIconButton tabUI = new OwnTextIconButton(I18n.txt("gui.ui.interfacesettings"), new Image(skin.getDrawable("iconic-browser")), skin, "toggle-big");
tabUI.pad(pad5);
tabUI.setWidth(tabwidth);
final OwnTextIconButton tabPerformance = new OwnTextIconButton(I18n.txt("gui.performance"), new Image(skin.getDrawable("iconic-dial")), skin, "toggle-big");
tabPerformance.pad(pad5);
tabPerformance.setWidth(tabwidth);
final OwnTextIconButton tabControls = new OwnTextIconButton(I18n.txt("gui.controls"), new Image(skin.getDrawable("iconic-laptop")), skin, "toggle-big");
tabControls.pad(pad5);
tabControls.setWidth(tabwidth);
final OwnTextIconButton tabScreenshots = new OwnTextIconButton(I18n.txt("gui.screenshots"), new Image(skin.getDrawable("iconic-image")), skin, "toggle-big");
tabScreenshots.pad(pad5);
tabScreenshots.setWidth(tabwidth);
final OwnTextIconButton tabFrames = new OwnTextIconButton(I18n.txt("gui.frameoutput.title"), new Image(skin.getDrawable("iconic-layers")), skin, "toggle-big");
tabFrames.pad(pad5);
tabFrames.setWidth(tabwidth);
final OwnTextIconButton tabCamera = new OwnTextIconButton(I18n.txt("gui.camerarec.title"), new Image(skin.getDrawable("iconic-camera-slr")), skin, "toggle-big");
tabCamera.pad(pad5);
tabCamera.setWidth(tabwidth);
final OwnTextIconButton tab360 = new OwnTextIconButton(I18n.txt("gui.360.title"), new Image(skin.getDrawable("iconic-cubemap")), skin, "toggle-big");
tab360.pad(pad5);
tab360.setWidth(tabwidth);
final OwnTextIconButton tabPlanetarium = new OwnTextIconButton(I18n.txt("gui.planetarium.title"), new Image(skin.getDrawable("iconic-dome")), skin, "toggle-big");
tabPlanetarium.pad(pad5);
tabPlanetarium.setWidth(tabwidth);
final OwnTextIconButton tabData = new OwnTextIconButton(I18n.txt("gui.data"), new Image(skin.getDrawable("iconic-clipboard")), skin, "toggle-big");
tabData.pad(pad5);
tabData.setWidth(tabwidth);
final OwnTextIconButton tabGaia = new OwnTextIconButton(I18n.txt("gui.gaia"), new Image(skin.getDrawable("iconic-gaia")), skin, "toggle-big");
tabGaia.pad(pad5);
tabGaia.setWidth(tabwidth);
final OwnTextIconButton tabSystem = new OwnTextIconButton(I18n.txt("gui.system"), new Image(skin.getDrawable("iconic-terminal")), skin, "toggle-big");
tabSystem.pad(pad5);
tabSystem.setWidth(tabwidth);
group.addActor(tabGraphics);
group.addActor(tabUI);
group.addActor(tabPerformance);
group.addActor(tabControls);
group.addActor(tabScreenshots);
group.addActor(tabFrames);
group.addActor(tabCamera);
group.addActor(tab360);
group.addActor(tabPlanetarium);
group.addActor(tabData);
group.addActor(tabGaia);
group.addActor(tabSystem);
content.add(group).align(Align.left | Align.top).padLeft(pad5);
// Create the tab content. Just using images here for simplicity.
Stack tabContent = new Stack();
tabContent.setSize(contentw, contenth);
/*
* ==== GRAPHICS ====
*/
final Table contentGraphicsTable = new Table(skin);
final OwnScrollPane contentGraphics = new OwnScrollPane(contentGraphicsTable, skin, "minimalist-nobg");
contentGraphics.setHeight(scrollh);
contentGraphics.setScrollingDisabled(true, false);
contentGraphics.setFadeScrollBars(false);
contents.add(contentGraphics);
contentGraphicsTable.align(Align.top | Align.left);
// RESOLUTION/MODE
Label titleResolution = new OwnLabel(I18n.txt("gui.resolutionmode"), skin, "header");
Table mode = new Table();
// Full screen mode resolutions
Array<DisplayMode> modes = new Array<>(Gdx.graphics.getDisplayModes());
modes.sort((o1, o2) -> Integer.compare(o2.height * o2.width, o1.height * o1.width));
fullscreenResolutions = new OwnSelectBox<>(skin);
fullscreenResolutions.setWidth(textwidth * 3.3f);
fullscreenResolutions.setItems(modes);
DisplayMode selectedMode = null;
for (DisplayMode dm : modes) {
if (dm.width == GlobalConf.screen.FULLSCREEN_WIDTH && dm.height == GlobalConf.screen.FULLSCREEN_HEIGHT) {
selectedMode = dm;
break;
}
}
if (selectedMode != null)
fullscreenResolutions.setSelected(selectedMode);
// Get current resolution
Table windowedResolutions = new Table(skin);
DisplayMode nativeMode = Gdx.graphics.getDisplayMode();
widthValidator = new IntValidator(100, 10000);
widthField = new OwnTextField(Integer.toString(MathUtils.clamp(GlobalConf.screen.SCREEN_WIDTH, 100, 10000)), skin, widthValidator);
widthField.setWidth(textwidth);
heightValidator = new IntValidator(100, 10000);
heightField = new OwnTextField(Integer.toString(MathUtils.clamp(GlobalConf.screen.SCREEN_HEIGHT, 100, 10000)), skin, heightValidator);
heightField.setWidth(textwidth);
final OwnLabel widthLabel = new OwnLabel(I18n.txt("gui.width") + ":", skin);
final OwnLabel heightLabel = new OwnLabel(I18n.txt("gui.height") + ":", skin);
windowedResolutions.add(widthLabel).left().padRight(pad5);
windowedResolutions.add(widthField).left().padRight(pad5);
windowedResolutions.add(heightLabel).left().padRight(pad5);
windowedResolutions.add(heightField).left().row();
// Radio buttons
fullscreen = new OwnCheckBox(I18n.txt("gui.fullscreen"), skin, "radio", pad5);
fullscreen.addListener(event -> {
if (event instanceof ChangeEvent) {
selectFullscreen(fullscreen.isChecked(), widthField, heightField, fullscreenResolutions, widthLabel, heightLabel);
return true;
}
return false;
});
fullscreen.setChecked(GlobalConf.screen.FULLSCREEN);
windowed = new OwnCheckBox(I18n.txt("gui.windowed"), skin, "radio", pad5);
windowed.addListener(event -> {
if (event instanceof ChangeEvent) {
selectFullscreen(!windowed.isChecked(), widthField, heightField, fullscreenResolutions, widthLabel, heightLabel);
return true;
}
return false;
});
windowed.setChecked(!GlobalConf.screen.FULLSCREEN);
selectFullscreen(GlobalConf.screen.FULLSCREEN, widthField, heightField, fullscreenResolutions, widthLabel, heightLabel);
new ButtonGroup<>(fullscreen, windowed);
// VSYNC
vsync = new OwnCheckBox(I18n.txt("gui.vsync"), skin, "default", pad5);
vsync.setChecked(GlobalConf.screen.VSYNC);
// LIMIT FPS
limitfpsValidator = new DoubleValidator(Constants.MIN_FPS, Constants.MAX_FPS);
limitFps = new OwnTextField(nf3.format(MathUtilsd.clamp(GlobalConf.screen.LIMIT_FPS, Constants.MIN_FPS, Constants.MAX_FPS)), skin, limitfpsValidator);
limitFps.setDisabled(GlobalConf.screen.LIMIT_FPS == 0);
limitfpsCb = new OwnCheckBox(I18n.txt("gui.limitfps"), skin, "default", pad5);
limitfpsCb.setChecked(GlobalConf.screen.LIMIT_FPS > 0);
limitfpsCb.addListener((event) -> {
if (event instanceof ChangeEvent) {
enableComponents(limitfpsCb.isChecked(), limitFps);
return true;
}
return false;
});
mode.add(fullscreen).left().padRight(pad5 * 2);
mode.add(fullscreenResolutions).left().row();
mode.add(windowed).left().padRight(pad5 * 2).padTop(pad5 * 2);
mode.add(windowedResolutions).left().padTop(pad5 * 2).row();
mode.add(vsync).left().padTop(pad5 * 2).colspan(2).row();
mode.add(limitfpsCb).left().padRight(pad5 * 2);
mode.add(limitFps).left();
// Add to content
contentGraphicsTable.add(titleResolution).left().padBottom(pad5 * 2).row();
contentGraphicsTable.add(mode).left().padBottom(pad5 * 4).row();
// GRAPHICS SETTINGS
Label titleGraphics = new OwnLabel(I18n.txt("gui.graphicssettings"), skin, "header");
Table graphics = new Table();
OwnLabel gqualityLabel = new OwnLabel(I18n.txt("gui.gquality"), skin);
gqualityLabel.addListener(new OwnTextTooltip(I18n.txt("gui.gquality.info"), skin));
ComboBoxBean[] gqs = new ComboBoxBean[GraphicsQuality.values().length];
int i = 0;
for (GraphicsQuality q : GraphicsQuality.values()) {
gqs[i] = new ComboBoxBean(I18n.txt(q.key), q.ordinal());
i++;
}
gquality = new OwnSelectBox<>(skin);
gquality.setItems(gqs);
gquality.setWidth(textwidth * 3f);
gquality.setSelected(gqs[GlobalConf.scene.GRAPHICS_QUALITY.ordinal()]);
gquality.addListener((event) -> {
if (event instanceof ChangeEvent) {
ComboBoxBean s = gquality.getSelected();
GraphicsQuality gq = GraphicsQuality.values()[s.value];
if ((DataDescriptor.currentDataDescriptor == null || !DataDescriptor.currentDataDescriptor.datasetPresent("hi-res-textures")) && (gq.isHigh() || gq.isUltra())) {
// Show notice
// Hi resolution textures notice
if (noticeHiResCell != null && noticeHiResCell.getActor() == null) {
String infostr = I18n.txt("gui.gquality.hires.info") + "\n";
int lines1 = GlobalResources.countOccurrences(infostr, '\n');
OwnTextArea noticeHiRes = new OwnTextArea(infostr, skin, "info");
noticeHiRes.setDisabled(true);
noticeHiRes.setPrefRows(lines1 + 1);
noticeHiRes.setWidth(tawidth);
noticeHiRes.clearListeners();
noticeHiResCell.setActor(noticeHiRes);
}
} else {
// Hide notice
if (noticeHiResCell != null) {
noticeHiResCell.setActor(null);
}
}
}
return false;
});
OwnImageButton gqualityTooltip = new OwnImageButton(skin, "tooltip");
gqualityTooltip.addListener(new OwnTextTooltip(I18n.txt("gui.gquality.info"), skin));
// AA
OwnLabel aaLabel = new OwnLabel(I18n.txt("gui.aa"), skin);
aaLabel.addListener(new OwnTextTooltip(I18n.txt("gui.aa.info"), skin));
ComboBoxBean[] aas = new ComboBoxBean[] { new ComboBoxBean(I18n.txt("gui.aa.no"), 0), new ComboBoxBean(I18n.txt("gui.aa.fxaa"), -1), new ComboBoxBean(I18n.txt("gui.aa.nfaa"), -2) };
aa = new OwnSelectBox<>(skin);
aa.setItems(aas);
aa.setWidth(textwidth * 3f);
aa.setSelected(aas[idxAa(2, GlobalConf.postprocess.POSTPROCESS_ANTIALIAS)]);
OwnImageButton aaTooltip = new OwnImageButton(skin, "tooltip");
aaTooltip.addListener(new OwnTextTooltip(I18n.txt("gui.aa.info"), skin));
// ORBITS
OwnLabel orbitsLabel = new OwnLabel(I18n.txt("gui.orbitrenderer"), skin);
ComboBoxBean[] orbitItems = new ComboBoxBean[] { new ComboBoxBean(I18n.txt("gui.orbitrenderer.line"), 0), new ComboBoxBean(I18n.txt("gui.orbitrenderer.gpu"), 1) };
orbitRenderer = new OwnSelectBox<>(skin);
orbitRenderer.setItems(orbitItems);
orbitRenderer.setWidth(textwidth * 3f);
orbitRenderer.setSelected(orbitItems[GlobalConf.scene.ORBIT_RENDERER]);
// LINE RENDERER
OwnLabel lrLabel = new OwnLabel(I18n.txt("gui.linerenderer"), skin);
ComboBoxBean[] lineRenderers = new ComboBoxBean[] { new ComboBoxBean(I18n.txt("gui.linerenderer.normal"), 0), new ComboBoxBean(I18n.txt("gui.linerenderer.quad"), 1) };
lineRenderer = new OwnSelectBox<>(skin);
lineRenderer.setItems(lineRenderers);
lineRenderer.setWidth(textwidth * 3f);
lineRenderer.setSelected(lineRenderers[GlobalConf.scene.LINE_RENDERER]);
// BLOOM
bloomBak = GlobalConf.postprocess.POSTPROCESS_BLOOM_INTENSITY;
OwnLabel bloomLabel = new OwnLabel(I18n.txt("gui.bloom"), skin, "default");
Slider bloomEffect = new OwnSlider(Constants.MIN_SLIDER, Constants.MAX_SLIDER * 0.2f, 1, skin);
bloomEffect.setName("bloom effect");
bloomEffect.setWidth(sliderWidth);
bloomEffect.setValue(GlobalConf.postprocess.POSTPROCESS_BLOOM_INTENSITY * 10f);
bloomEffect.addListener(event -> {
if (event instanceof ChangeEvent) {
EventManager.instance.post(Events.BLOOM_CMD, bloomEffect.getValue() / 10f, true);
return true;
}
return false;
});
// LABELS
labels.addAll(gqualityLabel, aaLabel, orbitsLabel, lrLabel, bloomLabel);
// LENS FLARE
lensflareBak = GlobalConf.postprocess.POSTPROCESS_LENS_FLARE;
CheckBox lensFlare = new CheckBox(" " + I18n.txt("gui.lensflare"), skin);
lensFlare.setName("lens flare");
lensFlare.addListener(event -> {
if (event instanceof ChangeEvent) {
EventManager.instance.post(Events.LENS_FLARE_CMD, lensFlare.isChecked(), true);
return true;
}
return false;
});
lensFlare.setChecked(GlobalConf.postprocess.POSTPROCESS_LENS_FLARE);
// LIGHT GLOW
lightglowBak = GlobalConf.postprocess.POSTPROCESS_LIGHT_SCATTERING;
CheckBox lightGlow = new CheckBox(" " + I18n.txt("gui.lightscattering"), skin);
lightGlow.setName("light scattering");
lightGlow.setChecked(GlobalConf.postprocess.POSTPROCESS_LIGHT_SCATTERING);
lightGlow.addListener(event -> {
if (event instanceof ChangeEvent) {
EventManager.instance.post(Events.LIGHT_SCATTERING_CMD, lightGlow.isChecked(), true);
return true;
}
return false;
});
// MOTION BLUR
motionblurBak = GlobalConf.postprocess.POSTPROCESS_MOTION_BLUR;
CheckBox motionBlur = new CheckBox(" " + I18n.txt("gui.motionblur"), skin);
motionBlur.setName("motion blur");
motionBlur.setChecked(GlobalConf.postprocess.POSTPROCESS_MOTION_BLUR);
motionBlur.addListener(event -> {
if (event instanceof ChangeEvent) {
EventManager.instance.post(Events.MOTION_BLUR_CMD, motionBlur.isChecked(), true);
return true;
}
return false;
});
graphics.add(gqualityLabel).left().padRight(pad5 * 4).padBottom(pad5);
graphics.add(gquality).left().padRight(pad5 * 2).padBottom(pad5);
graphics.add(gqualityTooltip).left().padBottom(pad5).row();
noticeHiResCell = graphics.add();
noticeHiResCell.colspan(2).left().row();
final Cell<Actor> noticeGraphicsCell = graphics.add((Actor) null);
noticeGraphicsCell.colspan(2).left().row();
graphics.add(aaLabel).left().padRight(pad5 * 4).padBottom(pad5);
graphics.add(aa).left().padRight(pad5 * 2).padBottom(pad5);
graphics.add(aaTooltip).left().padBottom(pad5).row();
graphics.add(orbitsLabel).left().padRight(pad5 * 4).padBottom(pad5);
graphics.add(orbitRenderer).left().padBottom(pad5).row();
graphics.add(lrLabel).left().padRight(pad5 * 4).padBottom(pad5);
graphics.add(lineRenderer).left().padBottom(pad5).row();
graphics.add(bloomLabel).left().padRight(pad5 * 4).padBottom(pad5);
graphics.add(bloomEffect).left().padBottom(pad5).row();
graphics.add(lensFlare).colspan(2).left().padBottom(pad5).row();
graphics.add(lightGlow).colspan(2).left().padBottom(pad5).row();
graphics.add(motionBlur).colspan(2).left().padBottom(pad5).row();
// Add to content
contentGraphicsTable.add(titleGraphics).left().padBottom(pad5 * 2).row();
contentGraphicsTable.add(graphics).left().padBottom(pad5 * 4).row();
// ELEVATION
Label titleElevation = new OwnLabel(I18n.txt("gui.elevation.title"), skin, "header");
Table elevation = new Table();
// ELEVATION TYPE
OwnLabel elevationTypeLabel = new OwnLabel(I18n.txt("gui.elevation.type"), skin);
ElevationComboBoxBean[] ecbb = new ElevationComboBoxBean[ElevationType.values().length];
i = 0;
for (ElevationType et : ElevationType.values()) {
ecbb[i] = new ElevationComboBoxBean(I18n.txt("gui.elevation.type." + et.toString().toLowerCase()), et);
i++;
}
elevationSb = new OwnSelectBox<>(skin);
elevationSb.setItems(ecbb);
elevationSb.setWidth(textwidth * 3f);
elevationSb.setSelectedIndex(GlobalConf.scene.ELEVATION_TYPE.ordinal());
elevationSb.addListener((event) -> {
if (event instanceof ChangeEvent) {
if (elevationSb.getSelected().type.isTessellation()) {
enableComponents(true, tessQuality, tessQualityLabel);
} else {
enableComponents(false, tessQuality, tessQualityLabel);
}
}
return false;
});
// TESSELLATION QUALITY
tessQualityLabel = new OwnLabel(I18n.txt("gui.elevation.tessellation.quality"), skin);
tessQualityLabel.setDisabled(!GlobalConf.scene.ELEVATION_TYPE.isTessellation());
tessQuality = new OwnSlider(Constants.MIN_TESS_QUALITY, Constants.MAX_TESS_QUALITY, 0.1f, skin);
tessQuality.setDisabled(!GlobalConf.scene.ELEVATION_TYPE.isTessellation());
tessQuality.setWidth(sliderWidth);
tessQuality.setValue((float) GlobalConf.scene.TESSELLATION_QUALITY);
// LABELS
labels.add(elevationTypeLabel, tessQualityLabel);
elevation.add(elevationTypeLabel).left().padRight(pad20).padBottom(pad5);
elevation.add(elevationSb).left().padRight(pad5 * 2f).padBottom(pad5).row();
elevation.add(tessQualityLabel).left().padRight(pad20).padBottom(pad5);
elevation.add(tessQuality).left().padRight(pad5 * 2f).padBottom(pad5);
// Add to content
contentGraphicsTable.add(titleElevation).left().padBottom(pad5 * 2).row();
contentGraphicsTable.add(elevation).left().padBottom(pad5 * 4).row();
// SHADOWS
Label titleShadows = new OwnLabel(I18n.txt("gui.graphics.shadows"), skin, "header");
Table shadows = new Table();
// SHADOW MAP RESOLUTION
OwnLabel smResolutionLabel = new OwnLabel(I18n.txt("gui.graphics.shadows.resolution"), skin);
smResolutionLabel.setDisabled(!GlobalConf.scene.SHADOW_MAPPING);
IntValidator smResValidator = new IntValidator(128, 4096);
smResolution = new OwnTextField(Integer.toString(MathUtils.clamp(GlobalConf.scene.SHADOW_MAPPING_RESOLUTION, 128, 4096)), skin, smResValidator);
smResolution.setWidth(textwidth * 3f);
smResolution.setDisabled(!GlobalConf.scene.SHADOW_MAPPING);
// N SHADOWS
OwnLabel nShadowsLabel = new OwnLabel("#" + I18n.txt("gui.graphics.shadows"), skin);
nShadowsLabel.setDisabled(!GlobalConf.scene.SHADOW_MAPPING);
ComboBoxBean[] nsh = new ComboBoxBean[] { new ComboBoxBean("1", 1), new ComboBoxBean("2", 2), new ComboBoxBean("3", 3), new ComboBoxBean("4", 4) };
nshadows = new OwnSelectBox<>(skin);
nshadows.setItems(nsh);
nshadows.setWidth(textwidth * 3f);
nshadows.setSelected(nsh[GlobalConf.scene.SHADOW_MAPPING_N_SHADOWS - 1]);
nshadows.setDisabled(!GlobalConf.scene.SHADOW_MAPPING);
// ENABLE SHADOWS
shadowsCb = new OwnCheckBox(I18n.txt("gui.graphics.shadows.enable"), skin, "default", pad5);
shadowsCb.setChecked(GlobalConf.scene.SHADOW_MAPPING);
shadowsCb.addListener((event) -> {
if (event instanceof ChangeEvent) {
// Enable or disable resolution
enableComponents(shadowsCb.isChecked(), smResolution, smResolutionLabel, nshadows, nShadowsLabel);
return true;
}
return false;
});
// LABELS
labels.add(smResolutionLabel);
shadows.add(shadowsCb).left().padRight(pad5 * 2).padBottom(pad5).row();
shadows.add(smResolutionLabel).left().padRight(pad5 * 4).padBottom(pad5);
shadows.add(smResolution).left().padRight(pad5 * 2).padBottom(pad5).row();
shadows.add(nShadowsLabel).left().padRight(pad5 * 4).padBottom(pad5);
shadows.add(nshadows).left().padRight(pad5 * 2).padBottom(pad5);
// Add to content
contentGraphicsTable.add(titleShadows).left().padBottom(pad5 * 2).row();
contentGraphicsTable.add(shadows).left().padBottom(pad5 * 4).row();
// DISPLAY SETTINGS
Label titleDisplay = new OwnLabel(I18n.txt("gui.graphics.imglevels"), skin, "header");
Table display = new Table();
brightnessBak = GlobalConf.postprocess.POSTPROCESS_BRIGHTNESS;
contrastBak = GlobalConf.postprocess.POSTPROCESS_CONTRAST;
hueBak = GlobalConf.postprocess.POSTPROCESS_HUE;
saturationBak = GlobalConf.postprocess.POSTPROCESS_SATURATION;
gammaBak = GlobalConf.postprocess.POSTPROCESS_GAMMA;
toneMappingBak = GlobalConf.postprocess.POSTPROCESS_TONEMAPPING_TYPE;
exposureBak = GlobalConf.postprocess.POSTPROCESS_EXPOSURE;
/* Brightness */
OwnLabel brightnessl = new OwnLabel(I18n.txt("gui.brightness"), skin, "default");
Slider brightness = new OwnSlider(Constants.MIN_SLIDER, Constants.MAX_SLIDER, 1, skin);
brightness.setName("brightness");
brightness.setWidth(sliderWidth);
brightness.setValue(MathUtilsd.lint(GlobalConf.postprocess.POSTPROCESS_BRIGHTNESS, Constants.MIN_BRIGHTNESS, Constants.MAX_BRIGHTNESS, Constants.MIN_SLIDER, Constants.MAX_SLIDER));
brightness.addListener(event -> {
if (event instanceof ChangeEvent) {
EventManager.instance.post(Events.BRIGHTNESS_CMD, MathUtilsd.lint(brightness.getValue(), Constants.MIN_SLIDER, Constants.MAX_SLIDER, Constants.MIN_BRIGHTNESS, Constants.MAX_BRIGHTNESS), true);
return true;
}
return false;
});
display.add(brightnessl).left().padRight(pad5 * 4).padBottom(pad5);
display.add(brightness).left().padRight(pad5 * 2).padBottom(pad5).row();
/* Contrast */
OwnLabel contrastl = new OwnLabel(I18n.txt("gui.contrast"), skin, "default");
Slider contrast = new OwnSlider(Constants.MIN_SLIDER, Constants.MAX_SLIDER, 1, skin);
contrast.setName("contrast");
contrast.setWidth(sliderWidth);
contrast.setValue(MathUtilsd.lint(GlobalConf.postprocess.POSTPROCESS_CONTRAST, Constants.MIN_CONTRAST, Constants.MAX_CONTRAST, Constants.MIN_SLIDER, Constants.MAX_SLIDER));
contrast.addListener(event -> {
if (event instanceof ChangeEvent) {
EventManager.instance.post(Events.CONTRAST_CMD, MathUtilsd.lint(contrast.getValue(), Constants.MIN_SLIDER, Constants.MAX_SLIDER, Constants.MIN_CONTRAST, Constants.MAX_CONTRAST), true);
return true;
}
return false;
});
display.add(contrastl).left().padRight(pad5 * 4).padBottom(pad5);
display.add(contrast).left().padRight(pad5 * 2).padBottom(pad5).row();
/* Hue */
OwnLabel huel = new OwnLabel(I18n.txt("gui.hue"), skin, "default");
Slider hue = new OwnSlider(Constants.MIN_SLIDER, Constants.MAX_SLIDER, 1, skin);
hue.setName("hue");
hue.setWidth(sliderWidth);
hue.setValue(MathUtilsd.lint(GlobalConf.postprocess.POSTPROCESS_HUE, Constants.MIN_HUE, Constants.MAX_HUE, Constants.MIN_SLIDER, Constants.MAX_SLIDER));
hue.addListener(event -> {
if (event instanceof ChangeEvent) {
EventManager.instance.post(Events.HUE_CMD, MathUtilsd.lint(hue.getValue(), Constants.MIN_SLIDER, Constants.MAX_SLIDER, Constants.MIN_HUE, Constants.MAX_HUE), true);
return true;
}
return false;
});
display.add(huel).left().padRight(pad5 * 4).padBottom(pad5);
display.add(hue).left().padRight(pad5 * 2).padBottom(pad5).row();
/* Saturation */
OwnLabel saturationl = new OwnLabel(I18n.txt("gui.saturation"), skin, "default");
Slider saturation = new OwnSlider(Constants.MIN_SLIDER, Constants.MAX_SLIDER, 1, skin);
saturation.setName("saturation");
saturation.setWidth(sliderWidth);
saturation.setValue(MathUtilsd.lint(GlobalConf.postprocess.POSTPROCESS_SATURATION, Constants.MIN_SATURATION, Constants.MAX_SATURATION, Constants.MIN_SLIDER, Constants.MAX_SLIDER));
saturation.addListener(event -> {
if (event instanceof ChangeEvent) {
EventManager.instance.post(Events.SATURATION_CMD, MathUtilsd.lint(saturation.getValue(), Constants.MIN_SLIDER, Constants.MAX_SLIDER, Constants.MIN_SATURATION, Constants.MAX_SATURATION), true);
return true;
}
return false;
});
display.add(saturationl).left().padRight(pad5 * 4).padBottom(pad5);
display.add(saturation).left().padRight(pad5 * 2).padBottom(pad5).row();
/* Gamma */
OwnLabel gammal = new OwnLabel(I18n.txt("gui.gamma"), skin, "default");
Slider gamma = new OwnSlider(Constants.MIN_GAMMA, Constants.MAX_GAMMA, 0.1f, false, skin);
gamma.setName("gamma");
gamma.setWidth(sliderWidth);
gamma.setValue(GlobalConf.postprocess.POSTPROCESS_GAMMA);
gamma.addListener(event -> {
if (event instanceof ChangeEvent) {
EventManager.instance.post(Events.GAMMA_CMD, gamma.getValue(), true);
return true;
}
return false;
});
display.add(gammal).left().padRight(pad5 * 4).padBottom(pad5);
display.add(gamma).left().padRight(pad5 * 2).padBottom(pad5).row();
/* Tone Mapping */
OwnLabel toneMappingl = new OwnLabel(I18n.txt("gui.tonemapping.type"), skin, "default");
ComboBoxBean[] toneMappingTypes = new ComboBoxBean[] { new ComboBoxBean(I18n.txt("gui.tonemapping.auto"), ToneMapping.AUTO.ordinal()), new ComboBoxBean(I18n.txt("gui.tonemapping.exposure"), ToneMapping.EXPOSURE.ordinal()), new ComboBoxBean("Filmic", ToneMapping.FILMIC.ordinal()), new ComboBoxBean("Uncharted", ToneMapping.UNCHARTED.ordinal()), new ComboBoxBean("ACES", ToneMapping.ACES.ordinal()), new ComboBoxBean(I18n.txt("gui.tonemapping.none"), ToneMapping.NONE.ordinal()) };
OwnSelectBox<ComboBoxBean> toneMappingSelect = new OwnSelectBox<>(skin);
toneMappingSelect.setItems(toneMappingTypes);
toneMappingSelect.setWidth(textwidth * 3f);
toneMappingSelect.setSelectedIndex(GlobalConf.postprocess.POSTPROCESS_TONEMAPPING_TYPE.ordinal());
display.add(toneMappingl).left().padRight(pad5 * 4).padBottom(pad5);
display.add(toneMappingSelect).left().padBottom(pad5).row();
/* Exposure */
OwnLabel exposurel = new OwnLabel(I18n.txt("gui.exposure"), skin, "default");
exposurel.setDisabled(GlobalConf.postprocess.POSTPROCESS_TONEMAPPING_TYPE != ToneMapping.EXPOSURE);
Slider exposure = new OwnSlider(Constants.MIN_EXPOSURE, Constants.MAX_EXPOSURE, 0.1f, false, skin);
exposure.setName("exposure");
exposure.setWidth(sliderWidth);
exposure.setValue(GlobalConf.postprocess.POSTPROCESS_EXPOSURE);
exposure.setDisabled(GlobalConf.postprocess.POSTPROCESS_TONEMAPPING_TYPE != ToneMapping.EXPOSURE);
exposure.addListener(event -> {
if (event instanceof ChangeEvent) {
EventManager.instance.post(Events.EXPOSURE_CMD, exposure.getValue(), true);
return true;
}
return false;
});
toneMappingSelect.addListener((event) -> {
if (event instanceof ChangeEvent) {
ToneMapping newTM = ToneMapping.values()[toneMappingSelect.getSelectedIndex()];
EventManager.instance.post(Events.TONEMAPPING_TYPE_CMD, newTM, true);
boolean disabled = newTM != ToneMapping.EXPOSURE;
exposurel.setDisabled(disabled);
exposure.setDisabled(disabled);
return true;
}
return false;
});
display.add(exposurel).left().padRight(pad5 * 4).padBottom(pad5);
display.add(exposure).left().padRight(pad5 * 2).padBottom(pad5).row();
// LABELS
labels.addAll(brightnessl, contrastl, huel, saturationl, gammal);
// Add to content
contentGraphicsTable.add(titleDisplay).left().padBottom(pad5 * 2).row();
contentGraphicsTable.add(display).left();
/*
* ==== UI ====
*/
float labelWidth = 250f * GlobalConf.UI_SCALE_FACTOR;
final Table contentUI = new Table(skin);
contents.add(contentUI);
contentUI.align(Align.top | Align.left);
OwnLabel titleUI = new OwnLabel(I18n.txt("gui.ui.interfacesettings"), skin, "header");
Table ui = new Table();
// LANGUAGE
OwnLabel langLabel = new OwnLabel(I18n.txt("gui.ui.language"), skin);
langLabel.setWidth(labelWidth);
File i18nfolder = new File(GlobalConf.ASSETS_LOC + File.separator + "i18n");
String i18nname = "gsbundle";
String[] files = i18nfolder.list();
LangComboBoxBean[] langs = new LangComboBoxBean[files.length];
i = 0;
for (String file : files) {
if (file.startsWith("gsbundle") && file.endsWith(".properties")) {
String locale = file.substring(i18nname.length(), file.length() - ".properties".length());
// Default locale
if (locale.isEmpty())
locale = "-en-GB";
// Remove underscore _
locale = locale.substring(1).replace("_", "-");
Locale loc = Locale.forLanguageTag(locale);
langs[i] = new LangComboBoxBean(loc);
}
i++;
}
Arrays.sort(langs);
lang = new OwnSelectBox<>(skin);
lang.setWidth(textwidth * 3f);
lang.setItems(langs);
if (!GlobalConf.program.LOCALE.isEmpty()) {
lang.setSelected(langs[idxLang(GlobalConf.program.LOCALE, langs)]);
} else {
// Empty locale
int lidx = idxLang(null, langs);
if (lidx < 0 || lidx >= langs.length) {
lidx = idxLang(Locale.getDefault().toLanguageTag(), langs);
if (lidx < 0 || lidx >= langs.length) {
// Default is en_GB
lidx = 2;
}
}
lang.setSelected(langs[lidx]);
}
// THEME
OwnLabel themeLabel = new OwnLabel(I18n.txt("gui.ui.theme"), skin);
themeLabel.setWidth(labelWidth);
String[] themes = new String[] { "dark-green", "dark-blue", "dark-orange", "night-red" };
theme = new OwnSelectBox<>(skin);
theme.setWidth(textwidth * 3f);
theme.setItems(themes);
theme.setSelected(GlobalConf.program.getUIThemeBase());
// HiDPI
hidpiCb = new OwnCheckBox(I18n.txt("gui.ui.theme.hidpi"), skin, "default", pad5);
hidpiCb.setChecked(GlobalConf.program.isHiDPITheme());
// POINTER COORDINATES
pointerCoords = new OwnCheckBox(I18n.txt("gui.ui.pointercoordinates"), skin, "default", pad5);
pointerCoords.setChecked(GlobalConf.program.DISPLAY_POINTER_COORDS);
// MINIMAP SIZE
OwnLabel minimapSizeLabel = new OwnLabel(I18n.txt("gui.ui.minimap.size"), skin, "default");
minimapSizeLabel.setWidth(labelWidth);
minimapSize = new OwnSlider(Constants.MIN_MINIMAP_SIZE, Constants.MAX_MINIMAP_SIZE, 1f, skin);
minimapSize.setName("minimapSize");
minimapSize.setWidth(sliderWidth);
minimapSize.setValue(GlobalConf.program.MINIMAP_SIZE);
// LABELS
labels.addAll(langLabel, themeLabel);
// Add to table
ui.add(langLabel).left().padRight(pad5 * 4).padBottom(pad10);
ui.add(lang).left().padBottom(pad10).row();
ui.add(themeLabel).left().padRight(pad5 * 4).padBottom(pad10);
ui.add(theme).left().padBottom(pad10).row();
ui.add(hidpiCb).colspan(2).left().padBottom(pad10).row();
ui.add(pointerCoords).colspan(2).left().padRight(pad5).padBottom(pad10).row();
ui.add(minimapSizeLabel).left().padRight(pad5).padBottom(pad10);
ui.add(minimapSize).left().padRight(pad5).padBottom(pad10).row();
/* CROSSHAIR AND MARKERS */
OwnLabel titleCrosshair = new OwnLabel(I18n.txt("gui.ui.crosshair"), skin, "header");
Table ch = new Table();
// CROSSHAIR FOCUS
crosshairFocusCb = new OwnCheckBox("" + I18n.txt("gui.ui.crosshair.focus"), skin, pad10);
crosshairFocusCb.setName("ch focus");
crosshairFocusCb.setChecked(GlobalConf.scene.CROSSHAIR_FOCUS);
// CROSSHAIR CLOSEST
crosshairClosestCb = new OwnCheckBox("" + I18n.txt("gui.ui.crosshair.closest"), skin, pad10);
crosshairClosestCb.setName("ch closest");
crosshairClosestCb.setChecked(GlobalConf.scene.CROSSHAIR_CLOSEST);
// CROSSHAIR HOME
crosshairHomeCb = new OwnCheckBox("" + I18n.txt("gui.ui.crosshair.home"), skin, pad10);
crosshairHomeCb.setName("ch home");
crosshairHomeCb.setChecked(GlobalConf.scene.CROSSHAIR_HOME);
// Add to table
ch.add(crosshairFocusCb).left().padBottom(pad5).row();
ch.add(crosshairClosestCb).left().padBottom(pad5).row();
ch.add(crosshairHomeCb).left().padBottom(pad5).row();
/* POINTER GUIDES */
OwnLabel titleGuides = new OwnLabel(I18n.txt("gui.ui.pointer.guides"), skin, "header");
Table pg = new Table();
// GUIDES CHECKBOX
pointerGuidesCb = new OwnCheckBox("" + I18n.txt("gui.ui.pointer.guides.display"), skin, pad10);
pointerGuidesCb.setName("pointer guides cb");
pointerGuidesCb.setChecked(GlobalConf.program.DISPLAY_POINTER_GUIDES);
OwnImageButton guidesTooltip = new OwnImageButton(skin, "tooltip");
guidesTooltip.addListener(new OwnTextTooltip(I18n.txt("gui.ui.pointer.guides.info"), skin));
HorizontalGroup pointerGuidesCbGroup = new HorizontalGroup();
pointerGuidesCbGroup.space(pad10);
pointerGuidesCbGroup.addActor(pointerGuidesCb);
pointerGuidesCbGroup.addActor(guidesTooltip);
// GUIDES COLOR
float cpsize = 20f * GlobalConf.UI_SCALE_FACTOR;
pointerGuidesColor = new ColorPicker(stage, skin);
pointerGuidesColor.setPickedColor(GlobalConf.program.POINTER_GUIDES_COLOR);
// GUIDES WIDTH
OwnLabel guidesWidthLabel = new OwnLabel(I18n.txt("gui.ui.pointer.guides.width"), skin, "default");
guidesWidthLabel.setWidth(labelWidth);
pointerGuidesWidth = new OwnSlider(Constants.MIN_POINTER_GUIDES_WIDTH, Constants.MAX_POINTER_GUIDES_WIDTH, Constants.SLIDER_STEP_TINY, skin);
pointerGuidesWidth.setName("pointerguideswidth");
pointerGuidesWidth.setWidth(sliderWidth);
pointerGuidesWidth.setValue(GlobalConf.program.POINTER_GUIDES_WIDTH);
// Add to table
pg.add(pointerGuidesCbGroup).left().colspan(2).padBottom(pad5).row();
pg.add(new OwnLabel(I18n.txt("gui.ui.pointer.guides.color"), skin)).left().padBottom(pad5).padRight(pad10);
pg.add(pointerGuidesColor).left().size(cpsize).padBottom(pad5).row();
pg.add(guidesWidthLabel).left().padBottom(pad5).padRight(pad10);
pg.add(pointerGuidesWidth).left().padBottom(pad5).padRight(pad10);
// Add to content
contentUI.add(titleUI).left().padBottom(pad5 * 2).row();
contentUI.add(ui).left().padBottom(pad5 * 4).row();
contentUI.add(titleCrosshair).left().padBottom(pad5 * 2).row();
contentUI.add(ch).left().padBottom(pad5 * 4).row();
contentUI.add(titleGuides).left().padBottom(pad5 * 2).row();
contentUI.add(pg).left();
/*
* ==== PERFORMANCE ====
*/
final Table contentPerformance = new Table(skin);
contents.add(contentPerformance);
contentPerformance.align(Align.top | Align.left);
// MULTITHREADING
OwnLabel titleMultiThread = new OwnLabel(I18n.txt("gui.multithreading"), skin, "header");
Table multiThread = new Table(skin);
OwnLabel numThreadsLabel = new OwnLabel(I18n.txt("gui.thread.number"), skin);
int maxThreads = Runtime.getRuntime().availableProcessors();
ComboBoxBean[] cbs = new ComboBoxBean[maxThreads + 1];
cbs[0] = new ComboBoxBean(I18n.txt("gui.letdecide"), 0);
for (i = 1; i <= maxThreads; i++) {
cbs[i] = new ComboBoxBean(I18n.txt("gui.thread", i), i);
}
numThreads = new OwnSelectBox<>(skin);
numThreads.setWidth(textwidth * 3f);
numThreads.setItems(cbs);
numThreads.setSelectedIndex(GlobalConf.performance.NUMBER_THREADS);
multithreadCb = new OwnCheckBox(I18n.txt("gui.thread.enable"), skin, "default", pad5);
multithreadCb.addListener(event -> {
if (event instanceof ChangeEvent) {
numThreads.setDisabled(!multithreadCb.isChecked());
// Add notice
return true;
}
return false;
});
multithreadCb.setChecked(GlobalConf.performance.MULTITHREADING);
numThreads.setDisabled(!multithreadCb.isChecked());
// Add to table
multiThread.add(multithreadCb).colspan(2).left().padBottom(pad5).row();
multiThread.add(numThreadsLabel).left().padRight(pad5 * 4).padBottom(pad5);
multiThread.add(numThreads).left().padBottom(pad5).row();
final Cell<Actor> noticeMultiThreadCell = multiThread.add((Actor) null);
noticeMultiThreadCell.colspan(2).left();
multithreadCb.addListener(event -> {
if (event instanceof ChangeEvent) {
if (noticeMultiThreadCell.getActor() == null) {
String nextInfoStr = I18n.txt("gui.ui.info") + '\n';
int lines = GlobalResources.countOccurrences(nextInfoStr, '\n');
TextArea nextTimeInfo = new OwnTextArea(nextInfoStr, skin, "info");
nextTimeInfo.setDisabled(true);
nextTimeInfo.setPrefRows(lines + 1);
nextTimeInfo.setWidth(tawidth);
nextTimeInfo.clearListeners();
noticeMultiThreadCell.setActor(nextTimeInfo);
}
return true;
}
return false;
});
// Add to content
contentPerformance.add(titleMultiThread).left().padBottom(pad5 * 2).row();
contentPerformance.add(multiThread).left().padBottom(pad5 * 4).row();
// DRAW DISTANCE
OwnLabel titleLod = new OwnLabel(I18n.txt("gui.lod"), skin, "header");
Table lod = new Table(skin);
// Smooth transitions
lodFadeCb = new OwnCheckBox(I18n.txt("gui.lod.fade"), skin, "default", pad5);
lodFadeCb.setChecked(GlobalConf.scene.OCTREE_PARTICLE_FADE);
// Draw distance
OwnLabel ddLabel = new OwnLabel(I18n.txt("gui.lod.thresholds"), skin);
lodTransitions = new OwnSlider(Constants.MIN_SLIDER, Constants.MAX_SLIDER, 0.1f, Constants.MIN_LOD_TRANS_ANGLE_DEG, Constants.MAX_LOD_TRANS_ANGLE_DEG, false, skin);
lodTransitions.setDisplayValueMapped(true);
lodTransitions.setWidth(sliderWidth);
lodTransitions.setMappedValue(GlobalConf.scene.OCTANT_THRESHOLD_0 * MathUtilsd.radDeg);
OwnImageButton lodTooltip = new OwnImageButton(skin, "tooltip");
lodTooltip.addListener(new OwnTextTooltip(I18n.txt("gui.lod.thresholds.info"), skin));
// LABELS
labels.addAll(numThreadsLabel, ddLabel);
// Add to table
lod.add(lodFadeCb).colspan(3).left().padBottom(pad5).row();
lod.add(ddLabel).left().padRight(pad5 * 4).padBottom(pad5);
lod.add(lodTransitions).left().padRight(pad10).padBottom(pad5);
lod.add(lodTooltip).left().padBottom(pad5);
// Add to content
contentPerformance.add(titleLod).left().padBottom(pad5 * 2).row();
contentPerformance.add(lod).left();
/*
* ==== CONTROLS ====
*/
final Table contentControls = new Table(skin);
contents.add(contentControls);
contentControls.align(Align.top | Align.left);
OwnLabel titleController = new OwnLabel(I18n.txt("gui.controller"), skin, "header");
// DETECTED CONTROLLER NAMES
controllersTable = new Table(skin);
OwnLabel detectedLabel = new OwnLabel(I18n.txt("gui.controller.detected"), skin);
generateControllersList(controllersTable);
// CONTROLLER MAPPINGS
OwnLabel mappingsLabel = new OwnLabel(I18n.txt("gui.controller.mappingsfile"), skin);
controllerMappings = new OwnSelectBox<>(skin);
reloadControllerMappings(null);
// INVERT X
invertx = new OwnCheckBox(I18n.txt("gui.controller.axis.invert", "X"), skin, "default", pad5);
invertx.setChecked(GlobalConf.controls.INVERT_LOOK_X_AXIS);
// INVERT Y
inverty = new OwnCheckBox(I18n.txt("gui.controller.axis.invert", "Y"), skin, "default", pad5);
inverty.setChecked(GlobalConf.controls.INVERT_LOOK_Y_AXIS);
// KEY BINDINGS
OwnLabel titleKeybindings = new OwnLabel(I18n.txt("gui.keymappings"), skin, "header");
Map<ProgramAction, Array<TreeSet<Integer>>> keyboardMappings = KeyBindings.instance.getSortedMappingsInv();
String[][] data = new String[keyboardMappings.size()][];
i = 0;
for (ProgramAction action : keyboardMappings.keySet()) {
Array<TreeSet<Integer>> keys = keyboardMappings.get(action);
String[] act = new String[1 + keys.size];
act[0] = action.actionName;
for (int j = 0; j < keys.size; j++) {
act[j + 1] = keysToString(keys.get(j));
}
data[i] = act;
i++;
}
Table controls = new Table(skin);
controls.align(Align.left | Align.top);
// Header
controls.add(new OwnLabel(I18n.txt("gui.keymappings.action"), skin, "header")).left();
controls.add(new OwnLabel(I18n.txt("gui.keymappings.keys"), skin, "header")).left().row();
controls.add(new OwnLabel(I18n.txt("action.forward"), skin)).left().padRight(pad10);
controls.add(new OwnLabel(Keys.toString(Keys.UP).toUpperCase(), skin, "default-pink")).left().row();
controls.add(new OwnLabel(I18n.txt("action.backward"), skin)).left().padRight(pad10);
controls.add(new OwnLabel(Keys.toString(Keys.DOWN).toUpperCase(), skin, "default-pink")).left().row();
controls.add(new OwnLabel(I18n.txt("action.left"), skin)).left().padRight(pad10);
controls.add(new OwnLabel(Keys.toString(Keys.LEFT).toUpperCase(), skin, "default-pink")).left().row();
controls.add(new OwnLabel(I18n.txt("action.right"), skin)).left().padRight(pad10);
controls.add(new OwnLabel(Keys.toString(Keys.RIGHT).toUpperCase(), skin, "default-pink")).left().row();
// Controls
for (String[] action : data) {
HorizontalGroup keysGroup = new HorizontalGroup();
keysGroup.space(pad5);
for (int j = 1; j < action.length; j++) {
String[] keys = action[j].split("\\+");
for (int k = 0; k < keys.length; k++) {
keysGroup.addActor(new OwnLabel(keys[k].trim(), skin, "default-pink"));
if (k < keys.length - 1)
keysGroup.addActor(new OwnLabel("+", skin));
}
if (j < action.length - 1)
keysGroup.addActor(new OwnLabel("/", skin));
}
controls.add(new OwnLabel(action[0], skin)).left().padRight(pad10);
controls.add(keysGroup).left().row();
}
OwnScrollPane controlsScroll = new OwnScrollPane(controls, skin, "minimalist-nobg");
controlsScroll.setWidth(controlsscrollw);
controlsScroll.setHeight(controllsscrollh * 0.6f);
controlsScroll.setScrollingDisabled(true, false);
controlsScroll.setSmoothScrolling(true);
controlsScroll.setFadeScrollBars(false);
scrolls.add(controlsScroll);
// Add to content
contentControls.add(titleController).colspan(2).left().padBottom(pad10).row();
contentControls.add(detectedLabel).left().padBottom(pad10).padRight(pad10);
contentControls.add(controllersTable).left().padBottom(pad10).row();
contentControls.add(mappingsLabel).left().padBottom(pad10).padRight(pad10);
contentControls.add(controllerMappings).left().padBottom(pad10).row();
contentControls.add(invertx).left().colspan(2).padBottom(pad10).row();
contentControls.add(inverty).left().colspan(2).padBottom(pad10).row();
contentControls.add(titleKeybindings).colspan(2).left().padBottom(pad10).row();
contentControls.add(controlsScroll).colspan(2).left();
/*
* ==== SCREENSHOTS ====
*/
final Table contentScreenshots = new Table(skin);
contents.add(contentScreenshots);
contentScreenshots.align(Align.top | Align.left);
// SCREEN CAPTURE
OwnLabel titleScreenshots = new OwnLabel(I18n.txt("gui.screencapture"), skin, "header");
Table screenshots = new Table(skin);
// Info
String ssInfoStr = I18n.txt("gui.screencapture.info") + '\n';
int ssLines = GlobalResources.countOccurrences(ssInfoStr, '\n');
TextArea screenshotsInfo = new OwnTextArea(ssInfoStr, skin, "info");
screenshotsInfo.setDisabled(true);
screenshotsInfo.setPrefRows(ssLines + 1);
screenshotsInfo.setWidth(tawidth);
screenshotsInfo.clearListeners();
// Save location
OwnLabel screenshotsLocationLabel = new OwnLabel(I18n.txt("gui.screenshots.save"), skin);
screenshotsLocationLabel.pack();
screenshotsLocation = new OwnTextButton(GlobalConf.screenshot.SCREENSHOT_FOLDER, skin);
screenshotsLocation.pad(pad5);
screenshotsLocation.addListener(event -> {
if (event instanceof ChangeEvent) {
FileChooser fc = new FileChooser(I18n.txt("gui.screenshots.directory.choose"), skin, stage, Paths.get(GlobalConf.screenshot.SCREENSHOT_FOLDER), FileChooser.FileChooserTarget.DIRECTORIES);
fc.setResultListener((success, result) -> {
if (success) {
// do stuff with result
screenshotsLocation.setText(result.toString());
}
return true;
});
fc.show(stage);
return true;
}
return false;
});
// Size
final OwnLabel screenshotsSizeLabel = new OwnLabel(I18n.txt("gui.screenshots.size"), skin);
screenshotsSizeLabel.setDisabled(GlobalConf.screenshot.isSimpleMode());
final OwnLabel xLabel = new OwnLabel("x", skin);
screenshotsSizeValidator = new IntValidator(GlobalConf.ScreenshotConf.MIN_SCREENSHOT_SIZE, GlobalConf.ScreenshotConf.MAX_SCREENSHOT_SIZE);
sswidthField = new OwnTextField(Integer.toString(MathUtils.clamp(GlobalConf.screenshot.SCREENSHOT_WIDTH, GlobalConf.ScreenshotConf.MIN_SCREENSHOT_SIZE, GlobalConf.ScreenshotConf.MAX_SCREENSHOT_SIZE)), skin, screenshotsSizeValidator);
sswidthField.setWidth(textwidth);
sswidthField.setDisabled(GlobalConf.screenshot.isSimpleMode());
ssheightField = new OwnTextField(Integer.toString(MathUtils.clamp(GlobalConf.screenshot.SCREENSHOT_HEIGHT, GlobalConf.ScreenshotConf.MIN_SCREENSHOT_SIZE, GlobalConf.ScreenshotConf.MAX_SCREENSHOT_SIZE)), skin, screenshotsSizeValidator);
ssheightField.setWidth(textwidth);
ssheightField.setDisabled(GlobalConf.screenshot.isSimpleMode());
HorizontalGroup ssSizeGroup = new HorizontalGroup();
ssSizeGroup.space(pad5 * 2);
ssSizeGroup.addActor(sswidthField);
ssSizeGroup.addActor(xLabel);
ssSizeGroup.addActor(ssheightField);
// Mode
OwnLabel ssModeLabel = new OwnLabel(I18n.txt("gui.screenshots.mode"), skin);
ComboBoxBean[] screenshotModes = new ComboBoxBean[] { new ComboBoxBean(I18n.txt("gui.screenshots.mode.simple"), 0), new ComboBoxBean(I18n.txt("gui.screenshots.mode.redraw"), 1) };
screenshotMode = new OwnSelectBox<>(skin);
screenshotMode.setItems(screenshotModes);
screenshotMode.setWidth(textwidth * 3f);
screenshotMode.addListener(event -> {
if (event instanceof ChangeEvent) {
if (screenshotMode.getSelected().value == 0) {
// Simple
enableComponents(false, sswidthField, ssheightField, screenshotsSizeLabel, xLabel);
} else {
// Redraw
enableComponents(true, sswidthField, ssheightField, screenshotsSizeLabel, xLabel);
}
return true;
}
return false;
});
screenshotMode.setSelected(screenshotModes[GlobalConf.screenshot.SCREENSHOT_MODE.ordinal()]);
screenshotMode.addListener(new OwnTextTooltip(I18n.txt("gui.tooltip.screenshotmode"), skin));
OwnImageButton screenshotsModeTooltip = new OwnImageButton(skin, "tooltip");
screenshotsModeTooltip.addListener(new OwnTextTooltip(I18n.txt("gui.tooltip.screenshotmode"), skin));
HorizontalGroup ssModeGroup = new HorizontalGroup();
ssModeGroup.space(pad5);
ssModeGroup.addActor(screenshotMode);
ssModeGroup.addActor(screenshotsModeTooltip);
// LABELS
labels.addAll(screenshotsLocationLabel, ssModeLabel, screenshotsSizeLabel);
// Add to table
screenshots.add(screenshotsInfo).colspan(2).left().padBottom(pad5).row();
screenshots.add(screenshotsLocationLabel).left().padRight(pad5 * 4).padBottom(pad5);
screenshots.add(screenshotsLocation).left().expandX().padBottom(pad5).row();
screenshots.add(ssModeLabel).left().padRight(pad5 * 4).padBottom(pad5);
screenshots.add(ssModeGroup).left().expandX().padBottom(pad5).row();
screenshots.add(screenshotsSizeLabel).left().padRight(pad5 * 4).padBottom(pad5);
screenshots.add(ssSizeGroup).left().expandX().padBottom(pad5).row();
// Add to content
contentScreenshots.add(titleScreenshots).left().padBottom(pad5 * 2).row();
contentScreenshots.add(screenshots).left();
/*
* ==== FRAME OUTPUT ====
*/
final Table contentFrames = new Table(skin);
contents.add(contentFrames);
contentFrames.align(Align.top | Align.left);
// FRAME OUTPUT CONFIG
OwnLabel titleFrameoutput = new OwnLabel(I18n.txt("gui.frameoutput"), skin, "header");
Table frameoutput = new Table(skin);
// Info
String foinfostr = I18n.txt("gui.frameoutput.info") + '\n';
ssLines = GlobalResources.countOccurrences(foinfostr, '\n');
TextArea frameoutputInfo = new OwnTextArea(foinfostr, skin, "info");
frameoutputInfo.setDisabled(true);
frameoutputInfo.setPrefRows(ssLines + 1);
frameoutputInfo.setWidth(tawidth);
frameoutputInfo.clearListeners();
// Save location
OwnLabel frameoutputLocationLabel = new OwnLabel(I18n.txt("gui.frameoutput.location"), skin);
frameoutputLocation = new OwnTextButton(GlobalConf.frame.RENDER_FOLDER, skin);
frameoutputLocation.pad(pad5);
frameoutputLocation.addListener(event -> {
if (event instanceof ChangeEvent) {
FileChooser fc = new FileChooser(I18n.txt("gui.frameoutput.directory.choose"), skin, stage, Paths.get(GlobalConf.frame.RENDER_FOLDER), FileChooser.FileChooserTarget.DIRECTORIES);
fc.setResultListener((success, result) -> {
if (success) {
// do stuff with result
frameoutputLocation.setText(result.toString());
}
return true;
});
fc.show(stage);
return true;
}
return false;
});
// Prefix
OwnLabel prefixLabel = new OwnLabel(I18n.txt("gui.frameoutput.prefix"), skin);
frameoutputPrefix = new OwnTextField(GlobalConf.frame.RENDER_FILE_NAME, skin, new RegexpValidator("^\\w+$"));
frameoutputPrefix.setWidth(textwidth * 3f);
// FPS
OwnLabel fpsLabel = new OwnLabel(I18n.txt("gui.target.fps"), skin);
frameoutputFps = new OwnTextField(nf3.format(GlobalConf.frame.RENDER_TARGET_FPS), skin, new DoubleValidator(Constants.MIN_FPS, Constants.MAX_FPS));
frameoutputFps.setWidth(textwidth * 3f);
// Size
final OwnLabel frameoutputSizeLabel = new OwnLabel(I18n.txt("gui.frameoutput.size"), skin);
frameoutputSizeLabel.setDisabled(GlobalConf.frame.isSimpleMode());
final OwnLabel xLabelfo = new OwnLabel("x", skin);
frameoutputSizeValidator = new IntValidator(GlobalConf.FrameConf.MIN_FRAME_SIZE, GlobalConf.FrameConf.MAX_FRAME_SIZE);
fowidthField = new OwnTextField(Integer.toString(MathUtils.clamp(GlobalConf.frame.RENDER_WIDTH, GlobalConf.FrameConf.MIN_FRAME_SIZE, GlobalConf.FrameConf.MAX_FRAME_SIZE)), skin, frameoutputSizeValidator);
fowidthField.setWidth(textwidth);
fowidthField.setDisabled(GlobalConf.frame.isSimpleMode());
foheightField = new OwnTextField(Integer.toString(MathUtils.clamp(GlobalConf.frame.RENDER_HEIGHT, GlobalConf.FrameConf.MIN_FRAME_SIZE, GlobalConf.FrameConf.MAX_FRAME_SIZE)), skin, frameoutputSizeValidator);
foheightField.setWidth(textwidth);
foheightField.setDisabled(GlobalConf.frame.isSimpleMode());
HorizontalGroup foSizeGroup = new HorizontalGroup();
foSizeGroup.space(pad5 * 2);
foSizeGroup.addActor(fowidthField);
foSizeGroup.addActor(xLabelfo);
foSizeGroup.addActor(foheightField);
// Mode
OwnLabel fomodeLabel = new OwnLabel(I18n.txt("gui.screenshots.mode"), skin);
ComboBoxBean[] frameoutputModes = new ComboBoxBean[] { new ComboBoxBean(I18n.txt("gui.screenshots.mode.simple"), 0), new ComboBoxBean(I18n.txt("gui.screenshots.mode.redraw"), 1) };
frameoutputMode = new OwnSelectBox<>(skin);
frameoutputMode.setItems(frameoutputModes);
frameoutputMode.setWidth(textwidth * 3f);
frameoutputMode.addListener(event -> {
if (event instanceof ChangeEvent) {
if (frameoutputMode.getSelected().value == 0) {
// Simple
enableComponents(false, fowidthField, foheightField, frameoutputSizeLabel, xLabelfo);
} else {
// Redraw
enableComponents(true, fowidthField, foheightField, frameoutputSizeLabel, xLabelfo);
}
return true;
}
return false;
});
frameoutputMode.setSelected(frameoutputModes[GlobalConf.frame.FRAME_MODE.ordinal()]);
frameoutputMode.addListener(new OwnTextTooltip(I18n.txt("gui.tooltip.screenshotmode"), skin));
OwnImageButton frameoutputModeTooltip = new OwnImageButton(skin, "tooltip");
frameoutputModeTooltip.addListener(new OwnTextTooltip(I18n.txt("gui.tooltip.screenshotmode"), skin));
HorizontalGroup foModeGroup = new HorizontalGroup();
foModeGroup.space(pad5);
foModeGroup.addActor(frameoutputMode);
foModeGroup.addActor(frameoutputModeTooltip);
// Counter
OwnLabel counterLabel = new OwnLabel(I18n.txt("gui.frameoutput.sequence"), skin);
HorizontalGroup counterGroup = new HorizontalGroup();
counterGroup.space(pad5);
OwnLabel counter = new OwnLabel(ImageRenderer.getSequenceNumber() + "", skin);
counter.setWidth(textwidth * 3f);
OwnTextButton resetCounter = new OwnTextButton(I18n.txt("gui.frameoutput.sequence.reset"), skin);
resetCounter.pad(pad10);
resetCounter.addListener((event) -> {
if (event instanceof ChangeEvent) {
ImageRenderer.resetSequenceNumber();
counter.setText("0");
}
return false;
});
counterGroup.addActor(counter);
// LABELS
labels.addAll(frameoutputLocationLabel, prefixLabel, fpsLabel, fomodeLabel, frameoutputSizeLabel);
// Add to table
frameoutput.add(frameoutputInfo).colspan(2).left().padBottom(pad5).row();
frameoutput.add(frameoutputLocationLabel).left().padRight(pad20).padBottom(pad5);
frameoutput.add(frameoutputLocation).left().expandX().padBottom(pad5).row();
frameoutput.add(prefixLabel).left().padRight(pad20).padBottom(pad5);
frameoutput.add(frameoutputPrefix).left().padBottom(pad5).row();
frameoutput.add(fpsLabel).left().padRight(pad20).padBottom(pad5);
frameoutput.add(frameoutputFps).left().padBottom(pad5).row();
frameoutput.add(fomodeLabel).left().padRight(pad20).padBottom(pad5);
frameoutput.add(foModeGroup).left().expandX().padBottom(pad5).row();
frameoutput.add(frameoutputSizeLabel).left().padRight(pad20).padBottom(pad5);
frameoutput.add(foSizeGroup).left().expandX().padBottom(pad5).row();
frameoutput.add(counterLabel).left().padRight(pad20).padBottom(pad5);
frameoutput.add(counterGroup).left().expandX().padBottom(pad5).row();
frameoutput.add().padRight(pad20);
frameoutput.add(resetCounter).left();
// Add to content
contentFrames.add(titleFrameoutput).left().padBottom(pad5 * 2).row();
contentFrames.add(frameoutput).left();
/*
* ==== CAMERA ====
*/
final Table contentCamera = new Table(skin);
contents.add(contentCamera);
contentCamera.align(Align.top | Align.left);
// CAMERA RECORDING
Table camrec = new Table(skin);
OwnLabel titleCamrec = new OwnLabel(I18n.txt("gui.camerarec.title"), skin, "header");
// fps
OwnLabel camfpsLabel = new OwnLabel(I18n.txt("gui.target.fps"), skin);
camrecFps = new OwnTextField(nf3.format(GlobalConf.frame.CAMERA_REC_TARGET_FPS), skin, new DoubleValidator(Constants.MIN_FPS, Constants.MAX_FPS));
camrecFps.setWidth(textwidth * 3f);
OwnImageButton camrecFpsTooltip = new OwnImageButton(skin, "tooltip");
camrecFpsTooltip.addListener(new OwnTextTooltip(I18n.txt("gui.tooltip.playcamera.targetfps"), skin));
// Keyframe preferences
Button keyframePrefs = new OwnTextIconButton(I18n.txt("gui.keyframes.preferences"), skin, "preferences");
keyframePrefs.setName("keyframe preferences");
keyframePrefs.pad(pad10);
keyframePrefs.addListener(new OwnTextTooltip(I18n.txt("gui.tooltip.kf.editprefs"), skin));
keyframePrefs.addListener((event) -> {
if (event instanceof ChangeListener.ChangeEvent) {
KeyframePreferencesWindow kpw = new KeyframePreferencesWindow(stage, skin);
kpw.setAcceptRunnable(() -> {
if (kpw.camrecFps != null && kpw.camrecFps.isValid()) {
camrecFps.setText(kpw.camrecFps.getText());
}
});
kpw.show(stage);
return true;
}
return false;
});
// Activate automatically
cbAutoCamrec = new OwnCheckBox(I18n.txt("gui.camerarec.frameoutput"), skin, "default", pad5);
cbAutoCamrec.setChecked(GlobalConf.frame.AUTO_FRAME_OUTPUT_CAMERA_PLAY);
cbAutoCamrec.addListener(new OwnTextTooltip(I18n.txt("gui.tooltip.playcamera.frameoutput"), skin));
OwnImageButton camrecAutoTooltip = new OwnImageButton(skin, "tooltip");
camrecAutoTooltip.addListener(new OwnTextTooltip(I18n.txt("gui.tooltip.playcamera.frameoutput"), skin));
HorizontalGroup cbGroup = new HorizontalGroup();
cbGroup.space(pad5);
cbGroup.addActor(cbAutoCamrec);
cbGroup.addActor(camrecAutoTooltip);
// LABELS
labels.add(camfpsLabel);
// Add to table
camrec.add(camfpsLabel).left().padRight(pad5 * 4).padBottom(pad5);
camrec.add(camrecFps).left().expandX().padBottom(pad5);
camrec.add(camrecFpsTooltip).left().padLeft(pad5).padBottom(pad5).row();
camrec.add(cbGroup).colspan(3).left().padBottom(pad5 * 2).row();
camrec.add(keyframePrefs).colspan(3).left().row();
// Add to content
contentCamera.add(titleCamrec).left().padBottom(pad5 * 2).row();
contentCamera.add(camrec).left();
/*
* ==== PANORAMA ====
*/
final Table content360 = new Table(skin);
contents.add(content360);
content360.align(Align.top | Align.left);
// CUBEMAP
OwnLabel titleCubemap = new OwnLabel(I18n.txt("gui.360"), skin, "header");
Table cubemap = new Table(skin);
// Info
String cminfostr = I18n.txt("gui.360.info") + '\n';
ssLines = GlobalResources.countOccurrences(cminfostr, '\n');
TextArea cmInfo = new OwnTextArea(cminfostr, skin, "info");
cmInfo.setDisabled(true);
cmInfo.setPrefRows(ssLines + 1);
cmInfo.setWidth(tawidth);
cmInfo.clearListeners();
// Resolution
OwnLabel cmResolutionLabel = new OwnLabel(I18n.txt("gui.360.resolution"), skin);
cmResolution = new OwnTextField(Integer.toString(GlobalConf.program.CUBEMAP_FACE_RESOLUTION), skin, new IntValidator(20, 15000));
cmResolution.setWidth(textwidth * 3f);
cmResolution.addListener((event) -> {
if (event instanceof ChangeEvent) {
if (cmResolution.isValid()) {
plResolution.setText(cmResolution.getText());
}
return true;
}
return false;
});
// LABELS
labels.add(cmResolutionLabel);
// Add to table
cubemap.add(cmInfo).colspan(2).left().padBottom(pad5).row();
cubemap.add(cmResolutionLabel).left().padRight(pad5 * 4).padBottom(pad5);
cubemap.add(cmResolution).left().expandX().padBottom(pad5).row();
// Add to content
content360.add(titleCubemap).left().padBottom(pad5 * 2).row();
content360.add(cubemap).left();
/*
* ==== PLANETARIUM ====
*/
final Table contentPlanetarium = new Table(skin);
contents.add(contentPlanetarium);
contentPlanetarium.align(Align.top | Align.left);
// CUBEMAP
OwnLabel titlePlanetarium = new OwnLabel(I18n.txt("gui.planetarium"), skin, "header");
Table planetarium = new Table(skin);
// Aperture
Label apertureLabel = new OwnLabel(I18n.txt("gui.planetarium.aperture"), skin);
plAperture = new OwnTextField(Float.toString(GlobalConf.program.PLANETARIUM_APERTURE), skin, new FloatValidator(30, 360));
plAperture.setWidth(textwidth * 3f);
// Skew angle
Label plangleLabel = new OwnLabel(I18n.txt("gui.planetarium.angle"), skin);
plAngle = new OwnTextField(Float.toString(GlobalConf.program.PLANETARIUM_ANGLE), skin, new FloatValidator(-180, 180));
plAngle.setWidth(textwidth * 3f);
// Info
String plinfostr = I18n.txt("gui.planetarium.info") + '\n';
ssLines = GlobalResources.countOccurrences(plinfostr, '\n');
TextArea plInfo = new OwnTextArea(plinfostr, skin, "info");
plInfo.setDisabled(true);
plInfo.setPrefRows(ssLines + 1);
plInfo.setWidth(tawidth);
plInfo.clearListeners();
// Resolution
OwnLabel plResolutionLabel = new OwnLabel(I18n.txt("gui.360.resolution"), skin);
plResolution = new OwnTextField(Integer.toString(GlobalConf.program.CUBEMAP_FACE_RESOLUTION), skin, new IntValidator(20, 15000));
plResolution.setWidth(textwidth * 3f);
plResolution.addListener((event) -> {
if (event instanceof ChangeEvent) {
if (plResolution.isValid()) {
cmResolution.setText(plResolution.getText());
}
return true;
}
return false;
});
// LABELS
labels.add(plResolutionLabel);
// Add to table
planetarium.add(apertureLabel).left().padRight(pad20).padBottom(pad10 * 3f);
planetarium.add(plAperture).left().expandX().padBottom(pad10 * 3f).row();
planetarium.add(plangleLabel).left().padRight(pad20).padBottom(pad10 * 3f);
planetarium.add(plAngle).left().expandX().padBottom(pad10 * 3f).row();
planetarium.add(plInfo).colspan(2).left().padBottom(pad5).row();
planetarium.add(plResolutionLabel).left().padRight(pad5 * 4).padBottom(pad5);
planetarium.add(plResolution).left().expandX().padBottom(pad5).row();
// Add to content
contentPlanetarium.add(titlePlanetarium).left().padBottom(pad5 * 2).row();
contentPlanetarium.add(planetarium).left();
/*
* ==== DATA ====
*/
final Table contentDataTable = new Table(skin);
contentDataTable.align(Align.top | Align.left);
final OwnScrollPane contentData = new OwnScrollPane(contentDataTable, skin, "minimalist-nobg");
contentData.setHeight(scrollh);
contentData.setScrollingDisabled(true, false);
contentData.setFadeScrollBars(false);
contents.add(contentData);
// GENERAL OPTIONS
OwnLabel titleGeneralData = new OwnLabel(I18n.txt("gui.data.options"), skin, "header");
highAccuracyPositions = new OwnCheckBox(I18n.txt("gui.data.highaccuracy"), skin, pad5);
highAccuracyPositions.setChecked(GlobalConf.data.HIGH_ACCURACY_POSITIONS);
highAccuracyPositions.addListener(new OwnTextTooltip(I18n.txt("gui.tooltip.data.highaccuracy"), skin));
OwnImageButton highAccTooltip = new OwnImageButton(skin, "tooltip");
highAccTooltip.addListener(new OwnTextTooltip(I18n.txt("gui.tooltip.data.highaccuracy"), skin));
HorizontalGroup haGroup = new HorizontalGroup();
haGroup.space(pad5);
haGroup.addActor(highAccuracyPositions);
haGroup.addActor(highAccTooltip);
// DATA SOURCE
OwnLabel titleData = new OwnLabel(I18n.txt("gui.data.source"), skin, "header");
// Info
String dsInfoStr = I18n.txt("gui.data.source.info") + '\n';
int dsLines = GlobalResources.countOccurrences(dsInfoStr, '\n');
TextArea dataSourceInfo = new OwnTextArea(dsInfoStr, skin, "info");
dataSourceInfo.setDisabled(true);
dataSourceInfo.setPrefRows(dsLines + 1);
dataSourceInfo.setWidth(tawidth);
dataSourceInfo.clearListeners();
String assetsLoc = GlobalConf.ASSETS_LOC;
dw = new DatasetsWidget(skin, assetsLoc);
Array<FileHandle> catalogFiles = dw.buildCatalogFiles();
Actor dataSource = dw.buildDatasetsWidget(catalogFiles, false, 20);
// CATALOG CHOOSER SHOW CRITERIA
OwnLabel titleCatChooser = new OwnLabel(I18n.txt("gui.data.dschooser.title"), skin, "header");
datasetChooserDefault = new OwnCheckBox(I18n.txt("gui.data.dschooser.default"), skin, "radio", pad5);
datasetChooserDefault.setChecked(GlobalConf.program.CATALOG_CHOOSER.def());
datasetChooserAlways = new OwnCheckBox(I18n.txt("gui.data.dschooser.always"), skin, "radio", pad5);
datasetChooserAlways.setChecked(GlobalConf.program.CATALOG_CHOOSER.always());
datasetChooserNever = new OwnCheckBox(I18n.txt("gui.data.dschooser.never"), skin, "radio", pad5);
datasetChooserNever.setChecked(GlobalConf.program.CATALOG_CHOOSER.never());
ButtonGroup dsCh = new ButtonGroup();
dsCh.add(datasetChooserDefault, datasetChooserAlways, datasetChooserNever);
OwnTextButton dataDownload = new OwnTextButton(I18n.txt("gui.download.title"), skin);
dataDownload.setSize(150 * GlobalConf.UI_SCALE_FACTOR, 25 * GlobalConf.UI_SCALE_FACTOR);
dataDownload.addListener((event) -> {
if (event instanceof ChangeEvent) {
if (DataDescriptor.currentDataDescriptor != null) {
DownloadDataWindow ddw = new DownloadDataWindow(stage, skin, DataDescriptor.currentDataDescriptor, false, I18n.txt("gui.close"), null);
ddw.setModal(true);
ddw.show(stage);
} else {
// Try again
FileHandle dataDescriptor = Gdx.files.absolute(SysUtils.getDefaultTmpDir() + "/gaiasky-data.json");
DownloadHelper.downloadFile(GlobalConf.program.DATA_DESCRIPTOR_URL, dataDescriptor, null, (digest) -> {
DataDescriptor dd = DataDescriptorUtils.instance().buildDatasetsDescriptor(dataDescriptor);
DownloadDataWindow ddw = new DownloadDataWindow(stage, skin, dd, false, I18n.txt("gui.close"), null);
ddw.setModal(true);
ddw.show(stage);
}, () -> {
// Fail?
logger.error("No internet connection or server is down!");
GuiUtils.addNoConnectionWindow(skin, stage);
}, null);
}
return true;
}
return false;
});
// Add to content
contentDataTable.add(titleGeneralData).left().padBottom(pad5 * 2).row();
contentDataTable.add(haGroup).left().padBottom(pad5 * 4).row();
contentDataTable.add(titleData).left().padBottom(pad5 * 2).row();
contentDataTable.add(dataSourceInfo).left().padBottom(pad5).row();
contentDataTable.add(dataSource).left().padBottom(pad5 * 4).row();
contentDataTable.add(titleCatChooser).left().padBottom(pad5 * 2).row();
contentDataTable.add(datasetChooserDefault).left().padBottom(pad5 * 2).row();
contentDataTable.add(datasetChooserAlways).left().padBottom(pad5 * 2).row();
contentDataTable.add(datasetChooserNever).left().padBottom(pad5 * 6).row();
contentDataTable.add(dataDownload).left();
/*
* ==== GAIA ====
*/
final Table contentGaia = new Table(skin);
contents.add(contentGaia);
contentGaia.align(Align.top | Align.left);
// ATTITUDE
OwnLabel titleAttitude = new OwnLabel(I18n.txt("gui.gaia.attitude"), skin, "header");
Table attitude = new Table(skin);
real = new OwnCheckBox(I18n.txt("gui.gaia.real"), skin, "radio", pad5);
real.setChecked(GlobalConf.data.REAL_GAIA_ATTITUDE);
nsl = new OwnCheckBox(I18n.txt("gui.gaia.nsl"), skin, "radio", pad5);
nsl.setChecked(!GlobalConf.data.REAL_GAIA_ATTITUDE);
new ButtonGroup<>(real, nsl);
// Add to table
attitude.add(nsl).left().padBottom(pad5).row();
attitude.add(real).left().padBottom(pad5).row();
final Cell<Actor> noticeAttCell = attitude.add((Actor) null);
noticeAttCell.colspan(2).left();
EventListener attNoticeListener = event -> {
if (event instanceof ChangeEvent) {
if (noticeAttCell.getActor() == null) {
String nextinfostr = I18n.txt("gui.ui.info") + '\n';
int lines1 = GlobalResources.countOccurrences(nextinfostr, '\n');
TextArea nextTimeInfo = new OwnTextArea(nextinfostr, skin, "info");
nextTimeInfo.setDisabled(true);
nextTimeInfo.setPrefRows(lines1 + 1);
nextTimeInfo.setWidth(tawidth);
nextTimeInfo.clearListeners();
noticeAttCell.setActor(nextTimeInfo);
}
return true;
}
return false;
};
real.addListener(attNoticeListener);
nsl.addListener(attNoticeListener);
// Add to content
contentGaia.add(titleAttitude).left().padBottom(pad5 * 2).row();
contentGaia.add(attitude).left();
/*
* ==== SYSTEM ====
*/
final Table contentSystem = new Table(skin);
contents.add(contentSystem);
contentSystem.align(Align.top | Align.left);
// STATS
OwnLabel titleStats = new OwnLabel(I18n.txt("gui.system.reporting"), skin, "header");
Table stats = new Table(skin);
debugInfoBak = GlobalConf.program.SHOW_DEBUG_INFO;
debugInfo = new OwnCheckBox(I18n.txt("gui.system.debuginfo"), skin, pad5);
debugInfo.setChecked(GlobalConf.program.SHOW_DEBUG_INFO);
debugInfo.addListener((event) -> {
if (event instanceof ChangeEvent) {
EventManager.instance.post(Events.SHOW_DEBUG_CMD, !GlobalConf.program.SHOW_DEBUG_INFO);
return true;
}
return false;
});
// EXIT CONFIRMATION
exitConfirmation = new OwnCheckBox(I18n.txt("gui.quit.confirmation"), skin, pad5);
exitConfirmation.setChecked(GlobalConf.program.EXIT_CONFIRMATION);
// RELOAD DEFAULTS
OwnTextButton reloadDefaults = new OwnTextButton(I18n.txt("gui.system.reloaddefaults"), skin);
reloadDefaults.addListener(event -> {
if (event instanceof ChangeEvent) {
reloadDefaultPreferences();
me.hide();
// Prevent saving current state
GaiaSky.instance.saveState = false;
Gdx.app.exit();
return true;
}
return false;
});
reloadDefaults.setSize(180 * GlobalConf.UI_SCALE_FACTOR, 25 * GlobalConf.UI_SCALE_FACTOR);
OwnLabel warningLabel = new OwnLabel(I18n.txt("gui.system.reloaddefaults.warn"), skin, "default-red");
// Add to table
stats.add(debugInfo).left().padBottom(pad5).row();
stats.add(exitConfirmation).left().padBottom(pad5).row();
stats.add(warningLabel).left().padBottom(pad5).row();
stats.add(reloadDefaults).left();
// Add to content
contentSystem.add(titleStats).left().padBottom(pad5 * 2).row();
contentSystem.add(stats).left();
/* COMPUTE LABEL WIDTH */
float maxLabelWidth = 0;
for (OwnLabel l : labels) {
l.pack();
if (l.getWidth() > maxLabelWidth)
maxLabelWidth = l.getWidth();
}
maxLabelWidth = Math.max(textwidth * 2, maxLabelWidth);
for (OwnLabel l : labels)
l.setWidth(maxLabelWidth);
/* ADD ALL CONTENT */
tabContent.addActor(contentGraphics);
tabContent.addActor(contentUI);
tabContent.addActor(contentPerformance);
tabContent.addActor(contentControls);
tabContent.addActor(contentScreenshots);
tabContent.addActor(contentFrames);
tabContent.addActor(contentCamera);
tabContent.addActor(content360);
tabContent.addActor(contentPlanetarium);
tabContent.addActor(contentData);
tabContent.addActor(contentGaia);
tabContent.addActor(contentSystem);
/* ADD TO MAIN TABLE */
content.add(tabContent).left().padLeft(10).expand().fill();
// Listen to changes in the tab button checked states
// Set visibility of the tab content to match the checked state
ChangeListener tab_listener = new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
if (((Button) actor).isChecked()) {
contentGraphics.setVisible(tabGraphics.isChecked());
contentUI.setVisible(tabUI.isChecked());
contentPerformance.setVisible(tabPerformance.isChecked());
contentControls.setVisible(tabControls.isChecked());
contentScreenshots.setVisible(tabScreenshots.isChecked());
contentFrames.setVisible(tabFrames.isChecked());
contentCamera.setVisible(tabCamera.isChecked());
content360.setVisible(tab360.isChecked());
contentPlanetarium.setVisible(tabPlanetarium.isChecked());
contentData.setVisible(tabData.isChecked());
contentGaia.setVisible(tabGaia.isChecked());
contentSystem.setVisible(tabSystem.isChecked());
if (lastTabFlag)
lastTab = (OwnTextIconButton) actor;
}
}
};
tabGraphics.addListener(tab_listener);
tabUI.addListener(tab_listener);
tabPerformance.addListener(tab_listener);
tabControls.addListener(tab_listener);
tabScreenshots.addListener(tab_listener);
tabFrames.addListener(tab_listener);
tabCamera.addListener(tab_listener);
tab360.addListener(tab_listener);
tabPlanetarium.addListener(tab_listener);
tabData.addListener(tab_listener);
tabGaia.addListener(tab_listener);
tabSystem.addListener(tab_listener);
lastTabFlag = false;
// Let only one tab button be checked at a time
ButtonGroup<Button> tabs = new ButtonGroup<>();
tabs.setMinCheckCount(1);
tabs.setMaxCheckCount(1);
tabs.add(tabGraphics);
tabs.add(tabUI);
tabs.add(tabPerformance);
tabs.add(tabControls);
tabs.add(tabScreenshots);
tabs.add(tabFrames);
tabs.add(tabCamera);
tabs.add(tab360);
tabs.add(tabPlanetarium);
tabs.add(tabData);
tabs.add(tabGaia);
tabs.add(tabSystem);
lastTabFlag = true;
if (lastTab != null)
tabs.setChecked(lastTab.getText().toString());
}
protected void reloadControllerMappings(Path selectedFile) {
Array<FileComboBoxBean> controllerMappingsFiles = new Array<>();
Path mappingsAssets = Path.of(GlobalConf.ASSETS_LOC, SysUtils.getMappingsDirName());
Path mappingsData = SysUtils.getDefaultMappingsDir();
Array<Path> mappingFiles = new Array<>();
GlobalResources.listRec(mappingsAssets, mappingFiles, ".inputListener", ".controller");
GlobalResources.listRec(mappingsData, mappingFiles, ".inputListener", ".controller");
FileComboBoxBean selected = null;
for (Path path : mappingFiles) {
FileComboBoxBean fcbb = new MappingFileComboBoxBean(path);
controllerMappingsFiles.add(fcbb);
if (selectedFile == null && GlobalConf.controls.CONTROLLER_MAPPINGS_FILE.endsWith(path.getFileName().toString())) {
selected = fcbb;
} else if (selectedFile != null && selectedFile.toAbsolutePath().toString().endsWith(path.getFileName().toString())) {
selected = fcbb;
}
}
controllerMappings.setItems(controllerMappingsFiles);
controllerMappings.setSelected(selected);
controllerMappings.pack();
}
protected void generateControllersList(Table table) {
Array<Controller> controllers = Controllers.getControllers();
Array<OwnLabel> controllerNames = new Array<>();
for (Controller c : controllers) {
OwnLabel cl = new OwnLabel(c.getName(), skin, "default-blue");
cl.setName(c.getName());
if (GlobalConf.controls.isControllerBlacklisted(c.getName())) {
cl.setText(cl.getText() + " [*]");
cl.setColor(1, 0, 0, 1);
cl.addListener(new OwnTextTooltip(I18n.txt("gui.tooltip.controller.blacklist"), skin));
}
controllerNames.add(cl);
}
if (controllerNames.isEmpty()) {
controllerNames.add(new OwnLabel(I18n.txt("gui.controller.nocontrollers"), skin));
}
if (table == null)
table = new Table(skin);
table.clear();
int i = 0;
for (OwnLabel cn : controllerNames) {
String controllerName = cn.getName();
table.add(cn).left().padBottom(i == controllerNames.size - 1 ? 0f : pad5 * 2f).padRight(pad10 * 2f);
if (controllerName != null && !GlobalConf.controls.isControllerBlacklisted(controllerName)) {
OwnTextButton config = new OwnTextButton("Configure", skin);
config.pad(pad5, pad5 * 2f, pad5, pad5 * 2f);
config.addListener(event -> {
if (event instanceof ChangeEvent) {
// Get currently selected mappings
ControllerMappings cm = new ControllerMappings(controllerName, Path.of(controllerMappings.getSelected().file));
ControllerConfigWindow ccw = new ControllerConfigWindow(controllerName, cm, stage, skin);
ccw.setAcceptRunnable(() -> {
if (ccw.savedFile != null) {
// File was saved, reload, select
reloadControllerMappings(ccw.savedFile);
}
});
ccw.show(stage);
return true;
}
return false;
});
table.add(config).left().padBottom(i == controllerNames.size - 1 ? 0f : pad5 * 2f).row();
} else {
table.add().left().row();
}
i++;
}
table.pack();
}
@Override
protected void accept() {
saveCurrentPreferences();
unsubscribe();
}
@Override
protected void cancel() {
revertLivePreferences();
unsubscribe();
}
private void reloadDefaultPreferences() {
// User config file
Path userFolder = SysUtils.getConfigDir();
Path userFolderConfFile = userFolder.resolve("global.properties");
// Internal config
Path confFolder = Paths.get(GlobalConf.ASSETS_LOC, "conf" + File.separator);
Path internalFolderConfFile = confFolder.resolve("global.properties");
// Delete current conf
if (Files.exists(userFolderConfFile)) {
try {
Files.delete(userFolderConfFile);
} catch (IOException e) {
logger.error(e);
}
}
// Copy file
try {
if (Files.exists(confFolder) && Files.isDirectory(confFolder)) {
// Running released package
GlobalResources.copyFile(internalFolderConfFile, userFolderConfFile, true);
logger.info("Default configuration file applied successfully! Gaia Sky will shut down now");
} else {
throw new IOException("File " + confFolder + " does not exist!");
}
} catch (Exception e) {
Logger.getLogger(this.getClass()).error(e, "Error copying default preferences file to user folder: " + userFolderConfFile);
}
}
private void saveCurrentPreferences() {
// Add all properties to GlobalConf.instance
final boolean reloadFullscreenMode = fullscreen.isChecked() != GlobalConf.screen.FULLSCREEN;
final boolean reloadScreenMode = reloadFullscreenMode || (GlobalConf.screen.FULLSCREEN && (GlobalConf.screen.FULLSCREEN_WIDTH != fullscreenResolutions.getSelected().width || GlobalConf.screen.FULLSCREEN_HEIGHT != fullscreenResolutions.getSelected().height)) || (!GlobalConf.screen.FULLSCREEN && (GlobalConf.screen.SCREEN_WIDTH != Integer.parseInt(widthField.getText())) || GlobalConf.screen.SCREEN_HEIGHT != Integer.parseInt(heightField.getText()));
GlobalConf.screen.FULLSCREEN = fullscreen.isChecked();
// Fullscreen options
GlobalConf.screen.FULLSCREEN_WIDTH = fullscreenResolutions.getSelected().width;
GlobalConf.screen.FULLSCREEN_HEIGHT = fullscreenResolutions.getSelected().height;
// Windowed options
GlobalConf.screen.SCREEN_WIDTH = Integer.parseInt(widthField.getText());
GlobalConf.screen.SCREEN_HEIGHT = Integer.parseInt(heightField.getText());
// Graphics
ComboBoxBean bean = gquality.getSelected();
if (GlobalConf.scene.GRAPHICS_QUALITY.ordinal() != bean.value) {
GlobalConf.scene.GRAPHICS_QUALITY = GraphicsQuality.values()[bean.value];
EventManager.instance.post(Events.GRAPHICS_QUALITY_UPDATED, GlobalConf.scene.GRAPHICS_QUALITY);
}
bean = aa.getSelected();
Antialias newaa = GlobalConf.postprocess.getAntialias(bean.value);
if (GlobalConf.postprocess.POSTPROCESS_ANTIALIAS != newaa) {
GlobalConf.postprocess.POSTPROCESS_ANTIALIAS = GlobalConf.postprocess.getAntialias(bean.value);
EventManager.instance.post(Events.ANTIALIASING_CMD, GlobalConf.postprocess.POSTPROCESS_ANTIALIAS);
}
GlobalConf.screen.VSYNC = vsync.isChecked();
try {
// Windows backend crashes for some reason
Gdx.graphics.setVSync(GlobalConf.screen.VSYNC);
} catch (Exception e) {
Logger.getLogger(this.getClass()).error(e);
}
if (limitfpsCb.isChecked()) {
EventManager.instance.post(Events.LIMIT_FPS_CMD, Parser.parseDouble(limitFps.getText()));
} else {
EventManager.instance.post(Events.LIMIT_FPS_CMD, 0.0);
}
// Orbit renderer
GlobalConf.scene.ORBIT_RENDERER = orbitRenderer.getSelected().value;
// Line renderer
boolean reloadLineRenderer = GlobalConf.scene.LINE_RENDERER != lineRenderer.getSelected().value;
bean = lineRenderer.getSelected();
GlobalConf.scene.LINE_RENDERER = bean.value;
// Elevation representation
ElevationType newType = elevationSb.getSelected().type;
boolean reloadElevation = newType != GlobalConf.scene.ELEVATION_TYPE;
if (reloadElevation) {
EventManager.instance.post(Events.ELEVATION_TYPE_CMD, newType);
}
// Tess quality
EventManager.instance.post(Events.TESSELLATION_QUALITY_CMD, tessQuality.getValue());
// Shadow mapping
GlobalConf.scene.SHADOW_MAPPING = shadowsCb.isChecked();
int newshadowres = Integer.parseInt(smResolution.getText());
int newnshadows = nshadows.getSelected().value;
final boolean reloadShadows = shadowsCb.isChecked() && (GlobalConf.scene.SHADOW_MAPPING_RESOLUTION != newshadowres || GlobalConf.scene.SHADOW_MAPPING_N_SHADOWS != newnshadows);
// Interface
LangComboBoxBean lbean = lang.getSelected();
String newTheme = theme.getSelected();
if (hidpiCb.isChecked()) {
newTheme += "-x2";
}
boolean reloadUI = !GlobalConf.program.UI_THEME.equals(newTheme) || !lbean.locale.toLanguageTag().equals(GlobalConf.program.LOCALE) || GlobalConf.program.MINIMAP_SIZE != minimapSize.getValue();
GlobalConf.program.LOCALE = lbean.locale.toLanguageTag();
I18n.forceInit(new FileHandle(GlobalConf.ASSETS_LOC + File.separator + "i18n/gsbundle"));
GlobalConf.program.UI_THEME = newTheme;
boolean previousPointerCoords = GlobalConf.program.DISPLAY_POINTER_COORDS;
GlobalConf.program.DISPLAY_POINTER_COORDS = pointerCoords.isChecked();
if (previousPointerCoords != GlobalConf.program.DISPLAY_POINTER_COORDS) {
EventManager.instance.post(Events.DISPLAY_POINTER_COORDS_CMD, GlobalConf.program.DISPLAY_POINTER_COORDS);
}
// Update scale factor according to theme - for HiDPI screens
GlobalConf.updateScaleFactor(GlobalConf.program.UI_THEME.endsWith("x2") ? 1.6f : 1f);
// Crosshairs
EventManager.instance.post(Events.CROSSHAIR_FOCUS_CMD, crosshairFocusCb.isChecked());
EventManager.instance.post(Events.CROSSHAIR_CLOSEST_CMD, crosshairClosestCb.isChecked());
EventManager.instance.post(Events.CROSSHAIR_HOME_CMD, crosshairHomeCb.isChecked());
// Pointer guides
EventManager.instance.post(Events.POINTER_GUIDES_CMD, pointerGuidesCb.isChecked(), pointerGuidesColor.getPickedColor(), pointerGuidesWidth.getMappedValue());
// Minimap size
GlobalConf.program.MINIMAP_SIZE = minimapSize.getValue();
// Performance
bean = numThreads.getSelected();
GlobalConf.performance.NUMBER_THREADS = bean.value;
GlobalConf.performance.MULTITHREADING = multithreadCb.isChecked();
GlobalConf.scene.OCTREE_PARTICLE_FADE = lodFadeCb.isChecked();
GlobalConf.scene.OCTANT_THRESHOLD_0 = MathUtilsd.lint(lodTransitions.getValue(), Constants.MIN_SLIDER, Constants.MAX_SLIDER, Constants.MIN_LOD_TRANS_ANGLE_DEG, Constants.MAX_LOD_TRANS_ANGLE_DEG) * (float) MathUtilsd.degRad;
// Here we use a 0.4 rad between the thresholds
GlobalConf.scene.OCTANT_THRESHOLD_1 = GlobalConf.scene.OCTREE_PARTICLE_FADE ? GlobalConf.scene.OCTANT_THRESHOLD_0 + 0.4f : GlobalConf.scene.OCTANT_THRESHOLD_0;
// Data
boolean hapos = GlobalConf.data.HIGH_ACCURACY_POSITIONS;
GlobalConf.data.HIGH_ACCURACY_POSITIONS = highAccuracyPositions.isChecked();
if (hapos != GlobalConf.data.HIGH_ACCURACY_POSITIONS) {
// Event
EventManager.instance.post(Events.HIGH_ACCURACY_CMD, GlobalConf.data.HIGH_ACCURACY_POSITIONS);
}
GlobalConf.data.CATALOG_JSON_FILES.clear();
for (Button b : dw.cbs) {
if (b.isChecked()) {
GlobalConf.data.CATALOG_JSON_FILES.add(dw.candidates.get(b));
}
}
ShowCriterion sc = ShowCriterion.DEFAULT;
if (datasetChooserDefault.isChecked())
sc = ShowCriterion.DEFAULT;
else if (datasetChooserAlways.isChecked())
sc = ShowCriterion.ALWAYS;
else if (datasetChooserNever.isChecked()) {
sc = ShowCriterion.NEVER;
}
GlobalConf.program.CATALOG_CHOOSER = sc;
// Screenshots
File ssfile = new File(screenshotsLocation.getText().toString());
if (ssfile.exists() && ssfile.isDirectory())
GlobalConf.screenshot.SCREENSHOT_FOLDER = ssfile.getAbsolutePath();
ScreenshotMode prev = GlobalConf.screenshot.SCREENSHOT_MODE;
GlobalConf.screenshot.SCREENSHOT_MODE = GlobalConf.ScreenshotMode.values()[screenshotMode.getSelectedIndex()];
int ssw = Integer.parseInt(sswidthField.getText());
int ssh = Integer.parseInt(ssheightField.getText());
boolean ssupdate = ssw != GlobalConf.screenshot.SCREENSHOT_WIDTH || ssh != GlobalConf.screenshot.SCREENSHOT_HEIGHT || !prev.equals(GlobalConf.screenshot.SCREENSHOT_MODE);
GlobalConf.screenshot.SCREENSHOT_WIDTH = ssw;
GlobalConf.screenshot.SCREENSHOT_HEIGHT = ssh;
if (ssupdate)
EventManager.instance.post(Events.SCREENSHOT_SIZE_UDPATE, GlobalConf.screenshot.SCREENSHOT_WIDTH, GlobalConf.screenshot.SCREENSHOT_HEIGHT);
// Frame output
File fofile = new File(frameoutputLocation.getText().toString());
if (fofile.exists() && fofile.isDirectory())
GlobalConf.frame.RENDER_FOLDER = fofile.getAbsolutePath();
String text = frameoutputPrefix.getText();
if (text.matches("^\\w+$")) {
GlobalConf.frame.RENDER_FILE_NAME = text;
}
prev = GlobalConf.frame.FRAME_MODE;
GlobalConf.frame.FRAME_MODE = GlobalConf.ScreenshotMode.values()[frameoutputMode.getSelectedIndex()];
int fow = Integer.parseInt(fowidthField.getText());
int foh = Integer.parseInt(foheightField.getText());
boolean foupdate = fow != GlobalConf.frame.RENDER_WIDTH || foh != GlobalConf.frame.RENDER_HEIGHT || !prev.equals(GlobalConf.frame.FRAME_MODE);
GlobalConf.frame.RENDER_WIDTH = fow;
GlobalConf.frame.RENDER_HEIGHT = foh;
GlobalConf.frame.RENDER_TARGET_FPS = Parser.parseDouble(frameoutputFps.getText());
if (foupdate)
EventManager.instance.post(Events.FRAME_SIZE_UDPATE, GlobalConf.frame.RENDER_WIDTH, GlobalConf.frame.RENDER_HEIGHT);
// Camera recording
EventManager.instance.post(Events.CAMRECORDER_FPS_CMD, Parser.parseDouble(camrecFps.getText()));
GlobalConf.frame.AUTO_FRAME_OUTPUT_CAMERA_PLAY = cbAutoCamrec.isChecked();
// Cubemap resolution (same as plResolution)
int newres = Integer.parseInt(cmResolution.getText());
if (newres != GlobalConf.program.CUBEMAP_FACE_RESOLUTION)
EventManager.instance.post(Events.CUBEMAP_RESOLUTION_CMD, newres);
// Planetarium aperture
float ap = Float.parseFloat(plAperture.getText());
if (ap != GlobalConf.program.PLANETARIUM_APERTURE) {
EventManager.instance.post(Events.PLANETARIUM_APERTURE_CMD, ap);
}
// Planetarium angle
float pa = Float.parseFloat(plAngle.getText());
if (pa != GlobalConf.program.PLANETARIUM_ANGLE) {
EventManager.instance.post(Events.PLANETARIUM_ANGLE_CMD, pa);
}
// Controllers
if (controllerMappings.getSelected() != null) {
String mappingsFile = controllerMappings.getSelected().file;
if (!mappingsFile.equals(GlobalConf.controls.CONTROLLER_MAPPINGS_FILE)) {
GlobalConf.controls.CONTROLLER_MAPPINGS_FILE = mappingsFile;
EventManager.instance.post(Events.RELOAD_CONTROLLER_MAPPINGS, mappingsFile);
}
}
GlobalConf.controls.INVERT_LOOK_X_AXIS = invertx.isChecked();
GlobalConf.controls.INVERT_LOOK_Y_AXIS = inverty.isChecked();
// Gaia attitude
GlobalConf.data.REAL_GAIA_ATTITUDE = real.isChecked();
// System
if (GlobalConf.program.SHOW_DEBUG_INFO != debugInfoBak) {
EventManager.instance.post(Events.SHOW_DEBUG_CMD, !debugInfoBak);
}
GlobalConf.program.EXIT_CONFIRMATION = exitConfirmation.isChecked();
// Save configuration
ConfInit.instance.persistGlobalConf(new File(System.getProperty("properties.file")));
EventManager.instance.post(Events.PROPERTIES_WRITTEN);
if (reloadScreenMode) {
GaiaSky.postRunnable(() -> {
EventManager.instance.post(Events.SCREEN_MODE_CMD);
});
}
if (reloadLineRenderer) {
GaiaSky.postRunnable(() -> {
EventManager.instance.post(Events.LINE_RENDERER_UPDATE);
});
}
if (reloadShadows) {
GaiaSky.postRunnable(() -> {
GlobalConf.scene.SHADOW_MAPPING_RESOLUTION = newshadowres;
GlobalConf.scene.SHADOW_MAPPING_N_SHADOWS = newnshadows;
EventManager.instance.post(Events.REBUILD_SHADOW_MAP_DATA_CMD);
});
}
if (reloadUI) {
reloadUI();
}
}
private void unsubscribe() {
EventManager.instance.removeAllSubscriptions(this);
}
/**
* Reverts preferences which have been modified live. It needs backup values.
*/
private void revertLivePreferences() {
EventManager.instance.post(Events.BRIGHTNESS_CMD, brightnessBak, true);
EventManager.instance.post(Events.CONTRAST_CMD, contrastBak, true);
EventManager.instance.post(Events.HUE_CMD, hueBak, true);
EventManager.instance.post(Events.SATURATION_CMD, saturationBak, true);
EventManager.instance.post(Events.GAMMA_CMD, gammaBak, true);
EventManager.instance.post(Events.MOTION_BLUR_CMD, motionblurBak, true);
EventManager.instance.post(Events.LENS_FLARE_CMD, lensflareBak, true);
EventManager.instance.post(Events.LIGHT_SCATTERING_CMD, lightglowBak, true);
EventManager.instance.post(Events.BLOOM_CMD, bloomBak, true);
EventManager.instance.post(Events.EXPOSURE_CMD, exposureBak, true);
EventManager.instance.post(Events.TONEMAPPING_TYPE_CMD, toneMappingBak, true);
EventManager.instance.post(Events.SHOW_DEBUG_CMD, debugInfoBak);
}
private void reloadUI() {
EventManager.instance.post(Events.UI_RELOAD_CMD);
}
private void selectFullscreen(boolean fullscreen, OwnTextField widthField, OwnTextField heightField, SelectBox<DisplayMode> fullScreenResolutions, OwnLabel widthLabel, OwnLabel heightLabel) {
if (fullscreen) {
GlobalConf.screen.SCREEN_WIDTH = fullScreenResolutions.getSelected().width;
GlobalConf.screen.SCREEN_HEIGHT = fullScreenResolutions.getSelected().height;
} else {
GlobalConf.screen.SCREEN_WIDTH = Integer.parseInt(widthField.getText());
GlobalConf.screen.SCREEN_HEIGHT = Integer.parseInt(heightField.getText());
}
enableComponents(!fullscreen, widthField, heightField, widthLabel, heightLabel);
enableComponents(fullscreen, fullScreenResolutions);
}
private int idxAa(int base, Antialias x) {
if (x.getAACode() == -1)
return 1;
if (x.getAACode() == -2)
return 2;
if (x.getAACode() == 0)
return 0;
return (int) (Math.log(x.getAACode()) / Math.log(base) + 1e-10) + 2;
}
private int idxLang(String code, LangComboBoxBean[] langs) {
if (code == null || code.isEmpty()) {
code = I18n.bundle.getLocale().toLanguageTag();
}
for (int i = 0; i < langs.length; i++) {
if (langs[i].locale.toLanguageTag().equals(code)) {
return i;
}
}
return -1;
}
private String keysToString(TreeSet<Integer> keys) {
String s = "";
int i = 0;
int n = keys.size();
for (Integer key : keys) {
s += keyToString(key).toUpperCase().replace(' ', '_');
if (i < n - 1) {
s += "+";
}
i++;
}
return s;
}
private String keyToString(int key) {
switch (key) {
case Keys.PLUS:
return "+";
default:
return Keys.toString(key);
}
}
@Override
public void notify(final Events event, final Object... data) {
switch (event) {
case CONTROLLER_CONNECTED_INFO:
case CONTROLLER_DISCONNECTED_INFO:
generateControllersList(controllersTable);
break;
default:
break;
}
}
}
| ari-zah/gaiasandbox | core/src/gaiasky/interafce/PreferencesWindow.java | Java | lgpl-3.0 | 105,686 |
package net.minecraft.src;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class CombatTracker
{
private final List field_94556_a = new ArrayList();
private final EntityLivingBase field_94554_b;
private int field_94555_c;
private boolean field_94552_d;
private boolean field_94553_e;
private String field_94551_f;
public CombatTracker(EntityLivingBase par1EntityLivingBase)
{
this.field_94554_b = par1EntityLivingBase;
}
public void func_94545_a()
{
this.func_94542_g();
if (this.field_94554_b.isOnLadder())
{
int var1 = this.field_94554_b.worldObj.getBlockId(MathHelper.floor_double(this.field_94554_b.posX), MathHelper.floor_double(this.field_94554_b.boundingBox.minY), MathHelper.floor_double(this.field_94554_b.posZ));
if (var1 == Block.ladder.blockID)
{
this.field_94551_f = "ladder";
}
else if (var1 == Block.vine.blockID)
{
this.field_94551_f = "vines";
}
}
else if (this.field_94554_b.isInWater())
{
this.field_94551_f = "water";
}
}
public void func_94547_a(DamageSource par1DamageSource, float par2, float par3)
{
this.func_94549_h();
this.func_94545_a();
CombatEntry var4 = new CombatEntry(par1DamageSource, this.field_94554_b.ticksExisted, par2, par3, this.field_94551_f, this.field_94554_b.fallDistance);
this.field_94556_a.add(var4);
this.field_94555_c = this.field_94554_b.ticksExisted;
this.field_94553_e = true;
this.field_94552_d |= var4.func_94559_f();
}
public ChatMessageComponent func_111182_b()
{
if (this.field_94556_a.size() == 0)
{
return ChatMessageComponent.func_111082_b("death.attack.generic", new Object[] {this.field_94554_b.getTranslatedEntityName()});
}
else
{
CombatEntry var1 = this.func_94544_f();
CombatEntry var2 = (CombatEntry)this.field_94556_a.get(this.field_94556_a.size() - 1);
String var4 = var2.func_94558_h();
Entity var5 = var2.func_94560_a().getEntity();
ChatMessageComponent var3;
if (var1 != null && var2.func_94560_a() == DamageSource.fall)
{
String var6 = var1.func_94558_h();
if (var1.func_94560_a() != DamageSource.fall && var1.func_94560_a() != DamageSource.outOfWorld)
{
if (var6 != null && (var4 == null || !var6.equals(var4)))
{
Entity var9 = var1.func_94560_a().getEntity();
ItemStack var8 = var9 instanceof EntityLivingBase ? ((EntityLivingBase)var9).getHeldItem() : null;
if (var8 != null && var8.hasDisplayName())
{
var3 = ChatMessageComponent.func_111082_b("death.fell.assist.item", new Object[] {this.field_94554_b.getTranslatedEntityName(), var6, var8.getDisplayName()});
}
else
{
var3 = ChatMessageComponent.func_111082_b("death.fell.assist", new Object[] {this.field_94554_b.getTranslatedEntityName(), var6});
}
}
else if (var4 != null)
{
ItemStack var7 = var5 instanceof EntityLivingBase ? ((EntityLivingBase)var5).getHeldItem() : null;
if (var7 != null && var7.hasDisplayName())
{
var3 = ChatMessageComponent.func_111082_b("death.fell.finish.item", new Object[] {this.field_94554_b.getTranslatedEntityName(), var4, var7.getDisplayName()});
}
else
{
var3 = ChatMessageComponent.func_111082_b("death.fell.finish", new Object[] {this.field_94554_b.getTranslatedEntityName(), var4});
}
}
else
{
var3 = ChatMessageComponent.func_111082_b("death.fell.killer", new Object[] {this.field_94554_b.getTranslatedEntityName()});
}
}
else
{
var3 = ChatMessageComponent.func_111082_b("death.fell.accident." + this.func_94548_b(var1), new Object[] {this.field_94554_b.getTranslatedEntityName()});
}
}
else
{
var3 = var2.func_94560_a().func_111181_b(this.field_94554_b);
}
return var3;
}
}
public EntityLivingBase func_94550_c()
{
EntityLivingBase var1 = null;
EntityPlayer var2 = null;
float var3 = 0.0F;
float var4 = 0.0F;
Iterator var5 = this.field_94556_a.iterator();
while (var5.hasNext())
{
CombatEntry var6 = (CombatEntry)var5.next();
if (var6.func_94560_a().getEntity() instanceof EntityPlayer && (var2 == null || var6.func_94563_c() > var4))
{
var4 = var6.func_94563_c();
var2 = (EntityPlayer)var6.func_94560_a().getEntity();
}
if (var6.func_94560_a().getEntity() instanceof EntityLivingBase && (var1 == null || var6.func_94563_c() > var3))
{
var3 = var6.func_94563_c();
var1 = (EntityLivingBase)var6.func_94560_a().getEntity();
}
}
if (var2 != null && var4 >= var3 / 3.0F)
{
return var2;
}
else
{
return var1;
}
}
private CombatEntry func_94544_f()
{
CombatEntry var1 = null;
CombatEntry var2 = null;
byte var3 = 0;
float var4 = 0.0F;
for (int var5 = 0; var5 < this.field_94556_a.size(); ++var5)
{
CombatEntry var6 = (CombatEntry)this.field_94556_a.get(var5);
CombatEntry var7 = var5 > 0 ? (CombatEntry)this.field_94556_a.get(var5 - 1) : null;
if ((var6.func_94560_a() == DamageSource.fall || var6.func_94560_a() == DamageSource.outOfWorld) && var6.func_94561_i() > 0.0F && (var1 == null || var6.func_94561_i() > var4))
{
if (var5 > 0)
{
var1 = var7;
}
else
{
var1 = var6;
}
var4 = var6.func_94561_i();
}
if (var6.func_94562_g() != null && (var2 == null || var6.func_94563_c() > (float)var3))
{
var2 = var6;
}
}
if (var4 > 5.0F && var1 != null)
{
return var1;
}
else if (var3 > 5 && var2 != null)
{
return var2;
}
else
{
return null;
}
}
private String func_94548_b(CombatEntry par1CombatEntry)
{
return par1CombatEntry.func_94562_g() == null ? "generic" : par1CombatEntry.func_94562_g();
}
private void func_94542_g()
{
this.field_94551_f = null;
}
private void func_94549_h()
{
int var1 = this.field_94552_d ? 300 : 100;
if (this.field_94553_e && this.field_94554_b.ticksExisted - this.field_94555_c > var1)
{
this.field_94556_a.clear();
this.field_94553_e = false;
this.field_94552_d = false;
}
}
}
| Neil5043/Minetweak | src/main/java/net/minecraft/src/CombatTracker.java | Java | lgpl-3.0 | 7,734 |
/**
* Copyright (C) 2015 Michael Schnell. All rights reserved.
* http://www.fuin.org/
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option) any
* later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library. If not, see http://www.gnu.org/licenses/.
*/
package org.fuin.srcgen4j.core.velocity;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.fuin.srcgen4j.commons.DefaultContext;
import org.fuin.srcgen4j.commons.SrcGen4J;
import org.fuin.srcgen4j.commons.SrcGen4JConfig;
import org.junit.jupiter.api.Test;
// CHECKSTYLE:OFF
class ParameterizedTemplateGeneratorTest {
private static final String TEST_RES_DIR = "src/test/resources";
private static final String TARGET_DIR = "target/test-data";
@Test
void testIntegration() throws Exception {
// PREPARE
final File expectedA = new File(TEST_RES_DIR + "/A.java");
final File expectedB = new File(TEST_RES_DIR + "/B.java");
final File expectedA2 = new File(TEST_RES_DIR + "/A2.java");
final File expectedB2 = new File(TEST_RES_DIR + "/B2.java");
final File configFile = new File(TEST_RES_DIR + "/velocity-test-config.xml");
final SrcGen4JConfig config = PTGenHelper.createAndInit(new DefaultContext(), configFile);
final SrcGen4J testee = new SrcGen4J(config, new DefaultContext());
// EXECUTE
testee.execute();
// VERIFY
// Generated using a list
final File fileA = new File(TARGET_DIR, "a/A.java");
final File fileB = new File(TARGET_DIR, "b/B.java");
assertThat(fileA).exists();
assertThat(fileB).exists();
assertThat(FileUtils.contentEquals(fileA, expectedA)).isTrue();
assertThat(FileUtils.contentEquals(fileB, expectedB)).isTrue();
// Generated using a generator
final File fileA2 = new File(TARGET_DIR, "a/A2.java");
final File fileB2 = new File(TARGET_DIR, "b/B2.java");
assertThat(fileA2).exists();
assertThat(fileB2).exists();
assertThat(FileUtils.contentEquals(fileA2, expectedA2)).isTrue();
assertThat(FileUtils.contentEquals(fileB2, expectedB2)).isTrue();
}
}
// CHECKSTYLE:ON
| fuinorg/srcgen4j-core | src/test/java/org/fuin/srcgen4j/core/velocity/ParameterizedTemplateGeneratorTest.java | Java | lgpl-3.0 | 2,834 |
///////////////////////////////////////////////////////////////////////////////
//
// PACKAGE : com.astra.ses.spell.gui.views.controls.master
//
// FILE : RecoveryComposite.java
//
// DATE : 2008-11-21 08:55
//
// Copyright (C) 2008, 2015 SES ENGINEERING, Luxembourg S.A.R.L.
//
// By using this software in any way, you are agreeing to be bound by
// the terms of this license.
//
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// which accompanies this distribution, and is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// NO WARRANTY
// EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED
// ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER
// EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR
// CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A
// PARTICULAR PURPOSE. Each Recipient is solely responsible for determining
// the appropriateness of using and distributing the Program and assumes all
// risks associated with its exercise of rights under this Agreement ,
// including but not limited to the risks and costs of program errors,
// compliance with applicable laws, damage to or loss of data, programs or
// equipment, and unavailability or interruption of operations.
//
// DISCLAIMER OF LIABILITY
// EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY
// CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION
// LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE
// EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGES.
//
// Contributors:
// SES ENGINEERING - initial API and implementation and/or initial documentation
//
// PROJECT : SPELL
//
// SUBPROJECT: SPELL GUI Client
//
///////////////////////////////////////////////////////////////////////////////
package com.astra.ses.spell.gui.views.controls.master.recovery;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.ui.PlatformUI;
import com.astra.ses.spell.gui.core.interfaces.IContextProxy;
import com.astra.ses.spell.gui.core.interfaces.ServiceManager;
import com.astra.ses.spell.gui.core.model.server.ProcedureRecoveryInfo;
import com.astra.ses.spell.gui.core.model.types.Level;
import com.astra.ses.spell.gui.core.utils.Logger;
import com.astra.ses.spell.gui.model.commands.CommandResult;
import com.astra.ses.spell.gui.model.commands.helpers.CommandHelper;
import com.astra.ses.spell.gui.model.jobs.DeleteRecoverFileJob;
import com.astra.ses.spell.gui.model.jobs.RecoverProcedureJob;
import com.astra.ses.spell.gui.procs.interfaces.IProcedureManager;
/**
* @author Rafael Chinchilla
*
*/
public class RecoveryComposite extends Composite implements SelectionListener
{
// =========================================================================
// # STATIC DATA MEMBERS
// =========================================================================
// PRIVATE -----------------------------------------------------------------
/** Button labels */
private static final String BTN_RECOVER = "Recover procedure";
private static final String BTN_REFRESH = "Refresh";
private static final String BTN_DELETE = "Delete files";
/** Procedure manager handle */
private static IProcedureManager s_procMgr = null;
/** Procedure manager handle */
private static IContextProxy s_proxy = null;
// PROTECTED ---------------------------------------------------------------
// PUBLIC ------------------------------------------------------------------
public static final String ID = "com.astra.ses.spell.gui.dialogs.RecoveryDialog";
// =========================================================================
// # INSTANCE DATA MEMBERS
// =========================================================================
// PRIVATE -----------------------------------------------------------------
/** Holds the table of contexts */
private RecoveryTable m_recoveryTable;
/** Holds the recover button */
private Button m_btnRecover;
/** Holds the refresh button */
private Button m_btnRefresh;
/** Holds the delete files button */
private Button m_btnDelete;
// PROTECTED ---------------------------------------------------------------
// PUBLIC ------------------------------------------------------------------
/***************************************************************************
*
**************************************************************************/
public RecoveryComposite( Composite parent, int style )
{
super(parent,style);
if (s_procMgr == null)
{
s_procMgr = (IProcedureManager) ServiceManager.get(IProcedureManager.class);
}
if (s_proxy == null)
{
s_proxy = (IContextProxy) ServiceManager.get(IContextProxy.class);
}
createContents();
}
/***************************************************************************
* Button callback
**************************************************************************/
@Override
public void widgetDefaultSelected(SelectionEvent e)
{
widgetSelected(e);
}
/***************************************************************************
* Button callback
**************************************************************************/
@Override
public void widgetSelected(SelectionEvent e)
{
if (e.widget instanceof Button)
{
ProcedureRecoveryInfo[] procs = m_recoveryTable.getSelectedProcedures();
if (e.widget == m_btnRecover)
{
if ((procs == null) || (procs.length == 0)) return;
doRecoverProcedure(procs);
}
else if (e.widget == m_btnRefresh)
{
doRefreshFiles();
m_recoveryTable.getTable().deselectAll();
updateButtons();
}
else if (e.widget == m_btnDelete)
{
doDeleteFiles( procs );
doRefreshFiles();
m_recoveryTable.getTable().deselectAll();
updateButtons();
}
}
else if (e.widget instanceof Table)
{
updateButtons();
}
}
/***************************************************************************
* Create the executor information group
**************************************************************************/
private void createContents()
{
GridLayout clayout = new GridLayout();
clayout.marginHeight = 2;
clayout.marginWidth = 2;
clayout.marginTop = 2;
clayout.marginBottom = 2;
clayout.marginLeft = 2;
clayout.marginRight = 2;
clayout.numColumns = 1;
setLayout(clayout);
m_recoveryTable = new RecoveryTable(this);
GridData tableLayoutData = new GridData(GridData.FILL_BOTH);
tableLayoutData.grabExcessHorizontalSpace = true;
tableLayoutData.widthHint = 700;
tableLayoutData.heightHint = 200;
m_recoveryTable.getTable().setLayoutData(tableLayoutData);
Composite buttonBar = new Composite(this, SWT.BORDER);
buttonBar.setLayout(new FillLayout(SWT.HORIZONTAL));
buttonBar.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
m_btnRecover = new Button(buttonBar, SWT.PUSH);
m_btnRecover.setText(BTN_RECOVER);
m_btnRecover.addSelectionListener(this);
m_btnRefresh = new Button(buttonBar, SWT.PUSH);
m_btnRefresh.setText(BTN_REFRESH);
m_btnRefresh.addSelectionListener(this);
m_btnDelete = new Button(buttonBar, SWT.PUSH);
m_btnDelete.setText(BTN_DELETE);
m_btnDelete.addSelectionListener(this);
updateFiles();
}
/***************************************************************************
* Update the file table
**************************************************************************/
private void updateFiles()
{
Logger.debug("Updating executors table", Level.GUI, this);
m_recoveryTable.refresh();
updateButtons();
}
/***************************************************************************
* Update button bar
**************************************************************************/
private void updateButtons()
{
ProcedureRecoveryInfo[] procs = m_recoveryTable.getSelectedProcedures();
m_btnRecover.setEnabled((procs.length > 0));
m_btnDelete.setEnabled((procs.length > 0));
}
/***************************************************************************
*
**************************************************************************/
private boolean doRecoverProcedure( ProcedureRecoveryInfo[] procs)
{
String message = "Do you really want to recover the procedure(s):\n";
for(ProcedureRecoveryInfo proc : procs)
{
message += " - " + proc.getName() + "\n";
}
if (MessageDialog.openConfirm( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Recover", message))
{
// Ensure that all are uncontrolled.
for (ProcedureRecoveryInfo proc : procs)
{
Logger.debug("Recovering procedure " + proc.getOriginalInstanceId(), Level.PROC, this);
RecoverProcedureJob job = new RecoverProcedureJob(proc);
CommandHelper.executeInProgress(job, true, true);
if (job.result == CommandResult.FAILED)
{
MessageDialog.openError(getShell(), "Recover error", job.message);
}
else if (job.result == CommandResult.CANCELLED)
{
break;
}
}
return true;
}
return false;
}
/***************************************************************************
*
**************************************************************************/
private boolean doRefreshFiles()
{
m_recoveryTable.setInput(s_proxy);
m_recoveryTable.refresh();
return true;
}
/***************************************************************************
*
**************************************************************************/
private boolean doDeleteFiles( ProcedureRecoveryInfo[] procs )
{
String message = "Do you really want to delete the recovery files for the procedure(s):\n";
for(ProcedureRecoveryInfo proc : procs)
{
message += " - " + proc.getName() + "\n";
}
if (MessageDialog.openConfirm( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Delete files", message))
{
// Ensure that all are uncontrolled.
Logger.debug("Deleting recovery file(s)", Level.PROC, this);
DeleteRecoverFileJob job = new DeleteRecoverFileJob(procs);
CommandHelper.executeInProgress(job, true, true);
if (job.result == CommandResult.FAILED)
{
MessageDialog.openError(getShell(), "Delete error", job.message);
}
else if (job.result == CommandResult.CANCELLED)
{
return false;
}
return true;
}
return false;
}
}
| Spacecraft-Code/SPELL | src/spel-gui/com.astra.ses.spell.gui/src/com/astra/ses/spell/gui/views/controls/master/recovery/RecoveryComposite.java | Java | lgpl-3.0 | 11,169 |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.hwpf.dev;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.POIDocument;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.HWPFDocumentCore;
import org.apache.poi.hwpf.HWPFOldDocument;
import org.apache.poi.hwpf.OldWordFileFormatException;
import org.apache.poi.hwpf.model.CHPX;
import org.apache.poi.hwpf.model.FieldsDocumentPart;
import org.apache.poi.hwpf.model.FileInformationBlock;
import org.apache.poi.hwpf.model.GenericPropertyNode;
import org.apache.poi.hwpf.model.LFO;
import org.apache.poi.hwpf.model.LFOData;
import org.apache.poi.hwpf.model.ListLevel;
import org.apache.poi.hwpf.model.ListTables;
import org.apache.poi.hwpf.model.PAPFormattedDiskPage;
import org.apache.poi.hwpf.model.PAPX;
import org.apache.poi.hwpf.model.PlexOfCps;
import org.apache.poi.hwpf.model.StyleDescription;
import org.apache.poi.hwpf.model.StyleSheet;
import org.apache.poi.hwpf.model.TextPiece;
import org.apache.poi.hwpf.sprm.SprmIterator;
import org.apache.poi.hwpf.sprm.SprmOperation;
import org.apache.poi.hwpf.usermodel.Bookmark;
import org.apache.poi.hwpf.usermodel.Bookmarks;
import org.apache.poi.hwpf.usermodel.Field;
import org.apache.poi.hwpf.usermodel.OfficeDrawing;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.ParagraphProperties;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.poifs.common.POIFSConstants;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DirectoryNode;
import org.apache.poi.poifs.filesystem.Entry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.Beta;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.LittleEndian;
/**
* Used by developers to list out key information on a HWPF file. End users will
* probably never need to use this program.
*
* @author Nick Burch (nick at torchbox dot com)
* @author Sergey Vladimirov (vlsergey at gmail dot com)
*/
@Beta
public final class HWPFLister
{
private static HWPFDocumentCore loadDoc( File docFile ) throws IOException
{
final FileInputStream istream = new FileInputStream( docFile );
try
{
return loadDoc( istream );
}
finally
{
IOUtils.closeQuietly( istream );
}
}
private static HWPFDocumentCore loadDoc( InputStream inputStream )
throws IOException
{
final POIFSFileSystem poifsFileSystem = HWPFDocumentCore
.verifyAndBuildPOIFS( inputStream );
try
{
return new HWPFDocument( poifsFileSystem );
}
catch ( OldWordFileFormatException exc )
{
return new HWPFOldDocument( poifsFileSystem );
}
}
public static void main( String[] args ) throws Exception
{
if ( args.length == 0 )
{
System.err.println( "Use:" );
System.err.println( "\tHWPFLister <filename>\n" + "\t\t[--dop]\n"
+ "\t\t[--textPieces] [--textPiecesText]\n"
+ "\t\t[--chpx] [--chpxProperties] [--chpxSprms]\n"
+ "\t\t[--papx] [--papxProperties] [--papxSprms]\n"
+ "\t\t[--paragraphs] [--paragraphsText]\n"
+ "\t\t[--bookmarks]\n" + "\t\t[--escher]\n"
+ "\t\t[--fields]\n" + "\t\t[--pictures]\n"
+ "\t\t[--officeDrawings]\n" + "\t\t[--styles]\n"
+ "\t\t[--writereadback]\n" );
System.exit( 1 );
}
boolean outputDop = false;
boolean outputTextPieces = false;
boolean outputTextPiecesText = false;
boolean outputChpx = false;
boolean outputChpxProperties = false;
boolean outputChpxSprms = false;
boolean outputParagraphs = false;
boolean outputParagraphsText = false;
boolean outputPapx = false;
boolean outputPapxSprms = false;
boolean outputPapxProperties = false;
boolean outputBookmarks = false;
boolean outputEscher = false;
boolean outputFields = false;
boolean outputPictures = false;
boolean outputOfficeDrawings = false;
boolean outputStyles = false;
boolean writereadback = false;
for ( String arg : Arrays.asList( args ).subList( 1, args.length ) )
{
if ( "--dop".equals( arg ) )
outputDop = true;
if ( "--textPieces".equals( arg ) )
outputTextPieces = true;
if ( "--textPiecesText".equals( arg ) )
outputTextPiecesText = true;
if ( "--chpx".equals( arg ) )
outputChpx = true;
if ( "--chpxProperties".equals( arg ) )
outputChpxProperties = true;
if ( "--chpxSprms".equals( arg ) )
outputChpxSprms = true;
if ( "--paragraphs".equals( arg ) )
outputParagraphs = true;
if ( "--paragraphsText".equals( arg ) )
outputParagraphsText = true;
if ( "--papx".equals( arg ) )
outputPapx = true;
if ( "--papxProperties".equals( arg ) )
outputPapxProperties = true;
if ( "--papxSprms".equals( arg ) )
outputPapxSprms = true;
if ( "--bookmarks".equals( arg ) )
outputBookmarks = true;
if ( "--escher".equals( arg ) )
outputEscher = true;
if ( "--fields".equals( arg ) )
outputFields = true;
if ( "--pictures".equals( arg ) )
outputPictures = true;
if ( "--officeDrawings".equals( arg ) )
outputOfficeDrawings = true;
if ( "--styles".equals( arg ) )
outputStyles = true;
if ( "--writereadback".equals( arg ) )
writereadback = true;
}
HWPFDocumentCore doc = loadDoc( new File( args[0] ) );
if ( writereadback )
doc = writeOutAndReadBack( doc );
HWPFDocumentCore original;
{
System.setProperty( "org.apache.poi.hwpf.preserveBinTables",
Boolean.TRUE.toString() );
System.setProperty( "org.apache.poi.hwpf.preserveTextTable",
Boolean.TRUE.toString() );
original = loadDoc( new File( args[0] ) );
if ( writereadback )
original = writeOutAndReadBack( original );
}
HWPFLister listerOriginal = new HWPFLister( original );
HWPFLister listerRebuilded = new HWPFLister( doc );
System.out.println( "== OLE streams ==" );
listerOriginal.dumpFileSystem();
System.out.println( "== FIB (original) ==" );
listerOriginal.dumpFIB();
if ( outputDop )
{
System.out.println( "== Document properties ==" );
listerOriginal.dumpDop();
}
if ( outputTextPieces )
{
System.out.println( "== Text pieces (original) ==" );
listerOriginal.dumpTextPieces( outputTextPiecesText );
}
if ( outputChpx )
{
System.out.println( "== CHPX (original) ==" );
listerOriginal.dumpChpx( outputChpxProperties, outputChpxSprms );
System.out.println( "== CHPX (rebuilded) ==" );
listerRebuilded.dumpChpx( outputChpxProperties, outputChpxSprms );
}
if ( outputPapx )
{
System.out.println( "== PAPX (original) ==" );
listerOriginal.dumpPapx( outputPapxProperties, outputPapxSprms );
System.out.println( "== PAPX (rebuilded) ==" );
listerRebuilded.dumpPapx( outputPapxProperties, outputPapxSprms );
}
if ( outputParagraphs )
{
System.out.println( "== Text paragraphs (original) ==" );
listerRebuilded.dumpParagraphs( true );
System.out.println( "== DOM paragraphs (rebuilded) ==" );
listerRebuilded.dumpParagraphsDom( outputParagraphsText );
}
if ( outputBookmarks )
{
System.out.println( "== BOOKMARKS (rebuilded) ==" );
listerRebuilded.dumpBookmarks();
}
if ( outputEscher )
{
System.out.println( "== ESCHER PROPERTIES (rebuilded) ==" );
listerRebuilded.dumpEscher();
}
if ( outputFields )
{
System.out.println( "== FIELDS (rebuilded) ==" );
listerRebuilded.dumpFields();
}
if ( outputOfficeDrawings )
{
System.out.println( "== OFFICE DRAWINGS (rebuilded) ==" );
listerRebuilded.dumpOfficeDrawings();
}
if ( outputPictures )
{
System.out.println( "== PICTURES (rebuilded) ==" );
listerRebuilded.dumpPictures();
}
if ( outputStyles )
{
System.out.println( "== STYLES (rebuilded) ==" );
listerRebuilded.dumpStyles();
}
}
private static HWPFDocumentCore writeOutAndReadBack(
HWPFDocumentCore original )
{
try
{
ByteArrayOutputStream baos = new ByteArrayOutputStream( 4096 );
original.write( baos );
ByteArrayInputStream bais = new ByteArrayInputStream(
baos.toByteArray() );
return loadDoc( bais );
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
}
private final HWPFDocumentCore _doc;
private LinkedHashMap<Integer, String> paragraphs;
public HWPFLister( HWPFDocumentCore doc )
{
_doc = doc;
buildParagraphs();
}
private void buildParagraphs()
{
paragraphs = new LinkedHashMap<Integer, String>();
StringBuilder part = new StringBuilder();
String text = _doc.getDocumentText();
for ( int charIndex = 0; charIndex < text.length(); charIndex++ )
{
char c = text.charAt( charIndex );
part.append( c );
if ( c == 13 || c == 7 || c == 12 )
{
paragraphs.put( Integer.valueOf( charIndex ), part.toString() );
part.setLength( 0 );
}
}
}
private void dumpBookmarks()
{
if ( !( _doc instanceof HWPFDocument ) )
{
System.out.println( "Word 95 not supported so far" );
return;
}
HWPFDocument document = (HWPFDocument) _doc;
Bookmarks bookmarks = document.getBookmarks();
for ( int b = 0; b < bookmarks.getBookmarksCount(); b++ )
{
Bookmark bookmark = bookmarks.getBookmark( b );
System.out.println( "[" + bookmark.getStart() + "; "
+ bookmark.getEnd() + "): " + bookmark.getName() );
}
}
public void dumpChpx( boolean withProperties, boolean withSprms )
{
for ( CHPX chpx : _doc.getCharacterTable().getTextRuns() )
{
System.out.println( chpx );
if ( withProperties )
{
System.out.println( chpx.getCharacterProperties(
_doc.getStyleSheet(), (short) StyleSheet.NIL_STYLE ) );
}
if ( withSprms )
{
SprmIterator sprmIt = new SprmIterator( chpx.getGrpprl(), 0 );
while ( sprmIt.hasNext() )
{
SprmOperation sprm = sprmIt.next();
System.out.println( "\t" + sprm.toString() );
}
}
if ( true )
{
String text = new Range( chpx.getStart(), chpx.getEnd(),
_doc.getOverallRange() )
{
public String toString()
{
return "CHPX range (" + super.toString() + ")";
}
}.text();
StringBuilder stringBuilder = new StringBuilder();
for ( char c : text.toCharArray() )
{
if ( c < 30 )
stringBuilder
.append( "\\0x" + Integer.toHexString( c ) );
else
stringBuilder.append( c );
}
System.out.println( stringBuilder );
}
}
}
private void dumpDop()
{
if ( !( _doc instanceof HWPFDocument ) )
{
System.out.println( "Word 95 not supported so far" );
return;
}
System.out.println( ( (HWPFDocument) _doc ).getDocProperties() );
}
private void dumpEscher()
{
if ( _doc instanceof HWPFOldDocument )
{
System.out.println( "Word 95 not supported so far" );
return;
}
System.out.println( ( (HWPFDocument) _doc ).getEscherRecordHolder() );
}
public void dumpFIB()
{
FileInformationBlock fib = _doc.getFileInformationBlock();
System.out.println( fib );
}
private void dumpFields()
{
if ( !( _doc instanceof HWPFDocument ) )
{
System.out.println( "Word 95 not supported so far" );
return;
}
HWPFDocument document = (HWPFDocument) _doc;
for ( FieldsDocumentPart part : FieldsDocumentPart.values() )
{
System.out.println( "=== Document part: " + part + " ===" );
for ( Field field : document.getFields().getFields( part ) )
{
System.out.println( field );
}
}
}
public void dumpFileSystem() throws Exception
{
java.lang.reflect.Field field = POIDocument.class
.getDeclaredField( "directory" );
field.setAccessible( true );
DirectoryNode directoryNode = (DirectoryNode) field.get( _doc );
System.out.println( dumpFileSystem( directoryNode ) );
}
private String dumpFileSystem( DirectoryEntry directory )
{
StringBuilder result = new StringBuilder();
result.append( "+ " );
result.append( directory.getName() );
for ( Iterator<Entry> iterator = directory.getEntries(); iterator
.hasNext(); )
{
Entry entry = iterator.next();
String entryToString = "\n" + dumpFileSystem( entry );
entryToString = entryToString.replaceAll( "\n", "\n+---" );
result.append( entryToString );
}
result.append( "\n" );
return result.toString();
}
private String dumpFileSystem( Entry entry )
{
if ( entry instanceof DirectoryEntry )
return dumpFileSystem( (DirectoryEntry) entry );
return entry.getName();
}
private void dumpOfficeDrawings()
{
if ( !( _doc instanceof HWPFDocument ) )
{
System.out.println( "Word 95 not supported so far" );
return;
}
HWPFDocument document = (HWPFDocument) _doc;
if ( document.getOfficeDrawingsHeaders() != null )
{
System.out.println( "=== Document part: HEADER ===" );
for ( OfficeDrawing officeDrawing : document
.getOfficeDrawingsHeaders().getOfficeDrawings() )
{
System.out.println( officeDrawing );
}
}
if ( document.getOfficeDrawingsHeaders() != null )
{
System.out.println( "=== Document part: MAIN ===" );
for ( OfficeDrawing officeDrawing : document
.getOfficeDrawingsMain().getOfficeDrawings() )
{
System.out.println( officeDrawing );
}
}
}
public void dumpPapx( boolean withProperties, boolean withSprms )
throws Exception
{
if ( _doc instanceof HWPFDocument )
{
System.out.println( "binary PAP pages " );
HWPFDocument doc = (HWPFDocument) _doc;
java.lang.reflect.Field fMainStream = HWPFDocumentCore.class
.getDeclaredField( "_mainStream" );
fMainStream.setAccessible( true );
byte[] mainStream = (byte[]) fMainStream.get( _doc );
PlexOfCps binTable = new PlexOfCps( doc.getTableStream(), doc
.getFileInformationBlock().getFcPlcfbtePapx(), doc
.getFileInformationBlock().getLcbPlcfbtePapx(), 4 );
List<PAPX> papxs = new ArrayList<PAPX>();
int length = binTable.length();
for ( int x = 0; x < length; x++ )
{
GenericPropertyNode node = binTable.getProperty( x );
int pageNum = LittleEndian.getInt( node.getBytes() );
int pageOffset = POIFSConstants.SMALLER_BIG_BLOCK_SIZE
* pageNum;
PAPFormattedDiskPage pfkp = new PAPFormattedDiskPage(
mainStream, doc.getDataStream(), pageOffset,
doc.getTextTable() );
System.out.println( "* PFKP: " + pfkp );
for ( PAPX papx : pfkp.getPAPXs() )
{
System.out.println( "** " + papx );
papxs.add( papx );
if ( papx != null && withSprms )
{
SprmIterator sprmIt = new SprmIterator(
papx.getGrpprl(), 2 );
dumpSprms( sprmIt, "*** " );
}
}
}
Collections.sort( papxs );
System.out.println( "* Sorted by END" );
for ( PAPX papx : papxs )
{
System.out.println( "** " + papx );
if ( papx != null && withSprms )
{
SprmIterator sprmIt = new SprmIterator( papx.getGrpprl(), 2 );
dumpSprms( sprmIt, "*** " );
}
}
}
Method newParagraph = Paragraph.class.getDeclaredMethod(
"newParagraph", Range.class, PAPX.class );
newParagraph.setAccessible( true );
java.lang.reflect.Field _props = Paragraph.class
.getDeclaredField( "_props" );
_props.setAccessible( true );
for ( PAPX papx : _doc.getParagraphTable().getParagraphs() )
{
System.out.println( papx );
if ( withProperties )
{
Paragraph paragraph = (Paragraph) newParagraph.invoke( null,
_doc.getOverallRange(), papx );
System.out.println( _props.get( paragraph ) );
}
if ( true )
{
SprmIterator sprmIt = new SprmIterator( papx.getGrpprl(), 2 );
dumpSprms( sprmIt, "\t" );
}
}
}
public void dumpParagraphs( boolean dumpAssotiatedPapx )
{
for ( Map.Entry<Integer, String> entry : paragraphs.entrySet() )
{
Integer endOfParagraphCharOffset = entry.getKey();
System.out.println( "[...; " + ( endOfParagraphCharOffset + 1 )
+ "): " + entry.getValue() );
if ( dumpAssotiatedPapx )
{
boolean hasAssotiatedPapx = false;
for ( PAPX papx : _doc.getParagraphTable().getParagraphs() )
{
if ( papx.getStart() <= endOfParagraphCharOffset.intValue()
&& endOfParagraphCharOffset.intValue() < papx
.getEnd() )
{
hasAssotiatedPapx = true;
System.out.println( "* " + papx );
SprmIterator sprmIt = new SprmIterator(
papx.getGrpprl(), 2 );
dumpSprms( sprmIt, "** " );
}
}
if ( !hasAssotiatedPapx )
{
System.out.println( "* "
+ "NO PAPX ASSOTIATED WITH PARAGRAPH!" );
}
}
}
}
protected void dumpSprms( SprmIterator sprmIt, String linePrefix )
{
while ( sprmIt.hasNext() )
{
SprmOperation sprm = sprmIt.next();
System.out.println( linePrefix + sprm.toString() );
}
}
public void dumpParagraphsDom( boolean withText )
{
Range range = _doc.getOverallRange();
for ( int p = 0; p < range.numParagraphs(); p++ )
{
Paragraph paragraph = range.getParagraph( p );
System.out.println( p + ":\t" + paragraph.toString() );
if ( withText )
System.out.println( paragraph.text() );
}
}
private void dumpPictures()
{
if ( _doc instanceof HWPFOldDocument )
{
System.out.println( "Word 95 not supported so far" );
return;
}
List<Picture> allPictures = ( (HWPFDocument) _doc ).getPicturesTable()
.getAllPictures();
for ( Picture picture : allPictures )
{
System.out.println( picture.toString() );
}
}
private void dumpStyles()
{
if ( _doc instanceof HWPFOldDocument )
{
System.out.println( "Word 95 not supported so far" );
return;
}
HWPFDocument hwpfDocument = (HWPFDocument) _doc;
for ( int s = 0; s < hwpfDocument.getStyleSheet().numStyles(); s++ )
{
StyleDescription styleDescription = hwpfDocument.getStyleSheet()
.getStyleDescription( s );
if ( styleDescription == null )
continue;
System.out.println( "=== Style #" + s + " '"
+ styleDescription.getName() + "' ===" );
System.out.println( styleDescription );
if ( styleDescription.getPAPX() != null )
dumpSprms( new SprmIterator( styleDescription.getPAPX(), 2 ),
"Style's PAP SPRM: " );
if ( styleDescription.getCHPX() != null )
dumpSprms( new SprmIterator( styleDescription.getCHPX(), 0 ),
"Style's CHP SPRM: " );
}
}
protected void dumpParagraphLevels( ListTables listTables,
ParagraphProperties paragraph )
{
if ( paragraph.getIlfo() != 0 )
{
final LFO lfo = listTables.getLfo( paragraph.getIlfo() );
System.out.println( "PAP's LFO: " + lfo );
final LFOData lfoData = listTables.getLfoData( paragraph.getIlfo() );
System.out.println( "PAP's LFOData: " + lfoData );
if ( lfo != null )
{
final ListLevel listLevel = listTables.getLevel( lfo.getLsid(),
paragraph.getIlvl() );
System.out.println( "PAP's ListLevel: " + listLevel );
if ( listLevel.getGrpprlPapx() != null )
{
System.out.println( "PAP's ListLevel PAPX:" );
dumpSprms(
new SprmIterator( listLevel.getGrpprlPapx(), 0 ),
"* " );
}
if ( listLevel.getGrpprlPapx() != null )
{
System.out.println( "PAP's ListLevel CHPX:" );
dumpSprms(
new SprmIterator( listLevel.getGrpprlChpx(), 0 ),
"* " );
}
}
}
}
public void dumpTextPieces( boolean withText )
{
for ( TextPiece textPiece : _doc.getTextTable().getTextPieces() )
{
System.out.println( textPiece );
if ( withText )
{
System.out.println( "\t" + textPiece.getStringBuilder() );
}
}
}
}
| rmage/gnvc-ims | stratchpad/org/apache/poi/hwpf/dev/HWPFLister.java | Java | lgpl-3.0 | 25,630 |
/*
* SonarQube CSS / SCSS / Less Analyzer
* Copyright (C) 2013-2017 David RACODON
* mailto: [email protected]
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.css.model.property.standard;
import org.sonar.css.model.property.StandardProperty;
public class Binding extends StandardProperty {
public Binding() {
setObsolete(true);
}
}
| racodond/sonar-css-plugin | css-frontend/src/main/java/org/sonar/css/model/property/standard/Binding.java | Java | lgpl-3.0 | 1,069 |
package org.pg5100.exam.frontend;
import org.junit.Before;
import org.junit.Test;
import org.pg5100.exam.frontend.po.CreateUserPageObject;
import org.pg5100.exam.frontend.po.HomePageObject;
import org.pg5100.exam.frontend.po.LoginPageObject;
import static org.junit.Assert.*;
public class UserCreateAndLoginIT extends WebTestBase{
@Test
public void testHomePage(){
home.toStartingPage();
assertTrue(home.isOnPage());
}
@Test
public void testLoginLink(){
LoginPageObject login = home.toLogin();
assertTrue(login.isOnPage());
}
@Test
public void testLoginWrongUser(){
LoginPageObject login = home.toLogin();
HomePageObject home = login.clickLogin(getUniqueId(),"foo");
assertNull(home);
assertTrue(login.isOnPage());
}
@Test
public void testLogin(){
String userId = getUniqueId();
createAndLogNewUser(userId, "Joe", "Black");
home.logout();
assertFalse(home.isLoggedIn());
LoginPageObject login = home.toLogin();
home = login.clickLogin(userId, "foo");
assertNotNull(home);
assertTrue(home.isOnPage());
assertTrue(home.isLoggedIn(userId));
}
@Test
public void testCreateValidUser(){
LoginPageObject login = home.toLogin();
CreateUserPageObject create = login.clickCreateNewUser();
assertTrue(create.isOnPage());
String userName = getUniqueId();
HomePageObject home = create.createUser(userName,"foo","foo","Foo","","Bar");
assertNotNull(home);
assertTrue(home.isOnPage());
assertTrue(home.isLoggedIn(userName));
home.logout();
assertFalse(home.isLoggedIn());
}
@Test
public void testCreateUserFailDueToPasswordMismatch(){
LoginPageObject login = home.toLogin();
CreateUserPageObject create = login.clickCreateNewUser();
HomePageObject home = create.createUser(getUniqueId(),"foo","differentPassword","Foo","","Bar");
assertNull(home);
assertTrue(create.isOnPage());
}
}
| arcuri82/pg5100_autumn_2016 | exam/frontend/src/test/java/org/pg5100/exam/frontend/UserCreateAndLoginIT.java | Java | lgpl-3.0 | 2,116 |
package com.github.cunvoas.mail;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
/**
* Compte d'authentification de messagerie.
* @author CUNVOAS
* @see javax.mail.Authenticator
*/
public class MailSenderAccount extends Authenticator {
private String user;
private String password;
/**
* @see javax.mail.Authenticator#getPasswordAuthentication()
*/
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
/**
* Constructeur.
* @param user
* @param password
*/
public MailSenderAccount(String user, String password) {
this.user=user;
this.password=password;
}
}
| cunvoas/email-tool | src/main/java/com/github/cunvoas/mail/MailSenderAccount.java | Java | lgpl-3.0 | 687 |
/*
* $Id: AbstractPage.java 102464 2013-08-21 15:35:16Z nahlikm1 $
*
* Copyright (c) 2010 AspectWorks, spol. s r.o.
*/
package com.pageobject.component;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import com.pageobject.TableControl;
import com.pageobject.controller.BrowserController;
/**
* Convenience base class for all Pages that are used for tests.
* Don't forget to annotate the page with {@link Page} annotation.
*
* <p>This class offers lifecycle methods {@link #isValidPage()} and {@link #init(Object...)}
* as well as logic for navigation: {@link #navigateTo(Class, Object...)}.
*
* @author Pavel Muller
* @version $Revision: 102464 $
*/
public abstract class AbstractPage extends AbstractComponent {
/**
* Navigates to a given page.
* Optionally you may specify init parameter to pass to the page.
* <p>This method creates a prototype page bean, call {@link #assertValidPage()} and
* {@link #init(Object...)} with optioanal init parameters.
* @param pageClass class with {@link Page} annotation
* @param params optional parameters to pass to the page
* @return configured page
* @throws IllegalArgumentException if the page class is not annotated with {@link Page}
*/
protected <T extends AbstractPage> T navigateTo(Class<T> pageClass, Object... params) {
logger.info("Navigating to page '{}'", pageClass.getSimpleName());
T page;
// get page prototype bean from Spring context
try {
page = applicationContext.getBean(pageClass);
} catch (NoSuchBeanDefinitionException e) {
IllegalArgumentException ex = new IllegalArgumentException("Page '" + pageClass.getSimpleName() + "' not found. " +
"Is it configured properly? Use @Page annotation.", e);
logger.error(ex.getMessage(), ex);
throw ex;
} catch (BeansException e) {
IllegalArgumentException ex = new IllegalArgumentException("Page '" + pageClass.getSimpleName() + "' configuration problem.", e);
logger.error(ex.getMessage(), ex);
throw ex;
}
// initialize page
page.init(params);
// check if the browser is on this page
if (!page.isValidPage()) {
throw new IllegalStateException("Browser state is invalid when trying to navigate to " + getClass().getSimpleName() +
". Current window title is: " + browser.getTitle());
}
return page;
}
/**
* Callback to initialize the page.
* @param params optional parameters, may be <code>null</code>
*/
protected void init(Object... params) {
}
/**
* Checks whether the browser is on the current page.
* Override this method if you need this check.
* @see ValidPageAspect
*/
public abstract boolean isValidPage();
/**
* Close current browser window and select the main one.
*/
public void closePage() {
browser.closePage();
browser.selectWindow("null");
}
/**
* Return the title of current page.
*
* @see {@link BrowserController#getTitle()}
*
* @return The title of current page.
*/
public String getTitle() {
return browser.getTitle();
}
/**
* Returns the current web page state.
*
* @see {@link BrowserController#getPageState()}
*
* @return String representation of that state.
*/
public String getPageState() {
return browser.getPageState();
}
/**
* Checks if the page is fully loaded.
*
* @see {@link BrowserController#isPageLoaded()}
*
* @return true if the page is fully loaded, false otherwise.
*/
public boolean isPageLoaded() {
return browser.isPageLoaded();
}
/**
* Waits for the page to be fully loaded.
*
* @see {@link BrowserController#waitForPageToLoad(long)}
*
* @param timeout
* the amount of time that should be waited at top, expressed in
* milliseconds.
*/
public void waitForPageToLoad(long timeout) {
browser.waitForPageToLoad(timeout);
}
/**
* Returns {@link TableControl} for specified table locator.
* Creates new table control for each call.
* @return configured table control
*/
public TableControl getTableControl() {
return applicationContext.getBean(TableControl.class);
}
}
| selenium-pageobject/pageobject | src/main/java/com/pageobject/component/AbstractPage.java | Java | lgpl-3.0 | 4,161 |
/*
* (C) Copyright 2014 Instituto de Pesquisas Eldorado (http://www.eldorado.org.br/).
*
* This file is part of the software Remote Resources
*
* All rights reserved. This file and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 3.0 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* This file is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
package com.eldorado.remoteresources.utils;
public enum SubType {
NONE, PULL, PUSH, INSTALL, UNINSTALL
} | IPEldorado/RemoteResources | src/com/eldorado/remoteresources/utils/SubType.java | Java | lgpl-3.0 | 778 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tablealias.dinue.helpers;
/**
*
* @author INEGI
*/
public interface WhereGenerator {
String getWhere();
}
| MxSIG/TableAliasV60 | TableAliasV60/src/main/java/tablealias/dinue/helpers/WhereGenerator.java | Java | lgpl-3.0 | 225 |
/*
* Mivvi - Metadata, organisation and identification for television programs
* Copyright © 2004-2016 Joseph Walton
*
* This library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation, either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <https://www.gnu.org/licenses/>.
*/
package org.kafsemo.mivvi.app;
import java.io.File;
import java.io.IOException;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.ValueFactory;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
import org.kafsemo.mivvi.rdf.IdentifierMappings;
import junit.framework.TestCase;
public class TestUriSetFile extends TestCase
{
/**
* Test updating a <code>UriSetFile</code> according to an <code>IdentifierMappings</code>.
*
* @throws IOException
*/
public void testMapIdentifiers() throws IOException
{
ValueFactory vf = SimpleValueFactory.getInstance();
IRI orig = vf.createIRI("http://www.example.com/orig-episode-uri"),
newUri = vf.createIRI("http://www.example.com/new-episode-uri"),
other = vf.createIRI("http://www.example.com/other-episode-uri");
IdentifierMappings im = new IdentifierMappings();
im.put(orig, newUri);
File f = File.createTempFile(getClass().getName(), "uris");
f.deleteOnExit();
UriSetFile usf = new UriSetFile(f);
usf.add(orig);
usf.add(other);
usf.update(im);
assertFalse("The original URI should no longer be present", usf.contains(orig));
assertTrue("The new URI should now be present", usf.contains(newUri));
assertTrue("The other URI should be unaffected", usf.contains(other));
}
}
| josephw/mivvi | rdf/src/test/java/org/kafsemo/mivvi/app/TestUriSetFile.java | Java | lgpl-3.0 | 2,204 |
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2013 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* SonarQube is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.squid.math;
import org.junit.Before;
import org.junit.Test;
import org.sonar.squid.api.SourceCode;
import org.sonar.squid.api.SourceFile;
import org.sonar.squid.measures.Metric;
import java.util.Arrays;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class MeasuresDistributionTest {
private MeasuresDistribution distribution;
@Before
public void setup() {
SourceFile file0 = newFile("File0.java", 0);
SourceFile file1 = newFile("File1.java", 1);
SourceFile file8 = newFile("File8.java", 8);
SourceFile file10 = newFile("File10.java", 10);
SourceFile file20 = newFile("File20.java", 20);
SourceFile file21 = newFile("File21.java", 21);
SourceFile file30 = newFile("File3.java", 30);
distribution = new MeasuresDistribution(Arrays.<SourceCode>asList(file0, file1, file8, file10, file20, file21, file30));
}
private SourceFile newFile(String filename, int complexity) {
SourceFile file0 = new SourceFile(filename);
file0.setMeasure(Metric.COMPLEXITY, complexity);
return file0;
}
@Test
public void testComplexityDistribution() {
Map<Integer, Integer> intervals = distribution.distributeAccordingTo(Metric.COMPLEXITY, 1, 10, 18, 25);
assertEquals(4, intervals.size());
assertEquals(2, (int) intervals.get(1)); // between 1 included and 10 excluded
assertEquals(1, (int) intervals.get(10));// between 10 included and 18 excluded
assertEquals(2, (int) intervals.get(18));
assertEquals(1, (int) intervals.get(25)); // >= 25
}
}
| xinghuangxu/xinghuangxu.sonarqube | sonar-squid/src/test/java/org/sonar/squid/math/MeasuresDistributionTest.java | Java | lgpl-3.0 | 2,446 |
/*
* This class was automatically generated with
* <a href="http://www.castor.org">Castor 1.3.1</a>, using an XML
* Schema.
* $Id: CreditCardChargeRetChoiceItem.java,v 1.1.1.1 2010-05-04 22:05:59 ryan Exp $
*/
package org.chocolate_milk.model;
/**
* Class CreditCardChargeRetChoiceItem.
*
* @version $Revision: 1.1.1.1 $ $Date: 2010-05-04 22:05:59 $
*/
@SuppressWarnings("serial")
public class CreditCardChargeRetChoiceItem implements java.io.Serializable {
//--------------------------/
//- Class/Member Variables -/
//--------------------------/
/**
* Field _itemLineRet.
*/
private org.chocolate_milk.model.ItemLineRet _itemLineRet;
/**
* Field _itemGroupLineRet.
*/
private org.chocolate_milk.model.ItemGroupLineRet _itemGroupLineRet;
//----------------/
//- Constructors -/
//----------------/
public CreditCardChargeRetChoiceItem() {
super();
}
//-----------/
//- Methods -/
//-----------/
/**
* Returns the value of field 'itemGroupLineRet'.
*
* @return the value of field 'ItemGroupLineRet'.
*/
public org.chocolate_milk.model.ItemGroupLineRet getItemGroupLineRet(
) {
return this._itemGroupLineRet;
}
/**
* Returns the value of field 'itemLineRet'.
*
* @return the value of field 'ItemLineRet'.
*/
public org.chocolate_milk.model.ItemLineRet getItemLineRet(
) {
return this._itemLineRet;
}
/**
* Sets the value of field 'itemGroupLineRet'.
*
* @param itemGroupLineRet the value of field 'itemGroupLineRet'
*/
public void setItemGroupLineRet(
final org.chocolate_milk.model.ItemGroupLineRet itemGroupLineRet) {
this._itemGroupLineRet = itemGroupLineRet;
}
/**
* Sets the value of field 'itemLineRet'.
*
* @param itemLineRet the value of field 'itemLineRet'.
*/
public void setItemLineRet(
final org.chocolate_milk.model.ItemLineRet itemLineRet) {
this._itemLineRet = itemLineRet;
}
}
| galleon1/chocolate-milk | src/org/chocolate_milk/model/CreditCardChargeRetChoiceItem.java | Java | lgpl-3.0 | 2,112 |
package micdoodle8.mods.galacticraft.planets.mars.nei;
import codechicken.nei.PositionedStack;
import codechicken.nei.api.API;
import codechicken.nei.api.IConfigureNEI;
import micdoodle8.mods.galacticraft.core.Constants;
import micdoodle8.mods.galacticraft.core.items.GCItems;
import micdoodle8.mods.galacticraft.planets.asteroids.items.AsteroidsItems;
import micdoodle8.mods.galacticraft.planets.mars.blocks.MarsBlocks;
import micdoodle8.mods.galacticraft.planets.mars.items.MarsItems;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class NEIGalacticraftMarsConfig implements IConfigureNEI
{
private static HashMap<ArrayList<PositionedStack>, PositionedStack> rocketBenchRecipes = new HashMap<ArrayList<PositionedStack>, PositionedStack>();
private static HashMap<ArrayList<PositionedStack>, PositionedStack> cargoBenchRecipes = new HashMap<ArrayList<PositionedStack>, PositionedStack>();
private static HashMap<PositionedStack, PositionedStack> liquefierRecipes = new HashMap<PositionedStack, PositionedStack>();
private static HashMap<PositionedStack, PositionedStack> synthesizerRecipes = new HashMap<PositionedStack, PositionedStack>();
@Override
public void loadConfig()
{
this.registerRecipes();
API.registerRecipeHandler(new RocketT2RecipeHandler());
API.registerUsageHandler(new RocketT2RecipeHandler());
API.registerRecipeHandler(new CargoRocketRecipeHandler());
API.registerUsageHandler(new CargoRocketRecipeHandler());
API.registerRecipeHandler(new GasLiquefierRecipeHandler());
API.registerUsageHandler(new GasLiquefierRecipeHandler());
API.registerRecipeHandler(new MethaneSynthesizerRecipeHandler());
API.registerUsageHandler(new MethaneSynthesizerRecipeHandler());
API.registerHighlightIdentifier(MarsBlocks.marsBlock, new GCMarsNEIHighlightHandler());
}
@Override
public String getName()
{
return "Galacticraft Mars NEI Plugin";
}
@Override
public String getVersion()
{
return Constants.LOCALMAJVERSION + "." + Constants.LOCALMINVERSION + "." + Constants.LOCALBUILDVERSION;
}
public void registerRocketBenchRecipe(ArrayList<PositionedStack> input, PositionedStack output)
{
NEIGalacticraftMarsConfig.rocketBenchRecipes.put(input, output);
}
public void registerCargoBenchRecipe(ArrayList<PositionedStack> input, PositionedStack output)
{
NEIGalacticraftMarsConfig.cargoBenchRecipes.put(input, output);
}
public static Set<Map.Entry<ArrayList<PositionedStack>, PositionedStack>> getRocketBenchRecipes()
{
return NEIGalacticraftMarsConfig.rocketBenchRecipes.entrySet();
}
public static Set<Map.Entry<ArrayList<PositionedStack>, PositionedStack>> getCargoBenchRecipes()
{
return NEIGalacticraftMarsConfig.cargoBenchRecipes.entrySet();
}
private void registerLiquefierRecipe(PositionedStack inputStack, PositionedStack outputStack)
{
NEIGalacticraftMarsConfig.liquefierRecipes.put(inputStack, outputStack);
}
public static Set<Entry<PositionedStack, PositionedStack>> getLiquefierRecipes()
{
return NEIGalacticraftMarsConfig.liquefierRecipes.entrySet();
}
private void registerSynthesizerRecipe(PositionedStack inputStack, PositionedStack outputStack)
{
NEIGalacticraftMarsConfig.synthesizerRecipes.put(inputStack, outputStack);
}
public static Set<Entry<PositionedStack, PositionedStack>> getSynthesizerRecipes()
{
return NEIGalacticraftMarsConfig.synthesizerRecipes.entrySet();
}
public void registerRecipes()
{
final int changeY = 15;
ArrayList<PositionedStack> input1 = new ArrayList<PositionedStack>();
input1.add(new PositionedStack(new ItemStack(GCItems.partNoseCone), 45, -8 + changeY));
input1.add(new PositionedStack(new ItemStack(MarsItems.marsItemBasic, 1, 3), 36, -6 + 16 + changeY));
input1.add(new PositionedStack(new ItemStack(MarsItems.marsItemBasic, 1, 3), 36, -6 + 18 + 16 + changeY));
input1.add(new PositionedStack(new ItemStack(MarsItems.marsItemBasic, 1, 3), 36, -6 + 36 + 16 + changeY));
input1.add(new PositionedStack(new ItemStack(MarsItems.marsItemBasic, 1, 3), 36, -6 + 54 + 16 + changeY));
input1.add(new PositionedStack(new ItemStack(MarsItems.marsItemBasic, 1, 3), 36, -6 + 72 + 16 + changeY));
input1.add(new PositionedStack(new ItemStack(MarsItems.marsItemBasic, 1, 3), 54, -6 + 16 + changeY));
input1.add(new PositionedStack(new ItemStack(MarsItems.marsItemBasic, 1, 3), 54, -6 + 18 + 16 + changeY));
input1.add(new PositionedStack(new ItemStack(MarsItems.marsItemBasic, 1, 3), 54, -6 + 36 + 16 + changeY));
input1.add(new PositionedStack(new ItemStack(MarsItems.marsItemBasic, 1, 3), 54, -6 + 54 + 16 + changeY));
input1.add(new PositionedStack(new ItemStack(MarsItems.marsItemBasic, 1, 3), 54, -6 + 72 + 16 + changeY));
input1.add(new PositionedStack(new ItemStack(GCItems.rocketEngine), 45, 100 + changeY));
input1.add(new PositionedStack(new ItemStack(GCItems.rocketEngine, 1, 1), 18, 64 + changeY));
input1.add(new PositionedStack(new ItemStack(GCItems.rocketEngine, 1, 1), 72, 64 + changeY));
input1.add(new PositionedStack(new ItemStack(GCItems.partFins), 18, 82 + changeY));
input1.add(new PositionedStack(new ItemStack(GCItems.partFins), 18, 100 + changeY));
input1.add(new PositionedStack(new ItemStack(GCItems.partFins), 72, 82 + changeY));
input1.add(new PositionedStack(new ItemStack(GCItems.partFins), 72, 100 + changeY));
this.registerRocketBenchRecipe(input1, new PositionedStack(new ItemStack(MarsItems.spaceship, 1, 0), 139, 87 + changeY));
ArrayList<PositionedStack> input2 = new ArrayList<PositionedStack>(input1);
input2.add(new PositionedStack(new ItemStack(Blocks.chest), 90, -15 + changeY));
this.registerRocketBenchRecipe(input2, new PositionedStack(new ItemStack(MarsItems.spaceship, 1, 1), 139, 87 + changeY));
input2 = new ArrayList<PositionedStack>(input1);
input2.add(new PositionedStack(new ItemStack(Blocks.chest), 90 + 26, -15 + changeY));
this.registerRocketBenchRecipe(input2, new PositionedStack(new ItemStack(MarsItems.spaceship, 1, 1), 139, 87 + changeY));
input2 = new ArrayList<PositionedStack>(input1);
input2.add(new PositionedStack(new ItemStack(Blocks.chest), 90 + 52, -15 + changeY));
this.registerRocketBenchRecipe(input2, new PositionedStack(new ItemStack(MarsItems.spaceship, 1, 1), 139, 87 + changeY));
input2 = new ArrayList<PositionedStack>(input1);
input2.add(new PositionedStack(new ItemStack(Blocks.chest), 90, -15 + changeY));
input2.add(new PositionedStack(new ItemStack(Blocks.chest), 90 + 26, -15 + changeY));
this.registerRocketBenchRecipe(input2, new PositionedStack(new ItemStack(MarsItems.spaceship, 1, 2), 139, 87 + changeY));
input2 = new ArrayList<PositionedStack>(input1);
input2.add(new PositionedStack(new ItemStack(Blocks.chest), 90 + 26, -15 + changeY));
input2.add(new PositionedStack(new ItemStack(Blocks.chest), 90 + 52, -15 + changeY));
this.registerRocketBenchRecipe(input2, new PositionedStack(new ItemStack(MarsItems.spaceship, 1, 2), 139, 87 + changeY));
input2 = new ArrayList<PositionedStack>(input1);
input2.add(new PositionedStack(new ItemStack(Blocks.chest), 90, -15 + changeY));
input2.add(new PositionedStack(new ItemStack(Blocks.chest), 90 + 52, -15 + changeY));
this.registerRocketBenchRecipe(input2, new PositionedStack(new ItemStack(MarsItems.spaceship, 1, 2), 139, 87 + changeY));
input2 = new ArrayList<PositionedStack>(input1);
input2.add(new PositionedStack(new ItemStack(Blocks.chest), 90, -15 + changeY));
input2.add(new PositionedStack(new ItemStack(Blocks.chest), 90 + 26, -15 + changeY));
input2.add(new PositionedStack(new ItemStack(Blocks.chest), 90 + 52, -15 + changeY));
this.registerRocketBenchRecipe(input2, new PositionedStack(new ItemStack(MarsItems.spaceship, 1, 3), 139, 87 + changeY));
input1 = new ArrayList<PositionedStack>();
input1.add(new PositionedStack(new ItemStack(GCItems.partNoseCone), 45, 14));
input1.add(new PositionedStack(new ItemStack(GCItems.basicItem, 1, 14), 45, 32));
input1.add(new PositionedStack(new ItemStack(MarsItems.marsItemBasic, 1, 3), 36, 50));
input1.add(new PositionedStack(new ItemStack(MarsItems.marsItemBasic, 1, 3), 36, 68));
input1.add(new PositionedStack(new ItemStack(MarsItems.marsItemBasic, 1, 3), 36, 86));
input1.add(new PositionedStack(new ItemStack(MarsItems.marsItemBasic, 1, 3), 54, 50));
input1.add(new PositionedStack(new ItemStack(MarsItems.marsItemBasic, 1, 3), 54, 68));
input1.add(new PositionedStack(new ItemStack(MarsItems.marsItemBasic, 1, 3), 54, 86));
input1.add(new PositionedStack(new ItemStack(GCItems.partFins), 18, 86));
input1.add(new PositionedStack(new ItemStack(GCItems.partFins), 72, 86));
input1.add(new PositionedStack(new ItemStack(GCItems.rocketEngine), 45, 104));
input1.add(new PositionedStack(new ItemStack(GCItems.partFins), 18, 104));
input1.add(new PositionedStack(new ItemStack(GCItems.partFins), 72, 104));
input2 = new ArrayList<PositionedStack>(input1);
input2.add(new PositionedStack(new ItemStack(Blocks.chest), 90, -7 + changeY));
this.registerCargoBenchRecipe(input2, new PositionedStack(new ItemStack(MarsItems.spaceship, 1, 11), 139, 77 + changeY));
input2 = new ArrayList<PositionedStack>(input1);
input2.add(new PositionedStack(new ItemStack(Blocks.chest), 116, -7 + changeY));
this.registerCargoBenchRecipe(input2, new PositionedStack(new ItemStack(MarsItems.spaceship, 1, 11), 139, 77 + changeY));
input2 = new ArrayList<PositionedStack>(input1);
input2.add(new PositionedStack(new ItemStack(Blocks.chest), 90 + 52, -7 + changeY));
this.registerCargoBenchRecipe(input2, new PositionedStack(new ItemStack(MarsItems.spaceship, 1, 11), 139, 77 + changeY));
input2 = new ArrayList<PositionedStack>(input1);
input2.add(new PositionedStack(new ItemStack(Blocks.chest), 90, -7 + changeY));
input2.add(new PositionedStack(new ItemStack(Blocks.chest), 90 + 26, -7 + changeY));
this.registerCargoBenchRecipe(input2, new PositionedStack(new ItemStack(MarsItems.spaceship, 1, 12), 139, 77 + changeY));
input2 = new ArrayList<PositionedStack>(input1);
input2.add(new PositionedStack(new ItemStack(Blocks.chest), 90, -7 + changeY));
input2.add(new PositionedStack(new ItemStack(Blocks.chest), 90 + 52, -7 + changeY));
this.registerCargoBenchRecipe(input2, new PositionedStack(new ItemStack(MarsItems.spaceship, 1, 12), 139, 77 + changeY));
input2 = new ArrayList<PositionedStack>(input1);
input2.add(new PositionedStack(new ItemStack(Blocks.chest), 116, -7 + changeY));
input2.add(new PositionedStack(new ItemStack(Blocks.chest), 90 + 52, -7 + changeY));
this.registerCargoBenchRecipe(input2, new PositionedStack(new ItemStack(MarsItems.spaceship, 1, 12), 139, 77 + changeY));
input2 = new ArrayList<PositionedStack>(input1);
input2.add(new PositionedStack(new ItemStack(Blocks.chest), 90, -7 + changeY));
input2.add(new PositionedStack(new ItemStack(Blocks.chest), 90 + 26, -7 + changeY));
input2.add(new PositionedStack(new ItemStack(Blocks.chest), 90 + 52, -7 + changeY));
this.registerCargoBenchRecipe(input2, new PositionedStack(new ItemStack(MarsItems.spaceship, 1, 13), 139, 77 + changeY));
this.registerLiquefierRecipe(new PositionedStack(new ItemStack(AsteroidsItems.methaneCanister, 1, 1), 2, 3), new PositionedStack(new ItemStack(GCItems.fuelCanister, 1, 1), 127, 3));
this.registerLiquefierRecipe(new PositionedStack(new ItemStack(AsteroidsItems.atmosphericValve, 1, 0), 2, 3), new PositionedStack(new ItemStack(AsteroidsItems.canisterLN2, 1, 1), 127, 3));
this.registerLiquefierRecipe(new PositionedStack(new ItemStack(AsteroidsItems.atmosphericValve, 1, 0), 2, 3), new PositionedStack(new ItemStack(AsteroidsItems.canisterLOX, 1, 1), 148, 3));
this.registerLiquefierRecipe(new PositionedStack(new ItemStack(AsteroidsItems.canisterLN2, 1, 501), 2, 3), new PositionedStack(new ItemStack(AsteroidsItems.canisterLN2, 1, 1), 127, 3));
this.registerLiquefierRecipe(new PositionedStack(new ItemStack(AsteroidsItems.canisterLOX, 1, 501), 2, 3), new PositionedStack(new ItemStack(AsteroidsItems.canisterLOX, 1, 1), 148, 3));
this.registerSynthesizerRecipe(new PositionedStack(new ItemStack(AsteroidsItems.atmosphericValve, 1, 0), 23, 3), new PositionedStack(new ItemStack(AsteroidsItems.methaneCanister, 1, 1), 148, 3));
this.registerSynthesizerRecipe(new PositionedStack(new ItemStack(MarsItems.carbonFragments, 25, 0), 23, 49), new PositionedStack(new ItemStack(AsteroidsItems.methaneCanister, 1, 1), 148, 3));
}
}
| Lapiman/Galacticraft | src/main/java/micdoodle8/mods/galacticraft/planets/mars/nei/NEIGalacticraftMarsConfig.java | Java | lgpl-3.0 | 13,275 |
/**
* DynamicReports - Free Java reporting library for creating reports dynamically
*
* Copyright (C) 2010 - 2015 Ricardo Mariaca
* http://www.dynamicreports.org
*
* This file is part of DynamicReports.
*
* DynamicReports 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.
*
* DynamicReports 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 DynamicReports. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.dynamicreports.jasper.base.templatedesign;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import net.sf.dynamicreports.jasper.transformation.ConstantTransform;
import net.sf.dynamicreports.report.base.DRField;
import net.sf.dynamicreports.report.base.DRMargin;
import net.sf.dynamicreports.report.constant.Constants;
import net.sf.dynamicreports.report.constant.PageOrientation;
import net.sf.dynamicreports.report.constant.WhenNoDataType;
import net.sf.dynamicreports.report.constant.WhenResourceMissingType;
import net.sf.dynamicreports.report.definition.DRIField;
import net.sf.dynamicreports.report.definition.DRIMargin;
import net.sf.dynamicreports.report.definition.DRITemplateDesign;
import net.sf.dynamicreports.report.exception.DRException;
import net.sf.jasperreports.engine.JRBand;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRField;
import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
import net.sf.jasperreports.engine.xml.JRXmlWriter;
import org.apache.commons.lang3.Validate;
/**
* @author Ricardo Mariaca ([email protected])
*/
public class JasperTemplateDesign implements DRITemplateDesign<JasperDesign> {
private static final long serialVersionUID = Constants.SERIAL_VERSION_UID;
private JasperDesign jasperDesign;
private List<DRIField<?>> fields;
private DRMargin margin;
private transient ByteArrayOutputStream templateDesign;
public JasperTemplateDesign(JasperDesign jasperDesign) throws DRException {
init(jasperDesign);
}
public JasperTemplateDesign(File file) throws DRException {
Validate.notNull(file, "file must not be null");
try {
init(JRXmlLoader.load(file));
} catch (JRException e) {
throw new DRException(e);
}
}
public JasperTemplateDesign(String fileName) throws DRException {
Validate.notNull(fileName, "fileName must not be null");
try {
init(JRXmlLoader.load(fileName));
} catch (JRException e) {
throw new DRException(e);
}
}
public JasperTemplateDesign(InputStream inputStream) throws DRException {
Validate.notNull(inputStream, "inputStream must not be null");
try {
init(JRXmlLoader.load(inputStream));
} catch (JRException e) {
throw new DRException(e);
}
}
public JasperTemplateDesign(URL url) throws DRException {
Validate.notNull(url, "url must not be null");
try {
init(JRXmlLoader.load(url.openStream()));
} catch (JRException e) {
throw new DRException(e);
} catch (IOException e) {
throw new DRException(e);
}
}
private void init(JasperDesign jasperDesign) throws DRException {
Validate.notNull(jasperDesign, "jasperDesign must not be null");
this.jasperDesign = jasperDesign;
this.fields = new ArrayList<DRIField<?>>();
for (JRField jrField : jasperDesign.getFields()) {
@SuppressWarnings({ "unchecked", "rawtypes" })
DRField<?> field = new DRField(jrField.getName(), jrField.getValueClass());
fields.add(field);
}
this.margin = new DRMargin();
margin.setTop(jasperDesign.getTopMargin());
margin.setLeft(jasperDesign.getLeftMargin());
margin.setBottom(jasperDesign.getBottomMargin());
margin.setRight(jasperDesign.getRightMargin());
}
@Override
public String getReportName() {
return jasperDesign.getName();
}
@Override
public List<DRIField<?>> getFields() {
return fields;
}
@Override
public boolean isDefinedParameter(String name) {
JRParameter parameter = jasperDesign.getParametersMap().get(name);
return parameter != null;
}
@Override
public String getResourceBundleName() {
return jasperDesign.getResourceBundle();
}
@Override
public Boolean getIgnorePagination() {
return jasperDesign.isIgnorePagination();
}
@Override
public WhenNoDataType getWhenNoDataType() {
return ConstantTransform.whenNoDataType(jasperDesign.getWhenNoDataTypeValue());
}
@Override
public WhenResourceMissingType getWhenResourceMissingType() {
return ConstantTransform.whenResourceMissingType(jasperDesign.getWhenResourceMissingTypeValue());
}
@Override
public Boolean getTitleOnANewPage() {
return jasperDesign.isTitleNewPage();
}
@Override
public Boolean getSummaryOnANewPage() {
return jasperDesign.isSummaryNewPage();
}
@Override
public Boolean getSummaryWithPageHeaderAndFooter() {
return jasperDesign.isSummaryWithPageHeaderAndFooter();
}
@Override
public Boolean getFloatColumnFooter() {
return jasperDesign.isFloatColumnFooter();
}
@Override
public Integer getPageWidth() {
return jasperDesign.getPageWidth();
}
@Override
public Integer getPageHeight() {
return jasperDesign.getPageHeight();
}
@Override
public PageOrientation getPageOrientation() {
return ConstantTransform.pageOrientation(jasperDesign.getOrientationValue());
}
@Override
public DRIMargin getPageMargin() {
return margin;
}
@Override
public Integer getPageColumnsPerPage() {
return jasperDesign.getColumnCount();
}
@Override
public Integer getPageColumnSpace() {
return jasperDesign.getColumnSpacing();
}
@Override
public Integer getPageColumnWidth() {
return jasperDesign.getColumnWidth();
}
@Override
public int getTitleComponentsCount() {
return getBandComponentsCount(jasperDesign.getTitle());
}
@Override
public int getPageHeaderComponentsCount() {
return getBandComponentsCount(jasperDesign.getPageHeader());
}
@Override
public int getPageFooterComponentsCount() {
return getBandComponentsCount(jasperDesign.getPageFooter());
}
@Override
public int getColumnHeaderComponentsCount() {
return getBandComponentsCount(jasperDesign.getColumnHeader());
}
@Override
public int getColumnFooterComponentsCount() {
return getBandComponentsCount(jasperDesign.getColumnFooter());
}
@Override
public int getLastPageFooterComponentsCount() {
return getBandComponentsCount(jasperDesign.getLastPageFooter());
}
@Override
public int getSummaryComponentsCount() {
return getBandComponentsCount(jasperDesign.getSummary());
}
@Override
public int getNoDataComponentsCount() {
return getBandComponentsCount(jasperDesign.getNoData());
}
@Override
public int getBackgroundComponentsCount() {
return getBandComponentsCount(jasperDesign.getBackground());
}
private int getBandComponentsCount(JRBand band) {
if (band != null && band.getElements() != null) {
return band.getElements().length;
}
return 0;
}
@Override
public JasperDesign getDesign() throws DRException {
try {
if (templateDesign == null) {
templateDesign = new ByteArrayOutputStream();
JRXmlWriter.writeReport(jasperDesign, templateDesign, "UTF-8");
}
return JRXmlLoader.load(new ByteArrayInputStream(templateDesign.toByteArray()));
} catch (JRException e) {
throw new DRException(e);
}
}
}
| svn2github/dynamicreports-jasper | dynamicreports-core/src/main/java/net/sf/dynamicreports/jasper/base/templatedesign/JasperTemplateDesign.java | Java | lgpl-3.0 | 8,193 |
/**
* Copyright (C) 2013-2014 the original author or authors.
*
* 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,
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package org.excalibur.core.events;
import org.excalibur.core.events.handlers.DeadEventLoggingHandler;
import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;
import com.google.common.util.concurrent.ListeningExecutorService;
public class EventBusFactory
{
public static AsyncEventBus createAsyncEventBus(ListeningExecutorService executor, DeadEventLoggingHandler deadEventLoggingHandler)
{
return createAsyncEventBus("default-async-event-bus", executor, deadEventLoggingHandler);
}
public static AsyncEventBus createAsyncEventBus(String name, ListeningExecutorService executor, DeadEventLoggingHandler deadEventLoggingHandler)
{
AsyncEventBus asyncEventBus = new AsyncEventBus(name, executor);
asyncEventBus.register(deadEventLoggingHandler);
return asyncEventBus;
}
public static EventBus createSyncEventBus(DeadEventLoggingHandler deadEventLoggingHandler)
{
return createSyncEventBus("default-event-bus", deadEventLoggingHandler);
}
public static EventBus createSyncEventBus(String name, DeadEventLoggingHandler deadEventLoggingHandler)
{
EventBus eventBus = new EventBus(name);
eventBus.register(deadEventLoggingHandler);
return eventBus;
}
}
| alessandroleite/dohko | core/src/main/java/org/excalibur/core/events/EventBusFactory.java | Java | lgpl-3.0 | 2,041 |
/**
* Copyright 2014 - 2022 Jörgen Lundgren
*
* This file is part of Dayflower.
*
* Dayflower 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.
*
* Dayflower 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 Dayflower. If not, see <http://www.gnu.org/licenses/>.
*/
package org.dayflower.scene;
/**
* A {@code BSSRDF} represents a BSSRDF (Bidirectional Surface Scattering Reflectance Distribution Function).
*
* @since 1.0.0
* @author Jörgen Lundgren
*/
public interface BSSRDF {
} | macroing/Dayflower | src/main/java/org/dayflower/scene/BSSRDF.java | Java | lgpl-3.0 | 985 |
package net.lomeli.achieveson.api;
import net.minecraft.stats.Achievement;
public abstract class ConditionHandler {
public static IConditionManager conditionManager;
public abstract void registerAchievementCondition(Achievement achievement, String... args);
/**
* Typically, condition handlers will have FML/Forge events. This method is called to register those events
*/
public abstract void registerEvent();
/**
* This is what is what needs to be put in "conditionType" in the json file to use this condition
*
* @return
*/
public abstract String conditionID();
/**
* Set to true if you're using a client side event. Use {@link net.lomeli.achieveson.api.IConditionManager#sendAchievementPacket} to give the player their achievement.
*/
public abstract boolean isClientSide();
public static final void registerHandler(Class<? extends ConditionHandler> clazz) {
conditionManager.registerAchievements(clazz);
}
}
| Lomeli12/AchieveSON | src/main/java/net/lomeli/achieveson/api/ConditionHandler.java | Java | lgpl-3.0 | 1,008 |
/*
* Copyright (C) 2012 B3Partners B.V.
*
* 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 nl.b3p.imagetool;
import java.io.IOException;
import java.io.StringReader;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import nl.b3p.commons.services.HttpClientConfigured;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.JDOMException;
import org.xml.sax.InputSource;
/**
*
* @author Roy Braam
*/
public class ArcServerImageCollector extends PrePostImageCollector{
private static final Log log = LogFactory.getLog(ArcServerImageCollector.class);
private static XPathExpression xPathImageURL;
static{
XPathFactory factory = XPathFactory.newInstance();
XPath xPath = factory.newXPath();
try {
xPathImageURL = xPath.compile("//ImageURL/text()");
} catch (Exception ex) {
log.error("Error while creating xpath expr",ex);
}
}
public ArcServerImageCollector(ImageManager manager, CombineImageUrl ciu, HttpClientConfigured client){
super(manager, ciu, client);
}
@Override
protected String getUrlFromXML(String returnXML) throws XPathExpressionException, JDOMException, IOException {
String s=xPathImageURL.evaluate(new InputSource(new StringReader(returnXML)));
if (s!=null && s.length() ==0){
s=null;
}
return s;
}
}
| B3Partners/b3p-combineImageTool | src/main/java/nl/b3p/imagetool/ArcServerImageCollector.java | Java | lgpl-3.0 | 2,141 |
package exc.xmpF;
import java.util.ArrayList;
import java.util.List;
import exc.object.*;
import exc.block.*;
import java.util.*;
import xcodeml.util.XmOption;
import exc.xcalablemp.*;
/**
* process analyze XcalableMP pragma
* pass1: check directive and allocate descriptor
*/
public class XMPanalyzePragma
{
XMPenv env;
public XMPanalyzePragma() {}
public void run(FuncDefBlock def, XMPenv env) {
this.env = env;
env.setCurrentDef(def);
Block b;
Block fblock = def.getBlock();
// pass1: traverse to collect information about XMP pramga
XMP.debug("pass1:");
// check module use
checkUseDecl(fblock.getBody().getDecls());
b = fblock.getBody().getHead();
if(b == null) return; // null body, do nothing
b.setProp(XMP.prop, new XMPinfo(XMPpragma.FUNCTION_BODY, null, b, env));
// scan by topdown iterator
BlockIterator i = new topdownBlockIterator(fblock);
for(i.init(); !i.end(); i.next()) {
b = i.getBlock();
if(XMP.debugFlag) System.out.println("pass1=" + b);
if (b.Opcode() == Xcode.XMP_PRAGMA){
PragmaBlock pb = (PragmaBlock)b;
// These two pragmas must be processed in advance because they may be converted into another
// ones, which will be processed again later.
if (XMPpragma.valueOf(pb.getPragma()) == XMPpragma.GMOVE){
analyzePragma(pb);
}
if (XMPpragma.valueOf(pb.getPragma()) == XMPpragma.ARRAY){
b = analyzeArray(pb);
if (b != null) i.setBlock(b);
}
analyzePragma((PragmaBlock)b);
}
}
}
// check use and import if use of module is found.
private void checkUseDecl(Xobject decls){
if(decls == null) return;
for(Xobject decl: (XobjList)decls){
if(decl.Opcode() != Xcode.F_USE_DECL) continue;
String name = decl.getArg(0).getName();
env.useModule(name);
env.findModule(name); // import
}
}
private void analyzePragma(PragmaBlock pb) {
String pragmaName = pb.getPragma();
// debug
if(XMP.debugFlag){
System.out.println("Pragma: "+pragmaName);
System.out.println(" Clause= "+pb.getClauses());
System.out.println(" Body= "+pb.getBody());
}
XMPinfo outer = null;
for(Block bp = pb.getParentBlock(); bp != null; bp = bp.getParentBlock()) {
if(bp.Opcode() == Xcode.XMP_PRAGMA) {
outer = (XMPinfo)bp.getProp(XMP.prop);
}
}
XMPinfo info = new XMPinfo(XMPpragma.valueOf(pb.getPragma()), outer, pb, env);
pb.setProp(XMP.prop, info);
XMPpragma p = info.pragma;
switch (p){
case NODES:
{
Xobject clauses = pb.getClauses();
XMPnodes.analyzePragma(clauses, env, pb);
}
break;
case TEMPLATE:
{
Xobject templateDecl = pb.getClauses();
XobjList templateNameList = (XobjList)templateDecl.getArg(0);
for(Xobject xx:templateNameList){
XMPtemplate.analyzeTemplate(xx,templateDecl.getArg(1), env, pb);
}
}
break;
case DISTRIBUTE:
{
Xobject distributeDecl = pb.getClauses();
XobjList distributeNameList = (XobjList)distributeDecl.getArg(0);
Xobject distributeDeclCopy = distributeDecl.copy();
for(Xobject xx:distributeNameList){
XMPtemplate.analyzeDistribute(xx,distributeDecl.getArg(1),
distributeDecl.getArg(2),env, pb);
}
}
break;
case ALIGN:
{
Xobject alignDecl = pb.getClauses();
XobjList alignNameList = (XobjList)alignDecl.getArg(0);
for(Xobject xx: alignNameList){
XMParray.analyzeAlign(xx, alignDecl.getArg(1),
alignDecl.getArg(2),
alignDecl.getArg(3),
env, pb);
if(XMP.hasError()) break;
}
}
break;
case SHADOW:
{
Xobject shadowDecl = pb.getClauses();
XobjList shadowNameList = (XobjList) shadowDecl.getArg(0);
Xobject shadow_w_list = shadowDecl.getArg(1);
for(Xobject xx: shadowNameList){
XMParray.analyzeShadow(xx,shadow_w_list,env,pb);
if(XMP.hasError()) break;
}
}
break;
case LOCAL_ALIAS:
analyzeLocalAlias(pb.getClauses(), env, pb);
break;
case SAVE_DESC:
{
XobjList xmpObjList = (XobjList)pb.getClauses();
for (Xobject xx: xmpObjList){
String objName = xx.getString();
XMPobject xmpObject = env.findXMPobject(objName, pb);
if (xmpObject != null){
xmpObject.setSaveDesc(true);
continue;
}
Ident id = env.findVarIdent(objName, pb);
if (id != null){
XMParray array = XMParray.getArray(id);
if (array != null){
array.setSaveDesc(true);
}
else {
XMP.errorAt(pb, "object '" + objName + "' is not an aligned array");
}
continue;
}
XMP.errorAt(pb, "object '" + objName + "' is not declared");
}
}
break;
case TEMPLATE_FIX:
analyzeTemplateFix(pb.getClauses(), info, pb);
break;
case LOOP:
{
Block newBlock = null;
XobjList expandOpt = (XobjList)pb.getClauses().getArg(2);
if (expandOpt == null || expandOpt.hasNullArg()){
;
}
else if (expandOpt.getArg(0).getInt() == XMP.LOOP_MARGIN){
newBlock = divideMarginLoop(pb);
}
else if (expandOpt.getArg(0).getInt() == XMP.LOOP_PEEL_AND_WAIT){
newBlock = peelLoop(pb);
}
if (newBlock != null){
Block next;
for (Block b = newBlock.getBody().getHead(); b != null; b = next){
next = b.getNext();
analyzePragma((PragmaBlock)b);
}
pb.replace(newBlock);
}
else {
analyzeLoop(pb.getClauses(), pb.getBody(), pb, info);
}
break;
}
case REFLECT:
case REDUCE_SHADOW:
analyzeReflect(pb.getClauses(),info,pb);
break;
case BARRIER:
analyzeBarrier(pb.getClauses(),info,pb);
break;
case REDUCTION:
analyzeReduction(pb.getClauses(),info,pb);
break;
case BCAST:
analyzeBcast(pb.getClauses(),info,pb);
break;
case WAIT_ASYNC:
analyzeWaitAsync(pb.getClauses(),info,pb);
break;
case TASK:
analyzeTask(pb.getClauses(), pb.getBody(), info, pb);
break;
case TASKS:
analyzeTasks(pb.getClauses(), pb.getBody(), info, pb);
break;
case GMOVE:
analyzeGmove(pb.getClauses(), pb.getBody(), info, pb);
break;
case COARRAY:
if (XmOption.isCoarray()) {
XMPcoarray.analyzeCoarrayDirective(pb.getClauses(), env, pb);
} else {
XMP.error("coarray directive is specified.");
}
break;
case IMAGE:
if (XmOption.isCoarray()) {
XMPtransCoarrayRun.analyzeImageDirective(pb.getClauses(), env, pb);
} else {
XMP.error("image directive is specified.");
}
break;
case ARRAY:
break;
default:
XMP.fatal("'" + pragmaName.toLowerCase() +
"' directive is not supported yet");
}
}
private static boolean isEqualVar(Xobject v1, Xobject v2){
return (v1.isVariable() && v2.isVariable() &&
v1.getName().equals(v2.getName()));
}
public static void analyzeLocalAlias(Xobject localAliasDecl,
XMPenv env, PragmaBlock pb){
// global array
String gName = localAliasDecl.getArg(1).getName();
Ident gArrayId = env.findVarIdent(gName, pb);
if (gArrayId == null) {
XMP.errorAt(pb, "global array '" + gName + "' is not declared");
return;
}
XMParray gObject = XMParray.getArray(gArrayId);
if (gObject == null){
XMP.errorAt(pb, "global array '" + gName + "' is not aligned");
return;
}
// local array
String lName = localAliasDecl.getArg(0).getName();
Ident lArrayId = env.findVarIdent(lName, pb);
if (lArrayId == null) {
XMP.errorAt(pb, "local alias '" + lName + "' is not declared");
return;
}
XMParray lObject = XMParray.getArray(lArrayId);
if (lObject != null){
XMP.errorAt(pb, "local alias '" + lName + "' is aligned");
return;
}
// check type matching
FarrayType gType = (FarrayType)gArrayId.Type();
FarrayType lType = (FarrayType)lArrayId.Type();
if (!lType.isFassumedShape()){
XMP.errorAt(pb, "local alias must be declared as an assumed-shape array.");
return;
}
if (gType.getNumDimensions() != lType.getNumDimensions()){
XMP.errorAt(pb, "The rank is different between the global array and the local alias");
return;
}
if (!gType.getRef().equals(lType.getRef())){
XMP.errorAt(pb, "The element type unmatched between the global array and the local alias");
return;
}
// replace name
Ident origLocalId = gObject.getLocalId();
env.removeIdent(origLocalId.getName(), pb);
lArrayId.setProp(XMP.origIndexRange, ((FarrayType)lArrayId.Type()).getFindexRange());
int arrayDim = lType.getNumDimensions();
Xobject[] sizeExprs = new Xobject[arrayDim];
for (int i = 0; i < arrayDim; i++)
sizeExprs[i] = Xcons.FindexRangeOfAssumedShape();
lType.setFarraySizeExpr(sizeExprs);
lType.setIsFallocatable(true);
gObject.setLocalId(lArrayId);
lArrayId.setProp(XMP.globalAlias, gObject);
}
private void analyzeTemplateFix(Xobject tfixDecl,
XMPinfo info, PragmaBlock pb){
XobjList distList = (XobjList)tfixDecl.getArg(0);
Xobject t = tfixDecl.getArg(1);
XobjList sizeList = (XobjList)tfixDecl.getArg(2);
// get template object
String tName = t.getString();
XMPtemplate tObject = env.findXMPtemplate(tName, pb);
if (tObject == null) {
XMP.errorAt(pb, "template '" + tName + "' is not declared");
return;
}
if (tObject.isFixed()) {
XMP.errorAt(pb, "template '" + tName + "' is alreday fixed");
}
if (!sizeList.isEmptyList()){
for (int i = 0; i < tObject.getDim(); i++){
if (sizeList.getArg(i).Opcode() != Xcode.LIST){
sizeList.setArg(i, Xcons.List(Xcons.IntConstant(1), sizeList.getArg(i)));
}
}
}
// set info
info.setTemplateFix(tObject, sizeList, distList);
}
/*
* analyze Loop directive:
* loopDecl = (on_ref | ...)
*/
void analyzeLoop(Xobject loopDecl, BlockList loopBody,
PragmaBlock pb, XMPinfo info) {
// get block to schedule
Vector<XMPdimInfo> dims = new Vector<XMPdimInfo>();
// schedule loop
XobjList loopIterList = (XobjList)loopDecl.getArg(0);
if (loopIterList == null || loopIterList.Nargs() == 0) {
XobjList onRef = (XobjList)loopDecl.getArg(1);
XobjList onRefIterList = (XobjList)onRef.getArg(1);
loopIterList = XMPutil.getLoopIterListFromOnRef(onRefIterList);
}
while(true){
ForBlock loopBlock = getOutermostLoopBlock(loopBody);
if(loopBlock == null) break;
boolean is_found = false;
for(Xobject x: loopIterList){
if(x.Opcode() == Xcode.LIST) x = x.getArg(0);
if(isEqualVar(loopBlock.getInductionVar(),x)){
is_found = true;
break;
}
}
if(is_found)
dims.add(XMPdimInfo.loopInfo(loopBlock));
loopBody = loopBlock.getBody();
}
/* check loopIterList */
for(Xobject x: loopIterList){
if(x.Opcode() == Xcode.LIST){
if(x.getArgOrNull(1) != null || x.getArgOrNull(2) != null){
XMP.errorAt(pb,"bad syntax in loop directive");
}
x = x.getArg(0);
}
boolean is_found = false;
for(XMPdimInfo d_info: dims){
if(isEqualVar(d_info.getLoopVar(),x)){
is_found = true;
break;
}
}
if(!is_found)
XMP.errorAt(pb,"loop index is not found in loop varaibles");
}
XMPobjectsRef on_ref = XMPobjectsRef.parseDecl(loopDecl.getArg(1),env,pb);
if(XMP.hasError()) return;
/* check on ref: it should be v+off */
int on_ref_idx = 0;
Vector<XMPdimInfo> on_ref_dims = on_ref.getSubscripts();
for(int k = 0; k < on_ref_dims.size(); k++){
XMPdimInfo d_info = on_ref_dims.elementAt(k);
if(d_info.isStar()) continue;
if(d_info.isTriplet()){
//XMP.errorAt(pb,"on-ref in loop must not be triplet");
continue;
} else {
Xobject t = d_info.getIndex();
if(t == null) continue;
Xobject v = null;
Xobject off = null;
if(t.isVariable()){
v = t;
} else {
switch(t.Opcode()){
case PLUS_EXPR:
case MINUS_EXPR:
if(!t.left().isVariable())
XMP.errorAt(pb,"left-hand side in align-subscript must be a variable");
else {
v = t.left();
off = t.right();
if(t.Opcode() == Xcode.MINUS_EXPR)
off = Xcons.unaryOp(Xcode.UNARY_MINUS_EXPR,off);
}
// check right-hand side?
break;
default:
XMP.errorAt(pb,"bad expression in subsript of on-ref");
}
}
if(v == null) continue; // some error occurs
// find varaible
int idx = -1;
for(int i = 0; i < dims.size(); i++){
if(isEqualVar(v,dims.elementAt(i).getLoopVar())){
idx = i;
dims.elementAt(i).setLoopOnIndex(k);
break;
}
}
if(idx < 0)
XMP.errorAt(pb,"loop variable is not found in on_ref: '"
+v.getName()+"'");
d_info.setLoopOnRefInfo(idx,off);
}
}
// width list
XobjList expandOpt = (XobjList)loopDecl.getArg(2);
int loopType;
Vector<XMPdimInfo> widthList = new Vector<XMPdimInfo>();
if (expandOpt == null || expandOpt.hasNullArg()){
loopType = XMP.LOOP_NONE;
}
else {
loopType = expandOpt.getArg(0).getInt();
for (Xobject x: (XobjList)expandOpt.getArg(1)){
XMPdimInfo width = new XMPdimInfo();
if (XMP.debugFlag)
System.out.println("width = ("+x.getArg(0)+":"+x.getArg(1)+":"+x.getArg(2)+")");
width.parse(x);
widthList.add(width);
}
}
Xobject reductionSpec = loopDecl.getArg(3);
if(reductionSpec != null)
analyzeReductionSpec(info, reductionSpec, pb);
on_ref.setLoopDimInfo(dims); // set back pointer
checkLocalizableLoop(dims,on_ref,pb);
info.setBody(loopBody); // inner most body
info.setLoopInfo(dims, on_ref, loopType, widthList);
}
private static Block divideMarginLoop(PragmaBlock pb){
// The type is XMP.LOOP_MARGIN
BlockList loops = Bcons.emptyBody();
boolean flag = false;
XobjList expandOpt = (XobjList)pb.getClauses().getArg(2);
PragmaBlock pb1, pb2;
XobjList expandOpt1 = null, expandOpt2 = null;
for (int i = 0; i < expandOpt.getArg(1).Nargs(); i++){
Xobject expandWidth = expandOpt.getArg(1).getArg(i);
Xobject lower = expandWidth.getArg(0);
Xobject upper = expandWidth.getArg(1);
Xobject stride = expandWidth.getArg(2);
if (stride.isIntConstant() && stride.getInt() == -1) continue;
if (!lower.isZeroConstant() && !upper.isZeroConstant()){
flag = true;
// for lower margin
pb1 = (PragmaBlock)pb.copy();
expandOpt1 = (XobjList)pb1.getClauses().getArg(2);
for (int j = 0; j < expandOpt1.getArg(1).Nargs(); j++){
Xobject expandWidth1 = expandOpt1.getArg(1).getArg(j);
if (j == i){
expandWidth1.setArg(0, lower);
expandWidth1.setArg(1, Xcons.IntConstant(0));
}
else if (j > i){
expandWidth1.setArg(2, Xcons.IntConstant(-1)); // edge of margin
}
else { // j < i
expandWidth1.setArg(0, Xcons.IntConstant(0));
expandWidth1.setArg(1, Xcons.IntConstant(0));
}
}
loops.add(pb1);
// for upper margin
pb2 = (PragmaBlock)pb.copy();
expandOpt2 = (XobjList)pb2.getClauses().getArg(2);
for (int j = 0; j < expandOpt1.getArg(1).Nargs(); j++){
Xobject expandWidth2 = expandOpt2.getArg(1).getArg(j);
if (j == i){
expandWidth2.setArg(0, Xcons.IntConstant(0));
expandWidth2.setArg(1, upper);
}
else if (j > i){
expandWidth2.setArg(2, Xcons.IntConstant(-1)); // edge of margin
}
else { // j < i
expandWidth2.setArg(0, Xcons.IntConstant(0));
expandWidth2.setArg(1, Xcons.IntConstant(0));
}
}
loops.add(pb2);
}
}
if (flag){
return Bcons.COMPOUND(loops);
}
else {
return null;
}
}
private static Block peelLoop(PragmaBlock pb){
// The type is XMP.LOOP_PEEL_AND_WAIT
BlockList bl = Bcons.emptyBody();
// First, create the kernel loop
PragmaBlock pb3 = (PragmaBlock)pb.copy();
pb3.getClauses().getArg(2).setArg(0, Xcons.IntConstant(XMP.LOOP_EXPAND));
pb3.getClauses().getArg(2).setArg(1, pb.getClauses().getArg(2).getArg(2));
bl.add(pb3);
// Second, create wait_async
XobjList clauses = Xcons.List();
clauses.add(Xcons.List(pb.getClauses().getArg(2).getArg(1)));
clauses.add(null);
PragmaBlock pb2 = new PragmaBlock(Xcode.XMP_PRAGMA, "WAIT_ASYNC", clauses, null);
bl.add(pb2);
// Third, create the peeled Loop
PragmaBlock pb1 = (PragmaBlock)pb.copy();
pb1.getClauses().getArg(2).setArg(0, Xcons.IntConstant(XMP.LOOP_MARGIN));
pb1.getClauses().getArg(2).setArg(1, pb.getClauses().getArg(2).getArg(2));
bl.add(pb1);
return Bcons.COMPOUND(bl);
}
private static ForBlock getOutermostLoopBlock(BlockList body) {
Block b = body.getHead();
while (b != null) {
if (b.Opcode() == Xcode.F_DO_STATEMENT) {
ForBlock forBlock = (ForBlock)b;
forBlock.Canonicalize();
if (!(forBlock.isCanonical())){
// XMP.error("loop statement is not canonical");
return null;
}
return forBlock;
}
else if (b.Opcode() == Xcode.COMPOUND_STATEMENT)
return getOutermostLoopBlock(b.getBody());
else if (b.Opcode() == Xcode.OMP_PRAGMA || b.Opcode() == Xcode.ACC_PRAGMA)
return getOutermostLoopBlock(b.getBody());
b = b.getNext();
}
return null;
}
/*
* distributed loop is localizable if:
* (1) step is 1
* (2) distribution is BLOCK
*/
private void checkLocalizableLoop(Vector<XMPdimInfo> dims,
XMPobjectsRef on_ref, Block b){
for(int i = 0; i < dims.size(); i++){
boolean localizable = false;
XMPdimInfo d_info = dims.elementAt(i);
if(d_info.getStride().isOneConstant())
localizable = true;
else {
if(!(on_ref.getRefObject() instanceof XMPtemplate))
continue;
XMPtemplate tmpl = (XMPtemplate)on_ref.getRefObject();
if(tmpl.isDistributed()){
if(tmpl.getDistMannerAt(d_info.getLoopOnIndex())
== XMPtemplate.BLOCK)
localizable = true;
} else
XMP.errorAt(b,"template '"+tmpl.getName()+"' is not distributed");
}
if(XMP.debugFlag)
System.out.println("localizable(i="+i+")="+localizable);
if(localizable){
Xobject loop_var = d_info.getLoopVar();
/* if localiable, allocate local */
Ident local_loop_var =
env.declIdent(XMP.genSym(loop_var.getName()),
loop_var.Type(),b);
d_info.setLoopLocalVar(local_loop_var);
}
}
}
private void analyzeReflect(Xobject reflectDecl,
XMPinfo info, PragmaBlock pb){
XobjList reflectNameList = (XobjList) reflectDecl.getArg(0);
XobjList widthOpt = (XobjList) reflectDecl.getArg(1);
Xobject asyncOpt = reflectDecl.getArg(2);
Xobject accOpt = reflectDecl.getArg(3);
Vector<XMParray> reflectArrays = new Vector<XMParray>();
for(Xobject x: reflectNameList){
if(x.Opcode() == Xcode.MEMBER_REF){
String structName = x.getArg(0).getName();
String memberName = x.getArg(1).getName();
Ident structId = env.findVarIdent(structName,pb);
Ident memberId = structId.Type().getMemberList().getIdent(XMP.PREFIX_ + memberName);
memberId.setProp(XMP.HasShadow, info);
continue;
}
if(!x.isVariable()){
XMP.errorAt(pb,"Bad array name in reflect name list");
continue;
}
String name = x.getName();
Ident id = env.findVarIdent(name,pb);
if(id == null){
XMP.errorAt(pb,"variable '" + name + "'for reflect is not declared");
continue;
}
XMParray array = XMParray.getArray(id);
if(array == null){
XMP.errorAt(pb,"array '" + name + "'for reflect is not declared");
continue;
}
reflectArrays.add(array);
}
Vector<XMPdimInfo> widthList = new Vector<XMPdimInfo>();
for (Xobject x: widthOpt){
XMPdimInfo width = new XMPdimInfo();
if(XMP.debugFlag)
System.out.println("width = ("+x.getArg(0)+":"+x.getArg(1)+":"+x.getArg(2)+")");
width.parse(x);
widthList.add(width);
}
info.setReflectArrays(reflectArrays, widthList);
info.setAsyncId(asyncOpt);
info.setAcc(accOpt);
if (info.isAcc() && !XmOption.isXcalableACC()){
XMP.errorAt(pb, "Enable XcalableACC to use the acc clause");
}
}
void analyzeBarrier(Xobject barrierDecl,
XMPinfo info, PragmaBlock pb) {
Xobject barrierOnRef = barrierDecl.getArg(0);
Xobject barrierOpt = barrierDecl.getArg(1);
if(barrierOpt != null){
System.out.println("opt="+barrierOpt);
XMP.fatal("barrier opt is not supported yet, sorry!");
return;
}
info.setOnRef(XMPobjectsRef.parseDecl(barrierOnRef,env,pb));
}
void analyzeReduction(Xobject reductionDecl,
XMPinfo info, PragmaBlock pb){
Xobject reductionSpec = reductionDecl.getArg(0);
Xobject reductionOnRef = reductionDecl.getArg(1);
Xobject asyncOpt = reductionDecl.getArg(2);
Xobject accOpt = reductionDecl.getArg(3);
analyzeReductionSpec(info, reductionSpec, pb);
info.setOnRef(XMPobjectsRef.parseDecl(reductionOnRef,env,pb));
if (asyncOpt != null && !XmOption.isAsync())
XMP.errorAt(pb, "MPI-3 is required to use the async clause on a reduction directive");
info.setAsyncId(asyncOpt);
info.setAcc(accOpt);
if (info.isAcc() && !XmOption.isXcalableACC())
XMP.errorAt(pb, "Enable XcalableACC to use the acc clause");
}
private void analyzeReductionSpec(XMPinfo info, Xobject reductionSpec,
PragmaBlock pb){
Xobject op = reductionSpec.getArg(0);
if(!op.isIntConstant()) XMP.fatal("reduction: op is not INT");
Vector<Ident> reduction_vars = new Vector<Ident>();
Vector<Vector<Ident>> reduction_pos_vars = new Vector<Vector<Ident>>();
for(Xobject w: (XobjList)reductionSpec.getArg(1)){
Xobject v = w.getArg(0);
if(!v.isVariable()){
XMP.errorAt(pb,"not variable in reduction spec list");
}
Ident id = env.findVarIdent(v.getName(),pb);
if(id == null){
XMP.errorAt(pb,"variable '"+v.getName()+"' in reduction is not found");
}
reduction_vars.add(id);
Vector<Ident> plist = new Vector<Ident>();
if (w.getArg(1) != null){
for (Xobject p: (XobjList)w.getArg(1)){
Ident pid = env.findVarIdent(p.getName(), pb);
if (pid == null){
XMP.errorAt(pb, "variable '" + p.getName() + "' in reduction is not found");
}
plist.add(pid);
}
}
reduction_pos_vars.add(plist);
}
info.setReductionInfo(op.getInt(), reduction_vars, reduction_pos_vars);
}
private void analyzeBcast(Xobject bcastDecl,
XMPinfo info, PragmaBlock pb){
XobjList bcastNameList = (XobjList) bcastDecl.getArg(0);
Xobject fromRef = bcastDecl.getArg(1);
Xobject onRef = bcastDecl.getArg(2);
Xobject asyncOpt = bcastDecl.getArg(3);
Xobject accOpt = bcastDecl.getArg(4);
Vector<Xobject> bcast_vars = new Vector<Xobject>();
for(Xobject v: bcastNameList)
bcast_vars.add(v); // not analyzed here
info.setBcastInfo(XMPobjectsRef.parseDecl(fromRef,env,pb),
XMPobjectsRef.parseDecl(onRef,env,pb),
bcast_vars);
if (asyncOpt != null && !XmOption.isAsync())
XMP.errorAt(pb, "MPI-3 is required to use the async clause on a bcast directive");
info.setAsyncId(asyncOpt);
info.setAcc(accOpt);
if (info.isAcc() && !XmOption.isXcalableACC())
XMP.errorAt(pb, "Enable XcalableACC to use the acc clause");
}
private void analyzeWaitAsync(Xobject waitAsyncDecl,
XMPinfo info, PragmaBlock pb){
XobjList asyncIdList = (XobjList) waitAsyncDecl.getArg(0);
Vector<Xobject> asyncIds = new Vector<Xobject>();
for (Xobject x: asyncIdList){
asyncIds.add(x);
}
info.setWaitAsyncIds(asyncIds);
Xobject onRef = waitAsyncDecl.getArg(1);
info.setOnRef(XMPobjectsRef.parseDecl(onRef, env, pb));
}
void analyzeTask(Xobject taskDecl, BlockList taskBody,
XMPinfo info, PragmaBlock pb) {
Xobject onRef = taskDecl.getArg(0);
Xobject nocomm = taskDecl.getArg(1);
info.setOnRef(XMPobjectsRef.parseDecl(onRef,env,pb));
info.setNocomm(nocomm);
}
private void analyzeTasks(Xobject tasksDecl, BlockList taskList,
XMPinfo info, PragmaBlock pb){
//XMP.fatal("analyzeTasks");
}
private void analyzeGmove(Xobject gmoveDecl, BlockList body,
XMPinfo info, PragmaBlock pb) {
Xobject gmoveOpt = gmoveDecl.getArg(0); // NORMAL | IN | OUT
Xobject asyncOpt = gmoveDecl.getArg(1);
Xobject accOpt = gmoveDecl.getArg(2);
// check body is single statement.
Block b = body.getHead();
if(b.getNext() != null) XMP.fatal("not single block for Gmove");
Statement s = b.getBasicBlock().getHead();
if(b.Opcode() != Xcode.F_STATEMENT_LIST ||s.getNext() != null)
XMP.fatal("not single statment for Gmove");
Xobject x = s.getExpr();
if(x.Opcode() != Xcode.F_ASSIGN_STATEMENT)
XMP.fatal("not assignment for Gmove");
Xobject left = x.left();
Xobject right = x.right();
// opcode must be VAR or ARRAY_REF
boolean left_is_global = checkGmoveOperand(left, gmoveOpt.getInt() == XMP.GMOVE_OUT, pb);
boolean right_is_global = checkGmoveOperand(right, gmoveOpt.getInt() == XMP.GMOVE_IN, pb);
boolean left_is_scalar = isScalar(left);
boolean right_is_scalar = isScalar(right);
if (left_is_scalar && !right_is_scalar)
XMP.errorAt(pb, "Incompatible ranks in assignment.");
else if (!right_is_global && gmoveOpt.getInt() == XMP.GMOVE_IN)
XMP.errorAt(pb, "RHS should be global in GMOVE IN.");
else if (!left_is_global && gmoveOpt.getInt() == XMP.GMOVE_OUT)
XMP.errorAt(pb, "LHS should be global in GMOVE OUT.");
if (!left_is_global){
if (!right_is_global){ // local assignment
info.setGmoveOperands(null, null);
return;
}
}
else if (left_is_global){
if (!right_is_global){
if (gmoveOpt.getInt() == XMP.GMOVE_NORMAL && !left_is_scalar &&
convertGmoveToArray(pb, left, right)) return;
}
}
if(XMP.hasError()) return;
info.setGmoveOperands(left,right);
info.setGmoveOpt(gmoveOpt);
if (asyncOpt != null && !XmOption.isAsync())
XMP.errorAt(pb, "MPI-3 is required to use the async clause on a gmove directive");
info.setAsyncId(asyncOpt);
info.setAcc(accOpt);
if (info.isAcc() && !XmOption.isXcalableACC())
XMP.errorAt(pb, "Enable XcalableACC to use the acc clause");
}
private boolean checkGmoveOperand(Xobject x, boolean remotely_accessed, PragmaBlock pb){
Ident id = null;
XMParray array = null;
switch(x.Opcode()){
case F_ARRAY_REF:
Xobject a = x.getArg(0);
if(a.Opcode() != Xcode.F_VAR_REF)
XMP.fatal("not F_VAR_REF for F_ARRAY_REF");
a = a.getArg(0);
if(a.Opcode() == Xcode.VAR){
id = env.findVarIdent(a.getName(),pb);
if(id == null)
XMP.fatal("array in F_ARRAY_REF is not declared");
array = XMParray.getArray(id);
}
else if(a.Opcode() == Xcode.MEMBER_REF){
String structName = a.getArg(0).getName();
String memberName = a.getArg(1).getName();
Ident structId = env.findVarIdent(structName,pb);
Ident memberId = structId.Type().getMemberList().getIdent(XMP.PREFIX_ + memberName);
if(memberId.isMemberAligned() && (XMPpragma.valueOf(pb.getPragma()) != XMPpragma.ARRAY)){
Xobject memberObj = a.getArg(1);
memberObj.setProp(XMP.RWprotected, "foo"); // This is a flag to remove the distributed array
// in gmove construct from the target of rewriting
// in XMPrewriteExpr.rewriteExpr().
return true;
}
}
else{
XMP.fatal("not VAR for F_VAR_REF or MEMBER_REF");
}
if(array != null){
if (remotely_accessed && id.getStorageClass() != StorageClass.FSAVE){
XMP.fatal("Current limitation: Only a SAVE or MODULE variable can be the target of gmove in/out.");
}
if (XMPpragma.valueOf(pb.getPragma()) != XMPpragma.ARRAY) a.setProp(XMP.RWprotected, array);
return true;
}
break;
case VAR:
id = env.findVarIdent(x.getName(), pb);
if (id == null)
XMP.fatal("variable" + x.getName() + "is not declared");
array = XMParray.getArray(id);
if (array != null){
if (remotely_accessed && id.getStorageClass() != StorageClass.FSAVE){
XMP.fatal("Current limitation: Only a SAVE or MODULE variable can be the target of gmove in/out.");
}
if (XMPpragma.valueOf(pb.getPragma()) != XMPpragma.ARRAY) x.setProp(XMP.RWprotected, array);
return true;
}
break;
case F_LOGICAL_CONSTATNT:
case F_CHARACTER_CONSTATNT:
case F_COMPLEX_CONSTATNT:
case STRING_CONSTANT:
case INT_CONSTANT:
case FLOAT_CONSTANT:
case LONGLONG_CONSTANT:
case MOE_CONSTANT:
return false;
default:
XMP.errorAt(pb,"gmove must be followed by simple assignment");
}
return false;
}
private boolean isScalar(Xobject x){
switch (x.Opcode()){
case F_ARRAY_REF:
XobjList subscripts = (XobjList)x.getArg(1);
Xobject var = x.getArg(0).getArg(0);
int n = var.Type().getNumDimensions();
for (int i = 0; i < n; i++){
Xobject sub = subscripts.getArg(i);
if (sub.Opcode() == Xcode.F_INDEX_RANGE) return false;
}
break;
case VAR:
if (x.Type().getKind() == Xtype.F_ARRAY) return false;
break;
}
return true;
}
private boolean convertGmoveToArray(PragmaBlock pb, Xobject left, Xobject right){
pb.setPragma("ARRAY");
Xobject onRef = Xcons.List();
Xobject a = left.getArg(0).getArg(0);
a.remProp(XMP.RWprotected);
Ident id = env.findVarIdent(a.getName(), pb);
assert id != null;
XMParray array = XMParray.getArray(id);
assert array != null;
Xobject t = Xcons.Symbol(Xcode.VAR, array.getAlignTemplate().getName());
onRef.add(t);
Xobject subscripts = Xcons.List();
for (int i = 0; i < array.getAlignTemplate().getDim(); i++){
subscripts.add(null);
}
for (int i = 0; i < array.getDim(); i++){
int alignSubscriptIndex = array.getAlignSubscriptIndexAt(i);
Xobject alignSubscriptOffset = array.getAlignSubscriptOffsetAt(i);
Xobject lb = left.getArg(1).getArg(i).getArg(0);
if (alignSubscriptOffset != null) lb = Xcons.binaryOp(Xcode.PLUS_EXPR, lb, alignSubscriptOffset);
Xobject ub = left.getArg(1).getArg(i).getArg(1);
if (alignSubscriptOffset != null) ub = Xcons.binaryOp(Xcode.PLUS_EXPR, ub, alignSubscriptOffset);
Xobject st = left.getArg(1).getArg(i).getArg(2);
Xobject triplet = Xcons.List(lb, ub, st);
subscripts.setArg(alignSubscriptIndex, triplet);
}
onRef.add(subscripts);
Xobject decl = Xcons.List(onRef);
pb.setClauses(decl);
return true;
}
private Block analyzeArray(PragmaBlock pb){
Xobject arrayDecl = pb.getClauses();
BlockList body = pb.getBody();
XMPinfo outer = null;
for(Block bp = pb.getParentBlock(); bp != null; bp = bp.getParentBlock()) {
if(bp.Opcode() == Xcode.XMP_PRAGMA) {
outer = (XMPinfo)bp.getProp(XMP.prop);
}
}
XMPinfo info = new XMPinfo(XMPpragma.ARRAY, outer, pb, env);
pb.setProp(XMP.prop, info);
Xobject onRef = arrayDecl.getArg(0);
// check body is single statement.
Block b = body.getHead();
if (b.getNext() != null) XMP.fatal("not single block for Array");
Statement s = b.getBasicBlock().getHead();
if (b.Opcode() != Xcode.F_STATEMENT_LIST ||s.getNext() != null)
XMP.fatal("not single statment for Array");
Xobject x = s.getExpr();
if (x.Opcode() != Xcode.F_ASSIGN_STATEMENT)
XMP.fatal("not assignment for Array");
XobjectIterator i = new topdownXobjectIterator(x);
for (i.init(); !i.end(); i.next()) {
Xobject y = i.getXobject();
if (y == null) continue;
if (y.Opcode() == Xcode.VAR && y.Type().isFarray() &&
(i.getParent() == null || i.getParent().Opcode() != Xcode.F_VAR_REF)){
i.setXobject(Xcons.FarrayRef(y));
}
}
Xobject left = x.left();
Xobject right = x.right();
// opcode must be VAR or ARRAY_REF
boolean left_is_global = checkGmoveOperand(left, false, pb);
if (XMP.hasError()) return null;
info.setGmoveOperands(left, right);
info.setOnRef(XMPobjectsRef.parseDecl(onRef, env, pb));
return convertArrayToLoop(pb, info);
}
private Block convertArrayToLoop(PragmaBlock pb, XMPinfo info){
List<Ident> varList = new ArrayList<Ident>();
List<Ident> varListTemplate = new ArrayList<Ident>(XMP.MAX_DIM);
for (int i = 0; i < XMP.MAX_DIM; i++) varListTemplate.add(null);
List<Xobject> lbList = new ArrayList<Xobject>();
List<Xobject> ubList = new ArrayList<Xobject>();
List<Xobject> stList = new ArrayList<Xobject>();
//
// convert LHS
//
Xobject left = info.getGmoveLeft();
if (left.Opcode() != Xcode.F_ARRAY_REF) XMP.fatal(pb, "ARRAY not followed by array ref.");
Xobject left_var = left.getArg(0).getArg(0);
int n = left_var.Type().getNumDimensions();
XobjList subscripts = (XobjList)left.getArg(1);
Xobject[] sizeExprs = left_var.Type().getFarraySizeExpr();
String name = left_var.getName();
Ident id = env.findVarIdent(name, pb);
XMParray leftArray = XMParray.getArray(id);
for (int i = 0; i < n; i++){
Xobject sub = subscripts.getArg(i);
Ident var;
Xobject lb, ub, st;
if (sub.Opcode() == Xcode.F_ARRAY_INDEX){
continue;
}
else if (sub.Opcode() == Xcode.F_INDEX_RANGE){
int tidx = leftArray.getAlignSubscriptIndexAt(i);
if (tidx == -1) continue;
var = env.declIdent(XMP.genSym("loop_i"), Xtype.intType, pb);
varList.add(var);
varListTemplate.set(tidx, var);
lb = ((XobjList)sub).getArg(0);
if (lb == null){
if (!left_var.Type().isFallocatable()){
lb = sizeExprs[i].getArg(0);
}
if (lb == null){
lb = env.declInternIdent("xmp_lbound", Xtype.FintFunctionType).
Call(Xcons.List(leftArray.getDescId().Ref(), Xcons.IntConstant(i+1)));
}
}
ub = ((XobjList)sub).getArg(1);
if (ub == null){
if (!left_var.Type().isFallocatable()){
ub = sizeExprs[i].getArg(1);
}
if (ub == null){
ub = env.declInternIdent("xmp_ubound", Xtype.FintFunctionType).
Call(Xcons.List(leftArray.getDescId().Ref(), Xcons.IntConstant(i+1)));
}
}
st = ((XobjList)sub).getArg(2);
if (st == null) st = Xcons.IntConstant(1);
lbList.add(lb);
ubList.add(ub);
stList.add(st);
Xobject expr;
expr = Xcons.binaryOp(Xcode.MUL_EXPR, var.Ref(), st);
expr = Xcons.binaryOp(Xcode.PLUS_EXPR, expr, lb);
subscripts.setArg(i, Xcons.FarrayIndex(expr));
}
}
//
// convert RHS
//
XobjectIterator j = new topdownXobjectIterator(info.getGmoveRight());
for (j.init(); !j.end(); j.next()) {
Xobject x = j.getXobject();
if (x.Opcode() == Xcode.F_ARRAY_REF){
int k = 0;
Xobject x_var = x.getArg(0).getArg(0);
XobjList subscripts1 = (XobjList)x.getArg(1);
Xobject[] sizeExprs1 = x_var.Type().getFarraySizeExpr();
String name1 = x_var.getName();
Ident id1 = env.findVarIdent(name1, pb);
XMParray array1 = XMParray.getArray(id1);
for (int i = 0; i < x_var.Type().getNumDimensions(); i++){
Xobject sub = subscripts1.getArg(i);
if (sub.Opcode() == Xcode.F_INDEX_RANGE){
Xobject lb, st;
lb = ((XobjList)sub).getArg(0);
if (lb == null){
if (!x_var.Type().isFallocatable()){
lb = sizeExprs1[i].getArg(0);
}
if (lb == null){
lb = env.declInternIdent("xmp_lbound", Xtype.FintFunctionType).
Call(Xcons.List(array1.getDescId().Ref(), Xcons.IntConstant(i+1)));
}
}
st = ((XobjList)sub).getArg(2);
if (st == null) st = Xcons.IntConstant(1);
Xobject expr;
Ident loopVar;
if (array1 != null){
int tidx = array1.getAlignSubscriptIndexAt(i);
loopVar = varListTemplate.get(tidx);
}
else
loopVar = varList.get(k);
if (loopVar == null) XMP.fatal("array on rhs does not conform to that on lhs.");
expr = Xcons.binaryOp(Xcode.MUL_EXPR, loopVar.Ref(), st);
expr = Xcons.binaryOp(Xcode.PLUS_EXPR, expr, lb);
subscripts1.setArg(i, Xcons.FarrayIndex(expr));
k++;
}
}
}
}
//
// construct loop
//
BlockList loop = null;
BlockList body = Bcons.emptyBody();
body.add(Xcons.Set(info.getGmoveLeft(), info.getGmoveRight()));
for (int i = 0; i < varList.size(); i++){
loop = Bcons.emptyBody();
Xobject ub = Xcons.binaryOp(Xcode.MINUS_EXPR, ubList.get(i), lbList.get(i));
ub = Xcons.binaryOp(Xcode.PLUS_EXPR, ub, stList.get(i));
ub = Xcons.binaryOp(Xcode.DIV_EXPR, ub, stList.get(i));
ub = Xcons.binaryOp(Xcode.MINUS_EXPR, ub, Xcons.IntConstant(1));
loop.add(Bcons.Fdo(varList.get(i).Ref(),
Xcons.List(Xcons.IntConstant(0), ub, Xcons.IntConstant(1)), body, null));
body = loop;
}
//
// convert ARRAY to LOOP directive
//
Xobject args = Xcons.List();
XobjList loopIterList = Xcons.List();
for (int i = 0; i < varList.size(); i++){
loopIterList.add(varList.get(i).Ref());
}
args.add(loopIterList);
Xobject onRef = Xcons.List();
String templateName = pb.getClauses().getArg(0).getArg(0).getName();
XMPtemplate template = env.findXMPtemplate(templateName, pb);
if (template == null) XMP.errorAt(pb,"template '" + templateName + "' not found");
onRef.add(pb.getClauses().getArg(0).getArg(0));
Xobject subscriptList = Xcons.List();
Xobject onSubscripts = pb.getClauses().getArg(0).getArg(1);
if (onSubscripts != null && !onSubscripts.isEmptyList()){
for (int i = 0; i < onSubscripts.Nargs(); i++){
Xobject sub = onSubscripts.getArg(i);
if (sub.Opcode() == Xcode.LIST){ // triplet
Xobject lb = ((XobjList)sub).getArg(0);
if (lb == null){
if (template.isFixed()){
lb = template.getLowerAt(i);
}
else {
Ident ret = env.declIdent(XMP.genSym("ret_"), Xtype.intType, pb);
Ident tlb = env.declIdent(XMP.genSym(template.getName() + "_lb"), Xtype.intType, pb);
Ident f = env.declInternIdent("xmp_template_lbound", Xtype.FintFunctionType);
Xobject args1 = Xcons.List(template.getDescId().Ref(), Xcons.IntConstant(i+1), tlb.Ref());
pb.insert(Xcons.Set(ret.Ref(), f.Call(args1)));
lb = tlb.Ref();
}
}
else if (lb.Opcode() == Xcode.VAR){
String lbName = lb.getString();
Ident lbId = env.findVarIdent(lbName, pb);
if (lbId == null) {
XMP.errorAt(pb, "variable '" + lbName + "' is not declared");
return null;
}
lb = lbId.Ref();
}
Xobject st = ((XobjList)sub).getArg(2);
if (st != null){
if (st.Opcode() == Xcode.INT_CONSTANT && ((XobjInt)st).getInt() == 0){ // scalar
subscriptList.add(sub);
continue;
}
else if (st.Opcode() == Xcode.VAR){
String stName = st.getString();
Ident stId = env.findVarIdent(stName, pb);
if (stId == null) {
XMP.errorAt(pb, "variable '" + stName + "' is not declared");
return null;
}
st = stId.Ref();
}
}
else st = Xcons.IntConstant(1);
Ident loopVar = varListTemplate.get(i);
if (loopVar != null){
Xobject expr = Xcons.binaryOp(Xcode.MUL_EXPR, loopVar.Ref(), st);
expr = Xcons.binaryOp(Xcode.PLUS_EXPR, expr, lb);
subscriptList.add(expr);
}
else {
subscriptList.add(null);
}
}
else { // scalar
subscriptList.add(sub);
}
}
}
else {
for (int i = 0; i < template.getDim(); i++){
Xobject lb;
if (template.isFixed()){
lb = template.getLowerAt(i);
}
else {
Ident ret = env.declIdent(XMP.genSym("ret_"), Xtype.intType, pb);
Ident tlb = env.declIdent(XMP.genSym(template.getName() + "_lb"), Xtype.intType, pb);
Ident f = env.declInternIdent("xmp_template_lbound", Xtype.FintFunctionType);
Xobject args1 = Xcons.List(template.getDescId().Ref(), Xcons.IntConstant(i+1), tlb.Ref());
pb.insert(Xcons.Set(ret.Ref(), f.Call(args1)));
lb = tlb.Ref();
}
Ident loopVar = varListTemplate.get(i);
if (loopVar != null){
Xobject expr = Xcons.binaryOp(Xcode.PLUS_EXPR, loopVar.Ref(), lb);
subscriptList.add(expr);
}
else {
subscriptList.add(null);
}
}
}
onRef.add(subscriptList);
args.add(onRef);
args.add(null);
args.add(null);
return Bcons.PRAGMA(Xcode.XMP_PRAGMA, "LOOP", args, loop);
}
}
| omni-compiler/omni-compiler | XcodeML-Exc-Tools/src/exc/xmpF/XMPanalyzePragma.java | Java | lgpl-3.0 | 40,536 |
package eu.europa.echa.iuclid6.namespaces.endpoint_study_record_toxicityreproductionother._2;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import eu.europa.echa.iuclid6.namespaces.platform_fields.v1.PicklistField;
import eu.europa.echa.iuclid6.namespaces.platform_fields.v1.PicklistFieldWithSmallTextRemarks;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Species" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistField"/>
* <element name="Strain" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithSmallTextRemarks"/>
* <element name="Sex" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistField"/>
* <element name="OrganismDetails" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldLarge"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"species",
"strain",
"sex",
"organismDetails"
})
public class TestAnimals {
@XmlElement(name = "Species", required = true)
protected PicklistField species;
@XmlElement(name = "Strain", required = true)
protected PicklistFieldWithSmallTextRemarks strain;
@XmlElement(name = "Sex", required = true)
protected PicklistField sex;
@XmlElement(name = "OrganismDetails", required = true)
protected String organismDetails;
/**
* Gets the value of the species property.
*
* @return
* possible object is
* {@link PicklistField }
*
*/
public PicklistField getSpecies() {
return species;
}
/**
* Sets the value of the species property.
*
* @param value
* allowed object is
* {@link PicklistField }
*
*/
public void setSpecies(PicklistField value) {
this.species = value;
}
/**
* Gets the value of the strain property.
*
* @return
* possible object is
* {@link PicklistFieldWithSmallTextRemarks }
*
*/
public PicklistFieldWithSmallTextRemarks getStrain() {
return strain;
}
/**
* Sets the value of the strain property.
*
* @param value
* allowed object is
* {@link PicklistFieldWithSmallTextRemarks }
*
*/
public void setStrain(PicklistFieldWithSmallTextRemarks value) {
this.strain = value;
}
/**
* Gets the value of the sex property.
*
* @return
* possible object is
* {@link PicklistField }
*
*/
public PicklistField getSex() {
return sex;
}
/**
* Sets the value of the sex property.
*
* @param value
* allowed object is
* {@link PicklistField }
*
*/
public void setSex(PicklistField value) {
this.sex = value;
}
/**
* Gets the value of the organismDetails property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOrganismDetails() {
return organismDetails;
}
/**
* Sets the value of the organismDetails property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOrganismDetails(String value) {
this.organismDetails = value;
}
}
| ideaconsult/i5 | iuclid_6_2-io/src/main/java/eu/europa/echa/iuclid6/namespaces/endpoint_study_record_toxicityreproductionother/_2/TestAnimals.java | Java | lgpl-3.0 | 3,939 |
package com.plectix.simulator.io.xml;
import java.util.List;
import javax.xml.stream.XMLStreamException;
import com.plectix.simulator.interfaces.ObservableConnectedComponentInterface;
import com.plectix.simulator.io.SimulationDataOutputUtil;
import com.plectix.simulator.simulator.KappaSystem;
import com.plectix.simulator.staticanalysis.Rule;
import com.plectix.simulator.staticanalysis.influencemap.InfluenceMap;
import com.plectix.simulator.staticanalysis.influencemap.InfluenceMapEdge;
/*package*/ class InfluenceMapXMLWriter {
// TODO move out
private final InfluenceMap influenceMap;
private final static String TYPE_NEGATIVE_MAP = "NEGATIVE";
private final static String TYPE_POSITIVE_MAP = "POSITIVE";
public InfluenceMapXMLWriter(InfluenceMap influenceMap) {
this.influenceMap = influenceMap;
}
public final void write(OurXMLWriter writer, int rules,
List<ObservableConnectedComponentInterface> observableComponents,
boolean isInhibitionMap, KappaSystem kappaSystem,
boolean isOcamlStyleObsName) throws XMLStreamException {
writer.writeStartElement("InfluenceMap");
int rulesAndObsNumber = observableComponents.size() + rules;
/**
* add kappaSystem.getObservables()
* */
for (int i = observableComponents.size() - 1; i >= 0; i--) {
ObservableConnectedComponentInterface obsCC = observableComponents.get(i);
writer.writeStartElement("Node");
writer.writeAttribute("Id", Integer.toString(rulesAndObsNumber--));
writer.writeAttribute("Type", "OBSERVABLE");
String obsName = obsCC.getName();
if (obsName == null)
obsName = obsCC.getLine();
writer.writeAttribute("Text", '[' + obsName + ']');
writer.writeAttribute("Data", obsCC.getLine());
writer.writeAttribute("Name", '[' + obsName + ']');
writer.writeEndElement();
}
/**
* add rules
* */
addRulesToXML(rulesAndObsNumber, writer, rules, isOcamlStyleObsName,
kappaSystem, true);
/**
* add activation map
* */
for (int i = rules - 1; i >= 0; i--) {
Rule rule = kappaSystem.getRuleById(i);
printMap(writer, TYPE_POSITIVE_MAP, rule, influenceMap.getActivationMap().get(Integer
.valueOf(i)), influenceMap.getActivationMapObservables().get(Integer.valueOf(i)),
rules);
}
if (isInhibitionMap) {
for (int i = rules - 1; i >= 0; i--) {
Rule rule = kappaSystem.getRuleById(i);
printMap(writer, TYPE_NEGATIVE_MAP, rule, influenceMap.getInhibitionMap()
.get(Integer.valueOf(i)), influenceMap.getInhibitionMapObservables().get(Integer
.valueOf(i)), rules);
}
}
writer.writeEndElement();
}
private static final void printMap(OurXMLWriter writer, String mapType,
Rule rule, List<InfluenceMapEdge> rulesToPrint,
List<InfluenceMapEdge> influenceMapEdges, int allRules)
throws XMLStreamException {
int rulesNumber = allRules + 1;
if (influenceMapEdges != null)
for (int j = influenceMapEdges.size() - 1; j >= 0; j--) {
int fromNode = rule.getRuleId() + 1;
int toNode = influenceMapEdges.get(j).getTargetRule() + rulesNumber;
if(mapType == TYPE_NEGATIVE_MAP && fromNode == toNode)
continue;
writer.writeStartElement("Connection");
writer.writeAttribute("FromNode", Integer.toString(fromNode));
writer.writeAttribute("ToNode", Integer.toString(toNode));
writer.writeAttribute("Relation", mapType);
writer.writeEndElement();
}
if (rulesToPrint != null)
for (int j = rulesToPrint.size() - 1; j >= 0; j--) {
int fromNode = rule.getRuleId() + 1;
int toNode = rulesToPrint.get(j).getTargetRule() + 1;
if(mapType == TYPE_NEGATIVE_MAP && fromNode == toNode)
continue;
writer.writeStartElement("Connection");
writer.writeAttribute("FromNode", Integer.toString(fromNode));
writer.writeAttribute("ToNode", Integer.toString(toNode));
// .getRuleID() + 1));
writer.writeAttribute("Relation", mapType);
writer.writeEndElement();
}
}
public static final void addRulesToXML(int rulesAndObsNumber,
OurXMLWriter writer, int rules, boolean isOcamlStyleObsName,
KappaSystem kappaSystem, boolean writeText) throws XMLStreamException {
for (int i = rules - 1; i >= 0; i--) {
Rule rule = kappaSystem.getRuleById(i);
if(writeText)
writer.writeStartElement("Node");
else
writer.writeStartElement("Rule");
writer.writeAttribute("Type", "RULE");
if (rule.getName() != null) {
if(writeText)
writer.writeAttribute("Text", rule.getName());
writer.writeAttribute("Name", rule.getName());
} else {
Integer ruleId = rule.getRuleId() + 1;
if(writeText)
writer.writeAttribute("Text", "%Auto_" + ruleId);
writer.writeAttribute("Name", "%Auto_" + ruleId);
}
writer.writeAttribute("Id", Integer.toString(rulesAndObsNumber--));
// TODO ENG-419
writer.writeAttribute("Data", SimulationDataOutputUtil.getData(rule,
isOcamlStyleObsName));
writer.writeEndElement();
}
}
}
| kappamodeler/jkappa | src/main/com/plectix/simulator/io/xml/InfluenceMapXMLWriter.java | Java | lgpl-3.0 | 5,040 |
package uk.co.mmscomputing.imageio.tiff;
import java.io.*;
public class TIFFClassFMMROutputStream extends TIFFClassFOutputStream{
public TIFFClassFMMROutputStream(OutputStream out)throws IOException{
super(out);
}
public void write(int cw)throws IOException{ // MMR code 'bytes'
if(lastByteWasZero){ // 0x00,0x80 end of line code words
if((cw&0x00FF)==0x80){ // signal new line
lastByteWasZero=false;
height++; // end of line increase height
return;
}
super.write(0); // if not part of end of line code, write last 0 byte
}
if(cw==0x00){ // check for possible end of line code
lastByteWasZero=true; // don't write 0 byte just yet, maybe end of line code
}else{
super.write(cw); // write code word
}
}
public void writePageEnd()throws IOException{
if(lastByteWasZero){buf.write(0);}
int align=buf.size()&0x01;
byte[] data=buf.toByteArray();
int ifdoffset=offset+data.length+align+16; // data.length+xres.size+yres.size
writeInt(ifdoffset); // ptr to ifd; write data in front of ifd
out.write(data); // write to image stream
if(align>0){out.write(0);} // word alignment
writeInt(xres); // xres -16
writeInt(1);
writeInt(yres); // yres -8
writeInt(1);
writeShort(12); // IFD +0: count directory entries
// entries need to be in tag order !
writeShort(ImageWidth); // 256 +2
writeShort(LONG);
writeInt(1);
writeInt(width);
writeShort(ImageLength); // 257 +14
writeShort(LONG);
writeInt(1);
writeInt(height);
writeShort(Compression); // 259 +26
writeShort(SHORT);
writeInt(1);
writeInt(CCITTFAXT6);
writeShort(PhotometricInterpretation); // 262 +38
writeShort(SHORT);
writeInt(1);
writeInt(WhiteIsZero);
writeShort(FillOrder); // 266 +50
writeShort(SHORT);
writeInt(1);
writeInt(2); // 2 = Least Significant Bit first
writeShort(StripOffsets); // 273 +62
writeShort(LONG);
writeInt(1); // all data in one strip !
writeInt(offset);
writeShort(RowsPerStrip); // 278 +74
writeShort(LONG);
writeInt(1);
writeInt(height); // all data in one strip !
writeShort(StripByteCounts); // 279 +86
writeShort(LONG);
writeInt(1);
writeInt(data.length); // all data in one strip !
writeShort(XResolution); // 282 +98
writeShort(RATIONAL);
writeInt(1);
writeInt(ifdoffset-16); // 203.0
writeShort(YResolution); // 283 +110
writeShort(RATIONAL);
writeInt(1);
writeInt(ifdoffset-8); // 196.0
writeShort(T6Options); // 293 +122
writeShort(LONG);
writeInt(1);
writeInt(0); // 293 MMR;
writeShort(ResolutionUnit); // 296 +134
writeShort(SHORT);
writeInt(1);
writeInt(Inch);
offset=ifdoffset+150;
}
}
| alex73/mmscomputing | src/uk/co/mmscomputing/imageio/tiff/TIFFClassFMMROutputStream.java | Java | lgpl-3.0 | 3,673 |
/*
* This file is part of FAST Wireshark.
*
* FAST Wireshark is free software: you can redistribute it and/or modify
* it under the terms of the Lesser GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FAST Wireshark 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
* Lesser GNU General Public License for more details.
*
* You should have received a copy of the Lesser GNU General Public License
* along with FAST Wireshark. If not, see
* <http://www.gnu.org/licenses/lgpl.txt>.
*/
package fastwireshark.runner;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.Iterator;
import java.util.List;
import org.openfast.DecimalValue;
import org.openfast.GroupValue;
import org.openfast.Message;
import org.openfast.MessageOutputStream;
import org.openfast.SequenceValue;
import org.openfast.template.ComposedScalar;
import org.openfast.template.Field;
import org.openfast.template.Group;
import org.openfast.template.Scalar;
import org.openfast.template.Sequence;
import fastwireshark.data.ByteMessagePlan;
import fastwireshark.data.DataPlan;
import fastwireshark.data.MessagePlan;
import fastwireshark.io.PcapFileWriter;
import fastwireshark.util.Constants;
public class DataPlanRunner implements Constants{
/**
* The output stream that will be used to write out the messages
*/
private MessageOutputStream messageOut;
/**
* Retrieves the output stream used by this runner to write out run results
* @return The MessageOutputStream used by the runner
*/
public MessageOutputStream getMessageOutputStream(){
return messageOut;
}
/**
* Sets the output stream to be used by this runner to write out run results
* @param messageOut The MessageOutputStream to use to write out run results
*/
public void setMessageOutputStream(MessageOutputStream messageOut){
this.messageOut = messageOut;
}
/**
* Runs a DataPlan
* Will iterate over all the MessagePlans in the DataPlan and write out each message in order.
* @param dp The DataPlan to run
* @throws RuntimeException If {@link #messageOut} is null
*/
public void runDataPlan(DataPlan dp){
if(messageOut == null){
throw new RuntimeException("messageOut is null");
}
for(fastwireshark.data.Message mp : dp){
if(messageOut.getUnderlyingStream() instanceof PcapFileWriter){
PcapFileWriter writer = (PcapFileWriter) messageOut.getUnderlyingStream();
writer.setFrom(mp.getFrom());
writer.setTo(mp.getTo());
}
if(mp instanceof MessagePlan){
runMessagePlan((MessagePlan)mp);
} else if (mp instanceof ByteMessagePlan){
runByteMessagePlan((ByteMessagePlan)mp);
}
}
messageOut.close();
try {
messageOut.getUnderlyingStream().close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Runs a MessagePlan
* Creates a message based on the plan template, then populates the fields, then writes it using the Runner's MessageOutputStream
* The MessageOutputStream is then flushed to force the message out.
* @param mp The Message Plan to run
*/
private void runMessagePlan(MessagePlan mp){
Message m = new Message(mp.getTemplate());
populateGroup(m,mp.getValues());
messageOut.writeMessage(m);
try {
messageOut.getUnderlyingStream().flush();
} catch (IOException e) {
System.err.println("Error writing message: " + m);
e.printStackTrace();
}
}
/**
* Runs a ByteMessagePlan
* Reads the bytes of the message plan and writes it out
* @param mp The Message Plan to run
*/
private void runByteMessagePlan(ByteMessagePlan mp){
OutputStream out = messageOut.getUnderlyingStream();
try {
out.write(mp.getBytes());
out.flush();
} catch (IOException e) {
System.err.println("Error writing message: " + mp);
e.printStackTrace();
}
}
/**
* Populate the fields in a group with those in a list
* @param gv The group to populate
* @param values The list of values to use to populate
*/
@SuppressWarnings("unchecked")
private void populateGroup(GroupValue gv, List<Object> values){
Iterator<Object> iter = values.iterator();
//The message is special and needs to have its first value skipped, this causes all other instances to require one less in the loop
for(int i = gv instanceof Message ? 1 : 0 ; i <= values.size() + (gv instanceof Message ? 0 : -1) ; i++){
Object o = iter.next();
Field f = gv.getGroup().getField(i);
if (o == null) {
// DO NOTHING!
} else
if(f instanceof Sequence){
Sequence s = (Sequence)f;
SequenceValue sv = new SequenceValue(s);
List<List<Object>> seqValues = (List<List<Object>>) o;
for(List<Object> l : seqValues){
GroupValue sgv = new GroupValue(s.getGroup());
populateGroup(sgv,l);
sv.add(sgv);
}
gv.setFieldValue(i, sv);
} else
if(f instanceof Group){
Group g = (Group)f;
GroupValue ggv = new GroupValue(g);
populateGroup(ggv,(List<Object>)o);
gv.setFieldValue(i, ggv);
} else
if(f instanceof ComposedScalar){
setValue(gv,(ComposedScalar)f,i,o);
} else
if(f instanceof Scalar){
setValue(gv,(Scalar)f,i,o);
}
}
}
public void setValue(GroupValue gv, Scalar f, int i, Object o){
if(f.getType().getName().equals(INT32) ||
f.getType().getName().equals(UINT32)){
gv.setInteger(i, (Integer)o);
} else
if(f.getType().getName().equals(INT64) ||
f.getType().getName().equals(UINT64)){
gv.setLong(i, (Long)o);
} else
if(f.getType().getName().equals(DECIMAL)){
//Decimal can be of differing arguments, further determine correct type
if(o instanceof Double){
gv.setDecimal(i, (Double)o);
} else
if(o instanceof Float){
gv.setDecimal(i, (Float)o);
} else
if(o instanceof BigDecimal){
BigDecimal b = (BigDecimal)o;
DecimalValue dv = new DecimalValue(b.unscaledValue().longValue(),-b.scale());
gv.setFieldValue(i, dv);
}
} else
if(f.getType().getName().equals(UNICODE) ||
f.getType().getName().equals(ASCII)){
gv.setString(i, (String)o);
} else
if(f.getType().getName().equals(BYTEVECTOR)){
gv.setByteVector(i, (byte[])o);
}
}
public void setValue(GroupValue gv, ComposedScalar f, int i, Object o){
if(f.getType().getName().equals(INT32) ||
f.getType().getName().equals(UINT32)){
gv.setInteger(i, (Integer)o);
} else
if(f.getType().getName().equals(INT64) ||
f.getType().getName().equals(UINT64)){
gv.setLong(i, (Long)o);
} else
if(f.getType().getName().equals(DECIMAL)){
//Decimal can be of differing arguments, further determine correct type
if(o instanceof Double){
gv.setDecimal(i, (Double)o);
} else
if(o instanceof Float){
gv.setDecimal(i, (Float)o);
} else
if(o instanceof BigDecimal){
BigDecimal b = (BigDecimal)o;
DecimalValue dv = new DecimalValue(b.unscaledValue().longValue(),-b.scale());
// gv.setDecimal(i, (BigDecimal)o);
gv.setFieldValue(i, dv);
}
} else
if(f.getType().getName().equals(UNICODE) ||
f.getType().getName().equals(ASCII)){
gv.setString(i, (String)o);
} else
if(f.getType().getName().equals(BYTEVECTOR)){
gv.setByteVector(i, (byte[])o);
}
}
}
| sm1ly/fast-wireshark | test/src/fastwireshark/runner/DataPlanRunner.java | Java | lgpl-3.0 | 7,551 |
/*
* Copyright 2013, 2014, 2015, 2016 Jiri Lidinsky
*
* This file is part of control4j.
*
* control4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* control4j 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 control4j. If not, see <http://www.gnu.org/licenses/>.
*/
package cz.control4j.modules.text;
import cz.control4j.Control;
import cz.control4j.Input;
import cz.control4j.InputModule;
import cz.control4j.Signal;
import cz.control4j.SignalFormat;
import cz.control4j.VariableInput;
import cz.lidinsky.tools.reflect.Setter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
*
* Prints values of input signals in a human readable form on
* the given text device. Text device may be a file or just a
* console. Value of each signal is printed on separate line
* together with timestamp and signal name.
*
*/
@Input()
@VariableInput
public class IMNarrowFormatter extends InputModule {
/**
* A string which is used to separate particular data.
* Default value is a space.
*/
@Setter("delimiter")
public String delimiter = " ";
/**
* A valid ISO Language Code. These codes are the lower-case,
* two-letter codes as defined by ISO-639 (en or cz for example).
* You can find a full list of these codes at a number of sites,
* such as
* <a href="http://www.loc.gov/standards/iso639-2/php/English_list.php">
* here</a>
* Default value is taken from system settings of the computer.
*
* @see #initialize
*/
@Setter("language")
public String language = null;
/**
* A valid ISO Country Code. These codes are the upper-case,
* two-letter codes as defined by ISO-3166 (CZ or US for example).
* You can find a full list of these codes at a number of sites, such as:
* <a href="http://www.iso.ch/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/list-en1.html">here</a>
* Default value is taken from system settings.
*
* @see #initialize
*/
@Setter("country")
public String country = null;
/**
* Maximum fraction digits for decimal numbers.
* Default value is two.
*/
@Setter("max-fraction-digits")
public int maxFractionDigits = 2;
private SignalFormat signalFormat;
private final List<String> labels = new ArrayList<>();
/**
* Initialize the formatter. It uses variables: language, country
* and maxFractionDigits to create and initialize locale for
* the formatter. If language and country variables are null
* (not used) it uses default system locale settings of the
* computer. If you want to set country, you must also set
* the language property.
*
* @param configuration
* module configuration
*
* @see java.util.Locale
*/
/*
@Override
public void initialize() {
//super.initialize();
// initialize input labels
int inputs = definition.getInputSize() - 1;
if (inputs >= 0) {
labels = new String[inputs];
for (int i = 0; i < inputs; i++) {
try {
labels[i] = definition.getInput(i+1).getConfiguration()
.getString("label");
} catch (ConfigItemNotFoundException e) {
try {
labels[i] = definition.getInput(i+1).getConfiguration()
.getString("signal-name");
} catch (ConfigItemNotFoundException ex) {
labels[i] = "???";
}
}
}
}
//
Locale locale;
if (language == null)
locale = Locale.getDefault();
else if (country == null)
locale = new Locale(language);
else
locale = new Locale(language, country);
signalFormat = new SignalFormat(locale);
signalFormat.setMaximumFractionDigits(maxFractionDigits);
}
*/
@Override
public void prepare() {
Locale locale;
if (language == null) {
locale = Locale.getDefault();
} else if (country == null) {
locale = new Locale(language);
} else {
locale = new Locale(language, country);
}
signalFormat = new SignalFormat(locale);
signalFormat.setMaximumFractionDigits(maxFractionDigits);
}
/**
* Prints input signals on the text device in the human readable
* form. Signals are printed on separate lines. First input
* (input with index zero) serves as a enable input. Signals
* which index starts from one are printed only if the enable
* input is valid and true, or if this input is not used (null).
* Otherwise the print is disabled.
*
* @param input
* signal with index zero is interpreted as boolean.
* Function of this module is enabled only if this
* signal is null (not used) or if it is valid and
* true; function is disabled otherwise. Values
* of signals which index starts from one will be
* printed on text device. These cannot be null.
*/
@Override
protected void put(Signal[] input, int inputLength) {
if (input[0] == null || (input[0].isValid() && input[0].getBoolean())) {
for (int i=1; i<inputLength; i++) {
Control.print(labels.get(i-1), input[i]);
// System.out.println(input[i].toString(
// signalFormat, delimiter, labels.get(i - 1)));
}
}
}
@Override
public int getInputIndex(String key) {
if ("en".equals(key)) return 0;
labels.add(key);
return labels.indexOf(key) + 1;
}
}
| jilm/control4j | src/cz/control4j/modules/text/IMNarrowFormatter.java | Java | lgpl-3.0 | 5,887 |
package ch.loway.oss.ari4java.generated;
// ----------------------------------------------------
// THIS CLASS WAS GENERATED AUTOMATICALLY
// PLEASE DO NOT EDIT
// Generated on: Sat Sep 19 08:50:54 CEST 2015
// ----------------------------------------------------
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import ch.loway.oss.ari4java.tools.RestException;
import ch.loway.oss.ari4java.tools.AriCallback;
import ch.loway.oss.ari4java.tools.tags.*;
/**********************************************************
*
* Generated by: JavaInterface
*********************************************************/
public interface RecordingStarted {
// void setRecording LiveRecording
/**********************************************************
* Recording control object
*
* @since ari_0_0_1
*********************************************************/
public void setRecording(LiveRecording val );
// LiveRecording getRecording
/**********************************************************
* Recording control object
*
* @since ari_0_0_1
*********************************************************/
public LiveRecording getRecording();
}
;
| korvus81/ari4java | classes/ch/loway/oss/ari4java/generated/RecordingStarted.java | Java | lgpl-3.0 | 1,252 |
package com.sirma.itt.emf.audit.processor;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import org.easymock.Capture;
import org.easymock.EasyMock;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import com.sirma.itt.emf.audit.activity.AuditActivity;
import com.sirma.itt.emf.audit.command.AuditActionIDCommand;
import com.sirma.itt.emf.audit.command.AuditCommand;
import com.sirma.itt.emf.audit.command.instance.AuditObjectIDCommand;
import com.sirma.itt.emf.audit.db.AuditDao;
import com.sirma.itt.emf.audit.exception.MissingOperationIdException;
import com.sirma.itt.seip.resources.EmfUser;
import com.sirma.itt.seip.util.ReflectionUtils;
import de.akquinet.jbosscc.needle.annotation.ObjectUnderTest;
import de.akquinet.jbosscc.needle.junit.NeedleRule;
/**
* Test the logic in {@link AuditProcessor} when it is enabled.
*
* @author Mihail Radkov
*/
public class AuditProcessorTest {
/** The needle rule. */
@Rule
public NeedleRule needleRule = new NeedleRule();
@Inject
private AuditDao auditDao;
@ObjectUnderTest(id = "ap", implementation = AuditProcessorImpl.class)
private AuditProcessor processor;
/**
* Init test data.
*/
@Before
public void before() {
List<AuditCommand> commands = new ArrayList<>();
commands.add(new AuditObjectIDCommand());
commands.add(new AuditActionIDCommand());
ReflectionUtils.setFieldValue(processor, "commands", commands);
}
@Test
public void testUserAction() {
Capture<AuditActivity> capturedActivity = capturePublishing();
// Missing user
processor.auditUserOperation(null, null, null);
Assert.assertFalse(capturedActivity.hasCaptured());
EmfUser user = new EmfUser("Alduin");
user.setId("alduin");
processor.auditUserOperation(user, "login", null);
Assert.assertTrue(capturedActivity.hasCaptured());
Assert.assertEquals("Alduin", capturedActivity.getValue().getUserName());
Assert.assertEquals("alduin", capturedActivity.getValue().getUserId());
}
@Test(expected = MissingOperationIdException.class)
public void testUserActionWithMissingId() {
processor.auditUserOperation(new EmfUser("Alduin"), null, null);
}
/**
* Tests the processor behavior when the operation id is null.
*/
@Test(expected = MissingOperationIdException.class)
public void testWithNullOperation() {
processor.process(null, null, null);
}
/**
* Tests the processor behavior when the operation id is empty string.
*/
@Test(expected = MissingOperationIdException.class)
public void testWithEmptyOperation() {
processor.process(null, "", null);
}
private Capture<AuditActivity> capturePublishing() {
Capture<AuditActivity> capturedActivity = new Capture<>();
auditDao.publish(EasyMock.capture(capturedActivity));
EasyMock.replay(auditDao);
return capturedActivity;
}
}
| SirmaITT/conservation-space-1.7.0 | docker/sirma-platform/platform/seip-parent/platform/seip-audit/seip-audit-impl/src/test/java/com/sirma/itt/emf/audit/processor/AuditProcessorTest.java | Java | lgpl-3.0 | 2,857 |
/*
* Copyright 2008-2014, David Karnok
* The file is part of the Open Imperium Galactica project.
*
* The code should be distributed under the LGPL license.
* See http://www.gnu.org/licenses/lgpl.html for details.
*/
package hu.openig.ui;
import hu.openig.core.Action0;
import hu.openig.ui.UIMouse.Type;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.image.BufferedImage;
/**
* A static image display without any event handling.
* @author akarnokd
*/
public class UIImage extends UIComponent {
/** The image object. */
private BufferedImage image;
/** Scale the image to the defined width and height? */
private boolean scale;
/** Center the image? */
private boolean center;
/** Stretch the image? */
private boolean stretch;
/** Crop the image? */
private boolean crop;
/** The border color. */
protected int borderColor;
/** The background color. */
protected int backgroundColor;
/** The click action. */
public Action0 onClick;
/**
* Default constructor without any image. The component will have zero size.
*/
public UIImage() {
}
/**
* Create a non-scaled image component out of the supplied image.
* @param image the image to use
*/
public UIImage(BufferedImage image) {
this.image = image;
this.width = image.getWidth();
this.height = image.getHeight();
}
/**
* Create a scaled image component out of the supplied image.
* @param image the image
* @param width the target width
* @param height the target height
*/
public UIImage(BufferedImage image, int width, int height) {
this.image = image;
this.width = width;
this.height = height;
this.scale = true;
}
@Override
public void draw(Graphics2D g2) {
Shape clip0 = null;
if (crop) {
clip0 = g2.getClip();
g2.clipRect(0, 0, width, height);
}
if (backgroundColor != 0) {
g2.setColor(new Color(backgroundColor, true));
g2.fillRect(0, 0, width, height);
}
if (image != null) {
if (stretch) {
g2.drawImage(image, 0, 0, width, height, null);
} else
if (center) {
int dx = (width - image.getWidth()) / 2;
int dy = (height - image.getHeight()) / 2;
g2.drawImage(image, dx, dy, null);
} else
if (scale) {
float fx = width * 1.0f / image.getWidth();
float fy = height * 1.0f / image.getHeight();
float f = Math.min(fx, fy);
int dx = (int)((width - image.getWidth() * f) / 2);
int dy = (int)((height - image.getHeight() * f) / 2);
g2.drawImage(image, dx, dy, (int)(image.getWidth() * f), (int)(image.getHeight() * f), null);
} else {
g2.drawImage(image, 0, 0, null);
}
}
if (crop) {
g2.setClip(clip0);
}
if (borderColor != 0) {
g2.setColor(new Color(borderColor, true));
g2.drawRect(0, 0, width - 1, height - 1);
}
}
@Override
public boolean mouse(UIMouse e) {
if (e.has(Type.DOWN)) {
if (onClick != null) {
onClick.invoke();
return true;
}
}
return super.mouse(e);
}
/**
* Set the image content. Does not change the component dimensions.
* @param image the image to set
* @return this
*/
public UIImage image(BufferedImage image) {
this.image = image;
return this;
}
/**
* Center the image.
* @param state center?
* @return this
*/
public UIImage center(boolean state) {
this.center = state;
return this;
}
/**
* Scale the image to the current size.
* @param state the state
* @return this
*/
public UIImage scale(boolean state) {
this.scale = state;
return this;
}
/**
* @return The associated image.
*/
public BufferedImage image() {
return image;
}
/**
* Size to content.
*/
public void sizeToContent() {
if (image != null) {
width = image.getWidth();
height = image.getHeight();
} else {
width = 0;
height = 0;
}
}
/**
* @return the current border color ARGB
*/
public int borderColor() {
return borderColor;
}
/**
* Set the border color.
* @param newColor new color ARGB
* @return this
*/
public UIImage borderColor(int newColor) {
this.borderColor = newColor;
return this;
}
/**
* @return the current background color ARGB
*/
public int backgroundColor() {
return backgroundColor;
}
/**
* Set the background color.
* @param newColor the new color ARGB
* @return this
*/
public UIImage backgroundColor(int newColor) {
this.backgroundColor = newColor;
return this;
}
/**
* Stretch the image to the component size?
* @param stretch enable stretch
* @return this
*/
public UIImage stretch(boolean stretch) {
this.stretch = stretch;
return this;
}
/** @return the current stretch state. */
public boolean stretch() {
return this.stretch;
}
/**
* Crop the image?
* @param crop enable/disable cropping
* @return this
*/
public UIImage crop(boolean crop) {
this.crop = crop;
return this;
}
/**
* @return is the image cropped?
*/
public boolean crop() {
return crop;
}
}
| p-smith/open-ig | src/hu/openig/ui/UIImage.java | Java | lgpl-3.0 | 5,164 |
/*
* This class was automatically generated with
* <a href="http://www.castor.org">Castor 1.3.1</a>, using an XML
* Schema.
* $Id: ItemFixedAssetModRqTypeDescriptor.java,v 1.1.1.1 2010-05-04 22:06:00 ryan Exp $
*/
package org.chocolate_milk.model.descriptors;
//---------------------------------/
//- Imported classes and packages -/
//---------------------------------/
import org.chocolate_milk.model.ItemFixedAssetModRqType;
/**
* Class ItemFixedAssetModRqTypeDescriptor.
*
* @version $Revision: 1.1.1.1 $ $Date: 2010-05-04 22:06:00 $
*/
public class ItemFixedAssetModRqTypeDescriptor extends org.exolab.castor.xml.util.XMLClassDescriptorImpl {
//--------------------------/
//- Class/Member Variables -/
//--------------------------/
/**
* Field _elementDefinition.
*/
private boolean _elementDefinition;
/**
* Field _nsPrefix.
*/
private java.lang.String _nsPrefix;
/**
* Field _nsURI.
*/
private java.lang.String _nsURI;
/**
* Field _xmlName.
*/
private java.lang.String _xmlName;
/**
* Field _identity.
*/
private org.exolab.castor.xml.XMLFieldDescriptor _identity;
//----------------/
//- Constructors -/
//----------------/
public ItemFixedAssetModRqTypeDescriptor() {
super();
_xmlName = "ItemFixedAssetModRqType";
_elementDefinition = false;
//-- set grouping compositor
setCompositorAsSequence();
org.exolab.castor.xml.util.XMLFieldDescriptorImpl desc = null;
org.exolab.castor.mapping.FieldHandler handler = null;
org.exolab.castor.xml.FieldValidator fieldValidator = null;
//-- initialize attribute descriptors
//-- _requestID
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(java.lang.String.class, "_requestID", "requestID", org.exolab.castor.xml.NodeType.Attribute);
desc.setImmutable(true);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
ItemFixedAssetModRqType target = (ItemFixedAssetModRqType) object;
return target.getRequestID();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
ItemFixedAssetModRqType target = (ItemFixedAssetModRqType) object;
target.setRequestID( (java.lang.String) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return null;
}
};
desc.setSchemaType("string");
desc.setHandler(handler);
desc.setMultivalued(false);
addFieldDescriptor(desc);
//-- validation code for: _requestID
fieldValidator = new org.exolab.castor.xml.FieldValidator();
{ //-- local scope
org.exolab.castor.xml.validators.StringValidator typeValidator;
typeValidator = new org.exolab.castor.xml.validators.StringValidator();
fieldValidator.setValidator(typeValidator);
typeValidator.setWhiteSpace("preserve");
}
desc.setValidator(fieldValidator);
//-- initialize element descriptors
//-- _itemFixedAssetMod
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(org.chocolate_milk.model.ItemFixedAssetMod.class, "_itemFixedAssetMod", "ItemFixedAssetMod", org.exolab.castor.xml.NodeType.Element);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
ItemFixedAssetModRqType target = (ItemFixedAssetModRqType) object;
return target.getItemFixedAssetMod();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
ItemFixedAssetModRqType target = (ItemFixedAssetModRqType) object;
target.setItemFixedAssetMod( (org.chocolate_milk.model.ItemFixedAssetMod) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return null;
}
};
desc.setSchemaType("org.chocolate_milk.model.ItemFixedAssetMod");
desc.setHandler(handler);
desc.setRequired(true);
desc.setMultivalued(false);
addFieldDescriptor(desc);
addSequenceElement(desc);
//-- validation code for: _itemFixedAssetMod
fieldValidator = new org.exolab.castor.xml.FieldValidator();
fieldValidator.setMinOccurs(1);
{ //-- local scope
}
desc.setValidator(fieldValidator);
//-- _includeRetElementList
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(java.lang.String.class, "_includeRetElementList", "IncludeRetElement", org.exolab.castor.xml.NodeType.Element);
desc.setImmutable(true);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
ItemFixedAssetModRqType target = (ItemFixedAssetModRqType) object;
return target.getIncludeRetElement();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
ItemFixedAssetModRqType target = (ItemFixedAssetModRqType) object;
target.addIncludeRetElement( (java.lang.String) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
public void resetValue(Object object) throws IllegalStateException, IllegalArgumentException {
try {
ItemFixedAssetModRqType target = (ItemFixedAssetModRqType) object;
target.removeAllIncludeRetElement();
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return null;
}
};
desc.setSchemaType("list");
desc.setComponentType("string");
desc.setHandler(handler);
desc.setMultivalued(true);
addFieldDescriptor(desc);
addSequenceElement(desc);
//-- validation code for: _includeRetElementList
fieldValidator = new org.exolab.castor.xml.FieldValidator();
fieldValidator.setMinOccurs(0);
{ //-- local scope
org.exolab.castor.xml.validators.StringValidator typeValidator;
typeValidator = new org.exolab.castor.xml.validators.StringValidator();
fieldValidator.setValidator(typeValidator);
typeValidator.setWhiteSpace("preserve");
typeValidator.setMaxLength(50);
}
desc.setValidator(fieldValidator);
}
//-----------/
//- Methods -/
//-----------/
/**
* Method getAccessMode.
*
* @return the access mode specified for this class.
*/
@Override()
public org.exolab.castor.mapping.AccessMode getAccessMode(
) {
return null;
}
/**
* Method getIdentity.
*
* @return the identity field, null if this class has no
* identity.
*/
@Override()
public org.exolab.castor.mapping.FieldDescriptor getIdentity(
) {
return _identity;
}
/**
* Method getJavaClass.
*
* @return the Java class represented by this descriptor.
*/
@Override()
public java.lang.Class getJavaClass(
) {
return org.chocolate_milk.model.ItemFixedAssetModRqType.class;
}
/**
* Method getNameSpacePrefix.
*
* @return the namespace prefix to use when marshaling as XML.
*/
@Override()
public java.lang.String getNameSpacePrefix(
) {
return _nsPrefix;
}
/**
* Method getNameSpaceURI.
*
* @return the namespace URI used when marshaling and
* unmarshaling as XML.
*/
@Override()
public java.lang.String getNameSpaceURI(
) {
return _nsURI;
}
/**
* Method getValidator.
*
* @return a specific validator for the class described by this
* ClassDescriptor.
*/
@Override()
public org.exolab.castor.xml.TypeValidator getValidator(
) {
return this;
}
/**
* Method getXMLName.
*
* @return the XML Name for the Class being described.
*/
@Override()
public java.lang.String getXMLName(
) {
return _xmlName;
}
/**
* Method isElementDefinition.
*
* @return true if XML schema definition of this Class is that
* of a global
* element or element with anonymous type definition.
*/
public boolean isElementDefinition(
) {
return _elementDefinition;
}
}
| galleon1/chocolate-milk | src/org/chocolate_milk/model/descriptors/ItemFixedAssetModRqTypeDescriptor.java | Java | lgpl-3.0 | 10,137 |
/*
* This file is part of SpoutCommons (http://www.spout.org/).
*
* SpoutCommons 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.
*
* SpoutCommons 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.getspout.commons;
/**
* Represents the Spout core, to get singleton {@link Game} instance
* @author Cameron
*
*/
public final class Spout {
private static Game instance = null;
private Spout() {
throw new IllegalStateException("Can not construct Spout instance");
}
public static void setGame(Game game) {
if (instance == null) {
instance = game;
} else {
throw new UnsupportedOperationException("Can not redefine singleton Game instance");
}
}
public static Game getGame() {
return instance;
}
}
| raws/spout-commons | src/main/java/org/getspout/commons/Spout.java | Java | lgpl-3.0 | 1,278 |
//----------------------------------------------------------------------------//
// //
// L i n e a r E v a l u a t o r T e s t //
// //
//----------------------------------------------------------------------------//
// <editor-fold defaultstate="collapsed" desc="hdr"> //
// Copyright (C) Hervé Bitteur 2000-2011. All rights reserved. //
// This software is released under the GNU General Public License. //
// Goto http://kenai.com/projects/audiveris to report bugs or suggestions. //
//----------------------------------------------------------------------------//
// </editor-fold>
package omr.math;
import omr.math.LinearEvaluator.Printer;
import omr.math.LinearEvaluator.Sample;
import org.junit.AfterClass;
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;
/**
* Class <code>LinearEvaluatorTest</code> gathers unitary tests on
* LinearEvaluator class
*
* @author Hervé Bitteur
* @version $Id$
*/
public class LinearEvaluatorTest
{
//~ Static fields/initializers ---------------------------------------------
private static final String[] inNames = new String[] { "first", "second" };
private static final String dirName = "data/temp";
private static final String fileName = "linear.xml";
private static final List<Sample> samples = Arrays.asList(
new Sample("A", new double[] { 10, 20 }),
new Sample("A", new double[] { 11, 23 }),
new Sample("A", new double[] { 9, 20 }),
new Sample("B", new double[] { 5, 40 }),
new Sample("B", new double[] { 7, 50 }),
new Sample("C", new double[] { 100, 200 }),
new Sample("C", new double[] { 90, 205 }),
new Sample("C", new double[] { 95, 220 }),
new Sample("C", new double[] { 98, 210 }),
new Sample("D", new double[] { 30, 60 }),
new Sample("E", new double[] { 80, 20 }),
new Sample("E", new double[] { 80, 25 }));
//~ Constructors -----------------------------------------------------------
/**
* Creates a new LinearEvaluatorTest object.
*/
public LinearEvaluatorTest ()
{
}
//~ Methods ----------------------------------------------------------------
@BeforeClass
public static void setUpClass ()
throws Exception
{
}
@AfterClass
public static void tearDownClass ()
throws Exception
{
}
/**
* Test of categoryDistance method, of class LinearEvaluator.
*/
@Test
public void testCategoryDistance ()
{
System.out.println("\n--categoryDistance");
double[] pattern = new double[] { 14, 26 };
String category = "A";
LinearEvaluator instance = createTrainedInstance();
double expResult = 18.25;
double result = instance.categoryDistance(pattern, category);
assertEquals(expResult, result, 0.01);
}
/**
* Test of dump method, of class LinearEvaluator.
*/
@Test
public void testDump ()
{
System.out.println("\n--dump");
LinearEvaluator instance = createTrainedInstance();
instance.dump();
}
/**
* Test of dumpDistance method, of class LinearEvaluator.
*/
@Test
public void testDumpDistance ()
{
System.out.println("\n--dumpDistance");
double[] pattern = new double[] { 14, 26 };
String category = "A";
LinearEvaluator instance = createTrainedInstance();
instance.dumpDistance(pattern, category);
}
/**
* Test of patternDistance method, of class LinearEvaluator.
*/
@Test
public void testManyPatternDistance ()
{
System.out.println("\n--manyPatternDistance");
LinearEvaluator instance = createTrainedInstance();
double[] one = new double[] { 10, 20 };
System.out.println("Distances to " + Arrays.toString(one));
for (Sample sample : samples) {
double result = instance.patternDistance(one, sample.pattern);
System.out.println("dist:" + result + " " + sample);
}
}
/**
* Test of marshal method, of class LinearEvaluator.
* @throws Exception
*/
/////////@Test
public void testMarshal ()
throws Exception
{
System.out.println("\n--marshal");
File dir = new File(dirName);
File file = new File(dir, fileName);
dir.mkdirs();
OutputStream os = new FileOutputStream(file);
LinearEvaluator instance = createTrainedInstance();
instance.marshal(os);
os.close();
}
/**
* Test of patternDistance method, of class LinearEvaluator.
*/
@Test
public void testPatternDistance ()
{
System.out.println("\n--patternDistance");
double[] one = new double[] { 10, 20 };
double[] two = new double[] { 5, 40 };
LinearEvaluator instance = createTrainedInstance();
double expResult = 0.03;
double result = instance.patternDistance(one, two);
assertEquals(expResult, result, 0.1);
}
/**
* Test of Printer methods, of class LinearEvaluator.
*/
@Test
public void testPrinter ()
{
System.out.println("\n--Printer");
double[] one = new double[] { 10, 20 };
double[] two = new double[] { 5, 40 };
LinearEvaluator instance = createTrainedInstance();
Printer printer = instance.new Printer(12);
System.out.println("defaults: " + printer.getDefaults());
System.out.println(" names: " + printer.getNames());
System.out.println(" " + printer.getDashes());
System.out.println(" deltas: " + printer.getDeltas(one, two));
System.out.println(" wDeltas: " + printer.getWeightedDeltas(one, two));
}
/**
* Test of train method, of class LinearEvaluator.
*/
@Test
public void testTrain ()
{
System.out.println("\n--train");
LinearEvaluator instance = createTrainedInstance();
instance.dump();
}
/**
* Test of unmarshal method, of class LinearEvaluator.
* @throws Exception
*/
////////@Test
public void testUnmarshal ()
throws Exception
{
System.out.println("\n--unmarshal");
File dir = new File(dirName);
File file = new File(dir, fileName);
InputStream in = new FileInputStream(file);
LinearEvaluator result = LinearEvaluator.unmarshal(in);
result.dump();
}
/**
* Test of marchal THEN unmarshal methods.
* @throws Exception
*/
@Test
public void testMarshalThenUnmarshal ()
throws Exception
{
testMarshal();
testUnmarshal();
}
private LinearEvaluator createRawInstance ()
{
LinearEvaluator le = new LinearEvaluator(inNames);
return le;
}
private LinearEvaluator createTrainedInstance ()
{
LinearEvaluator le = createRawInstance();
le.train(samples);
return le;
}
}
| jlpoolen/libreveris | src/test/omr/math/LinearEvaluatorTest.java | Java | lgpl-3.0 | 7,622 |
/**
* DynamicReports - Free Java reporting library for creating reports dynamically
*
* Copyright (C) 2010 - 2015 Ricardo Mariaca
* http://www.dynamicreports.org
*
* This file is part of DynamicReports.
*
* DynamicReports 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.
*
* DynamicReports 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 DynamicReports. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.dynamicreports.report.definition.chart.plot;
import java.util.List;
/**
* @author Ricardo Mariaca ([email protected])
*/
public interface DRIMultiAxisPlot extends DRIAxisPlot {
public List<DRIChartAxis> getAxes();
}
| svn2github/dynamicreports-jasper | dynamicreports-core/src/main/java/net/sf/dynamicreports/report/definition/chart/plot/DRIMultiAxisPlot.java | Java | lgpl-3.0 | 1,170 |
package org.tagcloud;
import org.tagcloud.colorproviders.ShadesOfLightBlue;
import org.tagcloud.fontproviders.SansSerifFontProvider;
import java.awt.event.MouseEvent;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.util.logging.Logger;
import javax.swing.JLabel;
/*
TagCloudJLabel.java: A widget that shows a word in a Tag Cloud
Copyright (C) 2009-2014 Richard Eigenmann.
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 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.
The license is in gpl.txt.
See http://www.gnu.org/copyleft/gpl.html for the details.
*/
/**
* A JLabel that shows a word (in a Tag Cloud) with a color that changes
* depending on a percentage and a size that increases with a percentage. It
* also highlights the term in a different color if the mouse moves over the
* label.
*
* @author Richard Eigenmann
*/
public class TagCloudJLabel extends JLabel {
/**
* Defines a logger for this class
*/
private static final Logger LOGGER = Logger.getLogger( TagCloudJLabel.class.getName() );
/**
* The weighted word for which we are building a label
*/
private WeightedWordInterface weightedWord;
/**
* The font provider for the label
*/
private FontProvider fontProvider;
/**
* The color provider for the label
*/
private ColorProvider colorProvider;
/**
* The color to highlight the label in when moving the mouse over the label.
*/
private Color mouseoverColor;
/**
* Constructs a Word Label with default styles
*
* @param word The word to show
*/
public TagCloudJLabel( WeightedWordInterface word ) {
this( word, new SansSerifFontProvider(), new ShadesOfLightBlue(), new Color( 0x421ed9 ) );
}
/**
* Constructs a Word Label
*
* @param word The word to show
* @param fontProvider The font provider that will return the font to use
* @param colorProvider the color provider that will return the color to use
* @param mouseoverColor the color to use in the mouseover
*/
public TagCloudJLabel( WeightedWordInterface word, FontProvider fontProvider, ColorProvider colorProvider, Color mouseoverColor ) {
super( word.getWord() );
this.weightedWord = word;
setFontProvider( fontProvider );
setColorProvider( colorProvider );
setMouseoverColor( mouseoverColor );
addMouseListener( new MouseAdapter() {
@Override
public void mouseEntered( MouseEvent e ) {
super.mouseEntered( e );
setForeground( getMouseoverColor() );
}
@Override
public void mouseExited( MouseEvent e ) {
super.mouseExited( e );
setForegroundColor();
}
} );
}
/**
* Allows the Font provider to be set. Call validate after changing.
*
* @param fontProvider the new font provider.
*/
public final void setFontProvider( FontProvider fontProvider ) {
this.fontProvider = fontProvider;
setFont();
}
/**
* Sets the font based on the sizeWeight by querying the font provider.
*/
private void setFont() {
setFont( fontProvider.getFont( weightedWord.getSizeWeight(), weightedWord.getSizeValue() ) );
}
/**
* Sets the color to use when the mouse moves over the word
*
* @param mouseoverColor the color for the mouseover
*/
public final void setMouseoverColor( Color mouseoverColor ) {
this.mouseoverColor = mouseoverColor;
}
/**
* Returns the color to use when the mouse moves over the word
*
* @return the color to use in a mouseover
*/
public final Color getMouseoverColor() {
return mouseoverColor;
}
/**
* Sets the color provider for the label. Call validate() after changing.
* Internally calls setForegroundColor().
*
* @param colorProvider the new color provider
*/
public final void setColorProvider( ColorProvider colorProvider ) {
this.colorProvider = colorProvider;
setForegroundColor();
}
/**
* Sets the foreground color according to the colorWeight by calling the
* color provider's getColor method
*/
private void setForegroundColor() {
setForeground( colorProvider.getColor( weightedWord.getColorWeight(), weightedWord.getColorValue() ) );
}
/**
* Returns the WeightedWord for the Label
* @return the weighted word
*/
public WeightedWordInterface getWeightedWord() {
return weightedWord;
}
}
| richardeigenmann/TagCloud | src/main/java/org/tagcloud/TagCloudJLabel.java | Java | lgpl-3.0 | 5,261 |
package tools;
import org.junit.Assert;
import zildo.client.Client;
import zildo.client.ClientEngineZildo;
import zildo.client.gui.MenuTransitionProgress;
import zildo.client.stage.GameStage;
import zildo.client.stage.MenuStage;
import zildo.fwk.ui.ItemMenu;
import zildo.fwk.ui.Menu;
public class EngineWithMenuUT extends EngineUT {
protected void pickItem(String id) {
Client client = ClientEngineZildo.getClientForMenu();
Menu currentMenu = client.getCurrentMenu();
ItemMenu item = currentMenu.getItemNamed(id);
if (item == null) {
throw new RuntimeException("Item "+id+" doesn't exist in "+currentMenu+" !");
}
for (GameStage stage : client.getCurrentStages()) {
if (stage instanceof MenuStage) {
((MenuStage) stage).askForItemMenu(item);
}
}
renderFrames(2 + MenuTransitionProgress.BLOCKING_FRAMES_ON_MENU_INTERACTION);
}
protected void pickItemAndCheckDifferentMenu(String id) {
Client client = ClientEngineZildo.getClientForMenu();
Menu currentMenu = client.getCurrentMenu();
pickItem(id);
// Item has been activated, we should be in another menu
renderFrames(MenuTransitionProgress.BLOCKING_FRAMES_ON_MENU_INTERACTION);
Menu nextMenu = client.getCurrentMenu();
Assert.assertNotNull(nextMenu);
// Check that we're in a different menu
Assert.assertNotEquals(nextMenu, currentMenu);
}
}
| tchegito/zildo | zildo-test/src/main/java/tools/EngineWithMenuUT.java | Java | lgpl-3.0 | 1,396 |
/* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* (C) Copyright 2009-2014, Arnaud Roques
*
* Project Info: http://plantuml.sourceforge.net
*
* This file is part of PlantUML.
*
* PlantUML is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* PlantUML distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
*
* Original Author: Arnaud Roques
*/
package net.sourceforge.plantuml.svek.image;
import java.awt.geom.Dimension2D;
import java.awt.geom.Point2D;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import net.sourceforge.plantuml.Url;
import net.sourceforge.plantuml.graphic.StringBounder;
import net.sourceforge.plantuml.graphic.UDrawable;
import net.sourceforge.plantuml.ugraphic.ColorMapper;
import net.sourceforge.plantuml.ugraphic.ColorMapperIdentity;
import net.sourceforge.plantuml.ugraphic.UChange;
import net.sourceforge.plantuml.ugraphic.UChangeColor;
import net.sourceforge.plantuml.ugraphic.UGraphic;
import net.sourceforge.plantuml.ugraphic.UHorizontalLine;
import net.sourceforge.plantuml.ugraphic.UImage;
import net.sourceforge.plantuml.ugraphic.ULine;
import net.sourceforge.plantuml.ugraphic.UParam;
import net.sourceforge.plantuml.ugraphic.UParamNull;
import net.sourceforge.plantuml.ugraphic.UShape;
import net.sourceforge.plantuml.ugraphic.UStroke;
import net.sourceforge.plantuml.ugraphic.UText;
import net.sourceforge.plantuml.ugraphic.UTranslate;
public class Footprint {
private final StringBounder stringBounder;
public Footprint(StringBounder stringBounder) {
this.stringBounder = stringBounder;
}
class MyUGraphic implements UGraphic {
private final UTranslate translate;
private final List<Point2D.Double> all;
private MyUGraphic(List<Point2D.Double> all, UTranslate translate) {
this.all = all;
this.translate = translate;
}
public boolean isSpecialTxt() {
return false;
}
public MyUGraphic() {
this(new ArrayList<Point2D.Double>(), new UTranslate());
}
public UGraphic apply(UChange change) {
if (change instanceof UTranslate) {
return new MyUGraphic(all, translate.compose((UTranslate) change));
} else if (change instanceof UStroke || change instanceof UChangeColor) {
return new MyUGraphic(all, translate);
}
throw new UnsupportedOperationException();
}
public StringBounder getStringBounder() {
return stringBounder;
}
public UParam getParam() {
return new UParamNull();
}
public void draw(UShape shape) {
final double x = translate.getDx();
final double y = translate.getDy();
if (shape instanceof UText) {
drawText(x, y, (UText) shape);
} else if (shape instanceof UHorizontalLine) {
// Definitively a Horizontal line
} else if (shape instanceof ULine) {
// Probably a Horizontal line
} else if (shape instanceof UImage) {
drawImage(x, y, (UImage) shape);
} else {
throw new UnsupportedOperationException(shape.getClass().toString());
}
}
public ColorMapper getColorMapper() {
return new ColorMapperIdentity();
}
public void startUrl(Url url) {
}
public void closeAction() {
}
private void addPoint(double x, double y) {
all.add(new Point2D.Double(x, y));
}
private void drawText(double x, double y, UText text) {
final Dimension2D dim = stringBounder.calculateDimension(text.getFontConfiguration().getFont(),
text.getText());
y -= dim.getHeight() - 1.5;
addPoint(x, y);
addPoint(x, y + dim.getHeight());
addPoint(x + dim.getWidth(), y);
addPoint(x + dim.getWidth(), y + dim.getHeight());
}
private void drawImage(double x, double y, UImage image) {
addPoint(x, y);
addPoint(x, y + image.getHeight());
addPoint(x + image.getWidth(), y);
addPoint(x + image.getWidth(), y + image.getHeight());
}
public void flushUg() {
}
}
public ContainingEllipse getEllipse(UDrawable drawable, double alpha) {
final MyUGraphic ug = new MyUGraphic();
drawable.drawU(ug);
final List<Point2D.Double> all = ug.all;
final ContainingEllipse circle = new ContainingEllipse(alpha);
for (Point2D pt : all) {
circle.append(pt);
}
return circle;
}
// public void drawDebug(UGraphic ug, double dx, double dy, TextBlock text) {
// final MyUGraphic mug = new MyUGraphic();
// text.drawU(mug, dx, dy);
// for (Point2D pt : mug.all) {
// ug.draw(pt.getX(), pt.getY(), new URectangle(1, 1));
// }
//
// }
}
| mar9000/plantuml | src/net/sourceforge/plantuml/svek/image/Footprint.java | Java | lgpl-3.0 | 5,182 |
/*
* @(#)GrayColorSliderModel.java 1.0 May 22, 2005
*
* Copyright (c) 2005 Werner Randelshofer
* Staldenmattweg 2, Immensee, CH-6405, Switzerland.
* All rights reserved.
*
* This software is the confidential and proprietary information of
* Werner Randelshofer. ("Confidential Information"). You shall not
* disclose such Confidential Information and shall use it only in
* accordance with the terms of the license agreement you entered into
* with Werner Randelshofer.
*/
package org.pushingpixels.substance.internal.contrib.randelshofer.quaqua.colorchooser;
import javax.swing.*;
/**
* A ColorSliderModel for a gray color model (brightness).
*
* @author Werner Randelshofer
* @version 1.0 May 22, 2005 Created.
*/
public class GrayColorSliderModel extends ColorSliderModel {
/**
* Creates a new instance.
*/
public GrayColorSliderModel() {
super(new DefaultBoundedRangeModel[] {
new DefaultBoundedRangeModel(0, 0, 0, 100)
});
}
public int getRGB() {
int br = (int) (components[0].getValue() * 2.55f);
return 0xff000000 | (br << 16) | (br << 8) | (br);
}
public void setRGB(int rgb) {
components[0].setValue((int)
(
(((rgb & 0xff0000) >> 16) + ((rgb & 0x00ff00) >> 8) + (rgb & 0x0000ff))
/ 3f / 2.55f
)
);
}
public int toRGB(int[] values) {
int br = (int) (values[0] * 2.55f);
return 0xff000000 | (br << 16) | (br << 8) | (br);
}
}
| Depter/JRLib | NetbeansProject/jreserve-dummy/substance/src/main/java/org/pushingpixels/substance/internal/contrib/randelshofer/quaqua/colorchooser/GrayColorSliderModel.java | Java | lgpl-3.0 | 1,530 |
/*
* This file is part of Gaia Sky, which is released under the Mozilla Public License 2.0.
* See the file LICENSE.md in the project root for full license details.
*/
package gaiasky.util.gdx.loader;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g3d.model.data.ModelMaterial;
import com.badlogic.gdx.graphics.g3d.model.data.ModelTexture;
import com.badlogic.gdx.utils.Array;
import gaiasky.util.Logger;
import gaiasky.util.Logger.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class MtlLoader {
private static final Log logger = Logger.getLogger(MtlLoader.class);
public Array<ModelMaterial> materials = new Array<>();
/**
* loads .mtl file
*/
public void load(FileHandle file) {
String line;
String[] tokens;
String curMatName = "default";
Color difcolor = Color.WHITE;
Color speccolor = Color.WHITE;
Color emicolor = Color.WHITE;
Color reflcolor = Color.BLACK;
float opacity = 1.f;
float shininess = 0.f;
String texDiffuseFilename = null;
String texEmissiveFilename = null;
String texNormalFilename = null;
if (file == null || file.exists() == false) {
logger.error("ERROR: Material file not found: " + file.name());
return;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(file.read()), 4096);
try {
while ((line = reader.readLine()) != null) {
if (line.length() > 0 && line.charAt(0) == '\t')
line = line.substring(1).trim();
tokens = line.split("\\s+");
if (tokens[0].length() == 0) {
continue;
} else if (tokens[0].charAt(0) == '#')
continue;
else {
final String key = tokens[0].toLowerCase();
if (key.equals("newmtl")) {
addCurrentMat(curMatName, difcolor, speccolor, emicolor, reflcolor, opacity, shininess, texDiffuseFilename, texEmissiveFilename, texNormalFilename, materials);
if (tokens.length > 1) {
curMatName = tokens[1];
curMatName = curMatName.replace('.', '_');
} else {
curMatName = "default";
}
difcolor = Color.WHITE;
speccolor = Color.WHITE;
emicolor = Color.WHITE;
reflcolor = Color.BLACK;
texDiffuseFilename = null;
texEmissiveFilename = null;
texNormalFilename = null;
opacity = 1.f;
shininess = 0.f;
} else if (key.equals("kd") || key.equals("ks") || key.equals("ke") || key.equals("kr")) // diffuse, specular or emissive
{
float r = Float.parseFloat(tokens[1]);
float g = Float.parseFloat(tokens[2]);
float b = Float.parseFloat(tokens[3]);
float a = 1;
if (tokens.length > 4)
a = Float.parseFloat(tokens[4]);
if (tokens[0].toLowerCase().equals("kd")) {
difcolor = new Color();
difcolor.set(r, g, b, a);
} else if (tokens[0].toLowerCase().equals("ks")) {
speccolor = new Color();
speccolor.set(r, g, b, a);
} else if (tokens[0].toLowerCase().equals("ke")) {
emicolor = new Color();
emicolor.set(r, g, b, a);
} else if (tokens[0].toLowerCase().equals("kr")) {
reflcolor = new Color();
reflcolor.set(r, g, b, a);
}
} else if (key.equals("tr") || key.equals("d")) {
opacity = Float.parseFloat(tokens[1]);
} else if (key.equals("ns")) {
shininess = Float.parseFloat(tokens[1]);
} else if (key.equals("map_kd")) {
texDiffuseFilename = file.parent().child(tokens[1]).path();
} else if (key.equals("map_ke")) {
texEmissiveFilename = file.parent().child(tokens[1]).path();
} else if (key.equals("map_kn") || key.equals("map_bump")) {
texNormalFilename = file.parent().child(tokens[1]).path();
}
}
}
reader.close();
} catch (IOException e) {
return;
}
// last material
addCurrentMat(curMatName, difcolor, speccolor, emicolor, reflcolor, opacity, shininess, texDiffuseFilename, texEmissiveFilename, texNormalFilename, materials);
return;
}
private void addCurrentMat(String curMatName, Color difcolor, Color speccolor, Color emicolor, Color reflcolor, float opacity, float shininess, String texDiffuseFilename, String texEmissiveFilename, String texNormalFilename, Array<ModelMaterial> materials) {
ModelMaterial mat = new ModelMaterial();
mat.id = curMatName;
mat.diffuse = new Color(difcolor);
mat.specular = new Color(speccolor);
mat.emissive = new Color(emicolor);
mat.reflection = new Color(reflcolor);
mat.opacity = opacity;
mat.shininess = shininess;
if (texDiffuseFilename != null) {
ModelTexture tex = new ModelTexture();
tex.usage = ModelTexture.USAGE_DIFFUSE;
tex.fileName = texDiffuseFilename;
if (mat.textures == null)
mat.textures = new Array<>(1);
mat.textures.add(tex);
}
if (texEmissiveFilename != null) {
ModelTexture tex = new ModelTexture();
tex.usage = ModelTexture.USAGE_EMISSIVE;
tex.fileName = texEmissiveFilename;
if (mat.textures == null)
mat.textures = new Array<>(1);
mat.textures.add(tex);
}
if (texNormalFilename != null) {
ModelTexture tex = new ModelTexture();
tex.usage = ModelTexture.USAGE_NORMAL;
tex.fileName = texNormalFilename;
if (mat.textures == null)
mat.textures = new Array<>(1);
mat.textures.add(tex);
}
materials.add(mat);
}
public ModelMaterial getMaterial(final String name) {
for (final ModelMaterial m : materials)
if (m.id.equals(name))
return m;
ModelMaterial mat = new ModelMaterial();
mat.id = name;
mat.diffuse = new Color(Color.WHITE);
materials.add(mat);
return mat;
}
}
| ari-zah/gaiasandbox | core/src/gaiasky/util/gdx/loader/MtlLoader.java | Java | lgpl-3.0 | 7,183 |
package net.amygdalum.comtemplate.engine;
import static java.util.Collections.emptyList;
import static net.amygdalum.comtemplate.engine.TestTemplateIntepreter.interpreter;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class AbstractTemplateLoaderTest {
private AbstractTemplateLoader loader;
@BeforeEach
public void before() throws Exception {
loader = new AbstractTemplateLoader() {
@Override
public InputStream loadSource(String name) {
return new ByteArrayInputStream("template() ::= {mytest}".getBytes());
}
@Override
public String resolveResource(String name) {
return "test";
}
};
}
@Test
public void testLoadDefinition() throws Exception {
TemplateDefinition definition = loader.loadDefinition("mygroup.template");
assertThat(definition.evaluate(interpreter(), emptyList()), equalTo("mytest"));
}
}
| almondtools/comtemplate | src/test/java/net/amygdalum/comtemplate/engine/AbstractTemplateLoaderTest.java | Java | lgpl-3.0 | 1,058 |
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package jack.valuations;
import java.util.List;
/**
* @author TJ Goff [email protected]
* @version 1.0.0
* This interface defines common functionality for Valuation functions, which
* assign scores to combinations of goods. Clients should know the Valuation
* function by which their performance will be scored.
*/
public interface Valuation {
/**
* Read parameters from a config file and initialize the Valuation
* object can be used to generate scoring functions for clients, and to
* calculate scores. @param configFile The name of the configuration
* file which describes the valuation function, or a distribution of
* functions.
*/
void initialize(String configFile);
/**
* Generate a Valuation scoring function and encode it in a string.
* @return String which encodes a scoring function.
*/
String generateScoringFunction();
/**
* Given a list of goods and scoring function, calculate the score.
* @param scoreFunct String encoding a scoring function. @param goods
* List of goods for which to calculate a score. @return the score
* achieved with a combination of goods under a scoring function.
*/
double getScore(String scoreFunct, List<String> goods);
}
| BrownGLAMOR/JACK | src/jack/valuations/Valuation.java | Java | lgpl-3.0 | 2,061 |
/*******************************************************************************
* Copyright (c) 2013 Flux IT.
*
* This file is part of JQA (http://github.com/fluxitsoft/jqa).
*
* JQA 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.
*
* JQA 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 JQA. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package ar.com.fluxit.jqa;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
/**
* The activator class controls the plug-in life cycle
*
* @author Juan Ignacio Barisich
*/
public class JQAEclipsePlugin extends AbstractUIPlugin {
public static final String PLUGIN_ID = "ar.com.fluxit.jqa";
public static final String IMG_CHECK = "jqa.image.check";
public static final String IMG_UNCHECK = "jqa.image.uncheck";
private static JQAEclipsePlugin plugin;
public static JQAEclipsePlugin getDefault() {
return plugin;
}
public static ImageDescriptor getImageDescriptor(String path) {
return imageDescriptorFromPlugin(PLUGIN_ID, path);
}
public JQAEclipsePlugin() {
}
@Override
protected void initializeImageRegistry(ImageRegistry reg) {
super.initializeImageRegistry(reg);
Bundle bundle = Platform.getBundle(PLUGIN_ID);
ImageDescriptor checkImage = ImageDescriptor.createFromURL(FileLocator
.find(bundle, new Path("icons/check..gif"), null));
reg.put(IMG_CHECK, checkImage);
ImageDescriptor uncheckImage = ImageDescriptor
.createFromURL(FileLocator.find(bundle, new Path(
"icons/uncheck..gif"), null));
reg.put(IMG_UNCHECK, uncheckImage);
}
@Override
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
}
@Override
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
}
}
| fluxitsoft/jqa | jqa-parent/jqa-eclipse-plugin-parent/jqa-eclipse-plugin-core/src/main/java/ar/com/fluxit/jqa/JQAEclipsePlugin.java | Java | lgpl-3.0 | 2,631 |
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2013 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* SonarQube is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.api.server.rule;
import com.google.common.annotations.Beta;
import com.google.common.collect.*;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory;
import org.sonar.api.ServerExtension;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.rule.Severity;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* WARNING - DO NOT USE IN 4.2. THIS API WILL BE CHANGED IN 4.3.
* <p/>
* Defines the coding rules. For example the Java Findbugs plugin provides an implementation of
* this extension point in order to define the rules that it supports.
* <p/>
* This interface replaces the deprecated class org.sonar.api.rules.RuleRepository.
*/
@Beta
public interface RuleDefinitions extends ServerExtension {
/**
* Instantiated by core but not by plugins
*/
class Context {
private final Map<String, Repository> repositoriesByKey = Maps.newHashMap();
private final ListMultimap<String, ExtendedRepository> extendedRepositoriesByKey = ArrayListMultimap.create();
public NewRepository newRepository(String key, String language) {
return new NewRepositoryImpl(this, key, language, false);
}
public NewExtendedRepository extendRepository(String key, String language) {
return new NewRepositoryImpl(this, key, language, true);
}
@CheckForNull
public Repository repository(String key) {
return repositoriesByKey.get(key);
}
public List<Repository> repositories() {
return ImmutableList.copyOf(repositoriesByKey.values());
}
public List<ExtendedRepository> extendedRepositories(String repositoryKey) {
return ImmutableList.copyOf(extendedRepositoriesByKey.get(repositoryKey));
}
public List<ExtendedRepository> extendedRepositories() {
return ImmutableList.copyOf(extendedRepositoriesByKey.values());
}
private void registerRepository(NewRepositoryImpl newRepository) {
if (repositoriesByKey.containsKey(newRepository.key)) {
throw new IllegalStateException(String.format("The rule repository '%s' is defined several times", newRepository.key));
}
repositoriesByKey.put(newRepository.key, new RepositoryImpl(newRepository));
}
private void registerExtendedRepository(NewRepositoryImpl newRepository) {
extendedRepositoriesByKey.put(newRepository.key, new RepositoryImpl(newRepository));
}
}
interface NewExtendedRepository {
NewRule newRule(String ruleKey);
/**
* Reads definition of rule from the annotations provided by the library sonar-check-api.
*/
NewRule loadAnnotatedClass(Class clazz);
/**
* Reads definitions of rules from the annotations provided by the library sonar-check-api.
*/
NewExtendedRepository loadAnnotatedClasses(Class... classes);
/**
* Reads definitions of rules from a XML file. Format is :
* <pre>
* <rules>
* <rule>
* <!-- required fields -->
* <key>the-rule-key</key>
* <name>The purpose of the rule</name>
* <description>
* <![CDATA[The description]]>
* </description>
*
* <!-- optional fields -->
* <internalKey>Checker/TreeWalker/LocalVariableName</internalKey>
* <severity>BLOCKER</severity>
* <cardinality>MULTIPLE</cardinality>
* <status>BETA</status>
* <param>
* <key>the-param-key</key>
* <tag>style</tag>
* <tag>security</tag>
* <description>
* <![CDATA[
* the param-description
* ]]>
* </description>
* <defaultValue>42</defaultValue>
* </param>
* <param>
* <key>another-param</key>
* </param>
*
* <!-- deprecated fields -->
* <configKey>Checker/TreeWalker/LocalVariableName</configKey>
* <priority>BLOCKER</priority>
* </rule>
* </rules>
*
* </pre>
*/
NewExtendedRepository loadXml(InputStream xmlInput, String encoding);
void done();
}
interface NewRepository extends NewExtendedRepository {
NewRepository setName(String s);
@CheckForNull
NewRule rule(String ruleKey);
}
class NewRepositoryImpl implements NewRepository {
private final Context context;
private final boolean extended;
private final String key;
private String language;
private String name;
private final Map<String, NewRule> newRules = Maps.newHashMap();
private NewRepositoryImpl(Context context, String key, String language, boolean extended) {
this.extended = extended;
this.context = context;
this.key = this.name = key;
this.language = language;
}
@Override
public NewRepositoryImpl setName(@Nullable String s) {
if (StringUtils.isNotEmpty(s)) {
this.name = s;
}
return this;
}
@Override
public NewRule newRule(String ruleKey) {
if (newRules.containsKey(ruleKey)) {
// Should fail in a perfect world, but at the time being the Findbugs plugin
// defines several times the rule EC_INCOMPATIBLE_ARRAY_COMPARE
// See http://jira.codehaus.org/browse/SONARJAVA-428
LoggerFactory.getLogger(getClass()).warn(String.format("The rule '%s' of repository '%s' is declared several times", ruleKey, key));
}
NewRule newRule = new NewRule(key, ruleKey);
newRules.put(ruleKey, newRule);
return newRule;
}
@CheckForNull
@Override
public NewRule rule(String ruleKey) {
return newRules.get(ruleKey);
}
@Override
public NewRepositoryImpl loadAnnotatedClasses(Class... classes) {
new RuleDefinitionsFromAnnotations().loadRules(this, classes);
return this;
}
@Override
public RuleDefinitions.NewRule loadAnnotatedClass(Class clazz) {
return new RuleDefinitionsFromAnnotations().loadRule(this, clazz);
}
@Override
public NewRepositoryImpl loadXml(InputStream xmlInput, String encoding) {
new RuleDefinitionsFromXml().loadRules(this, xmlInput, encoding);
return this;
}
@Override
public void done() {
// note that some validations can be done here, for example for
// verifying that at least one rule is declared
if (extended) {
context.registerExtendedRepository(this);
} else {
context.registerRepository(this);
}
}
}
interface ExtendedRepository {
String key();
String language();
@CheckForNull
Rule rule(String ruleKey);
List<Rule> rules();
}
interface Repository extends ExtendedRepository {
String name();
}
@Immutable
class RepositoryImpl implements Repository {
private final String key, language, name;
private final Map<String, Rule> rulesByKey;
private RepositoryImpl(NewRepositoryImpl newRepository) {
this.key = newRepository.key;
this.language = newRepository.language;
this.name = newRepository.name;
ImmutableMap.Builder<String, Rule> ruleBuilder = ImmutableMap.builder();
for (NewRule newRule : newRepository.newRules.values()) {
newRule.validate();
ruleBuilder.put(newRule.key, new Rule(this, newRule));
}
this.rulesByKey = ruleBuilder.build();
}
@Override
public String key() {
return key;
}
@Override
public String language() {
return language;
}
@Override
public String name() {
return name;
}
@Override
@CheckForNull
public Rule rule(String ruleKey) {
return rulesByKey.get(ruleKey);
}
@Override
public List<Rule> rules() {
return ImmutableList.copyOf(rulesByKey.values());
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RepositoryImpl that = (RepositoryImpl) o;
return key.equals(that.key);
}
@Override
public int hashCode() {
return key.hashCode();
}
}
class NewRule {
private final String repoKey, key;
private String name, htmlDescription, internalKey, severity = Severity.MAJOR;
private boolean template;
private RuleStatus status = RuleStatus.defaultStatus();
private final Set<String> tags = Sets.newTreeSet();
private final Map<String, NewParam> paramsByKey = Maps.newHashMap();
private NewRule(String repoKey, String key) {
this.repoKey = repoKey;
this.key = key;
}
public String key() {
return this.key;
}
public NewRule setName(@Nullable String s) {
this.name = StringUtils.trim(s);
return this;
}
public NewRule setTemplate(boolean template) {
this.template = template;
return this;
}
public NewRule setSeverity(String s) {
if (!Severity.ALL.contains(s)) {
throw new IllegalArgumentException(String.format("Severity of rule %s is not correct: %s", this, s));
}
this.severity = s;
return this;
}
public NewRule setHtmlDescription(String s) {
this.htmlDescription = StringUtils.trim(s);
return this;
}
/**
* Load description from a file available in classpath. Example : <code>setHtmlDescription(getClass().getResource("/myrepo/Rule1234.html")</code>
*/
public NewRule setHtmlDescription(@Nullable URL classpathUrl) {
if (classpathUrl != null) {
try {
setHtmlDescription(IOUtils.toString(classpathUrl));
} catch (IOException e) {
throw new IllegalStateException("Fail to read: " + classpathUrl, e);
}
} else {
this.htmlDescription = null;
}
return this;
}
public NewRule setStatus(RuleStatus status) {
if (status.equals(RuleStatus.REMOVED)) {
throw new IllegalArgumentException(String.format("Status 'REMOVED' is not accepted on rule '%s'", this));
}
this.status = status;
return this;
}
public NewParam newParam(String paramKey) {
if (paramsByKey.containsKey(paramKey)) {
throw new IllegalArgumentException(String.format("The parameter '%s' is declared several times on the rule %s", paramKey, this));
}
NewParam param = new NewParam(paramKey);
paramsByKey.put(paramKey, param);
return param;
}
@CheckForNull
public NewParam param(String paramKey) {
return paramsByKey.get(paramKey);
}
/**
* @see RuleTagFormat
*/
public NewRule addTags(String... list) {
for (String tag : list) {
RuleTagFormat.validate(tag);
tags.add(tag);
}
return this;
}
/**
* @see RuleTagFormat
*/
public NewRule setTags(String... list) {
tags.clear();
addTags(list);
return this;
}
/**
* Optional key that can be used by the rule engine. Not displayed
* in webapp. For example the Java Checkstyle plugin feeds this field
* with the internal path ("Checker/TreeWalker/AnnotationUseStyle").
*/
public NewRule setInternalKey(@Nullable String s) {
this.internalKey = s;
return this;
}
private void validate() {
if (StringUtils.isBlank(name)) {
throw new IllegalStateException(String.format("Name of rule %s is empty", this));
}
if (StringUtils.isBlank(htmlDescription)) {
throw new IllegalStateException(String.format("HTML description of rule %s is empty", this));
}
}
@Override
public String toString() {
return String.format("[repository=%s, key=%s]", repoKey, key);
}
}
@Immutable
class Rule {
private final Repository repository;
private final String repoKey, key, name, htmlDescription, internalKey, severity;
private final boolean template;
private final Set<String> tags;
private final Map<String, Param> params;
private final RuleStatus status;
private Rule(Repository repository, NewRule newRule) {
this.repository = repository;
this.repoKey = newRule.repoKey;
this.key = newRule.key;
this.name = newRule.name;
this.htmlDescription = newRule.htmlDescription;
this.internalKey = newRule.internalKey;
this.severity = newRule.severity;
this.template = newRule.template;
this.status = newRule.status;
this.tags = ImmutableSortedSet.copyOf(newRule.tags);
ImmutableMap.Builder<String, Param> paramsBuilder = ImmutableMap.builder();
for (NewParam newParam : newRule.paramsByKey.values()) {
paramsBuilder.put(newParam.key, new Param(newParam));
}
this.params = paramsBuilder.build();
}
public Repository repository() {
return repository;
}
public String key() {
return key;
}
public String name() {
return name;
}
public String severity() {
return severity;
}
@CheckForNull
public String htmlDescription() {
return htmlDescription;
}
public boolean template() {
return template;
}
public RuleStatus status() {
return status;
}
@CheckForNull
public Param param(String key) {
return params.get(key);
}
public List<Param> params() {
return ImmutableList.copyOf(params.values());
}
public Set<String> tags() {
return tags;
}
/**
* @see RuleDefinitions.NewRule#setInternalKey(String)
*/
@CheckForNull
public String internalKey() {
return internalKey;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Rule other = (Rule) o;
return key.equals(other.key) && repoKey.equals(other.repoKey);
}
@Override
public int hashCode() {
int result = repoKey.hashCode();
result = 31 * result + key.hashCode();
return result;
}
@Override
public String toString() {
return String.format("[repository=%s, key=%s]", repoKey, key);
}
}
class NewParam {
private final String key;
private String name, description, defaultValue;
private RuleParamType type = RuleParamType.STRING;
private NewParam(String key) {
this.key = this.name = key;
}
public NewParam setName(@Nullable String s) {
// name must never be null.
this.name = StringUtils.defaultIfBlank(s, key);
return this;
}
public NewParam setType(RuleParamType t) {
this.type = t;
return this;
}
/**
* Plain-text description. Can be null.
*/
public NewParam setDescription(@Nullable String s) {
this.description = StringUtils.defaultIfBlank(s, null);
return this;
}
public NewParam setDefaultValue(@Nullable String s) {
this.defaultValue = s;
return this;
}
}
@Immutable
class Param {
private final String key, name, description, defaultValue;
private final RuleParamType type;
private Param(NewParam newParam) {
this.key = newParam.key;
this.name = newParam.name;
this.description = newParam.description;
this.defaultValue = newParam.defaultValue;
this.type = newParam.type;
}
public String key() {
return key;
}
public String name() {
return name;
}
@Nullable
public String description() {
return description;
}
@Nullable
public String defaultValue() {
return defaultValue;
}
public RuleParamType type() {
return type;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Param that = (Param) o;
return key.equals(that.key);
}
@Override
public int hashCode() {
return key.hashCode();
}
}
/**
* This method is executed when server is started.
*/
void define(Context context);
}
| xinghuangxu/xinghuangxu.sonarqube | sonar-plugin-api/src/main/java/org/sonar/api/server/rule/RuleDefinitions.java | Java | lgpl-3.0 | 17,373 |
/* Generated By:JavaCC: Do not edit this line. SimpleCharStream.java Version 4.0 */
package net.sourceforge.MSGViewer.rtfparser;
/**
* An implementation of interface CharStream, where the stream is assumed to
* contain only ASCII characters (without unicode processing).
*/
public class SimpleCharStream
{
public static final boolean staticFlag = false;
int bufsize;
int available;
int tokenBegin;
public int bufpos = -1;
protected int bufline[];
protected int bufcolumn[];
protected int column = 0;
protected int line = 1;
protected boolean prevCharIsCR = false;
protected boolean prevCharIsLF = false;
protected java.io.Reader inputStream;
protected char[] buffer;
protected int maxNextCharInd = 0;
protected int inBuf = 0;
protected int tabSize = 8;
protected void setTabSize(int i) { tabSize = i; }
protected int getTabSize(int i) { return tabSize; }
protected void ExpandBuff(boolean wrapAround)
{
char[] newbuffer = new char[bufsize + 2048];
int newbufline[] = new int[bufsize + 2048];
int newbufcolumn[] = new int[bufsize + 2048];
try
{
if (wrapAround)
{
System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
System.arraycopy(buffer, 0, newbuffer,
bufsize - tokenBegin, bufpos);
buffer = newbuffer;
System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos);
bufline = newbufline;
System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos);
bufcolumn = newbufcolumn;
maxNextCharInd = (bufpos += (bufsize - tokenBegin));
}
else
{
System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
buffer = newbuffer;
System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
bufline = newbufline;
System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
bufcolumn = newbufcolumn;
maxNextCharInd = (bufpos -= tokenBegin);
}
}
catch (Throwable t)
{
throw new Error(t.getMessage());
}
bufsize += 2048;
available = bufsize;
tokenBegin = 0;
}
protected void FillBuff() throws java.io.IOException
{
if (maxNextCharInd == available)
{
if (available == bufsize)
{
if (tokenBegin > 2048)
{
bufpos = maxNextCharInd = 0;
available = tokenBegin;
}
else if (tokenBegin < 0)
bufpos = maxNextCharInd = 0;
else
ExpandBuff(false);
}
else if (available > tokenBegin)
available = bufsize;
else if ((tokenBegin - available) < 2048)
ExpandBuff(true);
else
available = tokenBegin;
}
int i;
try {
if ((i = inputStream.read(buffer, maxNextCharInd,
available - maxNextCharInd)) == -1)
{
inputStream.close();
throw new java.io.IOException();
}
else
maxNextCharInd += i;
return;
}
catch(java.io.IOException e) {
--bufpos;
backup(0);
if (tokenBegin == -1)
tokenBegin = bufpos;
throw e;
}
}
public char BeginToken() throws java.io.IOException
{
tokenBegin = -1;
char c = readChar();
tokenBegin = bufpos;
return c;
}
protected void UpdateLineColumn(char c)
{
column++;
if (prevCharIsLF)
{
prevCharIsLF = false;
line += (column = 1);
}
else if (prevCharIsCR)
{
prevCharIsCR = false;
if (c == '\n')
{
prevCharIsLF = true;
}
else
line += (column = 1);
}
switch (c)
{
case '\r' :
prevCharIsCR = true;
break;
case '\n' :
prevCharIsLF = true;
break;
case '\t' :
column--;
column += (tabSize - (column % tabSize));
break;
default :
break;
}
bufline[bufpos] = line;
bufcolumn[bufpos] = column;
}
public char readChar() throws java.io.IOException
{
if (inBuf > 0)
{
--inBuf;
if (++bufpos == bufsize)
bufpos = 0;
return buffer[bufpos];
}
if (++bufpos >= maxNextCharInd)
FillBuff();
char c = buffer[bufpos];
UpdateLineColumn(c);
return (c);
}
/**
* @deprecated
* @see #getEndColumn
*/
public int getColumn() {
return bufcolumn[bufpos];
}
/**
* @deprecated
* @see #getEndLine
*/
public int getLine() {
return bufline[bufpos];
}
public int getEndColumn() {
return bufcolumn[bufpos];
}
public int getEndLine() {
return bufline[bufpos];
}
public int getBeginColumn() {
return bufcolumn[tokenBegin];
}
public int getBeginLine() {
return bufline[tokenBegin];
}
public void backup(int amount) {
inBuf += amount;
if ((bufpos -= amount) < 0)
bufpos += bufsize;
}
public SimpleCharStream(java.io.Reader dstream, int startline,
int startcolumn, int buffersize)
{
inputStream = dstream;
line = startline;
column = startcolumn - 1;
available = bufsize = buffersize;
buffer = new char[buffersize];
bufline = new int[buffersize];
bufcolumn = new int[buffersize];
}
public SimpleCharStream(java.io.Reader dstream, int startline,
int startcolumn)
{
this(dstream, startline, startcolumn, 4096);
}
public SimpleCharStream(java.io.Reader dstream)
{
this(dstream, 1, 1, 4096);
}
public void ReInit(java.io.Reader dstream, int startline,
int startcolumn, int buffersize)
{
inputStream = dstream;
line = startline;
column = startcolumn - 1;
if (buffer == null || buffersize != buffer.length)
{
available = bufsize = buffersize;
buffer = new char[buffersize];
bufline = new int[buffersize];
bufcolumn = new int[buffersize];
}
prevCharIsLF = prevCharIsCR = false;
tokenBegin = inBuf = maxNextCharInd = 0;
bufpos = -1;
}
public void ReInit(java.io.Reader dstream, int startline,
int startcolumn)
{
ReInit(dstream, startline, startcolumn, 4096);
}
public void ReInit(java.io.Reader dstream)
{
ReInit(dstream, 1, 1, 4096);
}
public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,
int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException
{
this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);
}
public SimpleCharStream(java.io.InputStream dstream, int startline,
int startcolumn, int buffersize)
{
this(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);
}
public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,
int startcolumn) throws java.io.UnsupportedEncodingException
{
this(dstream, encoding, startline, startcolumn, 4096);
}
public SimpleCharStream(java.io.InputStream dstream, int startline,
int startcolumn)
{
this(dstream, startline, startcolumn, 4096);
}
public SimpleCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException
{
this(dstream, encoding, 1, 1, 4096);
}
public SimpleCharStream(java.io.InputStream dstream)
{
this(dstream, 1, 1, 4096);
}
public void ReInit(java.io.InputStream dstream, String encoding, int startline,
int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException
{
ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);
}
public void ReInit(java.io.InputStream dstream, int startline,
int startcolumn, int buffersize)
{
ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);
}
public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException
{
ReInit(dstream, encoding, 1, 1, 4096);
}
public void ReInit(java.io.InputStream dstream)
{
ReInit(dstream, 1, 1, 4096);
}
public void ReInit(java.io.InputStream dstream, String encoding, int startline,
int startcolumn) throws java.io.UnsupportedEncodingException
{
ReInit(dstream, encoding, startline, startcolumn, 4096);
}
public void ReInit(java.io.InputStream dstream, int startline,
int startcolumn)
{
ReInit(dstream, startline, startcolumn, 4096);
}
public String GetImage()
{
if (bufpos >= tokenBegin)
return new String(buffer, tokenBegin, bufpos - tokenBegin + 1);
else
return new String(buffer, tokenBegin, bufsize - tokenBegin) +
new String(buffer, 0, bufpos + 1);
}
public char[] GetSuffix(int len)
{
char[] ret = new char[len];
if ((bufpos + 1) >= len)
System.arraycopy(buffer, bufpos - len + 1, ret, 0, len);
else
{
System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0,
len - bufpos - 1);
System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1);
}
return ret;
}
public void Done()
{
buffer = null;
bufline = null;
bufcolumn = null;
}
/**
* Method to adjust line and column numbers for the start of a token.
*/
public void adjustBeginLineColumn(int newLine, int newCol)
{
int start = tokenBegin;
int len;
if (bufpos >= tokenBegin)
{
len = bufpos - tokenBegin + inBuf + 1;
}
else
{
len = bufsize - tokenBegin + bufpos + 1 + inBuf;
}
int i = 0, j = 0, k = 0;
int nextColDiff = 0, columnDiff = 0;
while (i < len &&
bufline[j = start % bufsize] == bufline[k = ++start % bufsize])
{
bufline[j] = newLine;
nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j];
bufcolumn[j] = newCol + columnDiff;
columnDiff = nextColDiff;
i++;
}
if (i < len)
{
bufline[j] = newLine++;
bufcolumn[j] = newCol + columnDiff;
while (i++ < len)
{
if (bufline[j = start % bufsize] != bufline[++start % bufsize])
bufline[j] = newLine++;
else
bufline[j] = newLine;
}
}
line = bufline[j];
column = bufcolumn[j];
}
}
| daitangio/exchangews | src/msgviewer/java/net/sourceforge/MSGViewer/rtfparser/SimpleCharStream.java | Java | lgpl-3.0 | 11,184 |
/*
* Copyright (C) 2013, Peter Decsi.
*
* This library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation, either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jreserve.jrlib.linkratio;
/**
* Calculates the link-ratio for a development period as the
* weighted average of the development factors in the given
* development period.
*
* The formula for the link ratio for development period `d`:
* sum(c(a,d) * f(a,d))
* lr(d) = --------------------
* sum(c(a,d))
* where:
* - `f(a,d)` is the development factor for accident period `a` and
* development period `d`.
* - `c(a,d)` is the claim for accident period `a` and development
* period `d`.
* - if either `f(a,d)` or `c(a,d)` is NaN, then the cell is ignored.
*
* @author Peter Decsi
* @version 1.0
*/
public class WeightedAverageLRMethod extends AbstractLRMethod {
public final static double MACK_ALPHA = 1d;
@Override
protected double getLinkRatio(int accidents, int dev) {
double sum = 0d;
double sw = 0d;
for(int a=0; a<accidents; a++) {
double factor = factors.getValue(a, dev);
double weight = cik.getValue(a, dev);
if(!Double.isNaN(factor) && !Double.isNaN(weight)) {
sum += (factor * weight);
sw += weight;
}
}
return (sw != 0d)? sum / sw : Double.NaN;
}
@Override
public double getMackAlpha() {
return MACK_ALPHA;
}
@Override
public boolean equals(Object o) {
return (o instanceof WeightedAverageLRMethod);
}
@Override
public int hashCode() {
return WeightedAverageLRMethod.class.hashCode();
}
@Override
public String toString() {
return "WeightedAverageLRMethod";
}
}
| Depter/JRLib | NetbeansProject/jrlib/src/main/java/org/jreserve/jrlib/linkratio/WeightedAverageLRMethod.java | Java | lgpl-3.0 | 2,435 |
package jams.worldwind.data;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
*
* @author Ronny Berndt <ronny.berndt at uni-jena.de>
*/
public class RandomNumbers {
private final List<Double> valueList;
//private final double[] values;
public RandomNumbers(double from, double to, int count) {
//this.values = new double[count];
this.valueList = new ArrayList<>(count);
fill(from,to,count);
}
private void fill(double from, double to, int count) {
Random rnd = new Random();
for(int i=0;i<count;i++) {
//this.values[i]=from + rnd.nextDouble() * (to-from);
valueList.add(from + rnd.nextDouble() * (to-from));
}
}
public List<Double> getDoubleValues() {
return this.valueList;
}
public double[] getPrimitivDoubleValues() {
double[] result = new double[valueList.size()];
for(int i=0;i<this.valueList.size();i++) {
result[i]=this.valueList.get(i);
}
return result;
}
public Object[] getIntegerValues() {
Object[] intvalues = new Object[valueList.size()];
for(int i=0;i<intvalues.length;i++) {
intvalues[i] = (Object) Math.round(this.valueList.get(i));
}
return intvalues;
}
}
| kralisch/jams | JAMSworldwind/src/jams/worldwind/data/RandomNumbers.java | Java | lgpl-3.0 | 1,366 |
package org.javacord.api.entity.message.component;
import org.javacord.api.entity.message.component.internal.ActionRowBuilderDelegate;
import org.javacord.api.util.internal.DelegateFactory;
import java.util.Arrays;
import java.util.List;
public class ActionRowBuilder implements HighLevelComponentBuilder {
private final ActionRowBuilderDelegate delegate = DelegateFactory.createActionRowBuilderDelegate();
/**
* Add multiple low-level component builders.
*
* @param components The low-level components.
* @return The builder instance to chain methods.
*/
public ActionRowBuilder addComponents(LowLevelComponent... components) {
return addComponents(Arrays.asList(components));
}
/**
* Add a list containing low-level components builders.
*
* @param components The list containing low-level components.
* @return The builder instance to chain methods.
*/
public ActionRowBuilder addComponents(List<LowLevelComponent> components) {
delegate.addComponents(components);
return this;
}
/**
* Copy an action row into this action row builder's values.
*
* @param actionRow The action row to copy.
* @return The builder instance to chain methods.
*/
public ActionRowBuilder copy(ActionRow actionRow) {
delegate.copy(actionRow);
return this;
}
/**
* Remove a low-level component from the ActionRow.
*
* @param component The low-level component being removed.
* @return The builder instance to chain methods.
*/
public ActionRowBuilder removeComponent(LowLevelComponent component) {
delegate.removeComponent(component);
return this;
}
/**
* Remove a low-level component from the ActionRow.
*
* @param index The index placement to remove.
* @return The builder instance to chain methods.
*/
public ActionRowBuilder removeComponent(int index) {
delegate.removeComponent(index);
return this;
}
/**
* Remove a low-level component from the ActionRow.
*
* @param customId The low-level component's identifier.
* @return The builder instance to chain methods.
*/
public ActionRowBuilder removeComponent(String customId) {
delegate.removeComponent(customId);
return this;
}
/**
* Get the low-level components of this action row.
*
* @return A list of components.
*/
public List<LowLevelComponent> getComponents() {
return delegate.getComponents();
}
/**
* Get the type of this component (always {@link ComponentType#ACTION_ROW}).
*
* @return The component type.
*/
public ComponentType getType() {
return delegate.getType();
}
/**
* Creates a {@link ActionRow} instance with the given values.
*
* @return The created action row instance.
*/
public ActionRow build() {
return delegate.build();
}
/**
* Gets the delegate used by the component builder internally.
*
* @return The delegate used by this component builder internally.
*/
public ActionRowBuilderDelegate getDelegate() {
return delegate;
}
}
| BtoBastian/Javacord | javacord-api/src/main/java/org/javacord/api/entity/message/component/ActionRowBuilder.java | Java | lgpl-3.0 | 3,271 |
package com.sirma.sep.instance.operation;
import java.util.Collections;
import java.util.Set;
import com.sirma.itt.seip.configuration.Options;
import com.sirma.itt.seip.context.Context;
import com.sirma.itt.seip.domain.event.AbstractInstanceTwoPhaseEvent;
import com.sirma.itt.seip.domain.instance.Instance;
import com.sirma.itt.seip.domain.security.ActionTypeConstants;
import com.sirma.itt.seip.instance.actions.AbstractOperation;
import com.sirma.itt.seip.instance.actions.InstanceOperation;
import com.sirma.itt.seip.instance.event.InstanceEventProvider;
import com.sirma.itt.seip.instance.state.Operation;
import com.sirma.itt.seip.plugin.Extension;
/**
* Base implementation for delete operation.
*
* @author BBonev
*/
@Extension(target = InstanceOperation.TARGET_NAME, order = 99999)
public class BaseDeleteOperation extends AbstractOperation {
private static final Set<String> SUPPORTED_OPERATIONS = Collections.singleton(ActionTypeConstants.DELETE);
@Override
public Set<String> getSupportedOperations() {
return SUPPORTED_OPERATIONS;
}
@Override
public Object execute(Context<String, Object> executionContext) {
Instance instance = getTargetInstance(executionContext);
Operation operation = getExecutedOperation(executionContext);
delete(instance, operation);
return null;
}
private void delete(Instance instance, Operation operation) {
if (operation != null) {
Options.CURRENT_OPERATION.set(operation);
}
try {
instance.markAsDeleted();
AbstractInstanceTwoPhaseEvent<?, ?> event = createBeforeEvent(instance);
// first notify to update statutes
notifyForStateChange(operation, instance);
// if the operation require something to be executed before the operation
// it should go here
beforeOperation(instance, operation);
// fire next part of the event
eventService.fireNextPhase(event);
} finally {
if (operation != null) {
Options.CURRENT_OPERATION.clear();
}
}
}
@Override
protected AbstractInstanceTwoPhaseEvent<?, ?> createBeforeEvent(Instance instance) {
InstanceEventProvider<Instance> eventProvider = serviceRegistry.getEventProvider(instance);
if (eventProvider == null) {
return null;
}
AbstractInstanceTwoPhaseEvent<?, ?> event = eventProvider.createBeforeInstanceDeleteEvent(instance);
eventService.fire(event);
return event;
}
} | SirmaITT/conservation-space-1.7.0 | docker/sirma-platform/platform/seip-parent/platform/domain-model/instance-core/src/main/java/com/sirma/sep/instance/operation/BaseDeleteOperation.java | Java | lgpl-3.0 | 2,355 |
package org.jumbune.common.beans;
public class FieldProfilingBean {
/** The field number. */
private int fieldNumber;
/** The comparison value. */
private double comparisonValue ;
/** The data profiling operand. */
private String dataProfilingOperand = null;
/**
* @return the fieldNumber
*/
public int getFieldNumber() {
return fieldNumber;
}
/**
* @param fieldNumber
* the fieldNumber to set
*/
public void setFieldNumber(int fieldNumber) {
this.fieldNumber = fieldNumber;
}
public void setDataProfilingOperand(String dataProfilingOperand) {
this.dataProfilingOperand = dataProfilingOperand;
}
public String getDataProfilingOperand() {
return dataProfilingOperand;
}
public void setComparisonValue(double comparisonValue) {
this.comparisonValue = comparisonValue;
}
public double getComparisonValue() {
return comparisonValue;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(comparisonValue);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + ((dataProfilingOperand == null) ? 0 : dataProfilingOperand.hashCode());
result = prime * result + fieldNumber;
return result;
}
@Override
public String toString() {
return "FieldProfilingBean [fieldNumber=" + fieldNumber
+ ", comparisonValue=" + String.format("%.3f", comparisonValue)
+ ", dataProfilingOperand=" + dataProfilingOperand + "]";
}
} | impetus-opensource/jumbune | common/src/main/java/org/jumbune/common/beans/FieldProfilingBean.java | Java | lgpl-3.0 | 1,496 |
package org.effortless.gen.classes;
import java.util.List;
import org.effortless.ann.Module;
import org.effortless.gen.GApplication;
import org.effortless.gen.GClass;
import org.effortless.gen.GenContext;
import org.effortless.gen.Transform;
public class CreateUserProfileTransform extends Object implements Transform<GApplication> {
public CreateUserProfileTransform () {
super();
}
@Override
public void process(GApplication node) {
if (node != null && node.getUserProfileClass() == null) {
GClass cg = node.newClass("Perfil");
node.setUserProfileClass(cg);
cg.addAnnotation(Module.class, "usuarios");
cg.addField(String.class, "nombre");
cg.addField(String.class, "descripcion");
cg.addField(String.class, "comentario");
List<Transform> transforms = GenContext.getClassTransforms();
for (Transform t : transforms) {
t.process(cg);
}
}
}
}
| javaeffortless/effortless-community | gen/classes/org/effortless/gen/classes/CreateUserProfileTransform.java | Java | lgpl-3.0 | 902 |
/*
* This file is part of MyDMAM
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* 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.
*
* Copyright (C) hdsdi3g for hd3g.tv 2013
*
*/
package hd3gtv.mydmam.cli;
import hd3gtv.tools.ApplicationArgs;
public interface CLIDefinition {
public String getCliModuleName();
public String getCliModuleShortDescr();
public void execCliModule(ApplicationArgs args) throws Exception;
public void showFullCliModuleHelp();
public default boolean isFunctionnal() {
return true;
}
}
| hdsdi3g/MyDMAM | app/hd3gtv/mydmam/cli/CLIDefinition.java | Java | lgpl-3.0 | 941 |
/*
* Copyright (c) 2010 AnjLab
*
* This file is part of
* Reference Implementation of Romanov's Polynomial Algorithm for 3-SAT Problem.
*
* Reference Implementation of Romanov's Polynomial Algorithm for 3-SAT Problem
* 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.
*
* Reference Implementation of Romanov's Polynomial Algorithm for 3-SAT Problem
* 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
* Reference Implementation of Romanov's Polynomial Algorithm for 3-SAT Problem.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.anjlab.sat3;
public interface ICompactTripletsStructure extends ITabularFormula
{
boolean tiersSorted();
void union(ICompactTripletsStructure cts);
void intersect(ICompactTripletsStructure cts);
/**
*
* @param varName
* @param value
* @return {@link CleanupStatus} for this concretization.
*/
CleanupStatus concretize(int varName, Value value);
/**
*
* @param tripletPermutation
* @param tripletValue
* @return True if some clauses were removed during concretization.
*/
boolean concretize(ITripletPermutation tripletPermutation, ITripletValue tripletValue);
/**
* Runs clearing procedure on this formula.
* @return True if some clauses were removed during cleanup.
*/
boolean cleanup();
/**
* <p>The formula should be 'clean' in (0 ... from) range and (to ... tiers.size()-1) range,
* as well as inside (from ... to) range.</p>
*
* <p>Such formulas usually appear as a result of concretization of 'clean' formula.</p>
*
* @param from Tier index from (inclusive)
* @param to Tier index to (inclusive)
* @return
*/
CleanupStatus cleanup(int from, int to);
Value valueOf(int varName);
void clear();
boolean isElementary();
} | anjlab/sat3 | 3-sat-core/src/main/java/com/anjlab/sat3/ICompactTripletsStructure.java | Java | lgpl-3.0 | 2,392 |
package ma.tcp.ethernet;
/*
* #%L
* tcp-ip
* %%
* Copyright (C) 2013 - 2014 Software Engineering, RWTH Aachen University
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
import java.util.LinkedList;
import java.util.Queue;
import ma.tcp.EtherMsg;
import ma.tcp.HelpCollection;
import ma.tcp.ManchesterSignal;
import ma.tcp.ethernet.gen.AManchesterDecode;
/**
* This is the implementation of the ManchesterDecode component. It decodes a Manchestersignal to an
* EtherFrame. <br>
* <br>
* Copyright (c) 2013 RWTH Aachen. All rights reserved.
*
* @author Stefan Schubert
* @version 25.03.2013<br>
* 65
*/
public class ManchesterDecodeImpl extends AManchesterDecode {
private Queue<ManchesterSignal> signals = new LinkedList<ManchesterSignal>();
@Override
public void treatFromBus(ManchesterSignal message) {
signals.offer(message);
}
@Override
public void preTimeIncreased() {
if (!signals.isEmpty()) {
String payload = "";
for (ManchesterSignal m : signals) {
if (m == ManchesterSignal.RISING) {
payload += '1';
}
else {
payload += '0';
}
}
signals.clear();
EtherMsg ether = new EtherMsg();
ether.setPayload(HelpCollection.convertToByteArray(payload));
sendToMac(ether);
}
}
/**
* @see sim.generic.ATimedComponent#timeIncreased()
*/
@Override
protected void timeIncreased() {
// TODO Auto-generated method stub
}
}
| arnehaber/montiarc-examples | tcp-ip/src/main/java/ma/tcp/ethernet/ManchesterDecodeImpl.java | Java | lgpl-3.0 | 2,338 |
/***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
package de.cismet.cids.custom.wunda.oab.mapvis;
import Sirius.navigator.ui.ComponentRegistry;
import org.apache.log4j.Logger;
import org.openide.util.NbBundle;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.util.Arrays;
import javax.swing.AbstractAction;
import javax.swing.JOptionPane;
import de.cismet.cids.custom.wunda.oab.OabUtilities;
import de.cismet.cids.dynamics.CidsBean;
import de.cismet.cismap.commons.features.Feature;
import de.cismet.cismap.commons.gui.MappingComponent;
import de.cismet.cismap.commons.interaction.CismapBroker;
import de.cismet.cismap.navigatorplugin.CidsFeature;
/**
* DOCUMENT ME!
*
* @author [email protected]
* @version 1.0
*/
public class OabMapVisualisationAction extends AbstractAction {
//~ Static fields/initializers ---------------------------------------------
private static final transient Logger log = Logger.getLogger(OabMapVisualisationAction.class);
//~ Instance fields --------------------------------------------------------
private final Component parent;
private final OabMapVisualisationDialog dialog;
private boolean autoAddFeatureToMap;
private boolean featureAdditionSelected;
//~ Constructors -----------------------------------------------------------
/**
* Creates a new OabMapVisualisationAction object.
*
* @param parent DOCUMENT ME!
* @param dialog DOCUMENT ME!
*
* @throws IllegalArgumentException DOCUMENT ME!
*/
public OabMapVisualisationAction(final Component parent, final OabMapVisualisationDialog dialog) {
super(NbBundle.getMessage(
OabMapVisualisationAction.class,
"OabMapVisualisationAction.<init>(Component,OabMapVisualisationDialog).super.name")); // NOI18N
if (parent == null) {
throw new IllegalArgumentException("parent must not be null"); // NOI18N
}
if (dialog == null) {
throw new IllegalArgumentException("dialog must not be null"); // NOI18N
}
this.parent = parent;
this.dialog = dialog;
autoAddFeatureToMap = true;
featureAdditionSelected = false;
}
//~ Methods ----------------------------------------------------------------
@Override
public void actionPerformed(final ActionEvent e) {
final int answer = JOptionPane.showConfirmDialog(
parent,
dialog,
NbBundle.getMessage(
OabMapVisualisationAction.class,
"OabMapVisualisationAction.actionPerformed(ActionEvent).dialog.title"), // NOI18N
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE);
if (answer == JOptionPane.OK_OPTION) {
try {
final MappingComponent map = CismapBroker.getInstance().getMappingComponent();
if (dialog.isAddFeature()) {
if (isAutoAddFeatureToMap()) {
final Feature feature = new CidsFeature(dialog.getFeatureBean().getMetaObject());
map.getFeatureCollection().addFeature(feature);
CismapBroker.getInstance()
.getMappingComponent()
.zoomToAFeatureCollection(Arrays.asList(feature), true, false);
} else {
featureAdditionSelected = true;
}
}
if (dialog.isAddTin()) {
final String cap = dialog.getTinCapabilitiesUrl();
final String lname = dialog.getTinLayername();
map.getMappingModel().addLayer(OabUtilities.createWMSLayer(cap, lname));
}
if (dialog.isAddBE()) {
final String cap = dialog.getBeCapabilitiesUrl();
final String lname = dialog.getBeLayername();
map.getMappingModel().addLayer(OabUtilities.createWMSLayer(cap, lname));
}
if (dialog.isAddMaxWater()) {
final String cap = dialog.getMaxWaterCapabilitiesUrl();
final String lname = dialog.getMaxWaterLayername();
map.getMappingModel().addLayer(OabUtilities.createWMSLayer(cap, lname));
}
if (dialog.isAddTSWater()) {
final String cap = dialog.getTsWaterCapabilitiesUrl();
final String lname = dialog.getTsWaterLayername();
map.getMappingModel().addLayer(OabUtilities.createWMSLayer(cap, lname));
}
ComponentRegistry.getRegistry().showComponent("map");
} catch (final Exception ex) {
log.warn("illegal action setup, oab map visualisation state undefined", ex); // NOI18N
}
}
}
/**
* DOCUMENT ME!
*
* @param autoAddFeatureToMap DOCUMENT ME!
*/
public void setAutoAddFeatureToMap(final boolean autoAddFeatureToMap) {
this.autoAddFeatureToMap = autoAddFeatureToMap;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public boolean isAutoAddFeatureToMap() {
return autoAddFeatureToMap;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public boolean isFeatureAdditionSelected() {
return featureAdditionSelected;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public CidsBean getFeatureBean() {
return dialog.getFeatureBean();
}
}
| cismet/cids-custom-wuppertal | src/main/java/de/cismet/cids/custom/wunda/oab/mapvis/OabMapVisualisationAction.java | Java | lgpl-3.0 | 5,854 |
package org.skate.service.request;
/**
* The request parameters for the FDR search.
*
* http://km.fao.org/FIGISwiki/index.php/FAO_Document_Repository#
* Webservice_Interface
*
*
* @author Erik van Ingen
*
*/
public class PublicationSearchRequest extends SearchRequest {
private String wordsInTitle;
private String author;
private int year;
private String series;
private String owner;
private String statutoryBody;
private String isbn;
private String programmeName;
private String projectName;
private String documentNumber;
private String jobNumber;
private String publicationType;
private String country;
private String continent;
public String getWordsInTitle() {
return wordsInTitle;
}
public void setWordsInTitle(String wordsInTitle) {
this.wordsInTitle = wordsInTitle;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getSeries() {
return series;
}
public void setSeries(String series) {
this.series = series;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public String getStatutoryBody() {
return statutoryBody;
}
public void setStatutoryBody(String statutoryBody) {
this.statutoryBody = statutoryBody;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getProgrammeName() {
return programmeName;
}
public void setProgrammeName(String programmeName) {
this.programmeName = programmeName;
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public String getDocumentNumber() {
return documentNumber;
}
public void setDocumentNumber(String documentNumber) {
this.documentNumber = documentNumber;
}
public String getJobNumber() {
return jobNumber;
}
public void setJobNumber(String jobNumber) {
this.jobNumber = jobNumber;
}
public String getPublicationType() {
return publicationType;
}
public void setPublicationType(String publicationType) {
this.publicationType = publicationType;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getContinent() {
return continent;
}
public void setContinent(String continent) {
this.continent = continent;
}
}
| openfigis/skate-search | skate-search-interface-dto/src/main/java/org/skate/service/request/PublicationSearchRequest.java | Java | lgpl-3.0 | 2,575 |
package org.minetweak.command;
import net.minecraft.crash.exception.MinecraftException;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.WorldServer;
import org.minetweak.server.Server;
public class CommandSave extends CommandExecutor {
@Override
public void executeCommand(CommandSender sender, String overallCommand, String[] args) {
Server.broadcastMessage("Starting World Save...");
MinecraftServer var3 = MinecraftServer.getServer();
if (var3.getConfigurationManager() != null) {
var3.getConfigurationManager().saveAllPlayerData();
}
try {
int var4;
WorldServer var5;
boolean var6;
for (var4 = 0; var4 < var3.worldServers.length; ++var4) {
if (var3.worldServers[var4] != null) {
var5 = var3.worldServers[var4];
var6 = var5.levelSaving;
var5.levelSaving = false;
var5.saveAllChunks(true, null);
var5.levelSaving = var6;
}
}
Server.broadcastMessage("World Save Complete.");
} catch (MinecraftException var7) {
Server.broadcastMessage("World Save Failed.");
}
}
@Override
public String getHelpInfo() {
return "Saves Server Data";
}
}
| DirectCodeGraveyard/Minetweak | src/main/java/org/minetweak/command/CommandSave.java | Java | lgpl-3.0 | 1,383 |
package chat;
import chat.messages.ColoredTextMessage;
import chat.messages.DefaultTextMessage;
import chat.messages.LoginMessage;
import chat.messages.StatusMessage;
import chat.messages.PrivateMessage;
public interface IMessageVisitor {
public void visit(LoginMessage message);
public void visit(DefaultTextMessage message);
public void visit(StatusMessage message);
public void setNextVisitor(IMessageVisitor next);
public void visit(ColoredTextMessage message);
public void visit(PrivateMessage message);
}
| SergiyKolesnikov/fuji | examples/Chat_casestudies/chat-huber/src/clientgui/chat/IMessageVisitor.java | Java | lgpl-3.0 | 551 |
package zenithmods.recall.world;
import zenithmods.recall.Config;
import zenithmods.recall.registry.RecallRegistry;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import net.minecraft.world.WorldSavedData;
public class RecallWorldData extends WorldSavedData {
private static final String ID = Config.MODID+"Data";
public RecallWorldData(String id) {
super(ID);
//markDirty();
}
@Override
public void readFromNBT(NBTTagCompound nbt) {
RecallRegistry.readFromNBT(nbt);
}
@Override
public void writeToNBT(NBTTagCompound nbt) {
RecallRegistry.writeToNBT(nbt);
}
public static RecallWorldData get(World world) {
RecallWorldData data = (RecallWorldData) world.perWorldStorage.loadData(RecallWorldData.class, ID);
if (data == null) {
data = new RecallWorldData(ID);
world.perWorldStorage.setData(ID, data);
}
return data;
}
}
| Zenith-One/RecallResurrection | src/main/java/zenithmods/recall/world/RecallWorldData.java | Java | lgpl-3.0 | 928 |
/*
* 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.core.persistence.dialect;
import org.junit.Test;
import static org.fest.assertions.Assertions.assertThat;
public class MsSqlTest {
private MsSql msSql = new MsSql();
@Test
public void matchesJdbcURL() {
assertThat(msSql.matchesJdbcURL("jdbc:jtds:sqlserver://localhost;databaseName=SONAR;SelectMethod=Cursor")).isTrue();
assertThat(msSql.matchesJdbcURL("jdbc:microsoft:sqlserver://localhost:1433;databasename=sonar")).isTrue();
assertThat(msSql.matchesJdbcURL("jdbc:hsql:foo")).isFalse();
assertThat(msSql.matchesJdbcURL("jdbc:mysql:foo")).isFalse();
}
@Test
public void testBooleanSqlValues() {
assertThat(msSql.getTrueSqlValue()).isEqualTo("1");
assertThat(msSql.getFalseSqlValue()).isEqualTo("0");
}
@Test
public void should_configure() {
assertThat(msSql.getId()).isEqualTo("mssql");
assertThat(msSql.getActiveRecordDialectCode()).isEqualTo("sqlserver");
assertThat(msSql.getDefaultDriverClassName()).isEqualTo("net.sourceforge.jtds.jdbc.Driver");
assertThat(msSql.getValidationQuery()).isEqualTo("SELECT 1");
}
}
| teryk/sonarqube | sonar-core/src/test/java/org/sonar/core/persistence/dialect/MsSqlTest.java | Java | lgpl-3.0 | 1,987 |
/*
* Copyright (C) 2010 Teleal GmbH, Switzerland
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.teleal.cling.transport;
import org.teleal.cling.transport.spi.InitializationException;
/**
* Switchable network transport layer interface.
* <p>
* This router can be turned on and off, it will shutdown all listening
* threads and close all listening sockets when it is disabled, and
* rebind when it is enabled.
* </p>
* While disabled, only mock responses (mostly <code>null</code>) will be returned
* from this network transport layer, and all operations are NOOPs.
* </p>
*
* @author Christian Bauer
*/
public interface SwitchableRouter extends Router {
boolean isEnabled();
/**
* @return <code>true</code> if the router was enabled. <code>false</code> if it's already running.
*/
boolean enable();
/**
* @return <code>true</code> if the router was disabled. <code>false</code> if it wasn't running.
*/
boolean disable();
/**
* Called by the {@link #enable()} method before it returns.
*
* @param ex The cause of the failure.
*/
void handleStartFailure(InitializationException ex);
}
| HisenseUSA/Cling-1.0.5 | core/src/main/java/org/teleal/cling/transport/SwitchableRouter.java | Java | lgpl-3.0 | 1,810 |
package ecologylab.appframework.types;
import ecologylab.appframework.types.prefs.PrefsTranslationsProvider;
import ecologylab.generic.Debug;
import ecologylab.oodss.messages.DefaultServicesTranslations;
import ecologylab.serialization.SimplTypesScope;
/**
* Base translations for applications that use the ecologylab appframework and services.
*
* @author andruid
* @author andrew
*/
public class AppFrameworkTranslations extends Debug
{
public static final String PACKAGE_NAME = "ecologylab.appframework.types";
public static final SimplTypesScope inheritedTranslations[] =
{
DefaultServicesTranslations.get(),
PrefsTranslationsProvider.get()
};
/**
* Do not use this accessor.
*/
private AppFrameworkTranslations()
{
}
/**
* This accessor will work from anywhere, in any order, and stay efficient.
* @return
*/
public static SimplTypesScope get()
{
return SimplTypesScope.get(PACKAGE_NAME, inheritedTranslations);
}
}
| ecologylab/ecologylabFundamental | src/ecologylab/appframework/types/AppFrameworkTranslations.java | Java | lgpl-3.0 | 964 |
/*
* casmi
* http://casmi.github.com/
* Copyright (C) 2011, Xcoo, Inc.
*
* casmi is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package casmi;
import casmi.graphics.canvas.Canvas;
import casmi.graphics.object.Camera;
/**
* Class for Trackball manipulation.
*
* @author T. Takeuchi, Y. Ban
*/
public class Trackball {
private static final double TRACKBALL_SIZE = 0.8;
private static final int RENORM_COUNT = 97;
private static int count = 0;
private int width, height;
private Camera camera = null;
class Quaternion {
double x = 0.0, y = 0.0, z = 0.0;
double w = 1.0;
public Quaternion() {}
public Quaternion(double x, double y, double z, double w) {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
}
private Quaternion curQuat = new Quaternion();
public Trackball(int width, int height) {
if (width <= 0 || height <= 0) {
throw new IllegalArgumentException("Width and height must be more than zero.");
}
this.width = width;
this.height = height;
}
public Trackball(Applet applet) {
this(applet.getWidth(), applet.getHeight());
}
public void update(int mouseX, int mouseY, int prevMouseX, int prevMouseY) {
double normalizedMouseX = (2.0 * mouseX - width) / width;
double normalizedMouseY = (2.0 * mouseY - height) / height;
double normalizedPrevMouseX = (2.0 * prevMouseX - width) / width;
double normalizedPrevMouseY = (2.0 * prevMouseY - height) / height;
Quaternion lastQuat =
calcQuat(normalizedPrevMouseX, normalizedPrevMouseY, normalizedMouseX, normalizedMouseY);
curQuat = addQuats(lastQuat, curQuat);
}
public void reset() {
curQuat = new Quaternion();
}
public double[] getRotationMatrix() {
return calcRotMatrix();
}
public void rotate(Canvas obj) {
rotate(obj, obj.getX(), obj.getY(), obj.getZ());
}
public void rotate(Canvas obj, double baseX, double baseY, double baseZ) {
double[] rotMat = calcRotMatrix();
double[] mat1 =
{1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, -baseX, -baseY, -baseZ, 1.0};
double[] mat2 =
{1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, baseX, baseY, baseZ, 1.0};
double[] mat = multMatrix(mat1, multMatrix(rotMat, mat2));
obj.applyMatrix(mat);
}
private final Quaternion calcQuat(double x1, double y1, double x2, double y2) {
Quaternion quat = new Quaternion();
double[] a = new double[3];
double phi;
double[] p1 = new double[3];
double[] p2 = new double[3];
double[] d = new double[3];
double t;
if (x1 == x2 && y1 == y2) {
quat.x = 0.0;
quat.y = 0.0;
quat.z = 0.0;
quat.w = 1.0;
return quat;
}
p1[0] = x1;
p1[1] = y1;
p1[2] = tbProjectToSphere(TRACKBALL_SIZE, x1, y1);
p2[0] = x2;
p2[1] = y2;
p2[2] = tbProjectToSphere(TRACKBALL_SIZE, x2, y2);
a = vcross(p2, p1);
a = applyCameraMatrix(a);
d = vsub(p1, p2);
t = vlength(d) / (2.0 * TRACKBALL_SIZE);
if (1.0 < t) {
t = 1.0;
} else if (t < -1.0) {
t = -1.0;
}
phi = 2.0 * Math.asin(t);
quat = axisToQuat(a, phi);
return quat;
}
private double[] applyCameraMatrix(double[] mat) {
if(this.camera!=null){
double[] axis = {mat[0], mat[1], mat[2], 1};
double[] eye = this.camera.getViewMatrix();
double[] inv = inverseMatrix(eye);
inv[12] = inv[13]= inv[14] = 0;
axis = multMatrix(axis, inv);
double[] result = {axis[0], axis[1], axis[2]};
return result;
} else
return mat;
}
private final Quaternion addQuats(Quaternion quat1, Quaternion quat2) {
Quaternion ret = new Quaternion();
double[] q1 = {quat1.x, quat1.y, quat1.z, quat1.w};
double[] q2 = {quat2.x, quat2.y, quat2.z, quat2.w};
double[] t1 = new double[3];
double[] t2 = new double[3];
double[] t3 = new double[3];
double[] tf = new double[4];
t1[0] = q1[0];
t1[1] = q1[1];
t1[2] = q1[2];
t1 = vscale(t1, q2[3]);
t2[0] = q2[0];
t2[1] = q2[1];
t2[2] = q2[2];
t2 = vscale(t2, q1[3]);
t3 = vcross(q2, q1);
tf[0] = t1[0] + t2[0];
tf[1] = t1[1] + t2[1];
tf[2] = t1[2] + t2[2];
tf[0] += t3[0];
tf[1] += t3[1];
tf[2] += t3[2];
tf[3] = q1[3] * q2[3] - vdot(q1, q2);
ret.x = tf[0];
ret.y = tf[1];
ret.z = tf[2];
ret.w = tf[3];
if (RENORM_COUNT < ++count) {
count = 0;
ret = normalizeQuat(ret);
}
return ret;
}
private final double[] calcRotMatrix() {
double[] rotMatrix = new double[16];
rotMatrix[0] = 1.0 - 2.0 * (curQuat.y * curQuat.y + curQuat.z * curQuat.z);
rotMatrix[1] = 2.0 * (curQuat.x * curQuat.y - curQuat.z * curQuat.w);
rotMatrix[2] = 2.0 * (curQuat.z * curQuat.x + curQuat.y * curQuat.w);
rotMatrix[3] = 0.0;
rotMatrix[4] = 2.0 * (curQuat.x * curQuat.y + curQuat.z * curQuat.w);
rotMatrix[5] = 1.0 - 2.0 * (curQuat.z * curQuat.z + curQuat.x * curQuat.x);
rotMatrix[6] = 2.0 * (curQuat.y * curQuat.z - curQuat.x * curQuat.w);
rotMatrix[7] = 0.0;
rotMatrix[8] = 2.0 * (curQuat.z * curQuat.x - curQuat.y * curQuat.w);
rotMatrix[9] = 2.0 * (curQuat.y * curQuat.z + curQuat.x * curQuat.w);
rotMatrix[10] = 1.0 - 2.0 * (curQuat.y * curQuat.y + curQuat.x * curQuat.x);
rotMatrix[11] = 0.0;
rotMatrix[12] = 0.0;
rotMatrix[13] = 0.0;
rotMatrix[14] = 0.0;
rotMatrix[15] = 1.0;
return rotMatrix;
}
public void setSize(int width, int height) {
this.width = width;
this.height = height;
}
public void setCamera(Camera camera) {
this.camera = camera;
}
private final double tbProjectToSphere(double r, double x, double y) {
double d, t, z;
d = Math.sqrt(x * x + y * y);
if (d < r * 0.70710678118654752440) { // inside sphere
z = Math.sqrt(r * r - d * d);
} else { // on hyperbola
t = r / 1.41421356237309504880;
z = t * t / d;
}
return z;
}
private final double[] vcross(final double[] v1, final double[] v2) {
double[] ret = new double[3];
ret[0] = (v1[1] * v2[2]) - (v1[2] * v2[1]);
ret[1] = (v1[2] * v2[0]) - (v1[0] * v2[2]);
ret[2] = (v1[0] * v2[1]) - (v1[1] * v2[0]);
return ret;
}
private final double[] vsub(double[] src1, double[] src2) {
double[] ret = new double[3];
ret[0] = src1[0] - src2[0];
ret[1] = src1[1] - src2[1];
ret[2] = src1[2] - src2[2];
return ret;
}
private final double[] vnormal(double[] v) {
return vscale(v, 1.0 / vlength(v));
}
private final double[] vscale(final double[] v, final double div) {
double[] ret = new double[3];
ret[0] = v[0] * div;
ret[1] = v[1] * div;
ret[2] = v[2] * div;
return ret;
}
private final double vlength(final double[] v) {
return Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
}
private final double vdot(final double[] v1, final double[] v2) {
return v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2];
}
private final Quaternion normalizeQuat(Quaternion q) {
Quaternion ret = new Quaternion();
double mag = Math.sqrt(q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w);
ret.x = q.x / mag;
ret.y = q.y / mag;
ret.z = q.z / mag;
ret.w = q.w / mag;
return ret;
}
private final Quaternion axisToQuat(double[] a, double phi) {
double[] ret = new double[4];
a = vnormal(a);
ret[0] = a[0];
ret[1] = a[1];
ret[2] = a[2];
double[] tmp = vscale(ret, Math.sin(phi / 2.0));
ret[0] = tmp[0];
ret[1] = tmp[1];
ret[2] = tmp[2];
ret[3] = Math.cos(phi / 2.0);
return new Quaternion(ret[0], ret[1], ret[2], ret[3]);
}
private final double calcDeterminate(final double[] mat) {
return mat[12] * mat[9] * mat[6] * mat[3] - mat[8] * mat[13] * mat[6] * mat[3] -
mat[12] * mat[5] * mat[10] * mat[3] + mat[4] * mat[13] * mat[10] * mat[3] +
mat[8] * mat[5] * mat[14] * mat[3] - mat[4] * mat[9] * mat[14] * mat[3] -
mat[12] * mat[9] * mat[2] * mat[7] + mat[8] * mat[13] * mat[2] * mat[7] +
mat[12] * mat[1] * mat[10] * mat[7] - mat[0] * mat[13] * mat[10] * mat[7] -
mat[8] * mat[1] * mat[14] * mat[7] + mat[0] * mat[9] * mat[14] * mat[7] +
mat[12] * mat[5] * mat[2] * mat[11] - mat[4] * mat[13] * mat[2] * mat[11] -
mat[12] * mat[1] * mat[6] * mat[11] + mat[0] * mat[13] * mat[6] * mat[11] +
mat[4] * mat[1] * mat[14] * mat[11] - mat[0] * mat[5] * mat[14] * mat[11] -
mat[8] * mat[5] * mat[2] * mat[15] + mat[4] * mat[9] * mat[2] * mat[15] +
mat[8] * mat[1] * mat[6] * mat[15] - mat[0] * mat[9] * mat[6] * mat[15] -
mat[4] * mat[1] * mat[10] * mat[15] + mat[0] * mat[5] * mat[10] * mat[15] ;
}
private final double[] inverseMatrix(final double[] mat) {
double[] inv = new double[16];
double[] result = new double[16];
double det = 1.0f / calcDeterminate(mat);
inv[0] = mat[6]*mat[11]*mat[13] - mat[7]*mat[10]*mat[13]
+ mat[7]*mat[9]*mat[14] - mat[5]*mat[11]*mat[14]
- mat[6]*mat[9]*mat[15] + mat[5]*mat[10]*mat[15];
inv[4] = mat[3]*mat[10]*mat[13] - mat[2]*mat[11]*mat[13]
- mat[3]*mat[9]*mat[14] + mat[1]*mat[11]*mat[14]
+ mat[2]*mat[9]*mat[15] - mat[1]*mat[10]*mat[15];
inv[8] = mat[2]*mat[7]*mat[13] - mat[3]*mat[6]*mat[13]
+ mat[3]*mat[5]*mat[14] - mat[1]*mat[7]*mat[14]
- mat[2]*mat[5]*mat[15] + mat[1]*mat[6]*mat[15];
inv[12] = mat[3]*mat[6]*mat[9] - mat[2]*mat[7]*mat[9]
- mat[3]*mat[5]*mat[10] + mat[1]*mat[7]*mat[10]
+ mat[2]*mat[5]*mat[11] - mat[1]*mat[6]*mat[11];
inv[1] = mat[7]*mat[10]*mat[12] - mat[6]*mat[11]*mat[12]
- mat[7]*mat[8]*mat[14] + mat[4]*mat[11]*mat[14]
+ mat[6]*mat[8]*mat[15] - mat[4]*mat[10]*mat[15];
inv[5] = mat[2]*mat[11]*mat[12] - mat[3]*mat[10]*mat[12]
+ mat[3]*mat[8]*mat[14] - mat[0]*mat[11]*mat[14]
- mat[2]*mat[8]*mat[15] + mat[0]*mat[10]*mat[15];
inv[9] = mat[3]*mat[6]*mat[12] - mat[2]*mat[7]*mat[12]
- mat[3]*mat[4]*mat[14] + mat[0]*mat[7]*mat[14]
+ mat[2]*mat[4]*mat[15] - mat[0]*mat[6]*mat[15];
inv[13] = mat[2]*mat[7]*mat[8] - mat[3]*mat[6]*mat[8]
+ mat[3]*mat[4]*mat[10] - mat[0]*mat[7]*mat[10]
- mat[2]*mat[4]*mat[11] + mat[0]*mat[6]*mat[11];
inv[2] = mat[5]*mat[11]*mat[12] - mat[7]*mat[9]*mat[12]
+ mat[7]*mat[8]*mat[13] - mat[4]*mat[11]*mat[13]
- mat[5]*mat[8]*mat[15] + mat[4]*mat[9]*mat[15];
inv[6] = mat[3]*mat[9]*mat[12] - mat[1]*mat[11]*mat[12]
- mat[3]*mat[8]*mat[13] + mat[0]*mat[11]*mat[13]
+ mat[1]*mat[8]*mat[15] - mat[0]*mat[9]*mat[15];
inv[10] = mat[1]*mat[7]*mat[12] - mat[3]*mat[5]*mat[12]
+ mat[3]*mat[4]*mat[13] - mat[0]*mat[7]*mat[13]
- mat[1]*mat[4]*mat[15] + mat[0]*mat[5]*mat[15];
inv[14] = mat[3]*mat[5]*mat[8] - mat[1]*mat[7]*mat[8]
- mat[3]*mat[4]*mat[9] + mat[0]*mat[7]*mat[9]
+ mat[1]*mat[4]*mat[11] - mat[0]*mat[5]*mat[11];
inv[3] = mat[6]*mat[9]*mat[12] - mat[5]*mat[10]*mat[12]
- mat[6]*mat[8]*mat[13] + mat[4]*mat[10]*mat[13]
+ mat[5]*mat[8]*mat[14] - mat[4]*mat[9]*mat[14];
inv[7] = mat[1]*mat[10]*mat[12] - mat[2]*mat[9]*mat[12]
+ mat[2]*mat[8]*mat[13] - mat[0]*mat[10]*mat[13]
- mat[1]*mat[8]*mat[14] + mat[0]*mat[9]*mat[14];
inv[11] = mat[2]*mat[5]*mat[12] - mat[1]*mat[6]*mat[12]
- mat[2]*mat[4]*mat[13] + mat[0]*mat[6]*mat[13]
+ mat[1]*mat[4]*mat[14] - mat[0]*mat[5]*mat[14];
inv[15] = mat[1]*mat[6]*mat[8] - mat[2]*mat[5]*mat[8]
+ mat[2]*mat[4]*mat[9] - mat[0]*mat[6]*mat[9]
- mat[1]*mat[4]*mat[10] + mat[0]*mat[5]*mat[10];
for (int i = 0; i < 16; i++)
inv[i] *= det;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
result[i*4+j] = inv[i+4*j];
return result;
}
private final double[] multMatrix(final double[] mat1, final double[] mat2) {
double [] ret;
if(mat1.length == 16){
ret = new double[16];
ret[0] = mat1[0] * mat2[0] + mat1[1] * mat2[4] + mat1[2] * mat2[8] + mat1[3] * mat2[12];
ret[1] = mat1[0] * mat2[1] + mat1[1] * mat2[5] + mat1[2] * mat2[9] + mat1[3] * mat2[13];
ret[2] = mat1[0] * mat2[2] + mat1[1] * mat2[6] + mat1[2] * mat2[10] + mat1[3] * mat2[14];
ret[3] = mat1[0] * mat2[3] + mat1[1] * mat2[7] + mat1[2] * mat2[11] + mat1[3] * mat2[15];
ret[4] = mat1[4] * mat2[0] + mat1[5] * mat2[4] + mat1[6] * mat2[8] + mat1[7] * mat2[12];
ret[5] = mat1[4] * mat2[1] + mat1[5] * mat2[5] + mat1[6] * mat2[9] + mat1[7] * mat2[13];
ret[6] = mat1[4] * mat2[2] + mat1[5] * mat2[6] + mat1[6] * mat2[10] + mat1[7] * mat2[14];
ret[7] = mat1[4] * mat2[3] + mat1[5] * mat2[7] + mat1[6] * mat2[11] + mat1[7] * mat2[15];
ret[8] = mat1[8] * mat2[0] + mat1[9] * mat2[4] + mat1[10] * mat2[8] + mat1[11] * mat2[12];
ret[9] = mat1[8] * mat2[1] + mat1[9] * mat2[5] + mat1[10] * mat2[9] + mat1[11] * mat2[13];
ret[10] = mat1[8] * mat2[2] + mat1[9] * mat2[6] + mat1[10] * mat2[10] + mat1[11] * mat2[14];
ret[11] = mat1[8] * mat2[3] + mat1[9] * mat2[7] + mat1[10] * mat2[11] + mat1[11] * mat2[15];
ret[12] = mat1[12] * mat2[0] + mat1[13] * mat2[4] + mat1[14] * mat2[8] + mat1[15] * mat2[12];
ret[13] = mat1[12] * mat2[1] + mat1[13] * mat2[5] + mat1[14] * mat2[9] + mat1[15] * mat2[13];
ret[14] = mat1[12] * mat2[2] + mat1[13] * mat2[6] + mat1[14] * mat2[10] + mat1[15] * mat2[14];
ret[15] = mat1[12] * mat2[3] + mat1[13] * mat2[7] + mat1[14] * mat2[11] + mat1[15] * mat2[15];
} else {
ret = new double[4];
ret[0] = mat1[0] * mat2[0] + mat1[1] * mat2[4] + mat1[2] * mat2[8] + mat1[3] * mat2[12];
ret[1] = mat1[0] * mat2[1] + mat1[1] * mat2[5] + mat1[2] * mat2[9] + mat1[3] * mat2[13];
ret[2] = mat1[0] * mat2[2] + mat1[1] * mat2[6] + mat1[2] * mat2[10] + mat1[3] * mat2[14];
ret[3] = mat1[0] * mat2[3] + mat1[1] * mat2[7] + mat1[2] * mat2[11] + mat1[3] * mat2[15];
}
return ret;
}
}
| casmi/casmi | src/main/java/casmi/Trackball.java | Java | lgpl-3.0 | 15,978 |
/*
* JasperReports - Free Java Reporting Library.
* Copyright (C) 2001 - 2013 Jaspersoft Corporation. All rights reserved.
* http://www.jaspersoft.com
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is part of JasperReports.
*
* JasperReports is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JasperReports is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with JasperReports. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Contributors:
* Greg Hilton
*/
package net.sf.jasperreports.engine.export.ooxml;
import net.sf.jasperreports.engine.DefaultJasperReportsContext;
import net.sf.jasperreports.engine.JRPrintElement;
import net.sf.jasperreports.engine.JasperReportsContext;
import net.sf.jasperreports.engine.export.AbstractExporterNature;
import net.sf.jasperreports.engine.export.ExporterFilter;
/**
* @author sanda zaharia ([email protected])
* @version $Id: JROfficeOpenXmlExporterNature.java 6076 2013-04-18 09:41:58Z lucianc $
*/
public abstract class JROfficeOpenXmlExporterNature extends AbstractExporterNature
{
/**
*
*/
public JROfficeOpenXmlExporterNature(JasperReportsContext jasperReportsContext, ExporterFilter filter)
{
super(jasperReportsContext, filter);
}
/**
* @deprecated Replaced by {@link #JROfficeOpenXmlExporterNature(JasperReportsContext, ExporterFilter)}.
*/
public JROfficeOpenXmlExporterNature(ExporterFilter filter)
{
this(DefaultJasperReportsContext.getInstance(), filter);
}
/**
*
*/
public boolean isToExport(JRPrintElement element)
{
return (filter == null || filter.isToExport(element));
}
/**
*
*/
public boolean isSpanCells()
{
return true;
}
/**
*
*/
public boolean isIgnoreLastRow()
{
return true;
}
public boolean isHorizontallyMergeEmptyCells()
{
return false;
}
/**
* Specifies whether empty page margins should be ignored
*/
public boolean isIgnorePageMargins()
{
return false;
}
/**
*
*/
public boolean isBreakBeforeRow(JRPrintElement element)
{
return false;
}
/**
*
*/
public boolean isBreakAfterRow(JRPrintElement element)
{
return false;
}
}
| sikachu/jasperreports | src/net/sf/jasperreports/engine/export/ooxml/JROfficeOpenXmlExporterNature.java | Java | lgpl-3.0 | 2,694 |
package jmathlibtests.ui;
import junit.framework.*;
/**
* TestSuite that runs all the tests
*
*/
public class AllTests {
public static void main (String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite ( ) {
TestSuite suite= new TestSuite("ui");
/* include subdirectories here */
//suite.addTest(jmathlibtests.core.functions.AllTests.suite());
/* include tests in this directory here */
//suite.addTest(MathLib.Tools.TestSuite.Interpreter.testParser.suite());
return suite;
}
}
| nightscape/JMathLib | src/jmathlibtests/ui/AllTests.java | Java | lgpl-3.0 | 581 |
package com.harium.keel.filter.search;
import com.harium.keel.core.source.ImageSource;
import com.harium.keel.feature.Feature;
import com.harium.keel.feature.PointFeature;
public class PointSearch extends BooleanMaskSearch {
public PointSearch(int w, int h) {
super(w, h);
}
@Override
public boolean filter(int x, int y, int width, int height, ImageSource source, Feature component) {
if (!mask[x][y] && selectionStrategy.validateColor(source.getRGB(x, y), x, y)) {
PointFeature holder = new PointFeature(x, y, 1, 1);
results.add(holder);
return true;
}
return false;
}
@Override
public boolean filterFirst(int x, int y, int width, int height, ImageSource source, Feature component) {
if (!mask[x][y] && selectionStrategy.validateColor(source.getRGB(x, y), x, y)) {
lastComponent.setBounds(x, y, 1, 1);
return true;
}
return false;
}
}
| yuripourre/keel | src/main/java/com/harium/keel/filter/search/PointSearch.java | Java | lgpl-3.0 | 990 |
// Internal action code for project lost_robot
package observer;
import hmm.HiddenMarkovModel;
import jason.asSemantics.DefaultInternalAction;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.Literal;
import jason.asSyntax.Term;
public class check_time extends DefaultInternalAction {
@Override
public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
HiddenMarkovModel hmm = HiddenMarkovModel.get();
if (hmm == null) {
return false;
}
int time = hmm.getTime();
int interval = Integer.parseInt(args[0].toString());
if (time > 0 && time % interval == 0) {
ts.getAg().addBel(Literal.parseLiteral("time(" + time + ")"));
}
return true;
}
}
| stchepanhagn/the-lost-robeau | src/java/observer/check_time.java | Java | unlicense | 851 |
package okio;
public abstract interface h extends x
{
public abstract long a(y paramy);
public abstract h b(String paramString);
public abstract h b(ByteString paramByteString);
public abstract h b(byte[] paramArrayOfByte);
public abstract f c();
public abstract h c(byte[] paramArrayOfByte, int paramInt1, int paramInt2);
public abstract h f(int paramInt);
public abstract h g(int paramInt);
public abstract h h(int paramInt);
public abstract h h(long paramLong);
public abstract h r();
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: okio.h
* JD-Core Version: 0.6.0
*/ | clilystudio/NetBook | allsrc/okio/h.java | Java | unlicense | 670 |
package de.leoliebig.playground.patterns.mvvm.userprofile;
import android.databinding.DataBindingUtil;
import android.databinding.Observable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
import de.leoliebig.playground.R;
import de.leoliebig.playground.data.net.clients.UserServiceClient;
import de.leoliebig.playground.databinding.BindingUserProfile;
public class UserProfileActivityMvvm extends AppCompatActivity {
private static final String TAG = UserProfileActivityMvvm.class.getSimpleName();
private UserProfileViewModel viewModel;
private int userId = 2;
private Observable.OnPropertyChangedCallback viewModelListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewModel = new UserProfileViewModel(new UserServiceClient(), userId);
viewModelListener = createViewModelListener();
BindingUserProfile binding = DataBindingUtil.setContentView(this, R.layout.activity_user_profile_mvvm);
binding.setViewModel(viewModel);
}
@Override
protected void onResume() {
super.onResume();
viewModel.addOnPropertyChangedCallback(viewModelListener);
}
@Override
protected void onPause() {
super.onPause();
viewModel.removeOnPropertyChangedCallback(viewModelListener);
}
private Observable.OnPropertyChangedCallback createViewModelListener() {
return new Observable.OnPropertyChangedCallback() {
@Override
public void onPropertyChanged(Observable observable, final int id) {
if (id == UserProfileViewModel.PROPERTY_ERROR_MESSAGE) {
Log.e(TAG, viewModel.getErrorMessage() );
} else if (id == UserProfileViewModel.PROPERTY_USER_ID) {
Log.d(TAG, "User id changed: " + viewModel.getUserId());
}
}
};
}
}
| lliebig/Android-Playground | app/src/main/java/de/leoliebig/playground/patterns/mvvm/userprofile/UserProfileActivityMvvm.java | Java | unlicense | 2,018 |
package net.minecraft.block;
import java.util.Random;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.BlockFaceShape;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class BlockGrassPath extends Block
{
protected static final AxisAlignedBB GRASS_PATH_AABB = new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 0.9375D, 1.0D);
protected BlockGrassPath()
{
super(Material.GROUND);
this.setLightOpacity(255);
}
@SideOnly(Side.CLIENT)
public boolean shouldSideBeRendered(IBlockState blockState, IBlockAccess blockAccess, BlockPos pos, EnumFacing side)
{
switch (side)
{
case UP:
return true;
case NORTH:
case SOUTH:
case WEST:
case EAST:
IBlockState iblockstate = blockAccess.getBlockState(pos.offset(side));
Block block = iblockstate.getBlock();
return !iblockstate.isOpaqueCube() && block != Blocks.FARMLAND && block != Blocks.GRASS_PATH;
default:
return super.shouldSideBeRendered(blockState, blockAccess, pos, side);
}
}
/**
* Called after the block is set in the Chunk data, but before the Tile Entity is set
*/
public void onBlockAdded(World worldIn, BlockPos pos, IBlockState state)
{
super.onBlockAdded(worldIn, pos, state);
this.updateBlockState(worldIn, pos);
}
private void updateBlockState(World worldIn, BlockPos pos)
{
if (worldIn.getBlockState(pos.up()).getMaterial().isSolid())
{
worldIn.setBlockState(pos, Blocks.DIRT.getDefaultState());
}
}
public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos)
{
return GRASS_PATH_AABB;
}
/**
* Used to determine ambient occlusion and culling when rebuilding chunks for render
*/
public boolean isOpaqueCube(IBlockState state)
{
return false;
}
public boolean isFullCube(IBlockState state)
{
return false;
}
/**
* Get the Item that this Block should drop when harvested.
*/
public Item getItemDropped(IBlockState state, Random rand, int fortune)
{
return Blocks.DIRT.getItemDropped(Blocks.DIRT.getDefaultState().withProperty(BlockDirt.VARIANT, BlockDirt.DirtType.DIRT), rand, fortune);
}
public ItemStack getItem(World worldIn, BlockPos pos, IBlockState state)
{
return new ItemStack(this);
}
/**
* Called when a neighboring block was changed and marks that this state should perform any checks during a neighbor
* change. Cases may include when redstone power is updated, cactus blocks popping off due to a neighboring solid
* block, etc.
*/
public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block blockIn, BlockPos fromPos)
{
super.neighborChanged(state, worldIn, pos, blockIn, fromPos);
this.updateBlockState(worldIn, pos);
}
public BlockFaceShape getBlockFaceShape(IBlockAccess p_193383_1_, IBlockState p_193383_2_, BlockPos p_193383_3_, EnumFacing p_193383_4_)
{
return p_193383_4_ == EnumFacing.DOWN ? BlockFaceShape.SOLID : BlockFaceShape.UNDEFINED;
}
} | InverMN/MinecraftForgeReference | MinecraftBlocks/BlockGrassPath.java | Java | unlicense | 3,833 |
package br.com.tosin.ssd.controllers;
import br.com.tosin.ssd.PhysicsInterface;
import br.com.tosin.ssd.models.Position;
import br.com.tosin.ssd.models.environment.ObjectInWorld;
import br.com.tosin.ssd.utils.CONST;
/**
* Created by roger on 11/03/17.
*/
public class Physics implements PhysicsInterface {
@Override
public boolean moveTo(ObjectInWorld[][] world, Position oldPos, Position newPos) {
if (newPos.x >= 0 && newPos.x < world.length && newPos.y >= 0 && newPos.y < world[0].length) {
if (world[newPos.x][newPos.y] == null) {
return true;
}
else {
return false;
}
}
else {
return false;
}
}
@Override
public boolean nextMoveIsTarget(ObjectInWorld[][] world, Position oldPos, Position newPos) {
if (newPos.x >= 0 && newPos.x < world.length && newPos.y >= 0 && newPos.y < world[0].length) {
ObjectInWorld objectInWorld = world[newPos.x][newPos.y];
if (objectInWorld == null) {
return false;
}
else {
if (objectInWorld.code == CONST.CODE_TARGET)
return true;
}
}
return false;
}
}
| TosinRoger/SmartSystemsDesign | src/br/com/tosin/ssd/controllers/Physics.java | Java | unlicense | 1,277 |
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.mail;
import org.springframework.core.NestedRuntimeException;
/**
* Base class for all mail exceptions.
*
* @author Dmitriy Kopylenko
*/
public abstract class MailException extends NestedRuntimeException {
/**
* Constructor for MailException.
* @param msg the detail message
*/
public MailException(String msg) {
super(msg);
}
/**
* Constructor for MailException.
* @param msg the detail message
* @param cause the root cause from the mail API in use
*/
public MailException(String msg, Throwable cause) {
super(msg, cause);
}
}
| codeApeFromChina/resource | frame_packages/java_libs/spring-2.5.6-src/src/org/springframework/mail/MailException.java | Java | unlicense | 1,257 |
package net.restlesscoder.heli;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
public class CopterSpread extends Thing {
protected static final double SPREAD_SPEED = 10;
protected static BoundedImage image;
static {
int size = 9;
BufferedImage img = ImageTools.makeImage(size, size);
Graphics g = img.createGraphics();
g.setColor(Color.blue);
g.fillRoundRect(0, 0, size, size, size / 2, size / 2);
g.dispose();
image = new BoundedImage(img);
image.addBox(new BoundingBox());
}
public CopterSpread(Thing thing, double angle) {
super(thing.getGame());
type = GOOD_BULLET;
setImage(image);
float x = thing.getCX() - getWidth() / 2, y = thing.getY();
float xd = -(float) (100 * Math.cos(angle)) + x;
float yd = -(float) (100 * Math.sin(angle)) + y;
move = new BulletMovement(this, x, y, xd, yd, SPREAD_SPEED);
}
}
| ctrueden/veggie-copter | src/main/java/net/restlesscoder/heli/CopterSpread.java | Java | unlicense | 929 |
package com.changhong.smarthome.phone.foundation.logic;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.changhong.sdk.baseapi.HttpUrl;
import com.changhong.sdk.entity.BaseAccountInfo;
import com.changhong.sdk.entity.Pager;
import com.changhong.sdk.http.HttpSenderUtils;
import com.changhong.sdk.httpbean.ServiceResponse;
import com.changhong.sdk.logic.SuperLogic;
import com.changhong.smarthome.phone.foundation.baseapi.HttpAction;
import com.changhong.smarthome.phone.foundation.baseapi.JsonParse;
import com.changhong.smarthome.phone.foundation.baseapi.MsgWhat;
import com.changhong.smarthome.phone.foundation.baseapi.RequestId;
import com.changhong.smarthome.phone.foundation.baseapi.ResultCode;
import com.changhong.smarthome.phone.foundation.bean.MessageInfo;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
/**
*
* 物管通知
* [功能详细描述]
* @author hanliangru
* @version [智慧社区-终端底座, 2014年4月25日]
*/
public class PromanageNoticeLogic extends SuperLogic
{
private static PromanageNoticeLogic ins;
public static final int PAGENUM = 10;
public int currentPage = 1;
//当前请求是刷新还是加载更多
public boolean isRefresh = true;
public static synchronized PromanageNoticeLogic getInstance()
{
if (null == ins)
{
ins = new PromanageNoticeLogic();
}
return ins;
}
public List<MessageInfo> list = new ArrayList<MessageInfo>();
public HttpHandler<String> httpHanlder;
@Override
public void handleHttpException(HttpException error, String msg)
{
handler.sendEmptyMessage(CONNECT_ERROR_MSGWHAT);
}
@Override
public void handleHttpResponse(ServiceResponse serviceRes, int requestId,
InputStream is)
{
switch (requestId)
{
case RequestId.AllMSGLIST_REQUESTID:
handleMsgListData(serviceRes);
break;
default:
break;
}
}
public void handleMsgListData(ServiceResponse response)
{
try
{
if (ResultCode.RESULT_SUCCESS.equals(response.getBody().getResult()))
{
list = JsonParse.parseMsgListRes(response.getBody()
.getParamsString());
handler.sendEmptyMessage(MsgWhat.MSGWHAT_PRO_NOTICE_SUCCESS);
}
else
{
handler.sendEmptyMessage(DATA_FORMAT_ERROR_MSGWHAT);
}
}
catch (Exception e)
{
}
}
public void requestProNotice(BaseAccountInfo baseAccountInfo, int[] type,
String maxId, String timeStamp, HttpUtils httpUtils)
{
Pager pager = new Pager();
pager.setPageId(isRefresh ? 1 : currentPage + 1);
pager.setPageSize(PAGENUM);
RequestParams params = new RequestParams();
Map<String, Object> serviceInfo = new HashMap<String, Object>();
serviceInfo.put("accountInfo", baseAccountInfo);
serviceInfo.put("msgType", type);
serviceInfo.put("pager", pager);
serviceInfo.put("maxNum", 100);
serviceInfo.put("maxId", maxId);
serviceInfo.put("timeStamp", timeStamp);
fixRequestParams(params,
serviceInfo,
HttpAction.ACTION_GET_MSGLIST,
"sc",
"sc",
"4100");
httpHanlder = HttpSenderUtils.sendMsgImpl(HttpAction.ACTION_GET_MSGLIST,
params,
HttpSenderUtils.METHOD_POST,
httpUtils,
RequestId.AllMSGLIST_REQUESTID,
this,
false,
HttpUrl.URL_CBS);// HttpUrl.URL_CBS
}
@Override
public void clear()
{
list.clear();
}
@Override
public void stopRequest()
{
}
}
| yangjun2/android | changhong/ChanghongSmartHome/src/com/changhong/smarthome/phone/foundation/logic/PromanageNoticeLogic.java | Java | unlicense | 4,226 |
package cz.slahora.compling.gui.about;
/**
*
* Class with text of unlicense.org licence
*
* <dl>
* <dt>Created by:</dt>
* <dd>slaha</dd>
* <dt>On:</dt>
* <dd> 5.4.14 11:55</dd>
* </dl>
*/
public class Licence {
public static final String LICENCE = "This is free and unencumbered software released into the public domain.\n" +
"\n" +
"Anyone is free to copy, modify, publish, use, compile, sell, or\n" +
"distribute this software, either in source code form or as a compiled\n" +
"binary, for any purpose, commercial or non-commercial, and by any\n" +
"means.\n" +
"\n" +
"In jurisdictions that recognize copyright laws, the author or authors\n" +
"of this software dedicate any and all copyright interest in the\n" +
"software to the public domain. We make this dedication for the benefit\n" +
"of the public at large and to the detriment of our heirs and\n" +
"successors. We intend this dedication to be an overt act of\n" +
"relinquishment in perpetuity of all present and future rights to this\n" +
"software under copyright law.\n" +
"\n" +
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n" +
"EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n" +
"MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n" +
"IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n" +
"OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n" +
"ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n" +
"OTHER DEALINGS IN THE SOFTWARE.\n" +
"\n" +
"For more information, please refer to <http://unlicense.org>";
}
| slaha/compLing-gui | src/main/java/cz/slahora/compling/gui/about/Licence.java | Java | unlicense | 1,661 |
/* ZAbsSSNGCoreEffectCls.java */
package com.sun.org.jfx.scenario.effect;
import com.sun.javafx.org.annotations.ZAdded;
import com.sun.prism.ps.Shader;
import com.sun.scenario.effect.Effect;
import com.sun.scenario.effect.impl.prism.ps.PPSEffectPeer;
import com.sun.scenario.effect.impl.state.RenderState;
import javafx.org.scene.effect.shaderstore.mng.ZSS_EffMngITF;
/**
* This abstract class is only used for NG core effect (...).<br>
*
* @author ZZZ. No copyright(c). Public Domain.
* @param <FF>
* @param <EFP>
* @param <T>
* @param <SHA>
* @param <SST>
*/
@ZAdded
public abstract class ZAbsSSNGCoreEffectCls<FF extends Effect, EFP extends PPSEffectPeer, T extends RenderState, SHA extends Shader, SST extends ZSS_EffMngITF>
extends ZAbsNGCoreEffectCls<FF, EFP, T, SHA> {
/**
* Create a new instance.
*/
protected ZAbsSSNGCoreEffectCls() {
super();
// p_initShaderStorage(); Not here.....
}
protected ZAbsSSNGCoreEffectCls(FF input) {
super(input);
// p_initShaderStorage(); Not here.....
}
protected ZAbsSSNGCoreEffectCls(FF input1, FF input2) {
super(input1, input2);
// p_initShaderStorage(); Not here.....
}
/**
* Dispose.
*/
@Override
public void dispose() {
disposeShaderStorage();
super.dispose();
}
protected final void p_initShaderStorage() {
initShaderStorage();
}
// ========================================================================
// But for this kind of object, the shader is stored inside Renderer.
// The shader storage must be a static instance ....
// ========================================================================
/**
*
*/
protected SST shaderStorage = null; // But this is a static instance....
/**
*
*/
protected void disposeShaderStorage() {
this.shaderStorage = null;
}
/**
*
*/
protected void initShaderStorage() {
SST newShaderStorage = createShaderStorage();
if (newShaderStorage == null) {
return;
}
this.setShaderStorage(newShaderStorage);
// To force the shader to have a first name condition...
this.setFirstName(this.shaderStorage.obtFirstShaderName()); // ???
}
/**
*
* @return
*/
protected abstract SST createShaderStorage();
/**
* @return the shaderStorage
*/
public SST getShaderStorage() {
return shaderStorage;
}
/**
* @param shaderStorage the shaderStorage to set
*/
protected void setShaderStorage(SST shaderStorage) {
// Not null...
this.shaderStorage = shaderStorage;
}
// ========================================================================
}
| pepe1914/jfx_libbase | src-effect2/com/sun/org/jfx/scenario/effect/ZAbsSSNGCoreEffectCls.java | Java | unlicense | 2,825 |
package com.nullprogram.maze;
import java.awt.Color;
import java.awt.Stroke;
import java.awt.Graphics;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.BasicStroke;
import javax.swing.JPanel;
/**
* Displays a maze to the user as a GUI component.
*/
class MazeDisplay extends JPanel implements SolverListener {
private static final long serialVersionUID = 1L;
private static final Stroke WALL_STROKE = new BasicStroke(1);
/* Color scheme. */
private static final Color SOLUTION = Color.GREEN;
private static final Color ERROR = new Color(255, 127, 127);
private static final Color WALL = Color.BLACK;
private Maze maze;
/**
* Display the given maze at the given size.
* @param view the maze to be displayed
*/
public MazeDisplay(final Maze view) {
super();
setMaze(view);
}
@Override
public void paintComponent(final Graphics graphics) {
super.paintComponent(graphics);
Graphics2D g = (Graphics2D) graphics;
double scaleX = getWidth() * 1.0 / maze.getWidth();
double scaleY = getHeight() * 1.0 / maze.getHeight();
g.scale(scaleX, scaleY);
g.setStroke(WALL_STROKE);
for (Cell cell : maze) {
if (cell.hasMark(MazeSolver.ERROR_MARK)) {
g.setColor(ERROR);
g.fill(cell.getShape());
} else if (cell.hasMark(MazeSolver.SOLUTION_MARK)) {
g.setColor(SOLUTION);
g.fill(cell.getShape());
}
g.setColor(WALL);
g.draw(cell.getWalls());
}
}
/**
* Assign a new maze to this display.
* @param view the new maze to be displayed
*/
public void setMaze(final Maze view) {
maze = view;
Dimension size = new Dimension(maze.getWidth(), maze.getHeight());
setMinimumSize(size);
setPreferredSize(size);
repaint();
}
@Override
public final void solveDone() {
repaint();
}
@Override
public final void solveStep() {
repaint();
}
}
| skeeto/RunMaze | src/com/nullprogram/maze/MazeDisplay.java | Java | unlicense | 2,116 |
package gestock.entity;
import gestock.util.Tools;
/**
* Created by Roger on 1/10/2016.
*/
public class Quantity {
private final static String[] liquidUnits = {"mL", "cL", "dL", "L", "daL", "hL", "kL"};
private final static String[] weigthUnits = {"mg", "cg", "dg", "g", "dag", "hg", "kg"};
protected double quantity;
protected double smallestUnitQuantity; //in mg, ml
protected String unit;
protected int type = 3; //1 L, 2 g, 3 other
public Quantity(String text) {
if (text.contains(" ") && text.split(" ").length == 2) {
String[] toParse = text.split(" ");
if (Tools.isNumeric(toParse[0])) {
this.quantity = Double.parseDouble(toParse[0]);
} else {
int lastIndex = 0;
for (int i = 0; i < toParse[0].length(); i++) {
if (Tools.isNumeric(toParse[0].substring(0, i))) {
lastIndex = i;
}
}
this.quantity = 0;
this.quantity = Double.parseDouble(toParse[0].substring(0, lastIndex));
this.quantity += Double.parseDouble("0." + toParse[0].substring(lastIndex+1));
}
this.unit = toParse[1];
} else if (!text.contains(" ")) {
int lastIndex = 0;
for (int i = 0; i < text.length(); i++) {
if (Tools.isNumeric(text.substring(0, i))) {
lastIndex = i;
}
}
this.quantity = 0;
this.unit = "u";
this.quantity = Double.parseDouble(text.substring(0, lastIndex));
this.unit = (text.substring(lastIndex));
} else {
String[] toParse = text.split(" ");
StringBuilder sbNumbers = new StringBuilder();
StringBuilder sbUnits = new StringBuilder();
for (String s : toParse) {
if (Tools.isNumeric(s)) {
sbNumbers.append(s);
} else {
sbUnits.append(s);
}
}
this.quantity = 0;
this.unit = "u";
this.quantity = Double.parseDouble(sbNumbers.toString());
this.unit = sbUnits.toString();
}
//process type
smallestUnitQuantity = quantity;
for (String unit : liquidUnits) {
if (unit.toLowerCase().equals(this.unit.toLowerCase())) {
this.unit = unit;
this.type = 1;
Integer diff = difference(liquidUnits, liquidUnits[0], unit);
if (diff != null) {
double factor = Math.pow(10, diff);
smallestUnitQuantity = quantity * factor;
}
}
}
for (String unit : weigthUnits) {
if (unit.toLowerCase().equals(this.unit.toLowerCase())) {
this.unit = unit;
this.type = 2;
Integer diff = difference(weigthUnits, weigthUnits[0], unit);
if (diff != null) {
double factor = Math.pow(10, diff);
smallestUnitQuantity = quantity * factor;
}
}
}
}
private Integer difference(String[] array, String in, String out) {
Integer first = getIndex(array, in);
Integer last = getIndex(array, out);
if (first == null || last == null) {
return null;
}
return last - first;
}
private Integer getIndex(String[] array, String element) {
Integer result = null;
for (int i = 0; i < array.length; i++) {
if (array[i].toLowerCase().equals(element.toLowerCase())) {
result = i;
}
}
return result;
}
public double getQuantity(String unit) {
Integer index;
double quantity;
switch (type) {
case 1: //liquids
index = getIndex(liquidUnits, unit);
if (index != null) {
double factor = Math.pow(10, -index);
quantity = smallestUnitQuantity * factor;
} else {
quantity = 0;
}
break;
case 2: //weight
index = getIndex(weigthUnits, unit);
if (index != null) {
double factor = Math.pow(10, -index);
quantity = smallestUnitQuantity * factor;
} else {
quantity = 0;
}
break;
default:
quantity = this.quantity;
break;
}
return quantity;
}
public String toString() {
return quantity + " " + unit;
}
public String getSaveString() {
return quantity + unit;
}
}
| rogerxaic/gestock | src/gestock/entity/Quantity.java | Java | unlicense | 4,920 |
package nl.tehdreamteam.se42.domain;
import javax.persistence.*;
import java.util.LinkedList;
import java.util.List;
/**
* An User is a user of the application. An User can send messages in a Conversation.
*
* @author Oscar de Leeuw
*/
@Entity
@Table(name = "user")
@NamedQueries({
@NamedQuery(name = "User.findByUsername",
query = "SELECT a FROM User AS a WHERE a.loginCredentials.username = :username")
})
public class User {
@Id
@GeneratedValue
private Long id;
@Embedded
private LoginCredentials loginCredentials;
@ManyToMany(mappedBy = "participants", cascade = CascadeType.MERGE)
private List<Conversation> conversations;
protected User() {
}
/**
* Creates a new User.
*
* @param loginCredentials The LoginCredentials of the User.
*/
public User(LoginCredentials loginCredentials) {
this.loginCredentials = loginCredentials;
this.conversations = new LinkedList<>();
}
public long getId() {
return id;
}
public LoginCredentials getLoginCredentials() {
return loginCredentials;
}
public List<Conversation> getConversations() {
return conversations;
}
/**
* Adds a new Conversation to this user.
*
* @param conversation The conversation to add to the user.
*/
public void addConversation(Conversation conversation) {
conversations.add(conversation);
}
/**
* Removes a Conversation from this user.
*
* @param conversation The conversation to remove from this user.
*/
public void removeConversation(Conversation conversation) {
conversations.remove(conversation);
}
}
| TehDreamTeam/SE42 | domain/src/main/java/nl/tehdreamteam/se42/domain/User.java | Java | unlicense | 1,722 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.