code
stringlengths 10
749k
| repo_name
stringlengths 5
108
| path
stringlengths 7
333
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 10
749k
|
---|---|---|---|---|---|
package brennus.asm;
import static brennus.model.ExistingType.VOID;
import static brennus.model.ExistingType.existing;
import static brennus.model.Protection.PUBLIC;
import static junit.framework.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import brennus.Builder;
import brennus.MethodBuilder;
import brennus.SwitchBuilder;
import brennus.ThenBuilder;
import brennus.asm.TestGeneration.DynamicClassLoader;
import brennus.model.FutureType;
import brennus.printer.TypePrinter;
import org.junit.Test;
public class TestGoto {
abstract public static class FSA {
private List<String> states = new ArrayList<String>();
abstract public void exec();
public void state(String p) {
states.add(p);
}
public List<String> getStates() {
return states;
}
}
abstract public static class FSA2 {
private List<String> states = new ArrayList<String>();
abstract public void exec(Iterator<Integer> it);
public void state(String p) {
states.add(p);
}
public List<String> getStates() {
return states;
}
}
@Test
public void testGoto() throws Exception {
FutureType testClass = new Builder()
.startClass("brennus.asm.TestGoto$TestClass", existing(FSA.class))
.startMethod(PUBLIC, VOID, "exec")
.label("a")
.exec().callOnThis("state").literal("a").endCall().endExec()
.gotoLabel("c")
.label("b")
.exec().callOnThis("state").literal("b").endCall().endExec()
.gotoLabel("end")
.label("c")
.exec().callOnThis("state").literal("c").endCall().endExec()
.gotoLabel("b")
.label("end")
.endMethod()
.endClass();
// new TypePrinter().print(testClass);
DynamicClassLoader cl = new DynamicClassLoader();
cl.define(testClass);
Class<?> generated = (Class<?>)cl.loadClass("brennus.asm.TestGoto$TestClass");
FSA fsa = (FSA)generated.newInstance();
fsa.exec();
assertEquals(Arrays.asList("a", "c", "b"), fsa.getStates());
}
@Test
public void testFSA() throws Exception {
int[][] fsa = {
{0,1,2,3},
{0,1,2,3},
{0,1,2,3},
{0,1,2,3}
};
MethodBuilder m = new Builder()
.startClass("brennus.asm.TestGoto$TestClass2", existing(FSA2.class))
.startMethod(PUBLIC, VOID, "exec").param(existing(Iterator.class), "it")
.gotoLabel("start")
.label("start");
for (int i = 0; i < fsa.length; i++) {
m = m.label("s_"+i)
.exec().callOnThis("state").literal("s_"+i).endCall().endExec();
SwitchBuilder<ThenBuilder<MethodBuilder>> s = m.ifExp().get("it").callNoParam("hasNext").thenBlock()
.switchOn().get("it").callNoParam("next").switchBlock();
for (int j = 0; j < fsa[i].length; j++) {
int to = fsa[i][j];
s = s.caseBlock(j)
.gotoLabel("s_"+to)
.endCase();
}
m = s.endSwitch()
.elseBlock()
.gotoLabel("end")
.endIf();
}
FutureType testClass = m.label("end").endMethod().endClass();
new TypePrinter().print(testClass);
Logger.getLogger("brennus").setLevel(Level.FINEST);
Logger.getLogger("brennus").addHandler(new Handler() {
public void publish(LogRecord record) {
System.out.println(record.getMessage());
}
public void flush() {
System.out.flush();
}
public void close() throws SecurityException {
System.out.flush();
}
});
DynamicClassLoader cl = new DynamicClassLoader();
cl.define(testClass);
Class<?> generated = (Class<?>)cl.loadClass("brennus.asm.TestGoto$TestClass2");
FSA2 compiledFSA = (FSA2)generated.newInstance();
compiledFSA.exec(Arrays.asList(3,2,1).iterator());
assertEquals(Arrays.asList("s_0", "s_3", "s_2", "s_1"), compiledFSA.getStates());
}
}
| julienledem/brennus | brennus-asm/src/test/java/brennus/asm/TestGoto.java | Java | apache-2.0 | 4,143 |
/*-
* #%L
* Simmetrics - Examples
* %%
* Copyright (C) 2014 - 2021 Simmetrics 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.
* #L%
*/
package com.github.mpkorstanje.simmetrics.example;
import static com.github.mpkorstanje.simmetrics.builders.StringDistanceBuilder.with;
import com.github.mpkorstanje.simmetrics.StringDistance;
import com.github.mpkorstanje.simmetrics.builders.StringDistanceBuilder;
import com.github.mpkorstanje.simmetrics.metrics.EuclideanDistance;
import com.github.mpkorstanje.simmetrics.metrics.StringDistances;
import com.github.mpkorstanje.simmetrics.tokenizers.Tokenizers;
/**
* The StringDistances utility class contains a predefined list of well
* known distance metrics for strings.
*/
final class StringDistanceExample {
/**
* Two strings can be compared using a predefined distance metric.
*/
static float example01() {
String str1 = "This is a sentence. It is made of words";
String str2 = "This sentence is similar. It has almost the same words";
StringDistance metric = StringDistances.levenshtein();
return metric.distance(str1, str2); // 30.0000
}
/**
* A tokenizer is included when the metric is a set or list metric. For the
* euclidean distance, it is a whitespace tokenizer.
*
* Note that most predefined metrics are setup with a whitespace tokenizer.
*/
static float example02() {
String str1 = "A quirky thing it is. This is a sentence.";
String str2 = "This sentence is similar. A quirky thing it is.";
StringDistance metric = StringDistances.euclideanDistance();
return metric.distance(str1, str2); // 2.0000
}
/**
* Using the string distance builder distance metrics can be customized.
* Instead of a whitespace tokenizer a q-gram tokenizer is used.
*
* For more examples see StringDistanceBuilderExample.
*/
static float example03() {
String str1 = "A quirky thing it is. This is a sentence.";
String str2 = "This sentence is similar. A quirky thing it is.";
StringDistance metric =
StringDistanceBuilder.with(new EuclideanDistance<>())
.tokenize(Tokenizers.qGram(3))
.build();
return metric.distance(str1, str2); // 4.8989
}
}
| mpkorstanje/simmetrics | simmetrics-example/src/main/java/com/github/mpkorstanje/simmetrics/example/StringDistanceExample.java | Java | apache-2.0 | 2,695 |
/**
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.hdodenhof.androidstatemachine;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.Vector;
/**
* <p>The state machine defined here is a hierarchical state machine which processes messages
* and can have states arranged hierarchically.</p>
*
* <p>A state is a <code>State</code> object and must implement
* <code>processMessage</code> and optionally <code>enter/exit/getName</code>.
* The enter/exit methods are equivalent to the construction and destruction
* in Object Oriented programming and are used to perform initialization and
* cleanup of the state respectively. The <code>getName</code> method returns the
* name of the state the default implementation returns the class name it may be
* desirable to have this return the name of the state instance name instead.
* In particular if a particular state class has multiple instances.</p>
*
* <p>When a state machine is created <code>addState</code> is used to build the
* hierarchy and <code>setInitialState</code> is used to identify which of these
* is the initial state. After construction the programmer calls <code>start</code>
* which initializes and starts the state machine. The first action the StateMachine
* is to the invoke <code>enter</code> for all of the initial state's hierarchy,
* starting at its eldest parent. The calls to enter will be done in the context
* of the StateMachines Handler not in the context of the call to start and they
* will be invoked before any messages are processed. For example, given the simple
* state machine below mP1.enter will be invoked and then mS1.enter. Finally,
* messages sent to the state machine will be processed by the current state,
* in our simple state machine below that would initially be mS1.processMessage.</p>
<code>
mP1
/ \
mS2 mS1 ----> initial state
</code>
* <p>After the state machine is created and started, messages are sent to a state
* machine using <code>sendMessage</code> and the messages are created using
* <code>obtainMessage</code>. When the state machine receives a message the
* current state's <code>processMessage</code> is invoked. In the above example
* mS1.processMessage will be invoked first. The state may use <code>transitionTo</code>
* to change the current state to a new state</p>
*
* <p>Each state in the state machine may have a zero or one parent states and if
* a child state is unable to handle a message it may have the message processed
* by its parent by returning false or NOT_HANDLED. If a message is never processed
* <code>unhandledMessage</code> will be invoked to give one last chance for the state machine
* to process the message.</p>
*
* <p>When all processing is completed a state machine may choose to call
* <code>transitionToHaltingState</code>. When the current <code>processingMessage</code>
* returns the state machine will transfer to an internal <code>HaltingState</code>
* and invoke <code>halting</code>. Any message subsequently received by the state
* machine will cause <code>haltedProcessMessage</code> to be invoked.</p>
*
* <p>If it is desirable to completely stop the state machine call <code>quit</code> or
* <code>quitNow</code>. These will call <code>exit</code> of the current state and its parents,
* call <code>onQuiting</code> and then exit Thread/Loopers.</p>
*
* <p>In addition to <code>processMessage</code> each <code>State</code> has
* an <code>enter</code> method and <code>exit</code> method which may be overridden.</p>
*
* <p>Since the states are arranged in a hierarchy transitioning to a new state
* causes current states to be exited and new states to be entered. To determine
* the list of states to be entered/exited the common parent closest to
* the current state is found. We then exit from the current state and its
* parent's up to but not including the common parent state and then enter all
* of the new states below the common parent down to the destination state.
* If there is no common parent all states are exited and then the new states
* are entered.</p>
*
* <p>Two other methods that states can use are <code>deferMessage</code> and
* <code>sendMessageAtFrontOfQueue</code>. The <code>sendMessageAtFrontOfQueue</code> sends
* a message but places it on the front of the queue rather than the back. The
* <code>deferMessage</code> causes the message to be saved on a list until a
* transition is made to a new state. At which time all of the deferred messages
* will be put on the front of the state machine queue with the oldest message
* at the front. These will then be processed by the new current state before
* any other messages that are on the queue or might be added later. Both of
* these are protected and may only be invoked from within a state machine.</p>
*
* <p>To illustrate some of these properties we'll use state machine with an 8
* state hierarchy:</p>
<code>
mP0
/ \
mP1 mS0
/ \
mS2 mS1
/ \ \
mS3 mS4 mS5 ---> initial state
</code>
* <p>After starting mS5 the list of active states is mP0, mP1, mS1 and mS5.
* So the order of calling processMessage when a message is received is mS5,
* mS1, mP1, mP0 assuming each processMessage indicates it can't handle this
* message by returning false or NOT_HANDLED.</p>
*
* <p>Now assume mS5.processMessage receives a message it can handle, and during
* the handling determines the machine should change states. It could call
* transitionTo(mS4) and return true or HANDLED. Immediately after returning from
* processMessage the state machine runtime will find the common parent,
* which is mP1. It will then call mS5.exit, mS1.exit, mS2.enter and then
* mS4.enter. The new list of active states is mP0, mP1, mS2 and mS4. So
* when the next message is received mS4.processMessage will be invoked.</p>
*
* <p>Now for some concrete examples, here is the canonical HelloWorld as a state machine.
* It responds with "Hello World" being printed to the log for every message.</p>
<code>
class HelloWorld extends StateMachine {
HelloWorld(String name) {
super(name);
addState(mState1);
setInitialState(mState1);
}
public static HelloWorld makeHelloWorld() {
HelloWorld hw = new HelloWorld("hw");
hw.start();
return hw;
}
class State1 extends State {
@Override public boolean processMessage(Message message) {
log("Hello World");
return HANDLED;
}
}
State1 mState1 = new State1();
}
void testHelloWorld() {
HelloWorld hw = makeHelloWorld();
hw.sendMessage(hw.obtainMessage());
}
</code>
* <p>A more interesting state machine is one with four states
* with two independent parent states.</p>
<code>
mP1 mP2
/ \
mS2 mS1
</code>
* <p>Here is a description of this state machine using pseudo code.</p>
<code>
state mP1 {
enter { log("mP1.enter"); }
exit { log("mP1.exit"); }
on msg {
CMD_2 {
send(CMD_3);
defer(msg);
transitonTo(mS2);
return HANDLED;
}
return NOT_HANDLED;
}
}
INITIAL
state mS1 parent mP1 {
enter { log("mS1.enter"); }
exit { log("mS1.exit"); }
on msg {
CMD_1 {
transitionTo(mS1);
return HANDLED;
}
return NOT_HANDLED;
}
}
state mS2 parent mP1 {
enter { log("mS2.enter"); }
exit { log("mS2.exit"); }
on msg {
CMD_2 {
send(CMD_4);
return HANDLED;
}
CMD_3 {
defer(msg);
transitionTo(mP2);
return HANDLED;
}
return NOT_HANDLED;
}
}
state mP2 {
enter {
log("mP2.enter");
send(CMD_5);
}
exit { log("mP2.exit"); }
on msg {
CMD_3, CMD_4 { return HANDLED; }
CMD_5 {
transitionTo(HaltingState);
return HANDLED;
}
return NOT_HANDLED;
}
}
</code>
* <p>The implementation is below and also in StateMachineTest:</p>
<code>
class Hsm1 extends StateMachine {
public static final int CMD_1 = 1;
public static final int CMD_2 = 2;
public static final int CMD_3 = 3;
public static final int CMD_4 = 4;
public static final int CMD_5 = 5;
public static Hsm1 makeHsm1() {
log("makeHsm1 E");
Hsm1 sm = new Hsm1("hsm1");
sm.start();
log("makeHsm1 X");
return sm;
}
Hsm1(String name) {
super(name);
log("ctor E");
// Add states, use indentation to show hierarchy
addState(mP1);
addState(mS1, mP1);
addState(mS2, mP1);
addState(mP2);
// Set the initial state
setInitialState(mS1);
log("ctor X");
}
class P1 extends State {
@Override public void enter() {
log("mP1.enter");
}
@Override public boolean processMessage(Message message) {
boolean retVal;
log("mP1.processMessage what=" + message.what);
switch(message.what) {
case CMD_2:
// CMD_2 will arrive in mS2 before CMD_3
sendMessage(obtainMessage(CMD_3));
deferMessage(message);
transitionTo(mS2);
retVal = HANDLED;
break;
default:
// Any message we don't understand in this state invokes unhandledMessage
retVal = NOT_HANDLED;
break;
}
return retVal;
}
@Override public void exit() {
log("mP1.exit");
}
}
class S1 extends State {
@Override public void enter() {
log("mS1.enter");
}
@Override public boolean processMessage(Message message) {
log("S1.processMessage what=" + message.what);
if (message.what == CMD_1) {
// Transition to ourself to show that enter/exit is called
transitionTo(mS1);
return HANDLED;
} else {
// Let parent process all other messages
return NOT_HANDLED;
}
}
@Override public void exit() {
log("mS1.exit");
}
}
class S2 extends State {
@Override public void enter() {
log("mS2.enter");
}
@Override public boolean processMessage(Message message) {
boolean retVal;
log("mS2.processMessage what=" + message.what);
switch(message.what) {
case(CMD_2):
sendMessage(obtainMessage(CMD_4));
retVal = HANDLED;
break;
case(CMD_3):
deferMessage(message);
transitionTo(mP2);
retVal = HANDLED;
break;
default:
retVal = NOT_HANDLED;
break;
}
return retVal;
}
@Override public void exit() {
log("mS2.exit");
}
}
class P2 extends State {
@Override public void enter() {
log("mP2.enter");
sendMessage(obtainMessage(CMD_5));
}
@Override public boolean processMessage(Message message) {
log("P2.processMessage what=" + message.what);
switch(message.what) {
case(CMD_3):
break;
case(CMD_4):
break;
case(CMD_5):
transitionToHaltingState();
break;
}
return HANDLED;
}
@Override public void exit() {
log("mP2.exit");
}
}
@Override
void onHalting() {
log("halting");
synchronized (this) {
this.notifyAll();
}
}
P1 mP1 = new P1();
S1 mS1 = new S1();
S2 mS2 = new S2();
P2 mP2 = new P2();
}
</code>
* <p>If this is executed by sending two messages CMD_1 and CMD_2
* (Note the synchronize is only needed because we use hsm.wait())</p>
<code>
Hsm1 hsm = makeHsm1();
synchronize(hsm) {
hsm.sendMessage(obtainMessage(hsm.CMD_1));
hsm.sendMessage(obtainMessage(hsm.CMD_2));
try {
// wait for the messages to be handled
hsm.wait();
} catch (InterruptedException e) {
loge("exception while waiting " + e.getMessage());
}
}
</code>
* <p>The output is:</p>
<code>
D/hsm1 ( 1999): makeHsm1 E
D/hsm1 ( 1999): ctor E
D/hsm1 ( 1999): ctor X
D/hsm1 ( 1999): mP1.enter
D/hsm1 ( 1999): mS1.enter
D/hsm1 ( 1999): makeHsm1 X
D/hsm1 ( 1999): mS1.processMessage what=1
D/hsm1 ( 1999): mS1.exit
D/hsm1 ( 1999): mS1.enter
D/hsm1 ( 1999): mS1.processMessage what=2
D/hsm1 ( 1999): mP1.processMessage what=2
D/hsm1 ( 1999): mS1.exit
D/hsm1 ( 1999): mS2.enter
D/hsm1 ( 1999): mS2.processMessage what=2
D/hsm1 ( 1999): mS2.processMessage what=3
D/hsm1 ( 1999): mS2.exit
D/hsm1 ( 1999): mP1.exit
D/hsm1 ( 1999): mP2.enter
D/hsm1 ( 1999): mP2.processMessage what=3
D/hsm1 ( 1999): mP2.processMessage what=4
D/hsm1 ( 1999): mP2.processMessage what=5
D/hsm1 ( 1999): mP2.exit
D/hsm1 ( 1999): halting
</code>
*/
public class StateMachine {
// Name of the state machine and used as logging tag
private String mName;
/** Message.what value when quitting */
private static final int SM_QUIT_CMD = -1;
/** Message.what value when initializing */
private static final int SM_INIT_CMD = -2;
/**
* Convenience constant that maybe returned by processMessage
* to indicate the the message was processed and is not to be
* processed by parent states
*/
public static final boolean HANDLED = true;
/**
* Convenience constant that maybe returned by processMessage
* to indicate the the message was NOT processed and is to be
* processed by parent states
*/
public static final boolean NOT_HANDLED = false;
/**
* StateMachine logging record.
*/
public static class LogRec {
private StateMachine mSm;
private long mTime;
private int mWhat;
private String mInfo;
private IState mState;
private IState mOrgState;
private IState mDstState;
/**
* Constructor
*
* @param msg
* @param state the state which handled the message
* @param orgState is the first state the received the message but
* did not processes the message.
* @param transToState is the state that was transitioned to after the message was
* processed.
*/
LogRec(StateMachine sm, Message msg, String info, IState state, IState orgState,
IState transToState) {
update(sm, msg, info, state, orgState, transToState);
}
/**
* Update the information in the record.
* @param state that handled the message
* @param orgState is the first state the received the message
* @param dstState is the state that was the transition target when logging
*/
public void update(StateMachine sm, Message msg, String info, IState state, IState orgState,
IState dstState) {
mSm = sm;
mTime = System.currentTimeMillis();
mWhat = (msg != null) ? msg.what : 0;
mInfo = info;
mState = state;
mOrgState = orgState;
mDstState = dstState;
}
/**
* @return time stamp
*/
public long getTime() {
return mTime;
}
/**
* @return msg.what
*/
public long getWhat() {
return mWhat;
}
/**
* @return the command that was executing
*/
public String getInfo() {
return mInfo;
}
/**
* @return the state that handled this message
*/
public IState getState() {
return mState;
}
/**
* @return the state destination state if a transition is occurring or null if none.
*/
public IState getDestState() {
return mDstState;
}
/**
* @return the original state that received the message.
*/
public IState getOriginalState() {
return mOrgState;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("time=");
Calendar c = Calendar.getInstance();
c.setTimeInMillis(mTime);
sb.append(String.format("%tm-%td %tH:%tM:%tS.%tL", c, c, c, c, c, c));
sb.append(" processed=");
sb.append(mState == null ? "<null>" : mState.getName());
sb.append(" org=");
sb.append(mOrgState == null ? "<null>" : mOrgState.getName());
sb.append(" dest=");
sb.append(mDstState == null ? "<null>" : mDstState.getName());
sb.append(" what=");
String what = mSm != null ? mSm.getWhatToString(mWhat) : "";
if (TextUtils.isEmpty(what)) {
sb.append(mWhat);
sb.append("(0x");
sb.append(Integer.toHexString(mWhat));
sb.append(")");
} else {
sb.append(what);
}
if (!TextUtils.isEmpty(mInfo)) {
sb.append(" ");
sb.append(mInfo);
}
return sb.toString();
}
}
/**
* A list of log records including messages recently processed by the state machine.
*
* The class maintains a list of log records including messages
* recently processed. The list is finite and may be set in the
* constructor or by calling setSize. The public interface also
* includes size which returns the number of recent records,
* count which is the number of records processed since the
* the last setSize, get which returns a record and
* add which adds a record.
*/
private static class LogRecords {
private static final int DEFAULT_SIZE = 20;
private Vector<LogRec> mLogRecVector = new Vector<LogRec>();
private int mMaxSize = DEFAULT_SIZE;
private int mOldestIndex = 0;
private int mCount = 0;
private boolean mLogOnlyTransitions = false;
/**
* private constructor use add
*/
private LogRecords() {
}
/**
* Set size of messages to maintain and clears all current records.
*
* @param maxSize number of records to maintain at anyone time.
*/
synchronized void setSize(int maxSize) {
mMaxSize = maxSize;
mCount = 0;
mLogRecVector.clear();
}
synchronized void setLogOnlyTransitions(boolean enable) {
mLogOnlyTransitions = enable;
}
synchronized boolean logOnlyTransitions() {
return mLogOnlyTransitions;
}
/**
* @return the number of recent records.
*/
synchronized int size() {
return mLogRecVector.size();
}
/**
* @return the total number of records processed since size was set.
*/
synchronized int count() {
return mCount;
}
/**
* Clear the list of records.
*/
synchronized void cleanup() {
mLogRecVector.clear();
}
/**
* @return the information on a particular record. 0 is the oldest
* record and size()-1 is the newest record. If the index is to
* large null is returned.
*/
synchronized LogRec get(int index) {
int nextIndex = mOldestIndex + index;
if (nextIndex >= mMaxSize) {
nextIndex -= mMaxSize;
}
if (nextIndex >= size()) {
return null;
} else {
return mLogRecVector.get(nextIndex);
}
}
/**
* Add a processed message.
*
* @param msg
* @param messageInfo to be stored
* @param state that handled the message
* @param orgState is the first state the received the message but
* did not processes the message.
* @param transToState is the state that was transitioned to after the message was
* processed.
*
*/
synchronized void add(StateMachine sm, Message msg, String messageInfo, IState state,
IState orgState, IState transToState) {
mCount += 1;
if (mLogRecVector.size() < mMaxSize) {
mLogRecVector.add(new LogRec(sm, msg, messageInfo, state, orgState, transToState));
} else {
LogRec pmi = mLogRecVector.get(mOldestIndex);
mOldestIndex += 1;
if (mOldestIndex >= mMaxSize) {
mOldestIndex = 0;
}
pmi.update(sm, msg, messageInfo, state, orgState, transToState);
}
}
}
private static class SmHandler extends Handler {
/** true if StateMachine has quit */
private boolean mHasQuit = false;
/** The debug flag */
private boolean mDbg = false;
/** The SmHandler object, identifies that message is internal */
private static final Object mSmHandlerObj = new Object();
/** The current message */
private Message mMsg;
/** A list of log records including messages this state machine has processed */
private LogRecords mLogRecords = new LogRecords();
/** true if construction of the state machine has not been completed */
private boolean mIsConstructionCompleted;
/** Stack used to manage the current hierarchy of states */
private StateInfo mStateStack[];
/** Top of mStateStack */
private int mStateStackTopIndex = -1;
/** A temporary stack used to manage the state stack */
private StateInfo mTempStateStack[];
/** The top of the mTempStateStack */
private int mTempStateStackCount;
/** State used when state machine is halted */
private HaltingState mHaltingState = new HaltingState();
/** State used when state machine is quitting */
private QuittingState mQuittingState = new QuittingState();
/** Reference to the StateMachine */
private StateMachine mSm;
/**
* Information about a state.
* Used to maintain the hierarchy.
*/
private class StateInfo {
/** The state */
State state;
/** The parent of this state, null if there is no parent */
StateInfo parentStateInfo;
/** True when the state has been entered and on the stack */
boolean active;
/**
* Convert StateInfo to string
*/
@Override
public String toString() {
return "state=" + state.getName() + ",active=" + active + ",parent="
+ ((parentStateInfo == null) ? "null" : parentStateInfo.state.getName());
}
}
/** The map of all of the states in the state machine */
private HashMap<State, StateInfo> mStateInfo = new HashMap<State, StateInfo>();
/** The initial state that will process the first message */
private State mInitialState;
/** The destination state when transitionTo has been invoked */
private State mDestState;
/** The list of deferred messages */
private ArrayList<Message> mDeferredMessages = new ArrayList<Message>();
/**
* State entered when transitionToHaltingState is called.
*/
private class HaltingState extends State {
@Override
public boolean processMessage(Message msg) {
mSm.haltedProcessMessage(msg);
return true;
}
}
/**
* State entered when a valid quit message is handled.
*/
private class QuittingState extends State {
@Override
public boolean processMessage(Message msg) {
return NOT_HANDLED;
}
}
/**
* Handle messages sent to the state machine by calling
* the current state's processMessage. It also handles
* the enter/exit calls and placing any deferred messages
* back onto the queue when transitioning to a new state.
*/
@Override
public final void handleMessage(Message msg) {
if (!mHasQuit) {
if (mDbg) mSm.log("handleMessage: E msg.what=" + msg.what);
/** Save the current message */
mMsg = msg;
/** State that processed the message */
State msgProcessedState = null;
if (mIsConstructionCompleted) {
/** Normal path */
msgProcessedState = processMsg(msg);
} else if (!mIsConstructionCompleted && (mMsg.what == SM_INIT_CMD)
&& (mMsg.obj == mSmHandlerObj)) {
/** Initial one time path. */
mIsConstructionCompleted = true;
invokeEnterMethods(0);
} else {
throw new RuntimeException("StateMachine.handleMessage: "
+ "The start method not called, received msg: " + msg);
}
performTransitions(msgProcessedState, msg);
// We need to check if mSm == null here as we could be quitting.
if (mDbg && mSm != null) mSm.log("handleMessage: X");
}
}
/**
* Do any transitions
* @param msgProcessedState is the state that processed the message
*/
private void performTransitions(State msgProcessedState, Message msg) {
/**
* If transitionTo has been called, exit and then enter
* the appropriate states. We loop on this to allow
* enter and exit methods to use transitionTo.
*/
State orgState = mStateStack[mStateStackTopIndex].state;
/**
* Record whether message needs to be logged before we transition and
* and we won't log special messages SM_INIT_CMD or SM_QUIT_CMD which
* always set msg.obj to the handler.
*/
boolean recordLogMsg = mSm.recordLogRec(mMsg) && (msg.obj != mSmHandlerObj);
if (mLogRecords.logOnlyTransitions()) {
/** Record only if there is a transition */
if (mDestState != null) {
mLogRecords.add(mSm, mMsg, mSm.getLogRecString(mMsg), msgProcessedState,
orgState, mDestState);
}
} else if (recordLogMsg) {
/** Record message */
mLogRecords.add(mSm, mMsg, mSm.getLogRecString(mMsg), msgProcessedState, orgState,
mDestState);
}
State destState = mDestState;
if (destState != null) {
/**
* Process the transitions including transitions in the enter/exit methods
*/
while (true) {
if (mDbg) mSm.log("handleMessage: new destination call exit/enter");
/**
* Determine the states to exit and enter and return the
* common ancestor state of the enter/exit states. Then
* invoke the exit methods then the enter methods.
*/
StateInfo commonStateInfo = setupTempStateStackWithStatesToEnter(destState);
invokeExitMethods(commonStateInfo);
int stateStackEnteringIndex = moveTempStateStackToStateStack();
invokeEnterMethods(stateStackEnteringIndex);
/**
* Since we have transitioned to a new state we need to have
* any deferred messages moved to the front of the message queue
* so they will be processed before any other messages in the
* message queue.
*/
moveDeferredMessageAtFrontOfQueue();
if (destState != mDestState) {
// A new mDestState so continue looping
destState = mDestState;
} else {
// No change in mDestState so we're done
break;
}
}
mDestState = null;
}
/**
* After processing all transitions check and
* see if the last transition was to quit or halt.
*/
if (destState != null) {
if (destState == mQuittingState) {
/**
* Call onQuitting to let subclasses cleanup.
*/
mSm.onQuitting();
cleanupAfterQuitting();
} else if (destState == mHaltingState) {
/**
* Call onHalting() if we've transitioned to the halting
* state. All subsequent messages will be processed in
* in the halting state which invokes haltedProcessMessage(msg);
*/
mSm.onHalting();
}
}
}
/**
* Cleanup all the static variables and the looper after the SM has been quit.
*/
private final void cleanupAfterQuitting() {
if (mSm.mSmThread != null) {
// If we made the thread then quit looper which stops the thread.
getLooper().quit();
mSm.mSmThread = null;
}
mSm.mSmHandler = null;
mSm = null;
mMsg = null;
mLogRecords.cleanup();
mStateStack = null;
mTempStateStack = null;
mStateInfo.clear();
mInitialState = null;
mDestState = null;
mDeferredMessages.clear();
mHasQuit = true;
}
/**
* Complete the construction of the state machine.
*/
private final void completeConstruction() {
if (mDbg) mSm.log("completeConstruction: E");
/**
* Determine the maximum depth of the state hierarchy
* so we can allocate the state stacks.
*/
int maxDepth = 0;
for (StateInfo si : mStateInfo.values()) {
int depth = 0;
for (StateInfo i = si; i != null; depth++) {
i = i.parentStateInfo;
}
if (maxDepth < depth) {
maxDepth = depth;
}
}
if (mDbg) mSm.log("completeConstruction: maxDepth=" + maxDepth);
mStateStack = new StateInfo[maxDepth];
mTempStateStack = new StateInfo[maxDepth];
setupInitialStateStack();
/** Sending SM_INIT_CMD message to invoke enter methods asynchronously */
sendMessageAtFrontOfQueue(obtainMessage(SM_INIT_CMD, mSmHandlerObj));
if (mDbg) mSm.log("completeConstruction: X");
}
/**
* Process the message. If the current state doesn't handle
* it, call the states parent and so on. If it is never handled then
* call the state machines unhandledMessage method.
* @return the state that processed the message
*/
private final State processMsg(Message msg) {
StateInfo curStateInfo = mStateStack[mStateStackTopIndex];
if (mDbg) {
mSm.log("processMsg: " + curStateInfo.state.getName());
}
if (isQuit(msg)) {
transitionTo(mQuittingState);
} else {
while (!curStateInfo.state.processMessage(msg)) {
/**
* Not processed
*/
curStateInfo = curStateInfo.parentStateInfo;
if (curStateInfo == null) {
/**
* No parents left so it's not handled
*/
mSm.unhandledMessage(msg);
break;
}
if (mDbg) {
mSm.log("processMsg: " + curStateInfo.state.getName());
}
}
}
return (curStateInfo != null) ? curStateInfo.state : null;
}
/**
* Call the exit method for each state from the top of stack
* up to the common ancestor state.
*/
private final void invokeExitMethods(StateInfo commonStateInfo) {
while ((mStateStackTopIndex >= 0)
&& (mStateStack[mStateStackTopIndex] != commonStateInfo)) {
State curState = mStateStack[mStateStackTopIndex].state;
if (mDbg) mSm.log("invokeExitMethods: " + curState.getName());
curState.exit();
mStateStack[mStateStackTopIndex].active = false;
mStateStackTopIndex -= 1;
}
}
/**
* Invoke the enter method starting at the entering index to top of state stack
*/
private final void invokeEnterMethods(int stateStackEnteringIndex) {
for (int i = stateStackEnteringIndex; i <= mStateStackTopIndex; i++) {
if (mDbg) mSm.log("invokeEnterMethods: " + mStateStack[i].state.getName());
mStateStack[i].state.enter();
mStateStack[i].active = true;
}
}
/**
* Move the deferred message to the front of the message queue.
*/
private final void moveDeferredMessageAtFrontOfQueue() {
/**
* The oldest messages on the deferred list must be at
* the front of the queue so start at the back, which
* as the most resent message and end with the oldest
* messages at the front of the queue.
*/
for (int i = mDeferredMessages.size() - 1; i >= 0; i--) {
Message curMsg = mDeferredMessages.get(i);
if (mDbg) mSm.log("moveDeferredMessageAtFrontOfQueue; what=" + curMsg.what);
sendMessageAtFrontOfQueue(curMsg);
}
mDeferredMessages.clear();
}
/**
* Move the contents of the temporary stack to the state stack
* reversing the order of the items on the temporary stack as
* they are moved.
*
* @return index into mStateStack where entering needs to start
*/
private final int moveTempStateStackToStateStack() {
int startingIndex = mStateStackTopIndex + 1;
int i = mTempStateStackCount - 1;
int j = startingIndex;
while (i >= 0) {
if (mDbg) mSm.log("moveTempStackToStateStack: i=" + i + ",j=" + j);
mStateStack[j] = mTempStateStack[i];
j += 1;
i -= 1;
}
mStateStackTopIndex = j - 1;
if (mDbg) {
mSm.log("moveTempStackToStateStack: X mStateStackTop=" + mStateStackTopIndex
+ ",startingIndex=" + startingIndex + ",Top="
+ mStateStack[mStateStackTopIndex].state.getName());
}
return startingIndex;
}
/**
* Setup the mTempStateStack with the states we are going to enter.
*
* This is found by searching up the destState's ancestors for a
* state that is already active i.e. StateInfo.active == true.
* The destStae and all of its inactive parents will be on the
* TempStateStack as the list of states to enter.
*
* @return StateInfo of the common ancestor for the destState and
* current state or null if there is no common parent.
*/
private final StateInfo setupTempStateStackWithStatesToEnter(State destState) {
/**
* Search up the parent list of the destination state for an active
* state. Use a do while() loop as the destState must always be entered
* even if it is active. This can happen if we are exiting/entering
* the current state.
*/
mTempStateStackCount = 0;
StateInfo curStateInfo = mStateInfo.get(destState);
do {
mTempStateStack[mTempStateStackCount++] = curStateInfo;
curStateInfo = curStateInfo.parentStateInfo;
} while ((curStateInfo != null) && !curStateInfo.active);
if (mDbg) {
mSm.log("setupTempStateStackWithStatesToEnter: X mTempStateStackCount="
+ mTempStateStackCount + ",curStateInfo: " + curStateInfo);
}
return curStateInfo;
}
/**
* Initialize StateStack to mInitialState.
*/
private final void setupInitialStateStack() {
if (mDbg) {
mSm.log("setupInitialStateStack: E mInitialState=" + mInitialState.getName());
}
StateInfo curStateInfo = mStateInfo.get(mInitialState);
for (mTempStateStackCount = 0; curStateInfo != null; mTempStateStackCount++) {
mTempStateStack[mTempStateStackCount] = curStateInfo;
curStateInfo = curStateInfo.parentStateInfo;
}
// Empty the StateStack
mStateStackTopIndex = -1;
moveTempStateStackToStateStack();
}
/**
* @return current message
*/
private final Message getCurrentMessage() {
return mMsg;
}
/**
* @return current state
*/
private final IState getCurrentState() {
return mStateStack[mStateStackTopIndex].state;
}
/**
* Add a new state to the state machine. Bottom up addition
* of states is allowed but the same state may only exist
* in one hierarchy.
*
* @param state the state to add
* @param parent the parent of state
* @return stateInfo for this state
*/
private final StateInfo addState(State state, State parent) {
if (mDbg) {
mSm.log("addStateInternal: E state=" + state.getName() + ",parent="
+ ((parent == null) ? "" : parent.getName()));
}
StateInfo parentStateInfo = null;
if (parent != null) {
parentStateInfo = mStateInfo.get(parent);
if (parentStateInfo == null) {
// Recursively add our parent as it's not been added yet.
parentStateInfo = addState(parent, null);
}
}
StateInfo stateInfo = mStateInfo.get(state);
if (stateInfo == null) {
stateInfo = new StateInfo();
mStateInfo.put(state, stateInfo);
}
// Validate that we aren't adding the same state in two different hierarchies.
if ((stateInfo.parentStateInfo != null)
&& (stateInfo.parentStateInfo != parentStateInfo)) {
throw new RuntimeException("state already added");
}
stateInfo.state = state;
stateInfo.parentStateInfo = parentStateInfo;
stateInfo.active = false;
if (mDbg) mSm.log("addStateInternal: X stateInfo: " + stateInfo);
return stateInfo;
}
/**
* Constructor
*
* @param looper for dispatching messages
* @param sm the hierarchical state machine
*/
private SmHandler(Looper looper, StateMachine sm) {
super(looper);
mSm = sm;
addState(mHaltingState, null);
addState(mQuittingState, null);
}
/** @see StateMachine#setInitialState(State) */
private final void setInitialState(State initialState) {
if (mDbg) mSm.log("setInitialState: initialState=" + initialState.getName());
mInitialState = initialState;
}
/** @see StateMachine#transitionTo(IState) */
private final void transitionTo(IState destState) {
mDestState = (State) destState;
if (mDbg) mSm.log("transitionTo: destState=" + mDestState.getName());
}
/** @see StateMachine#deferMessage(Message) */
private final void deferMessage(Message msg) {
if (mDbg) mSm.log("deferMessage: msg=" + msg.what);
/* Copy the "msg" to "newMsg" as "msg" will be recycled */
Message newMsg = obtainMessage();
newMsg.copyFrom(msg);
mDeferredMessages.add(newMsg);
}
/** @see StateMachine#quit() */
private final void quit() {
if (mDbg) mSm.log("quit:");
sendMessage(obtainMessage(SM_QUIT_CMD, mSmHandlerObj));
}
/** @see StateMachine#quitNow() */
private final void quitNow() {
if (mDbg) mSm.log("quitNow:");
sendMessageAtFrontOfQueue(obtainMessage(SM_QUIT_CMD, mSmHandlerObj));
}
/** Validate that the message was sent by quit or quitNow. */
private final boolean isQuit(Message msg) {
return (msg.what == SM_QUIT_CMD) && (msg.obj == mSmHandlerObj);
}
/** @see StateMachine#isDbg() */
private final boolean isDbg() {
return mDbg;
}
/** @see StateMachine#setDbg(boolean) */
private final void setDbg(boolean dbg) {
mDbg = dbg;
}
}
private SmHandler mSmHandler;
private HandlerThread mSmThread;
/**
* Initialize.
*
* @param looper for this state machine
* @param name of the state machine
*/
private void initStateMachine(String name, Looper looper) {
mName = name;
mSmHandler = new SmHandler(looper, this);
}
/**
* Constructor creates a StateMachine with its own thread.
*
* @param name of the state machine
*/
protected StateMachine(String name) {
mSmThread = new HandlerThread(name);
mSmThread.start();
Looper looper = mSmThread.getLooper();
initStateMachine(name, looper);
}
/**
* Constructor creates a StateMachine using the looper.
*
* @param name of the state machine
*/
protected StateMachine(String name, Looper looper) {
initStateMachine(name, looper);
}
/**
* Constructor creates a StateMachine using the handler.
*
* @param name of the state machine
*/
protected StateMachine(String name, Handler handler) {
initStateMachine(name, handler.getLooper());
}
/**
* Add a new state to the state machine
* @param state the state to add
* @param parent the parent of state
*/
protected final void addState(State state, State parent) {
mSmHandler.addState(state, parent);
}
/**
* Add a new state to the state machine, parent will be null
* @param state to add
*/
protected final void addState(State state) {
mSmHandler.addState(state, null);
}
/**
* Set the initial state. This must be invoked before
* and messages are sent to the state machine.
*
* @param initialState is the state which will receive the first message.
*/
protected final void setInitialState(State initialState) {
mSmHandler.setInitialState(initialState);
}
/**
* @return current message
*/
protected final Message getCurrentMessage() {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return null;
return smh.getCurrentMessage();
}
/**
* @return current state
*/
protected final IState getCurrentState() {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return null;
return smh.getCurrentState();
}
/**
* transition to destination state. Upon returning
* from processMessage the current state's exit will
* be executed and upon the next message arriving
* destState.enter will be invoked.
*
* this function can also be called inside the enter function of the
* previous transition target, but the behavior is undefined when it is
* called mid-way through a previous transition (for example, calling this
* in the enter() routine of a intermediate node when the current transition
* target is one of the nodes descendants).
*
* @param destState will be the state that receives the next message.
*/
protected final void transitionTo(IState destState) {
mSmHandler.transitionTo(destState);
}
/**
* transition to halt state. Upon returning
* from processMessage we will exit all current
* states, execute the onHalting() method and then
* for all subsequent messages haltedProcessMessage
* will be called.
*/
protected final void transitionToHaltingState() {
mSmHandler.transitionTo(mSmHandler.mHaltingState);
}
/**
* Defer this message until next state transition.
* Upon transitioning all deferred messages will be
* placed on the queue and reprocessed in the original
* order. (i.e. The next state the oldest messages will
* be processed first)
*
* @param msg is deferred until the next transition.
*/
protected final void deferMessage(Message msg) {
mSmHandler.deferMessage(msg);
}
/**
* Called when message wasn't handled
*
* @param msg that couldn't be handled.
*/
protected void unhandledMessage(Message msg) {
if (mSmHandler.mDbg) loge(" - unhandledMessage: msg.what=" + msg.what);
}
/**
* Called for any message that is received after
* transitionToHalting is called.
*/
protected void haltedProcessMessage(Message msg) {
}
/**
* This will be called once after handling a message that called
* transitionToHalting. All subsequent messages will invoke
* {@link StateMachine#haltedProcessMessage(Message)}
*/
protected void onHalting() {
}
/**
* This will be called once after a quit message that was NOT handled by
* the derived StateMachine. The StateMachine will stop and any subsequent messages will be
* ignored. In addition, if this StateMachine created the thread, the thread will
* be stopped after this method returns.
*/
protected void onQuitting() {
}
/**
* @return the name
*/
public final String getName() {
return mName;
}
/**
* Set number of log records to maintain and clears all current records.
*
* @param maxSize number of messages to maintain at anyone time.
*/
public final void setLogRecSize(int maxSize) {
mSmHandler.mLogRecords.setSize(maxSize);
}
/**
* Set to log only messages that cause a state transition
*
* @param enable {@code true} to enable, {@code false} to disable
*/
public final void setLogOnlyTransitions(boolean enable) {
mSmHandler.mLogRecords.setLogOnlyTransitions(enable);
}
/**
* @return number of log records
*/
public final int getLogRecSize() {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return 0;
return smh.mLogRecords.size();
}
/**
* @return the total number of records processed
*/
public final int getLogRecCount() {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return 0;
return smh.mLogRecords.count();
}
/**
* @return a log record, or null if index is out of range
*/
public final LogRec getLogRec(int index) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return null;
return smh.mLogRecords.get(index);
}
/**
* @return a copy of LogRecs as a collection
*/
public final Collection<LogRec> copyLogRecs() {
Vector<LogRec> vlr = new Vector<LogRec>();
SmHandler smh = mSmHandler;
if (smh != null) {
for (LogRec lr : smh.mLogRecords.mLogRecVector) {
vlr.add(lr);
}
}
return vlr;
}
/**
* Add the string to LogRecords.
*
* @param string
*/
protected void addLogRec(String string) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.mLogRecords.add(this, smh.getCurrentMessage(), string, smh.getCurrentState(),
smh.mStateStack[smh.mStateStackTopIndex].state, smh.mDestState);
}
/**
* @return true if msg should be saved in the log, default is true.
*/
protected boolean recordLogRec(Message msg) {
return true;
}
/**
* Return a string to be logged by LogRec, default
* is an empty string. Override if additional information is desired.
*
* @param msg that was processed
* @return information to be logged as a String
*/
protected String getLogRecString(Message msg) {
return "";
}
/**
* @return the string for msg.what
*/
protected String getWhatToString(int what) {
return null;
}
/**
* @return Handler, maybe null if state machine has quit.
*/
public final Handler getHandler() {
return mSmHandler;
}
/**
* Get a message and set Message.target state machine handler.
*
* Note: The handler can be null if the state machine has quit,
* which means target will be null and may cause a AndroidRuntimeException
* in MessageQueue#enqueMessage if sent directly or if sent using
* StateMachine#sendMessage the message will just be ignored.
*
* @return A Message object from the global pool
*/
public final Message obtainMessage() {
return Message.obtain(mSmHandler);
}
/**
* Get a message and set Message.target state machine handler, what.
*
* Note: The handler can be null if the state machine has quit,
* which means target will be null and may cause a AndroidRuntimeException
* in MessageQueue#enqueMessage if sent directly or if sent using
* StateMachine#sendMessage the message will just be ignored.
*
* @param what is the assigned to Message.what.
* @return A Message object from the global pool
*/
public final Message obtainMessage(int what) {
return Message.obtain(mSmHandler, what);
}
/**
* Get a message and set Message.target state machine handler,
* what and obj.
*
* Note: The handler can be null if the state machine has quit,
* which means target will be null and may cause a AndroidRuntimeException
* in MessageQueue#enqueMessage if sent directly or if sent using
* StateMachine#sendMessage the message will just be ignored.
*
* @param what is the assigned to Message.what.
* @param obj is assigned to Message.obj.
* @return A Message object from the global pool
*/
public final Message obtainMessage(int what, Object obj) {
return Message.obtain(mSmHandler, what, obj);
}
/**
* Get a message and set Message.target state machine handler,
* what, arg1 and arg2
*
* Note: The handler can be null if the state machine has quit,
* which means target will be null and may cause a AndroidRuntimeException
* in MessageQueue#enqueMessage if sent directly or if sent using
* StateMachine#sendMessage the message will just be ignored.
*
* @param what is assigned to Message.what
* @param arg1 is assigned to Message.arg1
* @return A Message object from the global pool
*/
public final Message obtainMessage(int what, int arg1) {
// use this obtain so we don't match the obtain(h, what, Object) method
return Message.obtain(mSmHandler, what, arg1, 0);
}
/**
* Get a message and set Message.target state machine handler,
* what, arg1 and arg2
*
* Note: The handler can be null if the state machine has quit,
* which means target will be null and may cause a AndroidRuntimeException
* in MessageQueue#enqueMessage if sent directly or if sent using
* StateMachine#sendMessage the message will just be ignored.
*
* @param what is assigned to Message.what
* @param arg1 is assigned to Message.arg1
* @param arg2 is assigned to Message.arg2
* @return A Message object from the global pool
*/
public final Message obtainMessage(int what, int arg1, int arg2) {
return Message.obtain(mSmHandler, what, arg1, arg2);
}
/**
* Get a message and set Message.target state machine handler,
* what, arg1, arg2 and obj
*
* Note: The handler can be null if the state machine has quit,
* which means target will be null and may cause a AndroidRuntimeException
* in MessageQueue#enqueMessage if sent directly or if sent using
* StateMachine#sendMessage the message will just be ignored.
*
* @param what is assigned to Message.what
* @param arg1 is assigned to Message.arg1
* @param arg2 is assigned to Message.arg2
* @param obj is assigned to Message.obj
* @return A Message object from the global pool
*/
public final Message obtainMessage(int what, int arg1, int arg2, Object obj) {
return Message.obtain(mSmHandler, what, arg1, arg2, obj);
}
/**
* Enqueue a message to this state machine.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessage(int what) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessage(obtainMessage(what));
}
/**
* Enqueue a message to this state machine.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessage(int what, Object obj) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessage(obtainMessage(what, obj));
}
/**
* Enqueue a message to this state machine.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessage(int what, int arg1) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessage(obtainMessage(what, arg1));
}
/**
* Enqueue a message to this state machine.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessage(int what, int arg1, int arg2) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessage(obtainMessage(what, arg1, arg2));
}
/**
* Enqueue a message to this state machine.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessage(int what, int arg1, int arg2, Object obj) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessage(obtainMessage(what, arg1, arg2, obj));
}
/**
* Enqueue a message to this state machine.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessage(Message msg) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessage(msg);
}
/**
* Enqueue a message to this state machine after a delay.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessageDelayed(int what, long delayMillis) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageDelayed(obtainMessage(what), delayMillis);
}
/**
* Enqueue a message to this state machine after a delay.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessageDelayed(int what, Object obj, long delayMillis) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageDelayed(obtainMessage(what, obj), delayMillis);
}
/**
* Enqueue a message to this state machine after a delay.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessageDelayed(int what, int arg1, long delayMillis) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageDelayed(obtainMessage(what, arg1), delayMillis);
}
/**
* Enqueue a message to this state machine after a delay.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessageDelayed(int what, int arg1, int arg2, long delayMillis) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageDelayed(obtainMessage(what, arg1, arg2), delayMillis);
}
/**
* Enqueue a message to this state machine after a delay.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessageDelayed(int what, int arg1, int arg2, Object obj,
long delayMillis) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageDelayed(obtainMessage(what, arg1, arg2, obj), delayMillis);
}
/**
* Enqueue a message to this state machine after a delay.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessageDelayed(Message msg, long delayMillis) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageDelayed(msg, delayMillis);
}
/**
* Enqueue a message to the front of the queue for this state machine.
* Protected, may only be called by instances of StateMachine.
*
* Message is ignored if state machine has quit.
*/
protected final void sendMessageAtFrontOfQueue(int what) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageAtFrontOfQueue(obtainMessage(what));
}
/**
* Enqueue a message to the front of the queue for this state machine.
* Protected, may only be called by instances of StateMachine.
*
* Message is ignored if state machine has quit.
*/
protected final void sendMessageAtFrontOfQueue(int what, Object obj) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageAtFrontOfQueue(obtainMessage(what, obj));
}
/**
* Enqueue a message to the front of the queue for this state machine.
* Protected, may only be called by instances of StateMachine.
*
* Message is ignored if state machine has quit.
*/
protected final void sendMessageAtFrontOfQueue(int what, int arg1) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageAtFrontOfQueue(obtainMessage(what, arg1));
}
/**
* Enqueue a message to the front of the queue for this state machine.
* Protected, may only be called by instances of StateMachine.
*
* Message is ignored if state machine has quit.
*/
protected final void sendMessageAtFrontOfQueue(int what, int arg1, int arg2) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageAtFrontOfQueue(obtainMessage(what, arg1, arg2));
}
/**
* Enqueue a message to the front of the queue for this state machine.
* Protected, may only be called by instances of StateMachine.
*
* Message is ignored if state machine has quit.
*/
protected final void sendMessageAtFrontOfQueue(int what, int arg1, int arg2, Object obj) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageAtFrontOfQueue(obtainMessage(what, arg1, arg2, obj));
}
/**
* Enqueue a message to the front of the queue for this state machine.
* Protected, may only be called by instances of StateMachine.
*
* Message is ignored if state machine has quit.
*/
protected final void sendMessageAtFrontOfQueue(Message msg) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageAtFrontOfQueue(msg);
}
/**
* Removes a message from the message queue.
* Protected, may only be called by instances of StateMachine.
*/
protected final void removeMessages(int what) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.removeMessages(what);
}
/**
* Validate that the message was sent by
* {@link StateMachine#quit} or {@link StateMachine#quitNow}.
* */
protected final boolean isQuit(Message msg) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return msg.what == SM_QUIT_CMD;
return smh.isQuit(msg);
}
/**
* Quit the state machine after all currently queued up messages are processed.
*/
protected final void quit() {
// mSmHandler can be null if the state machine is already stopped.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.quit();
}
/**
* Quit the state machine immediately all currently queued messages will be discarded.
*/
protected final void quitNow() {
// mSmHandler can be null if the state machine is already stopped.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.quitNow();
}
/**
* @return if debugging is enabled
*/
public boolean isDbg() {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return false;
return smh.isDbg();
}
/**
* Set debug enable/disabled.
*
* @param dbg is true to enable debugging.
*/
public void setDbg(boolean dbg) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.setDbg(dbg);
}
/**
* Start the state machine.
*/
public void start() {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
/** Send the complete construction message */
smh.completeConstruction();
}
/**
* Dump the current state.
*
* @param fd
* @param pw
* @param args
*/
public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
pw.println(getName() + ":");
pw.println(" total records=" + getLogRecCount());
for (int i = 0; i < getLogRecSize(); i++) {
pw.printf(" rec[%d]: %s\n", i, getLogRec(i).toString());
pw.flush();
}
pw.println("curState=" + getCurrentState().getName());
}
/**
* Log with debug and add to the LogRecords.
*
* @param s is string log
*/
protected void logAndAddLogRec(String s) {
addLogRec(s);
log(s);
}
/**
* Log with debug
*
* @param s is string log
*/
protected void log(String s) {
Log.d(mName, s);
}
/**
* Log with debug attribute
*
* @param s is string log
*/
protected void logd(String s) {
Log.d(mName, s);
}
/**
* Log with verbose attribute
*
* @param s is string log
*/
protected void logv(String s) {
Log.v(mName, s);
}
/**
* Log with info attribute
*
* @param s is string log
*/
protected void logi(String s) {
Log.i(mName, s);
}
/**
* Log with warning attribute
*
* @param s is string log
*/
protected void logw(String s) {
Log.w(mName, s);
}
/**
* Log with error attribute
*
* @param s is string log
*/
protected void loge(String s) {
Log.e(mName, s);
}
/**
* Log with error attribute
*
* @param s is string log
* @param e is a Throwable which logs additional information.
*/
protected void loge(String s, Throwable e) {
Log.e(mName, s, e);
}
}
| hdodenhof/AndroidStateMachine | library/src/main/java/de/hdodenhof/androidstatemachine/StateMachine.java | Java | apache-2.0 | 68,024 |
/*
* Camunda BPM REST API
* OpenApi Spec for Camunda BPM REST API.
*
* The version of the OpenAPI document: 7.13.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.camunda.consulting.openapi.client.model;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
/**
* Model tests for MissingAuthorizationDto
*/
public class MissingAuthorizationDtoTest {
private final MissingAuthorizationDto model = new MissingAuthorizationDto();
/**
* Model tests for MissingAuthorizationDto
*/
@Test
public void testMissingAuthorizationDto() {
// TODO: test MissingAuthorizationDto
}
/**
* Test the property 'permissionName'
*/
@Test
public void permissionNameTest() {
// TODO: test permissionName
}
/**
* Test the property 'resourceName'
*/
@Test
public void resourceNameTest() {
// TODO: test resourceName
}
/**
* Test the property 'resourceId'
*/
@Test
public void resourceIdTest() {
// TODO: test resourceId
}
}
| camunda/camunda-consulting | snippets/camunda-openapi-client/camunda-openapi-client/src/test/java/com/camunda/consulting/openapi/client/model/MissingAuthorizationDtoTest.java | Java | apache-2.0 | 1,545 |
package th.ac.kmitl.ce.ooad.cest.repository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import th.ac.kmitl.ce.ooad.cest.domain.Course;
import th.ac.kmitl.ce.ooad.cest.domain.Faculty;
import java.util.List;
public interface CourseRepository extends CrudRepository<Course, Long>{
Course findFirstByCourseId(String courseId);
Course findFirstByCourseName(String courseName);
List<Course> findByCourseNameContainingOrCourseIdContainingOrderByCourseNameAsc(String courseName, String courseId);
List<Course> findByFacultyOrderByCourseNameAsc(Faculty faculty);
List<Course> findByDepartmentOrderByCourseNameAsc(String department);
@Query("select c from Course c where c.department = ?2 or c.department = '' and c.faculty = ?1 order by c.courseName")
List<Course> findByFacultyAndDepartmentOrNone(Faculty faculty, String department);
}
| CE-KMITL-OOAD-2015/CE-SMART-TRACKER-DEV | CE Smart Tracker Server/src/main/java/th/ac/kmitl/ce/ooad/cest/repository/CourseRepository.java | Java | apache-2.0 | 930 |
package org.apache.lucene.facet.sampling;
import java.io.IOException;
import java.util.Collections;
import org.apache.lucene.document.Document;
import org.apache.lucene.facet.FacetTestCase;
import org.apache.lucene.facet.index.FacetFields;
import org.apache.lucene.facet.params.FacetIndexingParams;
import org.apache.lucene.facet.params.FacetSearchParams;
import org.apache.lucene.facet.sampling.RandomSampler;
import org.apache.lucene.facet.sampling.Sampler;
import org.apache.lucene.facet.sampling.SamplingAccumulator;
import org.apache.lucene.facet.sampling.SamplingParams;
import org.apache.lucene.facet.search.CountFacetRequest;
import org.apache.lucene.facet.search.FacetRequest;
import org.apache.lucene.facet.search.FacetResult;
import org.apache.lucene.facet.search.FacetResultNode;
import org.apache.lucene.facet.search.FacetsCollector;
import org.apache.lucene.facet.search.StandardFacetsAccumulator;
import org.apache.lucene.facet.search.FacetRequest.ResultMode;
import org.apache.lucene.facet.taxonomy.CategoryPath;
import org.apache.lucene.facet.taxonomy.TaxonomyReader;
import org.apache.lucene.facet.taxonomy.TaxonomyWriter;
import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyReader;
import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyWriter;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.IOUtils;
import org.junit.Test;
/*
* 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.
*/
public class OversampleWithDepthTest extends FacetTestCase {
@Test
public void testCountWithdepthUsingSampling() throws Exception, IOException {
Directory indexDir = newDirectory();
Directory taxoDir = newDirectory();
FacetIndexingParams fip = new FacetIndexingParams(randomCategoryListParams());
// index 100 docs, each with one category: ["root", docnum/10, docnum]
// e.g. root/8/87
index100Docs(indexDir, taxoDir, fip);
DirectoryReader r = DirectoryReader.open(indexDir);
TaxonomyReader tr = new DirectoryTaxonomyReader(taxoDir);
CountFacetRequest facetRequest = new CountFacetRequest(new CategoryPath("root"), 10);
// Setting the depth to '2', should potentially get all categories
facetRequest.setDepth(2);
facetRequest.setResultMode(ResultMode.PER_NODE_IN_TREE);
FacetSearchParams fsp = new FacetSearchParams(fip, facetRequest);
// Craft sampling params to enforce sampling
final SamplingParams params = new SamplingParams();
params.setMinSampleSize(2);
params.setMaxSampleSize(50);
params.setOversampleFactor(5);
params.setSamplingThreshold(60);
params.setSampleRatio(0.1);
FacetResult res = searchWithFacets(r, tr, fsp, params);
FacetRequest req = res.getFacetRequest();
assertEquals(facetRequest, req);
FacetResultNode rootNode = res.getFacetResultNode();
// Each node below root should also have sub-results as the requested depth was '2'
for (FacetResultNode node : rootNode.subResults) {
assertTrue("node " + node.label + " should have had children as the requested depth was '2'", node.subResults.size() > 0);
}
IOUtils.close(r, tr, indexDir, taxoDir);
}
private void index100Docs(Directory indexDir, Directory taxoDir, FacetIndexingParams fip) throws IOException {
IndexWriterConfig iwc = newIndexWriterConfig(TEST_VERSION_CURRENT, null);
IndexWriter w = new IndexWriter(indexDir, iwc);
TaxonomyWriter tw = new DirectoryTaxonomyWriter(taxoDir);
FacetFields facetFields = new FacetFields(tw, fip);
for (int i = 0; i < 100; i++) {
Document doc = new Document();
CategoryPath cp = new CategoryPath("root",Integer.toString(i / 10), Integer.toString(i));
facetFields.addFields(doc, Collections.singletonList(cp));
w.addDocument(doc);
}
IOUtils.close(tw, w);
}
/** search reader <code>r</code>*/
private FacetResult searchWithFacets(IndexReader r, TaxonomyReader tr, FacetSearchParams fsp,
final SamplingParams params) throws IOException {
// a FacetsCollector with a sampling accumulator
Sampler sampler = new RandomSampler(params, random());
StandardFacetsAccumulator sfa = new SamplingAccumulator(sampler, fsp, r, tr);
FacetsCollector fcWithSampling = FacetsCollector.create(sfa);
IndexSearcher s = new IndexSearcher(r);
s.search(new MatchAllDocsQuery(), fcWithSampling);
// there's only one expected result, return just it.
return fcWithSampling.getFacetResults().get(0);
}
}
| pkarmstr/NYBC | solr-4.2.1/lucene/facet/src/test/org/apache/lucene/facet/sampling/OversampleWithDepthTest.java | Java | apache-2.0 | 5,565 |
/*
* Licensed to GraphHopper GmbH under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* GraphHopper GmbH 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 com.graphhopper.jsprit.core.util;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import com.graphhopper.jsprit.core.algorithm.listener.AlgorithmEndsListener;
import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem;
import com.graphhopper.jsprit.core.problem.job.Job;
import com.graphhopper.jsprit.core.problem.solution.VehicleRoutingProblemSolution;
import com.graphhopper.jsprit.core.problem.solution.route.VehicleRoute;
public class SolutionVerifier implements AlgorithmEndsListener {
@Override
public void informAlgorithmEnds(VehicleRoutingProblem problem, Collection<VehicleRoutingProblemSolution> solutions) {
for (VehicleRoutingProblemSolution solution : solutions) {
Set<Job> jobsInSolution = new HashSet<Job>();
for (VehicleRoute route : solution.getRoutes()) {
jobsInSolution.addAll(route.getTourActivities().getJobs());
}
if (jobsInSolution.size() != problem.getJobs().size()) {
throw new IllegalStateException("we are at the end of the algorithm and still have not found a valid solution." +
"This cannot be.");
}
}
}
}
| balage1551/jsprit | jsprit-core/src/main/java/com/graphhopper/jsprit/core/util/SolutionVerifier.java | Java | apache-2.0 | 2,020 |
package jp.ac.keio.bio.fun.xitosbml.image;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import ij.ImagePlus;
import ij.ImageStack;
import ij.process.ByteProcessor;
/**
* The class Filler, which provides several morphological operations for filling holes in the image.
* Date Created: Feb 21, 2017
*
* @author Kaito Ii <[email protected]>
* @author Akira Funahashi <[email protected]>
*/
public class Filler {
/** The ImageJ image object. */
private ImagePlus image;
/** The width of an image. */
private int width;
/** The height of an image. */
private int height;
/** The depth of an image. */
private int depth;
/** The width of an image including padding. */
private int lwidth;
/** The height of an image including padding. */
private int lheight;
/** The depth of an image including padding. */
private int ldepth;
/** The mask which stores the label of each pixel. */
private int[] mask;
/**
* The hashmap of pixel value. <labelnumber, pixel value>.
* The domain which has pixel value = 0 will have a label = 1.
*/
private HashMap<Integer, Byte> hashPix = new HashMap<Integer, Byte>(); // label number, pixel value
/** The raw data (1D byte array) of the image. */
private byte[] pixels;
/** The raw data (1D int array) of inverted the image. */
private int[] invert;
/**
* Fill a hole in the given image (ImagePlus object) by morphology operation,
* and returns the filled image.
*
* @param image the ImageJ image object
* @return the filled ImageJ image (ImagePlus) object
*/
public ImagePlus fill(ImagePlus image){
this.width = image.getWidth();
this.height = image.getHeight();
this.depth = image.getStackSize();
this.image = image;
pixels = ImgProcessUtil.copyMat(image);
invertMat();
label();
if (checkHole()) {
while (checkHole()) {
fillHole();
hashPix.clear();
label();
}
ImageStack stack = createStack();
image.setStack(stack);
image.updateImage();
}
return image;
}
/**
* Fill a hole in the given image ({@link SpatialImage} object) by morphology operation,
* and returns the filled image as ImageJ image object.
*
* @param spImg the SpatialImage object
* @return the filled ImageJ image (ImagePlus) object
*/
public ImagePlus fill(SpatialImage spImg){
this.width = spImg.getWidth();
this.height = spImg.getHeight();
this.depth = spImg.getDepth();
this.image = spImg.getImage();
this.pixels = spImg.getRaw();
invertMat();
label();
if(checkHole()){
while(checkHole()){
fillHole();
hashPix.clear();
label();
}
ImageStack stack = createStack();
image.setStack(stack);
image.updateImage();
}
return image;
}
/**
* Creates the stack of images from raw data (1D array) of image (pixels[]),
* and returns the stack of images.
*
* @return the stack of images
*/
private ImageStack createStack(){
ImageStack altimage = new ImageStack(width, height);
for(int d = 0 ; d < depth ; d++){
byte[] matrix = new byte[width * height];
System.arraycopy(pixels, d * height * width, matrix, 0, matrix.length);
altimage.addSlice(new ByteProcessor(width,height,matrix,null));
}
return altimage;
}
/**
* Create an inverted 1D array of an image (invert[]) from 1D array of an image (pixels[]).
* Each pixel value will be inverted (0 -> 1, otherwise -> 0). For example, the Black and White
* binary image will be converted to a White and Black binary image.
*/
private void invertMat(){
lwidth = width + 2;
lheight = height + 2;
if(depth < 3) ldepth = depth;
else ldepth = depth + 2;
invert = new int[lwidth * lheight * ldepth];
mask = new int[lwidth * lheight * ldepth];
if (ldepth > depth) { // 3D image
for (int d = 0; d < ldepth; d++) {
for (int h = 0; h < lheight; h++) {
for (int w = 0; w < lwidth; w++) {
if (d == 0 || d == ldepth - 1 || h == 0 || h == lheight - 1 || w == 0 || w == lwidth - 1) {
invert[d * lheight * lwidth + h * lwidth + w] = 1;
mask[d * lheight * lwidth + h * lwidth + w] = 1;
continue;
}
if (pixels[(d - 1) * height * width + (h - 1) * width + w - 1] == 0)
invert[d * lheight * lwidth + h * lwidth + w] = 1;
else
invert[d * lheight * lwidth + h * lwidth + w] = 0;
}
}
}
} else { // 2D image
for (int d = 0; d < ldepth; d++) {
for (int h = 0; h < lheight; h++) {
for (int w = 0; w < lwidth; w++) {
if(h == 0 || h == lheight - 1 || w == 0 || w == lwidth - 1){
invert[d * lheight * lwidth + h * lwidth + w] = 1;
mask[d * lheight * lwidth + h * lwidth + w] = 1;
continue;
}
if (pixels[d * height * width + (h - 1) * width + w - 1] == 0)
invert[d * lheight * lwidth + h * lwidth + w] = 1;
else
invert[d * lheight * lwidth + h * lwidth + w] = 0;
}
}
}
}
}
/** The label count. */
private int labelCount;
/**
* Assign a label (label number) to each pixel.
* The label number will be stored in mask[] array.
* The domain which has pixel value = 0 will have a label = 1.
*/
public void label(){
hashPix.put(1, (byte)0);
labelCount = 2;
if (ldepth > depth) {
for (int d = 1; d < ldepth - 1; d++) {
for (int h = 1; h < lheight - 1; h++) {
for (int w = 1; w < lwidth - 1; w++) {
if (invert[d * lheight * lwidth + h * lwidth + w] == 1 && pixels[(d-1) * height * width + (h-1) * width + w - 1] == 0) {
mask[d * lheight * lwidth + h * lwidth + w] = setLabel(w, h, d, pixels[(d-1) * height * width + (h-1) * width + w - 1]);
}else{
mask[d * lheight * lwidth + h * lwidth + w] = setbackLabel(w, h, d, pixels[(d-1) * height * width + (h-1) * width + w - 1]);
}
}
}
}
}else{
for (int d = 0; d < ldepth; d++) {
for (int h = 1; h < lheight - 1; h++) {
for (int w = 1; w < lwidth - 1; w++) {
if (invert[d * lheight * lwidth + h * lwidth + w] == 1 && pixels[d * height * width + (h-1) * width + w - 1] == 0) {
mask[d * lheight * lwidth + h * lwidth + w] = setLabel(w, h, d, pixels[d * height * width + (h-1) * width + w - 1]);
}else{
mask[d * lheight * lwidth + h * lwidth + w] = setbackLabel(w, h, d, pixels[d * height * width + (h-1) * width + w - 1]);
}
}
}
}
}
}
/**
* Check whether a hole exists in the hashmap of pixels (HashMap<label number, pixel value>).
*
* @return true, if a hole exists
*/
public boolean checkHole(){
if(Collections.frequency(hashPix.values(), (byte) 0) > 1)
return true;
else
return false;
}
/**
* Fill a hole in the hashmap of pixels (HashMap<label number, pixel value> by morphology operation.
* The fill operation will be applied to each domain (which has unique label number).
*/
public void fillHole(){
for(Entry<Integer, Byte> e : hashPix.entrySet()){
if(!e.getKey().equals(1) && e.getValue().equals((byte)0)){
fill(e.getKey());
}
}
}
/**
* Fill a hole in the hashmap of pixels (HashMap<label number, pixel value> by morphology operation.
* The hole will be filled with the pixel value of adjacent pixel.
*
* @param labelNum the label number
*/
public void fill(int labelNum){
if (ldepth > depth) { // 3D image
for (int d = 1; d < ldepth; d++) {
for (int h = 1; h < lheight - 1; h++) {
for (int w = 1; w < lwidth - 1; w++) {
if (mask[d * lheight * lwidth + h * lwidth + w] == labelNum ) {
pixels[(d-1) * height * width + (h-1) * width + w - 1] = checkAdjacentsLabel(w, h, d, labelNum);
}
}
}
}
} else { // 2D image
for (int d = 0; d < ldepth; d++) {
for (int h = 1; h < lheight - 1; h++) {
for (int w = 1; w < lwidth - 1; w++) {
if (mask[d * lheight * lwidth + h * lwidth + w] == labelNum ) {
pixels[d * height * width + (h-1) * width + w - 1] = checkAdjacentsLabel(w, h, d, labelNum);
}
}
}
}
}
}
/**
* Check adjacent pixels whether it contains the given label (labelNum).
* If all the adjacent pixels have same label with given label, then return 0.
* If the adjacent pixels contain different labels, then returns the pixel
* value of most enclosing adjacent domain.
*
* @param w the x offset
* @param h the y offset
* @param d the z offset
* @param labelNum the label number
* @return the pixel value of most enclosing adjacent domain if different domain exists, otherwise 0
*/
public byte checkAdjacentsLabel(int w, int h, int d, int labelNum){
List<Byte> adjVal = new ArrayList<Byte>();
//check right
if(mask[d * lheight * lwidth + h * lwidth + w + 1] != labelNum)
adjVal.add(hashPix.get(mask[d * lheight * lwidth + h * lwidth + w + 1]));
//check left
if(mask[d * lheight * lwidth + h * lwidth + w - 1] != labelNum)
adjVal.add(hashPix.get(mask[d * lheight * lwidth + h * lwidth + w - 1]));
//check down
if(mask[d * lheight * lwidth + (h+1) * lwidth + w ] != labelNum)
adjVal.add(hashPix.get(mask[d * lheight * lwidth + (h+1) * lwidth + w]));
//check up
if(mask[d * lheight * lwidth + (h-1) * lwidth + w ] != labelNum)
adjVal.add(hashPix.get(mask[d * lheight * lwidth + (h-1) * lwidth + w]));
//check above
if(d != depth - 1 && mask[(d+1) * lheight * lwidth + h * lwidth + w] != labelNum)
adjVal.add(hashPix.get(mask[(d+1) * lheight * lwidth + h * lwidth + w]));
//check below
if(d != 0 && mask[(d-1) * lheight * lwidth + h * lwidth + w] != labelNum)
adjVal.add(hashPix.get(mask[(d - 1) * lheight * lwidth + h * lwidth + w]));
if(adjVal.isEmpty())
return 0;
int max = 0;
int count = 0;
int freq, temp; Byte val = 0;
for(int n = 0 ; n < adjVal.size() ; n++){
val = adjVal.get(n);
if(val == 0)
continue;
freq = Collections.frequency(adjVal, val);
temp = val & 0xFF;
if(freq > count){
max = temp;
count = freq;
}
if(freq == count && max < temp){
max = temp;
count = freq;
}
}
return (byte) max;
}
/**
* Sets the label of the given pixel (x offset, y offset, z offset) with its pixel value.
* Checks whether the adjacent pixel has the zero pixel value, and its label is already assigned.
*
* @param w the x offset
* @param h the y offset
* @param d the z offset
* @param pixVal the pixel value
* @return the label as integer value
*/
private int setLabel(int w , int h, int d, byte pixVal){
List<Integer> adjVal = new ArrayList<Integer>();
//check left
if(mask[d * lheight * lwidth + h * lwidth + w - 1] != 0 && hashPix.get(mask[d * lheight * lwidth + h * lwidth + w - 1]) == (byte)0)
adjVal.add(mask[d * lheight * lwidth + h * lwidth + w - 1]);
//check up
if(mask[d * lheight * lwidth + (h-1) * lwidth + w ] != 0 && hashPix.get(mask[d * lheight * lwidth + (h-1) * lwidth + w]) == (byte)0)
adjVal.add(mask[d * lheight * lwidth + (h-1) * lwidth + w]);
//check below
if(d != 0 && mask[(d-1) * lheight * lwidth + h * lwidth + w] != 0 && hashPix.get(mask[(d-1) * lheight * lwidth + h * lwidth + w]) == (byte)0)
adjVal.add(mask[(d-1) * lheight * lwidth + h * lwidth + w]);
if(adjVal.isEmpty()){
hashPix.put(labelCount, pixVal);
return labelCount++;
}
Collections.sort(adjVal);
//if all element are same or list has only one element
if(Collections.frequency(adjVal, adjVal.get(0)) == adjVal.size())
return adjVal.get(0);
int min = adjVal.get(0);
for(int i = 1; i < adjVal.size(); i++){
if(min == adjVal.get(i))
continue;
rewriteLabel(d, min, adjVal.get(i));
hashPix.remove(adjVal.get(i));
}
return min;
}
/**
* Sets back the label of the given pixel (x offset, y offset, z offset) with its pixel value.
* Checks whether the adjacent pixel has the non-zero pixel value, and its label is already assigned.
*
* @param w the x offset
* @param h the y offset
* @param d the z offset
* @param pixVal the pixel value
* @return the label as integer value
*/
private int setbackLabel(int w , int h, int d, byte pixVal){
List<Integer> adjVal = new ArrayList<Integer>();
//check left
if(mask[d * lheight * lwidth + h * lwidth + w - 1] != 0 && hashPix.get(mask[d * lheight * lwidth + h * lwidth + w - 1]) != (byte)0)
adjVal.add(mask[d * lheight * lwidth + h * lwidth + w - 1]);
//check up
if(mask[d * lheight * lwidth + (h-1) * lwidth + w ] != 0 && hashPix.get(mask[d * lheight * lwidth + (h-1) * lwidth + w]) != (byte)0)
adjVal.add(mask[d * lheight * lwidth + (h-1) * lwidth + w]);
//check below
if(d != 0 && mask[(d-1) * lheight * lwidth + h * lwidth + w] != 0 && hashPix.get(mask[(d-1) * lheight * lwidth + h * lwidth + w]) != (byte)0)
adjVal.add(mask[(d-1) * lheight * lwidth + h * lwidth + w]);
if(adjVal.isEmpty()){
hashPix.put(labelCount, pixVal);
return labelCount++;
}
Collections.sort(adjVal);
//if all element are same or list has only one element
if(Collections.frequency(adjVal, adjVal.get(0)) == adjVal.size())
return adjVal.get(0);
int min = adjVal.get(0);
for(int i = 1; i < adjVal.size(); i++){
if(min == adjVal.get(i))
continue;
hashPix.remove(adjVal.get(i));
rewriteLabel(d, min, adjVal.get(i));
}
return min;
}
/**
* Replace the label of pixels in the spatial image which has "before" to "after".
*
* @param dEnd the end of the depth
* @param after the label to set by this replacement
* @param before the label to be replaced
*/
private void rewriteLabel(int dEnd, int after, int before){
if (ldepth > depth) {
for (int d = 1; d <= dEnd; d++) {
for (int h = 1; h < lheight - 1; h++) {
for (int w = 1; w < lwidth - 1; w++) {
if (mask[d * lheight * lwidth + h * lwidth + w] == before)
mask[d * lheight * lwidth + h * lwidth + w] = after;
}
}
}
}else{
for (int d = 0; d <= dEnd; d++) {
for (int h = 1; h < lheight - 1; h++) {
for (int w = 1; w < lwidth - 1; w++) {
if (mask[d * lheight * lwidth + h * lwidth + w] == before)
mask[d * lheight * lwidth + h * lwidth + w] = after;
}
}
}
}
}
}
| spatialsimulator/XitoSBML | src/main/java/jp/ac/keio/bio/fun/xitosbml/image/Filler.java | Java | apache-2.0 | 14,320 |
/*
* Copyright 2015 Adaptris Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.adaptris.core;
import com.adaptris.annotation.Removal;
import com.adaptris.core.stubs.UpgradedToJunit4;
import com.adaptris.interlok.junit.scaffolding.ExampleConfigGenerator;
@Deprecated
@Removal(version = "4.0.0",
message = "moved to com.adaptris.interlok.junit.scaffolding")
public abstract class ExampleConfigCase extends ExampleConfigGenerator implements UpgradedToJunit4 {
}
| adaptris/interlok | interlok-core/src/test/java/com/adaptris/core/ExampleConfigCase.java | Java | apache-2.0 | 997 |
package org.ak.gitanalyzer.http.processor;
import org.ak.gitanalyzer.util.writer.CSVWriter;
import org.ak.gitanalyzer.util.writer.HTMLWriter;
import java.text.NumberFormat;
import java.util.Collection;
import java.util.function.BiConsumer;
import java.util.function.Function;
/**
* Created by Andrew on 02.12.2016.
*/
public class ProcessorMock extends BaseAnalysisProcessor {
public ProcessorMock(NumberFormat nf) {
super(nf);
}
@Override
public <T> String getCSVForReport(String[] headers, Collection<T> collection, BiConsumer<T, StringBuilder> consumer) {
return super.getCSVForReport(headers, collection, consumer);
}
@Override
public <T> String getJSONForTable(Collection<T> collection, BiConsumer<T, StringBuilder> consumer) {
return super.getJSONForTable(collection, consumer);
}
@Override
public <T> String getJSONFor2D(Collection<T> collection, BiConsumer<T, StringBuilder> consumer) {
return super.getJSONFor2D(collection, consumer);
}
@Override
public <T> String getJSONForGraph(Collection<T> collection, Function<T, Integer> nodeIdSupplier, TriConsumer<T, StringBuilder, Integer> consumer) {
return super.getJSONForGraph(collection, nodeIdSupplier, consumer);
}
@Override
public String getTypeString(double weight, double thickThreshold, double normalThreshold) {
return super.getTypeString(weight, thickThreshold, normalThreshold);
}
public HTMLWriter getHtmlWriter() {
return htmlWriter;
}
public CSVWriter getCsvWriter() {
return csvWriter;
}
}
| AndreyKunin/git-analyzer | src/test/java/org/ak/gitanalyzer/http/processor/ProcessorMock.java | Java | apache-2.0 | 1,622 |
package com.yezi.text.widget;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SwitchCompat;
import android.view.View;
import android.widget.CompoundButton;
import com.yezi.text.activity.AdapterSampleActivity;
import com.yezi.text.activity.AnimatorSampleActivity;
import com.yezi.text.R;
public class MyRecycleview extends AppCompatActivity {
private boolean enabledGrid = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mycycleview);
findViewById(R.id.btn_animator_sample).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MyRecycleview.this, AnimatorSampleActivity.class);
i.putExtra("GRID", enabledGrid);
startActivity(i);
}
});
findViewById(R.id.btn_adapter_sample).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MyRecycleview.this, AdapterSampleActivity.class);
i.putExtra("GRID", enabledGrid);
startActivity(i);
}
});
((SwitchCompat) findViewById(R.id.grid)).setOnCheckedChangeListener(
new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
enabledGrid = isChecked;
}
});
}
}
| qwertyezi/Test | text/app/src/main/java/com/yezi/text/widget/MyRecycleview.java | Java | apache-2.0 | 1,720 |
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.datalint.open.shared.xml;
import java.util.ArrayList;
import java.util.List;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import com.datalint.open.shared.xml.impl.XMLParserImpl;
/**
* This class represents the client interface to XML parsing.
*/
public class XMLParser {
private static final XMLParserImpl impl = XMLParserImpl.getInstance();
/**
* This method creates a new document, to be manipulated by the DOM API.
*
* @return the newly created document
*/
public static Document createDocument() {
return impl.createDocument();
}
/**
* This method parses a new document from the supplied string, throwing a
* <code>DOMParseException</code> if the parse fails.
*
* @param contents the String to be parsed into a <code>Document</code>
* @return the newly created <code>Document</code>
*/
public static Document parse(String contents) {
return impl.parse(contents);
}
// Update on 2020-05-10, does not work with XPath.
public static Document parseReadOnly(String contents) {
return impl.parseReadOnly(contents);
}
/**
* This method removes all <code>Text</code> nodes which are made up of only
* white space.
*
* @param n the node which is to have all of its whitespace descendents removed.
*/
public static void removeWhitespace(Node n) {
removeWhitespaceInner(n, null);
}
/**
* This method determines whether the browser supports {@link CDATASection} as
* distinct entities from <code>Text</code> nodes.
*
* @return true if the browser supports {@link CDATASection}, otherwise
* <code>false</code>.
*/
public static boolean supportsCDATASection() {
return impl.supportsCDATASection();
}
/*
* The inner recursive method for removeWhitespace
*/
private static void removeWhitespaceInner(Node n, Node parent) {
// This n is removed from the parent if n is a whitespace node
if (parent != null && n instanceof Text && (!(n instanceof CDATASection))) {
Text t = (Text) n;
if (t.getData().matches("[ \t\n]*")) {
parent.removeChild(t);
}
}
if (n.hasChildNodes()) {
int length = n.getChildNodes().getLength();
List<Node> toBeProcessed = new ArrayList<Node>();
// We collect all the nodes to iterate as the child nodes will
// change upon removal
for (int i = 0; i < length; i++) {
toBeProcessed.add(n.getChildNodes().item(i));
}
// This changes the child nodes, but the iterator of nodes never
// changes meaning that this is safe
for (Node childNode : toBeProcessed) {
removeWhitespaceInner(childNode, n);
}
}
}
/**
* Not instantiable.
*/
private XMLParser() {
}
}
| datalint/open | Open/src/main/java/com/datalint/open/shared/xml/XMLParser.java | Java | apache-2.0 | 3,302 |
/**
* 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.
*
* Copyright 2012-2016 the original author or authors.
*/
package org.assertj.core.api;
import static org.assertj.core.util.Lists.newArrayList;
import org.junit.Rule;
import org.junit.Test;
public class JUnitBDDSoftAssertionsSuccessTest {
@Rule
public final JUnitBDDSoftAssertions softly = new JUnitBDDSoftAssertions();
@Test
public void all_assertions_should_pass() throws Throwable {
softly.then(1).isEqualTo(1);
softly.then(newArrayList(1, 2)).containsOnly(1, 2);
}
}
| dorzey/assertj-core | src/test/java/org/assertj/core/api/JUnitBDDSoftAssertionsSuccessTest.java | Java | apache-2.0 | 1,039 |
/*******************************************************************************
* Copyright 2013-2015 alladin-IT GmbH
*
* 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 at.alladin.rmbt.controlServer;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.naming.NamingException;
import org.joda.time.DateTime;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.Reference;
import org.restlet.engine.header.Header;
import org.restlet.representation.Representation;
import org.restlet.resource.Options;
import org.restlet.resource.ResourceException;
import org.restlet.util.Series;
import at.alladin.rmbt.db.DbConnection;
import at.alladin.rmbt.shared.ResourceManager;
import at.alladin.rmbt.util.capability.Capabilities;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
public class ServerResource extends org.restlet.resource.ServerResource
{
protected Connection conn;
protected ResourceBundle labels;
protected ResourceBundle settings;
protected Capabilities capabilities = new Capabilities();
public static class MyDateTimeAdapter implements JsonSerializer<DateTime>, JsonDeserializer<DateTime>
{
public JsonElement serialize(DateTime src, Type typeOfSrc, JsonSerializationContext context)
{
return new JsonPrimitive(src.toString());
}
public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException
{
return new DateTime(json.getAsJsonPrimitive().getAsString());
}
}
public void readCapabilities(final JSONObject request) throws JSONException {
if (request != null) {
if (request.has("capabilities")) {
capabilities = new Gson().fromJson(request.get("capabilities").toString(), Capabilities.class);
}
}
}
public static Gson getGson(boolean prettyPrint)
{
GsonBuilder gb = new GsonBuilder()
.registerTypeAdapter(DateTime.class, new MyDateTimeAdapter());
if (prettyPrint)
gb = gb.setPrettyPrinting();
return gb.create();
}
@Override
public void doInit() throws ResourceException
{
super.doInit();
settings = ResourceManager.getCfgBundle();
// Set default Language for System
Locale.setDefault(new Locale(settings.getString("RMBT_DEFAULT_LANGUAGE")));
labels = ResourceManager.getSysMsgBundle();
try {
if (getQuery().getNames().contains("capabilities")) {
capabilities = new Gson().fromJson(getQuery().getValues("capabilities"), Capabilities.class);
}
} catch (final Exception e) {
e.printStackTrace();
}
// Get DB-Connection
try
{
conn = DbConnection.getConnection();
}
catch (final NamingException e)
{
e.printStackTrace();
}
catch (final SQLException e)
{
System.out.println(labels.getString("ERROR_DB_CONNECTION_FAILED"));
e.printStackTrace();
}
}
@Override
protected void doRelease() throws ResourceException
{
try
{
if (conn != null)
conn.close();
}
catch (final SQLException e)
{
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
protected void addAllowOrigin()
{
Series<Header> responseHeaders = (Series<Header>) getResponse().getAttributes().get("org.restlet.http.headers");
if (responseHeaders == null)
{
responseHeaders = new Series<>(Header.class);
getResponse().getAttributes().put("org.restlet.http.headers", responseHeaders);
}
responseHeaders.add("Access-Control-Allow-Origin", "*");
responseHeaders.add("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
responseHeaders.add("Access-Control-Allow-Headers", "Content-Type");
responseHeaders.add("Access-Control-Allow-Credentials", "false");
responseHeaders.add("Access-Control-Max-Age", "60");
}
@Options
public void doOptions(final Representation entity)
{
addAllowOrigin();
}
@SuppressWarnings("unchecked")
public String getIP()
{
final Series<Header> headers = (Series<Header>) getRequest().getAttributes().get("org.restlet.http.headers");
final String realIp = headers.getFirstValue("X-Real-IP", true);
if (realIp != null)
return realIp;
else
return getRequest().getClientInfo().getAddress();
}
@SuppressWarnings("unchecked")
public Reference getURL()
{
final Series<Header> headers = (Series<Header>) getRequest().getAttributes().get("org.restlet.http.headers");
final String realURL = headers.getFirstValue("X-Real-URL", true);
if (realURL != null)
return new Reference(realURL);
else
return getRequest().getOriginalRef();
}
protected String getSetting(String key, String lang)
{
if (conn == null)
return null;
try (final PreparedStatement st = conn.prepareStatement(
"SELECT value"
+ " FROM settings"
+ " WHERE key=? AND (lang IS NULL OR lang = ?)"
+ " ORDER BY lang NULLS LAST LIMIT 1");)
{
st.setString(1, key);
st.setString(2, lang);
try (final ResultSet rs = st.executeQuery();)
{
if (rs != null && rs.next())
return rs.getString("value");
}
return null;
}
catch (SQLException e)
{
e.printStackTrace();
return null;
}
}
}
| alladin-IT/open-rmbt | RMBTControlServer/src/at/alladin/rmbt/controlServer/ServerResource.java | Java | apache-2.0 | 7,059 |
package io.github.marktony.reader.qsbk;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import io.github.marktony.reader.R;
import io.github.marktony.reader.adapter.QsbkArticleAdapter;
import io.github.marktony.reader.data.Qiushibaike;
import io.github.marktony.reader.interfaze.OnRecyclerViewClickListener;
import io.github.marktony.reader.interfaze.OnRecyclerViewLongClickListener;
/**
* Created by Lizhaotailang on 2016/8/4.
*/
public class QsbkFragment extends Fragment
implements QsbkContract.View {
private QsbkContract.Presenter presenter;
private QsbkArticleAdapter adapter;
private RecyclerView recyclerView;
private SwipeRefreshLayout refreshLayout;
public QsbkFragment() {
// requires empty constructor
}
public static QsbkFragment newInstance(int page) {
return new QsbkFragment();
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.joke_list_fragment, container, false);
initViews(view);
presenter.loadArticle(true);
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
presenter.loadArticle(true);
adapter.notifyDataSetChanged();
if (refreshLayout.isRefreshing()){
refreshLayout.setRefreshing(false);
}
}
});
recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
boolean isSlidingToLast = false;
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
// 当不滚动时
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
// 获取最后一个完全显示的itemposition
int lastVisibleItem = manager.findLastCompletelyVisibleItemPosition();
int totalItemCount = manager.getItemCount();
// 判断是否滚动到底部并且是向下滑动
if (lastVisibleItem == (totalItemCount - 1) && isSlidingToLast) {
presenter.loadMore();
}
}
super.onScrollStateChanged(recyclerView, newState);
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
isSlidingToLast = dy > 0;
}
});
return view;
}
@Override
public void setPresenter(QsbkContract.Presenter presenter) {
if (presenter != null) {
this.presenter = presenter;
}
}
@Override
public void initViews(View view) {
recyclerView = (RecyclerView) view.findViewById(R.id.qsbk_rv);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
refreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.refresh);
}
@Override
public void showResult(ArrayList<Qiushibaike.Item> articleList) {
if (adapter == null) {
adapter = new QsbkArticleAdapter(getActivity(), articleList);
recyclerView.setAdapter(adapter);
} else {
adapter.notifyDataSetChanged();
}
adapter.setOnItemClickListener(new OnRecyclerViewClickListener() {
@Override
public void OnClick(View v, int position) {
presenter.shareTo(position);
}
});
adapter.setOnItemLongClickListener(new OnRecyclerViewLongClickListener() {
@Override
public void OnLongClick(View view, int position) {
presenter.copyToClipboard(position);
}
});
}
@Override
public void startLoading() {
refreshLayout.post(new Runnable() {
@Override
public void run() {
refreshLayout.setRefreshing(true);
}
});
}
@Override
public void stopLoading() {
refreshLayout.post(new Runnable() {
@Override
public void run() {
refreshLayout.setRefreshing(false);
}
});
}
@Override
public void showLoadError() {
Snackbar.make(recyclerView, "加载失败", Snackbar.LENGTH_SHORT)
.setAction("重试", new View.OnClickListener() {
@Override
public void onClick(View view) {
presenter.loadArticle(false);
}
}).show();
}
@Override
public void onResume() {
super.onResume();
presenter.start();
}
}
| HeJianF/iReader | app/src/main/java/io/github/marktony/reader/qsbk/QsbkFragment.java | Java | apache-2.0 | 5,506 |
package org.gradle.test.performance.mediummonolithicjavaproject.p428;
import org.junit.Test;
import static org.junit.Assert.*;
public class Test8570 {
Production8570 objectUnderTest = new Production8570();
@Test
public void testProperty0() {
String value = "value";
objectUnderTest.setProperty0(value);
assertEquals(value, objectUnderTest.getProperty0());
}
@Test
public void testProperty1() {
String value = "value";
objectUnderTest.setProperty1(value);
assertEquals(value, objectUnderTest.getProperty1());
}
@Test
public void testProperty2() {
String value = "value";
objectUnderTest.setProperty2(value);
assertEquals(value, objectUnderTest.getProperty2());
}
@Test
public void testProperty3() {
String value = "value";
objectUnderTest.setProperty3(value);
assertEquals(value, objectUnderTest.getProperty3());
}
@Test
public void testProperty4() {
String value = "value";
objectUnderTest.setProperty4(value);
assertEquals(value, objectUnderTest.getProperty4());
}
@Test
public void testProperty5() {
String value = "value";
objectUnderTest.setProperty5(value);
assertEquals(value, objectUnderTest.getProperty5());
}
@Test
public void testProperty6() {
String value = "value";
objectUnderTest.setProperty6(value);
assertEquals(value, objectUnderTest.getProperty6());
}
@Test
public void testProperty7() {
String value = "value";
objectUnderTest.setProperty7(value);
assertEquals(value, objectUnderTest.getProperty7());
}
@Test
public void testProperty8() {
String value = "value";
objectUnderTest.setProperty8(value);
assertEquals(value, objectUnderTest.getProperty8());
}
@Test
public void testProperty9() {
String value = "value";
objectUnderTest.setProperty9(value);
assertEquals(value, objectUnderTest.getProperty9());
}
} | oehme/analysing-gradle-performance | my-app/src/test/java/org/gradle/test/performance/mediummonolithicjavaproject/p428/Test8570.java | Java | apache-2.0 | 2,111 |
/*
* 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.geode.management.internal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.logging.log4j.Logger;
import org.apache.geode.annotations.internal.MakeNotStatic;
import org.apache.geode.distributed.DistributedSystemDisconnectedException;
import org.apache.geode.distributed.internal.InternalDistributedSystem;
import org.apache.geode.internal.cache.InternalCache;
import org.apache.geode.internal.cache.InternalCacheForClientAccess;
import org.apache.geode.logging.internal.log4j.api.LogService;
import org.apache.geode.management.ManagementService;
/**
* Super class to all Management Service
*
* @since GemFire 7.0
*/
public abstract class BaseManagementService extends ManagementService {
private static final Logger logger = LogService.getLogger();
/**
* The main mapping between different resources and Service instance Object can be Cache
*/
@MakeNotStatic
protected static final Map<Object, BaseManagementService> instances =
new HashMap<Object, BaseManagementService>();
/** List of connected <code>DistributedSystem</code>s */
@MakeNotStatic
private static final List<InternalDistributedSystem> systems =
new ArrayList<InternalDistributedSystem>(1);
/** Protected constructor. */
protected BaseManagementService() {}
// Static block to initialize the ConnectListener on the System
static {
initInternalDistributedSystem();
}
/**
* This method will close the service. Any operation on the service instance will throw exception
*/
protected abstract void close();
/**
* This method will close the service. Any operation on the service instance will throw exception
*/
protected abstract boolean isClosed();
/**
* Returns a ManagementService to use for the specified Cache.
*
* @param cache defines the scope of resources to be managed
*/
public static ManagementService getManagementService(InternalCacheForClientAccess cache) {
synchronized (instances) {
BaseManagementService service = instances.get(cache);
if (service == null) {
service = SystemManagementService.newSystemManagementService(cache);
instances.put(cache, service);
}
return service;
}
}
public static ManagementService getExistingManagementService(InternalCache cache) {
synchronized (instances) {
BaseManagementService service = instances.get(cache.getCacheForProcessingClientRequests());
return service;
}
}
/**
* Initialises the distributed system listener
*/
private static void initInternalDistributedSystem() {
synchronized (instances) {
// Initialize our own list of distributed systems via a connect listener
@SuppressWarnings("unchecked")
List<InternalDistributedSystem> existingSystems = InternalDistributedSystem
.addConnectListener(new InternalDistributedSystem.ConnectListener() {
@Override
public void onConnect(InternalDistributedSystem sys) {
addInternalDistributedSystem(sys);
}
});
// While still holding the lock on systems, add all currently known
// systems to our own list
for (InternalDistributedSystem sys : existingSystems) {
try {
if (sys.isConnected()) {
addInternalDistributedSystem(sys);
}
} catch (DistributedSystemDisconnectedException e) {
if (logger.isDebugEnabled()) {
logger.debug("DistributedSystemDisconnectedException {}", e.getMessage(), e);
}
}
}
}
}
/**
* Add an Distributed System and adds a Discon Listener
*/
private static void addInternalDistributedSystem(InternalDistributedSystem sys) {
synchronized (instances) {
sys.addDisconnectListener(new InternalDistributedSystem.DisconnectListener() {
@Override
public String toString() {
return "Disconnect listener for BaseManagementService";
}
@Override
public void onDisconnect(InternalDistributedSystem ss) {
removeInternalDistributedSystem(ss);
}
});
systems.add(sys);
}
}
/**
* Remove a Distributed System from the system lists. If list is empty it closes down all the
* services if not closed
*/
private static void removeInternalDistributedSystem(InternalDistributedSystem sys) {
synchronized (instances) {
systems.remove(sys);
if (systems.isEmpty()) {
for (Object key : instances.keySet()) {
BaseManagementService service = (BaseManagementService) instances.get(key);
try {
if (!service.isClosed()) {
// Service close method should take care of the cleaning up
// activities
service.close();
}
} catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.debug("ManagementException while removing InternalDistributedSystem {}",
e.getMessage(), e);
}
}
}
instances.clear();
}
}
}
}
| davebarnes97/geode | geode-core/src/main/java/org/apache/geode/management/internal/BaseManagementService.java | Java | apache-2.0 | 5,962 |
/*
* Copyright 1999-2020 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.csp.sentinel.adapter.okhttp.extractor;
import okhttp3.Connection;
import okhttp3.Request;
/**
* @author zhaoyuguang
*/
public class DefaultOkHttpResourceExtractor implements OkHttpResourceExtractor {
@Override
public String extract(Request request, Connection connection) {
return request.method() + ":" + request.url().toString();
}
}
| alibaba/Sentinel | sentinel-adapter/sentinel-okhttp-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/okhttp/extractor/DefaultOkHttpResourceExtractor.java | Java | apache-2.0 | 997 |
package com.melvin.share.ui.activity;
import android.content.Context;
import android.databinding.DataBindingUtil;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.melvin.share.R;
import com.melvin.share.Utils.ShapreUtils;
import com.melvin.share.Utils.Utils;
import com.melvin.share.databinding.ActivityOrderEvaluateBinding;
import com.melvin.share.model.Evaluation;
import com.melvin.share.model.WaitPayOrderInfo;
import com.melvin.share.model.list.CommonList;
import com.melvin.share.model.serverReturn.CommonReturnModel;
import com.melvin.share.modelview.acti.OrderEvaluateViewModel;
import com.melvin.share.network.GlobalUrl;
import com.melvin.share.rx.RxActivityHelper;
import com.melvin.share.rx.RxFragmentHelper;
import com.melvin.share.rx.RxModelSubscribe;
import com.melvin.share.rx.RxSubscribe;
import com.melvin.share.ui.activity.common.BaseActivity;
import com.melvin.share.ui.activity.shopcar.ShoppingCarActivity;
import com.melvin.share.ui.fragment.productinfo.ProductEvaluateFragment;
import com.melvin.share.view.MyRecyclerView;
import com.melvin.share.view.RatingBar;
import java.util.HashMap;
import java.util.Map;
import static com.melvin.share.R.id.map;
import static com.melvin.share.R.id.ratingbar;
/**
* Author: Melvin
* <p/>
* Data: 2017/4/8
* <p/>
* 描述: 订单评价页面
*/
public class OderEvaluateActivity extends BaseActivity {
private ActivityOrderEvaluateBinding binding;
private Context mContext = null;
private int starCount;
private WaitPayOrderInfo.OrderBean.OrderItemResponsesBean orderItemResponsesBean;
@Override
protected void initView() {
binding = DataBindingUtil.setContentView(this, R.layout.activity_order_evaluate);
mContext = this;
initWindow();
initToolbar(binding.toolbar);
ininData();
}
private void ininData() {
binding.ratingbar.setOnRatingChangeListener(new RatingBar.OnRatingChangeListener() {
@Override
public void onRatingChange(int var1) {
starCount = var1;
}
});
orderItemResponsesBean = getIntent().getParcelableExtra("orderItemResponsesBean");
if (orderItemResponsesBean != null) {
String[] split = orderItemResponsesBean.mainPicture.split("\\|");
if (split != null && split.length >= 1) {
String url = GlobalUrl.SERVICE_URL + split[0];
Glide.with(mContext)
.load(url)
.placeholder(R.mipmap.logo)
.centerCrop()
.into(binding.image);
}
binding.name.setText(orderItemResponsesBean.productName);
}
}
public void submit(View view) {
String contents = binding.content.getText().toString();
if (TextUtils.isEmpty(contents)) {
Utils.showToast(mContext, "请评价");
}
if (starCount == 0) {
Utils.showToast(mContext, "请评分");
}
Map map = new HashMap();
map.put("orderItemId", orderItemResponsesBean.id);
map.put("startlevel", starCount);
map.put("picture", orderItemResponsesBean.mainPicture);
map.put("content", contents);
ShapreUtils.putParamCustomerId(map);
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = (JsonObject) jsonParser.parse((new Gson().toJson(map)));
fromNetwork.insertOderItemEvaluation(jsonObject)
.compose(new RxActivityHelper<CommonReturnModel>().ioMain(OderEvaluateActivity.this, true))
.subscribe(new RxSubscribe<CommonReturnModel>(mContext, true) {
@Override
protected void myNext(CommonReturnModel commonReturnModel) {
Utils.showToast(mContext, commonReturnModel.message);
finish();
}
@Override
protected void myError(String message) {
Utils.showToast(mContext, message);
}
});
}
}
| MelvinWang/NewShare | NewShare/app/src/main/java/com/melvin/share/ui/activity/OderEvaluateActivity.java | Java | apache-2.0 | 4,380 |
package clockworktest.water;
import com.clockwork.app.SimpleApplication;
import com.clockwork.audio.AudioNode;
import com.clockwork.audio.LowPassFilter;
import com.clockwork.effect.ParticleEmitter;
import com.clockwork.effect.ParticleMesh;
import com.clockwork.input.KeyInput;
import com.clockwork.input.controls.ActionListener;
import com.clockwork.input.controls.KeyTrigger;
import com.clockwork.light.DirectionalLight;
import com.clockwork.material.Material;
import com.clockwork.material.RenderState.BlendMode;
import com.clockwork.math.ColorRGBA;
import com.clockwork.math.FastMath;
import com.clockwork.math.Quaternion;
import com.clockwork.math.Vector3f;
import com.clockwork.post.FilterPostProcessor;
import com.clockwork.post.filters.BloomFilter;
import com.clockwork.post.filters.DepthOfFieldFilter;
import com.clockwork.post.filters.LightScatteringFilter;
import com.clockwork.renderer.Camera;
import com.clockwork.renderer.queue.RenderQueue.Bucket;
import com.clockwork.renderer.queue.RenderQueue.ShadowMode;
import com.clockwork.scene.Geometry;
import com.clockwork.scene.Node;
import com.clockwork.scene.Spatial;
import com.clockwork.scene.shape.Box;
import com.clockwork.terrain.geomipmap.TerrainQuad;
import com.clockwork.terrain.heightmap.AbstractHeightMap;
import com.clockwork.terrain.heightmap.ImageBasedHeightMap;
import com.clockwork.texture.Texture;
import com.clockwork.texture.Texture.WrapMode;
import com.clockwork.texture.Texture2D;
import com.clockwork.util.SkyFactory;
import com.clockwork.water.WaterFilter;
import java.util.ArrayList;
import java.util.List;
/**
* test
*
*/
public class TestPostWater extends SimpleApplication {
private Vector3f lightDir = new Vector3f(-4.9236743f, -1.27054665f, 5.896916f);
private WaterFilter water;
TerrainQuad terrain;
Material matRock;
AudioNode waves;
LowPassFilter underWaterAudioFilter = new LowPassFilter(0.5f, 0.1f);
LowPassFilter underWaterReverbFilter = new LowPassFilter(0.5f, 0.1f);
LowPassFilter aboveWaterAudioFilter = new LowPassFilter(1, 1);
public static void main(String[] args) {
TestPostWater app = new TestPostWater();
app.start();
}
@Override
public void simpleInitApp() {
setDisplayFps(false);
setDisplayStatView(false);
Node mainScene = new Node("Main Scene");
rootNode.attachChild(mainScene);
createTerrain(mainScene);
DirectionalLight sun = new DirectionalLight();
sun.setDirection(lightDir);
sun.setColor(ColorRGBA.White.clone().multLocal(1.7f));
mainScene.addLight(sun);
DirectionalLight l = new DirectionalLight();
l.setDirection(Vector3f.UNIT_Y.mult(-1));
l.setColor(ColorRGBA.White.clone().multLocal(0.3f));
// mainScene.addLight(l);
flyCam.setMoveSpeed(50);
//cam.setLocation(new Vector3f(-700, 100, 300));
//cam.setRotation(new Quaternion().fromAngleAxis(0.5f, Vector3f.UNIT_Z));
cam.setLocation(new Vector3f(-327.21957f, 61.6459f, 126.884346f));
cam.setRotation(new Quaternion(0.052168474f, 0.9443102f, -0.18395276f, 0.2678024f));
cam.setRotation(new Quaternion().fromAngles(new float[]{FastMath.PI * 0.06f, FastMath.PI * 0.65f, 0}));
Spatial sky = SkyFactory.createSky(assetManager, "Scenes/Beach/FullskiesSunset0068.dds", false);
sky.setLocalScale(350);
mainScene.attachChild(sky);
cam.setFrustumFar(4000);
//cam.setFrustumNear(100);
//private FilterPostProcessor fpp;
water = new WaterFilter(rootNode, lightDir);
FilterPostProcessor fpp = new FilterPostProcessor(assetManager);
fpp.addFilter(water);
BloomFilter bloom = new BloomFilter();
//bloom.getE
bloom.setExposurePower(55);
bloom.setBloomIntensity(1.0f);
fpp.addFilter(bloom);
LightScatteringFilter lsf = new LightScatteringFilter(lightDir.mult(-300));
lsf.setLightDensity(1.0f);
fpp.addFilter(lsf);
DepthOfFieldFilter dof = new DepthOfFieldFilter();
dof.setFocusDistance(0);
dof.setFocusRange(100);
fpp.addFilter(dof);
//
// fpp.addFilter(new TranslucentBucketFilter());
//
// fpp.setNumSamples(4);
water.setWaveScale(0.003f);
water.setMaxAmplitude(2f);
water.setFoamExistence(new Vector3f(1f, 4, 0.5f));
water.setFoamTexture((Texture2D) assetManager.loadTexture("Common/MatDefs/Water/Textures/foam2.jpg"));
//water.setNormalScale(0.5f);
//water.setRefractionConstant(0.25f);
water.setRefractionStrength(0.2f);
//water.setFoamHardness(0.6f);
water.setWaterHeight(initialWaterHeight);
uw = cam.getLocation().y < waterHeight;
waves = new AudioNode(assetManager, "Sound/Environment/Ocean Waves.ogg", false);
waves.setLooping(true);
waves.setReverbEnabled(true);
if (uw) {
waves.setDryFilter(new LowPassFilter(0.5f, 0.1f));
} else {
waves.setDryFilter(aboveWaterAudioFilter);
}
audioRenderer.playSource(waves);
//
viewPort.addProcessor(fpp);
inputManager.addListener(new ActionListener() {
public void onAction(String name, boolean isPressed, float tpf) {
if (isPressed) {
if (name.equals("foam1")) {
water.setFoamTexture((Texture2D) assetManager.loadTexture("Common/MatDefs/Water/Textures/foam.jpg"));
}
if (name.equals("foam2")) {
water.setFoamTexture((Texture2D) assetManager.loadTexture("Common/MatDefs/Water/Textures/foam2.jpg"));
}
if (name.equals("foam3")) {
water.setFoamTexture((Texture2D) assetManager.loadTexture("Common/MatDefs/Water/Textures/foam3.jpg"));
}
if (name.equals("upRM")) {
water.setReflectionMapSize(Math.min(water.getReflectionMapSize() * 2, 4096));
System.out.println("Reflection map size : " + water.getReflectionMapSize());
}
if (name.equals("downRM")) {
water.setReflectionMapSize(Math.max(water.getReflectionMapSize() / 2, 32));
System.out.println("Reflection map size : " + water.getReflectionMapSize());
}
}
}
}, "foam1", "foam2", "foam3", "upRM", "downRM");
inputManager.addMapping("foam1", new KeyTrigger(KeyInput.KEY_1));
inputManager.addMapping("foam2", new KeyTrigger(KeyInput.KEY_2));
inputManager.addMapping("foam3", new KeyTrigger(KeyInput.KEY_3));
inputManager.addMapping("upRM", new KeyTrigger(KeyInput.KEY_PGUP));
inputManager.addMapping("downRM", new KeyTrigger(KeyInput.KEY_PGDN));
// createBox();
// createFire();
}
Geometry box;
private void createBox() {
//creating a transluscent box
box = new Geometry("box", new Box(new Vector3f(0, 0, 0), 50, 50, 50));
Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
mat.setColor("Color", new ColorRGBA(1.0f, 0, 0, 0.3f));
mat.getAdditionalRenderState().setBlendMode(BlendMode.Alpha);
//mat.getAdditionalRenderState().setDepthWrite(false);
//mat.getAdditionalRenderState().setDepthTest(false);
box.setMaterial(mat);
box.setQueueBucket(Bucket.Translucent);
//creating a post view port
// ViewPort post=renderManager.createPostView("transpPost", cam);
// post.setClearFlags(false, true, true);
box.setLocalTranslation(-600, 0, 300);
//attaching the box to the post viewport
//Don't forget to updateGeometricState() the box in the simpleUpdate
// post.attachScene(box);
rootNode.attachChild(box);
}
private void createFire() {
/**
* Uses Texture from CW-test-data library!
*/
ParticleEmitter fire = new ParticleEmitter("Emitter", ParticleMesh.Type.Triangle, 30);
Material mat_red = new Material(assetManager, "Common/MatDefs/Misc/Particle.j3md");
mat_red.setTexture("Texture", assetManager.loadTexture("Effects/Explosion/flame.png"));
fire.setMaterial(mat_red);
fire.setImagesX(2);
fire.setImagesY(2); // 2x2 texture animation
fire.setEndColor(new ColorRGBA(1f, 0f, 0f, 1f)); // red
fire.setStartColor(new ColorRGBA(1f, 1f, 0f, 0.5f)); // yellow
fire.getParticleInfluencer().setInitialVelocity(new Vector3f(0, 2, 0));
fire.setStartSize(10f);
fire.setEndSize(1f);
fire.setGravity(0, 0, 0);
fire.setLowLife(0.5f);
fire.setHighLife(1.5f);
fire.getParticleInfluencer().setVelocityVariation(0.3f);
fire.setLocalTranslation(-350, 40, 430);
fire.setQueueBucket(Bucket.Transparent);
rootNode.attachChild(fire);
}
private void createTerrain(Node rootNode) {
matRock = new Material(assetManager, "Common/MatDefs/Terrain/TerrainLighting.j3md");
matRock.setBoolean("useTriPlanarMapping", false);
matRock.setBoolean("WardIso", true);
matRock.setTexture("AlphaMap", assetManager.loadTexture("Textures/Terrain/splat/alphamap.png"));
Texture heightMapImage = assetManager.loadTexture("Textures/Terrain/splat/mountains512.png");
Texture grass = assetManager.loadTexture("Textures/Terrain/splat/grass.jpg");
grass.setWrap(WrapMode.Repeat);
matRock.setTexture("DiffuseMap", grass);
matRock.setFloat("DiffuseMap_0_scale", 64);
Texture dirt = assetManager.loadTexture("Textures/Terrain/splat/dirt.jpg");
dirt.setWrap(WrapMode.Repeat);
matRock.setTexture("DiffuseMap_1", dirt);
matRock.setFloat("DiffuseMap_1_scale", 16);
Texture rock = assetManager.loadTexture("Textures/Terrain/splat/road.jpg");
rock.setWrap(WrapMode.Repeat);
matRock.setTexture("DiffuseMap_2", rock);
matRock.setFloat("DiffuseMap_2_scale", 128);
Texture normalMap0 = assetManager.loadTexture("Textures/Terrain/splat/grass_normal.jpg");
normalMap0.setWrap(WrapMode.Repeat);
Texture normalMap1 = assetManager.loadTexture("Textures/Terrain/splat/dirt_normal.png");
normalMap1.setWrap(WrapMode.Repeat);
Texture normalMap2 = assetManager.loadTexture("Textures/Terrain/splat/road_normal.png");
normalMap2.setWrap(WrapMode.Repeat);
matRock.setTexture("NormalMap", normalMap0);
matRock.setTexture("NormalMap_1", normalMap2);
matRock.setTexture("NormalMap_2", normalMap2);
AbstractHeightMap heightmap = null;
try {
heightmap = new ImageBasedHeightMap(heightMapImage.getImage(), 0.25f);
heightmap.load();
} catch (Exception e) {
e.printStackTrace();
}
terrain = new TerrainQuad("terrain", 65, 513, heightmap.getHeightMap());
List<Camera> cameras = new ArrayList<Camera>();
cameras.add(getCamera());
terrain.setMaterial(matRock);
terrain.setLocalScale(new Vector3f(5, 5, 5));
terrain.setLocalTranslation(new Vector3f(0, -30, 0));
terrain.setLocked(false); // unlock it so we can edit the height
terrain.setShadowMode(ShadowMode.Receive);
rootNode.attachChild(terrain);
}
//This part is to emulate tides, slightly varrying the height of the water plane
private float time = 0.0f;
private float waterHeight = 0.0f;
private float initialWaterHeight = 90f;//0.8f;
private boolean uw = false;
@Override
public void simpleUpdate(float tpf) {
super.simpleUpdate(tpf);
// box.updateGeometricState();
time += tpf;
waterHeight = (float) Math.cos(((time * 0.6f) % FastMath.TWO_PI)) * 1.5f;
water.setWaterHeight(initialWaterHeight + waterHeight);
if (water.isUnderWater() && !uw) {
waves.setDryFilter(new LowPassFilter(0.5f, 0.1f));
uw = true;
}
if (!water.isUnderWater() && uw) {
uw = false;
//waves.setReverbEnabled(false);
waves.setDryFilter(new LowPassFilter(1, 1f));
//waves.setDryFilter(new LowPassFilter(1,1f));
}
}
}
| PlanetWaves/clockworkengine | branches/3.0/engine/src/test/clockworktest/water/TestPostWater.java | Java | apache-2.0 | 12,539 |
/*******************************************************************************
* Copyright 2002-2016 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 com.github.lothar.security.acl.elasticsearch.repository;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;
import com.github.lothar.security.acl.elasticsearch.domain.UnknownStrategyObject;
@Repository
public interface UnknownStrategyRepository
extends ElasticsearchRepository<UnknownStrategyObject, Long> {
}
| lordlothar99/strategy-spring-security-acl | elasticsearch/src/test/java/com/github/lothar/security/acl/elasticsearch/repository/UnknownStrategyRepository.java | Java | apache-2.0 | 1,173 |
package javassist.build;
/**
* A generic build exception when applying a transformer.
* Wraps the real cause of the (probably javassist) root exception.
* @author SNI
*/
@SuppressWarnings("serial")
public class JavassistBuildException extends Exception {
public JavassistBuildException() {
super();
}
public JavassistBuildException(String message, Throwable throwable) {
super(message, throwable);
}
public JavassistBuildException(String message) {
super(message);
}
public JavassistBuildException(Throwable throwable) {
super(throwable);
}
}
| stephanenicolas/javassist-build-plugin-api | src/main/java/javassist/build/JavassistBuildException.java | Java | apache-2.0 | 569 |
package com.hcentive.webservice.soap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;
import com.hcentive.service.FormResponse;
import com.hcentive.webservice.exception.HcentiveSOAPException;
import org.apache.log4j.Logger;
/**
* @author Mebin.Jacob
*Endpoint class.
*/
@Endpoint
public final class FormEndpoint {
private static final String NAMESPACE_URI = "http://hcentive.com/service";
Logger logger = Logger.getLogger(FormEndpoint.class);
@Autowired
FormRepository formRepo;
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "FormResponse")
@ResponsePayload
public FormResponse submitForm(@RequestPayload FormResponse request) throws HcentiveSOAPException {
// GetCountryResponse response = new GetCountryResponse();
// response.setCountry(countryRepository.findCountry(request.getName()));
FormResponse response = null;
logger.debug("AAGAYA");
try{
response = new FormResponse();
response.setForm1(formRepo.findForm("1"));
//make API call
}catch(Exception exception){
throw new HcentiveSOAPException("Something went wrong!!! The exception is --- " + exception);
}
return response;
// return null;
}
}
| mebinjacob/spring-boot-soap | src/main/java/com/hcentive/webservice/soap/FormEndpoint.java | Java | apache-2.0 | 1,458 |
/*
* Copyright 2015 Luca Capra <[email protected]>.
*
* 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.createnet.compose.data;
/**
*
* @author Luca Capra <[email protected]>
*/
public class GeoPointRecord extends Record<String> {
public Point point;
protected String value;
public GeoPointRecord() {}
public GeoPointRecord(String point) {
this.point = new Point(point);
}
public GeoPointRecord(double latitude, double longitude) {
this.point = new Point(latitude, longitude);
}
@Override
public String getValue() {
return point.toString();
}
@Override
public void setValue(Object value) {
this.value = parseValue(value);
this.point = new Point(this.value);
}
@Override
public String parseValue(Object raw) {
return (String)raw;
}
@Override
public String getType() {
return "geo_point";
}
public class Point {
public double latitude;
public double longitude;
public Point(double latitude, double longitude) {
this.latitude = latitude;
this.longitude = longitude;
}
public Point(String val) {
String[] coords = val.split(",");
longitude = Double.parseDouble(coords[0].trim());
latitude = Double.parseDouble(coords[1].trim());
}
@Override
public String toString() {
return this.longitude + "," + this.latitude;
}
}
}
| muka/compose-java-client | src/main/java/org/createnet/compose/data/GeoPointRecord.java | Java | apache-2.0 | 2,062 |
/*
* Copyright 2012-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.ide.intellij;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import com.facebook.buck.android.AssumeAndroidPlatform;
import com.facebook.buck.testutil.ProcessResult;
import com.facebook.buck.testutil.TemporaryPaths;
import com.facebook.buck.testutil.integration.ProjectWorkspace;
import com.facebook.buck.testutil.integration.TestDataHelper;
import com.facebook.buck.util.environment.Platform;
import com.facebook.buck.util.xml.XmlDomParser;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import java.io.File;
import java.io.IOException;
import org.hamcrest.Matchers;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.w3c.dom.Node;
public class ProjectIntegrationTest {
@Rule public TemporaryPaths temporaryFolder = new TemporaryPaths();
@Before
public void setUp() throws Exception {
// These tests consistently fail on Windows due to path separator issues.
Assume.assumeFalse(Platform.detect() == Platform.WINDOWS);
}
@Test
public void testAndroidLibraryProject() throws InterruptedException, IOException {
runBuckProjectAndVerify("android_library");
}
@Test
public void testAndroidBinaryProject() throws InterruptedException, IOException {
runBuckProjectAndVerify("android_binary");
}
@Test
public void testVersion2BuckProject() throws InterruptedException, IOException {
runBuckProjectAndVerify("project1");
}
@Test
public void testVersion2BuckProjectWithoutAutogeneratingSources()
throws InterruptedException, IOException {
runBuckProjectAndVerify("project_without_autogeneration");
}
@Test
public void testVersion2BuckProjectSlice() throws InterruptedException, IOException {
runBuckProjectAndVerify("project_slice", "--without-tests", "modules/dep1:dep1");
}
@Test
public void testVersion2BuckProjectSourceMerging() throws InterruptedException, IOException {
runBuckProjectAndVerify("aggregation");
}
@Test
public void testBuckProjectWithCustomAndroidSdks() throws InterruptedException, IOException {
runBuckProjectAndVerify("project_with_custom_android_sdks");
}
@Test
public void testBuckProjectWithCustomJavaSdks() throws InterruptedException, IOException {
runBuckProjectAndVerify("project_with_custom_java_sdks");
}
@Test
public void testBuckProjectWithIntellijSdk() throws InterruptedException, IOException {
runBuckProjectAndVerify("project_with_intellij_sdk");
}
@Test
public void testVersion2BuckProjectWithProjectSettings()
throws InterruptedException, IOException {
runBuckProjectAndVerify("project_with_project_settings");
}
@Test
public void testVersion2BuckProjectWithScripts() throws InterruptedException, IOException {
runBuckProjectAndVerify("project_with_scripts", "//modules/dep1:dep1");
}
@Test
public void testVersion2BuckProjectWithUnusedLibraries() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "project_with_unused_libraries", temporaryFolder);
workspace.setUp();
ProcessResult result = workspace.runBuckCommand("project");
result.assertSuccess("buck project should exit cleanly");
assertFalse(workspace.resolve(".idea/libraries/library_libs_jsr305.xml").toFile().exists());
}
@Test
public void testVersion2BuckProjectWithExcludedResources()
throws InterruptedException, IOException {
runBuckProjectAndVerify("project_with_excluded_resources");
}
@Test
public void testVersion2BuckProjectWithAssets() throws InterruptedException, IOException {
runBuckProjectAndVerify("project_with_assets");
}
@Test
public void testVersion2BuckProjectWithLanguageLevel() throws InterruptedException, IOException {
runBuckProjectAndVerify("project_with_language_level");
}
@Test
public void testVersion2BuckProjectWithOutputUrl() throws InterruptedException, IOException {
runBuckProjectAndVerify("project_with_output_url");
}
@Test
public void testVersion2BuckProjectWithJavaResources() throws InterruptedException, IOException {
runBuckProjectAndVerify("project_with_java_resources");
}
public void testVersion2BuckProjectWithExtraOutputModules()
throws InterruptedException, IOException {
runBuckProjectAndVerify("project_with_extra_output_modules");
}
@Test
public void testVersion2BuckProjectWithGeneratedSources()
throws InterruptedException, IOException {
runBuckProjectAndVerify("project_with_generated_sources");
}
@Test
public void testBuckProjectWithSubdirGlobResources() throws InterruptedException, IOException {
runBuckProjectAndVerify("project_with_subdir_glob_resources");
}
@Test
public void testRobolectricTestRule() throws InterruptedException, IOException {
runBuckProjectAndVerify("robolectric_test");
}
@Test
public void testAndroidResourcesInDependencies() throws InterruptedException, IOException {
runBuckProjectAndVerify("project_with_android_resources");
}
@Test
public void testPrebuiltJarWithJavadoc() throws InterruptedException, IOException {
runBuckProjectAndVerify("project_with_prebuilt_jar");
}
@Test
public void testZipFile() throws InterruptedException, IOException {
runBuckProjectAndVerify("project_with_zipfile");
}
@Test
public void testAndroidResourcesAndLibraryInTheSameFolder()
throws InterruptedException, IOException {
runBuckProjectAndVerify("android_resources_in_the_same_folder");
}
@Test
public void testAndroidResourcesWithPackagesAtTheSameLocation()
throws InterruptedException, IOException {
runBuckProjectAndVerify("project_with_multiple_resources_with_package_names");
}
@Test
public void testCxxLibrary() throws InterruptedException, IOException {
runBuckProjectAndVerify("project_with_cxx_library");
}
@Test
public void testAggregatingCxxLibrary() throws InterruptedException, IOException {
runBuckProjectAndVerify("aggregation_with_cxx_library");
}
@Test
public void testSavingGeneratedFilesList() throws InterruptedException, IOException {
runBuckProjectAndVerify(
"save_generated_files_list",
"--file-with-list-of-generated-files",
".idea/generated-files.txt");
}
@Test
public void testMultipleLibraries() throws InterruptedException, IOException {
runBuckProjectAndVerify("project_with_multiple_libraries");
}
@Test
public void testProjectWithIgnoredTargets() throws InterruptedException, IOException {
runBuckProjectAndVerify("project_with_ignored_targets");
}
@Test
public void testProjectWithCustomPackages() throws InterruptedException, IOException {
runBuckProjectAndVerify("aggregation_with_custom_packages");
}
@Test
public void testAndroidResourceAggregation() throws InterruptedException, IOException {
runBuckProjectAndVerify("android_resource_aggregation");
}
@Test
public void testAndroidResourceAggregationWithLimit() throws InterruptedException, IOException {
runBuckProjectAndVerify("android_resource_aggregation_with_limit");
}
@Test
public void testProjectIncludesTestsByDefault() throws InterruptedException, IOException {
runBuckProjectAndVerify("project_with_tests_by_default", "//modules/lib:lib");
}
@Test
public void testProjectExcludesTestsWhenRequested() throws InterruptedException, IOException {
runBuckProjectAndVerify("project_without_tests", "--without-tests", "//modules/lib:lib");
}
@Test
public void testProjectExcludesDepTestsWhenRequested() throws InterruptedException, IOException {
runBuckProjectAndVerify(
"project_without_dep_tests", "--without-dependencies-tests", "//modules/lib:lib");
}
@Test
public void testUpdatingExistingWorkspace() throws InterruptedException, IOException {
runBuckProjectAndVerify("update_existing_workspace");
}
@Test
public void testCreateNewWorkspace() throws InterruptedException, IOException {
runBuckProjectAndVerify("create_new_workspace");
}
@Test
public void testUpdateMalformedWorkspace() throws InterruptedException, IOException {
runBuckProjectAndVerify("update_malformed_workspace");
}
@Test
public void testUpdateWorkspaceWithoutIgnoredNodes() throws InterruptedException, IOException {
runBuckProjectAndVerify("update_workspace_without_ignored_nodes");
}
@Test
public void testUpdateWorkspaceWithoutManagerNode() throws InterruptedException, IOException {
runBuckProjectAndVerify("update_workspace_without_manager_node");
}
@Test
public void testUpdateWorkspaceWithoutProjectNode() throws InterruptedException, IOException {
runBuckProjectAndVerify("update_workspace_without_project_node");
}
@Test
public void testProjectWthPackageBoundaryException() throws InterruptedException, IOException {
runBuckProjectAndVerify("project_with_package_boundary_exception", "//project2:lib");
}
@Test
public void testProjectWithProjectRoot() throws InterruptedException, IOException {
runBuckProjectAndVerify(
"project_with_project_root",
"--intellij-project-root",
"project1",
"--intellij-include-transitive-dependencies",
"--intellij-module-group-name",
"",
"//project1/lib:lib");
}
@Test
public void testGeneratingAndroidManifest() throws InterruptedException, IOException {
runBuckProjectAndVerify("generate_android_manifest");
}
@Test
public void testGeneratingAndroidManifestWithMinSdkWithDifferentVersionsFromManifest()
throws InterruptedException, IOException {
runBuckProjectAndVerify("min_sdk_version_different_from_manifests");
}
@Test
public void testGeneratingAndroidManifestWithMinSdkFromBinaryManifest()
throws InterruptedException, IOException {
runBuckProjectAndVerify("min_sdk_version_from_binary_manifest");
}
@Test
public void testGeneratingAndroidManifestWithMinSdkFromBuckConfig()
throws InterruptedException, IOException {
runBuckProjectAndVerify("min_sdk_version_from_buck_config");
}
@Test
public void testGeneratingAndroidManifestWithNoMinSdkConfig()
throws InterruptedException, IOException {
runBuckProjectAndVerify("min_sdk_version_with_no_config");
}
@Test
public void testPreprocessScript() throws InterruptedException, IOException {
ProcessResult result = runBuckProjectAndVerify("preprocess_script_test");
assertEquals("intellij", result.getStdout().trim());
}
@Test
public void testScalaProject() throws InterruptedException, IOException {
runBuckProjectAndVerify("scala_project");
}
@Test
public void testIgnoredPathAddedToExcludedFolders() throws InterruptedException, IOException {
runBuckProjectAndVerify("ignored_excluded");
}
@Test
public void testBuckModuleRegenerateSubproject() throws Exception {
AssumeAndroidPlatform.assumeSdkIsAvailable();
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "incrementalProject", temporaryFolder.newFolder())
.setUp();
final String extraModuleFilePath = "modules/extra/modules_extra.iml";
final File extraModuleFile = workspace.getPath(extraModuleFilePath).toFile();
workspace
.runBuckCommand("project", "--intellij-aggregation-mode=none", "//modules/tip:tip")
.assertSuccess();
assertFalse(extraModuleFile.exists());
final String modulesBefore = workspace.getFileContents(".idea/modules.xml");
final String fileXPath =
String.format(
"/project/component/modules/module[contains(@filepath,'%s')]", extraModuleFilePath);
assertThat(XmlDomParser.parse(modulesBefore), Matchers.not(Matchers.hasXPath(fileXPath)));
// Run regenerate on the new modules
workspace
.runBuckCommand(
"project", "--intellij-aggregation-mode=none", "--update", "//modules/extra:extra")
.assertSuccess();
assertTrue(extraModuleFile.exists());
final String modulesAfter = workspace.getFileContents(".idea/modules.xml");
assertThat(XmlDomParser.parse(modulesAfter), Matchers.hasXPath(fileXPath));
workspace.verify();
}
@Test
public void testBuckModuleRegenerateSubprojectNoOp() throws InterruptedException, IOException {
AssumeAndroidPlatform.assumeSdkIsAvailable();
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "incrementalProject", temporaryFolder.newFolder())
.setUp();
workspace
.runBuckCommand(
"project",
"--intellij-aggregation-mode=none",
"//modules/tip:tip",
"//modules/extra:extra")
.assertSuccess();
workspace.verify();
// Run regenerate, should be a no-op relative to previous
workspace
.runBuckCommand(
"project", "--intellij-aggregation-mode=none", "--update", "//modules/extra:extra")
.assertSuccess();
workspace.verify();
}
@Test
public void testCrossCellIntelliJProject() throws Exception {
AssumeAndroidPlatform.assumeSdkIsAvailable();
ProjectWorkspace primary =
TestDataHelper.createProjectWorkspaceForScenario(
this, "inter-cell/primary", temporaryFolder.newFolder());
primary.setUp();
ProjectWorkspace secondary =
TestDataHelper.createProjectWorkspaceForScenario(
this, "inter-cell/secondary", temporaryFolder.newFolder());
secondary.setUp();
TestDataHelper.overrideBuckconfig(
primary,
ImmutableMap.of(
"repositories",
ImmutableMap.of("secondary", secondary.getPath(".").normalize().toString())));
// First try with cross-cell enabled
String target = "//apps/sample:app_with_cross_cell_android_lib";
ProcessResult result =
primary.runBuckCommand(
"project",
"--config",
"project.embedded_cell_buck_out_enabled=true",
"--ide",
"intellij",
target);
result.assertSuccess();
String libImlPath = ".idea/libraries/secondary__java_com_crosscell_crosscell.xml";
Node doc = XmlDomParser.parse(primary.getFileContents(libImlPath));
String urlXpath = "/component/library/CLASSES/root/@url";
// Assert that the library URL is inside the project root
assertThat(
doc,
Matchers.hasXPath(
urlXpath, Matchers.startsWith("jar://$PROJECT_DIR$/buck-out/cells/secondary/gen/")));
result =
primary.runBuckCommand(
"project",
"--config",
"project.embedded_cell_buck_out_enabled=false",
"--ide",
"intellij",
target);
result.assertSuccess();
Node doc2 = XmlDomParser.parse(primary.getFileContents(libImlPath));
// Assert that the library URL is outside the project root
assertThat(doc2, Matchers.hasXPath(urlXpath, Matchers.startsWith("jar://$PROJECT_DIR$/..")));
}
private ProcessResult runBuckProjectAndVerify(String folderWithTestData, String... commandArgs)
throws InterruptedException, IOException {
AssumeAndroidPlatform.assumeSdkIsAvailable();
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, folderWithTestData, temporaryFolder);
workspace.setUp();
ProcessResult result =
workspace.runBuckCommand(Lists.asList("project", commandArgs).toArray(new String[0]));
result.assertSuccess("buck project should exit cleanly");
workspace.verify();
return result;
}
}
| clonetwin26/buck | test/com/facebook/buck/ide/intellij/ProjectIntegrationTest.java | Java | apache-2.0 | 16,432 |
/*
* Copyright 2016 John Grosh <[email protected]>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jagrosh.jmusicbot.commands;
import java.util.List;
import java.util.concurrent.TimeUnit;
import com.jagrosh.jdautilities.commandclient.CommandEvent;
import com.jagrosh.jdautilities.menu.pagination.PaginatorBuilder;
import com.jagrosh.jmusicbot.Bot;
import com.jagrosh.jmusicbot.audio.AudioHandler;
import com.jagrosh.jmusicbot.audio.QueuedTrack;
import com.jagrosh.jmusicbot.utils.FormatUtil;
import net.dv8tion.jda.core.Permission;
import net.dv8tion.jda.core.exceptions.PermissionException;
/**
*
* @author John Grosh <[email protected]>
*/
public class QueueCmd extends MusicCommand {
private final PaginatorBuilder builder;
public QueueCmd(Bot bot)
{
super(bot);
this.name = "queue";
this.help = "shows the current queue";
this.arguments = "[pagenum]";
this.aliases = new String[]{"list"};
this.bePlaying = true;
this.botPermissions = new Permission[]{Permission.MESSAGE_ADD_REACTION,Permission.MESSAGE_EMBED_LINKS};
builder = new PaginatorBuilder()
.setColumns(1)
.setFinalAction(m -> {try{m.clearReactions().queue();}catch(PermissionException e){}})
.setItemsPerPage(10)
.waitOnSinglePage(false)
.useNumberedItems(true)
.showPageNumbers(true)
.setEventWaiter(bot.getWaiter())
.setTimeout(1, TimeUnit.MINUTES)
;
}
@Override
public void doCommand(CommandEvent event) {
int pagenum = 1;
try{
pagenum = Integer.parseInt(event.getArgs());
}catch(NumberFormatException e){}
AudioHandler ah = (AudioHandler)event.getGuild().getAudioManager().getSendingHandler();
List<QueuedTrack> list = ah.getQueue().getList();
if(list.isEmpty())
{
event.replyWarning("There is no music in the queue!"
+(!ah.isMusicPlaying() ? "" : " Now playing:\n\n**"+ah.getPlayer().getPlayingTrack().getInfo().title+"**\n"+FormatUtil.embedformattedAudio(ah)));
return;
}
String[] songs = new String[list.size()];
long total = 0;
for(int i=0; i<list.size(); i++)
{
total += list.get(i).getTrack().getDuration();
songs[i] = list.get(i).toString();
}
long fintotal = total;
builder.setText((i1,i2) -> getQueueTitle(ah, event.getClient().getSuccess(), songs.length, fintotal))
.setItems(songs)
.setUsers(event.getAuthor())
.setColor(event.getSelfMember().getColor())
;
builder.build().paginate(event.getChannel(), pagenum);
}
private String getQueueTitle(AudioHandler ah, String success, int songslength, long total)
{
StringBuilder sb = new StringBuilder();
if(ah.getPlayer().getPlayingTrack()!=null)
sb.append("**").append(ah.getPlayer().getPlayingTrack().getInfo().title).append("**\n").append(FormatUtil.embedformattedAudio(ah)).append("\n\n");
return sb.append(success).append(" Current Queue | ").append(songslength).append(" entries | `").append(FormatUtil.formatTime(total)).append("` ").toString();
}
}
| Blankscar/NothingToSeeHere | src/main/java/com/jagrosh/jmusicbot/commands/QueueCmd.java | Java | apache-2.0 | 3,885 |
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.opsworks.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DeregisterEcsCluster" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DeregisterEcsClusterResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DeregisterEcsClusterResult == false)
return false;
DeregisterEcsClusterResult other = (DeregisterEcsClusterResult) obj;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
return hashCode;
}
@Override
public DeregisterEcsClusterResult clone() {
try {
return (DeregisterEcsClusterResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| jentfoo/aws-sdk-java | aws-java-sdk-opsworks/src/main/java/com/amazonaws/services/opsworks/model/DeregisterEcsClusterResult.java | Java | apache-2.0 | 2,373 |
package com.google.api.ads.adwords.jaxws.v201509.cm;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
*
* Represents a criterion belonging to a shared set.
*
*
* <p>Java class for SharedCriterion complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="SharedCriterion">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="sharedSetId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
* <element name="criterion" type="{https://adwords.google.com/api/adwords/cm/v201509}Criterion" minOccurs="0"/>
* <element name="negative" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SharedCriterion", propOrder = {
"sharedSetId",
"criterion",
"negative"
})
public class SharedCriterion {
protected Long sharedSetId;
protected Criterion criterion;
protected Boolean negative;
/**
* Gets the value of the sharedSetId property.
*
* @return
* possible object is
* {@link Long }
*
*/
public Long getSharedSetId() {
return sharedSetId;
}
/**
* Sets the value of the sharedSetId property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setSharedSetId(Long value) {
this.sharedSetId = value;
}
/**
* Gets the value of the criterion property.
*
* @return
* possible object is
* {@link Criterion }
*
*/
public Criterion getCriterion() {
return criterion;
}
/**
* Sets the value of the criterion property.
*
* @param value
* allowed object is
* {@link Criterion }
*
*/
public void setCriterion(Criterion value) {
this.criterion = value;
}
/**
* Gets the value of the negative property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isNegative() {
return negative;
}
/**
* Sets the value of the negative property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setNegative(Boolean value) {
this.negative = value;
}
}
| gawkermedia/googleads-java-lib | modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201509/cm/SharedCriterion.java | Java | apache-2.0 | 2,764 |
package de.choesel.blechwiki.model;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import java.util.UUID;
/**
* Created by christian on 05.05.16.
*/
@DatabaseTable(tableName = "komponist")
public class Komponist {
@DatabaseField(generatedId = true)
private UUID id;
@DatabaseField(canBeNull = true, uniqueCombo = true)
private String name;
@DatabaseField(canBeNull = true)
private String kurzname;
@DatabaseField(canBeNull = true, uniqueCombo = true)
private Integer geboren;
@DatabaseField(canBeNull = true)
private Integer gestorben;
public UUID getId() {
return id;
}
public String getName() {
return name;
}
public String getKurzname() {
return kurzname;
}
public Integer getGeboren() {
return geboren;
}
public Integer getGestorben() {
return gestorben;
}
public void setId(UUID id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setKurzname(String kurzname) {
this.kurzname = kurzname;
}
public void setGeboren(Integer geboren) {
this.geboren = geboren;
}
public void setGestorben(Integer gestorben) {
this.gestorben = gestorben;
}
}
| ChristianHoesel/android-blechwiki | app/src/main/java/de/choesel/blechwiki/model/Komponist.java | Java | apache-2.0 | 1,341 |
package org.judal.examples.java.model.array;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.jdo.JDOException;
import org.judal.storage.DataSource;
import org.judal.storage.EngineFactory;
import org.judal.storage.java.ArrayRecord;
import org.judal.storage.relational.RelationalDataSource;
/**
* Extend ArrayRecord in order to create model classes manageable by JUDAL.
* Add your getters and setters for database fields.
*/
public class Student extends ArrayRecord {
private static final long serialVersionUID = 1L;
public static final String TABLE_NAME = "student";
public Student() throws JDOException {
this(EngineFactory.getDefaultRelationalDataSource());
}
public Student(RelationalDataSource dataSource) throws JDOException {
super(dataSource, TABLE_NAME);
}
@Override
public void store(DataSource dts) throws JDOException {
// Generate the student Id. from a sequence if it is not provided
if (isNull("id_student"))
setId ((int) dts.getSequence("seq_student").nextValue());
super.store(dts);
}
public int getId() {
return getInt("id_student");
}
public void setId(final int id) {
put("id_student", id);
}
public String getFirstName() {
return getString("first_name");
}
public void setFirstName(final String firstName) {
put("first_name", firstName);
}
public String getLastName() {
return getString("last_name");
}
public void setLastName(final String lastName) {
put("last_name", lastName);
}
public Calendar getDateOfBirth() {
return getCalendar("date_of_birth");
}
public void setDateOfBirth(final Calendar dob) {
put("date_of_birth", dob);
}
public void setDateOfBirth(final String yyyyMMdd) throws ParseException {
SimpleDateFormat dobFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = new GregorianCalendar();
cal.setTime(dobFormat.parse(yyyyMMdd));
setDateOfBirth(cal);
}
public byte[] getPhoto() {
return getBytes("photo");
}
public void setPhoto(final byte[] photoData) {
put("photo", photoData);
}
}
| sergiomt/judal | aexample/src/main/java/org/judal/examples/java/model/array/Student.java | Java | apache-2.0 | 2,209 |
/*
* Copyright 2011-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.http.apache.client.impl;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.http.settings.HttpClientSettings;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ApacheConnectionManagerFactoryTest {
private final ApacheConnectionManagerFactory factory = new ApacheConnectionManagerFactory();
@Test
public void validateAfterInactivityMillis_RespectedInConnectionManager() {
final int validateAfterInactivity = 1234;
final HttpClientSettings httpClientSettings =
HttpClientSettings.adapt(new ClientConfiguration()
.withValidateAfterInactivityMillis(validateAfterInactivity));
final PoolingHttpClientConnectionManager connectionManager =
(PoolingHttpClientConnectionManager) factory.create(httpClientSettings);
assertEquals(validateAfterInactivity, connectionManager.getValidateAfterInactivity());
}
} | dagnir/aws-sdk-java | aws-java-sdk-core/src/test/java/com/amazonaws/http/apache/client/impl/ApacheConnectionManagerFactoryTest.java | Java | apache-2.0 | 1,653 |
package org.spincast.core.routing;
import java.util.List;
import org.spincast.core.exchange.RequestContext;
/**
* The result of the router, when asked to find matches for
* a request.
*/
public interface RoutingResult<R extends RequestContext<?>> {
/**
* The handlers matching the route (a main handler + filters, if any),
* in order they have to be called.
*/
public List<RouteHandlerMatch<R>> getRouteHandlerMatches();
/**
* The main route handler and its information, from the routing result.
*/
public RouteHandlerMatch<R> getMainRouteHandlerMatch();
}
| spincast/spincast-framework | spincast-core-parent/spincast-core/src/main/java/org/spincast/core/routing/RoutingResult.java | Java | apache-2.0 | 609 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package king.flow.common;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import java.io.File;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import king.flow.action.business.ShowClockAction;
import king.flow.data.TLSResult;
import king.flow.view.Action;
import king.flow.view.Action.CleanAction;
import king.flow.view.Action.EjectCardAction;
import king.flow.view.Action.WithdrawCardAction;
import king.flow.view.Action.EncryptKeyboardAction;
import king.flow.view.Action.HideAction;
import king.flow.view.Action.InsertICardAction;
import king.flow.view.Action.LimitInputAction;
import king.flow.view.Action.MoveCursorAction;
import king.flow.view.Action.NumericPadAction;
import king.flow.view.Action.OpenBrowserAction;
import king.flow.view.Action.PlayMediaAction;
import king.flow.view.Action.PlayVideoAction;
import king.flow.view.Action.PrintPassbookAction;
import king.flow.view.Action.RunCommandAction;
import king.flow.view.Action.RwFingerPrintAction;
import king.flow.view.Action.SetFontAction;
import king.flow.view.Action.SetPrinterAction;
import king.flow.view.Action.ShowComboBoxAction;
import king.flow.view.Action.ShowGridAction;
import king.flow.view.Action.ShowTableAction;
import king.flow.view.Action.Swipe2In1CardAction;
import king.flow.view.Action.SwipeCardAction;
import king.flow.view.Action.UploadFileAction;
import king.flow.view.Action.UseTipAction;
import king.flow.view.Action.VirtualKeyboardAction;
import king.flow.view.Action.WriteICardAction;
import king.flow.view.ComponentEnum;
import king.flow.view.DefinedAction;
import king.flow.view.DeviceEnum;
import king.flow.view.JumpAction;
import king.flow.view.MsgSendAction;
/**
*
* @author LiuJin
*/
public class CommonConstants {
public static final String APP_STARTUP_ENTRY = "bank.exe";
public static final Charset UTF8 = Charset.forName("UTF-8");
static final File[] SYS_ROOTS = File.listRoots();
public static final int DRIVER_COUNT = SYS_ROOTS.length;
public static final String XML_NODE_PREFIX = "N_";
public static final String REVERT = "re_";
public static final String BID = "bid";
public static final String UID_PREFIX = "<" + TLSResult.UID + ">";
public static final String UID_AFFIX = "</" + TLSResult.UID + ">";
public static final String DEFAULT_DATE_FORMATE = "yyyy-MM-dd";
public static final String VALID_BANK_CARD = "validBankCard";
public static final String BALANCED_PAY_MAC = "balancedPayMAC";
public static final String CANCEL_ENCRYPTION_KEYBOARD = "[CANCEL]";
public static final String QUIT_ENCRYPTION_KEYBOARD = "[QUIT]";
public static final String INVALID_ENCRYPTION_LENGTH = "encryption.keyboard.type.length.prompt";
public static final String TIMEOUT_ENCRYPTION_TYPE = "encryption.keyboard.type.timeout.prompt";
public static final String ERROR_ENCRYPTION_TYPE = "encryption.keyboard.type.fail.prompt";
public static final int CONTAINER_KEY = Integer.MAX_VALUE;
public static final int NORMAL = 0;
public static final int ABNORMAL = 1;
public static final int BALANCE = 12345;
public static final int RESTART_SIGNAL = 1;
public static final int DOWNLOAD_KEY_SIGNAL = 1;
public static final int UPDATE_SIGNAL = 1;
public static final int WATCHDOG_CHECK_INTERVAL = 5;
public static final String VERSION;
public static final long DEBUG_MODE_PROGRESS_TIME = TimeUnit.SECONDS.toMillis(3);
public static final long RUN_MODE_PROGRESS_TIME = TimeUnit.SECONDS.toMillis(1);
// public static final String VERSION = Paths.get(".").toAbsolutePath().normalize().toString();
static {
String workingPath = System.getProperty("user.dir");
final int lastIndexOf = workingPath.lastIndexOf('_');
if (lastIndexOf != -1 && lastIndexOf < workingPath.length() - 1) {
VERSION = workingPath.substring(lastIndexOf + 1);
} else {
VERSION = "Unknown";
}
}
/* JMX configuration */
private static String getJmxRmiUrl(int port) {
return "service:jmx:rmi:///jndi/rmi://localhost:" + port + "/jmxrmi";
}
public static final int APP_JMX_RMI_PORT = 9998;
public static final String APP_JMX_RMI_URL = getJmxRmiUrl(APP_JMX_RMI_PORT);
public static final int WATCHDOG_JMX_RMI_PORT = 9999;
public static final String WATCHDOG_JMX_RMI_URL = getJmxRmiUrl(WATCHDOG_JMX_RMI_PORT);
/* system variable pattern */
public static final String SYSTEM_VAR_PATTERN = "\\$\\{(_?\\p{Alpha}+_\\p{Alpha}+)+\\}";
public static final String TEXT_MINGLED_SYSTEM_VAR_PATTERN = ".*" + SYSTEM_VAR_PATTERN + ".*";
public static final String TERMINAL_ID_SYS_VAR = "TERMINAL_ID";
/* swing default config */
public static final int DEFAULT_TABLE_ROW_COUNT = 15;
public static final int TABLE_ROW_HEIGHT = 25;
public static final int DEFAULT_VIDEO_REPLAY_INTERVAL_SECOND = 20;
/* packet header ID */
public static final int GENERAL_MSG_CODE = 0; //common message
public static final int REGISTRY_MSG_CODE = 1; //terminal registration message
public static final int KEY_DOWNLOAD_MSG_CODE = 2; //download secret key message
public static final int MANAGER_MSG_CODE = 100; //management message
/*MAX_MESSAGES_PER_READ refers to DefaultChannelConfig, AdaptiveRecvByteBufAllocator, FixedRecvByteBufAllocator */
public static final int MAX_MESSAGES_PER_READ = 64; //how many read actions in one message conversation
public static final int MIN_RECEIVED_BUFFER_SIZE = 1024; //1024 bytes
public static final int RECEIVED_BUFFER_SIZE = 32 * 1024; //32k bytes
public static final int MAX_RECEIVED_BUFFER_SIZE = 64 * 1024; //64k bytes
/* keyboard cipher key */
public static final String WORK_SECRET_KEY = "workSecretKey";
public static final String MA_KEY = "maKey";
public static final String MASTER_KEY = "masterKey";
/* packet result flag */
public static final int SUCCESSFUL_MSG_CODE = 0;
/* xml jaxb context */
public static final String NET_CONF_PACKAGE_CONTEXT = "king.flow.net";
public static final String TLS_PACKAGE_CONTEXT = "king.flow.data";
public static final String UI_CONF_PACKAGE_CONTEXT = "king.flow.view";
public static final String KING_FLOW_BACKGROUND = "king.flow.background";
public static final String KING_FLOW_PROGRESS = "king.flow.progress";
public static final String TEXT_TYPE_TOOL_CONFIG = "chinese.text.type.config";
public static final String COMBOBOX_ITEMS_PROPERTY_PATTERN = "([^,/]*/[^,/]*,)*+([^,/]*/[^,/]*){1}+";
public static final String ADVANCED_TABLE_TOTAL_PAGES = "total";
public static final String ADVANCED_TABLE_VALUE = "value";
public static final String ADVANCED_TABLE_CURRENT_PAGE = "current";
/* card-reading state */
public static final int INVALID_CARD_STATE = -1;
public static final int MAGNET_CARD_STATE = 2;
public static final int IC_CARD_STATE = 3;
/* union-pay transaction type */
public static final String UNION_PAY_REGISTRATION = "1";
public static final String UNION_PAY_TRANSACTION = "3";
public static final String UNION_PAY_TRANSACTION_BALANCE = "4";
/* card affiliation type */
public static final String CARD_AFFILIATION_INTERNAL = "1";
public static final String CARD_AFFILIATION_EXTERNAL = "2";
/* supported driver types */
static final ImmutableSet<DeviceEnum> SUPPORTED_DEVICES = new ImmutableSet.Builder<DeviceEnum>()
.add(DeviceEnum.IC_CARD)
.add(DeviceEnum.CASH_SAVER)
.add(DeviceEnum.GZ_CARD)
.add(DeviceEnum.HIS_CARD)
.add(DeviceEnum.KEYBOARD)
.add(DeviceEnum.MAGNET_CARD)
.add(DeviceEnum.MEDICARE_CARD)
.add(DeviceEnum.PATIENT_CARD)
.add(DeviceEnum.PID_CARD)
.add(DeviceEnum.PKG_8583)
.add(DeviceEnum.PRINTER)
.add(DeviceEnum.SENSOR_CARD)
.add(DeviceEnum.TWO_IN_ONE_CARD)
.build();
/* action-component relationship map */
public static final String JUMP_ACTION = JumpAction.class.getSimpleName();
public static final String SET_FONT_ACTION = SetFontAction.class.getSimpleName();
public static final String CLEAN_ACTION = CleanAction.class.getSimpleName();
public static final String HIDE_ACTION = HideAction.class.getSimpleName();
public static final String USE_TIP_ACTION = UseTipAction.class.getSimpleName();
public static final String PLAY_MEDIA_ACTION = PlayMediaAction.class.getSimpleName();
public static final String SEND_MSG_ACTION = MsgSendAction.class.getSimpleName();
public static final String MOVE_CURSOR_ACTION = MoveCursorAction.class.getSimpleName();
public static final String LIMIT_INPUT_ACTION = LimitInputAction.class.getSimpleName();
public static final String SHOW_COMBOBOX_ACTION = ShowComboBoxAction.class.getSimpleName();
public static final String SHOW_TABLE_ACTION = ShowTableAction.class.getSimpleName();
public static final String SHOW_CLOCK_ACTION = ShowClockAction.class.getSimpleName();
public static final String OPEN_BROWSER_ACTION = OpenBrowserAction.class.getSimpleName();
public static final String RUN_COMMAND_ACTION = RunCommandAction.class.getSimpleName();
public static final String OPEN_VIRTUAL_KEYBOARD_ACTION = VirtualKeyboardAction.class.getSimpleName();
public static final String PRINT_RECEIPT_ACTION = SetPrinterAction.class.getSimpleName();
public static final String INSERT_IC_ACTION = InsertICardAction.class.getSimpleName();
public static final String WRITE_IC_ACTION = WriteICardAction.class.getSimpleName();
public static final String BALANCE_TRANS_ACTION = "BalanceTransAction";
public static final String PRINT_PASSBOOK_ACTION = PrintPassbookAction.class.getSimpleName();
public static final String UPLOAD_FILE_ACTION = UploadFileAction.class.getSimpleName();
public static final String SWIPE_CARD_ACTION = SwipeCardAction.class.getSimpleName();
public static final String SWIPE_TWO_IN_ONE_CARD_ACTION = Swipe2In1CardAction.class.getSimpleName();
public static final String EJECT_CARD_ACTION = EjectCardAction.class.getSimpleName();
public static final String WITHDRAW_CARD_ACTION = WithdrawCardAction.class.getSimpleName();
public static final String READ_WRITE_FINGERPRINT_ACTION = RwFingerPrintAction.class.getSimpleName();
public static final String PLAY_VIDEO_ACTION = PlayVideoAction.class.getSimpleName();
public static final String CUSTOMIZED_ACTION = DefinedAction.class.getSimpleName();
public static final String ENCRYPT_KEYBORAD_ACTION = EncryptKeyboardAction.class.getSimpleName();
public static final String SHOW_GRID_ACTION = ShowGridAction.class.getSimpleName();
public static final String TYPE_NUMERIC_PAD_ACTION = NumericPadAction.class.getSimpleName();
public static final String WEB_LOAD_ACTION = Action.WebLoadAction.class.getSimpleName();
static final Map<ComponentEnum, List<String>> ACTION_COMPONENT_MAP = new ImmutableMap.Builder<ComponentEnum, List<String>>()
.put(ComponentEnum.BUTTON, new ImmutableList.Builder<String>()
.add(CUSTOMIZED_ACTION)
.add(JUMP_ACTION)
.add(SET_FONT_ACTION)
.add(CLEAN_ACTION)
.add(HIDE_ACTION)
.add(USE_TIP_ACTION)
.add(PLAY_MEDIA_ACTION)
.add(OPEN_BROWSER_ACTION)
.add(RUN_COMMAND_ACTION)
.add(OPEN_VIRTUAL_KEYBOARD_ACTION)
.add(PRINT_RECEIPT_ACTION)
.add(SEND_MSG_ACTION)
.add(INSERT_IC_ACTION)
.add(WRITE_IC_ACTION)
.add(MOVE_CURSOR_ACTION)
.add(PRINT_PASSBOOK_ACTION)
.add(UPLOAD_FILE_ACTION)
.add(BALANCE_TRANS_ACTION)
.add(EJECT_CARD_ACTION)
.add(WITHDRAW_CARD_ACTION)
.add(WEB_LOAD_ACTION)
.build())
.put(ComponentEnum.COMBO_BOX, new ImmutableList.Builder<String>()
.add(CUSTOMIZED_ACTION)
.add(SET_FONT_ACTION)
.add(USE_TIP_ACTION)
.add(SHOW_COMBOBOX_ACTION)
.add(SWIPE_CARD_ACTION)
.add(SWIPE_TWO_IN_ONE_CARD_ACTION)
.add(PLAY_MEDIA_ACTION)
.add(MOVE_CURSOR_ACTION)
.build())
.put(ComponentEnum.LABEL, new ImmutableList.Builder<String>()
.add(CUSTOMIZED_ACTION)
.add(SET_FONT_ACTION)
.add(USE_TIP_ACTION)
.add(SHOW_CLOCK_ACTION)
.build())
.put(ComponentEnum.TEXT_FIELD, new ImmutableList.Builder<String>()
.add(CUSTOMIZED_ACTION)
.add(SET_FONT_ACTION)
.add(LIMIT_INPUT_ACTION)
.add(USE_TIP_ACTION)
.add(PLAY_MEDIA_ACTION)
.add(READ_WRITE_FINGERPRINT_ACTION)
.add(OPEN_VIRTUAL_KEYBOARD_ACTION)
.add(MOVE_CURSOR_ACTION)
.build())
.put(ComponentEnum.PASSWORD_FIELD, new ImmutableList.Builder<String>()
.add(CUSTOMIZED_ACTION)
.add(SET_FONT_ACTION)
.add(LIMIT_INPUT_ACTION)
.add(USE_TIP_ACTION)
.add(PLAY_MEDIA_ACTION)
.add(READ_WRITE_FINGERPRINT_ACTION)
.add(MOVE_CURSOR_ACTION)
.add(ENCRYPT_KEYBORAD_ACTION)
.build())
.put(ComponentEnum.TABLE, new ImmutableList.Builder<String>()
.add(CUSTOMIZED_ACTION)
.add(SET_FONT_ACTION)
.add(USE_TIP_ACTION)
.add(SHOW_TABLE_ACTION)
.build())
.put(ComponentEnum.ADVANCED_TABLE, new ImmutableList.Builder<String>()
.add(CUSTOMIZED_ACTION)
.add(SET_FONT_ACTION)
.add(SHOW_TABLE_ACTION)
.add(SEND_MSG_ACTION)
.build())
.put(ComponentEnum.VIDEO_PLAYER, new ImmutableList.Builder<String>()
.add(CUSTOMIZED_ACTION)
.add(PLAY_VIDEO_ACTION)
.build())
.put(ComponentEnum.GRID, new ImmutableList.Builder<String>()
.add(SHOW_GRID_ACTION)
.build())
.put(ComponentEnum.NUMERIC_PAD, new ImmutableList.Builder<String>()
.add(TYPE_NUMERIC_PAD_ACTION)
.build())
.build();
}
| toyboxman/yummy-xml-UI | xml-UI/src/main/java/king/flow/common/CommonConstants.java | Java | apache-2.0 | 15,275 |
package ca.qc.bergeron.marcantoine.crammeur.android.repository.crud.sqlite;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import ca.qc.bergeron.marcantoine.crammeur.librairy.annotations.Entity;
import ca.qc.bergeron.marcantoine.crammeur.librairy.exceptions.KeyException;
import ca.qc.bergeron.marcantoine.crammeur.android.models.Client;
import ca.qc.bergeron.marcantoine.crammeur.android.repository.crud.SQLiteTemplate;
import ca.qc.bergeron.marcantoine.crammeur.librairy.repository.i.Repository;
/**
* Created by Marc-Antoine on 2017-01-11.
*/
public final class SQLiteClient extends SQLiteTemplate<Client,Integer> implements ca.qc.bergeron.marcantoine.crammeur.android.repository.crud.sqlite.i.SQLiteClient {
public SQLiteClient(Repository pRepository, Context context) {
super(Client.class,Integer.class,pRepository, context);
}
@Override
protected Client convertCursorToEntity(@NonNull Cursor pCursor) {
Client o = new Client();
o.Id = pCursor.getInt(pCursor.getColumnIndex(mId.getAnnotation(Entity.Id.class).name()));
o.Name = pCursor.getString(pCursor.getColumnIndex(F_CLIENT_NAME));
o.EMail = pCursor.getString(pCursor.getColumnIndex(F_CLIENT_EMAIL));
return o;
}
@Override
protected Integer convertCursorToId(@NonNull Cursor pCursor) {
Integer result;
result = pCursor.getInt(pCursor.getColumnIndex(mId.getAnnotation(Entity.Id.class).name()));
return result;
}
@Override
public void create() {
mDB.execSQL(CREATE_TABLE_CLIENTS);
}
@NonNull
@Override
public Integer save(@NonNull Client pData) throws KeyException {
ContentValues values = new ContentValues();
try {
if (pData.Id == null) {
pData.Id = this.getKey(pData);
}
values.put(mId.getAnnotation(Entity.Id.class).name(), mKey.cast(mId.get(pData)));
values.put(F_CLIENT_NAME, pData.Name);
values.put(F_CLIENT_EMAIL, pData.EMail);
if (mId.get(pData) == null || !this.contains(mKey.cast(mId.get(pData)))) {
mId.set(pData, (int) mDB.insert(T_CLIENTS, null, values));
} else {
mDB.update(T_CLIENTS, values, mId.getAnnotation(Entity.Id.class).name() + "=?", new String[]{String.valueOf(pData.Id)});
}
return pData.Id;
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
@Nullable
@Override
public Integer getKey(@NonNull Client pEntity) {
Integer result = null;
try {
if (mId.get(pEntity) != null) return (Integer) mId.get(pEntity);
String[] columns = new String[] {F_ID};
String where = "LOWER(" + F_CLIENT_NAME + ")=LOWER(?) AND LOWER(" + F_CLIENT_EMAIL + ")=LOWER(?)";
String[] whereArgs = new String[] {pEntity.Name,pEntity.EMail};
// limit 1 row = "1";
Cursor cursor = mDB.query(T_CLIENTS, columns, where, whereArgs, null, null, null, "1");
if (cursor.moveToFirst()) {
result = cursor.getInt(cursor.getColumnIndex(F_ID));
}
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return result;
}
}
| crammeur/MyInvoices | crammeurAndroid/src/main/java/ca/qc/bergeron/marcantoine/crammeur/android/repository/crud/sqlite/SQLiteClient.java | Java | apache-2.0 | 3,537 |
/*
* Copyright 2015 - 2021 TU Dortmund
*
* 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 de.learnlib.alex.learning.services;
import de.learnlib.alex.data.entities.ProjectEnvironment;
import de.learnlib.alex.data.entities.ProjectUrl;
import de.learnlib.alex.data.entities.actions.Credentials;
import java.util.HashMap;
import java.util.Map;
/**
* Class to mange a URL and get URL based on this.
*/
public class BaseUrlManager {
private final Map<String, ProjectUrl> urlMap;
/** Advanced constructor which sets the base url field. */
public BaseUrlManager(ProjectEnvironment environment) {
this.urlMap = new HashMap<>();
environment.getUrls().forEach(u -> this.urlMap.put(u.getName(), u));
}
/**
* Get the absolute URL of a path, i.e. based on the base url (base url + '/' + path'), as String
* and insert the credentials if possible.
*
* @param path
* The path to append on the base url.
* @param credentials
* The credentials to insert into the URL.
* @return An absolute URL as String
*/
public String getAbsoluteUrl(String urlName, String path, Credentials credentials) {
final String url = combineUrls(urlMap.get(urlName).getUrl(), path);
return BaseUrlManager.getUrlWithCredentials(url, credentials);
}
public String getAbsoluteUrl(String urlName, String path) {
final String url = combineUrls(urlMap.get(urlName).getUrl(), path);
return BaseUrlManager.getUrlWithCredentials(url, null);
}
/**
* Append apiPath to basePath and make sure that only one '/' is between them.
*
* @param basePath
* The prefix of the new URL.
* @param apiPath
* The suffix of the new URL.
* @return The combined URL.
*/
private String combineUrls(String basePath, String apiPath) {
if (basePath.endsWith("/") && apiPath.startsWith("/")) {
// both have a '/' -> remove one
return basePath + apiPath.substring(1);
} else if (!basePath.endsWith("/") && !apiPath.startsWith("/")) {
// no one has a '/' -> add one
return basePath + "/" + apiPath;
} else {
// exact 1. '/' in between -> good to go
return basePath + apiPath;
}
}
private static String getUrlWithCredentials(String url, Credentials credentials) {
if (credentials != null && credentials.areValid()) {
return url.replaceFirst("^(http[s]?://)", "$1"
+ credentials.getName() + ":"
+ credentials.getPassword() + "@");
} else {
return url;
}
}
}
| LearnLib/alex | backend/src/main/java/de/learnlib/alex/learning/services/BaseUrlManager.java | Java | apache-2.0 | 3,225 |
/*
* Copyright 2015 Cognitive Medical Systems, Inc (http://www.cognitivemedciine.com).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.socraticgrid.hl7.services.orders.model.types.orderitems;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.socraticgrid.hl7.services.orders.model.OrderItem;
import org.socraticgrid.hl7.services.orders.model.primatives.Code;
import org.socraticgrid.hl7.services.orders.model.primatives.Identifier;
import org.socraticgrid.hl7.services.orders.model.primatives.Period;
import org.socraticgrid.hl7.services.orders.model.primatives.Quantity;
import org.socraticgrid.hl7.services.orders.model.primatives.Ratio;
public class MedicationOrderItem extends OrderItem
{
/**
*
*/
private static final long serialVersionUID = 1L;
private String additionalDosageIntructions;
private String comment;
private Quantity dispenseQuantity= new Quantity();
private String dosageInstructions;
private Code dosageMethod;
private Quantity dosageQuantity = new Quantity();
private Ratio dosageRate = new Ratio();
private Code dosageSite = new Code();
private Date dosageTiming;
private Period dosageTimingPeriod = new Period();
private List<Identifier> drug = new ArrayList<Identifier>(0);
private Date endDate;
private Quantity expectedSupplyDuration = new Quantity();
private Ratio maxDosePerPeriod = new Ratio();
private List<Identifier> medication = new ArrayList<Identifier>(0);
private int numberOfRepeatsAllowed=0;
private Code prescriber;
private Code route = new Code();
private String schedule;
private Date startDate;
/**
* @return the additionalDosageIntructions
*/
public String getAdditionalDosageIntructions() {
return additionalDosageIntructions;
}
/**
* @return the comment
*/
public String getComment() {
return comment;
}
/**
* @return the dispenseQuantity
*/
public Quantity getDispenseQuantity() {
return dispenseQuantity;
}
/**
* @return the dosageInstructions
*/
public String getDosageInstructions() {
return dosageInstructions;
}
/**
* @return the dosageMethod
*/
public Code getDosageMethod() {
return dosageMethod;
}
/**
* @return the dosageQuantity
*/
public Quantity getDosageQuantity() {
return dosageQuantity;
}
/**
* @return the dosageRate
*/
public Ratio getDosageRate() {
return dosageRate;
}
/**
* @return the dosageSite
*/
public Code getDosageSite() {
return dosageSite;
}
/**
* @return the dosageTiming
*/
public Date getDosageTiming() {
return dosageTiming;
}
/**
* @return the dosageTimingPeriod
*/
public Period getDosageTimingPeriod() {
return dosageTimingPeriod;
}
/**
* @return the drug
*/
public List<Identifier> getDrug() {
return drug;
}
/**
* @return the endDate
*/
public Date getEndDate() {
return endDate;
}
/**
* @return the expectedSupplyDuration
*/
public Quantity getExpectedSupplyDuration() {
return expectedSupplyDuration;
}
/**
* @return the maxDosePerPeriod
*/
public Ratio getMaxDosePerPeriod() {
return maxDosePerPeriod;
}
/**
* @return the medication
*/
public List<Identifier> getMedication() {
return medication;
}
/**
* @return the numberOfRepeatsAllowed
*/
public int getNumberOfRepeatsAllowed() {
return numberOfRepeatsAllowed;
}
/**
* @return the prescriber
*/
public Code getPrescriber() {
return prescriber;
}
/**
* @return the route
*/
public Code getRoute() {
return route;
}
/**
* @return the schedule
*/
public String getSchedule() {
return schedule;
}
/**
* @return the startDate
*/
public Date getStartDate() {
return startDate;
}
/**
* @param additionalDosageIntructions the additionalDosageIntructions to set
*/
public void setAdditionalDosageIntructions(String additionalDosageIntructions) {
this.additionalDosageIntructions = additionalDosageIntructions;
}
/**
* @param comment the comment to set
*/
public void setComment(String comment) {
this.comment = comment;
}
/**
* @param dispenseQuantity the dispenseQuantity to set
*/
public void setDispenseQuantity(Quantity dispenseQuantity) {
this.dispenseQuantity = dispenseQuantity;
}
/**
* @param dosageInstructions the dosageInstructions to set
*/
public void setDosageInstructions(String dosageInstructions) {
this.dosageInstructions = dosageInstructions;
}
/**
* @param dosageMethod the dosageMethod to set
*/
public void setDosageMethod(Code dosageMethod) {
this.dosageMethod = dosageMethod;
}
/**
* @param dosageQuantity the dosageQuantity to set
*/
public void setDosageQuantity(Quantity dosageQuantity) {
this.dosageQuantity = dosageQuantity;
}
/**
* @param dosageRate the dosageRate to set
*/
public void setDosageRate(Ratio dosageRate) {
this.dosageRate = dosageRate;
}
/**
* @param dosageSite the dosageSite to set
*/
public void setDosageSite(Code dosageSite) {
this.dosageSite = dosageSite;
}
/**
* @param dosageTiming the dosageTiming to set
*/
public void setDosageTiming(Date dosageTiming) {
this.dosageTiming = dosageTiming;
}
/**
* @param dosageTimingPeriod the dosageTimingPeriod to set
*/
public void setDosageTimingPeriod(Period dosageTimingPeriod) {
this.dosageTimingPeriod = dosageTimingPeriod;
}
/**
* @param drug the drug to set
*/
public void setDrug(List<Identifier> drug) {
this.drug = drug;
}
/**
* @param endDate the endDate to set
*/
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
/**
* @param expectedSupplyDuration the expectedSupplyDuration to set
*/
public void setExpectedSupplyDuration(Quantity expectedSupplyDuration) {
this.expectedSupplyDuration = expectedSupplyDuration;
}
/**
* @param maxDosePerPeriod the maxDosePerPeriod to set
*/
public void setMaxDosePerPeriod(Ratio maxDosePerPeriod) {
this.maxDosePerPeriod = maxDosePerPeriod;
}
/**
* @param medication the medication to set
*/
public void setMedication(List<Identifier> medication) {
this.medication = medication;
}
/**
* @param numberOfRepeatsAllowed the numberOfRepeatsAllowed to set
*/
public void setNumberOfRepeatsAllowed(int numberOfRepeatsAllowed) {
this.numberOfRepeatsAllowed = numberOfRepeatsAllowed;
}
/**
* @param prescriber the prescriber to set
*/
public void setPrescriber(Code prescriber) {
this.prescriber = prescriber;
}
/**
* @param route the route to set
*/
public void setRoute(Code route) {
this.route = route;
}
/**
* @param schedule the schedule to set
*/
public void setSchedule(String schedule) {
this.schedule = schedule;
}
/**
* @param startDate the startDate to set
*/
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
}
| SocraticGrid/OMS-API | src/main/java/org/socraticgrid/hl7/services/orders/model/types/orderitems/MedicationOrderItem.java | Java | apache-2.0 | 7,408 |
package gui;
//: gui/SubmitLabelManipulationTask.java
import javax.swing.*;
import java.util.concurrent.*;
public class SubmitLabelManipulationTask {
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame("Hello Swing");
final JLabel label = new JLabel("A Label");
frame.add(label);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 100);
frame.setVisible(true);
TimeUnit.SECONDS.sleep(1);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
label.setText("Hey! This is Different!");
}
});
}
} ///:~
| vowovrz/thinkinj | thinkinj/src/main/java/gui/SubmitLabelManipulationTask.java | Java | apache-2.0 | 646 |
/**
* Copyright 2006-2015 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.mybatis.generator.codegen.ibatis2.dao.elements;
import java.util.Set;
import java.util.TreeSet;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.Interface;
import org.mybatis.generator.api.dom.java.JavaVisibility;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.Parameter;
import org.mybatis.generator.api.dom.java.TopLevelClass;
/**
*
* @author Jeff Butler
*
*/
public class UpdateByExampleWithoutBLOBsMethodGenerator extends
AbstractDAOElementGenerator {
public UpdateByExampleWithoutBLOBsMethodGenerator() {
super();
}
@Override
public void addImplementationElements(TopLevelClass topLevelClass) {
Set<FullyQualifiedJavaType> importedTypes = new TreeSet<FullyQualifiedJavaType>();
Method method = getMethodShell(importedTypes);
method
.addBodyLine("UpdateByExampleParms parms = new UpdateByExampleParms(record, example);"); //$NON-NLS-1$
StringBuilder sb = new StringBuilder();
sb.append("int rows = "); //$NON-NLS-1$
sb.append(daoTemplate.getUpdateMethod(introspectedTable
.getIbatis2SqlMapNamespace(), introspectedTable
.getUpdateByExampleStatementId(), "parms")); //$NON-NLS-1$
method.addBodyLine(sb.toString());
method.addBodyLine("return rows;"); //$NON-NLS-1$
if (context.getPlugins()
.clientUpdateByExampleWithoutBLOBsMethodGenerated(method,
topLevelClass, introspectedTable)) {
topLevelClass.addImportedTypes(importedTypes);
topLevelClass.addMethod(method);
}
}
@Override
public void addInterfaceElements(Interface interfaze) {
if (getExampleMethodVisibility() == JavaVisibility.PUBLIC) {
Set<FullyQualifiedJavaType> importedTypes = new TreeSet<FullyQualifiedJavaType>();
Method method = getMethodShell(importedTypes);
if (context.getPlugins()
.clientUpdateByExampleWithoutBLOBsMethodGenerated(method,
interfaze, introspectedTable)) {
interfaze.addImportedTypes(importedTypes);
interfaze.addMethod(method);
}
}
}
private Method getMethodShell(Set<FullyQualifiedJavaType> importedTypes) {
FullyQualifiedJavaType parameterType;
if (introspectedTable.getRules().generateBaseRecordClass()) {
parameterType = new FullyQualifiedJavaType(introspectedTable
.getBaseRecordType());
} else {
parameterType = new FullyQualifiedJavaType(introspectedTable
.getPrimaryKeyType());
}
importedTypes.add(parameterType);
Method method = new Method();
method.setVisibility(getExampleMethodVisibility());
method.setReturnType(FullyQualifiedJavaType.getIntInstance());
method.setName(getDAOMethodNameCalculator()
.getUpdateByExampleWithoutBLOBsMethodName(introspectedTable));
method.addParameter(new Parameter(parameterType, "record")); //$NON-NLS-1$
method.addParameter(new Parameter(new FullyQualifiedJavaType(
introspectedTable.getExampleType()), "example")); //$NON-NLS-1$
for (FullyQualifiedJavaType fqjt : daoTemplate.getCheckedExceptions()) {
method.addException(fqjt);
importedTypes.add(fqjt);
}
context.getCommentGenerator().addGeneralMethodComment(method,
introspectedTable);
return method;
}
}
| li24361/mybatis-generator-core | src/main/java/org/mybatis/generator/codegen/ibatis2/dao/elements/UpdateByExampleWithoutBLOBsMethodGenerator.java | Java | apache-2.0 | 4,329 |
package jp.teraparser.transition;
import java.util.Arrays;
/**
* Resizable-array implementation of Deque which works like java.util.ArrayDeque
*
* jp.teraparser.util
*
* @author Hiroki Teranishi
*/
public class Stack implements Cloneable {
private static final int MIN_INITIAL_CAPACITY = 8;
private int[] elements;
private int head;
private int tail;
/**
* Allocates empty array to hold the given number of elements.
*/
private void allocateElements(int numElements) {
int initialCapacity = MIN_INITIAL_CAPACITY;
// Find the best power of two to hold elements.
// Tests "<=" because arrays aren't kept full.
if (numElements >= initialCapacity) {
initialCapacity = numElements;
initialCapacity |= (initialCapacity >>> 1);
initialCapacity |= (initialCapacity >>> 2);
initialCapacity |= (initialCapacity >>> 4);
initialCapacity |= (initialCapacity >>> 8);
initialCapacity |= (initialCapacity >>> 16);
initialCapacity++;
if (initialCapacity < 0) { // Too many elements, must back off
initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements
}
}
elements = new int[initialCapacity];
}
/**
* Doubles the capacity of this deque. Call only when full, i.e.,
* when head and tail have wrapped around to become equal.
*/
private void doubleCapacity() {
assert head == tail;
int p = head;
int n = elements.length;
int r = n - p; // number of elements to the right of p
int newCapacity = n << 1;
if (newCapacity < 0) {
throw new IllegalStateException("Sorry, deque too big");
}
int[] a = new int[newCapacity];
System.arraycopy(elements, p, a, 0, r);
System.arraycopy(elements, 0, a, r, p);
elements = a;
head = 0;
tail = n;
}
public Stack() {
elements = new int[16];
}
public Stack(int numElements) {
allocateElements(numElements);
}
public void push(int e) {
elements[head = (head - 1) & (elements.length - 1)] = e;
if (head == tail) {
doubleCapacity();
}
}
public int pop() {
int h = head;
int result = elements[h];
elements[h] = 0;
head = (h + 1) & (elements.length - 1);
return result;
}
public int top() {
return elements[head];
}
public int getFirst() {
return top();
}
public int get(int position, int defaultValue) {
if (position < 0 || position >= size()) {
return defaultValue;
}
int mask = elements.length - 1;
int h = head;
for (int i = 0; i < position; i++) {
h = (h + 1) & mask;
}
return elements[h];
}
public int size() {
return (tail - head) & (elements.length - 1);
}
public boolean isEmpty() {
return head == tail;
}
public Stack clone() {
try {
Stack result = (Stack) super.clone();
result.elements = Arrays.copyOf(elements, elements.length);
return result;
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
}
| chantera/teraparser | src/jp/teraparser/transition/Stack.java | Java | apache-2.0 | 3,381 |
package ppp.menu;
import java.awt.image.BufferedImage;
public abstract interface Menu {
public abstract void up();
public abstract void down();
public abstract void enter();
public abstract void escape();
public abstract BufferedImage getImage();
}
| mzijlstra/java-games | ppp/menu/Menu.java | Java | apache-2.0 | 256 |
/*
*
*/
package org.utilities;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
// TODO: Auto-generated Javadoc
/**
* The Class CUtils.
*/
public class CUtils {
/**
* Work.
*
* @param task
* the task
* @return the object
*/
public static Object work(Callable<?> task) {
Future<?> futureTask = es.submit(task);
return futureTask;
}
/**
* Gets the random string.
*
* @param rndSeed the rnd seed
* @return the random string
*/
public static String getRandomString(double rndSeed) {
MessageDigest m;
try {
m = MessageDigest.getInstance("MD5");
byte[] data = ("" + rndSeed).getBytes();
m.update(data, 0, data.length);
BigInteger i = new BigInteger(1, m.digest());
return String.format("%1$032X", i);
} catch (NoSuchAlgorithmException e) {
}
return "" + rndSeed;
}
/**
* Gets the random number.
*
* @param s the s
* @return the random number
* @throws Exception the exception
*/
public static int getRandomNumber(String s) throws Exception {
MessageDigest m;
try {
m = MessageDigest.getInstance("MD5");
byte[] data = s.getBytes();
m.update(data, 0, data.length);
BigInteger i = new BigInteger(1, m.digest());
return i.intValue();
} catch (NoSuchAlgorithmException e) {
}
throw new Exception("Cannot generate random number");
}
/** The Constant es. */
private final static ExecutorService es = Executors.newCachedThreadPool();
/**
* Instantiates a new c utils.
*/
private CUtils() {
}
}
| sarathrami/Chain-Replication | src/org/utilities/CUtils.java | Java | apache-2.0 | 1,735 |
/* Copyright 2020 Telstra Open Source
*
* 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.openkilda.floodlight.switchmanager;
import static java.util.Collections.singletonList;
import static org.projectfloodlight.openflow.protocol.OFVersion.OF_12;
import static org.projectfloodlight.openflow.protocol.OFVersion.OF_13;
import net.floodlightcontroller.core.IOFSwitch;
import net.floodlightcontroller.util.FlowModUtils;
import org.projectfloodlight.openflow.protocol.OFFactory;
import org.projectfloodlight.openflow.protocol.OFFlowMod;
import org.projectfloodlight.openflow.protocol.OFMeterFlags;
import org.projectfloodlight.openflow.protocol.OFMeterMod;
import org.projectfloodlight.openflow.protocol.OFMeterModCommand;
import org.projectfloodlight.openflow.protocol.action.OFAction;
import org.projectfloodlight.openflow.protocol.action.OFActions;
import org.projectfloodlight.openflow.protocol.instruction.OFInstruction;
import org.projectfloodlight.openflow.protocol.instruction.OFInstructionApplyActions;
import org.projectfloodlight.openflow.protocol.meterband.OFMeterBandDrop;
import org.projectfloodlight.openflow.protocol.oxm.OFOxms;
import org.projectfloodlight.openflow.types.DatapathId;
import org.projectfloodlight.openflow.types.EthType;
import org.projectfloodlight.openflow.types.MacAddress;
import org.projectfloodlight.openflow.types.OFBufferId;
import org.projectfloodlight.openflow.types.OFPort;
import org.projectfloodlight.openflow.types.OFVlanVidMatch;
import org.projectfloodlight.openflow.types.TableId;
import org.projectfloodlight.openflow.types.TransportPort;
import org.projectfloodlight.openflow.types.U64;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
/**
* Utils for switch flow generation.
*/
public final class SwitchFlowUtils {
/**
* OVS software switch manufacturer constant value.
*/
public static final String OVS_MANUFACTURER = "Nicira, Inc.";
/**
* Indicates the maximum size in bytes for a packet which will be send from switch to the controller.
*/
private static final int MAX_PACKET_LEN = 0xFFFFFFFF;
private SwitchFlowUtils() {
}
/**
* Create a MAC address based on the DPID.
*
* @param dpId switch object
* @return {@link MacAddress}
*/
public static MacAddress convertDpIdToMac(DatapathId dpId) {
return MacAddress.of(Arrays.copyOfRange(dpId.getBytes(), 2, 8));
}
/**
* Create sent to controller OpenFlow action.
*
* @param ofFactory OpenFlow factory
* @return OpenFlow Action
*/
public static OFAction actionSendToController(OFFactory ofFactory) {
OFActions actions = ofFactory.actions();
return actions.buildOutput().setMaxLen(MAX_PACKET_LEN).setPort(OFPort.CONTROLLER)
.build();
}
/**
* Create an OFAction which sets the output port.
*
* @param ofFactory OF factory for the switch
* @param outputPort port to set in the action
* @return {@link OFAction}
*/
public static OFAction actionSetOutputPort(final OFFactory ofFactory, final OFPort outputPort) {
OFActions actions = ofFactory.actions();
return actions.buildOutput().setMaxLen(MAX_PACKET_LEN).setPort(outputPort).build();
}
/**
* Create go to table OFInstruction.
*
* @param ofFactory OF factory for the switch
* @param tableId tableId to go
* @return {@link OFAction}
*/
public static OFInstruction instructionGoToTable(final OFFactory ofFactory, final TableId tableId) {
return ofFactory.instructions().gotoTable(tableId);
}
/**
* Create an OFInstructionApplyActions which applies actions.
*
* @param ofFactory OF factory for the switch
* @param actionList OFAction list to apply
* @return {@link OFInstructionApplyActions}
*/
public static OFInstructionApplyActions buildInstructionApplyActions(OFFactory ofFactory,
List<OFAction> actionList) {
return ofFactory.instructions().applyActions(actionList).createBuilder().build();
}
/**
* Create set destination MAC address OpenFlow action.
*
* @param ofFactory OpenFlow factory
* @param macAddress MAC address to set
* @return OpenFlow Action
*/
public static OFAction actionSetDstMac(OFFactory ofFactory, final MacAddress macAddress) {
OFOxms oxms = ofFactory.oxms();
OFActions actions = ofFactory.actions();
return actions.buildSetField()
.setField(oxms.buildEthDst().setValue(macAddress).build()).build();
}
/**
* Create set source MAC address OpenFlow action.
*
* @param ofFactory OpenFlow factory
* @param macAddress MAC address to set
* @return OpenFlow Action
*/
public static OFAction actionSetSrcMac(OFFactory ofFactory, final MacAddress macAddress) {
return ofFactory.actions().buildSetField()
.setField(ofFactory.oxms().ethSrc(macAddress)).build();
}
/**
* Create set UDP source port OpenFlow action.
*
* @param ofFactory OpenFlow factory
* @param srcPort UDP src port to set
* @return OpenFlow Action
*/
public static OFAction actionSetUdpSrcAction(OFFactory ofFactory, TransportPort srcPort) {
OFOxms oxms = ofFactory.oxms();
return ofFactory.actions().setField(oxms.udpSrc(srcPort));
}
/**
* Create set UDP destination port OpenFlow action.
*
* @param ofFactory OpenFlow factory
* @param dstPort UDP dst port to set
* @return OpenFlow Action
*/
public static OFAction actionSetUdpDstAction(OFFactory ofFactory, TransportPort dstPort) {
OFOxms oxms = ofFactory.oxms();
return ofFactory.actions().setField(oxms.udpDst(dstPort));
}
/**
* Create OpenFlow flow modification command builder.
*
* @param ofFactory OpenFlow factory
* @param cookie cookie
* @param priority priority
* @param tableId table id
* @return OpenFlow command builder
*/
public static OFFlowMod.Builder prepareFlowModBuilder(OFFactory ofFactory, long cookie, int priority,
int tableId) {
OFFlowMod.Builder fmb = ofFactory.buildFlowAdd();
fmb.setIdleTimeout(FlowModUtils.INFINITE_TIMEOUT);
fmb.setHardTimeout(FlowModUtils.INFINITE_TIMEOUT);
fmb.setBufferId(OFBufferId.NO_BUFFER);
fmb.setCookie(U64.of(cookie));
fmb.setPriority(priority);
fmb.setTableId(TableId.of(tableId));
return fmb;
}
/**
* Create OpenFlow meter modification command.
*
* @param ofFactory OpenFlow factory
* @param bandwidth bandwidth
* @param burstSize burst size
* @param meterId meter id
* @param flags flags
* @param commandType ADD, MODIFY or DELETE
* @return OpenFlow command
*/
public static OFMeterMod buildMeterMod(OFFactory ofFactory, long bandwidth, long burstSize,
long meterId, Set<OFMeterFlags> flags, OFMeterModCommand commandType) {
OFMeterBandDrop.Builder bandBuilder = ofFactory.meterBands()
.buildDrop()
.setRate(bandwidth)
.setBurstSize(burstSize);
OFMeterMod.Builder meterModBuilder = ofFactory.buildMeterMod()
.setMeterId(meterId)
.setCommand(commandType)
.setFlags(flags);
if (ofFactory.getVersion().compareTo(OF_13) > 0) {
meterModBuilder.setBands(singletonList(bandBuilder.build()));
} else {
meterModBuilder.setMeters(singletonList(bandBuilder.build()));
}
return meterModBuilder.build();
}
/**
* Create an OFAction to add a VLAN header.
*
* @param ofFactory OF factory for the switch
* @param etherType ethernet type of the new VLAN header
* @return {@link OFAction}
*/
public static OFAction actionPushVlan(final OFFactory ofFactory, final int etherType) {
OFActions actions = ofFactory.actions();
return actions.buildPushVlan().setEthertype(EthType.of(etherType)).build();
}
/**
* Create an OFAction to change the outer most vlan.
*
* @param factory OF factory for the switch
* @param newVlan final VLAN to be set on the packet
* @return {@link OFAction}
*/
public static OFAction actionReplaceVlan(final OFFactory factory, final int newVlan) {
OFOxms oxms = factory.oxms();
OFActions actions = factory.actions();
if (OF_12.compareTo(factory.getVersion()) == 0) {
return actions.buildSetField().setField(oxms.buildVlanVid()
.setValue(OFVlanVidMatch.ofRawVid((short) newVlan))
.build()).build();
} else {
return actions.buildSetField().setField(oxms.buildVlanVid()
.setValue(OFVlanVidMatch.ofVlan(newVlan))
.build()).build();
}
}
/**
* Check switch is OVS.
*
* @param sw switch
* @return true if switch is OVS
*/
public static boolean isOvs(IOFSwitch sw) {
return OVS_MANUFACTURER.equals(sw.getSwitchDescription().getManufacturerDescription());
}
}
| telstra/open-kilda | src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/switchmanager/SwitchFlowUtils.java | Java | apache-2.0 | 9,966 |
/* Generated by camel build tools - do NOT edit this file! */
package org.apache.camel.component.nats;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.spi.GeneratedPropertyConfigurer;
import org.apache.camel.spi.PropertyConfigurerGetter;
import org.apache.camel.util.CaseInsensitiveMap;
import org.apache.camel.support.component.PropertyConfigurerSupport;
/**
* Generated by camel build tools - do NOT edit this file!
*/
@SuppressWarnings("unchecked")
public class NatsComponentConfigurer extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
private static final Map<String, Object> ALL_OPTIONS;
static {
Map<String, Object> map = new CaseInsensitiveMap();
map.put("servers", java.lang.String.class);
map.put("verbose", boolean.class);
map.put("bridgeErrorHandler", boolean.class);
map.put("lazyStartProducer", boolean.class);
map.put("basicPropertyBinding", boolean.class);
map.put("useGlobalSslContextParameters", boolean.class);
ALL_OPTIONS = map;
}
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
NatsComponent target = (NatsComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "basicpropertybinding":
case "basicPropertyBinding": target.setBasicPropertyBinding(property(camelContext, boolean.class, value)); return true;
case "bridgeerrorhandler":
case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true;
case "lazystartproducer":
case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
case "servers": target.setServers(property(camelContext, java.lang.String.class, value)); return true;
case "useglobalsslcontextparameters":
case "useGlobalSslContextParameters": target.setUseGlobalSslContextParameters(property(camelContext, boolean.class, value)); return true;
case "verbose": target.setVerbose(property(camelContext, boolean.class, value)); return true;
default: return false;
}
}
@Override
public Map<String, Object> getAllOptions(Object target) {
return ALL_OPTIONS;
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
NatsComponent target = (NatsComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "basicpropertybinding":
case "basicPropertyBinding": return target.isBasicPropertyBinding();
case "bridgeerrorhandler":
case "bridgeErrorHandler": return target.isBridgeErrorHandler();
case "lazystartproducer":
case "lazyStartProducer": return target.isLazyStartProducer();
case "servers": return target.getServers();
case "useglobalsslcontextparameters":
case "useGlobalSslContextParameters": return target.isUseGlobalSslContextParameters();
case "verbose": return target.isVerbose();
default: return null;
}
}
}
| alvinkwekel/camel | components/camel-nats/src/generated/java/org/apache/camel/component/nats/NatsComponentConfigurer.java | Java | apache-2.0 | 3,229 |
package ruboweb.pushetta.back.model;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.jpa.domain.AbstractPersistable;
@Entity
@Table(name = "user")
public class User extends AbstractPersistable<Long> {
private static final Logger logger = LoggerFactory.getLogger(User.class);
private static final long serialVersionUID = 6088280461151862299L;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String token;
public User() {
}
public User(String name) {
this.name = name;
this.token = this.generateToken();
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name
* the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the token
*/
public String getToken() {
return token;
}
/**
* @param token
* the token to set
*/
public void setToken(String token) {
this.token = token;
}
private String generateToken() {
try {
SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");
String randomNum = new Integer(prng.nextInt()).toString();
MessageDigest sha = MessageDigest.getInstance("SHA-1");
byte[] bytes = sha.digest(randomNum.getBytes());
StringBuilder result = new StringBuilder();
char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f' };
byte b;
for (int idx = 0; idx < bytes.length; ++idx) {
b = bytes[idx];
result.append(digits[(b & 240) >> 4]);
result.append(digits[b & 15]);
}
return result.toString();
} catch (NoSuchAlgorithmException ex) {
logger.error("generateToken() -- " + ex.getMessage());
}
return null;
}
}
| ruboweb/pushetta | src/main/java/ruboweb/pushetta/back/model/User.java | Java | apache-2.0 | 2,054 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// 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: 2016.10.09 at 10:10:23 AM CST
//
package com.elong.nb.model.elong;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import java.util.List;
import com.alibaba.fastjson.annotation.JSONField;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for CommentResult complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="CommentResult">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Count" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="Comments" type="{}ArrayOfCommentInfo" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "CommentResult", propOrder = {
"count",
"comments"
})
public class CommentResult {
@JSONField(name = "Count")
protected int count;
@JSONField(name = "Comments")
protected List<CommentInfo> comments;
/**
* Gets the value of the count property.
*
*/
public int getCount() {
return count;
}
/**
* Sets the value of the count property.
*
*/
public void setCount(int value) {
this.count = value;
}
/**
* Gets the value of the comments property.
*
* @return
* possible object is
* {@link List<CommentInfo> }
*
*/
public List<CommentInfo> getComments() {
return comments;
}
/**
* Sets the value of the comments property.
*
* @param value
* allowed object is
* {@link List<CommentInfo> }
*
*/
public void setComments(List<CommentInfo> value) {
this.comments = value;
}
}
| Gaonaifeng/eLong-OpenAPI-H5-demo | nb_demo_h5/src/main/java/com/elong/nb/model/elong/CommentResult.java | Java | apache-2.0 | 2,314 |
// Copyright 2014 The Serviced 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.zenoss.app.annotations;
import org.springframework.stereotype.Component;
/**
* Mark an object as an API implementation.
*/
@Component
public @interface API {
}
| zenoss/zenoss-zapp | java/zenoss-app/src/main/java/org/zenoss/app/annotations/API.java | Java | apache-2.0 | 773 |
/*
* Copyright 2021 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.ads.googleads.v9.services;
import com.google.ads.googleads.v9.resources.OperatingSystemVersionConstant;
import com.google.ads.googleads.v9.services.stub.OperatingSystemVersionConstantServiceStubSettings;
import com.google.api.core.ApiFunction;
import com.google.api.core.BetaApi;
import com.google.api.gax.core.GoogleCredentialsProvider;
import com.google.api.gax.core.InstantiatingExecutorProvider;
import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider;
import com.google.api.gax.rpc.ApiClientHeaderProvider;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.ClientSettings;
import com.google.api.gax.rpc.StubSettings;
import com.google.api.gax.rpc.TransportChannelProvider;
import com.google.api.gax.rpc.UnaryCallSettings;
import java.io.IOException;
import java.util.List;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* Settings class to configure an instance of {@link OperatingSystemVersionConstantServiceClient}.
*
* <p>The default instance has everything set to sensible defaults:
*
* <ul>
* <li> The default service address (googleads.googleapis.com) and default port (443) are used.
* <li> Credentials are acquired automatically through Application Default Credentials.
* <li> Retries are configured for idempotent methods but not for non-idempotent methods.
* </ul>
*
* <p>The builder of this class is recursive, so contained classes are themselves builders. When
* build() is called, the tree of builders is called to create the complete settings object.
*
* <p>For example, to set the total timeout of getOperatingSystemVersionConstant to 30 seconds:
*
* <pre>{@code
* OperatingSystemVersionConstantServiceSettings.Builder
* operatingSystemVersionConstantServiceSettingsBuilder =
* OperatingSystemVersionConstantServiceSettings.newBuilder();
* operatingSystemVersionConstantServiceSettingsBuilder
* .getOperatingSystemVersionConstantSettings()
* .setRetrySettings(
* operatingSystemVersionConstantServiceSettingsBuilder
* .getOperatingSystemVersionConstantSettings()
* .getRetrySettings()
* .toBuilder()
* .setTotalTimeout(Duration.ofSeconds(30))
* .build());
* OperatingSystemVersionConstantServiceSettings operatingSystemVersionConstantServiceSettings =
* operatingSystemVersionConstantServiceSettingsBuilder.build();
* }</pre>
*/
@Generated("by gapic-generator-java")
public class OperatingSystemVersionConstantServiceSettings
extends ClientSettings<OperatingSystemVersionConstantServiceSettings> {
/** Returns the object with the settings used for calls to getOperatingSystemVersionConstant. */
public UnaryCallSettings<GetOperatingSystemVersionConstantRequest, OperatingSystemVersionConstant>
getOperatingSystemVersionConstantSettings() {
return ((OperatingSystemVersionConstantServiceStubSettings) getStubSettings())
.getOperatingSystemVersionConstantSettings();
}
public static final OperatingSystemVersionConstantServiceSettings create(
OperatingSystemVersionConstantServiceStubSettings stub) throws IOException {
return new OperatingSystemVersionConstantServiceSettings.Builder(stub.toBuilder()).build();
}
/** Returns a builder for the default ExecutorProvider for this service. */
public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() {
return OperatingSystemVersionConstantServiceStubSettings.defaultExecutorProviderBuilder();
}
/** Returns the default service endpoint. */
public static String getDefaultEndpoint() {
return OperatingSystemVersionConstantServiceStubSettings.getDefaultEndpoint();
}
/** Returns the default service scopes. */
public static List<String> getDefaultServiceScopes() {
return OperatingSystemVersionConstantServiceStubSettings.getDefaultServiceScopes();
}
/** Returns a builder for the default credentials for this service. */
public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() {
return OperatingSystemVersionConstantServiceStubSettings.defaultCredentialsProviderBuilder();
}
/** Returns a builder for the default ChannelProvider for this service. */
public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() {
return OperatingSystemVersionConstantServiceStubSettings.defaultGrpcTransportProviderBuilder();
}
public static TransportChannelProvider defaultTransportChannelProvider() {
return OperatingSystemVersionConstantServiceStubSettings.defaultTransportChannelProvider();
}
@BetaApi("The surface for customizing headers is not stable yet and may change in the future.")
public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() {
return OperatingSystemVersionConstantServiceStubSettings
.defaultApiClientHeaderProviderBuilder();
}
/** Returns a new builder for this class. */
public static Builder newBuilder() {
return Builder.createDefault();
}
/** Returns a new builder for this class. */
public static Builder newBuilder(ClientContext clientContext) {
return new Builder(clientContext);
}
/** Returns a builder containing all the values of this settings class. */
public Builder toBuilder() {
return new Builder(this);
}
protected OperatingSystemVersionConstantServiceSettings(Builder settingsBuilder)
throws IOException {
super(settingsBuilder);
}
/** Builder for OperatingSystemVersionConstantServiceSettings. */
public static class Builder
extends ClientSettings.Builder<OperatingSystemVersionConstantServiceSettings, Builder> {
protected Builder() throws IOException {
this(((ClientContext) null));
}
protected Builder(ClientContext clientContext) {
super(OperatingSystemVersionConstantServiceStubSettings.newBuilder(clientContext));
}
protected Builder(OperatingSystemVersionConstantServiceSettings settings) {
super(settings.getStubSettings().toBuilder());
}
protected Builder(OperatingSystemVersionConstantServiceStubSettings.Builder stubSettings) {
super(stubSettings);
}
private static Builder createDefault() {
return new Builder(OperatingSystemVersionConstantServiceStubSettings.newBuilder());
}
public OperatingSystemVersionConstantServiceStubSettings.Builder getStubSettingsBuilder() {
return ((OperatingSystemVersionConstantServiceStubSettings.Builder) getStubSettings());
}
/**
* Applies the given settings updater function to all of the unary API methods in this service.
*
* <p>Note: This method does not support applying settings to streaming methods.
*/
public Builder applyToAllUnaryMethods(
ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) {
super.applyToAllUnaryMethods(
getStubSettingsBuilder().unaryMethodSettingsBuilders(), settingsUpdater);
return this;
}
/** Returns the builder for the settings used for calls to getOperatingSystemVersionConstant. */
public UnaryCallSettings.Builder<
GetOperatingSystemVersionConstantRequest, OperatingSystemVersionConstant>
getOperatingSystemVersionConstantSettings() {
return getStubSettingsBuilder().getOperatingSystemVersionConstantSettings();
}
@Override
public OperatingSystemVersionConstantServiceSettings build() throws IOException {
return new OperatingSystemVersionConstantServiceSettings(this);
}
}
}
| googleads/google-ads-java | google-ads-stubs-v9/src/main/java/com/google/ads/googleads/v9/services/OperatingSystemVersionConstantServiceSettings.java | Java | apache-2.0 | 8,198 |
/*
* Copyright 2016 Atanas Stoychev Kanchev
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.atanas.kanchev.testframework.appium.tests.android.browser_tests;
import io.appium.java_client.remote.AndroidMobileCapabilityType;
import io.appium.java_client.remote.MobileBrowserType;
import io.appium.java_client.remote.MobileCapabilityType;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Platform;
import org.openqa.selenium.ScreenOrientation;
import static com.atanas.kanchev.testframework.appium.accessors.AppiumAccessors.$appium;
import static com.atanas.kanchev.testframework.selenium.accessors.SeleniumAccessors.$selenium;
public class ChromeTest {
@Test public void androidChromeTest() throws Exception {
$appium().init().buildDefaultService();
$appium().init().startServer();
$appium().init()
.setCap(MobileCapabilityType.BROWSER_NAME, MobileBrowserType.CHROME)
.setCap(MobileCapabilityType.PLATFORM, Platform.ANDROID)
.setCap(MobileCapabilityType.DEVICE_NAME, "ZY22398GL7")
.setCap(MobileCapabilityType.PLATFORM_VERSION, "6.0.1")
.setCap(MobileCapabilityType.NEW_COMMAND_TIMEOUT, 60)
.setCap(MobileCapabilityType.FULL_RESET, false)
.setCap(AndroidMobileCapabilityType.ANDROID_DEVICE_READY_TIMEOUT, 60)
.setCap(AndroidMobileCapabilityType.ENABLE_PERFORMANCE_LOGGING, true);
$appium().init().getAndroidDriver();
$selenium().goTo("https://bbc.co.uk");
$selenium().find().elementBy(By.id("idcta-link"));
$appium().android().orientation().rotate(ScreenOrientation.LANDSCAPE);
}
}
| atanaskanchev/hybrid-test-framework | test-framework-appium/src/test/java/com/atanas/kanchev/testframework/appium/tests/android/browser_tests/ChromeTest.java | Java | apache-2.0 | 2,204 |
/*
* Copyright 2006-2016 Edward Smith
*
* 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 root.json;
import root.lang.StringExtractor;
/**
*
* @author Edward Smith
* @version 0.5
* @since 0.5
*/
final class JSONBoolean extends JSONValue {
// <><><><><><><><><><><><><>< Class Attributes ><><><><><><><><><><><><><>
private final boolean value;
// <><><><><><><><><><><><><><>< Constructors ><><><><><><><><><><><><><><>
JSONBoolean(final boolean value) {
this.value = value;
}
// <><><><><><><><><><><><><><> Public Methods <><><><><><><><><><><><><><>
@Override
public final void extract(final StringExtractor chars) {
chars.append(this.value);
}
} // End JSONBoolean
| macvelli/RootFramework | src/root/json/JSONBoolean.java | Java | apache-2.0 | 1,215 |
package uk.co.listpoint.context;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for Context6Type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="Context6Type">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="Data Standard"/>
* <enumeration value="Application"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "Context6Type", namespace = "http://www.listpoint.co.uk/schemas/v6")
@XmlEnum
public enum Context6Type {
@XmlEnumValue("Data Standard")
DATA_STANDARD("Data Standard"),
@XmlEnumValue("Application")
APPLICATION("Application");
private final String value;
Context6Type(String v) {
value = v;
}
public String value() {
return value;
}
public static Context6Type fromValue(String v) {
for (Context6Type c: Context6Type.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
| davidcarboni/listpoint-ws | src/main/java/uk/co/listpoint/context/Context6Type.java | Java | apache-2.0 | 1,238 |
package com.example.customviewdemo;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class DragViewActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drag_view);
}
}
| jianghang/CustomViewDemo | src/com/example/customviewdemo/DragViewActivity.java | Java | apache-2.0 | 354 |
package com.gentics.mesh.core.schema.field;
import static com.gentics.mesh.assertj.MeshAssertions.assertThat;
import static com.gentics.mesh.core.field.FieldSchemaCreator.CREATEBINARY;
import static com.gentics.mesh.core.field.FieldSchemaCreator.CREATEBOOLEAN;
import static com.gentics.mesh.core.field.FieldSchemaCreator.CREATEBOOLEANLIST;
import static com.gentics.mesh.core.field.FieldSchemaCreator.CREATEDATE;
import static com.gentics.mesh.core.field.FieldSchemaCreator.CREATEDATELIST;
import static com.gentics.mesh.core.field.FieldSchemaCreator.CREATEHTML;
import static com.gentics.mesh.core.field.FieldSchemaCreator.CREATEHTMLLIST;
import static com.gentics.mesh.core.field.FieldSchemaCreator.CREATEMICRONODE;
import static com.gentics.mesh.core.field.FieldSchemaCreator.CREATEMICRONODELIST;
import static com.gentics.mesh.core.field.FieldSchemaCreator.CREATENODE;
import static com.gentics.mesh.core.field.FieldSchemaCreator.CREATENODELIST;
import static com.gentics.mesh.core.field.FieldSchemaCreator.CREATENUMBER;
import static com.gentics.mesh.core.field.FieldSchemaCreator.CREATENUMBERLIST;
import static com.gentics.mesh.core.field.FieldSchemaCreator.CREATESTRING;
import static com.gentics.mesh.core.field.FieldSchemaCreator.CREATESTRINGLIST;
import static com.gentics.mesh.core.field.FieldTestHelper.NOOP;
import static com.gentics.mesh.test.ElasticsearchTestMode.TRACKING;
import static com.gentics.mesh.test.TestSize.FULL;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import org.junit.Test;
import com.gentics.mesh.FieldUtil;
import com.gentics.mesh.core.data.node.field.HibHtmlField;
import com.gentics.mesh.core.field.html.HtmlFieldTestHelper;
import com.gentics.mesh.test.MeshTestSetting;
import com.gentics.mesh.util.IndexOptionHelper;
@MeshTestSetting(elasticsearch = TRACKING, testSize = FULL, startServer = false)
public class HtmlFieldMigrationTest extends AbstractFieldMigrationTest implements HtmlFieldTestHelper {
@Test
@Override
public void testRemove() throws Exception {
removeField(CREATEHTML, FILLTEXT, FETCH);
}
@Test
@Override
public void testChangeToBinary() throws Exception {
changeType(CREATEHTML, FILLTEXT, FETCH, CREATEBINARY, (container, name) -> {
assertThat(container.getBinary(name)).as(NEWFIELD).isNull();
});
}
@Test
@Override
public void testEmptyChangeToBinary() throws Exception {
changeType(CREATEHTML, NOOP, FETCH, CREATEBINARY, (container, name) -> {
assertThat(container.getBinary(name)).as(NEWFIELD).isNull();
});
}
@Test
@Override
public void testChangeToBoolean() throws Exception {
changeType(CREATEHTML, FILLTRUE, FETCH, CREATEBOOLEAN, (container, name) -> {
assertThat(container.getBoolean(name)).as(NEWFIELD).isNotNull();
assertThat(container.getBoolean(name).getBoolean()).as(NEWFIELDVALUE).isEqualTo(true);
});
changeType(CREATEHTML, FILLFALSE, FETCH, CREATEBOOLEAN, (container, name) -> {
assertThat(container.getBoolean(name)).as(NEWFIELD).isNotNull();
assertThat(container.getBoolean(name).getBoolean()).as(NEWFIELDVALUE).isEqualTo(false);
});
changeType(CREATEHTML, FILL1, FETCH, CREATEBOOLEAN, (container, name) -> {
assertThat(container.getBoolean(name)).as(NEWFIELD).isNotNull();
assertThat(container.getBoolean(name).getBoolean()).as(NEWFIELDVALUE).isEqualTo(true);
});
changeType(CREATEHTML, FILL0, FETCH, CREATEBOOLEAN, (container, name) -> {
assertThat(container.getBoolean(name)).as(NEWFIELD).isNotNull();
assertThat(container.getBoolean(name).getBoolean()).as(NEWFIELDVALUE).isEqualTo(false);
});
changeType(CREATEHTML, FILLTEXT, FETCH, CREATEBOOLEAN, (container, name) -> {
assertThat(container.getBoolean(name)).as(NEWFIELD).isNull();
});
}
@Test
@Override
public void testEmptyChangeToBoolean() throws Exception {
changeType(CREATEHTML, NOOP, FETCH, CREATEBOOLEAN, (container, name) -> {
assertThat(container.getBoolean(name)).as(NEWFIELD).isNull();
});
}
@Test
@Override
public void testChangeToBooleanList() throws Exception {
changeType(CREATEHTML, FILLTRUE, FETCH, CREATEBOOLEANLIST, (container, name) -> {
assertThat(container.getBooleanList(name)).as(NEWFIELD).isNotNull();
assertThat(container.getBooleanList(name).getValues()).as(NEWFIELDVALUE).containsExactly(true);
});
changeType(CREATEHTML, FILLFALSE, FETCH, CREATEBOOLEANLIST, (container, name) -> {
assertThat(container.getBooleanList(name)).as(NEWFIELD).isNotNull();
assertThat(container.getBooleanList(name).getValues()).as(NEWFIELDVALUE).containsExactly(false);
});
changeType(CREATEHTML, FILL1, FETCH, CREATEBOOLEANLIST, (container, name) -> {
assertThat(container.getBooleanList(name)).as(NEWFIELD).isNotNull();
assertThat(container.getBooleanList(name).getValues()).as(NEWFIELDVALUE).containsExactly(true);
});
changeType(CREATEHTML, FILL0, FETCH, CREATEBOOLEANLIST, (container, name) -> {
assertThat(container.getBooleanList(name)).as(NEWFIELD).isNotNull();
assertThat(container.getBooleanList(name).getValues()).as(NEWFIELDVALUE).containsExactly(false);
});
changeType(CREATEHTML, FILLTEXT, FETCH, CREATEBOOLEANLIST, (container, name) -> {
assertThat(container.getBooleanList(name)).as(NEWFIELD).isNull();
});
}
@Test
@Override
public void testEmptyChangeToBooleanList() throws Exception {
changeType(CREATEHTML, NOOP, FETCH, CREATEBOOLEANLIST, (container, name) -> {
assertThat(container.getBooleanList(name)).as(NEWFIELD).isNull();
});
}
@Test
@Override
public void testChangeToDate() throws Exception {
changeType(CREATEHTML, FILL0, FETCH, CREATEDATE, (container, name) -> {
assertThat(container.getDate(name)).as(NEWFIELD).isNotNull();
assertThat(container.getDate(name).getDate()).as(NEWFIELDVALUE).isEqualTo(0L);
});
changeType(CREATEHTML, FILL1, FETCH, CREATEDATE, (container, name) -> {
assertThat(container.getDate(name)).as(NEWFIELD).isNotNull();
// Internally timestamps are stored in miliseconds
assertThat(container.getDate(name).getDate()).as(NEWFIELDVALUE).isEqualTo(1000L);
});
changeType(CREATEHTML, FILLTEXT, FETCH, CREATEDATE, (container, name) -> {
assertThat(container.getDate(name)).as(NEWFIELD).isNull();
});
}
@Test
@Override
public void testEmptyChangeToDate() throws Exception {
changeType(CREATEHTML, NOOP, FETCH, CREATEDATE, (container, name) -> {
assertThat(container.getDate(name)).as(NEWFIELD).isNull();
});
}
@Test
@Override
public void testChangeToDateList() throws Exception {
changeType(CREATEHTML, FILL0, FETCH, CREATEDATELIST, (container, name) -> {
assertThat(container.getDateList(name)).as(NEWFIELD).isNotNull();
assertThat(container.getDateList(name).getValues()).as(NEWFIELDVALUE).containsExactly(0L);
});
changeType(CREATEHTML, FILL1, FETCH, CREATEDATELIST, (container, name) -> {
assertThat(container.getDateList(name)).as(NEWFIELD).isNotNull();
// Internally timestamps are stored in miliseconds
assertThat(container.getDateList(name).getValues()).as(NEWFIELDVALUE).containsExactly(1000L);
});
changeType(CREATEHTML, FILLTEXT, FETCH, CREATEDATELIST, (container, name) -> {
assertThat(container.getDateList(name)).as(NEWFIELD).isNull();
});
}
@Test
@Override
public void testEmptyChangeToDateList() throws Exception {
changeType(CREATEHTML, NOOP, FETCH, CREATEDATELIST, (container, name) -> {
assertThat(container.getDateList(name)).as(NEWFIELD).isNull();
});
}
@Test
@Override
public void testChangeToHtml() throws Exception {
changeType(CREATEHTML, FILLTEXT, FETCH, CREATEHTML, (container, name) -> {
assertThat(container.getHtml(name)).as(NEWFIELD).isNotNull();
assertThat(container.getHtml(name).getHTML()).as(NEWFIELDVALUE).isEqualTo("<b>HTML</b> content");
});
}
@Test
@Override
public void testEmptyChangeToHtml() throws Exception {
changeType(CREATEHTML, NOOP, FETCH, CREATEHTML, (container, name) -> {
assertThat(container.getHtml(name)).as(NEWFIELD).isNull();
});
}
@Test
@Override
public void testChangeToHtmlList() throws Exception {
changeType(CREATEHTML, FILLTEXT, FETCH, CREATEHTMLLIST, (container, name) -> {
assertThat(container.getHTMLList(name)).as(NEWFIELD).isNotNull();
assertThat(container.getHTMLList(name).getValues()).as(NEWFIELDVALUE).containsExactly("<b>HTML</b> content");
});
}
@Test
@Override
public void testEmptyChangeToHtmlList() throws Exception {
changeType(CREATEHTML, NOOP, FETCH, CREATEHTMLLIST, (container, name) -> {
assertThat(container.getHTMLList(name)).as(NEWFIELD).isNull();
});
}
@Test
@Override
public void testChangeToMicronode() throws Exception {
changeType(CREATEHTML, FILLTEXT, FETCH, CREATEMICRONODE, (container, name) -> {
assertThat(container.getMicronode(name)).as(NEWFIELD).isNull();
});
}
@Test
@Override
public void testEmptyChangeToMicronode() throws Exception {
changeType(CREATEHTML, NOOP, FETCH, CREATEMICRONODE, (container, name) -> {
assertThat(container.getMicronode(name)).as(NEWFIELD).isNull();
});
}
@Test
@Override
public void testChangeToMicronodeList() throws Exception {
changeType(CREATEHTML, FILLTEXT, FETCH, CREATEMICRONODELIST, (container, name) -> {
assertThat(container.getMicronodeList(name)).as(NEWFIELD).isNull();
});
}
@Test
@Override
public void testEmptyChangeToMicronodeList() throws Exception {
changeType(CREATEHTML, NOOP, FETCH, CREATEMICRONODELIST, (container, name) -> {
assertThat(container.getMicronodeList(name)).as(NEWFIELD).isNull();
});
}
@Test
@Override
public void testChangeToNode() throws Exception {
changeType(CREATEHTML, FILLTEXT, FETCH, CREATENODE, (container, name) -> {
assertThat(container.getNode(name)).as(NEWFIELD).isNull();
});
}
@Test
@Override
public void testEmptyChangeToNode() throws Exception {
changeType(CREATEHTML, NOOP, FETCH, CREATENODE, (container, name) -> {
assertThat(container.getNode(name)).as(NEWFIELD).isNull();
});
}
@Test
@Override
public void testChangeToNodeList() throws Exception {
changeType(CREATEHTML, FILLTEXT, FETCH, CREATENODELIST, (container, name) -> {
assertThat(container.getNodeList(name)).as(NEWFIELD).isNull();
});
}
@Test
@Override
public void testEmptyChangeToNodeList() throws Exception {
changeType(CREATEHTML, NOOP, FETCH, CREATENODELIST, (container, name) -> {
assertThat(container.getNodeList(name)).as(NEWFIELD).isNull();
});
}
@Test
@Override
public void testChangeToNumber() throws Exception {
changeType(CREATEHTML, FILL0, FETCH, CREATENUMBER, (container, name) -> {
assertThat(container.getNumber(name)).as(NEWFIELD).isNotNull();
assertThat(container.getNumber(name).getNumber().longValue()).as(NEWFIELDVALUE).isEqualTo(0L);
});
changeType(CREATEHTML, FILL1, FETCH, CREATENUMBER, (container, name) -> {
assertThat(container.getNumber(name)).as(NEWFIELD).isNotNull();
assertThat(container.getNumber(name).getNumber().longValue()).as(NEWFIELDVALUE).isEqualTo(1L);
});
changeType(CREATEHTML, FILLTEXT, FETCH, CREATENUMBER, (container, name) -> {
assertThat(container.getNumber(name)).as(NEWFIELD).isNull();
});
}
@Test
@Override
public void testEmptyChangeToNumber() throws Exception {
changeType(CREATEHTML, NOOP, FETCH, CREATENUMBER, (container, name) -> {
assertThat(container.getNumber(name)).as(NEWFIELD).isNull();
});
}
@Test
@Override
public void testChangeToNumberList() throws Exception {
changeType(CREATEHTML, FILL0, FETCH, CREATENUMBERLIST, (container, name) -> {
assertThat(container.getNumberList(name)).as(NEWFIELD).isNotNull();
assertThat(container.getNumberList(name).getValues()).as(NEWFIELDVALUE).containsExactly(0L);
});
changeType(CREATEHTML, FILL1, FETCH, CREATENUMBERLIST, (container, name) -> {
assertThat(container.getNumberList(name)).as(NEWFIELD).isNotNull();
assertThat(container.getNumberList(name).getValues()).as(NEWFIELDVALUE).containsExactly(1L);
});
changeType(CREATEHTML, FILLTEXT, FETCH, CREATENUMBERLIST, (container, name) -> {
assertThat(container.getNumberList(name)).as(NEWFIELD).isNull();
});
}
@Test
@Override
public void testEmptyChangeToNumberList() throws Exception {
changeType(CREATEHTML, NOOP, FETCH, CREATENUMBERLIST, (container, name) -> {
assertThat(container.getNumberList(name)).as(NEWFIELD).isNull();
});
}
@Test
@Override
public void testChangeToString() throws Exception {
changeType(CREATEHTML, FILLTEXT, FETCH, CREATESTRING, (container, name) -> {
assertThat(container.getString(name)).as(NEWFIELD).isNotNull();
assertThat(container.getString(name).getString()).as(NEWFIELDVALUE).isEqualTo("<b>HTML</b> content");
});
}
@Test
@Override
public void testEmptyChangeToString() throws Exception {
changeType(CREATEHTML, NOOP, FETCH, CREATESTRING, (container, name) -> {
assertThat(container.getString(name)).as(NEWFIELD).isNull();
});
}
@Test
@Override
public void testChangeToStringList() throws Exception {
changeType(CREATEHTML, FILLTEXT, FETCH, CREATESTRINGLIST, (container, name) -> {
assertThat(container.getStringList(name)).as(NEWFIELD).isNotNull();
assertThat(container.getStringList(name).getValues()).as(NEWFIELDVALUE).containsExactly("<b>HTML</b> content");
});
}
@Test
@Override
public void testEmptyChangeToStringList() throws Exception {
changeType(CREATEHTML, NOOP, FETCH, CREATESTRINGLIST, (container, name) -> {
assertThat(container.getStringList(name)).as(NEWFIELD).isNull();
});
}
@Test
public void testIndexOptionAddRaw() throws InterruptedException, ExecutionException, TimeoutException {
changeType(CREATEHTML, FILLLONGTEXT, FETCH,
name -> FieldUtil.createHtmlFieldSchema(name).setElasticsearch(IndexOptionHelper.getRawFieldOption()),
(container, name) -> {
HibHtmlField htmlField = container.getHtml(name);
assertEquals("The html field should not be truncated.", 40_000, htmlField.getHTML().length());
waitForSearchIdleEvent();
assertThat(trackingSearchProvider()).recordedStoreEvents(1);
});
}
}
| gentics/mesh | tests/tests-core/src/main/java/com/gentics/mesh/core/schema/field/HtmlFieldMigrationTest.java | Java | apache-2.0 | 14,181 |
/*
* 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 redis.common.container;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.common.config.FlinkJedisClusterConfig;
import redis.common.config.FlinkJedisConfigBase;
import redis.common.config.FlinkJedisPoolConfig;
import redis.common.config.FlinkJedisSentinelConfig;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisSentinelPool;
import redis.common.container.*;
import redis.common.container.RedisCommandsContainer;
import redis.common.container.RedisContainer;
import java.util.Objects;
/**
* The builder for {@link redis.common.container.RedisCommandsContainer}.
*/
public class RedisCommandsContainerBuilder {
/**
* Initialize the {@link redis.common.container.RedisCommandsContainer} based on the instance type.
* @param flinkJedisConfigBase configuration base
* @return @throws IllegalArgumentException if jedisPoolConfig, jedisClusterConfig and jedisSentinelConfig are all null
*/
public static redis.common.container.RedisCommandsContainer build(FlinkJedisConfigBase flinkJedisConfigBase){
if(flinkJedisConfigBase instanceof FlinkJedisPoolConfig){
FlinkJedisPoolConfig flinkJedisPoolConfig = (FlinkJedisPoolConfig) flinkJedisConfigBase;
return RedisCommandsContainerBuilder.build(flinkJedisPoolConfig);
} else if (flinkJedisConfigBase instanceof FlinkJedisClusterConfig) {
FlinkJedisClusterConfig flinkJedisClusterConfig = (FlinkJedisClusterConfig) flinkJedisConfigBase;
return RedisCommandsContainerBuilder.build(flinkJedisClusterConfig);
} else if (flinkJedisConfigBase instanceof FlinkJedisSentinelConfig) {
FlinkJedisSentinelConfig flinkJedisSentinelConfig = (FlinkJedisSentinelConfig) flinkJedisConfigBase;
return RedisCommandsContainerBuilder.build(flinkJedisSentinelConfig);
} else {
throw new IllegalArgumentException("Jedis configuration not found");
}
}
/**
* Builds container for single Redis environment.
*
* @param jedisPoolConfig configuration for JedisPool
* @return container for single Redis environment
* @throws NullPointerException if jedisPoolConfig is null
*/
public static redis.common.container.RedisCommandsContainer build(FlinkJedisPoolConfig jedisPoolConfig) {
Objects.requireNonNull(jedisPoolConfig, "Redis pool config should not be Null");
GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
genericObjectPoolConfig.setMaxIdle(jedisPoolConfig.getMaxIdle());
genericObjectPoolConfig.setMaxTotal(jedisPoolConfig.getMaxTotal());
genericObjectPoolConfig.setMinIdle(jedisPoolConfig.getMinIdle());
JedisPool jedisPool = new JedisPool(genericObjectPoolConfig, jedisPoolConfig.getHost(),
jedisPoolConfig.getPort(), jedisPoolConfig.getConnectionTimeout(), jedisPoolConfig.getPassword(),
jedisPoolConfig.getDatabase());
return new redis.common.container.RedisContainer(jedisPool);
}
/**
* Builds container for Redis Cluster environment.
*
* @param jedisClusterConfig configuration for JedisCluster
* @return container for Redis Cluster environment
* @throws NullPointerException if jedisClusterConfig is null
*/
public static redis.common.container.RedisCommandsContainer build(FlinkJedisClusterConfig jedisClusterConfig) {
Objects.requireNonNull(jedisClusterConfig, "Redis cluster config should not be Null");
GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
genericObjectPoolConfig.setMaxIdle(jedisClusterConfig.getMaxIdle());
genericObjectPoolConfig.setMaxTotal(jedisClusterConfig.getMaxTotal());
genericObjectPoolConfig.setMinIdle(jedisClusterConfig.getMinIdle());
JedisCluster jedisCluster = new JedisCluster(jedisClusterConfig.getNodes(), jedisClusterConfig.getConnectionTimeout(),
jedisClusterConfig.getMaxRedirections(), genericObjectPoolConfig);
return new redis.common.container.RedisClusterContainer(jedisCluster);
}
/**
* Builds container for Redis Sentinel environment.
*
* @param jedisSentinelConfig configuration for JedisSentinel
* @return container for Redis sentinel environment
* @throws NullPointerException if jedisSentinelConfig is null
*/
public static RedisCommandsContainer build(FlinkJedisSentinelConfig jedisSentinelConfig) {
Objects.requireNonNull(jedisSentinelConfig, "Redis sentinel config should not be Null");
GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
genericObjectPoolConfig.setMaxIdle(jedisSentinelConfig.getMaxIdle());
genericObjectPoolConfig.setMaxTotal(jedisSentinelConfig.getMaxTotal());
genericObjectPoolConfig.setMinIdle(jedisSentinelConfig.getMinIdle());
JedisSentinelPool jedisSentinelPool = new JedisSentinelPool(jedisSentinelConfig.getMasterName(),
jedisSentinelConfig.getSentinels(), genericObjectPoolConfig,
jedisSentinelConfig.getConnectionTimeout(), jedisSentinelConfig.getSoTimeout(),
jedisSentinelConfig.getPassword(), jedisSentinelConfig.getDatabase());
return new RedisContainer(jedisSentinelPool);
}
}
| eltitopera/TFM | manager/src/src/main/java/redis/common/container/RedisCommandsContainerBuilder.java | Java | apache-2.0 | 6,212 |
package fundamental.games.metropolis.connection.bluetooth;
import android.bluetooth.BluetoothSocket;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.UUID;
import fundamental.games.metropolis.connection.global.MessagesQueue;
import fundamental.games.metropolis.connection.serializable.PlayerInitData;
import fundamental.games.metropolis.global.WidgetsData;
/**
* Created by regair on 27.05.15.
*/
public class BluetoothServerConnection extends BluetoothConnection
{
private ObjectOutputStream writer;
private ObjectInputStream reader;
//********************************
public BluetoothServerConnection(BluetoothSocket socket, MessagesQueue<Serializable> queue, UUID uuid)
{
super(socket, queue, uuid);
this.queue = new MessagesQueue<>();
deviceName = "SERVER";
}
//********************************
@Override
public void run()
{
working = true;
}
//********************************
@Override
public void stopConnection()
{
super.stopConnection();
BluetoothServer.getInstance().removeConnection(this);
}
public MessagesQueue<Serializable> getQueue()
{
return queue;
}
//**********************************
public void sendMessage(Serializable message)
{
if(message instanceof PlayerInitData)
{
setID(((PlayerInitData)message).ID);
//ID = ((PlayerInitData)message).ID;
BluetoothServer.getInstance().getIncomingQueue().addMessage(new PlayerInitData(WidgetsData.playerName, ID));
return;
}
queue.addMessage(message);
}
@Override
public void setID(int id)
{
super.setID(id);
BluetoothConnection.humanID = id;
}
}
| Ragnarokma/metropolis | src/main/java/fundamental/games/metropolis/connection/bluetooth/BluetoothServerConnection.java | Java | apache-2.0 | 1,850 |
package bookshop2.client.paymentService;
import java.util.List;
import org.aries.message.Message;
import org.aries.message.MessageInterceptor;
import org.aries.util.ExceptionUtil;
import bookshop2.Payment;
@SuppressWarnings("serial")
public class PaymentServiceInterceptor extends MessageInterceptor<PaymentService> implements PaymentService {
@Override
public List<Payment> getAllPaymentRecords() {
try {
log.info("#### [admin]: getAllPaymentRecords() sending...");
Message request = createMessage("getAllPaymentRecords");
Message response = getProxy().invoke(request);
List<Payment> result = response.getPart("result");
return result;
} catch (Exception e) {
throw ExceptionUtil.rewrap(e);
}
}
@Override
public Payment getPaymentRecordById(Long id) {
try {
log.info("#### [admin]: getPaymentRecordById() sending...");
Message request = createMessage("getPaymentRecordById");
request.addPart("id", id);
Message response = getProxy().invoke(request);
Payment result = response.getPart("result");
return result;
} catch (Exception e) {
throw ExceptionUtil.rewrap(e);
}
}
@Override
public List<Payment> getPaymentRecordsByPage(int pageIndex, int pageSize) {
try {
log.info("#### [admin]: getPaymentRecordsByPage() sending...");
Message request = createMessage("getPaymentRecordsByPage");
request.addPart("pageIndex", pageIndex);
request.addPart("pageSize", pageSize);
Message response = getProxy().invoke(request);
List<Payment> result = response.getPart("result");
return result;
} catch (Exception e) {
throw ExceptionUtil.rewrap(e);
}
}
@Override
public Long addPaymentRecord(Payment payment) {
try {
log.info("#### [admin]: addPaymentRecord() sending...");
Message request = createMessage("addPaymentRecord");
request.addPart("payment", payment);
Message response = getProxy().invoke(request);
Long result = response.getPart("result");
return result;
} catch (Exception e) {
throw ExceptionUtil.rewrap(e);
}
}
@Override
public void savePaymentRecord(Payment payment) {
try {
log.info("#### [admin]: savePaymentRecord() sending...");
Message request = createMessage("savePaymentRecord");
request.addPart("payment", payment);
getProxy().invoke(request);
} catch (Exception e) {
throw ExceptionUtil.rewrap(e);
}
}
@Override
public void removeAllPaymentRecords() {
try {
log.info("#### [admin]: removeAllPaymentRecords() sending...");
Message request = createMessage("removeAllPaymentRecords");
getProxy().invoke(request);
} catch (Exception e) {
throw ExceptionUtil.rewrap(e);
}
}
@Override
public void removePaymentRecord(Payment payment) {
try {
log.info("#### [admin]: removePaymentRecord() sending...");
Message request = createMessage("removePaymentRecord");
request.addPart("payment", payment);
getProxy().invoke(request);
} catch (Exception e) {
throw ExceptionUtil.rewrap(e);
}
}
@Override
public void importPaymentRecords() {
try {
log.info("#### [admin]: importPaymentRecords() sending...");
Message request = createMessage("importPaymentRecords");
getProxy().invoke(request);
} catch (Exception e) {
throw ExceptionUtil.rewrap(e);
}
}
}
| tfisher1226/ARIES | bookshop2/bookshop2-client/src/main/java/bookshop2/client/paymentService/PaymentServiceInterceptor.java | Java | apache-2.0 | 3,276 |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.redshift.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DeleteAuthenticationProfile"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DeleteAuthenticationProfileRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The name of the authentication profile to delete.
* </p>
*/
private String authenticationProfileName;
/**
* <p>
* The name of the authentication profile to delete.
* </p>
*
* @param authenticationProfileName
* The name of the authentication profile to delete.
*/
public void setAuthenticationProfileName(String authenticationProfileName) {
this.authenticationProfileName = authenticationProfileName;
}
/**
* <p>
* The name of the authentication profile to delete.
* </p>
*
* @return The name of the authentication profile to delete.
*/
public String getAuthenticationProfileName() {
return this.authenticationProfileName;
}
/**
* <p>
* The name of the authentication profile to delete.
* </p>
*
* @param authenticationProfileName
* The name of the authentication profile to delete.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DeleteAuthenticationProfileRequest withAuthenticationProfileName(String authenticationProfileName) {
setAuthenticationProfileName(authenticationProfileName);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getAuthenticationProfileName() != null)
sb.append("AuthenticationProfileName: ").append(getAuthenticationProfileName());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DeleteAuthenticationProfileRequest == false)
return false;
DeleteAuthenticationProfileRequest other = (DeleteAuthenticationProfileRequest) obj;
if (other.getAuthenticationProfileName() == null ^ this.getAuthenticationProfileName() == null)
return false;
if (other.getAuthenticationProfileName() != null && other.getAuthenticationProfileName().equals(this.getAuthenticationProfileName()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getAuthenticationProfileName() == null) ? 0 : getAuthenticationProfileName().hashCode());
return hashCode;
}
@Override
public DeleteAuthenticationProfileRequest clone() {
return (DeleteAuthenticationProfileRequest) super.clone();
}
}
| aws/aws-sdk-java | aws-java-sdk-redshift/src/main/java/com/amazonaws/services/redshift/model/DeleteAuthenticationProfileRequest.java | Java | apache-2.0 | 4,104 |
// Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package codeu.chat.client.core;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collection;
import codeu.chat.common.BasicView;
import codeu.chat.common.User;
import codeu.chat.util.Uuid;
import codeu.chat.util.connections.ConnectionSource;
public final class Context {
private final BasicView view;
private final Controller controller;
public Context(ConnectionSource source) {
this.view = new View(source);
this.controller = new Controller(source);
}
public UserContext create(String name) {
final User user = controller.newUser(name);
return user == null ?
null :
new UserContext(user, view, controller);
}
public Iterable<UserContext> allUsers() {
final Collection<UserContext> users = new ArrayList<>();
for (final User user : view.getUsers()) {
users.add(new UserContext(user, view, controller));
}
return users;
}
}
| crepric/codeu_mirrored_test_1 | src/codeu/chat/client/core/Context.java | Java | apache-2.0 | 1,510 |
/*
* Copyright 2015-2017 EMBL - European Bioinformatics Institute
*
* 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 uk.ac.ebi.eva.runner;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.launch.JobOperator;
import org.springframework.batch.test.JobLauncherTestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import uk.ac.ebi.eva.pipeline.runner.ManageJobsUtils;
import uk.ac.ebi.eva.test.configuration.AsynchronousBatchTestConfiguration;
import uk.ac.ebi.eva.test.utils.AbstractJobRestartUtils;
/**
* Test to check if the ManageJobUtils.markLastJobAsFailed let us restart a job redoing all the steps.
*/
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {AsynchronousBatchTestConfiguration.class})
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class JobRestartForceTest extends AbstractJobRestartUtils {
// Wait until the job has been launched properly. The launch operation is not transactional, and other
// instances of the same job with the same parameter can throw exceptions in this interval.
public static final int INITIALIZE_JOB_SLEEP = 100;
public static final int STEP_TIME_DURATION = 1000;
public static final int WAIT_FOR_JOB_TO_END = 2000;
@Autowired
private JobOperator jobOperator;
@Test
public void forceJobFailureEnsuresCleanRunEvenIfStepsNotRestartables() throws Exception {
Job job = getTestJob(getQuickStep(false), getWaitingStep(false, STEP_TIME_DURATION));
JobLauncherTestUtils jobLauncherTestUtils = getJobLauncherTestUtils(job);
JobExecution jobExecution = launchJob(jobLauncherTestUtils);
Thread.sleep(INITIALIZE_JOB_SLEEP);
jobOperator.stop(jobExecution.getJobId());
Thread.sleep(WAIT_FOR_JOB_TO_END);
ManageJobsUtils.markLastJobAsFailed(getJobRepository(), job.getName(), new JobParameters());
jobExecution = launchJob(jobLauncherTestUtils);
Thread.sleep(WAIT_FOR_JOB_TO_END);
Assert.assertFalse(jobExecution.getStepExecutions().isEmpty());
}
} | cyenyxe/eva-pipeline | src/test/java/uk/ac/ebi/eva/runner/JobRestartForceTest.java | Java | apache-2.0 | 2,993 |
//
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.2 generiert
// Siehe <a href="https://javaee.github.io/jaxb-v2/">https://javaee.github.io/jaxb-v2/</a>
// Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2020.03.13 um 12:48:52 PM CET
//
package net.opengis.ows._1;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
/**
* Complete reference to a remote or local resource, allowing including metadata about that resource.
*
* <p>Java-Klasse für ReferenceType complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType name="ReferenceType">
* <complexContent>
* <extension base="{http://www.opengis.net/ows/1.1}AbstractReferenceBaseType">
* <sequence>
* <element ref="{http://www.opengis.net/ows/1.1}Identifier" minOccurs="0"/>
* <element ref="{http://www.opengis.net/ows/1.1}Abstract" maxOccurs="unbounded" minOccurs="0"/>
* <element name="Format" type="{http://www.opengis.net/ows/1.1}MimeType" minOccurs="0"/>
* <element ref="{http://www.opengis.net/ows/1.1}Metadata" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ReferenceType", propOrder = {
"identifier",
"_abstract",
"format",
"metadata"
})
@XmlSeeAlso({
ServiceReferenceType.class
})
public class ReferenceType
extends AbstractReferenceBaseType
{
@XmlElement(name = "Identifier")
protected CodeType identifier;
@XmlElement(name = "Abstract")
protected List<LanguageStringType> _abstract;
@XmlElement(name = "Format")
protected String format;
@XmlElement(name = "Metadata")
protected List<MetadataType> metadata;
/**
* Optional unique identifier of the referenced resource.
*
* @return
* possible object is
* {@link CodeType }
*
*/
public CodeType getIdentifier() {
return identifier;
}
/**
* Legt den Wert der identifier-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link CodeType }
*
*/
public void setIdentifier(CodeType value) {
this.identifier = value;
}
public boolean isSetIdentifier() {
return (this.identifier!= null);
}
/**
* Gets the value of the abstract property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the abstract property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAbstract().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link LanguageStringType }
*
*
*/
public List<LanguageStringType> getAbstract() {
if (_abstract == null) {
_abstract = new ArrayList<LanguageStringType>();
}
return this._abstract;
}
public boolean isSetAbstract() {
return ((this._abstract!= null)&&(!this._abstract.isEmpty()));
}
public void unsetAbstract() {
this._abstract = null;
}
/**
* Ruft den Wert der format-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFormat() {
return format;
}
/**
* Legt den Wert der format-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFormat(String value) {
this.format = value;
}
public boolean isSetFormat() {
return (this.format!= null);
}
/**
* Optional unordered list of additional metadata about this resource. A list of optional metadata elements for this ReferenceType could be specified in the Implementation Specification for each use of this type in a specific OWS. Gets the value of the metadata property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the metadata property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getMetadata().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link MetadataType }
*
*
*/
public List<MetadataType> getMetadata() {
if (metadata == null) {
metadata = new ArrayList<MetadataType>();
}
return this.metadata;
}
public boolean isSetMetadata() {
return ((this.metadata!= null)&&(!this.metadata.isEmpty()));
}
public void unsetMetadata() {
this.metadata = null;
}
public void setAbstract(List<LanguageStringType> value) {
this._abstract = value;
}
public void setMetadata(List<MetadataType> value) {
this.metadata = value;
}
}
| 3dcitydb/web-feature-service | src-gen/main/java/net/opengis/ows/_1/ReferenceType.java | Java | apache-2.0 | 5,813 |
package io.github.varvelworld.var.ioc.core.annotation.meta.factory;
import io.github.varvelworld.var.ioc.core.annotation.Resource;
import io.github.varvelworld.var.ioc.core.meta.ParamResourceMeta;
import io.github.varvelworld.var.ioc.core.meta.factory.ParamResourceMetaFactory;
import java.lang.reflect.Parameter;
/**
* Created by luzhonghao on 2016/12/4.
*/
public class AnnotationParamResourceMetaFactoryImpl implements ParamResourceMetaFactory {
private final ParamResourceMeta paramResourceMeta;
public AnnotationParamResourceMetaFactoryImpl(Parameter parameter) {
this(parameter, parameter.getAnnotation(Resource.class));
}
public AnnotationParamResourceMetaFactoryImpl(Parameter parameter, Resource annotation) {
String id = annotation.value();
if(id.isEmpty()) {
if(parameter.isNamePresent()){
id = parameter.getName();
}
else {
throw new RuntimeException("id is empty");
}
}
this.paramResourceMeta = new ParamResourceMeta(id);
}
@Override
public ParamResourceMeta paramResourceMeta() {
return paramResourceMeta;
}
}
| varvelworld/var-ioc | src/main/java/io/github/varvelworld/var/ioc/core/annotation/meta/factory/AnnotationParamResourceMetaFactoryImpl.java | Java | apache-2.0 | 1,193 |
/**
* 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.camel.processor.juel;
import javax.naming.Context;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.InvalidPayloadException;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.util.ExchangeHelper;
import org.apache.camel.util.jndi.JndiContext;
import static org.apache.camel.language.juel.JuelExpression.el;
/**
* @version
*/
public class SimulatorTest extends ContextTestSupport {
protected Context createJndiContext() throws Exception {
JndiContext answer = new JndiContext();
answer.bind("foo", new MyBean("foo"));
answer.bind("bar", new MyBean("bar"));
return answer;
}
public void testReceivesFooResponse() throws Exception {
assertRespondsWith("foo", "Bye said foo");
}
public void testReceivesBarResponse() throws Exception {
assertRespondsWith("bar", "Bye said bar");
}
protected void assertRespondsWith(final String value, String containedText) throws InvalidPayloadException {
Exchange response = template.request("direct:a", new Processor() {
public void process(Exchange exchange) throws Exception {
Message in = exchange.getIn();
in.setBody("answer");
in.setHeader("cheese", value);
}
});
assertNotNull("Should receive a response!", response);
String text = ExchangeHelper.getMandatoryOutBody(response, String.class);
assertStringContains(text, containedText);
}
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
// START SNIPPET: example
from("direct:a").
recipientList(el("bean:${in.headers.cheese}"));
// END SNIPPET: example
}
};
}
public static class MyBean {
private String value;
public MyBean(String value) {
this.value = value;
}
public String doSomething(String in) {
return "Bye said " + value;
}
}
} | everttigchelaar/camel-svn | components/camel-juel/src/test/java/org/apache/camel/processor/juel/SimulatorTest.java | Java | apache-2.0 | 3,124 |
package com.stf.bj.app.game.players;
import java.util.Random;
import com.stf.bj.app.game.bj.Spot;
import com.stf.bj.app.game.server.Event;
import com.stf.bj.app.game.server.EventType;
import com.stf.bj.app.settings.AppSettings;
import com.stf.bj.app.strategy.FullStrategy;
public class RealisticBot extends BasicBot {
private enum InsuranceStrategy {
NEVER, EVEN_MONEY_ONLY, GOOD_HANDS_ONLY, RARELY, OFTEN;
}
private enum PlayAbility {
PERFECT, NOOB, RANDOM;
}
private enum BetChanging {
NEVER, RANDOM;
}
private final InsuranceStrategy insuranceStrategy;
private final PlayAbility playAbility;
private final Random r;
private double wager = -1.0;
private final BetChanging betChanging;
private boolean insurancePlay = false;
private boolean calculatedInsurancePlay = false;
private boolean messUpNextPlay = false;
public RealisticBot(AppSettings settings, FullStrategy strategy, Random r, Spot s) {
super(settings, strategy, r, s);
if (r == null) {
r = new Random(System.currentTimeMillis());
}
this.r = r;
insuranceStrategy = InsuranceStrategy.values()[r.nextInt(InsuranceStrategy.values().length)];
playAbility = PlayAbility.values()[r.nextInt(PlayAbility.values().length)];
setBaseBet();
betChanging = BetChanging.RANDOM;
}
@Override
public void sendEvent(Event e) {
super.sendEvent(e);
if (e.getType() == EventType.DECK_SHUFFLED) {
if (betChanging == BetChanging.RANDOM && r.nextInt(2) == 0) {
wager = 5;
}
}
}
@Override
public double getWager() {
if (delay > 0) {
delay--;
return -1;
}
return wager;
}
private void setBaseBet() {
int rInt = r.nextInt(12);
if (rInt < 6) {
wager = 5.0 * (1 + rInt);
} else if (rInt < 9) {
wager = 10.0;
} else {
wager = 5.0;
}
}
@Override
public boolean getInsurancePlay() {
if (insuranceStrategy == InsuranceStrategy.NEVER) {
return false;
}
if (!calculatedInsurancePlay) {
insurancePlay = calculateInsurancePlay();
calculatedInsurancePlay = true;
}
return insurancePlay;
}
private boolean calculateInsurancePlay() {
switch (insuranceStrategy) {
case EVEN_MONEY_ONLY:
return getHandSoftTotal(0) == 21;
case GOOD_HANDS_ONLY:
return getHandSoftTotal(0) > 16 + r.nextInt(3);
case OFTEN:
return r.nextInt(2) == 0;
case RARELY:
return r.nextInt(5) == 0;
default:
throw new IllegalStateException();
}
}
@Override
public Play getMove(int handIndex, boolean canDouble, boolean canSplit, boolean canSurrender) {
if (delay > 0) {
delay--;
return null;
}
Play play = super.getMove(handIndex, canDouble, canSplit, canSurrender);
if (messUpNextPlay) {
if (play != Play.SPLIT && canSplit) {
play = Play.SPLIT;
} else if (play != Play.DOUBLEDOWN && canSplit) {
play = Play.DOUBLEDOWN;
} else if (play == Play.STAND) {
play = Play.HIT;
} else {
play = Play.STAND;
}
}
return play;
}
@Override
protected void reset() {
super.reset();
calculatedInsurancePlay = false;
int random = r.nextInt(10);
if (playAbility == PlayAbility.RANDOM) {
messUpNextPlay = (random < 2);
}
if ((random == 2 || random == 3) && betChanging == BetChanging.RANDOM) {
wager += 5;
} else if (random == 4 && betChanging == BetChanging.RANDOM) {
if (wager > 6) {
wager -= 5;
}
}
}
}
| Boxxy/Blackjack | core/src/com/stf/bj/app/game/players/RealisticBot.java | Java | apache-2.0 | 3,337 |
package me.marcosassuncao.servsim.job;
import me.marcosassuncao.servsim.profile.RangeList;
import com.google.common.base.MoreObjects;
/**
* {@link Reservation} represents a resource reservation request
* made by a customer to reserve a given number of resources
* from a provider.
*
* @see WorkUnit
* @see DefaultWorkUnit
*
* @author Marcos Dias de Assuncao
*/
public class Reservation extends DefaultWorkUnit {
private long reqStartTime = WorkUnit.TIME_NOT_SET;
private RangeList rangeList;
/**
* Creates a reservation request to start at
* <code>startTime</code> and with the given duration.
* @param startTime the requested start time for the reservation
* @param duration the duration of the reservation
* @param numResources number of required resources
*/
public Reservation(long startTime,
long duration, int numResources) {
super(duration);
super.setNumReqResources(numResources);
this.reqStartTime = startTime;
}
/**
* Creates a reservation request to start at
* <code>startTime</code> and with the given duration and priority
* @param startTime the requested start time for the reservation
* @param duration the duration of the reservation
* @param numResources the number of resources to be reserved
* @param priority the reservation priority
*/
public Reservation(long startTime,
long duration, int numResources, int priority) {
super(duration, priority);
super.setNumReqResources(numResources);
this.reqStartTime = startTime;
}
/**
* Returns the start time requested by this reservation
* @return the requested start time
*/
public long getRequestedStartTime() {
return reqStartTime;
}
/**
* Sets the ranges of reserved resources
* @param ranges the ranges of resources allocated for the reservation
* @return <code>true</code> if the ranges have been set correctly,
* <code>false</code> otherwise.
*/
public boolean setResourceRanges(RangeList ranges) {
if (this.rangeList != null) {
return false;
}
this.rangeList = ranges;
return true;
}
/**
* Gets the ranges of reserved resources
* @return the ranges of reserved resources
*/
public RangeList getResourceRanges() {
return rangeList;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("id", getId())
.add("submission time", getSubmitTime())
.add("start time", getStartTime())
.add("finish time", getFinishTime())
.add("duration", getDuration())
.add("priority", getPriority())
.add("status", getStatus())
.add("resources", rangeList)
.toString();
}
} | assuncaomarcos/servsim | src/main/java/me/marcosassuncao/servsim/job/Reservation.java | Java | apache-2.0 | 2,646 |
/*
* Copyright (c) 2016, baihw ([email protected]).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*
*/
package com.yoya.rdf.router;
/**
* Created by baihw on 16-6-13.
*
* 统一的服务请求处理器规范接口,此接口用于标识类文件为请求处理器实现类,无必须实现的方法。
*
* 实现类中所有符合public void xxx( IRequest request, IResponse response )签名规则的方法都将被自动注册到对应的请求处理器中。
*
* 如下所示:
*
* public void login( IRequest request, IResponse response ){};
*
* public void logout( IRequest request, IResponse response ){} ;
*
* 上边的login, logout将被自动注册到请求处理器路径中。
*
* 假如类名为LoginHnadler, 则注册的处理路径为:/Loginhandler/login, /Loginhandler/logout.
*
* 注意:大小写敏感。
*
*/
public interface IRequestHandler{
/**
* 当请求中没有明确指定处理方法时,默认执行的请求处理方法。
*
* @param request 请求对象
* @param response 响应对象
*/
void handle( IRequest request, IResponse response );
} // end class
| javakf/rdf | src/main/java/com/yoya/rdf/router/IRequestHandler.java | Java | apache-2.0 | 1,692 |
/*
* Copyright 2010-2020 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.activiti.spring.test.servicetask;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import org.activiti.engine.impl.test.JobTestHelper;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.test.Deployment;
import org.activiti.spring.impl.test.SpringActivitiTestCase;
import org.springframework.test.context.ContextConfiguration;
/**
*/
@ContextConfiguration("classpath:org/activiti/spring/test/servicetask/servicetaskSpringTest-context.xml")
public class ServiceTaskSpringDelegationTest extends SpringActivitiTestCase {
private void cleanUp() {
List<org.activiti.engine.repository.Deployment> deployments = repositoryService.createDeploymentQuery().list();
for (org.activiti.engine.repository.Deployment deployment : deployments) {
repositoryService.deleteDeployment(deployment.getId(), true);
}
}
@Override
public void tearDown() {
cleanUp();
}
@Deployment
public void testDelegateExpression() {
ProcessInstance procInst = runtimeService.startProcessInstanceByKey("delegateExpressionToSpringBean");
assertThat(runtimeService.getVariable(procInst.getId(), "myVar")).isEqualTo("Activiti BPMN 2.0 process engine");
assertThat(runtimeService.getVariable(procInst.getId(), "fieldInjection")).isEqualTo("fieldInjectionWorking");
}
@Deployment
public void testAsyncDelegateExpression() throws Exception {
ProcessInstance procInst = runtimeService.startProcessInstanceByKey("delegateExpressionToSpringBean");
assertThat(JobTestHelper.areJobsAvailable(managementService)).isTrue();
waitForJobExecutorToProcessAllJobs(5000, 500);
Thread.sleep(1000);
assertThat(runtimeService.getVariable(procInst.getId(), "myVar")).isEqualTo("Activiti BPMN 2.0 process engine");
assertThat(runtimeService.getVariable(procInst.getId(), "fieldInjection")).isEqualTo("fieldInjectionWorking");
}
@Deployment
public void testMethodExpressionOnSpringBean() {
ProcessInstance procInst = runtimeService.startProcessInstanceByKey("methodExpressionOnSpringBean");
assertThat(runtimeService.getVariable(procInst.getId(), "myVar")).isEqualTo("ACTIVITI BPMN 2.0 PROCESS ENGINE");
}
@Deployment
public void testAsyncMethodExpressionOnSpringBean() {
ProcessInstance procInst = runtimeService.startProcessInstanceByKey("methodExpressionOnSpringBean");
assertThat(JobTestHelper.areJobsAvailable(managementService)).isTrue();
waitForJobExecutorToProcessAllJobs(5000, 500);
assertThat(runtimeService.getVariable(procInst.getId(), "myVar")).isEqualTo("ACTIVITI BPMN 2.0 PROCESS ENGINE");
}
@Deployment
public void testExecutionAndTaskListenerDelegationExpression() {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("executionAndTaskListenerDelegation");
assertThat(runtimeService.getVariable(processInstance.getId(), "executionListenerVar")).isEqualTo("working");
assertThat(runtimeService.getVariable(processInstance.getId(), "taskListenerVar")).isEqualTo("working");
assertThat(runtimeService.getVariable(processInstance.getId(), "executionListenerField")).isEqualTo("executionListenerInjection");
assertThat(runtimeService.getVariable(processInstance.getId(), "taskListenerField")).isEqualTo("taskListenerInjection");
}
}
| Activiti/Activiti | activiti-core/activiti-spring/src/test/java/org/activiti/spring/test/servicetask/ServiceTaskSpringDelegationTest.java | Java | apache-2.0 | 4,086 |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.impl;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.EObjectImpl;
import org.eclipse.emf.ecore.util.EcoreUtil;
import de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.Cpu_usage;
import de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.Sys_info_systeminfoPackage;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Cpu usage</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.impl.Cpu_usageImpl#getEContainer_cpu_usage <em>EContainer cpu usage</em>}</li>
* <li>{@link de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.impl.Cpu_usageImpl#getReal <em>Real</em>}</li>
* <li>{@link de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.impl.Cpu_usageImpl#getUser <em>User</em>}</li>
* <li>{@link de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.impl.Cpu_usageImpl#getSys <em>Sys</em>}</li>
* <li>{@link de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.impl.Cpu_usageImpl#getUnit <em>Unit</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class Cpu_usageImpl extends EObjectImpl implements Cpu_usage {
/**
* The default value of the '{@link #getReal() <em>Real</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getReal()
* @generated
* @ordered
*/
protected static final double REAL_EDEFAULT = 0.0;
/**
* The cached value of the '{@link #getReal() <em>Real</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getReal()
* @generated
* @ordered
*/
protected double real = REAL_EDEFAULT;
/**
* The default value of the '{@link #getUser() <em>User</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getUser()
* @generated
* @ordered
*/
protected static final double USER_EDEFAULT = 0.0;
/**
* The cached value of the '{@link #getUser() <em>User</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getUser()
* @generated
* @ordered
*/
protected double user = USER_EDEFAULT;
/**
* The default value of the '{@link #getSys() <em>Sys</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getSys()
* @generated
* @ordered
*/
protected static final double SYS_EDEFAULT = 0.0;
/**
* The cached value of the '{@link #getSys() <em>Sys</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getSys()
* @generated
* @ordered
*/
protected double sys = SYS_EDEFAULT;
/**
* The default value of the '{@link #getUnit() <em>Unit</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getUnit()
* @generated
* @ordered
*/
protected static final String UNIT_EDEFAULT = null;
/**
* The cached value of the '{@link #getUnit() <em>Unit</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getUnit()
* @generated
* @ordered
*/
protected String unit = UNIT_EDEFAULT;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected Cpu_usageImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return Sys_info_systeminfoPackage.Literals.CPU_USAGE;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System getEContainer_cpu_usage() {
if (eContainerFeatureID() != Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE) return null;
return (de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System)eContainer();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetEContainer_cpu_usage(de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System newEContainer_cpu_usage, NotificationChain msgs) {
msgs = eBasicSetContainer((InternalEObject)newEContainer_cpu_usage, Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE, msgs);
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setEContainer_cpu_usage(de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System newEContainer_cpu_usage) {
if (newEContainer_cpu_usage != eInternalContainer() || (eContainerFeatureID() != Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE && newEContainer_cpu_usage != null)) {
if (EcoreUtil.isAncestor(this, newEContainer_cpu_usage))
throw new IllegalArgumentException("Recursive containment not allowed for " + toString());
NotificationChain msgs = null;
if (eInternalContainer() != null)
msgs = eBasicRemoveFromContainer(msgs);
if (newEContainer_cpu_usage != null)
msgs = ((InternalEObject)newEContainer_cpu_usage).eInverseAdd(this, Sys_info_systeminfoPackage.SYSTEM__CPU_USAGE, de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System.class, msgs);
msgs = basicSetEContainer_cpu_usage(newEContainer_cpu_usage, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE, newEContainer_cpu_usage, newEContainer_cpu_usage));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public double getReal() {
return real;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setReal(double newReal) {
double oldReal = real;
real = newReal;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Sys_info_systeminfoPackage.CPU_USAGE__REAL, oldReal, real));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public double getUser() {
return user;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setUser(double newUser) {
double oldUser = user;
user = newUser;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Sys_info_systeminfoPackage.CPU_USAGE__USER, oldUser, user));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public double getSys() {
return sys;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setSys(double newSys) {
double oldSys = sys;
sys = newSys;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Sys_info_systeminfoPackage.CPU_USAGE__SYS, oldSys, sys));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getUnit() {
return unit;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setUnit(String newUnit) {
String oldUnit = unit;
unit = newUnit;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Sys_info_systeminfoPackage.CPU_USAGE__UNIT, oldUnit, unit));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE:
if (eInternalContainer() != null)
msgs = eBasicRemoveFromContainer(msgs);
return basicSetEContainer_cpu_usage((de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System)otherEnd, msgs);
}
return super.eInverseAdd(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE:
return basicSetEContainer_cpu_usage(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eBasicRemoveFromContainerFeature(NotificationChain msgs) {
switch (eContainerFeatureID()) {
case Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE:
return eInternalContainer().eInverseRemove(this, Sys_info_systeminfoPackage.SYSTEM__CPU_USAGE, de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System.class, msgs);
}
return super.eBasicRemoveFromContainerFeature(msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE:
return getEContainer_cpu_usage();
case Sys_info_systeminfoPackage.CPU_USAGE__REAL:
return getReal();
case Sys_info_systeminfoPackage.CPU_USAGE__USER:
return getUser();
case Sys_info_systeminfoPackage.CPU_USAGE__SYS:
return getSys();
case Sys_info_systeminfoPackage.CPU_USAGE__UNIT:
return getUnit();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE:
setEContainer_cpu_usage((de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System)newValue);
return;
case Sys_info_systeminfoPackage.CPU_USAGE__REAL:
setReal((Double)newValue);
return;
case Sys_info_systeminfoPackage.CPU_USAGE__USER:
setUser((Double)newValue);
return;
case Sys_info_systeminfoPackage.CPU_USAGE__SYS:
setSys((Double)newValue);
return;
case Sys_info_systeminfoPackage.CPU_USAGE__UNIT:
setUnit((String)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE:
setEContainer_cpu_usage((de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System)null);
return;
case Sys_info_systeminfoPackage.CPU_USAGE__REAL:
setReal(REAL_EDEFAULT);
return;
case Sys_info_systeminfoPackage.CPU_USAGE__USER:
setUser(USER_EDEFAULT);
return;
case Sys_info_systeminfoPackage.CPU_USAGE__SYS:
setSys(SYS_EDEFAULT);
return;
case Sys_info_systeminfoPackage.CPU_USAGE__UNIT:
setUnit(UNIT_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE:
return getEContainer_cpu_usage() != null;
case Sys_info_systeminfoPackage.CPU_USAGE__REAL:
return real != REAL_EDEFAULT;
case Sys_info_systeminfoPackage.CPU_USAGE__USER:
return user != USER_EDEFAULT;
case Sys_info_systeminfoPackage.CPU_USAGE__SYS:
return sys != SYS_EDEFAULT;
case Sys_info_systeminfoPackage.CPU_USAGE__UNIT:
return UNIT_EDEFAULT == null ? unit != null : !UNIT_EDEFAULT.equals(unit);
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (real: ");
result.append(real);
result.append(", user: ");
result.append(user);
result.append(", sys: ");
result.append(sys);
result.append(", unit: ");
result.append(unit);
result.append(')');
return result.toString();
}
} //Cpu_usageImpl
| markus1978/clickwatch | analysis/de.hub.clickwatch.specificmodels.brn/src/de/hub/clickwatch/specificmodels/brn/sys_info_systeminfo/impl/Cpu_usageImpl.java | Java | apache-2.0 | 14,073 |
/**
*
* Copyright 2016 David Strawn
*
* 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 strawn.longleaf.relay.util;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
/**
*
* @author David Strawn
*
* This class loads configuration from the file system.
*
*/
public class RelayConfigLoader {
private static final String serverConfigLocation = "./resources/serverconfig.properties";
private static final String clientConfigLocation = "./resources/clientconfig.properties";
private final Properties properties;
public RelayConfigLoader() {
properties = new Properties();
}
public void loadServerConfig() throws IOException {
loadConfigFromPath(serverConfigLocation);
}
public void loadClientConfig() throws IOException {
loadConfigFromPath(clientConfigLocation);
}
/**
* Use this method if you want to use a different location for the configuration.
* @param configFileLocation - location of the configuration file
* @throws IOException
*/
public void loadConfigFromPath(String configFileLocation) throws IOException {
FileInputStream fileInputStream = new FileInputStream(configFileLocation);
properties.load(fileInputStream);
fileInputStream.close();
}
public int getPort() {
return Integer.parseInt(properties.getProperty("port"));
}
public String getHost() {
return properties.getProperty("host");
}
}
| strontian/longleaf-relay | src/main/java/strawn/longleaf/relay/util/RelayConfigLoader.java | Java | apache-2.0 | 2,074 |
/**
* 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.oozie.executor.jpa;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.oozie.CoordinatorActionBean;
import org.apache.oozie.CoordinatorJobBean;
import org.apache.oozie.client.CoordinatorAction;
import org.apache.oozie.client.CoordinatorJob;
import org.apache.oozie.local.LocalOozie;
import org.apache.oozie.service.JPAService;
import org.apache.oozie.service.Services;
import org.apache.oozie.test.XDataTestCase;
import org.apache.oozie.util.XmlUtils;
public class TestCoordActionGetForStartJPAExecutor extends XDataTestCase {
Services services;
@Override
protected void setUp() throws Exception {
super.setUp();
services = new Services();
services.init();
cleanUpDBTables();
}
@Override
protected void tearDown() throws Exception {
services.destroy();
super.tearDown();
}
public void testCoordActionGet() throws Exception {
int actionNum = 1;
String errorCode = "000";
String errorMessage = "Dummy";
String resourceXmlName = "coord-action-get.xml";
CoordinatorJobBean job = addRecordToCoordJobTable(CoordinatorJob.Status.RUNNING, false, false);
CoordinatorActionBean action = createCoordAction(job.getId(), actionNum, CoordinatorAction.Status.WAITING,
resourceXmlName, 0);
// Add extra attributes for action
action.setSlaXml(XDataTestCase.slaXml);
action.setErrorCode(errorCode);
action.setErrorMessage(errorMessage);
// Insert the action
insertRecordCoordAction(action);
Path appPath = new Path(getFsTestCaseDir(), "coord");
String actionXml = getCoordActionXml(appPath, resourceXmlName);
Configuration conf = getCoordConf(appPath);
// Pass the expected values
_testGetForStartX(action.getId(), job.getId(), CoordinatorAction.Status.WAITING, 0, action.getId() + "_E",
XDataTestCase.slaXml, resourceXmlName, XmlUtils.prettyPrint(conf).toString(), actionXml,
errorCode, errorMessage);
}
private void _testGetForStartX(String actionId, String jobId, CoordinatorAction.Status status, int pending,
String extId, String slaXml, String resourceXmlName, String createdConf, String actionXml,
String errorCode, String errorMessage) throws Exception {
try {
JPAService jpaService = Services.get().get(JPAService.class);
assertNotNull(jpaService);
CoordActionGetForStartJPAExecutor actionGetCmd = new CoordActionGetForStartJPAExecutor(actionId);
CoordinatorActionBean action = jpaService.execute(actionGetCmd);
assertNotNull(action);
// Check for expected values
assertEquals(actionId, action.getId());
assertEquals(jobId, action.getJobId());
assertEquals(status, action.getStatus());
assertEquals(pending, action.getPending());
assertEquals(createdConf, action.getCreatedConf());
assertEquals(slaXml, action.getSlaXml());
assertEquals(actionXml, action.getActionXml());
assertEquals(extId, action.getExternalId());
assertEquals(errorMessage, action.getErrorMessage());
assertEquals(errorCode, action.getErrorCode());
}
catch (Exception ex) {
ex.printStackTrace();
fail("Unable to GET a record for COORD Action By actionId =" + actionId);
}
}
}
| terrancesnyder/oozie-hadoop2 | core/src/test/java/org/apache/oozie/executor/jpa/TestCoordActionGetForStartJPAExecutor.java | Java | apache-2.0 | 4,358 |
package leetcode.reverse_linked_list_ii;
import common.ListNode;
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if(head == null) return null;
ListNode curRight = head;
for(int len = 0; len < n - m; len++){
curRight = curRight.next;
}
ListNode prevLeft = null;
ListNode curLeft = head;
for(int len = 0; len < m - 1; len++){
prevLeft = curLeft;
curLeft = curLeft.next;
curRight = curRight.next;
}
if(prevLeft == null){
head = curRight;
}else{
prevLeft.next = curRight;
}
for(int len = 0; len < n - m; len++){
ListNode next = curLeft.next;
curLeft.next = curRight.next;
curRight.next = curLeft;
curLeft = next;
}
return head;
}
public static void dump(ListNode node){
while(node != null){
System.err.print(node.val + "->");
node = node.next;
}
System.err.println("null");
}
public static void main(String[] args){
final int N = 10;
ListNode[] list = new ListNode[N];
for(int m = 1; m <= N; m++){
for(int n = m; n <= N; n++){
for(int i = 0; i < N; i++){
list[i] = new ListNode(i);
if(i > 0) list[i - 1].next = list[i];
}
dump(new Solution().reverseBetween(list[0], m, n));
}
}
}
}
| ckclark/leetcode | java/leetcode/reverse_linked_list_ii/Solution.java | Java | apache-2.0 | 1,378 |
/*
* 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.giraph.examples.io.formats;
import com.google.common.collect.Lists;
import org.apache.giraph.edge.Edge;
import org.apache.giraph.edge.EdgeFactory;
import org.apache.giraph.examples.utils.BrachaTouegDeadlockVertexValue;
import org.apache.giraph.graph.Vertex;
import org.apache.giraph.io.formats.TextVertexInputFormat;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.IOException;
import java.util.List;
/**
* VertexInputFormat for the Bracha Toueg Deadlock Detection algorithm
* specified in JSON format.
*/
public class LongLongLongLongVertexInputFormat extends
TextVertexInputFormat<LongWritable, LongWritable,
LongWritable> {
@Override
public TextVertexReader createVertexReader(InputSplit split,
TaskAttemptContext context) {
return new JsonLongLongLongLongVertexReader();
}
/**
* VertexReader use for the Bracha Toueg Deadlock Detection Algorithm.
* The files should be in the following JSON format:
* JSONArray(<vertex id>,
* JSONArray(JSONArray(<dest vertex id>, <edge tag>), ...))
* The tag is use for the N-out-of-M semantics. Two edges with the same tag
* are considered to be combined and, hence, represent to combined requests
* that need to be both satisfied to continue execution.
* Here is an example with vertex id 1, and three edges (requests).
* First edge has a destination vertex 2 with tag 0.
* Second and third edge have a destination vertex respectively of 3 and 4
* with tag 1.
* [1,[[2,0], [3,1], [4,1]]]
*/
class JsonLongLongLongLongVertexReader
extends TextVertexReaderFromEachLineProcessedHandlingExceptions<JSONArray,
JSONException> {
@Override
protected JSONArray preprocessLine(Text line) throws JSONException {
return new JSONArray(line.toString());
}
@Override
protected LongWritable getId(JSONArray jsonVertex) throws JSONException,
IOException {
return new LongWritable(jsonVertex.getLong(0));
}
@Override
protected LongWritable getValue(JSONArray jsonVertex)
throws JSONException, IOException {
return new LongWritable();
}
@Override
protected Iterable<Edge<LongWritable, LongWritable>>
getEdges(JSONArray jsonVertex) throws JSONException, IOException {
JSONArray jsonEdgeArray = jsonVertex.getJSONArray(1);
/* get the edges */
List<Edge<LongWritable, LongWritable>> edges =
Lists.newArrayListWithCapacity(jsonEdgeArray.length());
for (int i = 0; i < jsonEdgeArray.length(); ++i) {
LongWritable targetId;
LongWritable tag;
JSONArray jsonEdge = jsonEdgeArray.getJSONArray(i);
targetId = new LongWritable(jsonEdge.getLong(0));
tag = new LongWritable((long) jsonEdge.getLong(1));
edges.add(EdgeFactory.create(targetId, tag));
}
return edges;
}
@Override
protected Vertex<LongWritable, LongWritable,
LongWritable> handleException(Text line, JSONArray jsonVertex,
JSONException e) {
throw new IllegalArgumentException(
"Couldn't get vertex from line " + line, e);
}
}
}
| KidEinstein/giraph | giraph-examples/src/main/java/org/apache/giraph/examples/io/formats/LongLongLongLongVertexInputFormat.java | Java | apache-2.0 | 4,147 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.testing.json;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import java.io.IOException;
import junit.framework.TestCase;
/**
* Tests {@link GoogleJsonResponseExceptionFactoryTesting}
*
* @author Eric Mintz
*/
public class GoogleJsonResponseExceptionFactoryTestingTest extends TestCase {
private static final JsonFactory JSON_FACTORY = new GsonFactory();
private static final int HTTP_CODE_NOT_FOUND = 404;
private static final String REASON_PHRASE_NOT_FOUND = "NOT FOUND";
public void testCreateException() throws IOException {
GoogleJsonResponseException exception =
GoogleJsonResponseExceptionFactoryTesting.newMock(
JSON_FACTORY, HTTP_CODE_NOT_FOUND, REASON_PHRASE_NOT_FOUND);
assertEquals(HTTP_CODE_NOT_FOUND, exception.getStatusCode());
assertEquals(REASON_PHRASE_NOT_FOUND, exception.getStatusMessage());
}
}
| googleapis/google-api-java-client | google-api-client/src/test/java/com/google/api/client/googleapis/testing/json/GoogleJsonResponseExceptionFactoryTestingTest.java | Java | apache-2.0 | 1,619 |
//============================================================================
//
// Copyright (C) 2006-2022 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
//============================================================================
package org.talend.components.google.drive.connection;
import java.util.EnumSet;
import java.util.Set;
import org.talend.components.api.component.ConnectorTopology;
import org.talend.components.api.component.runtime.ExecutionEngine;
import org.talend.components.api.properties.ComponentProperties;
import org.talend.components.google.drive.GoogleDriveComponentDefinition;
import org.talend.daikon.runtime.RuntimeInfo;
public class GoogleDriveConnectionDefinition extends GoogleDriveComponentDefinition {
public static final String COMPONENT_NAME = "tGoogleDriveConnection"; //$NON-NLS-1$
public GoogleDriveConnectionDefinition() {
super(COMPONENT_NAME);
}
@Override
public Class<? extends ComponentProperties> getPropertyClass() {
return GoogleDriveConnectionProperties.class;
}
@Override
public Set<ConnectorTopology> getSupportedConnectorTopologies() {
return EnumSet.of(ConnectorTopology.NONE);
}
@Override
public RuntimeInfo getRuntimeInfo(ExecutionEngine engine, ComponentProperties properties,
ConnectorTopology connectorTopology) {
assertEngineCompatibility(engine);
assertConnectorTopologyCompatibility(connectorTopology);
return getRuntimeInfo(GoogleDriveConnectionDefinition.SOURCE_OR_SINK_CLASS);
}
@Override
public boolean isStartable() {
return true;
}
}
| Talend/components | components/components-googledrive/components-googledrive-definition/src/main/java/org/talend/components/google/drive/connection/GoogleDriveConnectionDefinition.java | Java | apache-2.0 | 1,926 |
package si.majeric.smarthouse.xstream.dao;
public class SmartHouseConfigReadError extends RuntimeException {
private static final long serialVersionUID = 1L;
public SmartHouseConfigReadError(Exception e) {
super(e);
}
}
| umajeric/smart-house | smart-house-xstream-impl/src/main/java/si/majeric/smarthouse/xstream/dao/SmartHouseConfigReadError.java | Java | apache-2.0 | 228 |
/*
* Licensed to GraphHopper GmbH under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* GraphHopper GmbH 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 com.graphhopper.jsprit.core.algorithm;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Random;
import org.junit.Test;
import com.graphhopper.jsprit.core.algorithm.acceptor.SolutionAcceptor;
import com.graphhopper.jsprit.core.algorithm.listener.SearchStrategyModuleListener;
import com.graphhopper.jsprit.core.algorithm.selector.SolutionSelector;
import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem;
import com.graphhopper.jsprit.core.problem.solution.SolutionCostCalculator;
import com.graphhopper.jsprit.core.problem.solution.VehicleRoutingProblemSolution;
public class SearchStrategyTest {
@Test(expected = IllegalStateException.class)
public void whenANullModule_IsAdded_throwException() {
SolutionSelector select = mock(SolutionSelector.class);
SolutionAcceptor accept = mock(SolutionAcceptor.class);
SolutionCostCalculator calc = mock(SolutionCostCalculator.class);
SearchStrategy strat = new SearchStrategy("strat", select, accept, calc);
strat.addModule(null);
}
@Test
public void whenStratRunsWithOneModule_runItOnes() {
SolutionSelector select = mock(SolutionSelector.class);
SolutionAcceptor accept = mock(SolutionAcceptor.class);
SolutionCostCalculator calc = mock(SolutionCostCalculator.class);
final VehicleRoutingProblem vrp = mock(VehicleRoutingProblem.class);
final VehicleRoutingProblemSolution newSol = mock(VehicleRoutingProblemSolution.class);
when(select.selectSolution(null)).thenReturn(newSol);
final Collection<Integer> runs = new ArrayList<Integer>();
SearchStrategy strat = new SearchStrategy("strat", select, accept, calc);
SearchStrategyModule mod = new SearchStrategyModule() {
@Override
public VehicleRoutingProblemSolution runAndGetSolution(VehicleRoutingProblemSolution vrpSolution) {
runs.add(1);
return vrpSolution;
}
@Override
public String getName() {
return null;
}
@Override
public void addModuleListener(
SearchStrategyModuleListener moduleListener) {
}
};
strat.addModule(mod);
strat.run(vrp, null);
assertEquals(runs.size(), 1);
}
@Test
public void whenStratRunsWithTwoModule_runItTwice() {
SolutionSelector select = mock(SolutionSelector.class);
SolutionAcceptor accept = mock(SolutionAcceptor.class);
SolutionCostCalculator calc = mock(SolutionCostCalculator.class);
final VehicleRoutingProblem vrp = mock(VehicleRoutingProblem.class);
final VehicleRoutingProblemSolution newSol = mock(VehicleRoutingProblemSolution.class);
when(select.selectSolution(null)).thenReturn(newSol);
final Collection<Integer> runs = new ArrayList<Integer>();
SearchStrategy strat = new SearchStrategy("strat", select, accept, calc);
SearchStrategyModule mod = new SearchStrategyModule() {
@Override
public VehicleRoutingProblemSolution runAndGetSolution(VehicleRoutingProblemSolution vrpSolution) {
runs.add(1);
return vrpSolution;
}
@Override
public String getName() {
return null;
}
@Override
public void addModuleListener(
SearchStrategyModuleListener moduleListener) {
}
};
SearchStrategyModule mod2 = new SearchStrategyModule() {
@Override
public VehicleRoutingProblemSolution runAndGetSolution(VehicleRoutingProblemSolution vrpSolution) {
runs.add(1);
return vrpSolution;
}
@Override
public String getName() {
return null;
}
@Override
public void addModuleListener(
SearchStrategyModuleListener moduleListener) {
}
};
strat.addModule(mod);
strat.addModule(mod2);
strat.run(vrp, null);
assertEquals(runs.size(), 2);
}
@Test
public void whenStratRunsWithNModule_runItNTimes() {
SolutionSelector select = mock(SolutionSelector.class);
SolutionAcceptor accept = mock(SolutionAcceptor.class);
SolutionCostCalculator calc = mock(SolutionCostCalculator.class);
final VehicleRoutingProblem vrp = mock(VehicleRoutingProblem.class);
final VehicleRoutingProblemSolution newSol = mock(VehicleRoutingProblemSolution.class);
when(select.selectSolution(null)).thenReturn(newSol);
int N = new Random().nextInt(1000);
final Collection<Integer> runs = new ArrayList<Integer>();
SearchStrategy strat = new SearchStrategy("strat", select, accept, calc);
for (int i = 0; i < N; i++) {
SearchStrategyModule mod = new SearchStrategyModule() {
@Override
public VehicleRoutingProblemSolution runAndGetSolution(VehicleRoutingProblemSolution vrpSolution) {
runs.add(1);
return vrpSolution;
}
@Override
public String getName() {
return null;
}
@Override
public void addModuleListener(
SearchStrategyModuleListener moduleListener) {
}
};
strat.addModule(mod);
}
strat.run(vrp, null);
assertEquals(runs.size(), N);
}
@Test(expected = IllegalStateException.class)
public void whenSelectorDeliversNullSolution_throwException() {
SolutionSelector select = mock(SolutionSelector.class);
SolutionAcceptor accept = mock(SolutionAcceptor.class);
SolutionCostCalculator calc = mock(SolutionCostCalculator.class);
final VehicleRoutingProblem vrp = mock(VehicleRoutingProblem.class);
when(select.selectSolution(null)).thenReturn(null);
int N = new Random().nextInt(1000);
final Collection<Integer> runs = new ArrayList<Integer>();
SearchStrategy strat = new SearchStrategy("strat", select, accept, calc);
for (int i = 0; i < N; i++) {
SearchStrategyModule mod = new SearchStrategyModule() {
@Override
public VehicleRoutingProblemSolution runAndGetSolution(VehicleRoutingProblemSolution vrpSolution) {
runs.add(1);
return vrpSolution;
}
@Override
public String getName() {
return null;
}
@Override
public void addModuleListener(
SearchStrategyModuleListener moduleListener) {
}
};
strat.addModule(mod);
}
strat.run(vrp, null);
assertEquals(runs.size(), N);
}
}
| balage1551/jsprit | jsprit-core/src/test/java/com/graphhopper/jsprit/core/algorithm/SearchStrategyTest.java | Java | apache-2.0 | 8,039 |
package com.apixandru.rummikub.api;
/**
* @author Alexandru-Constantin Bledea
* @since Sep 16, 2015
*/
public enum Rank {
ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, ELEVEN, TWELVE, THIRTEEN;
public int asNumber() {
return ordinal() + 1;
}
@Override
public String toString() {
return String.format("%2d", asNumber());
}
}
| apixandru/rummikub-java | rummikub-model/src/main/java/com/apixandru/rummikub/api/Rank.java | Java | apache-2.0 | 405 |
/*
* Copyright (c) 2008-2015, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.simulator.provisioner;
import com.hazelcast.simulator.common.AgentsFile;
import com.hazelcast.simulator.common.SimulatorProperties;
import com.hazelcast.simulator.utils.Bash;
import com.hazelcast.simulator.utils.jars.HazelcastJARs;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import joptsimple.OptionSpec;
import org.jclouds.compute.ComputeService;
import static com.hazelcast.simulator.common.SimulatorProperties.PROPERTIES_FILE_NAME;
import static com.hazelcast.simulator.utils.CliUtils.initOptionsWithHelp;
import static com.hazelcast.simulator.utils.CliUtils.printHelpAndExit;
import static com.hazelcast.simulator.utils.CloudProviderUtils.isStatic;
import static com.hazelcast.simulator.utils.SimulatorUtils.loadSimulatorProperties;
import static com.hazelcast.simulator.utils.jars.HazelcastJARs.isPrepareRequired;
import static com.hazelcast.simulator.utils.jars.HazelcastJARs.newInstance;
import static java.util.Collections.singleton;
final class ProvisionerCli {
private final OptionParser parser = new OptionParser();
private final OptionSpec<Integer> scaleSpec = parser.accepts("scale",
"Number of Simulator machines to scale to. If the number of machines already exists, the call is ignored. If the"
+ " desired number of machines is smaller than the actual number of machines, machines are terminated.")
.withRequiredArg().ofType(Integer.class);
private final OptionSpec installSpec = parser.accepts("install",
"Installs Simulator on all provisioned machines.");
private final OptionSpec uploadHazelcastSpec = parser.accepts("uploadHazelcast",
"If defined --install will upload the Hazelcast JARs as well.");
private final OptionSpec<Boolean> enterpriseEnabledSpec = parser.accepts("enterpriseEnabled",
"Use JARs of Hazelcast Enterprise Edition.")
.withRequiredArg().ofType(Boolean.class).defaultsTo(false);
private final OptionSpec listAgentsSpec = parser.accepts("list",
"Lists the provisioned machines (from " + AgentsFile.NAME + " file).");
private final OptionSpec<String> downloadSpec = parser.accepts("download",
"Download all files from the remote Worker directories. Use --clean to delete all Worker directories.")
.withOptionalArg().ofType(String.class).defaultsTo("workers");
private final OptionSpec cleanSpec = parser.accepts("clean",
"Cleans the remote Worker directories on the provisioned machines.");
private final OptionSpec killSpec = parser.accepts("kill",
"Kills the Java processes on all provisioned machines (via killall -9 java).");
private final OptionSpec terminateSpec = parser.accepts("terminate",
"Terminates all provisioned machines.");
private final OptionSpec<String> propertiesFileSpec = parser.accepts("propertiesFile",
"The file containing the Simulator properties. If no file is explicitly configured, first the local working directory"
+ " is checked for a file '" + PROPERTIES_FILE_NAME + "'. All missing properties are always loaded from"
+ " '$SIMULATOR_HOME/conf/" + PROPERTIES_FILE_NAME + "'.")
.withRequiredArg().ofType(String.class);
private ProvisionerCli() {
}
static Provisioner init(String[] args) {
ProvisionerCli cli = new ProvisionerCli();
OptionSet options = initOptionsWithHelp(cli.parser, args);
SimulatorProperties properties = loadSimulatorProperties(options, cli.propertiesFileSpec);
ComputeService computeService = isStatic(properties) ? null : new ComputeServiceBuilder(properties).build();
Bash bash = new Bash(properties);
HazelcastJARs hazelcastJARs = null;
boolean enterpriseEnabled = options.valueOf(cli.enterpriseEnabledSpec);
if (options.has(cli.uploadHazelcastSpec)) {
String hazelcastVersionSpec = properties.getHazelcastVersionSpec();
if (isPrepareRequired(hazelcastVersionSpec) || !enterpriseEnabled) {
hazelcastJARs = newInstance(bash, properties, singleton(hazelcastVersionSpec));
}
}
return new Provisioner(properties, computeService, bash, hazelcastJARs, enterpriseEnabled);
}
static void run(String[] args, Provisioner provisioner) {
ProvisionerCli cli = new ProvisionerCli();
OptionSet options = initOptionsWithHelp(cli.parser, args);
try {
if (options.has(cli.scaleSpec)) {
int size = options.valueOf(cli.scaleSpec);
provisioner.scale(size);
} else if (options.has(cli.installSpec)) {
provisioner.installSimulator();
} else if (options.has(cli.listAgentsSpec)) {
provisioner.listMachines();
} else if (options.has(cli.downloadSpec)) {
String dir = options.valueOf(cli.downloadSpec);
provisioner.download(dir);
} else if (options.has(cli.cleanSpec)) {
provisioner.clean();
} else if (options.has(cli.killSpec)) {
provisioner.killJavaProcesses();
} else if (options.has(cli.terminateSpec)) {
provisioner.terminate();
} else {
printHelpAndExit(cli.parser);
}
} finally {
provisioner.shutdown();
}
}
}
| Danny-Hazelcast/hazelcast-stabilizer | simulator/src/main/java/com/hazelcast/simulator/provisioner/ProvisionerCli.java | Java | apache-2.0 | 6,122 |
package com.cognizant.cognizantits.qcconnection.qcupdation;
import com4j.DISPID;
import com4j.IID;
import com4j.VTID;
@IID("{B739B750-BFE1-43AF-8DD7-E8E8EFBBED7D}")
public abstract interface IDashboardFolderFactory
extends IBaseFactoryEx
{
@DISPID(9)
@VTID(17)
public abstract IList getChildPagesWithPrivateItems(IList paramIList);
}
/* Location: D:\Prabu\jars\QC.jar
* Qualified Name: qcupdation.IDashboardFolderFactory
* JD-Core Version: 0.7.0.1
*/ | CognizantQAHub/Cognizant-Intelligent-Test-Scripter | QcConnection/src/main/java/com/cognizant/cognizantits/qcconnection/qcupdation/IDashboardFolderFactory.java | Java | apache-2.0 | 482 |
/*
* Copyright (C) 2016 QAware GmbH
*
* 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 de.qaware.chronix.timeseries.dt;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import java.io.Serializable;
import java.util.Arrays;
import static de.qaware.chronix.timeseries.dt.ListUtil.*;
/**
* Implementation of a list with primitive doubles.
*
* @author f.lautenschlager
*/
public class DoubleList implements Serializable {
private static final long serialVersionUID = -1275724597860546074L;
/**
* Shared empty array instance used for empty instances.
*/
private static final double[] EMPTY_ELEMENT_DATA = {};
/**
* Shared empty array instance used for default sized empty instances. We
* distinguish this from EMPTY_ELEMENT_DATA to know how much to inflate when
* first element is added.
*/
private static final double[] DEFAULT_CAPACITY_EMPTY_ELEMENT_DATA = {};
private double[] doubles;
private int size;
/**
* Constructs an empty list with the specified initial capacity.
*
* @param initialCapacity the initial capacity of the list
* @throws IllegalArgumentException if the specified initial capacity
* is negative
*/
public DoubleList(int initialCapacity) {
if (initialCapacity > 0) {
this.doubles = new double[initialCapacity];
} else if (initialCapacity == 0) {
this.doubles = EMPTY_ELEMENT_DATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity);
}
}
/**
* Constructs an empty list with an initial capacity of ten.
*/
public DoubleList() {
this.doubles = DEFAULT_CAPACITY_EMPTY_ELEMENT_DATA;
}
/**
* Constructs a double list from the given values by simple assigning them.
*
* @param longs the values of the double list.
* @param size the index of the last value in the array.
*/
@SuppressWarnings("all")
public DoubleList(double[] longs, int size) {
if (longs == null) {
throw new IllegalArgumentException("Illegal initial array 'null'");
}
if (size < 0) {
throw new IllegalArgumentException("Size if negative.");
}
this.doubles = longs;
this.size = size;
}
/**
* Returns the number of elements in this list.
*
* @return the number of elements in this list
*/
public int size() {
return size;
}
/**
* Returns <tt>true</tt> if this list contains no elements.
*
* @return <tt>true</tt> if this list contains no elements
*/
public boolean isEmpty() {
return size == 0;
}
/**
* Returns <tt>true</tt> if this list contains the specified element.
* More formally, returns <tt>true</tt> if and only if this list contains
* at least one element <tt>e</tt> such that
* <tt>(o==null ? e==null : o.equals(e))</tt>.
*
* @param o element whose presence in this list is to be tested
* @return <tt>true</tt> if this list contains the specified element
*/
public boolean contains(double o) {
return indexOf(o) >= 0;
}
/**
* Returns the index of the first occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the lowest index <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*
* @param o the double value
* @return the index of the given double element
*/
public int indexOf(double o) {
for (int i = 0; i < size; i++) {
if (o == doubles[i]) {
return i;
}
}
return -1;
}
/**
* Returns the index of the last occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the highest index <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*
* @param o the double value
* @return the last index of the given double element
*/
public int lastIndexOf(double o) {
for (int i = size - 1; i >= 0; i--) {
if (o == doubles[i]) {
return i;
}
}
return -1;
}
/**
* Returns a shallow copy of this <tt>LongList</tt> instance. (The
* elements themselves are not copied.)
*
* @return a clone of this <tt>LongList</tt> instance
*/
public DoubleList copy() {
DoubleList v = new DoubleList(size);
v.doubles = Arrays.copyOf(doubles, size);
v.size = size;
return v;
}
/**
* Returns an array containing all of the elements in this list
* in proper sequence (from first to last element).
* <p>
* <p>The returned array will be "safe" in that no references to it are
* maintained by this list. (In other words, this method must allocate
* a new array). The caller is thus free to modify the returned array.
* <p>
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all of the elements in this list in
* proper sequence
*/
public double[] toArray() {
return Arrays.copyOf(doubles, size);
}
private void growIfNeeded(int newCapacity) {
if (newCapacity != -1) {
doubles = Arrays.copyOf(doubles, newCapacity);
}
}
/**
* Returns the element at the specified position in this list.
*
* @param index index of the element to return
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException
*/
public double get(int index) {
rangeCheck(index, size);
return doubles[index];
}
/**
* Replaces the element at the specified position in this list with
* the specified element.
*
* @param index index of the element to replace
* @param element element to be stored at the specified position
* @return the element previously at the specified position
* @throws IndexOutOfBoundsException
*/
public double set(int index, double element) {
rangeCheck(index, size);
double oldValue = doubles[index];
doubles[index] = element;
return oldValue;
}
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return <tt>true</tt> (as specified by Collection#add)
*/
public boolean add(double e) {
int newCapacity = calculateNewCapacity(doubles.length, size + 1);
growIfNeeded(newCapacity);
doubles[size++] = e;
return true;
}
/**
* Inserts the specified element at the specified position in this
* list. Shifts the element currently at that position (if any) and
* any subsequent elements to the right (adds one to their indices).
*
* @param index index at which the specified element is to be inserted
* @param element element to be inserted
* @throws IndexOutOfBoundsException
*/
public void add(int index, double element) {
rangeCheckForAdd(index, size);
int newCapacity = calculateNewCapacity(doubles.length, size + 1);
growIfNeeded(newCapacity);
System.arraycopy(doubles, index, doubles, index + 1, size - index);
doubles[index] = element;
size++;
}
/**
* Removes the element at the specified position in this list.
* Shifts any subsequent elements to the left (subtracts one from their
* indices).
*
* @param index the index of the element to be removed
* @return the element that was removed from the list
* @throws IndexOutOfBoundsException
*/
public double remove(int index) {
rangeCheck(index, size);
double oldValue = doubles[index];
int numMoved = size - index - 1;
if (numMoved > 0) {
System.arraycopy(doubles, index + 1, doubles, index, numMoved);
}
--size;
return oldValue;
}
/**
* Removes the first occurrence of the specified element from this list,
* if it is present. If the list does not contain the element, it is
* unchanged. More formally, removes the element with the lowest index
* <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
* (if such an element exists). Returns <tt>true</tt> if this list
* contained the specified element (or equivalently, if this list
* changed as a result of the call).
*
* @param o element to be removed from this list, if present
* @return <tt>true</tt> if this list contained the specified element
*/
public boolean remove(double o) {
for (int index = 0; index < size; index++) {
if (o == doubles[index]) {
fastRemove(index);
return true;
}
}
return false;
}
private void fastRemove(int index) {
int numMoved = size - index - 1;
if (numMoved > 0) {
System.arraycopy(doubles, index + 1, doubles, index, numMoved);
}
--size;
}
/**
* Removes all of the elements from this list. The list will
* be empty after this call returns.
*/
public void clear() {
doubles = DEFAULT_CAPACITY_EMPTY_ELEMENT_DATA;
size = 0;
}
/**
* Appends all of the elements in the specified collection to the end of
* this list, in the order that they are returned by the
* specified collection's Iterator. The behavior of this operation is
* undefined if the specified collection is modified while the operation
* is in progress. (This implies that the behavior of this call is
* undefined if the specified collection is this list, and this
* list is nonempty.)
*
* @param c collection containing elements to be added to this list
* @return <tt>true</tt> if this list changed as a result of the call
* @throws NullPointerException if the specified collection is null
*/
public boolean addAll(DoubleList c) {
double[] a = c.toArray();
int numNew = a.length;
int newCapacity = calculateNewCapacity(doubles.length, size + numNew);
growIfNeeded(newCapacity);
System.arraycopy(a, 0, doubles, size, numNew);
size += numNew;
return numNew != 0;
}
/**
* Appends the long[] at the end of this long list.
*
* @param otherDoubles the other double[] that is appended
* @return <tt>true</tt> if this list changed as a result of the call
* @throws NullPointerException if the specified array is null
*/
public boolean addAll(double[] otherDoubles) {
int numNew = otherDoubles.length;
int newCapacity = calculateNewCapacity(doubles.length, size + numNew);
growIfNeeded(newCapacity);
System.arraycopy(otherDoubles, 0, doubles, size, numNew);
size += numNew;
return numNew != 0;
}
/**
* Inserts all of the elements in the specified collection into this
* list, starting at the specified position. Shifts the element
* currently at that position (if any) and any subsequent elements to
* the right (increases their indices). The new elements will appear
* in the list in the order that they are returned by the
* specified collection's iterator.
*
* @param index index at which to insert the first element from the
* specified collection
* @param c collection containing elements to be added to this list
* @return <tt>true</tt> if this list changed as a result of the call
* @throws IndexOutOfBoundsException
* @throws NullPointerException if the specified collection is null
*/
public boolean addAll(int index, DoubleList c) {
rangeCheckForAdd(index, size);
double[] a = c.toArray();
int numNew = a.length;
int newCapacity = calculateNewCapacity(doubles.length, size + numNew);
growIfNeeded(newCapacity);
int numMoved = size - index;
if (numMoved > 0) {
System.arraycopy(doubles, index, doubles, index + numNew, numMoved);
}
System.arraycopy(a, 0, doubles, index, numNew);
size += numNew;
return numNew != 0;
}
/**
* Removes from this list all of the elements whose index is between
* {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
* Shifts any succeeding elements to the left (reduces their index).
* This call shortens the list by {@code (toIndex - fromIndex)} elements.
* (If {@code toIndex==fromIndex}, this operation has no effect.)
*
* @throws IndexOutOfBoundsException if {@code fromIndex} or
* {@code toIndex} is out of range
* ({@code fromIndex < 0 ||
* fromIndex >= size() ||
* toIndex > size() ||
* toIndex < fromIndex})
*/
public void removeRange(int fromIndex, int toIndex) {
int numMoved = size - toIndex;
System.arraycopy(doubles, toIndex, doubles, fromIndex, numMoved);
size = size - (toIndex - fromIndex);
}
/**
* Trims the capacity of this <tt>ArrayList</tt> instance to be the
* list's current size. An application can use this operation to minimize
* the storage of an <tt>ArrayList</tt> instance.
*/
private double[] trimToSize(int size, double[] elements) {
double[] copy = Arrays.copyOf(elements, elements.length);
if (size < elements.length) {
copy = (size == 0) ? EMPTY_ELEMENT_DATA : Arrays.copyOf(elements, size);
}
return copy;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj.getClass() != getClass()) {
return false;
}
DoubleList rhs = (DoubleList) obj;
double[] thisTrimmed = trimToSize(this.size, this.doubles);
double[] otherTrimmed = trimToSize(rhs.size, rhs.doubles);
return new EqualsBuilder()
.append(thisTrimmed, otherTrimmed)
.append(this.size, rhs.size)
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder()
.append(doubles)
.append(size)
.toHashCode();
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("doubles", trimToSize(this.size, doubles))
.append("size", size)
.toString();
}
/**
* @return maximum of the values of the list
*/
public double max() {
if (size <= 0) {
return Double.NaN;
}
double max = Double.MIN_VALUE;
for (int i = 0; i < size; i++) {
max = doubles[i] > max ? doubles[i] : max;
}
return max;
}
/**
* @return minimum of the values of the list
*/
public double min() {
if (size <= 0) {
return Double.NaN;
}
double min = Double.MAX_VALUE;
for (int i = 0; i < size; i++) {
min = doubles[i] < min ? doubles[i] : min;
}
return min;
}
/**
* @return average of the values of the list
*/
public double avg() {
if (size <= 0) {
return Double.NaN;
}
double current = 0;
for (int i = 0; i < size; i++) {
current += doubles[i];
}
return current / size;
}
/**
* @param scale to be applied to the values of this list
* @return a new instance scaled with the given parameter
*/
public DoubleList scale(double scale) {
DoubleList scaled = new DoubleList(size);
for (int i = 0; i < size; i++) {
scaled.add(doubles[i] * scale);
}
return scaled;
}
/**
* Calculates the standard deviation
*
* @return the standard deviation
*/
public double stdDeviation() {
if (isEmpty()) {
return Double.NaN;
}
return Math.sqrt(variance());
}
private double mean() {
double sum = 0.0;
for (int i = 0; i < size(); i++) {
sum = sum + get(i);
}
return sum / size();
}
private double variance() {
double avg = mean();
double sum = 0.0;
for (int i = 0; i < size(); i++) {
double value = get(i);
sum += (value - avg) * (value - avg);
}
return sum / (size() - 1);
}
/**
* Implemented the quantile type 7 referred to
* http://tolstoy.newcastle.edu.au/R/e17/help/att-1067/Quartiles_in_R.pdf
* and
* http://stat.ethz.ch/R-manual/R-patched/library/stats/html/quantile.html
* as its the default quantile implementation
* <p>
* <code>
* QuantileType7 = function (v, p) {
* v = sort(v)
* h = ((length(v)-1)*p)+1
* v[floor(h)]+((h-floor(h))*(v[floor(h)+1]- v[floor(h)]))
* }
* </code>
*
* @param percentile - the percentile (0 - 1), e.g. 0.25
* @return the value of the n-th percentile
*/
public double percentile(double percentile) {
double[] copy = toArray();
Arrays.sort(copy);// Attention: this is only necessary because this list is not restricted to non-descending values
return evaluateForDoubles(copy, percentile);
}
private static double evaluateForDoubles(double[] points, double percentile) {
//For example:
//values = [1,2,2,3,3,3,4,5,6], size = 9, percentile (e.g. 0.25)
// size - 1 = 8 * 0.25 = 2 (~ 25% from 9) + 1 = 3 => values[3] => 2
double percentileIndex = ((points.length - 1) * percentile) + 1;
double rawMedian = points[floor(percentileIndex - 1)];
double weight = percentileIndex - floor(percentileIndex);
if (weight > 0) {
double pointDistance = points[floor(percentileIndex - 1) + 1] - points[floor(percentileIndex - 1)];
return rawMedian + weight * pointDistance;
} else {
return rawMedian;
}
}
/**
* Wraps the Math.floor function and casts it to an integer
*
* @param value - the evaluatedValue
* @return the floored evaluatedValue
*/
private static int floor(double value) {
return (int) Math.floor(value);
}
}
| 0xhansdampf/chronix.kassiopeia | chronix-kassiopeia-simple/src/main/java/de/qaware/chronix/timeseries/dt/DoubleList.java | Java | apache-2.0 | 19,873 |
package de.devisnik.mine.robot.test;
import de.devisnik.mine.robot.AutoPlayerTest;
import de.devisnik.mine.robot.ConfigurationTest;
import junit.framework.Test;
import junit.framework.TestSuite;
public class AllTests {
public static Test suite() {
TestSuite suite = new TestSuite("Tests for de.devisnik.mine.robot");
//$JUnit-BEGIN$
suite.addTestSuite(AutoPlayerTest.class);
suite.addTestSuite(ConfigurationTest.class);
//$JUnit-END$
return suite;
}
}
| devisnik/mines | robot/src/test/java/de/devisnik/mine/robot/test/AllTests.java | Java | apache-2.0 | 470 |
package com.beanu.l2_shareutil.share;
import androidx.annotation.IntDef;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Created by shaohui on 2016/11/18.
*/
public class SharePlatform {
@IntDef({ DEFAULT, QQ, QZONE, WEIBO, WX, WX_TIMELINE })
@Retention(RetentionPolicy.SOURCE)
public @interface Platform{}
public static final int DEFAULT = 0;
public static final int QQ = 1;
public static final int QZONE = 2;
public static final int WX = 3;
public static final int WX_TIMELINE = 4;
public static final int WEIBO = 5;
}
| beanu/smart-farmer-android | l2_shareutil/src/main/java/com/beanu/l2_shareutil/share/SharePlatform.java | Java | apache-2.0 | 608 |
package com.blp.minotaurus.utils;
import com.blp.minotaurus.Minotaurus;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.plugin.RegisteredServiceProvider;
/**
* @author TheJeterLP
*/
public class EconomyManager {
private static Economy econ = null;
public static boolean setupEconomy() {
if (!Minotaurus.getInstance().getServer().getPluginManager().isPluginEnabled("Vault")) return false;
RegisteredServiceProvider<Economy> rsp = Bukkit.getServicesManager().getRegistration(Economy.class);
if (rsp == null || rsp.getProvider() == null) return false;
econ = rsp.getProvider();
return true;
}
public static Economy getEcon() {
return econ;
}
}
| BossLetsPlays/Minotaurus | src/main/java/com/blp/minotaurus/utils/EconomyManager.java | Java | apache-2.0 | 756 |
package eas.com;
public interface SomeInterface {
String someMethod(String param1, String param2, String param3, String param4);
}
| xalfonso/res_java | java-reflection-method/src/main/java/eas/com/SomeInterface.java | Java | apache-2.0 | 137 |
package com.mobisys.musicplayer.model;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by Govinda P on 6/3/2016.
*/
public class MusicFile implements Parcelable {
private String title;
private String album;
private String id;
private String singer;
private String path;
public MusicFile() {
}
public MusicFile(String title, String album, String id, String singer, String path) {
this.title = title;
this.album = album;
this.id = id;
this.singer = singer;
this.path = path;
}
protected MusicFile(Parcel in) {
title = in.readString();
album = in.readString();
id = in.readString();
singer = in.readString();
path=in.readString();
}
public static final Creator<MusicFile> CREATOR = new Creator<MusicFile>() {
@Override
public MusicFile createFromParcel(Parcel in) {
return new MusicFile(in);
}
@Override
public MusicFile[] newArray(int size) {
return new MusicFile[size];
}
};
public String getTitle() {
return title;
}
public String getAlbum() {
return album;
}
public String getId() {
return id;
}
public String getSinger() {
return singer;
}
public void setTitle(String title) {
this.title = title;
}
public void setAlbum(String album) {
this.album = album;
}
public void setId(String id) {
this.id = id;
}
public void setSinger(String singer) {
this.singer = singer;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
@Override
public String toString() {
return "MusicFile{" +
"title='" + title + '\'' +
", album='" + album + '\'' +
", id='" + id + '\'' +
", singer='" + singer + '\'' +
", path='" + path + '\'' +
'}';
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(title);
dest.writeString(album);
dest.writeString(id);
dest.writeString(singer);
dest.writeString(path);
}
}
| GovindaPaliwal/android-constraint-Layout | app/src/main/java/com/mobisys/musicplayer/model/MusicFile.java | Java | apache-2.0 | 2,408 |
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.cognitoidp.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.cognitoidp.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* AnalyticsMetadataType JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AnalyticsMetadataTypeJsonUnmarshaller implements Unmarshaller<AnalyticsMetadataType, JsonUnmarshallerContext> {
public AnalyticsMetadataType unmarshall(JsonUnmarshallerContext context) throws Exception {
AnalyticsMetadataType analyticsMetadataType = new AnalyticsMetadataType();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("AnalyticsEndpointId", targetDepth)) {
context.nextToken();
analyticsMetadataType.setAnalyticsEndpointId(context.getUnmarshaller(String.class).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return analyticsMetadataType;
}
private static AnalyticsMetadataTypeJsonUnmarshaller instance;
public static AnalyticsMetadataTypeJsonUnmarshaller getInstance() {
if (instance == null)
instance = new AnalyticsMetadataTypeJsonUnmarshaller();
return instance;
}
}
| jentfoo/aws-sdk-java | aws-java-sdk-cognitoidp/src/main/java/com/amazonaws/services/cognitoidp/model/transform/AnalyticsMetadataTypeJsonUnmarshaller.java | Java | apache-2.0 | 2,836 |
package com.doglandia.animatingtextviewlib;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | ThomasKomarnicki/AnimatingTextView | app/src/androidTest/java/com/doglandia/animatingtextviewlib/ApplicationTest.java | Java | apache-2.0 | 365 |
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.seongil.mvplife.fragment;
import android.os.Bundle;
import android.view.View;
import com.seongil.mvplife.base.MvpPresenter;
import com.seongil.mvplife.base.MvpView;
import com.seongil.mvplife.delegate.MvpDelegateCallback;
import com.seongil.mvplife.delegate.fragment.MvpFragmentDelegate;
import com.seongil.mvplife.delegate.fragment.MvpFragmentDelegateImpl;
/**
* Abstract class for the fragment which is holding a reference of the {@link MvpPresenter}
* Also, holding a {@link MvpFragmentDelegate} which is handling the lifecycle of the fragment.
*
* @param <V> The type of {@link MvpView}
* @param <P> The type of {@link MvpPresenter}
*
* @author seong-il, kim
* @since 17. 1. 6
*/
public abstract class BaseMvpFragment<V extends MvpView, P extends MvpPresenter<V>>
extends CoreFragment implements MvpView, MvpDelegateCallback<V, P> {
// ========================================================================
// Constants
// ========================================================================
// ========================================================================
// Fields
// ========================================================================
private MvpFragmentDelegate mFragmentDelegate;
private P mPresenter;
// ========================================================================
// Constructors
// ========================================================================
// ========================================================================
// Getter & Setter
// ========================================================================
// ========================================================================
// Methods for/from SuperClass/Interfaces
// ========================================================================
@Override
public abstract P createPresenter();
@Override
public P getPresenter() {
return mPresenter;
}
@Override
public void setPresenter(P presenter) {
mPresenter = presenter;
}
@Override
@SuppressWarnings("unchecked")
public V getMvpView() {
return (V) this;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getMvpDelegate().onViewCreated(view, savedInstanceState);
}
@Override
public void onDestroyView() {
getMvpDelegate().onDestroyView();
super.onDestroyView();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getMvpDelegate().onCreate(savedInstanceState);
}
@Override
public void onDestroy() {
super.onDestroy();
getMvpDelegate().onDestroy();
}
// ========================================================================
// Methods
// ========================================================================
protected MvpFragmentDelegate getMvpDelegate() {
if (mFragmentDelegate == null) {
mFragmentDelegate = new MvpFragmentDelegateImpl<>(this);
}
return mFragmentDelegate;
}
// ========================================================================
// Inner and Anonymous Classes
// ========================================================================
} | allsoft777/MVP-with-Firebase | mvplife/src/main/java/com/seongil/mvplife/fragment/BaseMvpFragment.java | Java | apache-2.0 | 4,046 |
package org.openstack.atlas.service.domain.exception;
public class UniqueLbPortViolationException extends PersistenceServiceException {
private final String message;
public UniqueLbPortViolationException(final String message) {
this.message = message;
}
@Override
public String getMessage() {
return message;
}
}
| openstack-atlas/atlas-lb | core-persistence/src/main/java/org/openstack/atlas/service/domain/exception/UniqueLbPortViolationException.java | Java | apache-2.0 | 356 |
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University
// Copyright (c) 2011, 2012 Open Networking Foundation
// Copyright (c) 2012, 2013 Big Switch Networks, Inc.
// This library was generated by the LoxiGen Compiler.
// See the file LICENSE.txt which should have been included in the source distribution
// Automatically generated by LOXI from template of_class.java
// Do not modify
package org.projectfloodlight.openflow.protocol.ver13;
import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Set;
import org.jboss.netty.buffer.ChannelBuffer;
import com.google.common.hash.PrimitiveSink;
import com.google.common.hash.Funnel;
class OFOxmBsnUdf4MaskedVer13 implements OFOxmBsnUdf4Masked {
private static final Logger logger = LoggerFactory.getLogger(OFOxmBsnUdf4MaskedVer13.class);
// version: 1.3
final static byte WIRE_VERSION = 4;
final static int LENGTH = 12;
private final static UDF DEFAULT_VALUE = UDF.ZERO;
private final static UDF DEFAULT_VALUE_MASK = UDF.ZERO;
// OF message fields
private final UDF value;
private final UDF mask;
//
// Immutable default instance
final static OFOxmBsnUdf4MaskedVer13 DEFAULT = new OFOxmBsnUdf4MaskedVer13(
DEFAULT_VALUE, DEFAULT_VALUE_MASK
);
// package private constructor - used by readers, builders, and factory
OFOxmBsnUdf4MaskedVer13(UDF value, UDF mask) {
if(value == null) {
throw new NullPointerException("OFOxmBsnUdf4MaskedVer13: property value cannot be null");
}
if(mask == null) {
throw new NullPointerException("OFOxmBsnUdf4MaskedVer13: property mask cannot be null");
}
this.value = value;
this.mask = mask;
}
// Accessors for OF message fields
@Override
public long getTypeLen() {
return 0x31908L;
}
@Override
public UDF getValue() {
return value;
}
@Override
public UDF getMask() {
return mask;
}
@Override
public MatchField<UDF> getMatchField() {
return MatchField.BSN_UDF4;
}
@Override
public boolean isMasked() {
return true;
}
public OFOxm<UDF> getCanonical() {
if (UDF.NO_MASK.equals(mask)) {
return new OFOxmBsnUdf4Ver13(value);
} else if(UDF.FULL_MASK.equals(mask)) {
return null;
} else {
return this;
}
}
@Override
public OFVersion getVersion() {
return OFVersion.OF_13;
}
public OFOxmBsnUdf4Masked.Builder createBuilder() {
return new BuilderWithParent(this);
}
static class BuilderWithParent implements OFOxmBsnUdf4Masked.Builder {
final OFOxmBsnUdf4MaskedVer13 parentMessage;
// OF message fields
private boolean valueSet;
private UDF value;
private boolean maskSet;
private UDF mask;
BuilderWithParent(OFOxmBsnUdf4MaskedVer13 parentMessage) {
this.parentMessage = parentMessage;
}
@Override
public long getTypeLen() {
return 0x31908L;
}
@Override
public UDF getValue() {
return value;
}
@Override
public OFOxmBsnUdf4Masked.Builder setValue(UDF value) {
this.value = value;
this.valueSet = true;
return this;
}
@Override
public UDF getMask() {
return mask;
}
@Override
public OFOxmBsnUdf4Masked.Builder setMask(UDF mask) {
this.mask = mask;
this.maskSet = true;
return this;
}
@Override
public MatchField<UDF> getMatchField() {
return MatchField.BSN_UDF4;
}
@Override
public boolean isMasked() {
return true;
}
@Override
public OFOxm<UDF> getCanonical()throws UnsupportedOperationException {
throw new UnsupportedOperationException("Property canonical not supported in version 1.3");
}
@Override
public OFVersion getVersion() {
return OFVersion.OF_13;
}
@Override
public OFOxmBsnUdf4Masked build() {
UDF value = this.valueSet ? this.value : parentMessage.value;
if(value == null)
throw new NullPointerException("Property value must not be null");
UDF mask = this.maskSet ? this.mask : parentMessage.mask;
if(mask == null)
throw new NullPointerException("Property mask must not be null");
//
return new OFOxmBsnUdf4MaskedVer13(
value,
mask
);
}
}
static class Builder implements OFOxmBsnUdf4Masked.Builder {
// OF message fields
private boolean valueSet;
private UDF value;
private boolean maskSet;
private UDF mask;
@Override
public long getTypeLen() {
return 0x31908L;
}
@Override
public UDF getValue() {
return value;
}
@Override
public OFOxmBsnUdf4Masked.Builder setValue(UDF value) {
this.value = value;
this.valueSet = true;
return this;
}
@Override
public UDF getMask() {
return mask;
}
@Override
public OFOxmBsnUdf4Masked.Builder setMask(UDF mask) {
this.mask = mask;
this.maskSet = true;
return this;
}
@Override
public MatchField<UDF> getMatchField() {
return MatchField.BSN_UDF4;
}
@Override
public boolean isMasked() {
return true;
}
@Override
public OFOxm<UDF> getCanonical()throws UnsupportedOperationException {
throw new UnsupportedOperationException("Property canonical not supported in version 1.3");
}
@Override
public OFVersion getVersion() {
return OFVersion.OF_13;
}
//
@Override
public OFOxmBsnUdf4Masked build() {
UDF value = this.valueSet ? this.value : DEFAULT_VALUE;
if(value == null)
throw new NullPointerException("Property value must not be null");
UDF mask = this.maskSet ? this.mask : DEFAULT_VALUE_MASK;
if(mask == null)
throw new NullPointerException("Property mask must not be null");
return new OFOxmBsnUdf4MaskedVer13(
value,
mask
);
}
}
final static Reader READER = new Reader();
static class Reader implements OFMessageReader<OFOxmBsnUdf4Masked> {
@Override
public OFOxmBsnUdf4Masked readFrom(ChannelBuffer bb) throws OFParseError {
// fixed value property typeLen == 0x31908L
int typeLen = bb.readInt();
if(typeLen != 0x31908)
throw new OFParseError("Wrong typeLen: Expected=0x31908L(0x31908L), got="+typeLen);
UDF value = UDF.read4Bytes(bb);
UDF mask = UDF.read4Bytes(bb);
OFOxmBsnUdf4MaskedVer13 oxmBsnUdf4MaskedVer13 = new OFOxmBsnUdf4MaskedVer13(
value,
mask
);
if(logger.isTraceEnabled())
logger.trace("readFrom - read={}", oxmBsnUdf4MaskedVer13);
return oxmBsnUdf4MaskedVer13;
}
}
public void putTo(PrimitiveSink sink) {
FUNNEL.funnel(this, sink);
}
final static OFOxmBsnUdf4MaskedVer13Funnel FUNNEL = new OFOxmBsnUdf4MaskedVer13Funnel();
static class OFOxmBsnUdf4MaskedVer13Funnel implements Funnel<OFOxmBsnUdf4MaskedVer13> {
private static final long serialVersionUID = 1L;
@Override
public void funnel(OFOxmBsnUdf4MaskedVer13 message, PrimitiveSink sink) {
// fixed value property typeLen = 0x31908L
sink.putInt(0x31908);
message.value.putTo(sink);
message.mask.putTo(sink);
}
}
public void writeTo(ChannelBuffer bb) {
WRITER.write(bb, this);
}
final static Writer WRITER = new Writer();
static class Writer implements OFMessageWriter<OFOxmBsnUdf4MaskedVer13> {
@Override
public void write(ChannelBuffer bb, OFOxmBsnUdf4MaskedVer13 message) {
// fixed value property typeLen = 0x31908L
bb.writeInt(0x31908);
message.value.write4Bytes(bb);
message.mask.write4Bytes(bb);
}
}
@Override
public String toString() {
StringBuilder b = new StringBuilder("OFOxmBsnUdf4MaskedVer13(");
b.append("value=").append(value);
b.append(", ");
b.append("mask=").append(mask);
b.append(")");
return b.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
OFOxmBsnUdf4MaskedVer13 other = (OFOxmBsnUdf4MaskedVer13) obj;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
if (mask == null) {
if (other.mask != null)
return false;
} else if (!mask.equals(other.mask))
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((value == null) ? 0 : value.hashCode());
result = prime * result + ((mask == null) ? 0 : mask.hashCode());
return result;
}
}
| o3project/openflowj-otn | src/main/java/org/projectfloodlight/openflow/protocol/ver13/OFOxmBsnUdf4MaskedVer13.java | Java | apache-2.0 | 10,443 |
package com.tamirhassan.pdfxtk.comparators;
/**
* pdfXtk - PDF Extraction Toolkit
* Copyright (c) by the authors/contributors. All rights reserved.
* This project includes code from PDFBox and TouchGraph.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the names pdfXtk or PDF Extraction Toolkit; nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* http://pdfxtk.sourceforge.net
*
*/
import java.util.Comparator;
import com.tamirhassan.pdfxtk.model.GenericSegment;
/**
* @author Tamir Hassan, [email protected]
* @version PDF Analyser 0.9
*
* Sorts on Xmid coordinate ((x1+x2)/2)
*/
public class XmidComparator implements Comparator<GenericSegment>
{
public int compare(GenericSegment obj1, GenericSegment obj2)
{
// sorts in x order
double x1 = obj1.getXmid();
double x2 = obj2.getXmid();
// causes a contract violation (rounding?)
// return (int) (x1 - x2);
if (x2 > x1) return -1;
else if (x2 == x1) return 0;
else return 1;
}
public boolean equals(Object obj)
{
return obj.equals(this);
}
} | tamirhassan/pdfxtk | src/com/tamirhassan/pdfxtk/comparators/XmidComparator.java | Java | apache-2.0 | 2,438 |
/**
* Copyright (C) 2015 meltmedia ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.meltmedia.dropwizard.etcd.json;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Function;
import java.util.function.Supplier;
import com.codahale.metrics.MetricRegistry;
import mousio.etcd4j.EtcdClient;
import io.dropwizard.Configuration;
import io.dropwizard.ConfiguredBundle;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
public class EtcdJsonBundle<C extends Configuration> implements ConfiguredBundle<C> {
public static class Builder<C extends Configuration> {
private Supplier<EtcdClient> client;
private Supplier<ScheduledExecutorService> executor;
private Function<C, String> directoryAccessor;
public Builder<C> withClient(Supplier<EtcdClient> client) {
this.client = client;
return this;
}
public Builder<C> withExecutor(Supplier<ScheduledExecutorService> executor) {
this.executor = executor;
return this;
}
public Builder<C> withDirectory(Function<C, String> directoryAccessor) {
this.directoryAccessor = directoryAccessor;
return this;
}
public EtcdJsonBundle<C> build() {
return new EtcdJsonBundle<C>(client, executor, directoryAccessor);
}
}
public static <C extends Configuration> Builder<C> builder() {
return new Builder<C>();
}
Supplier<EtcdClient> clientSupplier;
EtcdJson factory;
private Supplier<ScheduledExecutorService> executor;
private Function<C, String> directoryAccessor;
public EtcdJsonBundle(Supplier<EtcdClient> client, Supplier<ScheduledExecutorService> executor,
Function<C, String> directoryAccessor) {
this.clientSupplier = client;
this.executor = executor;
this.directoryAccessor = directoryAccessor;
}
@Override
public void initialize(Bootstrap<?> bootstrap) {
}
@Override
public void run(C configuration, Environment environment) throws Exception {
factory =
EtcdJson.builder().withClient(clientSupplier).withExecutor(executor.get())
.withBaseDirectory(directoryAccessor.apply(configuration))
.withMapper(environment.getObjectMapper())
.withMetricRegistry(environment.metrics()).build();
environment.lifecycle().manage(new EtcdJsonManager(factory));
environment.healthChecks().register("etcd-watch", new WatchServiceHealthCheck(factory.getWatchService()));
}
public EtcdJson getFactory() {
return this.factory;
}
}
| meltmedia/dropwizard-etcd | bundle/src/main/java/com/meltmedia/dropwizard/etcd/json/EtcdJsonBundle.java | Java | apache-2.0 | 3,068 |
import com.google.common.base.Function;
import javax.annotation.Nullable;
/**
* Created by ckale on 10/29/14.
*/
public class DateValueSortFunction implements Function<PojoDTO, Long>{
@Nullable
@Override
public Long apply(@Nullable final PojoDTO input) {
return input.getDateTime().getMillis();
}
}
| chax0r/PlayGround | playGround/src/main/java/DateValueSortFunction.java | Java | apache-2.0 | 329 |
package ru.stqa.javacourse.mantis.tests;
import org.testng.annotations.Test;
import ru.stqa.javacourse.mantis.model.Issue;
import ru.stqa.javacourse.mantis.model.Project;
import javax.xml.rpc.ServiceException;
import java.net.MalformedURLException;
import java.rmi.RemoteException;
import java.util.Set;
import static org.testng.Assert.assertEquals;
public class SoapTest extends TestBase {
@Test
public void testGetProjects() throws MalformedURLException, ServiceException, RemoteException {
Set<Project> projects = app.soap().getProjects();
System.out.println(projects.size());
for (Project project : projects) {
System.out.println(project.getName());
}
}
@Test
public void testCreateIssue() throws RemoteException, ServiceException, MalformedURLException {
Set<Project> projects = app.soap().getProjects();
Issue issue=new Issue().withSummary("test issue")
.withDescription("test issue description").withProject(projects.iterator().next());
Issue created = app.soap().addIssue(issue);
assertEquals(issue.getSummary(),created.getSummary());
}
}
| Olbar/courseJava | mantis-tests/src/test/java/ru/stqa/javacourse/mantis/tests/SoapTest.java | Java | apache-2.0 | 1,172 |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v10/services/customer_conversion_goal_service.proto
package com.google.ads.googleads.v10.services;
/**
* <pre>
* A single operation (update) on a customer conversion goal.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v10.services.CustomerConversionGoalOperation}
*/
public final class CustomerConversionGoalOperation extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v10.services.CustomerConversionGoalOperation)
CustomerConversionGoalOperationOrBuilder {
private static final long serialVersionUID = 0L;
// Use CustomerConversionGoalOperation.newBuilder() to construct.
private CustomerConversionGoalOperation(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CustomerConversionGoalOperation() {
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new CustomerConversionGoalOperation();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private CustomerConversionGoalOperation(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
com.google.ads.googleads.v10.resources.CustomerConversionGoal.Builder subBuilder = null;
if (operationCase_ == 1) {
subBuilder = ((com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_).toBuilder();
}
operation_ =
input.readMessage(com.google.ads.googleads.v10.resources.CustomerConversionGoal.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom((com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_);
operation_ = subBuilder.buildPartial();
}
operationCase_ = 1;
break;
}
case 18: {
com.google.protobuf.FieldMask.Builder subBuilder = null;
if (updateMask_ != null) {
subBuilder = updateMask_.toBuilder();
}
updateMask_ = input.readMessage(com.google.protobuf.FieldMask.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(updateMask_);
updateMask_ = subBuilder.buildPartial();
}
break;
}
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v10.services.CustomerConversionGoalServiceProto.internal_static_google_ads_googleads_v10_services_CustomerConversionGoalOperation_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v10.services.CustomerConversionGoalServiceProto.internal_static_google_ads_googleads_v10_services_CustomerConversionGoalOperation_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v10.services.CustomerConversionGoalOperation.class, com.google.ads.googleads.v10.services.CustomerConversionGoalOperation.Builder.class);
}
private int operationCase_ = 0;
private java.lang.Object operation_;
public enum OperationCase
implements com.google.protobuf.Internal.EnumLite,
com.google.protobuf.AbstractMessage.InternalOneOfEnum {
UPDATE(1),
OPERATION_NOT_SET(0);
private final int value;
private OperationCase(int value) {
this.value = value;
}
/**
* @param value The number of the enum to look for.
* @return The enum associated with the given number.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static OperationCase valueOf(int value) {
return forNumber(value);
}
public static OperationCase forNumber(int value) {
switch (value) {
case 1: return UPDATE;
case 0: return OPERATION_NOT_SET;
default: return null;
}
}
public int getNumber() {
return this.value;
}
};
public OperationCase
getOperationCase() {
return OperationCase.forNumber(
operationCase_);
}
public static final int UPDATE_MASK_FIELD_NUMBER = 2;
private com.google.protobuf.FieldMask updateMask_;
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
* @return Whether the updateMask field is set.
*/
@java.lang.Override
public boolean hasUpdateMask() {
return updateMask_ != null;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
* @return The updateMask.
*/
@java.lang.Override
public com.google.protobuf.FieldMask getUpdateMask() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
@java.lang.Override
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
return getUpdateMask();
}
public static final int UPDATE_FIELD_NUMBER = 1;
/**
* <pre>
* Update operation: The customer conversion goal is expected to have a
* valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code>
* @return Whether the update field is set.
*/
@java.lang.Override
public boolean hasUpdate() {
return operationCase_ == 1;
}
/**
* <pre>
* Update operation: The customer conversion goal is expected to have a
* valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code>
* @return The update.
*/
@java.lang.Override
public com.google.ads.googleads.v10.resources.CustomerConversionGoal getUpdate() {
if (operationCase_ == 1) {
return (com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_;
}
return com.google.ads.googleads.v10.resources.CustomerConversionGoal.getDefaultInstance();
}
/**
* <pre>
* Update operation: The customer conversion goal is expected to have a
* valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v10.resources.CustomerConversionGoalOrBuilder getUpdateOrBuilder() {
if (operationCase_ == 1) {
return (com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_;
}
return com.google.ads.googleads.v10.resources.CustomerConversionGoal.getDefaultInstance();
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (operationCase_ == 1) {
output.writeMessage(1, (com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_);
}
if (updateMask_ != null) {
output.writeMessage(2, getUpdateMask());
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (operationCase_ == 1) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(1, (com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_);
}
if (updateMask_ != null) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(2, getUpdateMask());
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.googleads.v10.services.CustomerConversionGoalOperation)) {
return super.equals(obj);
}
com.google.ads.googleads.v10.services.CustomerConversionGoalOperation other = (com.google.ads.googleads.v10.services.CustomerConversionGoalOperation) obj;
if (hasUpdateMask() != other.hasUpdateMask()) return false;
if (hasUpdateMask()) {
if (!getUpdateMask()
.equals(other.getUpdateMask())) return false;
}
if (!getOperationCase().equals(other.getOperationCase())) return false;
switch (operationCase_) {
case 1:
if (!getUpdate()
.equals(other.getUpdate())) return false;
break;
case 0:
default:
}
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasUpdateMask()) {
hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER;
hash = (53 * hash) + getUpdateMask().hashCode();
}
switch (operationCase_) {
case 1:
hash = (37 * hash) + UPDATE_FIELD_NUMBER;
hash = (53 * hash) + getUpdate().hashCode();
break;
case 0:
default:
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.ads.googleads.v10.services.CustomerConversionGoalOperation prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* A single operation (update) on a customer conversion goal.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v10.services.CustomerConversionGoalOperation}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v10.services.CustomerConversionGoalOperation)
com.google.ads.googleads.v10.services.CustomerConversionGoalOperationOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v10.services.CustomerConversionGoalServiceProto.internal_static_google_ads_googleads_v10_services_CustomerConversionGoalOperation_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v10.services.CustomerConversionGoalServiceProto.internal_static_google_ads_googleads_v10_services_CustomerConversionGoalOperation_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v10.services.CustomerConversionGoalOperation.class, com.google.ads.googleads.v10.services.CustomerConversionGoalOperation.Builder.class);
}
// Construct using com.google.ads.googleads.v10.services.CustomerConversionGoalOperation.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
@java.lang.Override
public Builder clear() {
super.clear();
if (updateMaskBuilder_ == null) {
updateMask_ = null;
} else {
updateMask_ = null;
updateMaskBuilder_ = null;
}
operationCase_ = 0;
operation_ = null;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v10.services.CustomerConversionGoalServiceProto.internal_static_google_ads_googleads_v10_services_CustomerConversionGoalOperation_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v10.services.CustomerConversionGoalOperation getDefaultInstanceForType() {
return com.google.ads.googleads.v10.services.CustomerConversionGoalOperation.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v10.services.CustomerConversionGoalOperation build() {
com.google.ads.googleads.v10.services.CustomerConversionGoalOperation result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v10.services.CustomerConversionGoalOperation buildPartial() {
com.google.ads.googleads.v10.services.CustomerConversionGoalOperation result = new com.google.ads.googleads.v10.services.CustomerConversionGoalOperation(this);
if (updateMaskBuilder_ == null) {
result.updateMask_ = updateMask_;
} else {
result.updateMask_ = updateMaskBuilder_.build();
}
if (operationCase_ == 1) {
if (updateBuilder_ == null) {
result.operation_ = operation_;
} else {
result.operation_ = updateBuilder_.build();
}
}
result.operationCase_ = operationCase_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.ads.googleads.v10.services.CustomerConversionGoalOperation) {
return mergeFrom((com.google.ads.googleads.v10.services.CustomerConversionGoalOperation)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v10.services.CustomerConversionGoalOperation other) {
if (other == com.google.ads.googleads.v10.services.CustomerConversionGoalOperation.getDefaultInstance()) return this;
if (other.hasUpdateMask()) {
mergeUpdateMask(other.getUpdateMask());
}
switch (other.getOperationCase()) {
case UPDATE: {
mergeUpdate(other.getUpdate());
break;
}
case OPERATION_NOT_SET: {
break;
}
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.ads.googleads.v10.services.CustomerConversionGoalOperation) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int operationCase_ = 0;
private java.lang.Object operation_;
public OperationCase
getOperationCase() {
return OperationCase.forNumber(
operationCase_);
}
public Builder clearOperation() {
operationCase_ = 0;
operation_ = null;
onChanged();
return this;
}
private com.google.protobuf.FieldMask updateMask_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> updateMaskBuilder_;
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
* @return Whether the updateMask field is set.
*/
public boolean hasUpdateMask() {
return updateMaskBuilder_ != null || updateMask_ != null;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
* @return The updateMask.
*/
public com.google.protobuf.FieldMask getUpdateMask() {
if (updateMaskBuilder_ == null) {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
} else {
return updateMaskBuilder_.getMessage();
}
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
updateMask_ = value;
onChanged();
} else {
updateMaskBuilder_.setMessage(value);
}
return this;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder setUpdateMask(
com.google.protobuf.FieldMask.Builder builderForValue) {
if (updateMaskBuilder_ == null) {
updateMask_ = builderForValue.build();
onChanged();
} else {
updateMaskBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (updateMask_ != null) {
updateMask_ =
com.google.protobuf.FieldMask.newBuilder(updateMask_).mergeFrom(value).buildPartial();
} else {
updateMask_ = value;
}
onChanged();
} else {
updateMaskBuilder_.mergeFrom(value);
}
return this;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder clearUpdateMask() {
if (updateMaskBuilder_ == null) {
updateMask_ = null;
onChanged();
} else {
updateMask_ = null;
updateMaskBuilder_ = null;
}
return this;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() {
onChanged();
return getUpdateMaskFieldBuilder().getBuilder();
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
if (updateMaskBuilder_ != null) {
return updateMaskBuilder_.getMessageOrBuilder();
} else {
return updateMask_ == null ?
com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>
getUpdateMaskFieldBuilder() {
if (updateMaskBuilder_ == null) {
updateMaskBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>(
getUpdateMask(),
getParentForChildren(),
isClean());
updateMask_ = null;
}
return updateMaskBuilder_;
}
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v10.resources.CustomerConversionGoal, com.google.ads.googleads.v10.resources.CustomerConversionGoal.Builder, com.google.ads.googleads.v10.resources.CustomerConversionGoalOrBuilder> updateBuilder_;
/**
* <pre>
* Update operation: The customer conversion goal is expected to have a
* valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code>
* @return Whether the update field is set.
*/
@java.lang.Override
public boolean hasUpdate() {
return operationCase_ == 1;
}
/**
* <pre>
* Update operation: The customer conversion goal is expected to have a
* valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code>
* @return The update.
*/
@java.lang.Override
public com.google.ads.googleads.v10.resources.CustomerConversionGoal getUpdate() {
if (updateBuilder_ == null) {
if (operationCase_ == 1) {
return (com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_;
}
return com.google.ads.googleads.v10.resources.CustomerConversionGoal.getDefaultInstance();
} else {
if (operationCase_ == 1) {
return updateBuilder_.getMessage();
}
return com.google.ads.googleads.v10.resources.CustomerConversionGoal.getDefaultInstance();
}
}
/**
* <pre>
* Update operation: The customer conversion goal is expected to have a
* valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code>
*/
public Builder setUpdate(com.google.ads.googleads.v10.resources.CustomerConversionGoal value) {
if (updateBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
operation_ = value;
onChanged();
} else {
updateBuilder_.setMessage(value);
}
operationCase_ = 1;
return this;
}
/**
* <pre>
* Update operation: The customer conversion goal is expected to have a
* valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code>
*/
public Builder setUpdate(
com.google.ads.googleads.v10.resources.CustomerConversionGoal.Builder builderForValue) {
if (updateBuilder_ == null) {
operation_ = builderForValue.build();
onChanged();
} else {
updateBuilder_.setMessage(builderForValue.build());
}
operationCase_ = 1;
return this;
}
/**
* <pre>
* Update operation: The customer conversion goal is expected to have a
* valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code>
*/
public Builder mergeUpdate(com.google.ads.googleads.v10.resources.CustomerConversionGoal value) {
if (updateBuilder_ == null) {
if (operationCase_ == 1 &&
operation_ != com.google.ads.googleads.v10.resources.CustomerConversionGoal.getDefaultInstance()) {
operation_ = com.google.ads.googleads.v10.resources.CustomerConversionGoal.newBuilder((com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_)
.mergeFrom(value).buildPartial();
} else {
operation_ = value;
}
onChanged();
} else {
if (operationCase_ == 1) {
updateBuilder_.mergeFrom(value);
}
updateBuilder_.setMessage(value);
}
operationCase_ = 1;
return this;
}
/**
* <pre>
* Update operation: The customer conversion goal is expected to have a
* valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code>
*/
public Builder clearUpdate() {
if (updateBuilder_ == null) {
if (operationCase_ == 1) {
operationCase_ = 0;
operation_ = null;
onChanged();
}
} else {
if (operationCase_ == 1) {
operationCase_ = 0;
operation_ = null;
}
updateBuilder_.clear();
}
return this;
}
/**
* <pre>
* Update operation: The customer conversion goal is expected to have a
* valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code>
*/
public com.google.ads.googleads.v10.resources.CustomerConversionGoal.Builder getUpdateBuilder() {
return getUpdateFieldBuilder().getBuilder();
}
/**
* <pre>
* Update operation: The customer conversion goal is expected to have a
* valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v10.resources.CustomerConversionGoalOrBuilder getUpdateOrBuilder() {
if ((operationCase_ == 1) && (updateBuilder_ != null)) {
return updateBuilder_.getMessageOrBuilder();
} else {
if (operationCase_ == 1) {
return (com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_;
}
return com.google.ads.googleads.v10.resources.CustomerConversionGoal.getDefaultInstance();
}
}
/**
* <pre>
* Update operation: The customer conversion goal is expected to have a
* valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v10.resources.CustomerConversionGoal, com.google.ads.googleads.v10.resources.CustomerConversionGoal.Builder, com.google.ads.googleads.v10.resources.CustomerConversionGoalOrBuilder>
getUpdateFieldBuilder() {
if (updateBuilder_ == null) {
if (!(operationCase_ == 1)) {
operation_ = com.google.ads.googleads.v10.resources.CustomerConversionGoal.getDefaultInstance();
}
updateBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v10.resources.CustomerConversionGoal, com.google.ads.googleads.v10.resources.CustomerConversionGoal.Builder, com.google.ads.googleads.v10.resources.CustomerConversionGoalOrBuilder>(
(com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_,
getParentForChildren(),
isClean());
operation_ = null;
}
operationCase_ = 1;
onChanged();;
return updateBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.ads.googleads.v10.services.CustomerConversionGoalOperation)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v10.services.CustomerConversionGoalOperation)
private static final com.google.ads.googleads.v10.services.CustomerConversionGoalOperation DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v10.services.CustomerConversionGoalOperation();
}
public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CustomerConversionGoalOperation>
PARSER = new com.google.protobuf.AbstractParser<CustomerConversionGoalOperation>() {
@java.lang.Override
public CustomerConversionGoalOperation parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new CustomerConversionGoalOperation(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<CustomerConversionGoalOperation> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CustomerConversionGoalOperation> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v10.services.CustomerConversionGoalOperation getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| googleads/google-ads-java | google-ads-stubs-v10/src/main/java/com/google/ads/googleads/v10/services/CustomerConversionGoalOperation.java | Java | apache-2.0 | 36,172 |
package org.openjava.upay.web.domain;
import java.util.List;
public class TablePage<T>
{
private long start;
private int length;
private long recordsTotal;
private long recordsFiltered;
private List<T> data;
public TablePage()
{
}
public long getStart()
{
return start;
}
public void setStart(long start)
{
this.start = start;
}
public int getLength()
{
return length;
}
public void setLength(int length)
{
this.length = length;
}
public long getRecordsTotal()
{
return recordsTotal;
}
public void setRecordsTotal(long recordsTotal)
{
this.recordsTotal = recordsTotal;
}
public long getRecordsFiltered()
{
return recordsFiltered;
}
public void setRecordsFiltered(long recordsFiltered)
{
this.recordsFiltered = recordsFiltered;
}
public List<T> getData()
{
return data;
}
public void setData(List<T> data)
{
this.data = data;
}
public TablePage wrapData(long total, List<T> data)
{
this.recordsTotal = total;
this.recordsFiltered = total;
this.data = data;
return this;
}
} | openjava2017/openjava-upay | upay-server/src/main/java/org/openjava/upay/web/domain/TablePage.java | Java | apache-2.0 | 1,263 |
package com.jy.controller.workflow.online.apply;
import com.jy.common.ajax.AjaxRes;
import com.jy.common.utils.DateUtils;
import com.jy.common.utils.base.Const;
import com.jy.common.utils.security.AccountShiroUtil;
import com.jy.controller.base.BaseController;
import com.jy.entity.attendance.WorkRecord;
import com.jy.entity.oa.overtime.Overtime;
import com.jy.entity.oa.patch.Patch;
import com.jy.entity.oa.task.TaskInfo;
import com.jy.service.oa.activiti.ActivitiDeployService;
import com.jy.service.oa.overtime.OvertimeService;
import com.jy.service.oa.patch.PatchService;
import com.jy.service.oa.task.TaskInfoService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 补卡页面
*/
@Controller
@RequestMapping(value = "/backstage/workflow/online/patch/")
public class PatchController extends BaseController<Object> {
private static final String SECURITY_URL = "/backstage/workflow/online/patch/index";
@Autowired
private RuntimeService runtimeService;
@Autowired
private TaskService taskService;
@Autowired
private TaskInfoService taskInfoService;
@Autowired
private IdentityService identityService;
@Autowired
private PatchService patchService;
@Autowired
private ActivitiDeployService activitiDeployService;
/**
* 补卡列表
*/
@RequestMapping(value = "index")
public String index(org.springframework.ui.Model model) {
if (doSecurityIntercept(Const.RESOURCES_TYPE_MENU)) {
model.addAttribute("permitBtn", getPermitBtn(Const.RESOURCES_TYPE_FUNCTION));
return "/system/workflow/online/apply/patch";
}
return Const.NO_AUTHORIZED_URL;
}
/**
* 启动流程
*/
@RequestMapping(value = "start", method = RequestMethod.POST)
@ResponseBody
public AjaxRes startWorkflow(Patch o) {
AjaxRes ar = getAjaxRes();
if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_MENU, SECURITY_URL))) {
try {
String currentUserId = AccountShiroUtil.getCurrentUser().getAccountId();
String[] approvers = o.getApprover().split(",");
Map<String, Object> variables = new HashMap<String, Object>();
for (int i = 0; i < approvers.length; i++) {
variables.put("approver" + (i + 1), approvers[i]);
}
String workflowKey = "patch";
identityService.setAuthenticatedUserId(currentUserId);
Date now = new Date();
ProcessInstance processInstance = runtimeService.startProcessInstanceByKeyAndTenantId(workflowKey, variables, getCompany());
String pId = processInstance.getId();
String leaveID = get32UUID();
o.setPid(pId);
o.setAccountId(currentUserId);
o.setCreatetime(now);
o.setIsvalid(0);
o.setName(AccountShiroUtil.getCurrentUser().getName());
o.setId(leaveID);
patchService.insert(o);
Task task = taskService.createTaskQuery().processInstanceId(pId).singleResult();
String processDefinitionName = ((ExecutionEntity) processInstance).getProcessInstance().getProcessDefinition().getName();
String subkect = processDefinitionName + "-"
+ AccountShiroUtil.getCurrentUser().getName() + "-" + DateUtils.formatDate(now, "yyyy-MM-dd HH:mm");
//开始流程
TaskInfo taskInfo = new TaskInfo();
taskInfo.setId(get32UUID());
taskInfo.setBusinesskey(leaveID);
taskInfo.setCode("start");
taskInfo.setName("发起申请");
taskInfo.setStatus(0);
taskInfo.setPresentationsubject(subkect);
taskInfo.setAttr1(processDefinitionName);
taskInfo.setCreatetime(DateUtils.addSeconds(now, -1));
taskInfo.setCompletetime(DateUtils.addSeconds(now, -1));
taskInfo.setCreator(currentUserId);
taskInfo.setAssignee(currentUserId);
taskInfo.setTaskid("0");
taskInfo.setPkey(workflowKey);
taskInfo.setExecutionid("0");
taskInfo.setProcessinstanceid(processInstance.getId());
taskInfo.setProcessdefinitionid(processInstance.getProcessDefinitionId());
taskInfoService.insert(taskInfo);
//第一级审批流程
taskInfo.setId(get32UUID());
taskInfo.setCode(processInstance.getActivityId());
taskInfo.setName(task.getName());
taskInfo.setStatus(1);
taskInfo.setTaskid(task.getId());
taskInfo.setCreatetime(now);
taskInfo.setCompletetime(null);
taskInfo.setAssignee(approvers[0]);
taskInfoService.insert(taskInfo);
ar.setSucceedMsg("发起补卡申请成功!");
} catch (Exception e) {
logger.error(e.toString(), e);
ar.setFailMsg("启动流程失败");
} finally {
identityService.setAuthenticatedUserId(null);
}
}
return ar;
}
}
| futureskywei/whale | src/main/java/com/jy/controller/workflow/online/apply/PatchController.java | Java | apache-2.0 | 5,402 |
/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning 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 com.ning.metrics.eventtracker;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.ning.metrics.serialization.event.ThriftToThriftEnvelopeEvent;
import com.ning.metrics.serialization.writer.SyncType;
import org.joda.time.DateTime;
import org.skife.config.ConfigurationObjectFactory;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.File;
import java.util.UUID;
@Test(enabled = false)
public class TestIntegration
{
private final File tmpDir = new File(System.getProperty("java.io.tmpdir"), "collector");
@SuppressWarnings("unused")
@BeforeTest(alwaysRun = true)
private void setupTmpDir()
{
if (!tmpDir.exists() && !tmpDir.mkdirs()) {
throw new RuntimeException("Failed to create: " + tmpDir);
}
if (!tmpDir.isDirectory()) {
throw new RuntimeException("Path points to something that's not a directory: " + tmpDir);
}
}
@SuppressWarnings("unused")
@AfterTest(alwaysRun = true)
private void cleanupTmpDir()
{
tmpDir.delete();
}
@Test(groups = "slow", enabled = false)
public void testGuiceThrift() throws Exception
{
System.setProperty("eventtracker.type", "SCRIBE");
System.setProperty("eventtracker.directory", tmpDir.getAbsolutePath());
System.setProperty("eventtracker.scribe.host", "127.0.0.1");
System.setProperty("eventtracker.scribe.port", "7911");
final Injector injector = Guice.createInjector(new CollectorControllerModule());
final CollectorController controller = injector.getInstance(CollectorController.class);
final ScribeSender sender = (ScribeSender) injector.getInstance(EventSender.class);
sender.createConnection();
fireThriftEvents(controller);
sender.close();
}
@Test(groups = "slow", enabled = false)
public void testScribeFactory() throws Exception
{
System.setProperty("eventtracker.type", "COLLECTOR");
System.setProperty("eventtracker.directory", tmpDir.getAbsolutePath());
System.setProperty("eventtracker.collector.host", "127.0.0.1");
System.setProperty("eventtracker.collector.port", "8080");
final EventTrackerConfig config = new ConfigurationObjectFactory(System.getProperties()).build(EventTrackerConfig.class);
final CollectorController controller = ScribeCollectorFactory.createScribeController(
config.getScribeHost(),
config.getScribePort(),
config.getScribeRefreshRate(),
config.getScribeMaxIdleTimeInMinutes(),
config.getSpoolDirectoryName(),
config.isFlushEnabled(),
config.getFlushIntervalInSeconds(),
SyncType.valueOf(config.getSyncType()),
config.getSyncBatchSize(),
config.getMaxUncommittedWriteCount(),
config.getMaxUncommittedPeriodInSeconds()
);
fireThriftEvents(controller);
}
private void fireThriftEvents(final CollectorController controller) throws Exception
{
controller.offerEvent(ThriftToThriftEnvelopeEvent.extractEvent("thrift", new DateTime(), new Click(UUID.randomUUID().toString(), new DateTime().getMillis(), "user agent")));
Assert.assertEquals(controller.getEventsReceived().get(), 1);
Assert.assertEquals(controller.getEventsLost().get(), 0);
controller.commit();
controller.flush();
Thread.sleep(5000);
}
}
| pierre/eventtracker | scribe/src/test/java/com/ning/metrics/eventtracker/TestIntegration.java | Java | apache-2.0 | 4,231 |
package com.nosolojava.fsm.impl.runtime.executable.basic;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.nosolojava.fsm.runtime.Context;
import com.nosolojava.fsm.runtime.executable.Elif;
import com.nosolojava.fsm.runtime.executable.Else;
import com.nosolojava.fsm.runtime.executable.Executable;
import com.nosolojava.fsm.runtime.executable.If;
public class BasicIf extends BasicConditional implements If {
private static final long serialVersionUID = -415238773021486012L;
private final List<Elif> elifs = new ArrayList<Elif>();
private final Else elseOperation;
public BasicIf(String condition) {
this(condition, null, null, null);
}
public BasicIf(String condition, List<Executable> executables) {
this(condition, null, null, executables);
}
public BasicIf(String condition, Else elseOperation, List<Executable> executables) {
this(condition, null, elseOperation, executables);
}
public BasicIf(String condition, List<Elif> elifs, Else elseOperation, List<Executable> executables) {
super(condition, executables);
if (elifs != null) {
this.elifs.addAll(elifs);
}
this.elseOperation = elseOperation;
}
@Override
public boolean runIf(Context context) {
boolean result = false;
// if condition fails
if (super.runIf(context)) {
result = true;
} else {
// try with elifs
boolean enterElif = false;
Iterator<Elif> iterElif = elifs.iterator();
Elif elif;
while (!enterElif && iterElif.hasNext()) {
elif = iterElif.next();
enterElif = elif.runIf(context);
}
// if no elif and else
if (!enterElif && this.elseOperation != null) {
elseOperation.run(context);
}
}
return result;
}
public List<Elif> getElifs() {
return this.elifs;
}
public void addElif(Elif elif) {
this.elifs.add(elif);
}
public void addElifs(List<Elif> elifs) {
this.elifs.addAll(elifs);
}
public void clearAndSetElifs(List<Elif> elifs) {
this.elifs.clear();
addElifs(elifs);
}
}
| nosolojava/scxml-java | scxml-java-implementation/src/main/java/com/nosolojava/fsm/impl/runtime/executable/basic/BasicIf.java | Java | apache-2.0 | 2,082 |
/**
* Copyright 2015 Santhosh Kumar Tekuri
*
* The JLibs authors license 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 jlibs.wamp4j.spi;
import java.io.InputStream;
public interface Listener{
public void onMessage(WAMPSocket socket, MessageType type, InputStream is);
public void onReadComplete(WAMPSocket socket);
public void readyToWrite(WAMPSocket socket);
public void onError(WAMPSocket socket, Throwable error);
public void onClose(WAMPSocket socket);
}
| santhosh-tekuri/jlibs | wamp4j-core/src/main/java/jlibs/wamp4j/spi/Listener.java | Java | apache-2.0 | 1,010 |
package me.littlepanda.dadbear.core.queue;
import java.util.Queue;
/**
* @author 张静波 [email protected]
*
*/
public interface DistributedQueue<T> extends Queue<T> {
/**
* <p>如果使用无参构造函数,需要先调用这个方法,队列才能使用</p>
* @param queue_name
* @param clazz
*/
abstract public void init(String queue_name, Class<T> clazz);
}
| myplaylife/dadbear | framework/core/src/main/java/me/littlepanda/dadbear/core/queue/DistributedQueue.java | Java | apache-2.0 | 402 |
/*
* 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 jp.eisbahn.oauth2.server.spi.servlet;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.junit.Test;
public class HttpServletRequestAdapterTest {
@Test
public void test() {
HttpServletRequest request = createMock(HttpServletRequest.class);
expect(request.getParameter("name1")).andReturn("value1");
expect(request.getHeader("name2")).andReturn("value2");
@SuppressWarnings("serial")
Map<String, String[]> map = new HashMap<String, String[]>() {
{
put("k1", new String[]{"v1"});
put("k2", new String[]{"v2"});
}
};
expect(request.getParameterMap()).andReturn(map);
replay(request);
HttpServletRequestAdapter target = new HttpServletRequestAdapter(request);
assertEquals("value1", target.getParameter("name1"));
assertEquals("value2", target.getHeader("name2"));
Map<String, String[]> parameterMap = target.getParameterMap();
assertEquals(2, parameterMap.size());
assertEquals("v1", parameterMap.get("k1")[0]);
assertEquals("v2", parameterMap.get("k2")[0]);
verify(request);
}
}
| morozumi-h/oauth2-server | src/test/java/jp/eisbahn/oauth2/server/spi/servlet/HttpServletRequestAdapterTest.java | Java | apache-2.0 | 1,972 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.