language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
Java | @BetaApi
public final class BatchedRequestIssuer<ResponseT> {
private final BatchedFuture<ResponseT> batchedFuture;
private final long messageCount;
private ResponseT responseToSend;
private Throwable throwableToSend;
public BatchedRequestIssuer(BatchedFuture<ResponseT> batchedFuture, long messageCount) {
this.batchedFuture = batchedFuture;
this.messageCount = messageCount;
this.responseToSend = null;
this.throwableToSend = null;
}
public long getMessageCount() {
return messageCount;
}
/**
* Set the response to set on the batched future. If this is called, setException cannot be
* called.
*/
public void setResponse(ResponseT response) {
Preconditions.checkState(throwableToSend == null, "Cannot set both exception and response");
responseToSend = response;
}
/**
* Set the exception to set on the batched future. If this is called, setResponse cannot be
* called.
*/
public void setException(Throwable throwable) {
Preconditions.checkState(responseToSend == null, "Cannot set both exception and response");
throwableToSend = throwable;
}
/** Sends back the result that was stored by either setResponse or setException */
public void sendResult() {
if (responseToSend != null) {
batchedFuture.set(responseToSend);
} else if (throwableToSend != null) {
batchedFuture.setException(throwableToSend);
} else {
throw new IllegalStateException(
"Neither response nor exception were set in BatchedRequestIssuer");
}
}
} |
Java | public class LogScriptEngine {
private static Logger logger = Logger.getLogger(LogScriptEngine.class);
private static final long DEFAULT_TIMEOUT = 20*60*1000*Simulation.MILLISECOND; /* 1200s = 20 minutes */
private ScriptEngine engine =
new ScriptEngineManager().getEngineByName("JavaScript");
/* Log output listener */
private LogOutputListener logOutputListener = new LogOutputListener() {
public void moteWasAdded(Mote mote) {
}
public void moteWasRemoved(Mote mote) {
}
public void newLogOutput(LogOutputEvent ev) {
handleNewMoteOutput(
ev.getMote(),
ev.getMote().getID(),
ev.getTime(),
ev.msg
);
}
public void removedLogOutput(LogOutputEvent ev) {
}
};
private Semaphore semaphoreScript = null; /* Semaphores blocking script/simulation */
private Semaphore semaphoreSim = null;
private Thread scriptThread = null; /* Script thread */
private Observer scriptLogObserver = null;
private ScriptMote scriptMote;
private boolean stopSimulation = false, quitCooja = false;
private Simulation simulation;
private boolean scriptActive = false;
private long timeout;
private long startTime;
private long startRealTime;
private long nextProgress;
private int exitCode = 0;
public LogScriptEngine(Simulation simulation) {
this.simulation = simulation;
}
/* Only called from the simulation loop */
private void stepScript() {
/* Release script - halt simulation */
Semaphore semScript = semaphoreScript;
Semaphore semSim = semaphoreSim;
if (semScript == null || semSim == null) {
return;
}
semScript.release();
/* ... script executing ... */
try {
semSim.acquire();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
/* ... script is now again waiting for script semaphore ... */
/* Check if test script requested us to stop */
if (stopSimulation) {
stopSimulationRunnable.run();
stopSimulation = false;
}
if (quitCooja) {
quitRunnable.run();
quitCooja = false;
}
}
/* Only called from the simulation loop */
private void handleNewMoteOutput(Mote mote, int id, long time, String msg) {
try {
if (scriptThread == null ||
!scriptThread.isAlive()) {
logger.warn("No script thread, deactivate script.");
/*scriptThread.isInterrupted()*/
return;
}
/* Update script variables */
engine.put("mote", mote);
engine.put("id", id);
engine.put("time", time);
engine.put("msg", msg);
stepScript();
} catch (UndeclaredThrowableException e) {
logger.fatal("Exception: " + e.getMessage(), e);
if (Cooja.isVisualized()) {
Cooja.showErrorDialog(Cooja.getTopParentContainer(),
e.getMessage(),
e, false);
}
simulation.stopSimulation();
}
}
/**
* Inject faked mote log output.
* Should only be used for debugging!
*
* @param msg Log message
* @param mote Mote
*/
public void fakeMoteLogOutput(final String msg, final Mote mote) {
simulation.invokeSimulationThread(new Runnable() {
public void run() {
handleNewMoteOutput(
mote,
mote.getID(),
mote.getSimulation().getSimulationTime(),
msg
);
}
});
}
public void setScriptLogObserver(Observer observer) {
scriptLogObserver = observer;
}
/**
* Deactivate script
*/
public void deactivateScript() {
if (!scriptActive) {
return;
}
scriptActive = false;
timeoutEvent.remove();
timeoutProgressEvent.remove();
simulation.getEventCentral().removeLogOutputListener(logOutputListener);
engine.put("SHUTDOWN", true);
try {
if (semaphoreScript != null) {
semaphoreScript.release(100);
}
} catch (Exception e) {
} finally {
semaphoreScript = null;
}
try {
if (semaphoreSim != null) {
semaphoreSim.release(100);
}
} catch (Exception e) {
} finally {
semaphoreSim = null;
}
if (scriptThread != null &&
scriptThread != Thread.currentThread() /* XXX May deadlock */ ) {
try {
scriptThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
}
}
scriptThread = null;
}
public void activateScript(String scriptCode) throws ScriptException {
if (scriptActive) {
return;
}
scriptActive = true;
if (semaphoreScript != null) {
logger.warn("Semaphores were not reset correctly");
semaphoreScript.release(100);
semaphoreScript = null;
}
if (semaphoreSim != null) {
logger.warn("Semaphores were not reset correctly");
semaphoreSim.release(100);
semaphoreSim = null;
}
scriptThread = null;
/* Parse current script */
ScriptParser parser = new ScriptParser(scriptCode);
String jsCode = parser.getJSCode();
timeout = parser.getTimeoutTime();
if (timeout < 0) {
timeout = DEFAULT_TIMEOUT;
logger.info("Default script timeout in " + (timeout/Simulation.MILLISECOND) + " ms");
} else {
logger.info("Script timeout in " + (timeout/Simulation.MILLISECOND) + " ms");
}
engine.eval(jsCode);
/* Setup script control */
semaphoreScript = new Semaphore(1);
semaphoreSim = new Semaphore(1);
engine.put("TIMEOUT", false);
engine.put("SHUTDOWN", false);
engine.put("SEMAPHORE_SCRIPT", semaphoreScript);
engine.put("SEMAPHORE_SIM", semaphoreSim);
try {
semaphoreScript.acquire();
} catch (InterruptedException e) {
logger.fatal("Error when creating engine: " + e.getMessage(), e);
}
ThreadGroup group = new ThreadGroup("script") {
public void uncaughtException(Thread t, Throwable e) {
while (e.getCause() != null) {
e = e.getCause();
}
if (e.getMessage() != null &&
e.getMessage().contains("test script killed") ) {
/* Ignore normal shutdown exceptions */
} else {
logger.fatal("Script error:", e);
}
}
};
scriptThread = new Thread(group, new Runnable() {
public void run() {
/*logger.info("test script thread starts");*/
try {
((Invocable)engine).getInterface(Runnable.class).run();
} catch (RuntimeException e) {
Throwable throwable = e;
while (throwable.getCause() != null) {
throwable = throwable.getCause();
}
if (throwable.getMessage() != null &&
throwable.getMessage().contains("test script killed") ) {
logger.info("Test script finished");
} else {
if (!Cooja.isVisualized()) {
logger.fatal("Test script error, terminating Cooja.");
logger.fatal("Script error:", e);
System.exit(1);
}
logger.fatal("Script error:", e);
deactivateScript();
simulation.stopSimulation();
if (Cooja.isVisualized()) {
Cooja.showErrorDialog(Cooja.getTopParentContainer(),
"Script error", e, false);
}
}
}
/*logger.info("test script thread exits");*/
}
});
scriptThread.start(); /* Starts by acquiring semaphore (blocks) */
while (!semaphoreScript.hasQueuedThreads()) {
Thread.yield();
}
/* Setup simulation observers */
simulation.getEventCentral().addLogOutputListener(logOutputListener);
/* Create script output logger */
engine.put("log", scriptLog);
Hashtable<Object, Object> hash = new Hashtable<Object, Object>();
engine.put("global", hash);
engine.put("sim", simulation);
engine.put("gui", simulation.getCooja());
engine.put("msg", new String(""));
scriptMote = new ScriptMote();
engine.put("node", scriptMote);
Runnable activate = new Runnable() {
public void run() {
startRealTime = System.currentTimeMillis();
startTime = simulation.getSimulationTime();
long endTime = startTime + timeout;
nextProgress = startTime + (endTime - startTime)/20;
timeoutProgressEvent.remove();
simulation.scheduleEvent(timeoutProgressEvent, nextProgress);
timeoutEvent.remove();
simulation.scheduleEvent(timeoutEvent, endTime);
}
};
if (simulation.isRunning()) {
simulation.invokeSimulationThread(activate);
} else {
activate.run();
}
}
private final TimeEvent timeoutEvent = new TimeEvent() {
public void execute(long t) {
if (!scriptActive) {
return;
}
exitCode = 2;
logger.info("Timeout event @ " + t);
engine.put("TIMEOUT", true);
stepScript();
}
};
private final TimeEvent timeoutProgressEvent = new TimeEvent() {
public void execute(long t) {
nextProgress = t + timeout/20;
simulation.scheduleEvent(this, nextProgress);
double progress = 1.0*(t - startTime)/timeout;
long realDuration = System.currentTimeMillis()-startRealTime;
double estimatedLeft = 1.0*realDuration/progress - realDuration;
if (estimatedLeft == 0) estimatedLeft = 1;
logger.info(String.format("Test script at %2.2f%%, done in %2.1f sec", 100*progress, estimatedLeft/1000));
}
};
private Runnable stopSimulationRunnable = new Runnable() {
public void run() {
simulation.stopSimulation();
}
};
private Runnable quitRunnable = new Runnable() {
public void run() {
simulation.stopSimulation();
new Thread() {
public void run() {
try { Thread.sleep(500); } catch (InterruptedException e) { }
simulation.getCooja().doQuit(false, exitCode);
};
}.start();
new Thread() {
public void run() {
try { Thread.sleep(2000); } catch (InterruptedException e) { }
logger.warn("Killing Cooja");
System.exit(exitCode);
};
}.start();
}
};
private ScriptLog scriptLog = new ScriptLog() {
public void log(String msg) {
if (scriptLogObserver != null) {
scriptLogObserver.update(null, msg);
}
}
public void append(String filename, String msg) {
try{
FileWriter fstream = new FileWriter(filename, true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(msg);
out.close();
} catch (Exception e) {
logger.warn("Test append failed: " + filename + ": " + e.getMessage());
}
}
public void writeFile(String filename, String msg) {
try{
FileWriter fstream = new FileWriter(filename, false);
BufferedWriter out = new BufferedWriter(fstream);
out.write(msg);
out.close();
} catch (Exception e) {
logger.warn("Write file failed: " + filename + ": " + e.getMessage());
}
}
public void testOK() {
exitCode = 0;
log("TEST OK\n");
deactive();
}
public void testFailed() {
exitCode = 1;
log("TEST FAILED\n");
deactive();
}
private void deactive() {
deactivateScript();
if (Cooja.isVisualized()) {
log("[if test was run without visualization, Cooja would now have been terminated]\n");
stopSimulation = true;
simulation.invokeSimulationThread(stopSimulationRunnable);
} else {
quitCooja = true;
simulation.invokeSimulationThread(quitRunnable);
}
throw new RuntimeException("test script killed");
}
public void generateMessage(final long delay, final String msg) {
final Mote currentMote = (Mote) engine.get("mote");
final TimeEvent generateEvent = new TimeEvent() {
public void execute(long t) {
if (scriptThread == null ||
!scriptThread.isAlive()) {
logger.info("script thread not alive. try deactivating script.");
/*scriptThread.isInterrupted()*/
return;
}
/* Update script variables */
engine.put("mote", currentMote);
engine.put("id", currentMote.getID());
engine.put("time", currentMote.getSimulation().getSimulationTime());
engine.put("msg", msg);
stepScript();
}
};
simulation.invokeSimulationThread(new Runnable() {
public void run() {
simulation.scheduleEvent(
generateEvent,
simulation.getSimulationTime() + delay*Simulation.MILLISECOND);
}
});
}
};
} |
Java | public class SensorMobilityModel extends drcl.inet.mac.MobilityModel
{
public static final String REPORT_SENSOR_PORT_ID = ".report_sensor";
/** Connects to the sensor nodes' node position tracker */
protected Port report_SensorPort = addPort(REPORT_SENSOR_PORT_ID, false);
public SensorMobilityModel(long nid_) {
super(nid_);
}
public SensorMobilityModel( ) {
super();
}
/** Sets the dimensions of the terrain of the sensor network */
public void setTopologyParameters(double maxX_, double maxY_, double minX_, double minY_) {
maxX = maxX_; maxY = maxY_; maxZ = 10.0;
minX = minX_; minY = minY_; minZ = 0.0;
dX = 1.0 ; dY = 1.0 ; dZ = 1.0 ;
}
/** Sets the dimensions of the terrain of the sensor network */
public void setTopologyParameters(double maxX_, double maxY_, double maxZ_, double minX_, double minY_, double minZ_) {
maxX = maxX_; maxY = maxY_; maxZ = maxZ_;
minX = minX_; minY = minY_; minZ = minZ_;
dX = 1.0 ; dY = 1.0 ; dZ = 1.0 ;
}
/** Sends position report to the mobility tracker components */
public synchronized void reportPosition(boolean forcedReport) {
if (forcedReport == true || (X-X0) >= dX || (X0-X) >= dX || (Y-Y0) >= dY || (Y0-Y) >= dY || (Z-Z0) >= dZ || (Z0-Z) >= dZ )
{ // if not forced report, report only if the change of position has exceeded the boundary
if ( reportPort.anyPeer() )
{
reportPort.doSending(new PositionReportContract.Message(nid, X, Y, Z, X0, Y0, Z0));
}
X0 = X; Y0 = Y; Z0 = Z;
}
if (forcedReport == true || (X-X0) >= 1.0 || (X0-X) >= 1.0 || (Y-Y0) >= 1.0 || (Y0-Y) >= 1.0 || (Z-Z0) >= 1.0 || (Z0-Z) >= 1.0 )
{ // if not forced report, report only if the change of position has exceeded the boundary
if ( report_SensorPort.anyPeer() )
{
report_SensorPort.doSending(new SensorPositionReportContract.Message(nid, X, Y, Z, X0, Y0, Z0));
}
X0 = X; Y0 = Y; Z0 = Z;
}
}
/** Processes location query and replies with current location */
protected synchronized void processQuery(Object data_)
{
updatePosition();
/* queryPort is a server port, so it can be connected to multiple ports with no problem */
/* If query comes from WirelessPhy */
if (data_ instanceof PositionReportContract.Message)
{
if ( queryPort.anyPeer() )
queryPort.doSending(new PositionReportContract.Message(X, Y, Z));
}
/* If query comes from SensorPhy */
if (data_ instanceof SensorPositionReportContract.Message)
{
if ( queryPort.anyPeer() )
queryPort.doSending(new SensorPositionReportContract.Message(X, Y, Z));
}
}
} |
Java | public class MatlabSaver extends AbstractFileSaver implements BatchConverter, IncrementalConverter {
/** for serialization. */
private static final long serialVersionUID = 4118356803697172614L;
/** the file extension. */
public static String FILE_EXTENSION = MatlabLoader.FILE_EXTENSION;
/** whether to save in double instead of single precision format. */
protected boolean m_UseDouble;
/** whether to use tabs instead of blanks. */
protected boolean m_UseTabs;
/** whether the header was written already. */
protected boolean m_HeaderWritten;
/** for formatting the numbers. */
protected DecimalFormat m_Format;
/**
* Constructor.
*/
public MatlabSaver() {
resetOptions();
}
/**
* Returns a string describing this Saver.
*
* @return a description of the Saver suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "Writes Matlab ASCII files, in single or double precision format.";
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result.addElement(new Option("\tUse double precision format.\n" + "\t(default: single precision)", "double", 0, "-double"));
result.addElement(new Option("\tUse tabs as separator.\n" + "\t(default: blanks)", "tabs", 0, "-tabs"));
result.addAll(Collections.list(super.listOptions()));
return result.elements();
}
/**
* returns the options of the current setup.
*
* @return the current options
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
if (getUseDouble()) {
result.add("-double");
}
if (getUseTabs()) {
result.add("-tabs");
}
Collections.addAll(result, super.getOptions());
return result.toArray(new String[result.size()]);
}
/**
* Parses the options for this object.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -i <the input file>
* The input file
* </pre>
*
* <pre>
* -o <the output file>
* The output file
* </pre>
*
* <pre>
* -double
* Use double precision format.
* (default: single precision)
* </pre>
*
* <pre>
* -tabs
* Use tabs as separator.
* (default: blanks)
* </pre>
*
* <!-- options-end -->
*
* @param options the options to use
* @throws Exception if setting of options fails
*/
@Override
public void setOptions(String[] options) throws Exception {
setUseDouble(Utils.getFlag("double", options));
setUseTabs(Utils.getFlag("tabs", options));
super.setOptions(options);
Utils.checkForRemainingOptions(options);
}
/**
* Returns a description of the file type.
*
* @return a short file description
*/
@Override
public String getFileDescription() {
return "Matlab ASCII files";
}
/**
* Resets the Saver.
*/
@Override
public void resetOptions() {
super.resetOptions();
setFileExtension(MatlabLoader.FILE_EXTENSION);
setUseDouble(false);
setUseTabs(false);
m_HeaderWritten = false;
}
/**
* Sets whether to use double or single precision.
*
* @param value if true then double precision is used
*/
public void setUseDouble(boolean value) {
m_UseDouble = value;
m_Format = (DecimalFormat) NumberFormat.getInstance(Locale.US);
if (m_UseDouble) {
// m_Format = new DecimalFormat(
m_Format.applyPattern(" 0.0000000000000000E00; -0.0000000000000000E00");
} else {
// m_Format = new DecimalFormat(" 0.00000000E00; -0.00000000E00");
m_Format.applyPattern(" 0.00000000E00; -0.00000000E00");
}
}
/**
* Returns whether double or single precision is used.
*
* @return true if double precision is used
*/
public boolean getUseDouble() {
return m_UseDouble;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String useDoubleTipText() {
return "Sets whether to use double instead of single precision.";
}
/**
* Sets whether to use tabs instead of blanks.
*
* @param value if true then tabs are used
*/
public void setUseTabs(boolean value) {
m_UseTabs = value;
}
/**
* Returns whether tabs are used instead of blanks.
*
* @return true if tabs are used
*/
public boolean getUseTabs() {
return m_UseTabs;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String useTabsTipText() {
return "Sets whether to use tabs as separators instead of blanks.";
}
/**
* Returns the Capabilities of this saver.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
// attributes
result.enable(Capability.NUMERIC_ATTRIBUTES);
// class
result.enable(Capability.NUMERIC_CLASS);
result.enable(Capability.NO_CLASS);
return result;
}
/**
* Generates a comment header.
*
* @return the header
*/
protected String matlabHeader() {
StringBuffer result;
int i;
result = new StringBuffer();
result.append("% Relation: " + getInstances().relationName() + "\n");
result.append("% Generated on: " + new Date() + "\n");
result.append("% Generated by: WEKA " + Version.VERSION + "\n");
result.append("%\n");
result.append("% ");
for (i = 0; i < getInstances().numAttributes(); i++) {
if (i > 0) {
result.append((m_UseTabs ? "\t " : " "));
}
result.append(Utils.padRight(getInstances().attribute(i).name(), (m_UseDouble ? 16 : 8) + 5));
}
return result.toString();
}
/**
* turns the instance into a Matlab row.
*
* @param inst the instance to transform
* @return the generated Matlab row
*/
protected String instanceToMatlab(Instance inst) {
StringBuffer result;
int i;
result = new StringBuffer();
// attributes
for (i = 0; i < inst.numAttributes(); i++) {
if (i > 0) {
result.append((m_UseTabs ? "\t" : " "));
}
result.append(m_Format.format(inst.value(i)));
}
return result.toString();
}
/**
* Saves an instances incrementally. Structure has to be set by using the
* setStructure() method or setInstances() method.
*
* @param inst the instance to save
* @throws IOException throws IOEXception if an instance cannot be saved
* incrementally.
*/
@Override
public void writeIncremental(Instance inst) throws IOException {
int writeMode = getWriteMode();
Instances structure = getInstances();
PrintWriter outW = null;
if ((getRetrieval() == BATCH) || (getRetrieval() == NONE)) {
throw new IOException("Batch and incremental saving cannot be mixed.");
}
if (getWriter() != null) {
outW = new PrintWriter(getWriter());
}
if (writeMode == WAIT) {
if (structure == null) {
setWriteMode(CANCEL);
if (inst != null) {
System.err.println("Structure (Header Information) has to be set in advance");
}
} else {
setWriteMode(STRUCTURE_READY);
}
writeMode = getWriteMode();
}
if (writeMode == CANCEL) {
if (outW != null) {
outW.close();
}
cancel();
}
// header
if (writeMode == STRUCTURE_READY) {
setWriteMode(WRITE);
if ((retrieveFile() == null) && (outW == null)) {
System.out.println(matlabHeader());
} else {
outW.println(matlabHeader());
}
writeMode = getWriteMode();
}
// row
if (writeMode == WRITE) {
if (structure == null) {
throw new IOException("No instances information available.");
}
if (inst != null) {
// write instance
if ((retrieveFile() == null) && (outW == null)) {
System.out.println(instanceToMatlab(inst));
} else {
outW.println(instanceToMatlab(inst));
m_incrementalCounter++;
// flush every 100 instances
if (m_incrementalCounter > 100) {
m_incrementalCounter = 0;
outW.flush();
}
}
} else {
// close
if (outW != null) {
outW.flush();
outW.close();
}
m_incrementalCounter = 0;
resetStructure();
outW = null;
resetWriter();
}
}
}
/**
* Writes a Batch of instances.
*
* @throws IOException throws IOException if saving in batch mode is not
* possible
*/
@Override
public void writeBatch() throws IOException {
if (getInstances() == null) {
throw new IOException("No instances to save");
}
if (getRetrieval() == INCREMENTAL) {
throw new IOException("Batch and incremental saving cannot be mixed.");
}
setRetrieval(BATCH);
setWriteMode(WRITE);
if ((retrieveFile() == null) && (getWriter() == null)) {
System.out.println(matlabHeader());
for (int i = 0; i < getInstances().numInstances(); i++) {
System.out.println(instanceToMatlab(getInstances().instance(i)));
}
setWriteMode(WAIT);
} else {
PrintWriter outW = new PrintWriter(getWriter());
outW.println(matlabHeader());
for (int i = 0; i < getInstances().numInstances(); i++) {
outW.println(instanceToMatlab(getInstances().instance(i)));
}
outW.flush();
outW.close();
setWriteMode(WAIT);
outW = null;
resetWriter();
setWriteMode(CANCEL);
}
}
/**
* Main method.
*
* @param args should contain the options of a Saver.
*/
public static void main(String[] args) {
runFileSaver(new MatlabSaver(), args);
}
} |
Java | public class SecurityActions
{
interface RunAsIdentityActions
{
RunAsIdentityActions PRIVILEGED = new RunAsIdentityActions()
{
private final PrivilegedAction peekAction = new PrivilegedAction()
{
public Object run()
{
return SecurityAssociation.peekRunAsIdentity();
}
};
private final PrivilegedAction popAction = new PrivilegedAction()
{
public Object run()
{
return SecurityAssociation.popRunAsIdentity();
}
};
public RunAsIdentity peek()
{
return (RunAsIdentity)AccessController.doPrivileged(peekAction);
}
public void push(final RunAsIdentity id)
{
AccessController.doPrivileged(
new PrivilegedAction()
{
public Object run()
{
SecurityAssociation.pushRunAsIdentity(id);
return null;
}
}
);
}
public RunAsIdentity pop()
{
return (RunAsIdentity)AccessController.doPrivileged(popAction);
}
};
RunAsIdentityActions NON_PRIVILEGED = new RunAsIdentityActions()
{
public RunAsIdentity peek()
{
return SecurityAssociation.peekRunAsIdentity();
}
public void push(RunAsIdentity id)
{
SecurityAssociation.pushRunAsIdentity(id);
}
public RunAsIdentity pop()
{
return SecurityAssociation.popRunAsIdentity();
}
};
RunAsIdentity peek();
void push(RunAsIdentity id);
RunAsIdentity pop();
}
static ClassLoader getContextClassLoader()
{
return TCLAction.UTIL.getContextClassLoader();
}
static ClassLoader getContextClassLoader(Thread thread)
{
return TCLAction.UTIL.getContextClassLoader(thread);
}
static void setContextClassLoader(ClassLoader loader)
{
TCLAction.UTIL.setContextClassLoader(loader);
}
static void setContextClassLoader(Thread thread, ClassLoader loader)
{
TCLAction.UTIL.setContextClassLoader(thread, loader);
}
static void pushRunAsIdentity(RunAsIdentity principal)
{
if(System.getSecurityManager() == null)
{
RunAsIdentityActions.NON_PRIVILEGED.push(principal);
}
else
{
RunAsIdentityActions.PRIVILEGED.push(principal);
}
}
static RunAsIdentity popRunAsIdentity()
{
if(System.getSecurityManager() == null)
{
return RunAsIdentityActions.NON_PRIVILEGED.pop();
}
else
{
return RunAsIdentityActions.PRIVILEGED.pop();
}
}
interface TCLAction
{
class UTIL
{
static TCLAction getTCLAction()
{
return System.getSecurityManager() == null ? NON_PRIVILEGED : PRIVILEGED;
}
static ClassLoader getContextClassLoader()
{
return getTCLAction().getContextClassLoader();
}
static ClassLoader getContextClassLoader(Thread thread)
{
return getTCLAction().getContextClassLoader(thread);
}
static void setContextClassLoader(ClassLoader cl)
{
getTCLAction().setContextClassLoader(cl);
}
static void setContextClassLoader(Thread thread, ClassLoader cl)
{
getTCLAction().setContextClassLoader(thread, cl);
}
}
TCLAction NON_PRIVILEGED = new TCLAction()
{
public ClassLoader getContextClassLoader()
{
return Thread.currentThread().getContextClassLoader();
}
public ClassLoader getContextClassLoader(Thread thread)
{
return thread.getContextClassLoader();
}
public void setContextClassLoader(ClassLoader cl)
{
Thread.currentThread().setContextClassLoader(cl);
}
public void setContextClassLoader(Thread thread, ClassLoader cl)
{
thread.setContextClassLoader(cl);
}
};
TCLAction PRIVILEGED = new TCLAction()
{
private final PrivilegedAction getTCLPrivilegedAction = new PrivilegedAction()
{
public Object run()
{
return Thread.currentThread().getContextClassLoader();
}
};
public ClassLoader getContextClassLoader()
{
return (ClassLoader)AccessController.doPrivileged(getTCLPrivilegedAction);
}
public ClassLoader getContextClassLoader(final Thread thread)
{
return (ClassLoader)AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
return thread.getContextClassLoader();
}
});
}
public void setContextClassLoader(final ClassLoader cl)
{
AccessController.doPrivileged(
new PrivilegedAction()
{
public Object run()
{
Thread.currentThread().setContextClassLoader(cl);
return null;
}
}
);
}
public void setContextClassLoader(final Thread thread, final ClassLoader cl)
{
AccessController.doPrivileged(
new PrivilegedAction()
{
public Object run()
{
thread.setContextClassLoader(cl);
return null;
}
}
);
}
};
ClassLoader getContextClassLoader();
ClassLoader getContextClassLoader(Thread thread);
void setContextClassLoader(ClassLoader cl);
void setContextClassLoader(Thread thread, ClassLoader cl);
}
} |
Java | public final class DictionaryPackInstallBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = DictionaryPackInstallBroadcastReceiver.class.getSimpleName();
final LatinIME mService;
public DictionaryPackInstallBroadcastReceiver() {
// This empty constructor is necessary for the system to instantiate this receiver.
// This happens when the dictionary pack says it can't find a record for our client,
// which happens when the dictionary pack settings are called before the keyboard
// was ever started once.
Log.i(TAG, "Latin IME dictionary broadcast receiver instantiated from the framework.");
mService = null;
}
public DictionaryPackInstallBroadcastReceiver(final LatinIME service) {
mService = service;
}
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
final PackageManager manager = context.getPackageManager();
// We need to reread the dictionary if a new dictionary package is installed.
if (action.equals(Intent.ACTION_PACKAGE_ADDED)) {
if (null == mService) {
Log.e(TAG, "Called with intent " + action + " but we don't know the service: this "
+ "should never happen");
return;
}
final Uri packageUri = intent.getData();
if (null == packageUri) return; // No package name : we can't do anything
final String packageName = packageUri.getSchemeSpecificPart();
if (null == packageName) return;
// TODO: do this in a more appropriate place
TargetPackageInfoGetterTask.removeCachedPackageInfo(packageName);
final PackageInfo packageInfo;
try {
packageInfo = manager.getPackageInfo(packageName, PackageManager.GET_PROVIDERS);
} catch (android.content.pm.PackageManager.NameNotFoundException e) {
return; // No package info : we can't do anything
}
final ProviderInfo[] providers = packageInfo.providers;
if (null == providers) return; // No providers : it is not a dictionary.
// Search for some dictionary pack in the just-installed package. If found, reread.
for (ProviderInfo info : providers) {
if (DictionaryPackConstants.AUTHORITY.equals(info.authority)) {
mService.resetSuggestMainDict();
return;
}
}
// If we come here none of the authorities matched the one we searched for.
// We can exit safely.
return;
} else if (action.equals(Intent.ACTION_PACKAGE_REMOVED)
&& !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
if (null == mService) {
Log.e(TAG, "Called with intent " + action + " but we don't know the service: this "
+ "should never happen");
return;
}
// When the dictionary package is removed, we need to reread dictionary (to use the
// next-priority one, or stop using a dictionary at all if this was the only one,
// since this is the user request).
// If we are replacing the package, we will receive ADDED right away so no need to
// remove the dictionary at the moment, since we will do it when we receive the
// ADDED broadcast.
// TODO: Only reload dictionary on REMOVED when the removed package is the one we
// read dictionary from?
mService.resetSuggestMainDict();
} else if (action.equals(DictionaryPackConstants.NEW_DICTIONARY_INTENT_ACTION)) {
if (null == mService) {
Log.e(TAG, "Called with intent " + action + " but we don't know the service: this "
+ "should never happen");
return;
}
mService.resetSuggestMainDict();
} else if (action.equals(DictionaryPackConstants.UNKNOWN_DICTIONARY_PROVIDER_CLIENT)) {
if (null != mService) {
// Careful! This is returning if the service is NOT null. This is because we
// should come here instantiated by the framework in reaction to a broadcast of
// the above action, so we should gave gone through the no-args constructor.
Log.e(TAG, "Called with intent " + action + " but we have a reference to the "
+ "service: this should never happen");
return;
}
// The dictionary provider does not know about some client. We check that it's really
// us that it needs to know about, and if it's the case, we register with the provider.
final String wantedClientId =
intent.getStringExtra(DictionaryPackConstants.DICTIONARY_PROVIDER_CLIENT_EXTRA);
final String myClientId = context.getString(R.string.dictionary_pack_client_id);
if (!wantedClientId.equals(myClientId)) return; // Not for us
BinaryDictionaryFileDumper.initializeClientRecordHelper(context, myClientId);
}
}
} |
Java | public class RawMessageInfoDecoder {
private final ProtoFieldTypeFactory factory;
private final ProtoReferences references;
RawMessageInfoDecoder(ProtoFieldTypeFactory factory, ProtoReferences references) {
this.factory = factory;
this.references = references;
}
public ProtoMessageInfo run(
DexEncodedMethod dynamicMethod, DexClass context, InvokeMethod invoke) {
assert references.isMessageInfoConstructionMethod(invoke.getInvokedMethod());
Value infoValue = getInfoValueFromMessageInfoConstructionInvoke(invoke, references);
Value objectsValue = getObjectsValueFromMessageInfoConstructionInvoke(invoke, references);
return run(dynamicMethod, context, infoValue, objectsValue);
}
public ProtoMessageInfo run(
DexEncodedMethod dynamicMethod, DexClass context, Value infoValue, Value objectsValue) {
try {
ProtoMessageInfo.Builder builder = ProtoMessageInfo.builder(dynamicMethod);
ThrowingIntIterator<InvalidRawMessageInfoException> infoIterator =
createInfoIterator(infoValue);
// flags := info[0].
int flags = infoIterator.nextIntComputeIfAbsent(this::invalidInfoFailure);
builder.setFlags(flags);
// fieldCount := info[1].
int fieldCount = infoIterator.nextIntComputeIfAbsent(this::invalidInfoFailure);
if (fieldCount == 0) {
return builder.build();
}
// numberOfOneOfObjects := info[2].
int numberOfOneOfObjects = infoIterator.nextIntComputeIfAbsent(this::invalidInfoFailure);
// numberOfHasBitsObjects := info[3].
int numberOfHasBitsObjects = infoIterator.nextIntComputeIfAbsent(this::invalidInfoFailure);
// minFieldNumber := info[4].
// maxFieldNumber := info[5].
// entryCount := info[6].
// mapFieldCount := info[7].
// repeatedFieldCount := info[8].
// checkInitialized := info[9].
for (int i = 4; i < 10; i++) {
// No need to store these values, since they can be computed from the rest (and need to be
// recomputed if the proto is changed).
infoIterator.nextIntComputeIfAbsent(this::invalidInfoFailure);
}
ThrowingIterator<Value, InvalidRawMessageInfoException> objectIterator =
createObjectIterator(objectsValue);
for (int i = 0; i < numberOfOneOfObjects; i++) {
ProtoObject oneOfObject =
createProtoObject(
objectIterator.computeNextIfAbsent(this::invalidObjectsFailure), context);
if (!oneOfObject.isProtoFieldObject()) {
throw new InvalidRawMessageInfoException();
}
ProtoObject oneOfCaseObject =
createProtoObject(
objectIterator.computeNextIfAbsent(this::invalidObjectsFailure), context);
if (!oneOfCaseObject.isProtoFieldObject()) {
throw new InvalidRawMessageInfoException();
}
builder.addOneOfObject(
oneOfObject.asProtoFieldObject(), oneOfCaseObject.asProtoFieldObject());
}
for (int i = 0; i < numberOfHasBitsObjects; i++) {
ProtoObject hasBitsObject =
createProtoObject(
objectIterator.computeNextIfAbsent(this::invalidObjectsFailure), context);
if (!hasBitsObject.isProtoFieldObject()) {
throw new InvalidRawMessageInfoException();
}
builder.addHasBitsObject(hasBitsObject.asProtoFieldObject());
}
boolean isProto2 = ProtoUtils.isProto2(flags);
for (int i = 0; i < fieldCount; i++) {
// Extract field-specific portion of "info" string.
int fieldNumber = infoIterator.nextIntComputeIfAbsent(this::invalidInfoFailure);
int fieldTypeWithExtraBits = infoIterator.nextIntComputeIfAbsent(this::invalidInfoFailure);
ProtoFieldType fieldType = factory.createField(fieldTypeWithExtraBits);
OptionalInt auxData;
if (fieldType.hasAuxData(isProto2)) {
auxData = OptionalInt.of(infoIterator.nextIntComputeIfAbsent(this::invalidInfoFailure));
} else {
auxData = OptionalInt.empty();
}
// Extract field-specific portion of "objects" array.
int numberOfObjects = fieldType.numberOfObjects(isProto2, factory);
try {
List<ProtoObject> objects = new ArrayList<>(numberOfObjects);
for (Value value : objectIterator.take(numberOfObjects)) {
objects.add(createProtoObject(value, context));
}
builder.addField(new ProtoFieldInfo(fieldNumber, fieldType, auxData, objects));
} catch (NoSuchElementException e) {
throw new InvalidRawMessageInfoException();
}
}
// Verify that the input was fully consumed.
if (infoIterator.hasNext() || objectIterator.hasNext()) {
throw new InvalidRawMessageInfoException();
}
return builder.build();
} catch (InvalidRawMessageInfoException e) {
// This should generally not happen, so leave an assert here just in case.
assert false;
return null;
}
}
private ProtoObject createProtoObject(Value value, DexClass context)
throws InvalidRawMessageInfoException {
Value root = value.getAliasedValue();
if (!root.isPhi()) {
Instruction definition = root.definition;
if (definition.isConstClass()) {
ConstClass constClass = definition.asConstClass();
return new ProtoTypeObject(constClass.getValue());
} else if (definition.isConstString()) {
ConstString constString = definition.asConstString();
DexField field = context.lookupUniqueInstanceFieldWithName(constString.getValue());
if (field != null) {
return new LiveProtoFieldObject(field);
}
// This const-string refers to a field that no longer exists. In this case, we create a
// special dead-object instead of failing with an InvalidRawMessageInfoException below.
return new DeadProtoFieldObject(context.type, constString.getValue());
} else if (definition.isDexItemBasedConstString()) {
DexItemBasedConstString constString = definition.asDexItemBasedConstString();
DexReference reference = constString.getItem();
NameComputationInfo<?> nameComputationInfo = constString.getNameComputationInfo();
if (reference.isDexField()
&& nameComputationInfo.isFieldNameComputationInfo()
&& nameComputationInfo.asFieldNameComputationInfo().isForFieldName()) {
DexField field = reference.asDexField();
DexEncodedField encodedField = context.lookupInstanceField(field);
if (encodedField != null) {
return new LiveProtoFieldObject(field);
}
// This const-string refers to a field that no longer exists. In this case, we create a
// special dead-object instead of failing with an InvalidRawMessageInfoException below.
return new DeadProtoFieldObject(context.type, field.name);
}
} else if (definition.isInvokeStatic()) {
InvokeStatic invoke = definition.asInvokeStatic();
if (invoke.arguments().isEmpty()) {
return new ProtoObjectFromInvokeStatic(invoke.getInvokedMethod());
}
} else if (definition.isStaticGet()) {
StaticGet staticGet = definition.asStaticGet();
return new ProtoObjectFromStaticGet(staticGet.getField());
}
}
throw new InvalidRawMessageInfoException();
}
private int invalidInfoFailure() throws InvalidRawMessageInfoException {
throw new InvalidRawMessageInfoException();
}
private Value invalidObjectsFailure() throws InvalidRawMessageInfoException {
throw new InvalidRawMessageInfoException();
}
public static ThrowingIntIterator<InvalidRawMessageInfoException> createInfoIterator(
Value infoValue) throws InvalidRawMessageInfoException {
if (!infoValue.isPhi() && infoValue.definition.isConstString()) {
return createInfoIterator(infoValue.definition.asConstString().getValue());
}
throw new InvalidRawMessageInfoException();
}
/** Returns an iterator that yields the integers that results from decoding the given string. */
private static ThrowingIntIterator<InvalidRawMessageInfoException> createInfoIterator(
DexString info) {
return new ThrowingIntIterator<InvalidRawMessageInfoException>() {
private final ThrowingCharIterator<UTFDataFormatException> charIterator = info.iterator();
@Override
public boolean hasNext() {
return charIterator.hasNext();
}
@Override
public int nextInt() throws InvalidRawMessageInfoException {
if (!hasNext()) {
throw new NoSuchElementException();
}
int value = 0;
int shift = 0;
while (true) {
char c;
try {
c = charIterator.nextChar();
} catch (UTFDataFormatException e) {
throw new InvalidRawMessageInfoException();
}
if (c >= 0xD800 && c < 0xE000) {
throw new InvalidRawMessageInfoException();
}
if (c < 0xD800) {
return value | (c << shift);
}
value |= (c & 0x1FFF) << shift;
shift += 13;
if (!hasNext()) {
throw new InvalidRawMessageInfoException();
}
}
}
};
}
/**
* Returns an iterator that yields the values that are stored in the `objects` array that is
* passed to GeneratedMessageLite.newMessageInfo(). The array values are returned in-order, i.e.,
* the value objects[i] will be returned prior to the value objects[i+1].
*/
private static ThrowingIterator<Value, InvalidRawMessageInfoException> createObjectIterator(
Value objectsValue) throws InvalidRawMessageInfoException {
if (objectsValue.isPhi() || !objectsValue.definition.isNewArrayEmpty()) {
throw new InvalidRawMessageInfoException();
}
NewArrayEmpty newArrayEmpty = objectsValue.definition.asNewArrayEmpty();
int expectedArraySize = objectsValue.uniqueUsers().size() - 1;
// Verify that the size is correct.
Value sizeValue = newArrayEmpty.size().getAliasedValue();
if (sizeValue.isPhi()
|| !sizeValue.definition.isConstNumber()
|| sizeValue.definition.asConstNumber().getIntValue() != expectedArraySize) {
throw new InvalidRawMessageInfoException();
}
// Create an iterator for the block of interest.
InstructionIterator instructionIterator = newArrayEmpty.getBlock().iterator();
instructionIterator.nextUntil(instruction -> instruction == newArrayEmpty);
return new ThrowingIterator<Value, InvalidRawMessageInfoException>() {
private int expectedNextIndex = 0;
@Override
public boolean hasNext() {
while (instructionIterator.hasNext()) {
Instruction next = instructionIterator.peekNext();
if (isArrayPutOfInterest(next)) {
return true;
}
if (next.isJumpInstruction()) {
return false;
}
instructionIterator.next();
}
return false;
}
@Override
public Value next() throws InvalidRawMessageInfoException {
if (!hasNext()) {
throw new NoSuchElementException();
}
ArrayPut arrayPut = instructionIterator.next().asArrayPut();
// Verify that the index correct.
Value indexValue = arrayPut.index().getAliasedValue();
if (indexValue.isPhi()
|| !indexValue.definition.isConstNumber()
|| indexValue.definition.asConstNumber().getIntValue() != expectedNextIndex) {
throw new InvalidRawMessageInfoException();
}
expectedNextIndex++;
return arrayPut.value().getAliasedValue();
}
private boolean isArrayPutOfInterest(Instruction instruction) {
return instruction.isArrayPut()
&& instruction.asArrayPut().array().getAliasedValue() == objectsValue;
}
};
}
private static class InvalidRawMessageInfoException extends Exception {}
} |
Java | public abstract class NdefFormatable implements BasicTagTechnology {
/**
* Get an instance of {@link NdefFormatable} for the given tag.
* <p>Does not cause any RF activity and does not block.
* <p>Returns null if {@link NdefFormatable} was not enumerated in {@link Tag#getTechList}.
* This indicates the tag is not NDEF formatable by this Android device.
*
* @param tag an NDEF formatable tag
* @return NDEF formatable object
*/
public static NdefFormatable get(Tag tag) {
if(tag instanceof TagImpl) {
TagImpl tagImpl = (TagImpl)tag;
if (!tagImpl.hasTech(TagTechnology.NDEF_FORMATABLE)) return null;
try {
return new NdefFormatableImpl(tagImpl);
} catch (RemoteException e) {
return null;
}
} else if(tag instanceof TagWrapper) {
TagWrapper delegate = (TagWrapper)tag;
android.nfc.tech.NdefFormatable ndefFormatable = android.nfc.tech.NdefFormatable.get(delegate.getDelegate());
if(ndefFormatable == null) {
return null;
}
return new NdefFormattableWrapper(ndefFormatable);
} else {
throw new IllegalArgumentException();
}
}
/**
* Format a tag as NDEF, and write a {@link NdefMessage}.
*
* <p>This is a multi-step process, an IOException is thrown
* if any one step fails.
* <p>The card is left in a read-write state after this operation.
*
* <p>This is an I/O operation and will block until complete. It must
* not be called from the main application thread. A blocked call will be canceled with
* {@link IOException} if {@link #close} is called from another thread.
*
* <p class="note">Requires the {@link android.Manifest.permission#NFC} permission.
*
* @param firstMessage the NDEF message to write after formatting, can be null
* @throws android.nfc.TagLostException if the tag leaves the field
* @throws IOException if there is an I/O failure, or the operation is canceled
* @throws FormatException if the NDEF Message to write is malformed
*/
public abstract void format(NdefMessage firstMessage) throws IOException, FormatException;
/**
* Formats a tag as NDEF, write a {@link NdefMessage}, and make read-only.
*
* <p>This is a multi-step process, an IOException is thrown
* if any one step fails.
* <p>The card is left in a read-only state if this method returns successfully.
*
* <p>This is an I/O operation and will block until complete. It must
* not be called from the main application thread. A blocked call will be canceled with
* {@link IOException} if {@link #close} is called from another thread.
*
* <p class="note">Requires the {@link android.Manifest.permission#NFC} permission.
*
* @param firstMessage the NDEF message to write after formatting
* @throws android.nfc.TagLostException if the tag leaves the field
* @throws IOException if there is an I/O failure, or the operation is canceled
* @throws FormatException if the NDEF Message to write is malformed
*/
public abstract void formatReadOnly(NdefMessage firstMessage) throws IOException, FormatException;
} |
Java | @XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "MetadataFloat")
public class MetadataFloat
extends X3DMetadataObject
{
@XmlAttribute(name = "value")
protected MFFloat value;
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link String }
*
*/
public MFFloat getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValue(MFFloat value) {
this.value = value;
}
} |
Java | public class LiRestv2Client extends LiRestClient {
private static final String LOG_TAG = "LiRestv2Client";
private static LiRestv2Client instance;
private LiRestv2Client(@NonNull LiSDKManager manager) throws LiInitializationException {
super(manager);
}
/**
* <p>
* Initializes the Rest Client singleton. If the initialization is successful {@link #getInstance()} will
* return an initialized SDK Manager. This function may or may not create a new instance or reinitialize
* with subsequent calls.
* </p>
*
* @param manager A Li SDK manager
* @throws LiInitializationException if the Rest client fails to initialize.
*/
public static void initialize(@NonNull LiSDKManager manager) throws LiInitializationException {
instance = new LiRestv2Client(manager);
}
/**
* Returns a singleton instance of this class.
*
* @return Instance of this class.
*/
@Nullable
public static LiRestv2Client getInstance() {
if (instance == null) {
try {
// TODO: remove this in next major version.
//noinspection ConstantConditions to support backwards compatibility
initialize(LiSDKManager.getInstance());
} catch (LiInitializationException e) {
e.printStackTrace();
}
}
return instance;
}
/**
* Makes Sync call.
*
* @param baseRestRequest {@link LiBaseRestRequest}
* @throws LiRestResponseException
*/
@Override
public LiBaseResponse processSync(@NonNull LiBaseRestRequest baseRestRequest) throws LiRestResponseException {
LiCoreSDKUtils.checkNotNull(baseRestRequest, MessageConstants.wasNull("baseRestRequest"));
LiRestV2Request restV2Request = getLiRestV2Request(baseRestRequest);
LiBaseResponse response = super.processSync(restV2Request);
return validateResponse(response);
}
/**
* Wraps LiBaseRestRequest to LiRestV2Request.
*
* @param baseRestRequest {@link LiBaseRestRequest}
* @return LiRestV2Request {@link LiRestV2Request}
* @throws LiRestResponseException
*/
@NonNull
private LiRestV2Request getLiRestV2Request(@NonNull LiBaseRestRequest baseRestRequest) throws LiRestResponseException {
LiCoreSDKUtils.checkNotNull(baseRestRequest, MessageConstants.wasNull("baseRestRequest"));
if (!(baseRestRequest instanceof LiBaseRestRequest)) {
Log.e(LOG_TAG, "Invalid rest v2 request");
throw LiRestResponseException.illegalArgumentError("Rest v2 request should pass a liql query request parameter");
}
return (LiRestV2Request) baseRestRequest;
}
/**
* Makes Async call.
*
* @param baseRestRequest {@link LiBaseRestRequest}
* @param callBack {@link LiAsyncRequestCallback}
*/
@Override
public void processAsync(@NonNull LiBaseRestRequest baseRestRequest, @NonNull LiAsyncRequestCallback callBack) {
LiCoreSDKUtils.checkNotNull(baseRestRequest, MessageConstants.wasNull("baseRestRequest"));
LiCoreSDKUtils.checkNotNull(callBack, MessageConstants.wasNull("callback"));
if (!(baseRestRequest instanceof LiBaseRestRequest)) {
Log.e(LOG_TAG, "Invalid rest v2 request");
callBack.onError(LiRestResponseException.illegalArgumentError("Rest v2 request should pass a liql query request parameter"));
}
LiRestV2Request restV2Request = null;
try {
restV2Request = getLiRestV2Request(baseRestRequest);
} catch (LiRestResponseException e) {
callBack.onError(e);
}
if (restV2Request != null) {
super.processAsync(restV2Request, callBack);
}
}
/**
* Makes Async call for uploading an image.
*
* @param baseRestRequest {@link LiBaseRestRequest}
* @param callBack {@link LiAsyncRequestCallback}
* @param imagePath Absolute path of the image file.
* @param imageName Name of the image file.
* @param requestBody request body for post call to upload image.
*/
public void uploadProcessAsync(@NonNull LiBaseRestRequest baseRestRequest, @NonNull LiAsyncRequestCallback callBack, String imagePath,
String imageName, String requestBody) {
LiCoreSDKUtils.checkNotNull(baseRestRequest, MessageConstants.wasNull("baseRestRequest"));
LiCoreSDKUtils.checkNotNull(callBack, MessageConstants.wasNull("callBack"));
if (!(baseRestRequest instanceof LiBaseRestRequest)) {
Log.e(LOG_TAG, "Invalid rest v2 request");
callBack.onError(LiRestResponseException.illegalArgumentError("Rest v2 request should pass a liql query request parameter"));
}
LiRestV2Request restV2Request = null;
try {
restV2Request = getLiRestV2Request(baseRestRequest);
} catch (LiRestResponseException e) {
callBack.onError(e);
}
super.uploadImageProcessAsync(baseRestRequest, callBack, imagePath, imageName, requestBody);
}
/**
* Validating the network response.
*
* @param response {@link LiBaseResponse}
* @return LiBaseResponse {@link LiBaseResponse}
* @throws LiRestResponseException
*/
private LiBaseResponse validateResponse(LiBaseResponse response) throws LiRestResponseException {
String jsonStr = null;
try {
jsonStr = asString(response);
} catch (IOException e) {
Log.e(LOG_TAG, "Error deserializing json");
throw LiRestResponseException.jsonSerializationError("Error deserializing rest response");
}
Gson gson = getGson();
JsonObject jsonObject = gson.fromJson(jsonStr, JsonObject.class);
if (jsonObject.has("http_code")) {
int httpResponeCode = jsonObject.get("http_code").getAsInt();
if (httpResponeCode == 200 || httpResponeCode == 201) {
response.setData(jsonObject);
return response;
} else {
Log.e(LOG_TAG, "Error response from server");
throw LiRestResponseException.fromJson(jsonObject.getAsString(), gson);
}
} else {
Log.e(LOG_TAG, "Error response from server");
throw LiRestResponseException.fromJson(jsonObject.getAsString(), gson);
}
}
} |
Java | public class MyFacesInitializerRegistrationBean extends ServletContainerInitializerRegistrationBean<MyFacesContainerInitializer> {
public MyFacesInitializerRegistrationBean() {
super(MyFacesContainerInitializer.class);
}
@Override
protected void handleScanResult(ScanResult scanResult) {
super.handleScanResult(scanResult);
Map<Class<? extends Annotation>, Set<Class<?>>> annotatedClasses = new HashMap<>();
Arrays.asList(
ManagedBean.class,
FacesComponent.class,
FacesBehavior.class,
FacesConverter.class,
NamedEvent.class,
FacesRenderer.class,
FacesBehaviorRenderer.class,
FacesValidator.class
).forEach(annotationClass -> {
List<Class<?>> classes = scanResult.getClassesWithAnnotation(annotationClass.getName()).loadClasses();
annotatedClasses.put(annotationClass, new HashSet<>(classes));
});
JoinFacesAnnotationProvider.setAnnotatedClasses(annotatedClasses);
}
} |
Java | public class LocalWriter implements ChukwaWriter {
static Logger log = Logger.getLogger(LocalWriter.class);
static final int STAT_INTERVAL_SECONDS = 30;
static String localHostAddr = null;
private int blockSize = 128 * 1024 * 1024;
private int pageSize = 1 * 1024 * 1024;
private final Object lock = new Object();
private BlockingQueue<String> fileQueue = null;
@SuppressWarnings("unused")
private LocalToRemoteHdfsMover localToRemoteHdfsMover = null;
private FileSystem fs = null;
private Configuration conf = null;
private String localOutputDir = null;
private Calendar calendar = Calendar.getInstance();
private Path currentPath = null;
private String currentFileName = null;
private AvroParquetWriter<GenericRecord> parquetWriter = null;
private int rotateInterval = 1000 * 60;
private volatile long dataSize = 0;
private volatile boolean isRunning = false;
private Timer rotateTimer = null;
private Timer statTimer = null;
private Schema avroSchema = null;
private int initWriteChunkRetries = 10;
private int writeChunkRetries = initWriteChunkRetries;
private boolean chunksWrittenThisRotate = false;
private long timePeriod = -1;
private long nextTimePeriodComputation = -1;
private int minPercentFreeDisk = 20;
static {
try {
localHostAddr = "_" + InetAddress.getLocalHost().getHostName() + "_";
} catch (UnknownHostException e) {
localHostAddr = "-NA-";
}
}
public LocalWriter(Configuration conf) throws WriterException {
setup(conf);
}
public void init(Configuration conf) throws WriterException {
}
public void setup(Configuration conf) throws WriterException {
this.conf = conf;
// load Chukwa Avro schema
avroSchema = ChukwaAvroSchema.getSchema();
try {
fs = FileSystem.getLocal(conf);
localOutputDir = conf.get("chukwaCollector.localOutputDir",
"/chukwa/datasink/");
if (!localOutputDir.endsWith("/")) {
localOutputDir += "/";
}
Path pLocalOutputDir = new Path(localOutputDir);
if (!fs.exists(pLocalOutputDir)) {
boolean exist = fs.mkdirs(pLocalOutputDir);
if (!exist) {
throw new WriterException("Cannot create local dataSink dir: "
+ localOutputDir);
}
} else {
FileStatus fsLocalOutputDir = fs.getFileStatus(pLocalOutputDir);
if (!fsLocalOutputDir.isDir()) {
throw new WriterException("local dataSink dir is not a directory: "
+ localOutputDir);
}
}
} catch (Throwable e) {
log.fatal("Cannot initialize LocalWriter", e);
throw new WriterException(e);
}
minPercentFreeDisk = conf.getInt("chukwaCollector.minPercentFreeDisk",20);
rotateInterval = conf.getInt("chukwaCollector.rotateInterval",
1000 * 60 * 5);// defaults to 5 minutes
initWriteChunkRetries = conf
.getInt("chukwaCollector.writeChunkRetries", 10);
writeChunkRetries = initWriteChunkRetries;
log.info("rotateInterval is " + rotateInterval);
log.info("outputDir is " + localOutputDir);
log.info("localFileSystem is " + fs.getUri().toString());
log.info("minPercentFreeDisk is " + minPercentFreeDisk);
if(rotateTimer==null) {
rotateTimer = new Timer();
rotateTimer.schedule(new RotateTask(), 0,
rotateInterval);
}
if(statTimer==null) {
statTimer = new Timer();
statTimer.schedule(new StatReportingTask(), 0,
STAT_INTERVAL_SECONDS * 1000);
}
fileQueue = new LinkedBlockingQueue<String>();
localToRemoteHdfsMover = new LocalToRemoteHdfsMover(fileQueue, conf);
}
private class RotateTask extends TimerTask {
public void run() {
try {
rotate();
} catch(WriterException e) {
log.error(ExceptionUtil.getStackTrace(e));
}
};
}
private class StatReportingTask extends TimerTask {
private long lastTs = System.currentTimeMillis();
public void run() {
long time = System.currentTimeMillis();
long currentDs = dataSize;
dataSize = 0;
long interval = time - lastTs;
lastTs = time;
if(interval <= 0) {
interval = 1;
}
long dataRate = 1000 * currentDs / interval; // kb/sec
log.info("stat:datacollection.writer.local.LocalWriter dataSize="
+ currentDs + " dataRate=" + dataRate);
}
};
protected void computeTimePeriod() {
synchronized (calendar) {
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
timePeriod = calendar.getTimeInMillis();
calendar.add(Calendar.HOUR, 1);
nextTimePeriodComputation = calendar.getTimeInMillis();
}
}
/**
* Best effort, there's no guarantee that chunks
* have really been written to disk
*/
public CommitStatus add(List<Chunk> chunks) throws WriterException {
if (!isRunning) {
throw new WriterException("Writer not yet ready");
}
long now = System.currentTimeMillis();
if (chunks != null) {
try {
chunksWrittenThisRotate = true;
ChukwaArchiveKey archiveKey = new ChukwaArchiveKey();
synchronized (lock) {
if (System.currentTimeMillis() >= nextTimePeriodComputation) {
computeTimePeriod();
}
for (Chunk chunk : chunks) {
archiveKey.setTimePartition(timePeriod);
archiveKey.setDataType(chunk.getDataType());
archiveKey.setStreamName(chunk.getTags() + "/" + chunk.getSource()
+ "/" + chunk.getStreamName());
archiveKey.setSeqId(chunk.getSeqID());
GenericRecord record = new GenericData.Record(avroSchema);
record.put("dataType", chunk.getDataType());
record.put("data", ByteBuffer.wrap(chunk.getData()));
record.put("tags", chunk.getTags());
record.put("seqId", chunk.getSeqID());
record.put("source", chunk.getSource());
record.put("stream", chunk.getStreamName());
parquetWriter.write(record);
// compute size for stats
dataSize += chunk.getData().length;
}
}// End synchro
long end = System.currentTimeMillis();
if (log.isDebugEnabled()) {
log.debug("duration=" + (end-now) + " size=" + chunks.size());
}
} catch (IOException e) {
writeChunkRetries--;
log.error("Could not save the chunk. ", e);
if (writeChunkRetries < 0) {
log
.fatal("Too many IOException when trying to write a chunk, Collector is going to exit!");
}
throw new WriterException(e);
}
}
return COMMIT_OK;
}
protected String getNewFileName() {
calendar.setTimeInMillis(System.currentTimeMillis());
String newName = new java.text.SimpleDateFormat("yyyyddHHmmssSSS")
.format(calendar.getTime());
newName += localHostAddr + new java.rmi.server.UID().toString();
newName = newName.replace("-", "");
newName = newName.replace(":", "");
newName = newName.replace(".", "");
newName = localOutputDir + "/" + newName.trim();
return newName;
}
protected void rotate() throws WriterException {
isRunning = true;
log.info("start Date [" + calendar.getTime() + "]");
log.info("Rotate from " + Thread.currentThread().getName());
String newName = getNewFileName();
synchronized (lock) {
try {
if (currentPath != null) {
Path previousPath = currentPath;
if (chunksWrittenThisRotate) {
String previousFileName = previousPath.getName().replace(".chukwa", ".done");
if(fs.exists(previousPath)) {
fs.rename(previousPath, new Path(previousFileName + ".done"));
}
fileQueue.add(previousFileName + ".done");
} else {
log.info("no chunks written to " + previousPath + ", deleting");
fs.delete(previousPath, false);
}
}
Path newOutputPath = new Path(newName + ".chukwa");
while(fs.exists(newOutputPath)) {
newName = getNewFileName();
newOutputPath = new Path(newName + ".chukwa");
}
currentPath = newOutputPath;
currentFileName = newName;
chunksWrittenThisRotate = false;
parquetWriter = new AvroParquetWriter<GenericRecord>(newOutputPath, avroSchema, CompressionCodecName.SNAPPY, blockSize, pageSize);
} catch (IOException e) {
log.fatal("IO Exception in rotate: ", e);
}
}
// Check for disk space
File directory4Space = new File(localOutputDir);
long totalSpace = directory4Space.getTotalSpace();
long freeSpace = directory4Space.getFreeSpace();
long minFreeAvailable = (totalSpace * minPercentFreeDisk) /100;
if (log.isDebugEnabled()) {
log.debug("Directory: " + localOutputDir + ", totalSpace: " + totalSpace
+ ", freeSpace: " + freeSpace + ", minFreeAvailable: " + minFreeAvailable
+ ", percentFreeDisk: " + minPercentFreeDisk);
}
if (freeSpace < minFreeAvailable) {
log.fatal("No space left on device.");
throw new WriterException("No space left on device.");
}
log.debug("finished rotate()");
}
public void close() {
synchronized (lock) {
if (rotateTimer != null) {
rotateTimer.cancel();
}
if (statTimer != null) {
statTimer.cancel();
}
try {
if (parquetWriter != null) {
parquetWriter.close();
}
if (localToRemoteHdfsMover != null) {
localToRemoteHdfsMover.shutdown();
}
fs.rename(currentPath, new Path(currentFileName + ".done"));
} catch (IOException e) {
log.error("failed to close and rename stream", e);
}
}
}
} |
Java | @ApplicationScoped
public class ExternalUpdateTokenService extends ExternalScriptService {
private static final long serialVersionUID = -1033475075863270259L;
public ExternalUpdateTokenService() {
super(CustomScriptType.UPDATE_TOKEN);
}
public boolean modifyIdTokenMethod(CustomScriptConfiguration script, JsonWebResponse jsonWebResponse, ExternalUpdateTokenContext context) {
try {
log.trace("Executing python 'updateToken' method, script name: {}, jsonWebResponse: {}, context: {}", script.getName(), jsonWebResponse, context);
context.setScript(script);
UpdateTokenType updateTokenType = (UpdateTokenType) script.getExternalType();
final boolean result = updateTokenType.modifyIdToken(jsonWebResponse, context);
log.trace("Finished 'updateToken' method, script name: {}, jsonWebResponse: {}, context: {}, result: {}", script.getName(), jsonWebResponse, context, result);
return result;
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
saveScriptError(script.getCustomScript(), ex);
}
return false;
}
public boolean modifyIdTokenMethods(JsonWebResponse jsonWebResponse, ExternalUpdateTokenContext context) {
List<CustomScriptConfiguration> scripts = getScripts(context);
if (scripts.isEmpty()) {
return false;
}
log.trace("Executing {} update-token scripts.", scripts.size());
for (CustomScriptConfiguration script : scripts) {
if (!modifyIdTokenMethod(script, jsonWebResponse, context)) {
return false;
}
}
return true;
}
public Function<JsonWebResponse, Void> buildModifyIdTokenProcessor(final ExternalUpdateTokenContext context) {
return jsonWebResponse -> {
modifyIdTokenMethods(jsonWebResponse, context);
return null;
};
}
public int getRefreshTokenLifetimeInSeconds(CustomScriptConfiguration script, ExternalUpdateTokenContext context) {
try {
log.trace("Executing python 'getRefreshTokenLifetimeInSeconds' method, script name: {}, context: {}", script.getName(), context);
context.setScript(script);
UpdateTokenType updateTokenType = (UpdateTokenType) script.getExternalType();
final int result = updateTokenType.getRefreshTokenLifetimeInSeconds(context);
log.trace("Finished 'getRefreshTokenLifetimeInSeconds' method, script name: {}, context: {}, result: {}", script.getName(), context, result);
return result;
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
saveScriptError(script.getCustomScript(), ex);
}
return 0;
}
public int getRefreshTokenLifetimeInSeconds(ExternalUpdateTokenContext context) {
List<CustomScriptConfiguration> scripts = getScripts(context);
if (scripts.isEmpty()) {
return 0;
}
log.trace("Executing {} 'getRefreshTokenLifetimeInSeconds' scripts.", scripts.size());
for (CustomScriptConfiguration script : scripts) {
final int lifetime = getRefreshTokenLifetimeInSeconds(script, context);
if (lifetime > 0) {
log.trace("Finished 'getRefreshTokenLifetimeInSeconds' methods, lifetime: {}", lifetime);
return lifetime;
}
}
return 0;
}
@NotNull
private List<CustomScriptConfiguration> getScripts(@NotNull ExternalUpdateTokenContext context) {
if (customScriptConfigurations == null || customScriptConfigurations.isEmpty() || context.getClient() == null) {
return Lists.newArrayList();
}
final List<CustomScriptConfiguration> scripts = getCustomScriptConfigurationsByDns(context.getClient().getAttributes().getUpdateTokenScriptDns());
if (!scripts.isEmpty()) {
return scripts;
}
log.trace("No UpdateToken scripts associated with client {}", context.getClient().getClientId());
return Lists.newArrayList();
}
public boolean modifyRefreshToken(CustomScriptConfiguration script, RefreshToken refreshToken, ExternalUpdateTokenContext context) {
try {
log.trace("Executing python 'modifyRefreshToken' method, script name: {}, context: {}", script.getName(), context);
context.setScript(script);
UpdateTokenType updateTokenType = (UpdateTokenType) script.getExternalType();
final boolean result = updateTokenType.modifyRefreshToken(refreshToken, context);
log.trace("Finished 'modifyRefreshToken' method, script name: {}, context: {}, result: {}", script.getName(), context, result);
return result;
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
saveScriptError(script.getCustomScript(), ex);
}
return false;
}
public boolean modifyRefreshToken(RefreshToken refreshToken, ExternalUpdateTokenContext context) {
List<CustomScriptConfiguration> scripts = getScripts(context);
if (scripts.isEmpty()) {
return true;
}
log.trace("Executing {} update-token modifyRefreshToken scripts.", scripts.size());
for (CustomScriptConfiguration script : scripts) {
if (!modifyRefreshToken(script, refreshToken, context)) {
return false;
}
}
return true;
}
public boolean modifyAccessToken(CustomScriptConfiguration script, AccessToken accessToken, ExternalUpdateTokenContext context) {
try {
log.trace("Executing python 'modifyAccessToken' method, script name: {}, context: {}", script.getName(), context);
context.setScript(script);
UpdateTokenType updateTokenType = (UpdateTokenType) script.getExternalType();
final boolean result = updateTokenType.modifyAccessToken(accessToken, context);
log.trace("Finished 'modifyAccessToken' method, script name: {}, context: {}, result: {}", script.getName(), context, result);
return result;
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
saveScriptError(script.getCustomScript(), ex);
}
return false;
}
public boolean modifyAccessToken(AccessToken accessToken, ExternalUpdateTokenContext context) {
List<CustomScriptConfiguration> scripts = getScripts(context);
if (scripts.isEmpty()) {
return true;
}
log.trace("Executing {} update-token modifyAccessToken scripts.", scripts.size());
for (CustomScriptConfiguration script : scripts) {
if (!modifyAccessToken(script, accessToken, context)) {
return false;
}
}
return true;
}
public int getAccessTokenLifetimeInSeconds(CustomScriptConfiguration script, ExternalUpdateTokenContext context) {
try {
log.trace("Executing python 'getAccessTokenLifetimeInSeconds' method, script name: {}, context: {}", script.getName(), context);
context.setScript(script);
UpdateTokenType updateTokenType = (UpdateTokenType) script.getExternalType();
final int result = updateTokenType.getAccessTokenLifetimeInSeconds(context);
log.trace("Finished 'getAccessTokenLifetimeInSeconds' method, script name: {}, context: {}, result: {}", script.getName(), context, result);
return result;
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
saveScriptError(script.getCustomScript(), ex);
}
return 0;
}
public int getAccessTokenLifetimeInSeconds(ExternalUpdateTokenContext context) {
List<CustomScriptConfiguration> scripts = getScripts(context);
if (scripts.isEmpty()) {
return 0;
}
log.trace("Executing {} 'getAccessTokenLifetimeInSeconds' scripts.", scripts.size());
for (CustomScriptConfiguration script : scripts) {
final int lifetime = getAccessTokenLifetimeInSeconds(script, context);
if (lifetime > 0) {
log.trace("Finished 'getAccessTokenLifetimeInSeconds' methods, lifetime: {}", lifetime);
return lifetime;
}
}
return 0;
}
public int getIdTokenLifetimeInSeconds(CustomScriptConfiguration script, ExternalUpdateTokenContext context) {
try {
log.trace("Executing python 'getIdTokenLifetimeInSeconds' method, script name: {}, context: {}", script.getName(), context);
context.setScript(script);
UpdateTokenType updateTokenType = (UpdateTokenType) script.getExternalType();
final int result = updateTokenType.getIdTokenLifetimeInSeconds(context);
log.trace("Finished 'getIdTokenLifetimeInSeconds' method, script name: {}, context: {}, result: {}", script.getName(), context, result);
return result;
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
saveScriptError(script.getCustomScript(), ex);
}
return 0;
}
public int getIdTokenLifetimeInSeconds(ExternalUpdateTokenContext context) {
List<CustomScriptConfiguration> scripts = getScripts(context);
if (scripts.isEmpty()) {
return 0;
}
log.trace("Executing {} 'getIdTokenLifetimeInSeconds' scripts.", scripts.size());
for (CustomScriptConfiguration script : scripts) {
final int lifetime = getIdTokenLifetimeInSeconds(script, context);
if (lifetime > 0) {
log.trace("Finished 'getIdTokenLifetimeInSeconds' methods, lifetime: {}", lifetime);
return lifetime;
}
}
return 0;
}
} |
Java | public class ViewMentorCommandParser implements Parser<EditCommand> {
/**
* Parses the given {@code String} of arguments in the context of the EditCommand
* and returns an EditCommand object for execution.
* @throws ParseException if the user input does not conform the expected format
*/
public EditCommand parse(String args) throws ParseException {
// The return type of this command will also have to be corrected
// to return a ViewTeamCommand object as designed by John instead of an
// EditCommand Object.
/**
* This is just placeholder code. We will implement proper code
* when the Team class has been finalised.
*/
return null;
}
/**
* Parses {@code Collection<String> tags} into a {@code Set<Tag>} if {@code tags} is non-empty.
* If {@code tags} contain only one element which is an empty string, it will be parsed into a
* {@code Set<Tag>} containing zero tags.
*/
private Optional<Set<Tag>> parseTagsForEdit(Collection<String> tags) throws ParseException {
assert tags != null;
if (tags.isEmpty()) {
return Optional.empty();
}
Collection<String> tagSet = tags.size() == 1 && tags.contains("") ? Collections.emptySet() : tags;
return Optional.of(AlfredParserUtil.parseTags(tagSet));
}
} |
Java | public class Attribute implements Serializable {
private static final long serialVersionUID = -182983902349882L;
private String name;
private String friendlyName;
private List<Object> values = new LinkedList<>();
private String nameFormat = AttributeNameFormat.UNSPECIFIED.toString();
private boolean required;
public String getName() {
return name;
}
public Attribute setName(String name) {
this.name = name;
return this;
}
public String getFriendlyName() {
return friendlyName;
}
public Attribute setFriendlyName(String friendlyName) {
this.friendlyName = friendlyName;
return this;
}
public List<Object> getValues() {
return values;
}
public Attribute setValues(List<Object> values) {
this.values.addAll(values);
return this;
}
public String getNameFormat() {
return nameFormat;
}
public Attribute setNameFormat(String nameFormat) {
this.nameFormat = nameFormat;
return this;
}
public boolean isRequired() {
return required;
}
public Attribute setRequired(boolean required) {
this.required = required;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Attribute attribute = (Attribute) o;
return required == attribute.required && Objects.equals(name, attribute.name) && Objects.equals(nameFormat, attribute.nameFormat);
}
@Override
public int hashCode() {
return Objects.hash(name, nameFormat, required);
}
} |
Java | public class DynamicsImpl extends ValueImpl implements Dynamics
{
/**
* The cached value of the '{@link #getInitialCondition() <em>Initial Condition</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getInitialCondition()
* @generated
* @ordered
*/
protected PhysicalQuantity initialCondition;
/**
* The cached value of the '{@link #getDynamics() <em>Dynamics</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDynamics()
* @generated
* @ordered
*/
protected Function dynamics;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected DynamicsImpl()
{
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass()
{
return ValuesPackage.Literals.DYNAMICS;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public PhysicalQuantity getInitialCondition()
{
return initialCondition;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetInitialCondition(PhysicalQuantity newInitialCondition, NotificationChain msgs)
{
PhysicalQuantity oldInitialCondition = initialCondition;
initialCondition = newInitialCondition;
if (eNotificationRequired())
{
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, ValuesPackage.DYNAMICS__INITIAL_CONDITION, oldInitialCondition, newInitialCondition);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setInitialCondition(PhysicalQuantity newInitialCondition)
{
if (newInitialCondition != initialCondition)
{
NotificationChain msgs = null;
if (initialCondition != null)
msgs = ((InternalEObject)initialCondition).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - ValuesPackage.DYNAMICS__INITIAL_CONDITION, null, msgs);
if (newInitialCondition != null)
msgs = ((InternalEObject)newInitialCondition).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - ValuesPackage.DYNAMICS__INITIAL_CONDITION, null, msgs);
msgs = basicSetInitialCondition(newInitialCondition, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ValuesPackage.DYNAMICS__INITIAL_CONDITION, newInitialCondition, newInitialCondition));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Function getDynamics()
{
return dynamics;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetDynamics(Function newDynamics, NotificationChain msgs)
{
Function oldDynamics = dynamics;
dynamics = newDynamics;
if (eNotificationRequired())
{
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, ValuesPackage.DYNAMICS__DYNAMICS, oldDynamics, newDynamics);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setDynamics(Function newDynamics)
{
if (newDynamics != dynamics)
{
NotificationChain msgs = null;
if (dynamics != null)
msgs = ((InternalEObject)dynamics).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - ValuesPackage.DYNAMICS__DYNAMICS, null, msgs);
if (newDynamics != null)
msgs = ((InternalEObject)newDynamics).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - ValuesPackage.DYNAMICS__DYNAMICS, null, msgs);
msgs = basicSetDynamics(newDynamics, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ValuesPackage.DYNAMICS__DYNAMICS, newDynamics, newDynamics));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs)
{
switch (featureID)
{
case ValuesPackage.DYNAMICS__INITIAL_CONDITION:
return basicSetInitialCondition(null, msgs);
case ValuesPackage.DYNAMICS__DYNAMICS:
return basicSetDynamics(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType)
{
switch (featureID)
{
case ValuesPackage.DYNAMICS__INITIAL_CONDITION:
return getInitialCondition();
case ValuesPackage.DYNAMICS__DYNAMICS:
return getDynamics();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue)
{
switch (featureID)
{
case ValuesPackage.DYNAMICS__INITIAL_CONDITION:
setInitialCondition((PhysicalQuantity)newValue);
return;
case ValuesPackage.DYNAMICS__DYNAMICS:
setDynamics((Function)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID)
{
switch (featureID)
{
case ValuesPackage.DYNAMICS__INITIAL_CONDITION:
setInitialCondition((PhysicalQuantity)null);
return;
case ValuesPackage.DYNAMICS__DYNAMICS:
setDynamics((Function)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID)
{
switch (featureID)
{
case ValuesPackage.DYNAMICS__INITIAL_CONDITION:
return initialCondition != null;
case ValuesPackage.DYNAMICS__DYNAMICS:
return dynamics != null;
}
return super.eIsSet(featureID);
}
} |
Java | public class ScannedFileHandleAssociation {
private String objectId;
private List<Long> fileHandleIds;
public ScannedFileHandleAssociation(String objectId) {
this.objectId = objectId;
}
public ScannedFileHandleAssociation(String objectId, Long fileHandleId) {
this.objectId = objectId;
this.fileHandleIds = Collections.singletonList(fileHandleId);
}
/**
* @return The id of the object that was scanned
*/
public String getObjectId() {
return objectId;
}
/**
* @return A potentially empty or null list of file handles that are associated with the object
*/
public List<Long> getFileHandleIds() {
return fileHandleIds;
}
/**
* Replace the list of discovered file handle ids
*
* @param fileHandleIds
* @return this
*/
public ScannedFileHandleAssociation withFileHandleIds(List<Long> fileHandleIds) {
this.fileHandleIds = fileHandleIds;
return this;
}
@Override
public int hashCode() {
return Objects.hash(fileHandleIds, objectId);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
ScannedFileHandleAssociation other = (ScannedFileHandleAssociation) obj;
return Objects.equals(fileHandleIds, other.fileHandleIds) && Objects.equals(objectId, other.objectId);
}
@Override
public String toString() {
return "ScannedFileHandleAssociation [objectId=" + objectId + ", fileHandleIds=" + fileHandleIds + "]";
}
} |
Java | public class OGraphFunctionFactory implements OSQLFunctionFactory {
private static final Map<String, Object> FUNCTIONS = new HashMap<String, Object>();
static {
register(OSQLFunctionGremlin.NAME, OSQLFunctionGremlin.class);
register(OSQLFunctionDijkstra.NAME, new OSQLFunctionDijkstra());
register(OSQLFunctionAstar.NAME, OSQLFunctionAstar.class);
register(OSQLFunctionShortestPath.NAME, new OSQLFunctionShortestPath());
register(OSQLFunctionLabel.NAME, new OSQLFunctionLabel());
register(OSQLFunctionOut.NAME, new OSQLFunctionOut());
register(OSQLFunctionIn.NAME, new OSQLFunctionIn());
register(OSQLFunctionBoth.NAME, new OSQLFunctionBoth());
register(OSQLFunctionOutE.NAME, new OSQLFunctionOutE());
register(OSQLFunctionInE.NAME, new OSQLFunctionInE());
register(OSQLFunctionBothE.NAME, new OSQLFunctionBothE());
register(OSQLFunctionOutV.NAME, new OSQLFunctionOutV());
register(OSQLFunctionInV.NAME, new OSQLFunctionInV());
register(OSQLFunctionBothV.NAME, new OSQLFunctionBothV());
}
public static void register(final String iName, final Object iImplementation) {
FUNCTIONS.put(iName.toLowerCase(Locale.ENGLISH), iImplementation);
}
public Set<String> getFunctionNames() {
return FUNCTIONS.keySet();
}
public boolean hasFunction(final String name) {
return FUNCTIONS.containsKey(name.toLowerCase());
}
public OSQLFunction createFunction(final String name) {
final Object obj = FUNCTIONS.get(name.toLowerCase());
if (obj == null)
throw new OCommandExecutionException("Unknown function name :" + name);
if (obj instanceof OSQLFunction)
return (OSQLFunction) obj;
else {
// it's a class
final Class<?> clazz = (Class<?>) obj;
try {
return (OSQLFunction) clazz.newInstance();
} catch (Exception e) {
throw OException.wrapException(new OCommandExecutionException("Error in creation of function " + name
+ "(). Probably there is not an empty constructor or the constructor generates errors"), e);
}
}
}
} |
Java | @RunWith(Parameterized.class)
public class DatasetIT extends NetworkEntityTest<Dataset> {
// Resets SOLR between each method
@Rule
public final SolrInitializer solrRule;
private final DatasetService service;
private final DatasetSearchService searchService;
private final OrganizationService organizationService;
private final NodeService nodeService;
private final InstallationService installationService;
private final DatasetIndexService datasetIndexService;
@Parameters
public static Iterable<Object[]> data() {
final Injector client = webserviceClient();
final Injector webservice = webservice();
return ImmutableList.<Object[]>of(
new Object[] {
webservice.getInstance(DatasetResource.class),
webservice.getInstance(DatasetResource.class),
webservice.getInstance(OrganizationResource.class),
webservice.getInstance(NodeResource.class),
webservice.getInstance(InstallationResource.class),
webservice.getInstance(RegistrySearchModule.DATASET_KEY),
webservice.getInstance(DatasetIndexService.class),
null // SimplePrincipalProvider only set in web service client
}
,
new Object[] {
client.getInstance(DatasetService.class),
client.getInstance(DatasetSearchService.class),
client.getInstance(OrganizationService.class),
client.getInstance(NodeService.class),
client.getInstance(InstallationService.class),
null, // use the SOLR in Grizzly
null, // use the SOLR in Grizzly
client.getInstance(SimplePrincipalProvider.class)
}
);
}
public DatasetIT(
DatasetService service,
DatasetSearchService searchService,
OrganizationService organizationService,
NodeService nodeService,
InstallationService installationService,
@Nullable SolrClient solrClient,
@Nullable DatasetIndexService indexService,
@Nullable SimplePrincipalProvider pp) {
super(service, pp);
this.service = service;
this.searchService = searchService;
this.organizationService = organizationService;
this.nodeService = nodeService;
this.installationService = installationService;
// if no SOLR are given for the test, use the SOLR in Grizzly
solrClient = solrClient == null ? RegistryServer.INSTANCE.getSolrClient() : solrClient;
this.datasetIndexService = indexService == null ? RegistryServer.INSTANCE.getIndexService() : indexService;
solrRule = new SolrInitializer(solrClient, this.datasetIndexService);
}
@Test
public void testCreateDoi() {
Dataset d = newEntity();
service.create(d);
assertEquals(Datasets.DATASET_DOI, d.getDoi());
d = newEntity();
d.setDoi(null);
UUID key = service.create(d);
d = service.get(key);
assertFalse(Datasets.DATASET_DOI.equals(d.getDoi()));
assertEquals(DOI.TEST_PREFIX, d.getDoi().getPrefix());
}
/**
* Override creation to add process properties.
* @param orig
* @param expectedCount
* @return
*/
@Override
protected Dataset create(Dataset orig, int expectedCount) {
return create(orig, expectedCount, buildExpectedProcessedProperties(orig));
}
protected Dataset duplicateForCreateAsEditorTest(Dataset entity) throws Exception {
Dataset duplicate = (Dataset) BeanUtils.cloneBean(entity);
duplicate.setPublishingOrganizationKey(entity.getPublishingOrganizationKey());
duplicate.setInstallationKey(entity.getInstallationKey());
return duplicate;
}
protected UUID keyForCreateAsEditorTest(Dataset entity) {
return organizationService.get(entity.getPublishingOrganizationKey()).getEndorsingNodeKey();
}
@Test
public void testConstituents() {
Dataset parent = newAndCreate(1);
for (int id = 0; id < 10; id++) {
Dataset constituent = newEntity();
constituent.setParentDatasetKey(parent.getKey());
constituent.setType(parent.getType());
create(constituent, id + 2);
}
assertEquals(10, service.get(parent.getKey()).getNumConstituents());
}
// Easier to test this here than OrganizationIT due to our utility dataset factory
@Test
public void testHostedByList() {
Dataset dataset = newAndCreate(1);
Installation i = installationService.get(dataset.getInstallationKey());
assertNotNull("Dataset should have an installation", i);
PagingResponse<Dataset> published =
organizationService.publishedDatasets(i.getOrganizationKey(), new PagingRequest());
PagingResponse<Dataset> hosted = organizationService.hostedDatasets(i.getOrganizationKey(), new PagingRequest());
assertEquals("This installation should have only 1 published dataset", 1, published.getResults().size());
assertTrue("This organization should not have any hosted datasets", hosted.getResults().isEmpty());
}
// Easier to test this here than OrganizationIT due to our utility dataset factory
@Test
public void testPublishedByList() {
Dataset dataset = newAndCreate(1);
PagingResponse<Dataset> published =
organizationService.publishedDatasets(dataset.getPublishingOrganizationKey(), new PagingRequest());
assertEquals("The organization should have only 1 dataset", 1, published.getResults().size());
assertEquals("The organization should publish the dataset created", published.getResults().get(0).getKey(),
dataset.getKey());
assertEquals("The organization should have 1 dataset count", 1,
organizationService.get(dataset.getPublishingOrganizationKey()).getNumPublishedDatasets());
}
// Easier to test this here than InstallationIT due to our utility dataset factory
@Test
public void testHostedByInstallationList() {
Dataset dataset = newAndCreate(1);
Installation i = installationService.get(dataset.getInstallationKey());
assertNotNull("Dataset should have an installation", i);
PagingResponse<Dataset> hosted =
installationService.getHostedDatasets(dataset.getInstallationKey(), new PagingRequest());
assertEquals("This installation should have only 1 hosted dataset", 1, hosted.getResults().size());
assertEquals("Paging response counts are not being set", Long.valueOf(1), hosted.getCount());
assertEquals("The hosted installation should serve the dataset created", hosted.getResults().get(0).getKey(),
dataset.getKey());
}
@Test
public void testTypedSearch() {
Dataset d = newEntity();
d.setType(DatasetType.CHECKLIST);
d = create(d, 1);
assertSearch(d.getTitle(), 1); // 1 result expected for a simple search
DatasetSearchRequest req = new DatasetSearchRequest();
req.addTypeFilter(DatasetType.CHECKLIST);
SearchResponse<DatasetSearchResult, DatasetSearchParameter> resp = searchService.search(req);
assertNotNull(resp.getCount());
assertEquals("SOLR does not have the expected number of results for query[" + req + "]", Long.valueOf(1),
resp.getCount());
}
@Test
public void testMultiCountryFacet() {
Dataset d = newEntity(Country.ALGERIA);
d.setType(DatasetType.CHECKLIST);
d = create(d, 1);
d = newEntity(Country.GERMANY);
d.setType(DatasetType.CHECKLIST);
d = create(d, 2);
d = newEntity(Country.FRANCE);
d.setType(DatasetType.OCCURRENCE);
d = create(d, 3);
d = newEntity(Country.GHANA);
d.setType(DatasetType.OCCURRENCE);
d = create(d, 4);
DatasetSearchRequest req = new DatasetSearchRequest();
req.addPublishingCountryFilter(Country.ANGOLA);
req.addFacets(DatasetSearchParameter.PUBLISHING_COUNTRY);
SearchResponse<DatasetSearchResult, DatasetSearchParameter> resp = searchService.search(req);
assertEquals("SOLR does not have the expected number of results for query[" + req + "]", Long.valueOf(0), resp.getCount());
assertEquals("SOLR does not have the expected number of facets for query[" + req + "]", 1, resp.getFacets().size());
assertEquals("SOLR does not have the expected number of facet values for query[" + req + "]", 0, resp.getFacets().get(0).getCounts().size());
req = new DatasetSearchRequest();
req.addPublishingCountryFilter(Country.ALGERIA);
req.addFacets(DatasetSearchParameter.PUBLISHING_COUNTRY);
req.addFacets(DatasetSearchParameter.LICENSE);
resp = searchService.search(req);
assertEquals("SOLR does not have the expected number of results for query[" + req + "]", Long.valueOf(1), resp.getCount());
assertEquals("SOLR does not have the expected number of facets for query[" + req + "]", 2, resp.getFacets().size());
req = new DatasetSearchRequest();
req.addPublishingCountryFilter(Country.GERMANY);
req.setMultiSelectFacets(true);
req.addFacets(DatasetSearchParameter.PUBLISHING_COUNTRY);
resp = searchService.search(req);
assertEquals("SOLR does not have the expected number of results for query[" + req + "]", Long.valueOf(1), resp.getCount());
assertEquals("SOLR does not have the expected number of facet values for query[" + req + "]", 4, resp.getFacets().get(0).getCounts().size());
}
@Test
public void testSearchParameter() throws InterruptedException {
Dataset d = newEntity(Country.SOUTH_AFRICA);
d.setType(DatasetType.CHECKLIST);
d.setLicense(License.CC0_1_0);
d.setLanguage(Language.AFRIKAANS);
create(d, 1);
Thread.sleep(100);
DatasetSearchRequest req = new DatasetSearchRequest();
req.addPublishingCountryFilter(Country.GERMANY);
SearchResponse<DatasetSearchResult, DatasetSearchParameter> resp = searchService.search(req);
assertEquals("SOLR does not have the expected number of results for query[" + req + "]", Long.valueOf(0),
resp.getCount());
req.addPublishingCountryFilter(Country.SOUTH_AFRICA);
req.addTypeFilter(DatasetType.CHECKLIST);
resp = searchService.search(req);
assertEquals("SOLR does not have the expected number of results for query[" + req + "]", Long.valueOf(1),
resp.getCount());
}
@Test
public void testSearchLargeTitles() {
Dataset d = newEntity();
d.setType(DatasetType.OCCURRENCE);
d = create(d, 1);
testSearch(d.getTitle());
testSearch("Pontaurus needs more than 255 characters for it's title");
testSearch("\"Vegetationskundliche Untersuchungen in der Hochgebirgsregion der Bolkar Daglari & Aladaglari, Türkei\"");
testSearch("Vegetationskundliche Untersuchungen in der Hochgebirgsregion der Bolkar Daglari & Aladaglari, Türkei");
testSearch("PonTaurus");
testSearch("Pon Taurus");
testSearch("Bolkar Daglari Aladaglari");
testSearch("PonTaurus Bolkar Daglari Aladaglari");
}
@Test
public void testEventTypeSearch() {
Dataset d = newEntity();
d.setType(DatasetType.SAMPLING_EVENT);
d = create(d, 1);
assertSearch(d.getTitle(), 1);
DatasetSearchRequest req = new DatasetSearchRequest();
req.addTypeFilter(DatasetType.SAMPLING_EVENT);
SearchResponse<DatasetSearchResult, DatasetSearchParameter> resp = searchService.search(req);
assertNotNull(resp.getCount());
assertEquals("SOLR does not have the expected number of results for query[" + req + "]", Long.valueOf(1),
resp.getCount());
}
@Test
@Ignore("See https://github.com/gbif/registry/issues/22")
public void testDismaxSearch() throws InterruptedException {
Dataset d = newAndCreate(1);
final UUID pubKey = d.getPublishingOrganizationKey();
final UUID instKey = d.getInstallationKey();
final UUID nodeKey = organizationService.get(pubKey).getEndorsingNodeKey();
d = new Dataset();
d.setPublishingOrganizationKey(pubKey);
d.setInstallationKey(instKey);
d.setTitle("eBird is cool");
d.setLicense(License.CC0_1_0);
d.setType(DatasetType.CHECKLIST);
d.setDescription("bli bla blub, mein Hund ist ins Klo gefallen. Oh je! Der kommt da alleine gar nicht mehr raus.");
service.create(d);
d.setKey(null);
d.setType(DatasetType.OCCURRENCE);
d.setTitle("Fall in eBird ");
d.setDescription("bli bla blub, es gibt nix neues.");
service.create(d);
d.setKey(null);
d.setTitle("Bird tracking - GPS tracking of Lesser Black-backed Gulls and Herring Gulls breeding at the southern North Sea coast");
d.setDescription("Bird tracking - GPS tracking of Lesser Black-backed Gulls and Herring Gulls breeding at the southern North Sea coast is a species occurrence dataset published by the Research Institute for Nature and Forest (INBO) and described in Stienen et al. 2016 (http://doi.org/10.3897/zookeys.555.6173) The dataset contains close to 2.5 million occurrences, recorded by 101 GPS trackers mounted on 75 Lesser Black-backed Gulls and 26 Herring Gulls breeding at the Belgian and Dutch coast (see https://inbo.cartodb.com/u/lifewatch/viz/da04f120-ea70-11e4-a3f2-0e853d047bba/public_map for a visualization of the data). The trackers were developed by the University of Amsterdam Bird Tracking System (UvA-BiTS, http://www.uva-bits.nl). These automatically record and transmit bird movements, which allows us and others to study their habitat use and migration behaviour in great detail. Our bird tracking network is operational since 2013. It is funded for LifeWatch by the Hercules Foundation and maintained in collaboration with UvA-BiTS and the Flanders Marine Institute (VLIZ). The recorded data are periodically released in bulk as open data (http://dataset.inbo.be/bird-tracking-gull-occurrences), and are also accessible through CartoDB and the Global Biodiversity Information Facility (GBIF, http://doi.org/10.15468/02omly). See the dataset metadata for contact information, scope and methodology. Issues with the dataset can be reported at https://github.com/LifeWatchINBO/data-publication/tree/master/datasets/bird-tracking-gull-occurrences");
final UUID gpsKey = service.create(d);
d.setKey(null);
d.setTitle("BID-AF2015-0004-NAC- données de Dénombrements Internationaux des Oiseaux d'Eau en Afrique");
d.setDescription("Le Togo est un pays d’Afrique de l’Ouest limité à l’Est par le Bénin, à l’Ouest par le Ghana, au Nord par le Burkina-Faso et au sud par l’Océan Atlantique. Il est compris entre les latitudes 6° 06’ Sud et 11° 08’ Nord et les longitudes 0° 09’ Ouest et 1° 49’ Est avec une superficie de 56.600 km2. Cette configuration géographique lui confère une gradation climatique favorisée par l’existence d’importantes zones humides estimées à 2210 km2. En l’absence quasi-totale de leur plan de gestion, leur dégradation s’est accentuée au fils des années au risque d’entrainer à terme leur disparition si des mesures adéquates ne sont pas prises. Le Togo, Partie à un certain nombre de traités et accords relatifs à l’environnement et aux ressources forestières notamment à l’accord sur la conservation des oiseaux d’eau migrateurs (AEWA) a pris l’engagement d’enclencher le processus de gestion des zones humides du pays notamment les zones humides des bassins du Mono, du Zio et de Haho. Dans cette dynamique, la direction des ressources forestières participe annuellement aux recensements des oiseaux d’eau migrateurs. C’est dans ce contexte que cette opération de dénombrement s’est effectuée le 21 janvier 2016 grâce à l’appui de Wetlantlands International avec pour objectif de contribuer à l’actualisation de données mondiales de ces espèces. L’opération s’est déroulée uniquement au niveau des zones humides du littoral. Au point de vue approche méthodologique, le travail a été fait en trois phases. -\tLa première phase a consisté en une mission effectuée sur le terrain au cours de laquelle il a été procédé à l’identification des sites devant faire l’objet de décompte. -\tLa deuxième phase est axée sur le recensement des oiseaux d’eau sur les différents sites ; et -\tLa troisième phase est le rapportage prenant en compte l’ensemble des activités menées, les analyses technique et scientifique portant sur la notification et le suivi des espèces phares sur les sites. II - OBJECTIF 1.1 Objectif global Il s’agit de contribuer à la mise à jour de la Base de Données Internationales de Comptage (IWC) d’oiseaux d’eau. 1.2 Objectifs spécifiques A travers cette opération, il a été question de : \uF0A7\tCollecter les informations relatives aux caractéristiques écologiques des sites de décompte cibles; \uF0A7\tConduire les recensements des oiseaux d’eau en janvier 2016. II- METHODOLOGIE DE TRAVAIL ET MATERIEL UTILISE 2.1 Méthodologie de travail Dans le cadre de cette opération, une équipe a été mise en place pour une visite prospective des sites. Il s’agit d’un spécialiste de faune et d’un spécialiste en gestion des zones humides et d’un biologiste environnementaliste. Ceux-ci se sont rendus sur le terrain pour un pré-dénombrement. Cette étape a permis de faire l’inventaire qualitatif afin de s’assurer de la présence ou non des oiseaux d’eau migrateurs, objet de la mission et d’avoir une idée sur les caractéristiques écologiques des sites. Les résultats de ce pré-dénombrement ont conduit à la constitution de six équipes multidisciplinaires pour couvrir les six sites retenus. Il s’agit de biologistes, d’environnementalistes, de spécialistes en aménagement de la faune, de spécialistes en zone humide et de spécialistes en gestion des ressources forestières. Le dénombrement proprement dit a été effectué le 21 janvier 2016 avec la participation des acteurs indiqués dans le tableau I en annexe. Les intéressés se sont rendus dans les limites des zones ciblées pour compter les oiseaux. 2.2 Matériel utilisé La mise en œuvre des activités a nécessité les moyens ci-après: -\tUn véhicule 4 x 4 ; -\tDouze motos ; - Deux appareils de Système de Positionnement Géographique (GPS) pour la prise des coordonnées des sites lors de la visite prospective ; -\tKits de terrain (Bloc note; fiches de terrain, écritoires etc.…) pour la collecte des informations; - Trois appareils photos pour la prise des images ; -\tSix paires de jumelles pour l’observation et l’identification des oiseaux ; -\tCinq guides de terrain pour l’identification des espèces (les oiseaux de l’Ouest africain, les limicoles : comment les reconnaître et Birds of Southern Africa); -\tTrois ordinateurs portables pour la compilation et le traitement des données ainsi que pour le rapportage. III - RESULTATS 3. 1 Recensement général des oiseaux Le tableau II en excel annexé au présent rapport présente la synthèse des résultats du dénombrement effectué le 21 janvier 2016 au Togo. 3.2 Commentaire Au total six (06) sites de décompte ont été explorés dans le cadre de cette opération de dénombrement des oiseaux d’eau à cause des moyens insuffisants. Tous ces sites sont localisés au niveau des zones humides du Littoral. Il s’agit de deux sites au niveau de la lagune de Bè, du site du retenu d’eau de l’Université de Lomé, d’Agbalépédogan, de l’ancien Wharf et ses environs et de la mare Togo 2000. L’analyse des données de décompte indiquée dans le tableau II, montre une diversité des espèces au niveau des six sites. L’un des faits marquant de cette opération est la diversité importante observée au niveau du lac artificiel d’Agbalépédogan (LAA) où ont été dénombrées 19 espèces avec un effectif total de 150 individus. CONCLUSION ET RECOMMANDATIONS La participation du Togo aux décomptes des oiseaux d’eau, année 2016 prouve l’attachement du pays non seulement aux objectifs de l’accord sur la conservation des oiseaux d’eau migrateurs d’Afrique Eurasie (AEWA) mais également sa volonté à partager ses expériences avec les autres pays, Parties à cet accord en produisant des informations pour contribuer à l’actualisation de la base de données de comptages internationaux d’oiseaux (IWC). Dans cette dynamique, notre pays est toujours disposé à participer aux opérations de dénombrement pour les saisons à venir en prenant en compte les zones humiques importantes pour la conservation des oiseaux d’eau. Pour couvrir toute l’étendue du territoire national, il y a nécessité que les moyens alloués pour cette opération soient conséquents. Les observations sur le terrain indiquent une dégradation avancée des écosystèmes des zones humides du littoral et il y a nécessité d’inverser cette tendance pour assurer le cycle biologique des espèces à travers un vaste projet de restauration des sites concernés. A ce titre, le Togo a entamé un processus d’élaboration des plans de gestion des zones humides du littoral. Il est à noter que les principales activités de menaces sont entre autres la pollution de tout genre.");
d.setLicense(License.CC_BY_NC_4_0);
service.create(d);
final Organization plazi = new Organization();
plazi.setTitle("Plazi.org taxonomic treatments database");
plazi.setCountry(Country.SWITZERLAND);
plazi.setEndorsingNodeKey(nodeKey);
plazi.setEndorsementApproved(true);
plazi.setLanguage(Language.ENGLISH);
plazi.setPassword("passw0rd");
plazi.setKey(organizationService.create(plazi));
d.setKey(null);
d.setTitle("A new species of Endecous Saussure, 1878 (Orthoptera, Gryllidae) from northeast Brazil with the first X X 0 chromosomal sex system in Gryllidae");
d.setPublishingOrganizationKey(plazi.getKey());
d.setDescription("This dataset contains the digitized treatments in Plazi based on the original journal article Zefa, Edison, Redü, Darlan Rutz, Costa, Maria Kátia Matiotti Da, Fontanetti, Carmem S., Gottschalk, Marco Silva, Padilha, Giovanna Boff, Fernandes, Anelise, Martins, Luciano De P. (2014): A new species of Endecous Saussure, 1878 (Orthoptera, Gryllidae) from northeast Brazil with the first X X 0 chromosomal sex system in Gryllidae. Zootaxa 3847 (1): 125-132, DOI: http://dx.doi.org/10.11646/zootaxa.3847.1.7");
d.setLicense(License.CC0_1_0);
service.create(d);
//Give some time to Solr to update
Thread.sleep(100);
assertAll(6l);
assertSearch("Hund", 1);
assertSearch("bli bla blub", 2);
assertSearch("PonTaurus", 1);
assertSearch("Pontaurus needs more than 255 characters", 1);
assertSearch("very, very long title", 1);
assertSearch("Bird tracking", 1);
assertSearch("Plazi", 1);
assertSearch("plazi.org", 1);
assertSearch("Kátia", 1);
assertSearch("10.11646/zootaxa.3847.1.7", 1);
List<DatasetSearchResult> docs = assertSearch("GPS", 2);
assertEquals(gpsKey, docs.get(0).getKey());
}
private void update(Organization publisher) throws InterruptedException {
organizationService.update(publisher);
// jenkins sometimes fails to update solr in time for the query to include the modified index.
// allow for some extra time (it should have no bad impact on the real time index)
// TODO: https://github.com/gbif/registry/issues/22
Thread.sleep(100);
}
@Test
@Ignore("See https://github.com/gbif/registry/issues/22")
public void testSearchListener() throws InterruptedException {
Dataset d = newEntity();
d = create(d, 1);
assertAll(1l);
assertSearch("Pontaurus needs more than 255 characters", 1); // 1 result expected
assertSearch("very, very long title", 1); // 1 result expected
// update
d.setTitle("NEW-DATASET-TITLE");
service.update(d);
assertAll(1l);
assertSearch("Pontaurus", 0);
assertSearch(d.getTitle(), 1);
// update publishing organization title should be captured
Organization publisher = organizationService.get(d.getPublishingOrganizationKey());
assertSearch(publisher.getTitle(), 1);
publisher.setTitle("OWNERTITLE");
update(publisher);
assertSearch(publisher.getTitle(), 1);
publisher.setTitle("BGBM");
update(publisher);
assertSearch(publisher.getTitle(), 1);
assertSearch("OWNERTITLE", 0);
// update hosting organization title should be captured
Installation installation = installationService.get(d.getInstallationKey());
assertNotNull("Installation should be present", installation);
Organization host = organizationService.get(installation.getOrganizationKey());
assertSearch(host.getTitle(), 1);
host.setTitle("HOSTTITLE");
update(host);
assertSearch(host.getTitle(), 1);
host.setTitle("BGBM");
update(host);
assertSearch(host.getTitle(), 1);
assertSearch("HOSTTITLE", 0);
// check a deletion removes the dataset for search
service.delete(d.getKey());
assertSearch(host.getTitle(), 0);
}
@Test
public void testInstallationMove() {
Dataset d = newEntity();
d = create(d, 1);
assertSearch(d.getTitle(), 1); // 1 result expected
UUID nodeKey = nodeService.create(Nodes.newInstance());
Organization o = Organizations.newInstance(nodeKey);
o.setTitle("ANEWORG");
UUID organizationKey = organizationService.create(o);
assertSearch(o.getTitle(), 0); // No datasets hosted by that organization yet
Installation installation = installationService.get(d.getInstallationKey());
installation.setOrganizationKey(organizationKey);
installationService.update(installation); // we just moved the installation to a new organization
assertSearch(o.getTitle(), 1); // The dataset moved with the organization!
assertSearch("*", 1);
}
/**
* Utility to verify that after waiting for SOLR to update, the given query returns the expected count of results.
*/
private List<DatasetSearchResult> assertSearch(String query, int expected) {
DatasetSearchUpdateUtils.awaitUpdates(datasetIndexService); // SOLR updates are asynchronous
DatasetSearchRequest req = new DatasetSearchRequest();
req.setQ(query);
SearchResponse<DatasetSearchResult, DatasetSearchParameter> resp = searchService.search(req);
assertNotNull(resp.getCount());
assertEquals("SOLR does not have the expected number of results for query[" + query + "]", Long.valueOf(expected), resp.getCount());
return resp.getResults();
}
/**
* Utility to verify that after waiting for SOLR to update, the given query returns the expected count of results.
*/
private void testSearch(String query) {
System.out.println("\n*****\n"+query);
DatasetSearchUpdateUtils.awaitUpdates(datasetIndexService); // SOLR updates are asynchronous
DatasetSearchRequest req = new DatasetSearchRequest();
req.setQ(query);
SearchResponse<DatasetSearchResult, DatasetSearchParameter> resp = searchService.search(req);
}
private void assertAll(Long expected) {
DatasetSearchUpdateUtils.awaitUpdates(datasetIndexService); // SOLR updates are asynchronous
DatasetSearchRequest req = new DatasetSearchRequest();
req.setQ("*");
SearchResponse<DatasetSearchResult, DatasetSearchParameter> resp = searchService.search(req);
assertNotNull(resp.getCount());
System.out.println(resp.getCount());
System.out.println(resp);
assertEquals("SOLR docs not as expected", expected, resp.getCount());
}
/**
* Utility to verify that after waiting for SOLR to update, the given query returns the expected count of results.
*/
private void assertSearch(Country publishingCountry, Country country, int expected) {
DatasetSearchUpdateUtils.awaitUpdates(datasetIndexService); // SOLR updates are asynchronous
DatasetSearchRequest req = new DatasetSearchRequest();
if (country != null) {
req.addCountryFilter(country);
}
if (publishingCountry != null) {
req.addPublishingCountryFilter(publishingCountry);
}
SearchResponse<DatasetSearchResult, DatasetSearchParameter> resp = searchService.search(req);
assertNotNull(resp.getCount());
assertEquals("SOLR does not have the expected number of results for country[" + country +
"] and publishingCountry[" + publishingCountry + "]", Long.valueOf(expected), resp.getCount());
}
private Dataset newEntity(@Nullable Country publisherCountry) {
// endorsing node for the organization
UUID nodeKey = nodeService.create(Nodes.newInstance());
// publishing organization (required field)
Organization o = Organizations.newInstance(nodeKey);
if (publisherCountry != null) {
o.setCountry(publisherCountry);
}
UUID organizationKey = organizationService.create(o);
Installation i = Installations.newInstance(organizationKey);
UUID installationKey = installationService.create(i);
return newEntity(organizationKey, installationKey);
}
@Override
protected Dataset newEntity() {
return newEntity(null);
}
private Dataset newEntity(UUID organizationKey, UUID installationKey) {
// the dataset
Dataset d = Datasets.newInstance(organizationKey, installationKey);
return d;
}
@Test
public void testDatasetHTMLSanitizer() {
Dataset dataset = newEntity();
dataset.setDescription("<h1 style=\"color:red\">headline</h1><br/>" +
"<p>paragraph with <a href=\"http://www.gbif.org\">link</a> and <em>italics</em></p>" +
"<script>//my script</script>" +
"<iframe src=\"perdu.com\">");
String expectedParagraph = "<h1>headline</h1><br /><p>paragraph with <a href=\"http://www.gbif.org\">link</a> and <em>italics</em></p>";
Map<String, Object> processProperties = Datasets.buildExpectedProcessedProperties(dataset);
processProperties.put("description", expectedParagraph);
dataset = create(dataset, 1, processProperties);
assertEquals(expectedParagraph, dataset.getDescription());
}
@Test
public void testCitation() {
Dataset dataset = newEntity();
dataset = create(dataset, 1);
dataset = service.get(dataset.getKey());
assertNotNull("Citation should never be null", dataset.getCitation());
assertEquals("ABC", dataset.getCitation().getIdentifier());
//original citation not preserved, we generate one
assertNotEquals("This is a citation text", dataset.getCitation().getText());
// update it
dataset.getCitation().setIdentifier("doi:123");
dataset.getCitation().setText("GOD publishing, volume 123");
service.update(dataset);
dataset = service.get(dataset.getKey());
assertEquals("doi:123", dataset.getCitation().getIdentifier());
//original citation not preserved, we generate one
assertNotEquals("GOD publishing, volume 123", dataset.getCitation().getText());
// setting to null should make it the default using the org:dataset titles
dataset.getCitation().setText(null);
service.update(dataset);
dataset = service.get(dataset.getKey());
assertEquals("doi:123", dataset.getCitation().getIdentifier());
//original citation not preserved, we generate one
assertNotEquals("The BGBM: Pontaurus needs more than 255 characters for it's title. It is a very, very, very, very long title in the German language. Word by word and character by character it's exact title is: \"Vegetationskundliche Untersuchungen in der Hochgebirgsregion der Bolkar Daglari & Aladaglari, Türkei\"", dataset.getCitation().getText());
}
@Test
public void testDoiChanges() {
final DOI external1 = new DOI("10.9999/nonGbif");
final DOI external2 = new DOI("10.9999/nonGbif2");
// we use the test prefix in tests for GBIF DOIs, see registry-test.properties
final DOI gbif2 = new DOI("10.21373/sthelse");
Dataset src = newEntity();
src.setDoi(external1);
final UUID key = create(src, 1).getKey();
Dataset dataset = service.get(key);
assertEquals(external1, dataset.getDoi());
assertEquals(0, service.listIdentifiers(key).size());
dataset.setDoi(null);
service.update(dataset);
dataset = service.get(key);
assertNotNull("DOI should never be null", dataset.getDoi());
assertFalse(dataset.getDoi().equals(external1));
final DOI originalGBIF = dataset.getDoi();
assertThat(service.listIdentifiers(key))
.hasSize(1)
.extracting("identifier").contains(external1.toString());
dataset.setDoi(external1);
service.update(dataset);
dataset = service.get(key);
assertEquals(external1, dataset.getDoi());
assertThat(service.listIdentifiers(key))
.hasSize(1)
.extracting("identifier").contains(originalGBIF.toString());
dataset.setDoi(external2);
service.update(dataset);
dataset = service.get(key);
assertEquals(external2, dataset.getDoi());
assertThat(service.listIdentifiers(key))
.hasSize(2)
.extracting("identifier").contains(originalGBIF.toString(), external1.toString());
dataset.setDoi(null);
service.update(dataset);
dataset = service.get(key);
assertEquals(originalGBIF, dataset.getDoi());
assertThat(service.listIdentifiers(key))
.hasSize(2)
.extracting("identifier").contains(external1.toString(), external2.toString());
dataset.setDoi(gbif2);
service.update(dataset);
dataset = service.get(key);
assertEquals(gbif2, dataset.getDoi());
assertThat(service.listIdentifiers(key))
.hasSize(3)
.extracting("identifier").contains(external1.toString(), external2.toString(), originalGBIF.toString());
dataset.setDoi(external1);
service.update(dataset);
dataset = service.get(key);
assertEquals(external1, dataset.getDoi());
assertThat(service.listIdentifiers(key))
.hasSize(3)
.extracting("identifier").contains(gbif2.toString(), external2.toString(), originalGBIF.toString());
}
@Test
public void testLicenseChanges() {
Dataset src = newEntity();
// start with dataset with null license
src.setLicense(null);
// register dataset
final UUID key = create(src, 1).getKey();
// ensure default license CC-BY 4.0 was assigned
Dataset dataset = service.get(key);
assertEquals(License.CC_BY_4_0, dataset.getLicense());
// try updating dataset, setting license to NULL - ensure original license was preserved
dataset.setLicense(null);
service.update(dataset);
dataset = service.get(key);
assertEquals(License.CC_BY_4_0, dataset.getLicense());
// try updating dataset with different, less restrictive license CC0 1.0 - ensure license was replaced
dataset.setLicense(License.CC0_1_0);
service.update(dataset);
dataset = service.get(key);
assertEquals(License.CC0_1_0, dataset.getLicense());
// try updating dataset with an UNSUPPORTED license - ensure original license CC0 1.0 was preserved
dataset.setLicense(License.UNSUPPORTED);
service.update(dataset);
dataset = service.get(key);
assertEquals(License.CC0_1_0, dataset.getLicense());
// try updating dataset with an UNSPECIFIED license - ensure original license CC0 1.0 was preserved
dataset.setLicense(License.UNSPECIFIED);
service.update(dataset);
dataset = service.get(key);
assertEquals(License.CC0_1_0, dataset.getLicense());
}
/**
* Test calls DatasetResource.updateFromPreferredMetadata directly, to ensure it updates the dataset by
* reinterpreting its preferred metadata document. In particular the test ensures the dataset license is updated
* properly as per the metadata document.
*/
@Test
public void testUpdateFromPreferredMetadata() throws IOException {
Dataset src = newEntity();
// start with dataset with CC0 license
src.setLicense(License.CC0_1_0);
// register dataset
final UUID key = create(src, 1).getKey();
// ensure license CC0 was assigned
Dataset dataset = service.get(key);
assertEquals(License.CC0_1_0, dataset.getLicense());
// insert metadata document, which sets license to more restrictive license CC-BY - ensure license was replaced
InputStream is = Resources.getResourceAsStream("metadata/sample-v1.1.xml");
service.insertMetadata(key, is);
dataset = service.get(key);
assertEquals(License.CC_BY_4_0, dataset.getLicense());
// update dataset, overwritting license back to CC0
dataset.setLicense(License.CC0_1_0);
service.update(dataset);
dataset = service.get(key);
assertEquals(License.CC0_1_0, dataset.getLicense());
// last, update dataset from preferred metadata document, ensuring license gets reset to CC-BY
DatasetResource datasetResource = webservice().getBinding(DatasetResource.class).getProvider().get();
datasetResource.updateFromPreferredMetadata(key, "DatasetIT");
dataset = service.get(key);
assertEquals(License.CC_BY_4_0, dataset.getLicense());
}
/**
* Test checks behaviour updating Citation with valid and invalid identifier.
* In the database, there is a min length 1 character constraint on Dataset.citation_identifier.
*/
@Test
public void testDatasetCitationIdentifierConstraint() throws IOException {
Dataset src = newEntity();
// register dataset
final UUID key = create(src, 1).getKey();
Dataset dataset = service.get(key);
assertNotNull(dataset.getCitation());
// set Citation identifier to null
Citation c = dataset.getCitation();
c.setIdentifier(null);
dataset.setCitation(c);
service.update(dataset);
// check update succeeds
dataset = service.get(key);
assertNotNull(dataset.getCitation());
// we use the generated citation
assertNotEquals("This is a citation text", dataset.getCitation().getText());
assertNull(dataset.getCitation().getIdentifier());
// set Citation identifier to single character
c = dataset.getCitation();
c.setIdentifier("");
dataset.setCitation(c);
// update dataset...
ConstraintViolationException exception = null;
try {
service.update(dataset);
} catch (ConstraintViolationException e) {
exception = e;
}
// /...and check it fails, however, constraint violation can only be thrown by web service because client
// trims Citation fields via StringTrimInterceptor
if (service.equals(webservice().getBinding(DatasetService.class).getProvider().get())) {
assertNotNull(exception);
}
}
@Test
public void testMaintenanceUpdateFrequencyChanges() {
Dataset src = newEntity();
assertNull(src.getMaintenanceUpdateFrequency());
final UUID key = create(src, 1).getKey();
Dataset dataset = service.get(key);
assertNull(src.getMaintenanceUpdateFrequency());
// try updating maintenanceUpdateFrequency - ensure value persisted
dataset.setMaintenanceUpdateFrequency(MaintenanceUpdateFrequency.AS_NEEDED);
service.update(dataset);
dataset = service.get(key);
assertEquals(MaintenanceUpdateFrequency.AS_NEEDED, dataset.getMaintenanceUpdateFrequency());
// try updating maintenanceUpdateFrequency again - ensure value replaced
dataset.setMaintenanceUpdateFrequency(MaintenanceUpdateFrequency.BIANNUALLY);
service.update(dataset);
dataset = service.get(key);
assertEquals(MaintenanceUpdateFrequency.BIANNUALLY, dataset.getMaintenanceUpdateFrequency());
}
@Test
public void test404() throws IOException {
assertNull(service.get(UUID.randomUUID()));
}
@Test
public void testMetadata() throws IOException {
Dataset d1 = create(newEntity(), 1);
assertEquals(License.CC_BY_NC_4_0, d1.getLicense());
List<Metadata> metadata = service.listMetadata(d1.getKey(), MetadataType.EML);
assertEquals("No EML uploaded yes", 0, metadata.size());
// upload a valid EML document (without a machine readable license)
service.insertMetadata(d1.getKey(), FileUtils.classpathStream("metadata/sample.xml"));
// verify dataset was updated from parsed document
Dataset d2 = service.get(d1.getKey());
assertNotEquals("Dataset should have changed after metadata was uploaded", d1, d2);
assertEquals("Tanzanian Entomological Collection", d2.getTitle());
assertEquals("Created data should not change", d1.getCreated(), d2.getCreated());
assertTrue("Dataset modification date should change", d1.getModified().before(d2.getModified()));
// verify license stayed the same, because no machine readable license was detected in EML document
assertEquals(License.CC_BY_NC_4_0, d2.getLicense());
// verify EML document was stored successfully
metadata = service.listMetadata(d1.getKey(), MetadataType.EML);
assertEquals("Exactly one EML uploaded", 1, metadata.size());
assertEquals("Wrong metadata type", MetadataType.EML, metadata.get(0).getType());
// check number of stored DC documents
metadata = service.listMetadata(d1.getKey(), MetadataType.DC);
assertTrue("No Dublin Core uplaoded yet", metadata.isEmpty());
// upload subsequent DC document which has less priority than the previous EML document
service.insertMetadata(d1.getKey(), FileUtils.classpathStream("metadata/worms_dc.xml"));
// verify dataset has NOT changed
Dataset d3 = service.get(d1.getKey());
assertEquals("Tanzanian Entomological Collection", d3.getTitle());
assertEquals("Created data should not change", d1.getCreated(), d3.getCreated());
// verify DC document was stored successfully
metadata = service.listMetadata(d1.getKey(), MetadataType.DC);
assertEquals("Exactly one DC uploaded", 1, metadata.size());
assertEquals("Wrong metadata type", MetadataType.DC, metadata.get(0).getType());
// upload 2nd EML doc (with a machine readable license), which has higher priority than the previous EML doc
service.insertMetadata(d1.getKey(), FileUtils.classpathStream("metadata/sample-v1.1.xml"));
// verify dataset was updated from parsed document
Dataset d4 = service.get(d1.getKey());
assertEquals("Sample Metadata RLS", d4.getTitle());
// verify license was updated because CC-BY 4.0 license was detected in EML document
assertEquals(License.CC_BY_4_0, d4.getLicense());
// verify EML document replaced EML docuemnt of less priority
metadata = service.listMetadata(d1.getKey(), MetadataType.EML);
assertEquals("Exactly one EML uploaded", 1, metadata.size());
// upload 3rd EML doc (with a machine readable UNSUPPORTED license), which has higher priority than the previous EML doc
service.insertMetadata(d1.getKey(), FileUtils.classpathStream("metadata/sample-v1.1-unsupported-license.xml"));
// verify dataset was updated from parsed document
Dataset d5 = service.get(d1.getKey());
assertEquals("Sample Metadata RLS (2)", d5.getTitle());
// verify license was NOT updated because UNSUPPORTED license was detected in EML document (only supported license
// can overwrite existing license)
assertEquals(License.CC_BY_4_0, d5.getLicense());
// verify EML document replaced EML document of less priority
metadata = service.listMetadata(d1.getKey(), MetadataType.EML);
assertEquals("Exactly one EML uploaded", 1, metadata.size());
int lastEmlMetadataDocKey = metadata.get(0).getKey();
// upload exact same EML doc again, but make sure it does NOT update dataset!
Dataset lastUpated = service.get(d1.getKey());
service.insertMetadata(d1.getKey(), FileUtils.classpathStream("metadata/sample-v1.1-unsupported-license.xml"));
// verify dataset was NOT updated from parsed document
Dataset d6 = service.get(d1.getKey());
assertTrue(d6.getModified().compareTo(lastUpated.getModified()) == 0);
// verify EML document NOT replaced
List<Metadata> metadata2 = service.listMetadata(d1.getKey(), MetadataType.EML);
int emlMetadataDocKey = metadata2.get(0).getKey();
assertEquals(lastEmlMetadataDocKey, emlMetadataDocKey);
// verify original EML document can be retrieved by WS request (verify POR-3170 fixed)
InputStream persistedDocument = service.getMetadataDocument(emlMetadataDocKey);
String persistedDocumentContent = CharStreams.toString(new InputStreamReader(persistedDocument, Charsets.UTF_8));
InputStream originalDocument = FileUtils.classpathStream("metadata/sample-v1.1-unsupported-license.xml");
String originalDocumentContent = CharStreams.toString(new InputStreamReader(originalDocument, Charsets.UTF_8));
assertEquals(originalDocumentContent, persistedDocumentContent);
}
/**
* Test that uploading the same document repeatedly does not change the dataset.
*/
@Test
public void testMetadataDuplication() throws IOException {
Dataset d1 = newAndCreate(1);
List<Metadata> m1 = service.listMetadata(d1.getKey(), MetadataType.EML);
// upload a valid EML doc
service.insertMetadata(d1.getKey(), FileUtils.classpathStream("metadata/sample.xml"));
// verify our dataset has changed
Dataset d2 = service.get(d1.getKey());
assertNotEquals("Dataset should have changed after metadata was uploaded", d1, d2);
List<Metadata> m2 = service.listMetadata(d1.getKey(), MetadataType.EML);
assertNotEquals("Dataset metadata should have changed after metadata was uploaded", m1, m2);
// upload the doc a second time - it should not update the metadata
service.insertMetadata(d1.getKey(), FileUtils.classpathStream("metadata/sample.xml"));
List<Metadata> m3 = service.listMetadata(d1.getKey(), MetadataType.EML);
assertEquals("Dataset metadata should not have changed after same metadata document was uploaded", m2, m3);
}
@Test
public void testByCountry() {
createCountryDatasets(DatasetType.OCCURRENCE, Country.ANDORRA, 3);
createCountryDatasets(DatasetType.OCCURRENCE, Country.DJIBOUTI, 1);
createCountryDatasets(DatasetType.METADATA, Country.HAITI, 7);
createCountryDatasets(DatasetType.OCCURRENCE, Country.HAITI, 3);
createCountryDatasets(DatasetType.CHECKLIST, Country.HAITI, 2);
assertResultsOfSize(service.listByCountry(Country.UNKNOWN, null, new PagingRequest()), 0);
assertResultsOfSize(service.listByCountry(Country.ANDORRA, null, new PagingRequest()), 3);
assertResultsOfSize(service.listByCountry(Country.DJIBOUTI, null, new PagingRequest()), 1);
assertResultsOfSize(service.listByCountry(Country.HAITI, null, new PagingRequest()), 12);
assertResultsOfSize(service.listByCountry(Country.ANDORRA, DatasetType.CHECKLIST, new PagingRequest()), 0);
assertResultsOfSize(service.listByCountry(Country.HAITI, DatasetType.OCCURRENCE, new PagingRequest()), 3);
assertResultsOfSize(service.listByCountry(Country.HAITI, DatasetType.CHECKLIST, new PagingRequest()), 2);
assertResultsOfSize(service.listByCountry(Country.HAITI, DatasetType.METADATA, new PagingRequest()), 7);
}
@Test
public void testListByType() {
createDatasetsWithType(DatasetType.METADATA, 1);
createDatasetsWithType(DatasetType.CHECKLIST, 2);
createDatasetsWithType(DatasetType.OCCURRENCE, 3);
createDatasetsWithType(DatasetType.SAMPLING_EVENT, 4);
assertResultsOfSize(service.listByType(DatasetType.METADATA, new PagingRequest()), 1);
assertResultsOfSize(service.listByType(DatasetType.CHECKLIST, new PagingRequest()), 2);
assertResultsOfSize(service.listByType(DatasetType.OCCURRENCE, new PagingRequest()), 3);
assertResultsOfSize(service.listByType(DatasetType.SAMPLING_EVENT, new PagingRequest()), 4);
}
@Test
@Ignore("Country coverage not populated yet: http://dev.gbif.org/issues/browse/REG-393")
public void testCountrySearch() {
createCountryDatasets(Country.ANDORRA, 3);
createCountryDatasets(DatasetType.OCCURRENCE, Country.DJIBOUTI, 1, Country.DJIBOUTI);
createCountryDatasets(DatasetType.OCCURRENCE, Country.HAITI, 3, Country.AFGHANISTAN, Country.DENMARK);
createCountryDatasets(DatasetType.CHECKLIST, Country.HAITI, 4, Country.GABON, Country.FIJI);
createCountryDatasets(DatasetType.OCCURRENCE, Country.DOMINICA, 2, Country.DJIBOUTI);
assertSearch(Country.ALBANIA, null, 0);
assertSearch(Country.ANDORRA, null, 3);
assertSearch(Country.DJIBOUTI, null, 1);
assertSearch(Country.HAITI, null, 7);
assertSearch(Country.UNKNOWN, null, 0);
assertSearch(Country.HAITI, Country.GABON, 4);
assertSearch(Country.HAITI, Country.FIJI, 4);
assertSearch(Country.HAITI, Country.DENMARK, 3);
assertSearch(Country.DJIBOUTI, Country.DENMARK, 0);
assertSearch(Country.DJIBOUTI, Country.DJIBOUTI, 1);
assertSearch(Country.DJIBOUTI, Country.GERMANY, 0);
assertSearch(null, Country.DJIBOUTI, 3);
}
@Test(expected = ValidationException.class)
public void createDatasetsWithInvalidUri() {
Dataset d = newEntity();
d.setHomepage(URI.create("file:/test.txt"));
service.create(d);
}
private void createCountryDatasets(Country publishingCountry, int number) {
createCountryDatasets(DatasetType.OCCURRENCE, publishingCountry, number, (Country) null);
}
private void createCountryDatasets(DatasetType type, Country publishingCountry, int number, Country... countries) {
Dataset d = addCountryCoverage(newEntity(), countries);
d.setType(type);
service.create(d);
// assign a controlled country based organization
Organization org = organizationService.get(d.getPublishingOrganizationKey());
org.setCountry(publishingCountry);
organizationService.update(org);
// create datasets for it
for (int x = 1; x < number; x++) {
d = addCountryCoverage(newEntity(org.getKey(), d.getInstallationKey()));
d.setType(type);
service.create(d);
}
}
/**
* Create a number of new Datasets, having a particular dataset type.
*
* @param type dataset type
* @param number amount of datasets to create
*/
private void createDatasetsWithType(DatasetType type, int number) {
// create datasets for it
for (int x = 0; x < number; x++) {
Dataset d = newEntity();
d.setType(type);
service.create(d);
}
}
private Dataset addCountryCoverage(Dataset d, Country... countries) {
if (countries != null) {
for (Country c : countries) {
if (c != null) {
d.getCountryCoverage().add(c);
}
}
}
return d;
}
/**
* Create a new instance of Dataset, store it using the create method.
* @param expectedCount
* @return
*/
private Dataset newAndCreate(int expectedCount) {
Dataset newDataset = newEntity();
return create(newDataset, expectedCount);
}
} |
Java | class ChildWorkflowInvocationHandler implements InvocationHandler {
private final ChildWorkflowStub stub;
private final POJOWorkflowInterfaceMetadata workflowMetadata;
ChildWorkflowInvocationHandler(
Class<?> workflowInterface,
ChildWorkflowOptions options,
WorkflowOutboundCallsInterceptor outboundCallsInterceptor) {
workflowMetadata = POJOWorkflowInterfaceMetadata.newInstance(workflowInterface);
Optional<POJOWorkflowMethodMetadata> workflowMethodMetadata =
workflowMetadata.getWorkflowMethod();
if (!workflowMethodMetadata.isPresent()) {
throw new IllegalArgumentException(
"Missing method annotated with @WorkflowMethod: " + workflowInterface.getName());
}
Method workflowMethod = workflowMethodMetadata.get().getWorkflowMethod();
MethodRetry retryAnnotation = workflowMethod.getAnnotation(MethodRetry.class);
CronSchedule cronSchedule = workflowMethod.getAnnotation(CronSchedule.class);
ChildWorkflowOptions merged =
ChildWorkflowOptions.newBuilder(options)
.setMethodRetry(retryAnnotation)
.setCronSchedule(cronSchedule)
.validateAndBuildWithDefaults();
this.stub =
new ChildWorkflowStubImpl(
workflowMethodMetadata.get().getName(), merged, outboundCallsInterceptor);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) {
// Implement StubMarker
if (method.getName().equals(StubMarker.GET_UNTYPED_STUB_METHOD)) {
return stub;
}
POJOWorkflowMethodMetadata methodMetadata = workflowMetadata.getMethodMetadata(method);
WorkflowMethodType type = methodMetadata.getType();
if (type == WorkflowMethodType.WORKFLOW) {
return getValueOrDefault(
stub.execute(method.getReturnType(), method.getGenericReturnType(), args),
method.getReturnType());
}
if (type == WorkflowMethodType.SIGNAL) {
stub.signal(methodMetadata.getName(), args);
return null;
}
if (type == WorkflowMethodType.QUERY) {
throw new UnsupportedOperationException(
"Query is not supported from workflow to workflow. "
+ "Use activity that perform the query instead.");
}
throw new IllegalArgumentException("unreachable");
}
} |
Java | public class UtilsValidation {
public static final String MISSING_REQUIRED_VALUE = "Missing required value";
public static final String INVALID_FORMAT = "invalid format";
public static final String INVALID_PARAMETER = "invalid parameter";
public static final String PARAMETER_DOES_NOT_EXIST = "field does not exist";
public static final String ALREADY_EXISTS = "field already exists";
private static final SimpleDateFormat SDF_DATETIME = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
private static final String PHONE_NUMBER_PATTERN = "^[0-9]*$";
private static final String SPECIAL_CHARS = "/*!@#$%^&*()\"{}_[]|\\?/<>,.";
private static final String TIME24HOURS_PATTERN = "([01]?[0-9]|2[0-3]):[0-5][0-9]";
private static final String DATE = "^((19|20)\\d\\d)-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])$";
private static final String HAS_NUMBER = ".*\\d+.*";
/**
* Validates that the property propertyName in the JsonObject object is an email with the pattern
* "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$", ignoring null
*
* @param object object to evaluate
* @param propertyName name of the property to evaluate
* @throws utils.UtilsValidation.PropertyValueException if the evaluation fails
*/
public static void isMail(final JsonObject object, final String propertyName) throws PropertyValueException {
evaluate(EMAIL_PATTERN, object, propertyName);
}
/**
* Validates that the property propertyName in the JsonObject object is a phone number with the pattern: "^[0-9]*$",
* ignoring null
*
* @param object object to evaluate
* @param propertyName name of the property to evaluate
* @throws utils.UtilsValidation.PropertyValueException if the evaluation fails
*/
public static void isPhoneNumber(final JsonObject object, final String propertyName) throws PropertyValueException {
evaluate(PHONE_NUMBER_PATTERN, object, propertyName);
}
/**
* Validates that the property propertyName in the JsonObject object is a date with the pattern:
* "^((19|20)\\d\\d)-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])$" , ignoring null
*
* @param object object to evaluate
* @param propertyName name of the property to evaluate
* @throws utils.UtilsValidation.PropertyValueException if the evaluation fails
*/
public static void isDate(final JsonObject object, final String propertyName) throws PropertyValueException {
evaluate(DATE, object, propertyName);
}
/**
* Validates that the property propertyName in the JsonObject object is a hour with the pattern:
* "([01]?[0-9]|2[0-3]):[0-5][0-9]", ignoring null
*
* @param object object to evaluate
* @param propertyName name of the property to evaluate
* @throws utils.UtilsValidation.PropertyValueException if the evaluation fails
*/
public static void isHour24(final JsonObject object, final String propertyName) throws PropertyValueException {
evaluate(TIME24HOURS_PATTERN, object, propertyName);
}
/**
* Validates that the text contains special character and do not be empty, ignoring null
*
* @param object object to evaluate
* @param propertyName name of the property to evaluate
* @throws utils.UtilsValidation.PropertyValueException if the evaluation fails
*/
public static void containsSpecialCharacter(final JsonObject object, final String propertyName) throws PropertyValueException {
try {
String s = object.getString(propertyName);
if (s != null) {
if (s.isEmpty()) {
throw new PropertyValueException(propertyName, INVALID_FORMAT);
}
for (int i = 0; i < s.length(); i++) {
if (SPECIAL_CHARS.contains(s.substring(i, (i + 1)))) {
throw new PropertyValueException(propertyName, INVALID_FORMAT);
}
}
}
} catch (ClassCastException e) {
throw new PropertyValueException(propertyName, INVALID_FORMAT);
}
}
/**
* Validates that the property matches with a personal name, ignoring null
*
* @param object object to evaluate
* @param propertyName name of the property to evaluate
* @throws utils.UtilsValidation.PropertyValueException if the evaluation fails
*/
public static void isName(final JsonObject object, final String propertyName) throws PropertyValueException {
try {
String s = object.getString(propertyName);
if (s != null) {
if (s.isEmpty()) {
throw new PropertyValueException(propertyName, INVALID_FORMAT);
}
if (s.contains("\"") || s.contains("'")) {
throw new PropertyValueException(propertyName, INVALID_FORMAT);
}
Matcher matcher = Pattern.compile(HAS_NUMBER).matcher(s);
if (matcher.matches()) {
throw new PropertyValueException(propertyName, INVALID_FORMAT);
}
}
} catch (ClassCastException e) {
throw new PropertyValueException(propertyName, INVALID_FORMAT);
}
}
/**
* Validates that the int value in the property is between the range from-to including from and to values, ignoring
* null
*
* @param from initial value to start the range
* @param to final value to end the range
* @param object object to evaluate
* @param propertyName name of the property to evaluate
* @throws utils.UtilsValidation.PropertyValueException if the evaluation fails
*/
public static void betweenRange(final JsonObject object, final String propertyName, final int from, final int to) throws PropertyValueException {
try {
Integer val = object.getInteger(propertyName);
if (val != null) {
if (val < from || val > to) { //out of range
throw new PropertyValueException(propertyName, INVALID_FORMAT);
}
}
} catch (ClassCastException e) {
throw new PropertyValueException(propertyName, INVALID_FORMAT);
}
}
/**
* Validates that the value in the property is one of the values provided, ignoring null
*
* @param values values to check equality
* @param object object to evaluate
* @param propertyName name of the property to evaluate
* @throws utils.UtilsValidation.PropertyValueException if the evaluation fails
*/
public static void isContained(final JsonObject object, final String propertyName, String... values) throws PropertyValueException {
try {
String propertyValue = object.getString(propertyName);
if (propertyValue != null) {
for (String value : values) {
if (value.equals(propertyValue)) {
return;
}
}
throw new PropertyValueException(propertyName, INVALID_FORMAT);
}
} catch (ClassCastException e) {
throw new PropertyValueException(propertyName, INVALID_FORMAT);
}
}
/**
* Validates that the property propertyName in the JsonObject object is an email with the pattern
* "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"
*
* @param object object to evaluate
* @param propertyName name of the property to evaluate
* @throws utils.UtilsValidation.PropertyValueException if the evaluation fails
*/
public static void isMailAndNotNull(final JsonObject object, final String propertyName) throws PropertyValueException {
evaluateAndNotNull(EMAIL_PATTERN, object, propertyName);
}
/**
* Validates that the property propertyName in the JsonObject object is a phone number with the pattern: "^[0-9]*$"
*
* @param object object to evaluate
* @param propertyName name of the property to evaluate
* @throws utils.UtilsValidation.PropertyValueException if the evaluation fails
*/
public static void isPhoneNumberAndNotNull(final JsonObject object, final String propertyName) throws PropertyValueException {
evaluateAndNotNull(PHONE_NUMBER_PATTERN, object, propertyName);
}
/**
* Validates that the property propertyName in the JsonObject object is a date with the pattern:
* "^((19|20)\\d\\d)-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])$"
*
* @param object object to evaluate
* @param propertyName name of the property to evaluate
* @throws utils.UtilsValidation.PropertyValueException if the evaluation fails
*/
public static void isDateAndNotNull(final JsonObject object, final String propertyName) throws PropertyValueException {
evaluateAndNotNull(DATE, object, propertyName);
}
/**
* Validates that the property propertyName in the JsonObject object is a hour with the pattern:
* "([01]?[0-9]|2[0-3]):[0-5][0-9]"
*
* @param object object to evaluate
* @param propertyName name of the property to evaluate
* @throws utils.UtilsValidation.PropertyValueException if the evaluation fails
*/
public static void isHour24AndNotNull(final JsonObject object, final String propertyName) throws PropertyValueException {
evaluateAndNotNull(TIME24HOURS_PATTERN, object, propertyName);
}
/**
* Validates that the text contains special character and do not be empty, considering not null
*
* @param object object to evaluate
* @param propertyName name of the property to evaluate
* @throws utils.UtilsValidation.PropertyValueException if the evaluation fails
*/
public static void containsSpecialCharacterAndNotNull(final JsonObject object, final String propertyName) throws PropertyValueException {
try {
String s = object.getString(propertyName);
if (s == null) {
throw new PropertyValueException(propertyName, MISSING_REQUIRED_VALUE);
}
if (s.isEmpty()) {
throw new PropertyValueException(propertyName, INVALID_FORMAT);
}
for (int i = 0; i < s.length(); i++) {
if (SPECIAL_CHARS.contains(s.substring(i, (i + 1)))) {
throw new PropertyValueException(propertyName, INVALID_FORMAT);
}
}
} catch (ClassCastException e) {
throw new PropertyValueException(propertyName, INVALID_FORMAT);
}
}
/**
* Validates that the property matches with a personal name
*
* @param object object to evaluate
* @param propertyName name of the property to evaluate
* @throws utils.UtilsValidation.PropertyValueException if the evaluation fails
*/
public static void isNameAndNotNull(final JsonObject object, final String propertyName) throws PropertyValueException {
try {
String s = object.getString(propertyName);
if (s != null) {
if (s.isEmpty()) {
throw new PropertyValueException(propertyName, INVALID_FORMAT);
}
if (s.contains("\"") || s.contains("'")) {
throw new PropertyValueException(propertyName, INVALID_FORMAT);
}
Matcher matcher = Pattern.compile(HAS_NUMBER).matcher(s);
if (matcher.matches()) {
throw new PropertyValueException(propertyName, INVALID_FORMAT);
}
} else {
throw new PropertyValueException(propertyName, MISSING_REQUIRED_VALUE);
}
} catch (ClassCastException e) {
throw new PropertyValueException(propertyName, INVALID_FORMAT);
}
}
/**
* Validates that the int value in the property is between the range from-to including from and to values
*
* @param from initial value to start the range
* @param to final value to end the range
* @param object object to evaluate
* @param propertyName name of the property to evaluate
* @throws utils.UtilsValidation.PropertyValueException if the evaluation fails
*/
public static void betweenRangeAndNotNull(final JsonObject object, final String propertyName, final int from, final int to) throws PropertyValueException {
try {
Integer val = object.getInteger(propertyName);
if (val != null) {
if (val < from || val > to) { //out of range
throw new PropertyValueException(propertyName, INVALID_FORMAT);
}
} else {
throw new PropertyValueException(propertyName, MISSING_REQUIRED_VALUE);
}
} catch (ClassCastException e) {
throw new PropertyValueException(propertyName, INVALID_FORMAT);
}
}
/**
* Validates that the value in the property is one of the values provided
*
* @param values values to check equality
* @param object object to evaluate
* @param propertyName name of the property to evaluate
* @throws utils.UtilsValidation.PropertyValueException if the evaluation fails
*/
public static void isContainedAndNotNull(final JsonObject object, final String propertyName, String... values) throws PropertyValueException {
try {
String propertyValue = object.getString(propertyName);
if (propertyValue != null) {
for (String value : values) {
if (value.equals(propertyValue)) {
return;
}
}
throw new PropertyValueException(propertyName, INVALID_FORMAT);
} else {
throw new PropertyValueException(propertyName, MISSING_REQUIRED_VALUE);
}
} catch (ClassCastException e) {
throw new PropertyValueException(propertyName, INVALID_FORMAT);
}
}
/**
* Validate the value of the property in the object with the pattern given as regular expresion, includes null
* validation, ignoring null
*
* @param pattern pattern to compile
* @param object object to evaluate
* @param propertyName name of the property to evaluate
* @throws utils.UtilsValidation.PropertyValueException if the evaluation fails
*/
private static void evaluate(final String pattern, JsonObject object, String propertyName) throws PropertyValueException {
try {
String s = object.getString(propertyName);
if (s != null) {
if (s.isEmpty()) {
throw new PropertyValueException(propertyName, INVALID_FORMAT);
}
Matcher matcher = Pattern.compile(pattern).matcher(s);
if (!matcher.matches()) {
throw new PropertyValueException(propertyName, INVALID_FORMAT);
}
}
} catch (ClassCastException e) {
throw new PropertyValueException(propertyName, INVALID_FORMAT);
}
}
/**
* Validate the value of the property in the object with the pattern given as regular expresion, includes null
* validation
*
* @param pattern pattern to compile
* @param object object to evaluate
* @param propertyName name of the property to evaluate
* @throws utils.UtilsValidation.PropertyValueException if the evaluation fails
*/
private static void evaluateAndNotNull(final String pattern, JsonObject object, String propertyName) throws PropertyValueException {
try {
String s = object.getString(propertyName);
if (s == null) {
throw new PropertyValueException(propertyName, MISSING_REQUIRED_VALUE);
}
if (s.isEmpty()) {
throw new PropertyValueException(propertyName, MISSING_REQUIRED_VALUE);
}
Matcher matcher = Pattern.compile(pattern).matcher(s);
if (!matcher.matches()) {
throw new PropertyValueException(propertyName, INVALID_FORMAT);
}
} catch (ClassCastException e) {
throw new PropertyValueException(propertyName, INVALID_FORMAT);
}
}
/**
* Validates that a string has almost 1 character
*
* @param object object to evaluate
* @param propertyName name of the property to evaluate
* @throws utils.UtilsValidation.PropertyValueException if the evaluation fails
*/
public static void isEmptyAndNotNull(final JsonObject object, final String propertyName) throws PropertyValueException {
try {
String s = object.getString(propertyName);
if (s == null) {
throw new PropertyValueException(propertyName, MISSING_REQUIRED_VALUE);
}
if (s.isEmpty()) {
throw new PropertyValueException(propertyName, INVALID_FORMAT);
}
} catch (ClassCastException e) {
throw new PropertyValueException(propertyName, INVALID_FORMAT);
}
}
/**
* Validates that a string has almost 1 character, ignoring null
*
* @param object object to evaluate
* @param propertyName name of the property to evaluate
* @throws utils.UtilsValidation.PropertyValueException if the evaluation fails
*/
public static void isEmpty(final JsonObject object, final String propertyName) throws PropertyValueException {
try {
String s = object.getString(propertyName);
if (s != null) {
if (s.isEmpty()) {
throw new PropertyValueException(propertyName, INVALID_FORMAT);
}
}
} catch (ClassCastException e) {
throw new PropertyValueException(propertyName, INVALID_FORMAT);
}
}
public static class PropertyValueException extends Exception {
private String name;
private String error;
public PropertyValueException(String name, String error) {
this.name = name;
this.error = error;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
}
} |
Java | public class MiscSpec extends BaseGSpec {
public static final int DEFAULT_TIMEOUT = 1000;
/**
* Generic constructor.
*
* @param spec object
*/
public MiscSpec(CommonG spec) {
this.commonspec = spec;
}
/**
* Save value for future use.
* <p>
* If element is a jsonpath expression (i.e. $.fragments[0].id), it will be
* applied over the last httpResponse.
* <p>
* If element is a jsonpath expression preceded by some other string
* (i.e. ["a","b",,"c"].$.[0]), it will be applied over this string.
* This will help to save the result of a jsonpath expression evaluated over
* previous stored variable.
*
* @param position position from a search result
* @param element key in the json response to be saved
* @param envVar thread environment variable where to store the value
* @throws IllegalAccessException exception
* @throws IllegalArgumentException exception
* @throws SecurityException exception
* @throws NoSuchFieldException exception
* @throws ClassNotFoundException exception
* @throws InstantiationException exception
* @throws InvocationTargetException exception
* @throws NoSuchMethodException exception
*/
@Given("^I save element (in position '(.+?)' in )?'(.+?)' in environment variable '(.+?)'$")
public void saveElementEnvironment(String position, String element, String envVar) throws Exception {
Pattern pattern = Pattern.compile("^((.*)(\\.)+)(\\$.*)$");
Matcher matcher = pattern.matcher(element);
String json;
String parsedElement;
if (matcher.find()) {
json = matcher.group(2);
parsedElement = matcher.group(4);
} else {
json = commonspec.getResponse().getResponse();
parsedElement = element;
}
String value = commonspec.getJSONPathString(json, parsedElement, position);
ThreadProperty.set(envVar, value.replaceAll("\n", ""));
}
/**
* Save value for future use.
*
* @param value value to be saved
* @param envVar thread environment variable where to store the value
*/
@Given("^I save '(.+?)' in variable '(.+?)'$")
public void saveInEnvironment(String value, String envVar) {
ThreadProperty.set(envVar, value);
}
/**
* Wait seconds.
*
* @param seconds
* @throws InterruptedException
*/
@When("^I wait '(\\d+)' seconds?$")
public void idleWait(Integer seconds) throws InterruptedException {
Thread.sleep(seconds * DEFAULT_TIMEOUT);
}
/**
* Sort elements in envVar by a criteria and order.
*
* @param envVar Environment variable to be sorted
* @param criteria alphabetical,...
* @param order ascending or descending
*/
@When("^I sort elements in '(.+?)' by '(.+?)' criteria in '(.+?)' order$")
public void sortElements(String envVar, String criteria, String order) {
String value = ThreadProperty.get(envVar);
JsonArray jsonArr = JsonValue.readHjson(value).asArray();
List<JsonValue> jsonValues = new ArrayList<JsonValue>();
for (int i = 0; i < jsonArr.size(); i++) {
jsonValues.add(jsonArr.get(i));
}
Comparator<JsonValue> comparator;
switch (criteria) {
case "alphabetical":
commonspec.getLogger().debug("Alphabetical criteria selected.");
comparator = new Comparator<JsonValue>() {
public int compare(JsonValue json1, JsonValue json2) {
int res = String.CASE_INSENSITIVE_ORDER.compare(json1.toString(), json2.toString());
if (res == 0) {
res = json1.toString().compareTo(json2.toString());
}
return res;
}
};
break;
default:
commonspec.getLogger().debug("No criteria selected.");
comparator = null;
}
if ("ascending".equals(order)) {
Collections.sort(jsonValues, comparator);
} else {
Collections.sort(jsonValues, comparator.reversed());
}
ThreadProperty.set(envVar, jsonValues.toString());
}
/**
* Checks if an exception has been thrown.
*
* @param exception : "IS NOT" | "IS"
* @param clazz
* @param exceptionMsg
*/
@Then("^an exception '(.+?)' thrown( with class '(.+?)')?( and message like '(.+?)')?")
public void assertExceptionNotThrown(String exception, String clazz, String exceptionMsg)
throws ClassNotFoundException {
List<Exception> exceptions = commonspec.getExceptions();
if ("IS NOT".equals(exception)) {
assertThat(exceptions).as("Captured exception list is not empty").isEmpty();
} else {
assertThat(exceptions).as("Captured exception list is empty").isNotEmpty();
Exception ex = exceptions.get(exceptions.size() - 1);
if (clazz != null && exceptionMsg != null) {
assertThat(ex.toString()).as("Unexpected last exception class").contains(clazz);
assertThat(ex.toString()).as("Unexpected last exception message").contains(exceptionMsg);
} else if (clazz != null) {
assertThat(exceptions.get(exceptions.size() - 1).getClass().getSimpleName()).as("Unexpected last exception class").isEqualTo(clazz);
}
commonspec.getExceptions().clear();
}
}
/**
* Check if expression defined by JSOPath (http://goessner.net/articles/JsonPath/index.html)
* match in JSON stored in a environment variable.
*
* @param envVar environment variable where JSON is stored
* @param table data table in which each row stores one expression
*/
@Then("^'(.+?)' matches the following cases:$")
public void matchWithExpresion(String envVar, DataTable table) throws Exception {
String jsonString = ThreadProperty.get(envVar);
for (List<String> row : table.cells()) {
String expression = row.get(0);
String condition = row.get(1);
String result = row.get(2);
String value = commonspec.getJSONPathString(jsonString, expression, null);
commonspec.evaluateJSONElementOperation(value, condition, result);
}
}
/*
* Check value stored in environment variable "is|matches|is higher than|is lower than|contains||does not contain|is different from" to value provided
*
* @param envVar
* @param value
*
*/
@Then("^'(.+)' (is|matches|is higher than|is higher than or equal to|is lower than|is lower than or equal to|contains|does not contain|is different from) '(.+)'$")
public void checkValue(String envVar, String operation, String value) throws Exception {
switch (operation.toLowerCase()) {
case "is":
Assertions.assertThat(envVar).as("Values are not equal.").isEqualTo(value);
break;
case "matches":
Assertions.assertThat(envVar).as("Values are different.").matches(value);
break;
case "is higher than":
if (envVar.matches("^-?\\d+$") && value.matches("^-?\\d+$")) {
Assertions.assertThat(Integer.parseInt(envVar)).as("First value is not higher than second one.").isGreaterThan(Integer.parseInt(value));
} else {
throw new Exception("A number should be provided in order to perform a valid comparison.");
}
break;
case "is higher than or equal to":
if (envVar.matches("^-?\\d+$") && value.matches("^-?\\d+$")) {
Assertions.assertThat(Integer.parseInt(envVar)).as("First value is not higher than or equal to second one.").isGreaterThanOrEqualTo(Integer.parseInt(value));
} else {
throw new Exception("A number should be provided in order to perform a valid comparison.");
}
break;
case "is lower than":
if (envVar.matches("^-?\\d+$") && value.matches("^-?\\d+$")) {
Assertions.assertThat(Integer.parseInt(envVar)).as("First value is not lower than second one.").isLessThan(Integer.parseInt(value));
} else {
throw new Exception("A number should be provided in order to perform a valid comparison.");
}
break;
case "is lower than or equal to":
if (envVar.matches("^-?\\d+$") && value.matches("^-?\\d+$")) {
Assertions.assertThat(Integer.parseInt(envVar)).as("First value is not lower than or equal to second one.").isLessThanOrEqualTo(Integer.parseInt(value));
} else {
throw new Exception("A number should be provided in order to perform a valid comparison.");
}
break;
case "contains":
Assertions.assertThat(envVar).as("Second value is not contained in first one.").contains(value);
break;
case "does not contain":
Assertions.assertThat(envVar).as("Second value is contained in first one.").doesNotContain(value);
break;
case "is different from":
Assertions.assertThat(envVar).as("Both values are equal.").isNotEqualTo(value);
break;
default:
throw new Exception("Not a valid comparison. Valid ones are: is | matches | is higher than | is higher than or equal to | is lower than | is lower than or equal to | contains | does not contain | is different from");
}
}
@Given("^I set tenant variables$")
public void setTenantVariables() throws Exception {
String ccTenant = System.getProperty("CC_TENANT", "NONE");
String dcosTenant = System.getProperty("DCOS_TENANT");
if (dcosTenant == null) {
throw new Exception("DCOS_TENANT is null");
}
String zkTenant = System.getProperty("ZK_TENANT") != null ? System.getProperty("ZK_TENANT") : System.getProperty("DCOS_TENANT");
String xdTenant = System.getProperty("XD_TENANT") != null ? System.getProperty("XD_TENANT") : System.getProperty("DCOS_TENANT");
String pgTenant = System.getProperty("PG_TENANT") != null ? System.getProperty("PG_TENANT") : System.getProperty("DCOS_TENANT");
String elasticTenant = System.getProperty("ELASTIC_TENANT") != null ? System.getProperty("ELASTIC_TENANT") : System.getProperty("DCOS_TENANT");
String kafkaTenant = System.getProperty("KAFKA_TENANT") != null ? System.getProperty("KAFKA_TENANT") : System.getProperty("DCOS_TENANT");
String sparkTenant = System.getProperty("SPARK_TENANT") != null ? System.getProperty("SPARK_TENANT") : System.getProperty("DCOS_TENANT");
String pgXLTenant = System.getProperty("PGD_TENANT") != null ? System.getProperty("PGD_TENANT") : System.getProperty("DCOS_TENANT");
String schemaRegistryTenant = System.getProperty("SCHEMA_REGISTRY_TENANT") != null ? System.getProperty("SCHEMA_REGISTRY_TENANT") : System.getProperty("DCOS_TENANT");
String restProxyTenant = System.getProperty("REST_PROXY_TENANT") != null ? System.getProperty("REST_PROXY_TENANT") : System.getProperty("DCOS_TENANT");
String govTenant = System.getProperty("GOV_TENANT") != null ? System.getProperty("GOV_TENANT") : System.getProperty("DCOS_TENANT");
String cassandraTenant = System.getProperty("CASSANDRA_TENANT") != null ? System.getProperty("CASSANDRA_TENANT") : System.getProperty("DCOS_TENANT");
String igniteTenant = System.getProperty("IGNITE_TENANT") != null ? System.getProperty("IGNITE_TENANT") : System.getProperty("DCOS_TENANT");
String etcdTenant = System.getProperty("ETCD_TENANT") != null ? System.getProperty("ETCD_TENANT") : System.getProperty("DCOS_TENANT");
String k8sTenant = System.getProperty("K8S_TENANT") != null ? System.getProperty("K8S_TENANT") : System.getProperty("DCOS_TENANT");
String arangoTenant = System.getProperty("ARANGO_TENANT") != null ? System.getProperty("ARANGO_TENANT") : System.getProperty("DCOS_TENANT");
String kibanaTenant = System.getProperty("KIBANA_TENANT") != null ? System.getProperty("KIBANA_TENANT") : System.getProperty("DCOS_TENANT");
String hdfsTenant = System.getProperty("HDFS_TENANT") != null ? System.getProperty("HDFS_TENANT") : System.getProperty("DCOS_TENANT");
String spartaTenant = System.getProperty("SPARTA_TENANT") != null ? System.getProperty("SPARTA_TENANT") : System.getProperty("DCOS_TENANT");
ThreadProperty.set("CC_TENANT", ccTenant);
ThreadProperty.set("XD_TENANT", xdTenant);
ThreadProperty.set("ZK_TENANT", zkTenant);
ThreadProperty.set("PG_TENANT", pgTenant);
ThreadProperty.set("ELASTIC_TENANT", elasticTenant);
ThreadProperty.set("KAFKA_TENANT", kafkaTenant);
ThreadProperty.set("SPARK_TENANT", sparkTenant);
ThreadProperty.set("PGD_TENANT", pgXLTenant);
ThreadProperty.set("SCHEMA_REGISTRY_TENANT", schemaRegistryTenant);
ThreadProperty.set("REST_PROXY_TENANT", restProxyTenant);
ThreadProperty.set("GOV_TENANT", govTenant);
ThreadProperty.set("CASSANDRA_TENANT", cassandraTenant);
ThreadProperty.set("IGNITE_TENANT", igniteTenant);
ThreadProperty.set("ETCD_TENANT", etcdTenant);
ThreadProperty.set("K8S_TENANT", k8sTenant);
ThreadProperty.set("ARANGO_TENANT", arangoTenant);
ThreadProperty.set("KIBANA_TENANT", kibanaTenant);
ThreadProperty.set("HDFS_TENANT", hdfsTenant);
ThreadProperty.set("SPARTA_TENANT", spartaTenant);
commonspec.getLogger().debug("Tenant variables: XD --> {}, ZK --> {}, CC --> {}, PG --> {}, ELASTIC --> {}, KAFKA --> {}, SPARK --> {}, PGD --> {}, SCHEMA REG --> {}, REST PROXY --> {}," +
"GOVERNANCE --> {}, CASSANDRA --> {}, IGNITE --> {}, ETCD --> {}, K8S --> {}, ARANGO --> {}, KIBANA --> {}, HDFS --> {}, SPARTA --> {}",
xdTenant, zkTenant, ccTenant, pgTenant, elasticTenant, kafkaTenant, sparkTenant, pgXLTenant, schemaRegistryTenant, restProxyTenant, govTenant, cassandraTenant, igniteTenant,
etcdTenant, k8sTenant, arangoTenant, kibanaTenant, hdfsTenant, spartaTenant);
}
@Given("^I set gosec API variables$")
public void setGosecVariables() throws Exception {
String gosecVersion = ThreadProperty.get("gosec-management_version");
if (gosecVersion == null) {
commonspec.getLogger().warn("gosec-management_version has not been defined");
} else {
String[] gosecVersionArray = gosecVersion.split("\\.");
if (gosecVersionArray.length != 3) {
commonspec.getLogger().warn("gosec-management_version must have X.X.X format");
} else {
if (Integer.parseInt(gosecVersionArray[0]) >= 1 && (Integer.parseInt(gosecVersionArray[1]) > 1 || (Integer.parseInt(gosecVersionArray[1]) == 1 && Integer.parseInt(gosecVersionArray[2]) >= 1))) { //Gosec version >= 1.1.1
ThreadProperty.set("API_USER", "/api/user?id=");
ThreadProperty.set("API_GROUP", "/api/group?id=");
ThreadProperty.set("API_POLICY", "/api/policy?id=");
ThreadProperty.set("API_TAG", "/api/policy/tag?id=");
ThreadProperty.set("API_USERS", "/api/users");
ThreadProperty.set("API_GROUPS", "/api/groups");
ThreadProperty.set("API_POLICIES", "/api/policies");
ThreadProperty.set("API_TAGS", "/api/policies/tags");
ThreadProperty.set("API_SERVICE", "/api/service");
} else {
ThreadProperty.set("API_USER", "/api/user/");
ThreadProperty.set("API_GROUP", "/api/group/");
ThreadProperty.set("API_POLICY", "/api/policy/");
ThreadProperty.set("API_TAG", "/api/policy/tag/");
ThreadProperty.set("API_USERS", "/api/user");
ThreadProperty.set("API_GROUPS", "/api/group");
ThreadProperty.set("API_POLICIES", "/api/policy");
ThreadProperty.set("API_TAGS", "/api/policy/tag");
ThreadProperty.set("API_SERVICE", "/api/service");
}
}
}
}
/**
* Convert provided date into timestamp
*
* @param date : provided date (2020-08-08, 2020-08-08 10:10:10, etc)
* @param format : provided format (yyyy-MM-dd, yyyy-MM-dd HH:mm:ss, etc) - Format should match with provided date/time
* @param timezone : Timezone GMT,GMT+1,GMT-1... (OPTIONAL) if not provided, UTC (GMT)
* @param envVar : environment variable where timestamp is saved
* @throws Exception
*/
@When("^I convert date '(.+?)' in format '(.+?)'( with timezone '(.+?)')? into timestamp and save the value in environment variable '(.+?)'$")
public void convertDateToTimestamp(String date, String format, String timezone, String envVar) throws Exception {
SimpleDateFormat isoFormat = new SimpleDateFormat(format);
if (timezone != null) {
isoFormat.setTimeZone(TimeZone.getTimeZone(timezone));
} else {
isoFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
}
try {
Date d = isoFormat.parse(date);
GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("Europe/Madrid"));
calendar.setTime(d);
ThreadProperty.set(envVar, Long.toString(calendar.getTimeInMillis()));
commonspec.getLogger().debug("Your date in timestamp: {} with timezone: {}", calendar.getTimeInMillis(), timezone);
} catch (AssertionError e) {
commonspec.getLogger().error("Error converting date {}, check date and format", date);
throw e;
}
}
/**
* Get current date and time and save into environment variable
*
* @param envVar : environment variable where date time is saved
*/
@Given("^I get current date and time and save the value in environment variable '(.+?)'$")
public void getCurrentDateTime(String envVar) {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date(); //now
dateFormat.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));
ThreadProperty.set(envVar, dateFormat.format(date));
commonspec.getLogger().debug("Current Date: {}", dateFormat.format(date));
}
/**
* Get current date and time plus provided minutes and save into environment variable
*
* @param envVar : environment variable where date time is saved
* @param addMinuteTime : added minutes
*/
@Given("^I get date and time with '(.+?)' more minutes from now and save the value in environment variable '(.+?)'$")
public void getOneMoreMinute(int addMinuteTime, String envVar) {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date targetTime = new Date(); //now
targetTime = DateUtils.addMinutes(targetTime, addMinuteTime); //add minute
dateFormat.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));
ThreadProperty.set(envVar, dateFormat.format(targetTime));
commonspec.getLogger().debug("Date adding {} minutes : {}", addMinuteTime, dateFormat.format(targetTime));
}
} |
Java | public class RNAIGeneScore extends LocusScoreBase implements LocusScore {
String batchCondition;
NamedFeature gene;
float geneScore;
int geneConfidence;
boolean hasGeneConfidence;
int numberOfHairpins;
int start;
int end;
/**
* Constructs ...
*
* @param batchId
* @param gene
* @param geneScore
* @param numberOfHairpins
*/
public RNAIGeneScore(String batchId, NamedFeature gene, float geneScore,
int numberOfHairpins) {
this.batchCondition = batchId;
this.gene = gene;
this.geneScore = geneScore;
geneConfidence = 3;
hasGeneConfidence = false;
this.numberOfHairpins = numberOfHairpins;
this.start = gene.getStart();
this.end = gene.getEnd();
}
/**
* Constructs ...
*
* @param batchId
* @param gene
* @param geneScore
* @param confidence
* @param numberOfHairpins
*/
public RNAIGeneScore(String batchId, NamedFeature gene, float geneScore, int confidence,
int numberOfHairpins) {
this.batchCondition = batchId;
this.gene = gene;
this.geneScore = geneScore;
this.geneConfidence = confidence;
hasGeneConfidence = true;
this.numberOfHairpins = numberOfHairpins;
this.start = gene.getStart();
this.end = gene.getEnd();
}
/**
* Copy constructor
*
* @param score
*/
public RNAIGeneScore(RNAIGeneScore score) {
this.batchCondition = score.batchCondition;
this.gene = score.gene;
this.geneScore = score.geneScore;
this.geneConfidence = score.geneConfidence;
this.numberOfHairpins = score.numberOfHairpins;
this.start = score.getStart();
this.end = score.getEnd();
}
/**
* Method description
*
* @return
*/
public RNAIGeneScore copy() {
return new RNAIGeneScore(this);
}
/**
* Checks if there is a confidence value for the gene score
*
* @return
*/
public boolean hasGeneConfidence() {
return hasGeneConfidence;
}
/**
* Method description
*
* @return
*/
public NamedFeature getGene() {
return gene;
}
public String getChr() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
/**
* Method description
*
* @return
*/
public int getStart() {
return start;
}
/**
* Method description
*
* @return
*/
public int getEnd() {
return end;
}
/**
* Method description
*
* @return
*/
public float getScore() {
return geneScore;
}
public float getConfidence() {
return geneConfidence;
}
public void setStart(int start) {
this.start = start;
}
public void setEnd(int end) {
this.end = end;
}
/**
* Return the list of hairpin scores associated with this gene. Scores are sorted alphabetically
* by haipin name
*
* @return
*/
List<RNAIHairpinValue> hairpinScores = null;
/**
* Method description
*
* @return
*/
public Collection<RNAIHairpinValue> getHairpinValues() {
if (hairpinScores == null) {
Collection<RNAIHairpinValue> tmp =
RNAIHairpinCache.getInstance().getHairpinScores(batchCondition, gene.getName().toUpperCase());
if (tmp != null) {
hairpinScores = new ArrayList(tmp);
}
}
return hairpinScores;
}
/**
* Method description
*
* @param ignored
* @return
*/
public String getValueString(double position, WindowFunction ignored) {
StringBuffer buf = new StringBuffer(100);
buf.append("<b>Gene: " + gene.getName() + "</b><br>");
buf.append("<b>Intensity: " + geneScore + "<br></b>");
if (hasGeneConfidence)
buf.append("Confidence: " + geneConfidence + "<br>");
Collection<RNAIHairpinValue> hpins = getHairpinValues();
if ((hpins == null) || hpins.isEmpty()) {
buf.append("# Hairpins: " + numberOfHairpins + "<br>");
} else {
buf.append("Hairpin scores:<br>");
for (RNAIHairpinValue hpScore : hpins) {
if (hpScore.hasScoreSTD()) {
buf.append(hpScore.getName() + ": " + hpScore.getScoreMean() + " ("
+ hpScore.getScoreSTD() + ")<br>");
} else {
buf.append(hpScore.getName() + ": " + hpScore.getScoreMean() + "<br>");
}
}
}
return buf.toString();
}
} |
Java | public static class Spec {
/** Output pin mode. */
public enum Mode {
/**
* Pin operates in push-pull mode, i.e. a logical "HIGH" is
* represented by a voltage of Vdd on the pin and a logical "LOW" by
* a voltage of 0 (ground).
*/
NORMAL,
/**
* Pin operates in open-drain mode, i.e. a logical "HIGH" is
* represented by a high impedance on the pin (as if it is
* disconnected) and a logical "LOW" by a voltage of 0 (ground).
* This mode is most commonly used for generating 5V logical signal
* on a 3.3V pin: 5V tolerant pins must be used; a pull-up resistor
* is connected between the pin and 5V, and the pin is used in open-
* drain mode.
*/
OPEN_DRAIN,
}
/** The pin number, as labeled on the board. */
public int pin;
/** The pin mode. */
public Mode mode;
/**
* Constructor.
*
* @param pin
* Pin number, as labeled on the board.
* @param mode
* Pin mode.
*/
public Spec(int pin, Mode mode) {
this.pin = pin;
this.mode = mode;
}
/**
* Shorthand for Spec(pin, Mode.NORMAL).
*
* @see DigitalOutput.Spec#Spec(int, DigitalOutput.Spec.Mode)
*/
public Spec(int pin) {
this(pin, Mode.NORMAL);
}
} |
Java | public class ClinitTest {
static {
//允许向前赋值 但不允许引用
i = 0;
// System.out.println(i);
}
static int i = 1;
static class Parent {
public static int A = 1;
// 类加载的初始化阶段 父类的static 也就是父类的clinit先于子类执行 所以 B = 2
static {
A = 2;
}
}
static class Sub extends Parent{
public static int B = A;
}
public static void main(String[] args) {
System.out.println(Sub.B);
}
} |
Java | public class VerboseTimeline
{
private double startTime;
private double lastTime;
private long minute;
private StringBuilder timeline;
/**
*
*
* @param filename
*/
public VerboseTimeline(String filename)
{
timeline = new StringBuilder();
minute = 0;
XMLHierarchy hierarchy = new XMLHierarchy("verbosegc");
hierarchy.makePermissive("verbosegc");
final XMLParser parser = new XMLParser(hierarchy, Event.PARSE_ERROR);
parser.setElementHandler("initialized", new VoidElementHandler()
{
public void elementEnd(Element element) throws HierarchyException, ParseError
{
startTime = VerboseUtil.parseTimestamp(element.getAttribute("timestamp"), 0);
}
});
parser.setElementHandler("gc-start", new VoidElementHandler()
{
public void elementEnd(Element element) throws HierarchyException, ParseError
{
processTimestamp(element.getAttribute("timestamp"));
if (element.getAttribute("type").equals("global"))
timeline.append(VerboseEvent.GLOBAL);
else if (element.getAttribute("type").equals("scavenge"))
timeline.append(VerboseEvent.SCAVENGE);
else
timeline.append(VerboseEvent.UNKNOWN);
}
});
parser.setElementHandler("concurrent-aborted", new VoidElementHandler()
{
public void elementEnd(Element element) throws HierarchyException, ParseError
{
timeline.append(VerboseEvent.CONCURRENT_ABORTED);
}
});
parser.setElementHandler("percolate-collect", new VoidElementHandler()
{
public void elementEnd(Element element) throws HierarchyException, ParseError
{
processTimestamp(element.getAttribute("timestamp"));
timeline.append(VerboseEvent.PERCOLATE_COLLECT);
}
});
parser.setElementHandler("warning", new VoidElementHandler()
{
public void elementEnd(Element element) throws HierarchyException, ParseError
{
timeline.append(VerboseUtil.getWarningEventType(element.getAttribute("details")));
}
});
parser.setElementHandler("copy-failed", new VoidElementHandler()
{
public void elementEnd(Element element) throws HierarchyException, ParseError
{
timeline.append(VerboseUtil.getCopyFailedEventType(element.getAttribute("type")));
}
});
parser.setElementHandler("gc-op", new VoidElementHandler()
{
public void elementEnd(Element element) throws HierarchyException, ParseError
{
processTimestamp(element.getAttribute("timestamp"));
}
});
parser.parse(filename);
}
/**
* Processes the timestamp, updating lastTime and appending a
* minute marker each time the minute changes.
*
* @param timestamp
*/
private void processTimestamp(String timestamp)
{
lastTime = VerboseUtil.parseTimestamp(timestamp, startTime);
long minutes = Math.round(Math.floor(lastTime / 60));
if (minutes > minute) {
minute = minutes;
timeline.append("|");
}
}
/**
* Gets a string representation of the events in the verbose file.
*
* @return
*/
public String toString()
{
return timeline.toString();
}
} |
Java | public class ModCompat
{
private final String modId;
private final String modName;
private final CompatBase compatClass;
private final boolean loaded;
/**
* Because sometimes it's useful to keep your Vanilla integration all in one place
*/
public ModCompat(CompatBase compatClass)
{
this("minecraft", "Minecraft", compatClass, true);
}
public ModCompat(String modId, CompatBase compatClass)
{
this(modId, modId, compatClass);
}
public ModCompat(String modId)
{
this(modId, modId, null, Loader.isModLoaded(modId));
}
public ModCompat(String modId, String modName)
{
this(modId, modName, null, Loader.isModLoaded(modId));
}
public ModCompat(String modId, String modName, CompatBase compatClass)
{
this(modId, modName, compatClass, Loader.isModLoaded(modId));
}
private ModCompat(String modId, String modName, CompatBase compatClass, boolean loaded)
{
this.modId = modId;
this.modName = modName;
this.compatClass = compatClass;
this.loaded = loaded;
}
public String getModId()
{
return modId;
}
public String getModName()
{
return modName;
}
public boolean isLoaded()
{
return loaded;
}
private void load()
{
compatClass.load(this);
}
} |
Java | public class OI {
//// CREATING BUTTONS
// One type of button is a joystick button which is any button on a joystick.
// You create one by telling it which joystick it's on and which button
// number it is.
// Joystick stick = new Joystick(port);
// Button button = new JoystickButton(stick, buttonNumber);
// There are a few additional built in buttons you can use. Additionally,
// by subclassing Button you can create custom triggers and bind those to
// commands the same as any other Button.
//// TRIGGERING COMMANDS WITH BUTTONS
// Once you have a button, it's trivial to bind it to a button in one of
// three ways:
// Start the command when the button is pressed and let it run the command
// until it is finished as determined by it's isFinished method.
// button.whenPressed(new ExampleCommand());
// Run the command while the button is being held down and interrupt it once
// the button is released.
// button.whileHeld(new ExampleCommand());
// Start the command when the button is released and let it run the command
// until it is finished as determined by it's isFinished method.
// button.whenReleased(new ExampleCommand());
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
public JoystickButton joystickButtonA; // Controller A
public JoystickButton joystickButtonB; // Controller B
public JoystickButton joystickButtonX; // Controller X
public JoystickButton joystickButtonY; // Controller Y
public JoystickButton joystickButton7;
public JoystickButton joystickButton8;
public JoystickButton joystickButton12;
public JoystickButton joystickButton5;// left bumper
public JoystickButton joystickButton6;// right bumper
private HIDPOVButton joyStickHatFore; // Hat Button Forward
private HIDPOVButton joyStickHatForeRight; // Hat Button Forward Right
private HIDPOVButton joyStickHatRight; // Hat Button Right
private HIDPOVButton joyStickHatAftRight; // Hat Button Aft Right
private HIDPOVButton joyStickHatAft; // Hat Button Aft
private HIDPOVButton joyStickHatAftLeft; // Hat Button Aft Left
private HIDPOVButton joyStickHatLeft; // Hat Button Left
private HIDPOVButton joyStickHatForeLeft; // Hat Button Forward Left
public JoystickButton joystickButtonRightStickPress; // Press Right Stick
private HIDPOVButton operatorStickHatFore; // Hat Button Forward
private HIDPOVButton operatorStickHatForeRight; // Hat Button Forward Right
private HIDPOVButton operatorStickHatRight; // Hat Button Right
private HIDPOVButton operatorStickHatAftRight; // Hat Button Aft Right
private HIDPOVButton operatorStickHatAft; // Hat Button Aft
private HIDPOVButton operatorStickHatAftLeft; // Hat Button Aft Left
private HIDPOVButton operatorStickHatLeft; // Hat Button Left
private HIDPOVButton operatorStickHatForeLeft; // Hat Button Forward Left
public XboxController driver;
public Joystick operatorJoystick = new Joystick(1);// instantiates thye operator joystick
public Button trigger ;
public Button operatorButton2;
public Button operatorButton8;
public Button operatorButton10;
public Button operatorButton12;
public Button operatorButton5;
public Button operatorButton3;
public Button operatorButton4;
public Button operatorButton6;
// for gate
public Button operatorButton7;
public Button operatorButton9;
public Button operatorButton11;
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
public OI() {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS
driver = new XboxController(0);
joystickButtonA = new JoystickButton(driver, 1);
// joystickButtonA.whileHeld(new AlignForShot(Vision.BoilerRange.FAR));
joystickButtonA.whileHeld(new ShootCommand(ShootCommand.ShotRangeCommand.AUTO));
//joystickButtonB = new JoystickButton(driver, 2);
//joystickButtonB.whenPressed(new SetCameraTarget());
joystickButtonX = new JoystickButton(driver, 3);
joystickButtonX.whenPressed(new ToggleCollection(State.ACTIVE));
// joystickButtonX.whenPressed(new ToggleCollection(State.INACTIVE));
joystickButtonY = new JoystickButton(driver, 4);
joystickButtonY.whileHeld(new AlignForShot(AlignForShot.ShotRangeCommand.FAR));
joystickButton5 = new JoystickButton(driver, 5);
joystickButton5.whileHeld(new AutoMoveToGear());
joystickButton6 = new JoystickButton(driver, 6);
joystickButton6.whenPressed(new GearStateCommand());
//joystickButton7 = new JoystickButton(driver, 7);
//joystickButton7.whenPressed(new OperatorGear(Gear.GearCommand.CLOSE));
//joystickButton8 = new JoystickButton(driver, 8);
//joystickButton8.whenPressed(new OperatorGear(Gear.GearCommand.CLOSE));
//joystickButtonRightStickPress = new JoystickButton(driver, 10);
//joystickButtonRightStickPress.whenPressed(new AlignToField());
joyStickHatFore = new HIDPOVButton(driver, 0);
joyStickHatFore.whenPressed(new StoreImages());
joyStickHatAft = new HIDPOVButton(driver, 180);
joyStickHatAft.whenPressed(new SetCamera());
// operatorButton2 = new JoystickButton(operatorJoystick, 2);
// operatorButton2.whileHeld(new ClimbCommand(ClimbCommand.ClimbCommandSpeed.SLOW));
// operatorButton8 = new JoystickButton(operatorJoystick, 8);
// operatorButton8.whenPressed(new ShootCommand(ShootCommand.ShotRangeCommand.FAR));
// operatorButton10 = new JoystickButton(operatorJoystick, 10);
// operatorButton10.whenPressed(new ShootCommand(ShootCommand.ShotRangeCommand.NEAR));
// operatorButton12 = new JoystickButton(operatorJoystick, 12);
// operatorButton12.whenPressed(new ShootCommand(ShootCommand.ShootCommand.STOP));
operatorButton2 = new JoystickButton(operatorJoystick, 2);
operatorButton2.whenPressed(new ToggleCollection(State.ACTIVE));
//operatorButton2.whenPressed(new ToggleCollection(State.INACTIVE));
//operatorButton10 = new JoystickButton(operatorJoystick, 10);
//operatorButton10.whenPressed(new ShootCommand(Shoot.ShootCommand.NEAR));
//operatorButton12 = new JoystickButton(operatorJoystick, 12);
//operatorButton12.whenPressed(new ShootCommand(Shoot.ShootCommand.IDLE));
trigger = new JoystickButton(operatorJoystick, 1);
trigger.whileHeld(new ShootCommand(ShootCommand.ShotRangeCommand.AUTO));
operatorButton3 = new JoystickButton(operatorJoystick, 3);
operatorButton3.whenPressed(new SetCameraTarget(VisionMode.FIND_BOILER, BoilerRange.NEAR));
operatorButton4 = new JoystickButton(operatorJoystick, 4);
operatorButton4.whenPressed(new SetCameraTarget(VisionMode.FIND_BOILER, BoilerRange.FAR));
operatorButton5 = new JoystickButton(operatorJoystick, 5);
operatorButton5.whenPressed(new StoreImages());
operatorButton6 = new JoystickButton(operatorJoystick, 6);
operatorButton6.whenPressed(new SetCameraTarget(VisionMode.FIND_GEAR));
operatorButton7 = new JoystickButton(operatorJoystick, 7);
operatorButton7.whenPressed(new ClimbCommand( ClimbCommandSpeed.SLOW));
operatorButton8 = new JoystickButton(operatorJoystick, 8);
operatorButton8.whenPressed(new ClimbCommand( ClimbCommandSpeed.FAST));
operatorButton9 = new JoystickButton(operatorJoystick, 9);
operatorButton9.whenPressed(new ClimbCommand( ClimbCommandSpeed.IDLE));
operatorButton11 = new JoystickButton(operatorJoystick, 11);
operatorButton11.whenPressed(new StoreImages());
// using lefts and rights for mitigating operator eror during compotitions
operatorStickHatFore = new HIDPOVButton(operatorJoystick,0 );
operatorStickHatFore.whileHeld(new ClimbCommand( ClimbCommandSpeed.FAST));
operatorStickHatForeRight = new HIDPOVButton(operatorJoystick, 45);
operatorStickHatForeRight.whileHeld(new ClimbCommand( ClimbCommandSpeed.FAST));
operatorStickHatForeLeft = new HIDPOVButton(operatorJoystick, 315);
operatorStickHatForeLeft.whileHeld(new ClimbCommand( ClimbCommandSpeed.FAST));
// operatorStickHatRight = new HIDPOVButton(operatorJoystick, 90);
// operatorStickHatRight.whenPressed(new DebugPrintInfo("Rumble On", DebugSelection.RUMBLE_ON));
// operatorStickHatRight = new HIDPOVButton(operatorJoystick, 270);
// operatorStickHatRight.whenPressed(new DebugPrintInfo("Rumble Off", DebugSelection.RUMBLE_OFF));
operatorStickHatAftRight = new HIDPOVButton(operatorJoystick, 135);
operatorStickHatAftRight.whileHeld(new ClimbCommand( ClimbCommandSpeed.SLOW));
operatorStickHatAft = new HIDPOVButton(operatorJoystick, 180);
operatorStickHatAft.whileHeld(new ClimbCommand( ClimbCommandSpeed.SLOW));
operatorStickHatAftLeft = new HIDPOVButton(operatorJoystick, 225);
operatorStickHatAftLeft.whileHeld(new ClimbCommand( ClimbCommandSpeed.SLOW));
// operatorStickHatLeft = new JoystickPOVButton(operatorJoystick, 270);
// operatorStickHatLeft.whenPressed(new ClimbCommand("O Hat Left"));
// joyStickHatFore = new HIDPOVButton(driver, 0);
// joyStickHatForeRight = new HIDPOVButton(driver, 45);
// joyStickHatRight = new HIDPOVButton(driver, 90);
// joyStickHatAftRight = new HIDPOVButton(driver, 135);
// joyStickHatAft = new HIDPOVButton(driver, 180);
// joyStickHatAftLeft = new HIDPOVButton(driver, 225);
// joyStickHatLeft = new HIDPOVButton(driver, 270);
// joyStickHatForeLeft = new HIDPOVButton(driver, 315);
//
// joyStickHatFore.whenPressed(new DebugPrintInfo("joyStickHatFore", DebugSelection.NOPRINT)); // Hat Button Forward
// joyStickHatForeRight.whenPressed(new DebugPrintInfo("joyStickHatForeRight", DebugSelection.NOPRINT)); // Hat Button Forward Right
// joyStickHatRight.whenPressed(new DebugPrintInfo("joyStickHatRight", DebugSelection.NOPRINT)); // Hat Button Right
// joyStickHatAftRight.whenPressed(new DebugPrintInfo("joyStickHatAftRight", DebugSelection.NOPRINT)); // Hat Button Aft Right
// joyStickHatAft.whenPressed(new DebugPrintInfo("joyStickHatAft", DebugSelection.NOPRINT)); // Hat Button Aft
// joyStickHatAftLeft.whenPressed(new DebugPrintInfo("joyStickHatAftLeft", DebugSelection.NOPRINT)); // Hat Button Aft Left
// joyStickHatLeft.whenPressed(new DebugPrintInfo("joyStickHatLeft", DebugSelection.NOPRINT)); // Hat Button Left
// joyStickHatForeLeft.whenPressed(new DebugPrintInfo("joyStickHatForeLeft", DebugSelection.NOPRINT)); // Hat Button Forward Left
//
// operatorStickHatFore = new HIDPOVButton(operatorJoystick, 0);
// operatorStickHatForeRight = new HIDPOVButton(operatorJoystick, 45);
// operatorStickHatRight = new HIDPOVButton(operatorJoystick, 90);
// operatorStickHatAftRight = new HIDPOVButton(operatorJoystick, 135);
// operatorStickHatAft = new HIDPOVButton(operatorJoystick, 180);
// operatorStickHatAftLeft = new HIDPOVButton(operatorJoystick, 225);
// operatorStickHatLeft = new HIDPOVButton(operatorJoystick, 270);
// operatorStickHatForeLeft = new HIDPOVButton(operatorJoystick, 315);
//
// operatorStickHatFore.whenPressed(new DebugPrintInfo("operatorStickHatFore", DebugSelection.NOPRINT)); // Hat Button Forward
// operatorStickHatForeRight.whenPressed(new DebugPrintInfo("operatorStickHatForeRight", DebugSelection.NOPRINT)); // Hat Button Forward Right
// operatorStickHatRight.whenPressed(new DebugPrintInfo("operatorStickHatRight", DebugSelection.NOPRINT)); // Hat Button Right
// operatorStickHatAftRight.whenPressed(new DebugPrintInfo("operatorStickHatAftRight", DebugSelection.NOPRINT)); // Hat Button Aft Right
// operatorStickHatAft.whenPressed(new DebugPrintInfo("operatorStickHatAft", DebugSelection.NOPRINT)); // Hat Button Aft
// operatorStickHatAftLeft.whenPressed(new DebugPrintInfo("operatorStickHatAftLeft", DebugSelection.NOPRINT)); // Hat Button Aft Left
// operatorStickHatLeft.whenPressed(new DebugPrintInfo("operatorStickHatLeft", DebugSelection.NOPRINT)); // Hat Button Left
// operatorStickHatForeLeft.whenPressed(new DebugPrintInfo("operatorStickHatForeLeft", DebugSelection.NOPRINT)); // Hat Button Forward Left
// SmartDashboard Buttons
SmartDashboard.putData("AlignToField", new AlignToField());
SmartDashboard.putData("Store Camera Images", new StoreImages());
// SmartDashboard.putData("Autonomous Command", new AutonomousCommand());
SmartDashboard.putData("DebugButton", new DebugPrintInfo("ScreenButton", DebugSelection.NOPRINT));
SmartDashboard.putData("Align for Near Shot", new AlignForShot(AlignForShot.ShotRangeCommand.NEAR));
SmartDashboard.putData("Align for Far Shot", new AlignForShot(AlignForShot.ShotRangeCommand.FAR));
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS
}
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=FUNCTIONS
public XboxController getDriver() {
return driver;
}
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=FUNCTIONS
} |
Java | public class Mesh {
private final int vaoID;
private final List<Integer> vboIDList; // list to store VBO IDs
private final int vertexCount;
public Mesh(float[] positions, int[] indices, float[] colours) {
// Create buffer in off-heap memory so that it's accessible by OpenGL library
FloatBuffer positionBuffer = null;
IntBuffer indicesBuffer = null;
FloatBuffer colourBuffer = null;
try {
vboIDList = new ArrayList<>();
vertexCount = indices.length;
// Create VAO and bind it
vaoID = glGenVertexArrays();
glBindVertexArray(vaoID);
// Create Position VBO, bind it and put positions into it
int posVboID = glGenBuffers();
vboIDList.add(posVboID);
positionBuffer = MemoryUtil.memAllocFloat(positions.length);
// Reset position of the buffer to the 0 position with flip()
positionBuffer.put(positions).flip();
glBindBuffer(GL_ARRAY_BUFFER, posVboID);
glBufferData(GL_ARRAY_BUFFER, positionBuffer, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0); //coordinates in location 0
// Create Index VBO and put indices in it
int indexVboID = glGenBuffers();
vboIDList.add(indexVboID);
indicesBuffer = MemoryUtil.memAllocInt(indices.length);
indicesBuffer.put(indices).flip();
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexVboID);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indicesBuffer, GL_STATIC_DRAW);
// Define structure of our data and store it in an attribute list in VAO
/*
* index: location where shader expects this data
* size: number of components per vertex attribute
* type: type of each component
* normalised: if value should be normalised
* stride: byte offset between consecutive generic vertex attributes
* pointer: offset to the first component in the buffer
*/
glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0); //coordinates in location 0
// Create Colour VBO and put colours in it
int colourVboID = glGenBuffers();
vboIDList.add(colourVboID);
colourBuffer = MemoryUtil.memAllocFloat(colours.length);
colourBuffer.put(colours).flip();
glBindBuffer(GL_ARRAY_BUFFER, colourVboID);
glBufferData(GL_ARRAY_BUFFER, colourBuffer, GL_STATIC_DRAW);
glVertexAttribPointer(1, 3, GL_FLOAT, false, 0, 0); //colour in location 1
// Unbind VBO
glBindBuffer(GL_ARRAY_BUFFER, 0);
// Unbind VAO
glBindVertexArray(0);
} finally {
// Free off-heap memory allocated by FloatBuffer & IntBuffer
if (positionBuffer != null) {
memFree(positionBuffer);
}
if (indicesBuffer != null) {
memFree(indicesBuffer);
}
if (colourBuffer != null) {
memFree(colourBuffer);
}
}
}
public int getVaoID() {
return vaoID;
}
public int getVertexCount() {
return vertexCount;
}
public void render() {
// Draw the mesh
// Bind to the VAO
glBindVertexArray(getVaoID());
glEnableVertexAttribArray(0); //enable attr1: coordinates
glEnableVertexAttribArray(1); //enable attr2: colour
// Draw vertices
// glDrawArrays(GL_TRIANGLES, 0, mesh.getVertexCount());
/*
* mode: primitive for rendering
* count: number of elements to be rendered
* type: type of value in indices data
* indices: offset to apply to indices data to start rendering
*/
glDrawElements(GL_TRIANGLES, getVertexCount(), GL_UNSIGNED_INT, 0);
// Restore state
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glBindVertexArray(0);
}
public void cleanup() {
glDisableVertexAttribArray(0);
// Delete VBO & VAO
glBindBuffer(GL_ARRAY_BUFFER, 0);
for (int vboID : vboIDList) {
glDeleteBuffers(vboID);
}
glBindVertexArray(0);
glDeleteBuffers(vaoID);
}
} |
Java | public class ClassLogicalTypeConverter {
@Deprecated
public static Class getDefaultExternalClassForType(LogicalType type) {
return TypeConversions.fromLogicalToDataType(type).getConversionClass();
}
/**
* Get internal(sql engine execution data formats) class for {@link LogicalType}.
*/
public static Class getInternalClassForType(LogicalType type) {
switch (type.getTypeRoot()) {
case BOOLEAN:
return Boolean.class;
case TINYINT:
return Byte.class;
case SMALLINT:
return Short.class;
case INTEGER:
case DATE:
case TIME_WITHOUT_TIME_ZONE:
case INTERVAL_YEAR_MONTH:
return Integer.class;
case BIGINT:
case TIMESTAMP_WITHOUT_TIME_ZONE:
case INTERVAL_DAY_TIME:
return Long.class;
case FLOAT:
return Float.class;
case DOUBLE:
return Double.class;
case CHAR:
case VARCHAR:
return BinaryString.class;
case DECIMAL:
return Decimal.class;
case ARRAY:
return BaseArray.class;
case MAP:
case MULTISET:
return BaseMap.class;
case ROW:
return BaseRow.class;
case BINARY:
case VARBINARY:
return byte[].class;
case ANY:
return BinaryGeneric.class;
default:
throw new RuntimeException("Not support type: " + type);
}
}
} |
Java | @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "taskType", defaultImpl = ProjectTaskProperties.class)
@JsonTypeName("Unknown")
@JsonSubTypes({
@JsonSubTypes.Type(name = "Migrate.SqlServer.AzureDbSqlMi.Complete", value = MigrateMISyncCompleteCommandProperties.class),
@JsonSubTypes.Type(name = "Migrate.Sync.Complete.Database", value = MigrateSyncCompleteCommandProperties.class),
@JsonSubTypes.Type(name = "MiSqlConnectionInfo", value = MiSqlConnectionInfo.class),
@JsonSubTypes.Type(name = "PostgreSqlConnectionInfo", value = PostgreSqlConnectionInfo.class),
@JsonSubTypes.Type(name = "OracleConnectionInfo", value = OracleConnectionInfo.class),
@JsonSubTypes.Type(name = "MySqlConnectionInfo", value = MySqlConnectionInfo.class),
@JsonSubTypes.Type(name = "MongoDbConnectionInfo", value = MongoDbConnectionInfo.class),
@JsonSubTypes.Type(name = "SqlConnectionInfo", value = SqlConnectionInfo.class),
@JsonSubTypes.Type(name = "Migrate.Ssis", value = MigrateSsisTaskProperties.class),
@JsonSubTypes.Type(name = "GetTDECertificates.Sql", value = GetTdeCertificatesSqlTaskProperties.class),
@JsonSubTypes.Type(name = "Validate.Oracle.AzureDbPostgreSql.Sync", value = ValidateOracleAzureDbForPostgreSqlSyncTaskProperties.class),
@JsonSubTypes.Type(name = "Validate.MongoDb", value = ValidateMongoDbTaskProperties.class),
@JsonSubTypes.Type(name = "ValidateMigrationInput.SqlServer.AzureSqlDbMI.Sync.LRS", value = ValidateMigrationInputSqlServerSqlMISyncTaskProperties.class),
@JsonSubTypes.Type(name = "ValidateMigrationInput.SqlServer.AzureSqlDbMI", value = ValidateMigrationInputSqlServerSqlMITaskProperties.class),
@JsonSubTypes.Type(name = "ValidateMigrationInput.SqlServer.SqlDb.Sync", value = ValidateMigrationInputSqlServerSqlDbSyncTaskProperties.class),
@JsonSubTypes.Type(name = "Migrate.Oracle.AzureDbForPostgreSql.Sync", value = MigrateOracleAzureDbForPostgreSqlSyncTaskProperties.class),
@JsonSubTypes.Type(name = "Migrate.PostgreSql.AzureDbForPostgreSql.Sync", value = MigratePostgreSqlAzureDbForPostgreSqlSyncTaskProperties.class),
@JsonSubTypes.Type(name = "Migrate.MySql.AzureDbForMySql.Sync", value = MigrateMySqlAzureDbForMySqlSyncTaskProperties.class),
@JsonSubTypes.Type(name = "Migrate.SqlServer.AzureSqlDb.Sync", value = MigrateSqlServerSqlDbSyncTaskProperties.class),
@JsonSubTypes.Type(name = "Migrate.SqlServer.SqlDb", value = MigrateSqlServerSqlDbTaskProperties.class),
@JsonSubTypes.Type(name = "Migrate.SqlServer.AzureSqlDbMI.Sync.LRS", value = MigrateSqlServerSqlMISyncTaskProperties.class),
@JsonSubTypes.Type(name = "Migrate.SqlServer.AzureSqlDbMI", value = MigrateSqlServerSqlMITaskProperties.class),
@JsonSubTypes.Type(name = "Migrate.MongoDb", value = MigrateMongoDbTaskProperties.class),
@JsonSubTypes.Type(name = "ConnectToTarget.AzureDbForMySql", value = ConnectToTargetAzureDbForMySqlTaskProperties.class),
@JsonSubTypes.Type(name = "ConnectToTarget.AzureSqlDbMI.Sync.LRS", value = ConnectToTargetSqlMISyncTaskProperties.class),
@JsonSubTypes.Type(name = "ConnectToTarget.AzureSqlDbMI", value = ConnectToTargetSqlMITaskProperties.class),
@JsonSubTypes.Type(name = "GetUserTablesPostgreSql", value = GetUserTablesPostgreSqlTaskProperties.class),
@JsonSubTypes.Type(name = "GetUserTablesOracle", value = GetUserTablesOracleTaskProperties.class),
@JsonSubTypes.Type(name = "GetUserTables.AzureSqlDb.Sync", value = GetUserTablesSqlSyncTaskProperties.class),
@JsonSubTypes.Type(name = "GetUserTables.Sql", value = GetUserTablesSqlTaskProperties.class),
@JsonSubTypes.Type(name = "ConnectToTarget.Oracle.AzureDbForPostgreSql.Sync", value = ConnectToTargetOracleAzureDbForPostgreSqlSyncTaskProperties.class),
@JsonSubTypes.Type(name = "ConnectToTarget.AzureDbForPostgreSql.Sync", value = ConnectToTargetAzureDbForPostgreSqlSyncTaskProperties.class),
@JsonSubTypes.Type(name = "ConnectToTarget.SqlDb.Sync", value = ConnectToTargetSqlSqlDbSyncTaskProperties.class),
@JsonSubTypes.Type(name = "ConnectToTarget.SqlDb", value = ConnectToTargetSqlDbTaskProperties.class),
@JsonSubTypes.Type(name = "ConnectToSource.Oracle.Sync", value = ConnectToSourceOracleSyncTaskProperties.class),
@JsonSubTypes.Type(name = "ConnectToSource.PostgreSql.Sync", value = ConnectToSourcePostgreSqlSyncTaskProperties.class),
@JsonSubTypes.Type(name = "ConnectToSource.SqlServer.Sync", value = ConnectToSourceSqlServerSyncTaskProperties.class),
@JsonSubTypes.Type(name = "ConnectToSource.SqlServer", value = ConnectToSourceSqlServerTaskProperties.class),
@JsonSubTypes.Type(name = "Connect.MongoDb", value = ConnectToMongoDbTaskProperties.class),
@JsonSubTypes.Type(name = "ConnectToSource.MySql", value = ConnectToSourceMySqlTaskProperties.class),
@JsonSubTypes.Type(name = "MigrateSchemaSqlServerSqlDb", value = MigrateSchemaSqlServerSqlDbTaskProperties.class),
@JsonSubTypes.Type(name = "cancel", value = MongoDbCancelCommand.class),
@JsonSubTypes.Type(name = "finish", value = MongoDbFinishCommand.class),
@JsonSubTypes.Type(name = "restart", value = MongoDbRestartCommand.class),
@JsonSubTypes.Type(name = "Service.Check.OCI", value = CheckOCIDriverTaskProperties.class),
@JsonSubTypes.Type(name = "Service.Upload.OCI", value = UploadOCIDriverTaskProperties.class),
@JsonSubTypes.Type(name = "Service.Install.OCI", value = InstallOCIDriverTaskProperties.class)
})
public class ProjectTaskProperties {
/**
* Array of errors. This is ignored if submitted.
*/
@JsonProperty(value = "errors", access = JsonProperty.Access.WRITE_ONLY)
private List<ODataError> errors;
/**
* The state of the task. This is ignored if submitted. Possible values
* include: 'Unknown', 'Queued', 'Running', 'Canceled', 'Succeeded',
* 'Failed', 'FailedInputValidation', 'Faulted'.
*/
@JsonProperty(value = "state", access = JsonProperty.Access.WRITE_ONLY)
private TaskState state;
/**
* Array of command properties.
*/
@JsonProperty(value = "commands", access = JsonProperty.Access.WRITE_ONLY)
private List<CommandPropertiesInner> commands;
/**
* Key value pairs of client data to attach meta data information to task.
*/
@JsonProperty(value = "clientData")
private Map<String, String> clientData;
/**
* Get array of errors. This is ignored if submitted.
*
* @return the errors value
*/
public List<ODataError> errors() {
return this.errors;
}
/**
* Get the state of the task. This is ignored if submitted. Possible values include: 'Unknown', 'Queued', 'Running', 'Canceled', 'Succeeded', 'Failed', 'FailedInputValidation', 'Faulted'.
*
* @return the state value
*/
public TaskState state() {
return this.state;
}
/**
* Get array of command properties.
*
* @return the commands value
*/
public List<CommandPropertiesInner> commands() {
return this.commands;
}
/**
* Get key value pairs of client data to attach meta data information to task.
*
* @return the clientData value
*/
public Map<String, String> clientData() {
return this.clientData;
}
/**
* Set key value pairs of client data to attach meta data information to task.
*
* @param clientData the clientData value to set
* @return the ProjectTaskProperties object itself.
*/
public ProjectTaskProperties withClientData(Map<String, String> clientData) {
this.clientData = clientData;
return this;
}
} |
Java | public class CountrySoap implements Serializable {
public static CountrySoap toSoapModel(Country model) {
CountrySoap soapModel = new CountrySoap();
soapModel.setCountryId(model.getCountryId());
soapModel.setCountryName(model.getCountryName());
return soapModel;
}
public static CountrySoap[] toSoapModels(Country[] models) {
CountrySoap[] soapModels = new CountrySoap[models.length];
for (int i = 0; i < models.length; i++) {
soapModels[i] = toSoapModel(models[i]);
}
return soapModels;
}
public static CountrySoap[][] toSoapModels(Country[][] models) {
CountrySoap[][] soapModels = null;
if (models.length > 0) {
soapModels = new CountrySoap[models.length][models[0].length];
}
else {
soapModels = new CountrySoap[0][0];
}
for (int i = 0; i < models.length; i++) {
soapModels[i] = toSoapModels(models[i]);
}
return soapModels;
}
public static CountrySoap[] toSoapModels(List<Country> models) {
List<CountrySoap> soapModels = new ArrayList<CountrySoap>(
models.size());
for (Country model : models) {
soapModels.add(toSoapModel(model));
}
return soapModels.toArray(new CountrySoap[soapModels.size()]);
}
public CountrySoap() {
}
public long getPrimaryKey() {
return _countryId;
}
public void setPrimaryKey(long pk) {
setCountryId(pk);
}
public long getCountryId() {
return _countryId;
}
public void setCountryId(long countryId) {
_countryId = countryId;
}
public String getCountryName() {
return _countryName;
}
public void setCountryName(String countryName) {
_countryName = countryName;
}
private long _countryId;
private String _countryName;
} |
Java | public class DruidDimensionValueLoader implements DimensionValueLoader {
private static final SystemConfig SYSTEM_CONFIG = SystemConfigProvider.getInstance();
public static final String DRUID_DIM_LOADER_DIMENSIONS =
SYSTEM_CONFIG.getPackageVariableName("druid_dim_loader_dimensions");
public static final String DRUID_DIM_LOADER_ROW_LIMIT =
SYSTEM_CONFIG.getPackageVariableName("druid_dim_loader_row_limit");
private static final Integer ROW_LIMIT = SYSTEM_CONFIG.getIntProperty(DRUID_DIM_LOADER_ROW_LIMIT, 1000);
private static final Interval INTERVAL = new Interval(Years.years(10), DateTime.now());
private static final String ANY_MATCH_PATTERN = ".*";
private static final SearchQuerySpec SEARCH_QUERY_SPEC = new RegexSearchQuerySpec(ANY_MATCH_PATTERN);
private final DruidWebService druidWebService;
private final LinkedHashSet<Dimension> dimensions;
private final LinkedHashSet<DataSource> dataSources;
private HttpErrorCallback errorCallback;
private FailureCallback failureCallback;
/**
* DruidDimensionRowProvider fetches data from Druid and adds it to the dimension cache.
* The dimensions loaded are taken from the system config.
*
* @param physicalTableDictionary The physical tables
* @param dimensionDictionary The dimensions to update
* @param druidWebService The druid webservice to query
*/
public DruidDimensionValueLoader(
PhysicalTableDictionary physicalTableDictionary,
DimensionDictionary dimensionDictionary,
DruidWebService druidWebService
) {
this(
physicalTableDictionary,
dimensionDictionary,
//Our configuration framework automatically converts a comma-separated config value into a list.
SYSTEM_CONFIG.getListProperty(DRUID_DIM_LOADER_DIMENSIONS),
druidWebService
);
}
/**
* DruidDimensionRowProvider fetches data from Druid and adds it to the dimension cache.
* The dimensions to be loaded can be passed in as a parameter.
*
* @param physicalTableDictionary The physical tables
* @param dimensionDictionary The dimension dictionary to load dimensions from.
* @param dimensionsToLoad The dimensions to use.
* @param druidWebService The druid webservice to query.
*/
public DruidDimensionValueLoader(
PhysicalTableDictionary physicalTableDictionary,
DimensionDictionary dimensionDictionary,
List<String> dimensionsToLoad,
DruidWebService druidWebService
) {
this.dimensions = dimensionsToLoad.stream()
.map(dimensionDictionary::findByApiName)
.collect(Collectors.toCollection(LinkedHashSet::new));
this.dataSources = physicalTableDictionary.values().stream()
.map(table -> table.withConstraint(DataSourceConstraint.unconstrained(table)))
.map(TableDataSource::new)
.collect(Collectors.toCollection(LinkedHashSet::new));
this.druidWebService = druidWebService;
}
@Override
public void setErrorCallback(HttpErrorCallback errorCallback) {
this.errorCallback = errorCallback;
}
@Override
public void setFailureCallback(FailureCallback failureCallback) {
this.failureCallback = failureCallback;
}
@Override
public Set<Dimension> getDimensions() {
return dimensions;
}
@Override
public Set<DataSource> getDataSources() {
return dataSources;
}
@Override
public void query(Dimension dimension, DataSource dataSource) {
// Success callback will update the dimension cache
SuccessCallback success = buildDruidDimensionsSuccessCallback(dimension);
DruidSearchQuery druidSearchQuery = new DruidSearchQuery(
dataSource,
AllGranularity.INSTANCE,
null,
Collections.singletonList(INTERVAL),
Collections.singletonList(dimension),
SEARCH_QUERY_SPEC,
null,
ROW_LIMIT
);
RequestContext requestContext = new RequestContext(null, false);
druidWebService.postDruidQuery(
requestContext,
success,
errorCallback,
failureCallback,
druidSearchQuery
);
}
/**
* Build the callback to handle the successful druid query response.
*
* @param dimension Dimension for which we are getting values
*
* @return the callback
*/
private SuccessCallback buildDruidDimensionsSuccessCallback(Dimension dimension) {
return rootNode -> {
rootNode.forEach(intervalNode -> {
intervalNode.get("result").forEach(dim -> {
String value = dim.get("value").asText();
if (dimension.findDimensionRowByKeyValue(value) == null) {
DimensionRow dimRow = dimension.createEmptyDimensionRow(value);
updateDimensionWithValue(dimension, dimRow);
}
});
});
updateDimension(dimension);
};
}
} |
Java | @SuppressWarnings("serial")
public abstract class BaseKeSession<M extends BaseKeSession<M>> extends Model<M> implements IBean {
public void setId(java.lang.String id) {
set("id", id);
}
public java.lang.String getId() {
return get("id");
}
public void setUserId(java.lang.Integer userId) {
set("user_id", userId);
}
public java.lang.Integer getUserId() {
return get("user_id");
}
public void setExpireTime(java.lang.Long expireTime) {
set("expire_time", expireTime);
}
public java.lang.Long getExpireTime() {
return get("expire_time");
}
} |
Java | public class Meal implements Comparable<Meal> {
private Dish dish;
private Timestamp timestamp;
/**
* Constructs a meal entry from a {@link Dish} and {@link Timestamp}.
* @param dish Dish eaten
* @param timestamp Time of meal
*/
public Meal(Dish dish, Timestamp timestamp) {
this.dish = dish;
this.timestamp = timestamp;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Meal meal = (Meal) o;
return Objects.equals(dish, meal.dish)
&& Objects.equals(timestamp, meal.timestamp);
}
@Override
public int hashCode() {
return Objects.hash(dish, timestamp);
}
/**
* Returns the dish eaten.
* @return Dish eaten
*/
public Dish getDish() {
return dish;
}
/**
* Sets the dish eaten.
* @param dish Dish eaten
*/
public void setDish(Dish dish) {
this.dish = dish;
}
/**
* Gets the time of meal.
* @return Time of meal
*/
public Timestamp getTimestamp() {
return timestamp;
}
/**
* Sets the time of meal.
*
* WARNING! Editing timestamp may cause ordering to change.
* @param timestamp Time of meal
*/
public void setTimestamp(Timestamp timestamp) {
this.timestamp = timestamp;
}
@Override
public int compareTo(Meal meal) {
return timestamp.compareTo(meal.timestamp);
}
@Override
public String toString() {
String mealString = this.dish.getName().toString() + " "
+ this.dish.getCalories().toString() + "cal";
if (!this.dish.getTags().isEmpty()) {
mealString = mealString + " " + this.dish.getTags().toString();
}
return mealString;
}
/**
* Returns true if both meals of the same dish have the same timestamp.
*/
public boolean isSameMeal(Meal otherMeal) {
if (otherMeal == this) {
return true;
}
return otherMeal != null
&& otherMeal.getDish().equals(getDish())
&& otherMeal.getTimestamp().equals(getTimestamp());
}
} |
Java | @Component
@ConfigurationProperties(prefix = "audio-sources")
public class AudioSourcesConfigProperties implements AudioSourcesConfig {
// audio managers
private boolean youtubeEnabled = true;
private boolean soundcloudEnabled = true;
private boolean bandcampEnabled = true;
private boolean twitchEnabled = true;
private boolean vimeoEnabled = true;
private boolean mixerEnabled = true;
private boolean spotifyEnabled = true;
private boolean localEnabled = false;
private boolean httpEnabled = false;
@Override
public boolean isYouTubeEnabled() {
return youtubeEnabled;
}
@Override
public boolean isSoundCloudEnabled() {
return soundcloudEnabled;
}
@Override
public boolean isBandCampEnabled() {
return bandcampEnabled;
}
@Override
public boolean isTwitchEnabled() {
return twitchEnabled;
}
@Override
public boolean isVimeoEnabled() {
return vimeoEnabled;
}
@Override
public boolean isMixerEnabled() {
return mixerEnabled;
}
@Override
public boolean isSpotifyEnabled() {
return spotifyEnabled;
}
@Override
public boolean isLocalEnabled() {
return localEnabled;
}
@Override
public boolean isHttpEnabled() {
return httpEnabled;
}
public void setEnableYoutube(boolean youtubeEnabled) {
this.youtubeEnabled = youtubeEnabled;
}
public void setEnableSoundcloud(boolean soundcloudEnabled) {
this.soundcloudEnabled = soundcloudEnabled;
}
public void setEnableBandcamp(boolean bandcampEnabled) {
this.bandcampEnabled = bandcampEnabled;
}
public void setEnableTwitch(boolean twitchEnabled) {
this.twitchEnabled = twitchEnabled;
}
public void setEnableVimeo(boolean vimeoEnabled) {
this.vimeoEnabled = vimeoEnabled;
}
public void setEnableMixer(boolean mixerEnabled) {
this.mixerEnabled = mixerEnabled;
}
public void setEnableSpotify(boolean spotifyEnabled) {
this.spotifyEnabled = spotifyEnabled;
}
public void setEnableLocal(boolean localEnabled) {
this.localEnabled = localEnabled;
}
public void setEnableHttp(boolean httpEnabled) {
this.httpEnabled = httpEnabled;
}
} |
Java | @Slf4j
@MessageEndpoint
public class AccidentStatisticsMessageHandler implements MessageHandler {
private final ObjectMapper objectMapper;
private final ModelMapper modelMapper;
private final IAccidentStatisticsService accidentStatisticsService;
public AccidentStatisticsMessageHandler(
ObjectMapper objectMapper,
ModelMapper modelMapper,
IAccidentStatisticsService accidentStatisticsService) {
this.objectMapper = objectMapper;
this.modelMapper = modelMapper;
this.accidentStatisticsService = accidentStatisticsService;
}
/**
* Handles an AccidentStatistics-Message. If the AccidentStatistics already exist, it will be
* updated.
*
* @param message which contains the payload with the AccidentStatistics.
* @throws MessagingException if an error occurs, while retrieving the message.
*/
@Override
@ServiceActivator(inputChannel = "accidentStatisticsChannel")
public void handleMessage(Message<?> message) throws MessagingException {
log.info("AccidentStatistics-Message arrived! Payload: {}", message.getPayload());
String payload = (String) message.getPayload();
AckReplyConsumer consumer =
(AckReplyConsumer) message.getHeaders().get(GcpPubSubHeaders.ACKNOWLEDGEMENT);
try {
AccidentStatisticsDTO accidentStatisticsDTO =
objectMapper.readValue(payload, AccidentStatisticsDTO.class);
accidentStatisticsService.update(convertToEntity(accidentStatisticsDTO));
} catch (ServiceException | IOException e) {
log.error("Could not handle AccidentStatistics-Message. Message ignored.", e);
}
if (consumer != null) {
consumer.ack();
}
}
/**
* Converts an AccidentStatisticsDTO to an AccidentStatics entity.
*
* @param accidentStatisticsDTO which should get converted to an entity.
* @return the entity, which got created from mapping the dto.
*/
private AccidentStatistics convertToEntity(AccidentStatisticsDTO accidentStatisticsDTO) {
return modelMapper.map(accidentStatisticsDTO, AccidentStatistics.class);
}
} |
Java | @Data
@AllArgsConstructor
@NoArgsConstructor
public class QueryBody {
private String state;
private String searchName;
private long pageIndex;
private long pageSize;
} |
Java | public class Subtract {
public static void buildOpcodes(Map<Byte, Runnable> funcTable, CPU cpu) {
funcTable.put((byte) 0x90, () -> Subtract.subtract8Bit(cpu, cpu.BC.getHighByte(), "B", (byte) 0x90));
funcTable.put((byte) 0x91, () -> Subtract.subtract8Bit(cpu, cpu.BC.getLowByte(), "C", (byte) 0x91));
funcTable.put((byte) 0x92, () -> Subtract.subtract8Bit(cpu, cpu.DE.getHighByte(), "D", (byte) 0x92));
funcTable.put((byte) 0x93, () -> Subtract.subtract8Bit(cpu, cpu.DE.getLowByte(), "E", (byte) 0x93));
funcTable.put((byte) 0x94, () -> Subtract.subtract8Bit(cpu, cpu.HL.getHighByte(), "H", (byte) 0x94));
funcTable.put((byte) 0x95, () -> Subtract.subtract8Bit(cpu, cpu.HL.getLowByte(), "L", (byte) 0x95));
funcTable.put((byte) 0x97, () -> Subtract.subtract8Bit(cpu, cpu.AF.getHighByte(), "A", (byte) 0x97));
funcTable.put((byte) 0x96, () -> {
int memValue = cpu.memory.read(cpu.HL.get());
Subtract.subtract8Bit(cpu, memValue, "MEM", (byte) 0x96);
});
funcTable.put((byte) 0x98, () -> Subtract.subtractCarry8Bit(cpu, cpu.BC.getHighByte(), "B", (byte) 0x98,
cpu.flags.getCarry()));
funcTable.put((byte) 0x99, () -> Subtract.subtractCarry8Bit(cpu, cpu.BC.getLowByte(), "C", (byte) 0x99,
cpu.flags.getCarry()));
funcTable.put((byte) 0x9A, () -> Subtract.subtractCarry8Bit(cpu, cpu.DE.getHighByte(), "D", (byte) 0x9A,
cpu.flags.getCarry()));
funcTable.put((byte) 0x9B, () -> Subtract.subtractCarry8Bit(cpu, cpu.DE.getLowByte(), "E", (byte) 0x9B,
cpu.flags.getCarry()));
funcTable.put((byte) 0x9C, () -> Subtract.subtractCarry8Bit(cpu, cpu.HL.getHighByte(), "H", (byte) 0x9C,
cpu.flags.getCarry()));
funcTable.put((byte) 0x9D, () -> Subtract.subtractCarry8Bit(cpu, cpu.HL.getLowByte(), "L", (byte) 0x9D,
cpu.flags.getCarry()));
funcTable.put((byte) 0x9F, () -> Subtract.subtractCarry8Bit(cpu, cpu.AF.getHighByte(), "A", (byte) 0x9F,
cpu.flags.getCarry()));
funcTable.put((byte) 0x9E, () -> {
int memValue = cpu.memory.read(cpu.HL.get());
Subtract.subtractCarry8Bit(cpu, memValue, "MEM", (byte) 0x9E, cpu.flags.getCarry());
});
funcTable.put((byte) 0xD6, () -> {
int immValue = cpu.memory.read(cpu.PC.get() + 1);
Subtract.subtract8Bit(cpu, immValue, "d8", (byte) 0xD6);
cpu.PC.set(cpu.PC.get() + 1);
});
funcTable.put((byte) 0xDE, () -> {
int immValue = cpu.memory.read(cpu.PC.get() + 1);
Subtract.subtractCarry8Bit(cpu, immValue, "d8", (byte) 0xDE, cpu.flags.getCarry());
cpu.PC.set(cpu.PC.get() + 1);
});
}
private static void subtractLogInstruction(CPU cpu, String input, byte instruction) {
Utils.PrintInstruction("SUB " + input, instruction, cpu.PC.get(), null, 0);
}
private static void subtract8Bit(CPU cpu, int input, String inputStr, byte instruction) {
int initial = cpu.AF.getHighByte();
int result = initial - input;
cpu.AF.setHighByte((byte) result);
cpu.flags.setFlags(initial, result, false, Flags.HALFC | Flags.CARRY | Flags.ZERO);
cpu.flags.setSign(true);
subtractLogInstruction(cpu, inputStr, instruction);
cpu.PC.set(cpu.PC.get() + 1);
}
private static void subtractCarryLogInstruction(CPU cpu, String input, byte instruction) {
Utils.PrintInstruction("SBC " + input, instruction, cpu.PC.get(), null, 0);
}
private static void subtractCarry8Bit(CPU cpu, int input, String inputStr, byte instruction, boolean carry) {
int initial = cpu.AF.getHighByte();
int result = initial - (input + (carry ? 1 : 0));
cpu.AF.setHighByte((byte) result);
cpu.flags.setFlags(initial, result, false, Flags.HALFC | Flags.CARRY | Flags.ZERO);
cpu.flags.setSign(true);
subtractCarryLogInstruction(cpu, inputStr, instruction);
cpu.PC.set(cpu.PC.get() + 1);
}
} |
Java | public class UnitTrackerInformation {
private HashMap<TilePosition, Integer> playerAirAttackTilePositions = new HashMap<>();
private HashMap<TilePosition, Integer> playerGroundAttackTilePositions = new HashMap<>();
private HashMap<TilePosition, Integer> playerHealthTilePositions = new HashMap<>();
private HashMap<TilePosition, Integer> playerSupportTilePositions = new HashMap<>();
private HashMap<TilePosition, Integer> enemyAirAttackTilePositions = new HashMap<>();
private HashMap<TilePosition, Integer> enemyGroundAttackTilePositions = new HashMap<>();
private HashMap<TilePosition, Integer> enemyHealthTilePositions = new HashMap<>();
private HashMap<TilePosition, Integer> enemySupportTilePositions = new HashMap<>();
private List<EnemyUnit> enemyBuildings = new ArrayList<EnemyUnit>();
private List<EnemyUnit> enemyUnits = new ArrayList<EnemyUnit>();
public UnitTrackerInformation() {
}
// -------------------- Functions
// ------------------------------ Getter / Setter
public HashMap<TilePosition, Integer> getPlayerAirAttackTilePositions() {
return playerAirAttackTilePositions;
}
public void setPlayerAirAttackTilePositions(HashMap<TilePosition, Integer> playerAirAttackTilePositions) {
this.playerAirAttackTilePositions = playerAirAttackTilePositions;
}
public HashMap<TilePosition, Integer> getPlayerGroundAttackTilePositions() {
return playerGroundAttackTilePositions;
}
public void setPlayerGroundAttackTilePositions(HashMap<TilePosition, Integer> playerGroundAttackTilePositions) {
this.playerGroundAttackTilePositions = playerGroundAttackTilePositions;
}
public HashMap<TilePosition, Integer> getPlayerHealthTilePositions() {
return playerHealthTilePositions;
}
public void setPlayerHealthTilePositions(HashMap<TilePosition, Integer> playerHealthTilePositions) {
this.playerHealthTilePositions = playerHealthTilePositions;
}
public HashMap<TilePosition, Integer> getPlayerSupportTilePositions() {
return playerSupportTilePositions;
}
public void setPlayerSupportTilePositions(HashMap<TilePosition, Integer> playerSupportTilePositions) {
this.playerSupportTilePositions = playerSupportTilePositions;
}
public HashMap<TilePosition, Integer> getEnemyAirAttackTilePositions() {
return enemyAirAttackTilePositions;
}
public void setEnemyAirAttackTilePositions(HashMap<TilePosition, Integer> enemyAirAttackTilePositions) {
this.enemyAirAttackTilePositions = enemyAirAttackTilePositions;
}
public HashMap<TilePosition, Integer> getEnemyGroundAttackTilePositions() {
return enemyGroundAttackTilePositions;
}
public void setEnemyGroundAttackTilePositions(HashMap<TilePosition, Integer> enemyGroundAttackTilePositions) {
this.enemyGroundAttackTilePositions = enemyGroundAttackTilePositions;
}
public HashMap<TilePosition, Integer> getEnemyHealthTilePositions() {
return enemyHealthTilePositions;
}
public void setEnemyHealthTilePositions(HashMap<TilePosition, Integer> enemyHealthTilePositions) {
this.enemyHealthTilePositions = enemyHealthTilePositions;
}
public HashMap<TilePosition, Integer> getEnemySupportTilePositions() {
return enemySupportTilePositions;
}
public void setEnemySupportTilePositions(HashMap<TilePosition, Integer> enemySupportTilePositions) {
this.enemySupportTilePositions = enemySupportTilePositions;
}
public List<EnemyUnit> getEnemyBuildings() {
return enemyBuildings;
}
public void setEnemyBuildings(List<EnemyUnit> enemyBuildings) {
this.enemyBuildings = enemyBuildings;
}
public List<EnemyUnit> getEnemyUnits() {
return enemyUnits;
}
public void setEnemyUnits(List<EnemyUnit> enemyUnits) {
this.enemyUnits = enemyUnits;
}
} |
Java | public class DefaultRackDispatcher extends AbstractRackDispatcher {
public DefaultRackDispatcher(RackContext rackContext) {
super(rackContext);
}
@Override
protected RackApplication getApplication() throws RackInitializationException {
return getRackFactory().getApplication();
}
@Override
protected void afterException(RackEnvironment request, Exception re,
RackResponseEnvironment response) throws IOException {
try {
RackApplication errorApp = getRackFactory().getErrorApplication();
request.setAttribute(RackEnvironment.EXCEPTION, re);
errorApp.call(request).respond(response);
} catch (Exception e) {
context.log("Error: Couldn't handle error", e);
response.sendError(500);
}
}
@Override
protected void afterProcess(RackApplication app) {
getRackFactory().finishedWithApplication(app);
}
@Override
public void destroy() {
getRackFactory().destroy();
}
protected RackApplicationFactory getRackFactory() {
if (context instanceof ServletRackContext) {
return ((ServletRackContext) context).getRackFactory();
}
throw new IllegalStateException("not a servlet rack context");
}
} |
Java | @Configuration
@AutoConfigureBefore(WebMvcAutoConfiguration.class)
@ConditionalOnClass(ServletContextInitializer.class)
@EnableConfigurationProperties(VaadinConfigurationProperties.class)
@Import({ VaadinApplicationConfiguration.class,
VaadinServletConfiguration.class })
public class SpringBootAutoConfiguration {
@Autowired
private WebApplicationContext context;
/**
* Creates a {@link ServletContextInitializer} instance.
*
* @return a custom ServletContextInitializer instance
*/
@Bean
public ServletContextInitializer contextInitializer() {
return new VaadinServletContextInitializer(context);
}
/**
* Creates a {@link ServletRegistrationBean} instance with Spring aware
* Vaadin servlet.
*
* @param multipartConfig
* multipart configuration, if available
* @param configurationProperties
* the vaadin configuration properties
* @return a custom ServletRegistrationBean instance
*/
@Bean
public ServletRegistrationBean<SpringServlet> servletRegistrationBean(
ObjectProvider<MultipartConfigElement> multipartConfig,
VaadinConfigurationProperties configurationProperties) {
String mapping = configurationProperties.getUrlMapping();
Map<String, String> initParameters = new HashMap<>();
boolean rootMapping = RootMappedCondition.isRootMapping(mapping);
if (rootMapping) {
mapping = VaadinServletConfiguration.VAADIN_SERVLET_MAPPING;
}
ServletRegistrationBean<SpringServlet> registration = new ServletRegistrationBean<>(
new SpringServlet(context, rootMapping), mapping);
registration.setInitParameters(initParameters);
registration
.setAsyncSupported(configurationProperties.isAsyncSupported());
registration.setName(
ClassUtils.getShortNameAsProperty(SpringServlet.class));
// Setup multi part form processing for non root servlet mapping to be
// able to process Hilla login out of the box
if (!rootMapping) {
multipartConfig.ifAvailable(registration::setMultipartConfig);
}
registration.setLoadOnStartup(
configurationProperties.isLoadOnStartup() ? 1 : -1);
return registration;
}
/**
* Deploys JSR-356 websocket endpoints when Atmosphere is available.
*
* @return the server endpoint exporter which does the actual work.
*/
@Bean
public ServerEndpointExporter websocketEndpointDeployer() {
return new VaadinWebsocketEndpointExporter();
}
} |
Java | public final class Message {
private final Descriptor descriptor;
private final String templateName;
private final MessageProperties extraProperties;
// Lazily created.
private List<Field> fields = null;
private List<Message> messages = null;
private List<ProtoEnum> enums = null;
private List<Message> referencedMessages = null;
private List<ProtoEnum> referencedEnums = null;
private String fullName;
private String fullJavaType;
public Message(Descriptor descriptor, String templateName, MessageProperties extraProperties) {
this.descriptor = descriptor;
this.templateName = templateName;
this.extraProperties = extraProperties;
}
/**
* Returns the short name of the Java type of this message, for example:
* <ul>
* <li>org.waveprotocol.pst.examples.Example1.Person = "Person"</li>
* </ul>
*
* @return the name of the protocol buffer message
*/
public String getName() {
return descriptor.getName();
}
/**
* Returns the short name of Java type being generated. For example:
* <ul>
* <li>org.waveprotocol.pst.examples.Example1.Person = <ul>
* <li>"PersonMessage" (for template name "message")</li>
* <li>"PersonMessageServerImpl" (for template name "messageServerImpl")</li></ul>
* </li>
* </ul>
*
* @return the name of the Java message
*/
public String getJavaType() {
return descriptor.getName() + Util.capitalize(templateName);
}
/**
* Returns the full name of the this message in abstract Java space. For
* example:
* <ul>
* <li>org.waveprotocol.pst.examples.Example1.Person = <ul>
* <li>"org.waveprotocol.pst.examples.Person"
* (for template name "Message" and package suffix "dto")</li></ul>
* </li>
* </ul>
*
* @return the name of the protocol buffer message
*/
public String getFullName() {
if (fullName == null) {
fullName = getFullName(false);
}
return fullName;
}
/**
* Returns the full name of the Java type of this message, for example:
* <ul>
* <li>org.waveprotocol.pst.examples.Example1.Person = <ul>
* <li>"org.waveprotocol.pst.examples.dto.PersonMessage"
* (for template name "Message" and package suffix "dto")</li>
* <li>"org.waveprotocol.pst.examples.impl.PersonImpl"
* (for template name "Impl" and package suffix "impl")</li></ul>
* </li>
* </ul>
*
* @return the name of the protocol buffer message
*/
public String getFullJavaType() {
if (fullJavaType == null) {
fullJavaType = getFullName(true);
}
return fullJavaType;
}
/**
* Gets the fully-qualified name of this message.
*
* @param covariant if true, the name refers to the Java type being generated
* for this message. Otherwise, the name refers to a
* template-independent Java type, which may or may not exist. This is
* intended to be used so that the generated Java type for this message
* can refer to other Java types derived from this message.
* @return the fully-qualified name of this message.
*/
private String getFullName(boolean covariant) {
String prefix;
if (descriptor.getContainingType() != null) {
prefix = adapt(descriptor.getContainingType()).getFullName(covariant);
} else {
prefix = covariant ? getPackage() : getPackageBase();
}
return prefix + "." + (covariant ? getJavaType() : getName());
}
/**
* Returns the package of the Java messageas the base plus the suffix
* components of the package, for example given org.waveprotocol.pst.examples.Example1.Person:
* <ul>
* <li>Message = "org.waveprotocol.pst.examples"</li>
* <li>MessageServerImpl (package suffix "server") = "org.waveprotocol.pst.examples.server"</li>
* <li>MessageClientImpl (package suffix "client") = "org.waveprotocol.pst.examples.client"</li>
* </ul>
*
* @return the Java package of the message
*/
public String getPackage() {
String suffix = getPackageSuffix();
return getPackageBase() + (!Strings.isNullOrEmpty(suffix) ? "." + suffix : "");
}
/**
* Returns the base component of the Java message package, for example, given
* org.waveprotocol.pst.examples.Example1.Person:
* <ul>
* <li>Message = "org.waveprotocol.pst.examples"</li>
* <li>MessageServerImpl (package suffix "server") = "org.waveprotocol.pst.examples"</li>
* </ul>
*
* @return the base component of the Java package
*/
public String getPackageBase() {
String javaPackage = descriptor.getFile().getOptions().getJavaPackage();
if (Strings.isNullOrEmpty(javaPackage)) {
javaPackage = descriptor.getFile().getPackage();
}
return javaPackage;
}
/**
* Returns the suffix component of the Java message package, as configured in
* the message's properties file, for example:
* <ul>
* <li>Message = null</li>
* <li>MessageServerImpl = "server"</li>
* <li>MessageClientImpl = "client"</li>
* </ul>
*/
public String getPackageSuffix() {
return extraProperties.getPackageSuffix();
}
/**
* @return the filename of the protocol buffer (.proto) file where the message
* is defined
*/
public String getFilename() {
return descriptor.getFile().getName();
}
/**
* Returns the qualified type of the protobuf message, for example:
* <ul>
* <li>org.waveprotocol.pst.examples.Example1.Person =
* "org.waveprotocol.pst.examples.Example1.Person"</li>
* </ul>
*
* @return the full type of the protocol buffer message
*/
public String getProtoType() {
Deque<String> scopes = Lists.newLinkedList();
for (Descriptor message = descriptor; message != null; message = message.getContainingType()) {
scopes.push(message.getName());
}
scopes.push(descriptor.getFile().getOptions().getJavaOuterClassname());
scopes.push(getPackageBase());
return Joiner.on('.').join(scopes);
}
/**
* @return the fields of the message
*/
public List<Field> getFields() {
if (fields == null) {
ImmutableList.Builder<Field> builder = ImmutableList.builder();
for (FieldDescriptor fd : descriptor.getFields()) {
builder.add(new Field(fd, new Type(fd, templateName, extraProperties), extraProperties));
}
fields = builder.build();
}
return fields;
}
/**
* @return the set of all messages referred to be this message and its nested
* messages. Message references are due to message-typed fields.
*/
public List<Message> getReferencedMessages() {
if (referencedMessages == null) {
referencedMessages = Lists.newArrayList();
for (Descriptor d : collectMessages(descriptor, Sets.<Descriptor>newLinkedHashSet())) {
referencedMessages.add(adapt(d));
}
}
return referencedMessages;
}
/**
* @return the set of all enums referred to be this message and its nested
* messages. Enum references are due to message-typed fields.
*/
public List<ProtoEnum> getReferencedEnums() {
if (referencedEnums == null) {
referencedEnums = Lists.newArrayList();
for (EnumDescriptor d : collectEnums(descriptor, Sets.<EnumDescriptor> newLinkedHashSet())) {
referencedEnums.add(adapt(d));
}
}
return referencedEnums;
}
/**
* Collects messages referred to by a message and its nested messages.
*
* @return {@code referenced}
*/
private static Collection<Descriptor> collectMessages(
Descriptor message, Collection<Descriptor> referenced) {
for (FieldDescriptor fd : message.getFields()) {
if (fd.getJavaType() == JavaType.MESSAGE) {
referenced.add(fd.getMessageType());
}
}
for (Descriptor nd : message.getNestedTypes()) {
collectMessages(nd, referenced);
}
return referenced;
}
/**
* Collects enums referred to by a message and its nested messages.
*
* @return {@code referenced}
*/
private static Collection<EnumDescriptor> collectEnums(
Descriptor d, Collection<EnumDescriptor> referenced) {
for (FieldDescriptor fd : d.getFields()) {
if (fd.getJavaType() == JavaType.ENUM) {
referenced.add(fd.getEnumType());
}
}
for (Descriptor nd : d.getNestedTypes()) {
collectEnums(nd, referenced);
}
return referenced;
}
/**
* @return the nested messages of the message
*/
public List<Message> getNestedMessages() {
if (messages == null) {
ImmutableList.Builder<Message> builder = ImmutableList.builder();
for (Descriptor d : descriptor.getNestedTypes()) {
builder.add(adapt(d));
}
messages = builder.build();
}
return messages;
}
/**
* @return the nested enums of the message
*/
public List<ProtoEnum> getNestedEnums() {
if (enums == null) {
ImmutableList.Builder<ProtoEnum> builder = ImmutableList.builder();
for (EnumDescriptor ed : descriptor.getEnumTypes()) {
builder.add(adapt(ed));
}
enums = builder.build();
}
return enums;
}
/**
* @return whether this is an inner class
*/
public boolean isInner() {
return descriptor.getContainingType() != null;
}
private Message adapt(Descriptor d) {
return new Message(d, templateName, extraProperties);
}
private ProtoEnum adapt(EnumDescriptor d) {
return new ProtoEnum(d, templateName, extraProperties);
}
} |
Java | public class Exercise20 {
public static void main(String[] args) {
boolean allFilesStartWithCAFEBABE = true;
String path = "";
try {
path = new File("./").getCanonicalPath();
Directory.TreeInfo tree = Directory.walk("./", ".*\\.class");
for(File file: tree.files) {
byte[] fileBytes = BinaryFile.read(file.getCanonicalFile());
String hexString = bytesToHexString(Arrays.copyOf(fileBytes, 4));
if(!hexString.toUpperCase().equals("CAFEBABE"))
allFilesStartWithCAFEBABE = false;
System.out.println("Filename: " + file.getName() + " startsWith: " + hexString);
}
} catch(IOException e) {
System.err.println("Caught " + e);
e.printStackTrace();
}
System.out.println("All files in " + path + " start with ‘CAFEBABE’ ? : "
+ (allFilesStartWithCAFEBABE ? "Yes": "No") );
}
public static String bytesToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
Formatter formatter = new Formatter(sb);
for (byte b : bytes) {
formatter.format("%02x", b);
}
return sb.toString();
}
} |
Java | @Generated("com.amazonaws:aws-java-sdk-code-generator")
public class InvalidTrackingOptionsException extends com.amazonaws.services.simpleemail.model.AmazonSimpleEmailServiceException {
private static final long serialVersionUID = 1L;
/**
* Constructs a new InvalidTrackingOptionsException with the specified error message.
*
* @param message
* Describes the error encountered.
*/
public InvalidTrackingOptionsException(String message) {
super(message);
}
} |
Java | public class FireCell extends Cell{
public static final int EMPTY = 1;
public static final int TREE = 0;
public static final int BURNING = 2;
public static final int PROB_CATCH_INDEX = 0;
public static final Paint[] colors = {Color.GREEN, Color.DARKGOLDENROD, Color.RED};
/**
* initializes a new FireCell object that has a given set of colors
*/
public FireCell() {
super();
super.setColors(colors);
}
/**
* apply the FireCell rules:
* if you're an empty cell, your next state will be empty
* if you're a burning cell, your next state will be empty
* if you're neighbors with a burning cell, your next state could be alive or burning
*/
@Override
public void applyRules() {
if(super.getCurrentState() == EMPTY){
return;
}
if (super.getCurrentState() == BURNING) {
super.setNextState(EMPTY);
return;
}
if (this.atRisk()) {
double prob = Math.random();
if (prob <= super.getParams()[PROB_CATCH_INDEX]){
super.setNextState(BURNING);
}
}
}
/**
*
* @return a boolean indicating whether the tree is at risk of burning
*/
private boolean atRisk(){
for (Cell tree:super.getNeighbors()) {
if (tree.getCurrentState() == BURNING){
return true;
}
}
return false;
}
} |
Java | public final class PublicSuffixMatcher {
private final Map<String, String> rules;
private final Map<String, String> exceptions;
public PublicSuffixMatcher(final Collection<String> rules, final Collection<String> exceptions) {
Args.notNull(rules, "Domain suffix rules");
this.rules = new ConcurrentHashMap<String, String>(rules.size());
for (String rule: rules) {
this.rules.put(rule, rule);
}
if (exceptions != null) {
this.exceptions = new ConcurrentHashMap<String, String>(exceptions.size());
for (String exception: exceptions) {
this.exceptions.put(exception, exception);
}
} else {
this.exceptions = null;
}
}
/**
* Returns registrable part of the domain for the given domain name of {@code null}
* if given domain represents a public suffix.
*
* @param domain
* @return domain root
*/
public String getDomainRoot(final String domain) {
if (domain == null) {
return null;
}
if (domain.startsWith(".")) {
return null;
}
String domainName = null;
String segment = domain.toLowerCase(Locale.ROOT);
while (segment != null) {
// An exception rule takes priority over any other matching rule.
if (this.exceptions != null && this.exceptions.containsKey(IDN.toUnicode(segment))) {
return segment;
}
if (this.rules.containsKey(IDN.toUnicode(segment))) {
break;
}
final int nextdot = segment.indexOf('.');
final String nextSegment = nextdot != -1 ? segment.substring(nextdot + 1) : null;
if (nextSegment != null) {
if (this.rules.containsKey("*." + IDN.toUnicode(nextSegment))) {
break;
}
}
if (nextdot != -1) {
domainName = segment;
}
segment = nextSegment;
}
return domainName;
}
public boolean matches(final String domain) {
if (domain == null) {
return false;
}
final String domainRoot = getDomainRoot(domain.startsWith(".") ? domain.substring(1) : domain);
return domainRoot == null;
}
} |
Java | public class ComponentCaption extends JPanel {
private Component owner;
private JLabel label;
private ToolTipButton toolTipButton;
public ComponentCaption(Component owner) {
BoxLayoutAdapter.create(this);
this.owner = owner;
takeOwnerProperties();
}
private void takeOwnerProperties() {
if (label == null) {
label = new JLabel();
add(label);
}
label.setText(((Component.HasCaption) owner).getCaption());
if (((Component.HasCaption) owner).getDescription() != null) {
if (toolTipButton == null) {
toolTipButton = new ToolTipButton();
toolTipButton.setFocusable(false);
DesktopToolTipManager.getInstance().registerTooltip(toolTipButton);
add(toolTipButton);
}
toolTipButton.setToolTipText(((Component.HasCaption) owner).getDescription());
} else if (toolTipButton != null) {
remove(toolTipButton);
toolTipButton = null;
}
setVisible(owner.isVisible());
setEnabled(owner.isEnabled());
}
public void update() {
takeOwnerProperties();
}
} |
Java | public class MinimumDepthofBinaryTree {
/**
* 解题思路:
* 1. 利用递归,利用每个当前节点求最小深度。
* 2. 需要处理单边的情况,如树转化为链表的情况,如
* 2
* /
* 1
*
* @param root
* @return
*/
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
int left = minDepth(root.left);
int right = minDepth(root.right);
return (left == 0 || right == 0) ? left + right + 1 : Math.min(left, right) + 1;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(3);
root.left = new TreeNode(9);
root.right = new TreeNode(20);
root.right.left = new TreeNode(15);
root.right.right = new TreeNode(7);
System.out.println(new MinimumDepthofBinaryTree().minDepth(root));
}
} |
Java | public abstract class TransportNegotiator extends JingleNegotiator {
private static final Logger LOGGER = Logger.getLogger(TransportNegotiator.class.getName());
// The time we give to the candidates check before we accept or decline the
// transport (in milliseconds)
public final static int CANDIDATES_ACCEPT_PERIOD = 4000;
// The session this nenotiator belongs to
//private final JingleSession session;
// The transport manager
private final TransportResolver resolver;
// Transport candidates we have offered
private final List<TransportCandidate> offeredCandidates = new ArrayList<TransportCandidate>();
// List of remote transport candidates
private final List<TransportCandidate> remoteCandidates = new ArrayList<TransportCandidate>();
// Valid remote candidates
private final List<TransportCandidate> validRemoteCandidates = new ArrayList<TransportCandidate>();
// Accepted Remote Candidates
private final List<TransportCandidate> acceptedRemoteCandidates = new ArrayList<TransportCandidate>();
// The best local candidate we have offered (and accepted by the other part)
private TransportCandidate acceptedLocalCandidate;
// The thread that will report the result to the other end
private Thread resultThread;
// Listener for the resolver
private TransportResolverListener.Resolver resolverListener;
private ContentNegotiator parentNegotiator;
/**
* Default constructor.
*
* @param session The Jingle session
* @param transResolver The JingleTransportManager to use
*/
public TransportNegotiator(JingleSession session, TransportResolver transResolver, ContentNegotiator parentNegotiator) {
super(session);
resolver = transResolver;
this.parentNegotiator = parentNegotiator;
resultThread = null;
}
/**
* Get a new instance of the right TransportNegotiator class with this
* candidate.
*
* @return A TransportNegotiator instance
*/
public abstract JingleTransport getJingleTransport(TransportCandidate cand);
/**
* Return true if the transport candidate is acceptable for the current
* negotiator.
*
* @return true if the transport candidate is acceptable
*/
public abstract boolean acceptableTransportCandidate(TransportCandidate tc, List<TransportCandidate> localCandidates);
/**
* Obtain the best local candidate we want to offer.
*
* @return the best local candidate
*/
public final TransportCandidate getBestLocalCandidate() {
return resolver.getPreferredCandidate();
}
/**
* Set the best local transport candidate we have offered and accepted by
* the other endpoint.
*
* @param bestLocalCandidate the acceptedLocalCandidate to set
*/
private void setAcceptedLocalCandidate(TransportCandidate bestLocalCandidate) throws XMPPException {
for (int i = 0; i < resolver.getCandidateCount(); i++) {
//TODO FIX The EQUAL Sentence
if (resolver.getCandidate(i).getIp().equals(bestLocalCandidate.getIp())
&& resolver.getCandidate(i).getPort() == bestLocalCandidate.getPort()) {
acceptedLocalCandidate = resolver.getCandidate(i);
return;
}
}
LOGGER.fine("BEST: ip=" + bestLocalCandidate.getIp() + " port=" + bestLocalCandidate.getPort() + " has not been offered.");
//throw new XMPPException("Local transport candidate has not be offered.");
}
/**
* Get the best accepted local candidate we have offered.
*
* @return a transport candidate we have offered.
*/
public TransportCandidate getAcceptedLocalCandidate() {
return acceptedLocalCandidate;
}
/**
* Called from above to start the negotiator during a session-initiate.
*/
protected void doStart() {
try {
sendTransportCandidatesOffer();
setNegotiatorState(JingleNegotiatorState.PENDING);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Called from above to session-terminate.
*/
public void close() {
super.close();
}
/**
* Return a JingleTransport that best reflects this transport negotiator.
*/
public JingleTransport getJingleTransport() {
return getJingleTransport(getBestRemoteCandidate());
}
public List<TransportCandidate> getOfferedCandidates() {
return offeredCandidates;
}
/**
* Obtain the best common transport candidate obtained in the negotiation.
*
* @return the bestRemoteCandidate
*/
public abstract TransportCandidate getBestRemoteCandidate();
/**
* Get the list of remote candidates.
*
* @return the remoteCandidates
*/
private List<TransportCandidate> getRemoteCandidates() {
return remoteCandidates;
}
/**
* Add a remote candidate to the list. The candidate will be checked in
* order to verify if it is usable.
*
* @param rc a remote candidate to add and check.
*/
private void addRemoteCandidate(TransportCandidate rc) {
// Add the candidate to the list
if (rc != null) {
if (acceptableTransportCandidate(rc, offeredCandidates)) {
synchronized (remoteCandidates) {
remoteCandidates.add(rc);
}
// Check if the new candidate can be used.
checkRemoteCandidate(rc);
}
}
}
/**
* Add a offered candidate to the list.
*
* @param rc a remote candidate we have offered.
*/
private void addOfferedCandidate(TransportCandidate rc) {
// Add the candidate to the list
if (rc != null) {
synchronized (offeredCandidates) {
offeredCandidates.add(rc);
}
}
}
/**
* Check asynchronously the new transport candidate.
*
* @param offeredCandidate a transport candidates to check
*/
private void checkRemoteCandidate(final TransportCandidate offeredCandidate) {
offeredCandidate.addListener(new TransportResolverListener.Checker() {
public void candidateChecked(TransportCandidate cand, final boolean validCandidate) {
if (validCandidate) {
if (getNegotiatorState() == JingleNegotiatorState.PENDING)
addValidRemoteCandidate(offeredCandidate);
}
}
public void candidateChecking(TransportCandidate cand) {
}
});
offeredCandidate.check(resolver.getCandidatesList());
}
/**
* Return true if the transport is established.
*
* @return true if the transport is established.
*/
private boolean isEstablished() {
return getBestRemoteCandidate() != null && getAcceptedLocalCandidate() != null;
}
/**
* Return true if the transport is fully established.
*
* @return true if the transport is fully established.
*/
public final boolean isFullyEstablished() {
return (isEstablished() && ((getNegotiatorState() == JingleNegotiatorState.SUCCEEDED) || (getNegotiatorState() == JingleNegotiatorState.FAILED)));
}
/**
* Launch a thread that checks, after some time, if any of the candidates
* offered by the other endpoint is usable. The thread does not check the
* candidates: it just checks if we have got a valid one and sends an Accept
* in that case.
*/
private void delayedCheckBestCandidate(final JingleSession js, final Jingle jin) {
//
// If this is the first insertion in the list, start the thread that
// will send the result of our checks...
//
if (resultThread == null && !getRemoteCandidates().isEmpty()) {
resultThread = new Thread(new Runnable() {
public void run() {
// Sleep for some time, waiting for the candidates checks
int totalTime = (CANDIDATES_ACCEPT_PERIOD + TransportResolver.CHECK_TIMEOUT);
int tries = (int) Math.ceil(totalTime / 1000);
for (int i = 0; i < tries - 1; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Once we are in pending state, look for any valid remote
// candidate, and send an "accept" if we have one...
TransportCandidate bestRemote = getBestRemoteCandidate();
//State state = getState();
if ((bestRemote != null)
&& ((getNegotiatorState() == JingleNegotiatorState.PENDING))) {
// Accepting the remote candidate
if (!acceptedRemoteCandidates.contains(bestRemote)) {
Jingle jout = new Jingle(JingleActionEnum.CONTENT_ACCEPT);
JingleContent content = parentNegotiator.getJingleContent();
content.addJingleTransport(getJingleTransport(bestRemote));
jout.addContent(content);
// Send the packet
try {
js.sendFormattedJingle(jin, jout);
}
catch (NotConnectedException e) {
throw new IllegalStateException(e);
}
acceptedRemoteCandidates.add(bestRemote);
}
if ((isEstablished()) && (getNegotiatorState() == JingleNegotiatorState.PENDING)) {
setNegotiatorState(JingleNegotiatorState.SUCCEEDED);
try {
triggerTransportEstablished(getAcceptedLocalCandidate(), bestRemote);
}
catch (NotConnectedException e) {
throw new IllegalStateException(e);
}
break;
}
}
}
// Once we are in pending state, look for any valid remote
// candidate, and send an "accept" if we have one...
TransportCandidate bestRemote = getBestRemoteCandidate();
if (bestRemote == null) {
boolean foundRemoteRelay = false;
for (TransportCandidate candidate : remoteCandidates) {
if (candidate instanceof ICECandidate) {
ICECandidate iceCandidate = (ICECandidate) candidate;
if (iceCandidate.getType().equals("relay")) {
//TODO Check if the relay is reacheable
addValidRemoteCandidate(iceCandidate);
foundRemoteRelay = true;
}
}
}
// If not found, check if we offered a relay. If yes, we should accept any remote candidate.
// We should accept the Public One if we received it, otherwise, accepts any.
if (!foundRemoteRelay) {
boolean foundLocalRelay = false;
for (TransportCandidate candidate : offeredCandidates) {
if (candidate instanceof ICECandidate) {
ICECandidate iceCandidate = (ICECandidate) candidate;
if (iceCandidate.getType().equals("relay")) {
foundLocalRelay = true;
}
}
}
if (foundLocalRelay) {
boolean foundRemotePublic = false;
for (TransportCandidate candidate : remoteCandidates) {
if (candidate instanceof ICECandidate) {
ICECandidate iceCandidate = (ICECandidate) candidate;
if (iceCandidate.getType().equals(ICECandidate.Type.srflx)) {
addValidRemoteCandidate(iceCandidate);
foundRemotePublic = true;
}
}
}
if (!foundRemotePublic) {
for (TransportCandidate candidate : remoteCandidates) {
if (candidate instanceof ICECandidate) {
ICECandidate iceCandidate = (ICECandidate) candidate;
addValidRemoteCandidate(iceCandidate);
}
}
}
}
}
}
for (int i = 0; i < 6; i++) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
bestRemote = getBestRemoteCandidate();
//State state = getState();
if ((bestRemote != null)
&& ((getNegotiatorState() == JingleNegotiatorState.PENDING))) {
if (!acceptedRemoteCandidates.contains(bestRemote)) {
Jingle jout = new Jingle(JingleActionEnum.CONTENT_ACCEPT);
JingleContent content = parentNegotiator.getJingleContent();
content.addJingleTransport(getJingleTransport(bestRemote));
jout.addContent(content);
// Send the packet
try {
js.sendFormattedJingle(jin, jout);
}
catch (NotConnectedException e) {
throw new IllegalStateException(e);
}
acceptedRemoteCandidates.add(bestRemote);
}
if (isEstablished()) {
setNegotiatorState(JingleNegotiatorState.SUCCEEDED);
break;
}
}
}
if (getNegotiatorState() != JingleNegotiatorState.SUCCEEDED) {
try {
session
.terminate("Unable to negotiate session. This may be caused by firewall configuration problems.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}, "Waiting for all the transport candidates checks...");
resultThread.setName("Transport Resolver Result");
resultThread.start();
}
}
/**
* Add a valid remote candidate to the list. The remote candidate has been
* checked, and the remote
*
* @param remoteCandidate a remote candidate to add
*/
private void addValidRemoteCandidate(TransportCandidate remoteCandidate) {
// Add the candidate to the list
if (remoteCandidate != null) {
synchronized (validRemoteCandidates) {
LOGGER.fine("Added valid candidate: " + remoteCandidate.getIp() + ":" + remoteCandidate.getPort());
validRemoteCandidates.add(remoteCandidate);
}
}
}
/**
* Get the list of valid (ie, checked) remote candidates.
*
* @return The list of valid (ie, already checked) remote candidates.
*/
final ArrayList<TransportCandidate> getValidRemoteCandidatesList() {
synchronized (validRemoteCandidates) {
return new ArrayList<TransportCandidate>(validRemoteCandidates);
}
}
/**
* Get an iterator for the list of valid (ie, checked) remote candidates.
*
* @return The iterator for the list of valid (ie, already checked) remote
* candidates.
*/
public final Iterator<TransportCandidate> getValidRemoteCandidates() {
return Collections.unmodifiableList(getRemoteCandidates()).iterator();
}
/**
* Add an offered remote candidate. The transport candidate can be unusable:
* we must check if we can use it.
*
* @param rc the remote candidate to add.
*/
private void addRemoteCandidates(List<TransportCandidate> rc) {
if (rc != null) {
if (rc.size() > 0) {
for (TransportCandidate aRc : rc) {
addRemoteCandidate(aRc);
}
}
}
}
/**
* Parse the list of transport candidates from a Jingle packet.
*
* @param jin The input jingle packet
*/
private List<TransportCandidate> obtainCandidatesList(Jingle jingle) {
List<TransportCandidate> result = new ArrayList<TransportCandidate>();
if (jingle != null) {
// Get the list of candidates from the packet
for (JingleContent jingleContent : jingle.getContentsList()) {
if (jingleContent.getName().equals(parentNegotiator.getName())) {
for (JingleTransport jingleTransport : jingleContent.getJingleTransportsList()) {
for (JingleTransportCandidate jingleTransportCandidate : jingleTransport.getCandidatesList()) {
TransportCandidate transCand = jingleTransportCandidate.getMediaTransport();
result.add(transCand);
}
}
}
}
}
return result;
}
/**
* Send an offer for a transport candidate
*
* @param cand
* @throws NotConnectedException
*/
private synchronized void sendTransportCandidateOffer(TransportCandidate cand) throws NotConnectedException {
if (!cand.isNull()) {
// Offer our new candidate...
addOfferedCandidate(cand);
JingleContent content = parentNegotiator.getJingleContent();
content.addJingleTransport(getJingleTransport(cand));
Jingle jingle = new Jingle(JingleActionEnum.TRANSPORT_INFO);
jingle.addContent(content);
// We SHOULD NOT be sending packets directly.
// This circumvents the state machinery.
// TODO - work this into the state machinery.
session.sendFormattedJingle(jingle);
}
}
/**
* Create a Jingle stanza(/packet) where we announce our transport candidates.
*
* @throws XMPPException
* @throws SmackException
*/
private void sendTransportCandidatesOffer() throws XMPPException, SmackException {
List<TransportCandidate> notOffered = resolver.getCandidatesList();
notOffered.removeAll(offeredCandidates);
// Send any unset candidate
for (Object aNotOffered : notOffered) {
sendTransportCandidateOffer((TransportCandidate) aNotOffered);
}
// .. and start a listener that will send any future candidate
if (resolverListener == null) {
// Add a listener that sends the offer when the resolver finishes...
resolverListener = new TransportResolverListener.Resolver() {
public void candidateAdded(TransportCandidate cand) throws NotConnectedException {
sendTransportCandidateOffer(cand);
}
public void end() {
}
public void init() {
}
};
resolver.addListener(resolverListener);
}
if (!(resolver.isResolving() || resolver.isResolved())) {
// Resolve our IP and port
LOGGER.fine("RESOLVER CALLED");
resolver.resolve(session);
}
}
/**
* Dispatch an incoming packet. The method is responsible for recognizing
* the stanza(/packet) type and, depending on the current state, deliverying the
* stanza(/packet) to the right event handler and wait for a response.
*
* @param iq the stanza(/packet) received
* @return the new Jingle stanza(/packet) to send.
* @throws XMPPException
* @throws SmackException
*/
public final List<IQ> dispatchIncomingPacket(IQ iq, String id) throws XMPPException, SmackException {
List<IQ> responses = new ArrayList<IQ>();
IQ response = null;
if (iq != null) {
if (iq.getType().equals(IQ.Type.error)) {
// Process errors
setNegotiatorState(JingleNegotiatorState.FAILED);
triggerTransportClosed(null);
// This next line seems wrong, and may subvert the normal closing process.
throw new JingleException(iq.getError().getDescriptiveText());
} else if (iq.getType().equals(IQ.Type.result)) {
// Process ACKs
if (isExpectedId(iq.getStanzaId())) {
response = receiveResult(iq);
removeExpectedId(iq.getStanzaId());
}
} else if (iq instanceof Jingle) {
// Get the action from the Jingle packet
Jingle jingle = (Jingle) iq;
JingleActionEnum action = jingle.getAction();
switch (action) {
case CONTENT_ACCEPT:
response = receiveContentAcceptAction(jingle);
break;
case CONTENT_MODIFY:
break;
case CONTENT_REMOVE:
break;
case SESSION_INFO:
break;
case SESSION_INITIATE:
response = receiveSessionInitiateAction(jingle);
break;
case SESSION_ACCEPT:
response = receiveSessionAcceptAction(jingle);
break;
case TRANSPORT_INFO:
response = receiveTransportInfoAction(jingle);
break;
default:
break;
}
}
}
if (response != null) {
addExpectedId(response.getStanzaId());
responses.add(response);
}
return responses;
}
/**
* The other endpoint has partially accepted our invitation: start
* offering a list of candidates.
*
* @return an IQ packet
* @throws XMPPException
* @throws SmackException
*/
private Jingle receiveResult(IQ iq) throws XMPPException, SmackException {
Jingle response = null;
sendTransportCandidatesOffer();
setNegotiatorState(JingleNegotiatorState.PENDING);
return response;
}
/**
* @param jingle
* @param jingleTransport
* @return the iq
* @throws SmackException
*/
private IQ receiveSessionInitiateAction(Jingle jingle) throws XMPPException, SmackException {
IQ response = null;
// Parse the Jingle and get any proposed transport candidates
//addRemoteCandidates(obtainCandidatesList(jin));
// Start offering candidates
sendTransportCandidatesOffer();
// All these candidates will be checked asyncronously. Wait for some
// time and check if we have a valid candidate to use...
delayedCheckBestCandidate(session, jingle);
// Set the next state
setNegotiatorState(JingleNegotiatorState.PENDING);
return response;
}
/**
* @param jingle
* @param jingleTransport
* @return the iq
*/
private IQ receiveTransportInfoAction(Jingle jingle) throws XMPPException {
IQ response = null;
// Parse the Jingle and get any proposed transport candidates
//addRemoteCandidates(obtainCandidatesList(jin));
// // Start offering candidates
// sendTransportCandidatesOffer();
//
// // All these candidates will be checked asyncronously. Wait for some
// // time and check if we have a valid candidate to use...
// delayedCheckBestCandidate(session, jingle);
//
// // Set the next state
// setNegotiatorState(JingleNegotiatorState.PENDING);
// Parse the Jingle and get any proposed transport candidates
addRemoteCandidates(obtainCandidatesList(jingle));
// Wait for some time and check if we have a valid candidate to
// use...
delayedCheckBestCandidate(session, jingle);
response = session.createAck(jingle);
return response;
}
/**
* One of our transport candidates has been accepted.
*
* @param jin The input packet
* @return a Jingle packet
* @throws XMPPException an exception
* @see org.jivesoftware.smackx.jingleold.JingleNegotiator.State#eventAccept(org.jivesoftware.smackx.jingleold.packet.Jingle)
*/
private IQ receiveContentAcceptAction(Jingle jingle) throws XMPPException {
IQ response = null;
// Parse the Jingle and get the accepted candidate
List<TransportCandidate> accepted = obtainCandidatesList(jingle);
if (!accepted.isEmpty()) {
for (TransportCandidate cand : accepted) {
LOGGER.fine("Remote acccepted candidate addr: " + cand.getIp());
}
TransportCandidate cand = (TransportCandidate) accepted.get(0);
setAcceptedLocalCandidate(cand);
if (isEstablished()) {
LOGGER.fine(cand.getIp() + " is set active");
//setNegotiatorState(JingleNegotiatorState.SUCCEEDED);
}
}
return response;
}
/**
* @param jingle
* @return the iq
*/
private IQ receiveSessionAcceptAction(Jingle jingle) {
IQ response = null;
LOGGER.fine("Transport stabilished");
//triggerTransportEstablished(getAcceptedLocalCandidate(), getBestRemoteCandidate());
//setNegotiatorState(JingleNegotiatorState.SUCCEEDED);
return response;
}
/**
* Trigger a Transport session established event.
*
* @param local TransportCandidate that has been agreed.
* @param remote TransportCandidate that has been agreed.
* @throws NotConnectedException
*/
private void triggerTransportEstablished(TransportCandidate local, TransportCandidate remote) throws NotConnectedException {
List<JingleListener> listeners = getListenersList();
for (JingleListener li : listeners) {
if (li instanceof JingleTransportListener) {
JingleTransportListener mli = (JingleTransportListener) li;
LOGGER.fine("triggerTransportEstablished " + local.getLocalIp() + ":" + local.getPort() + " <-> "
+ remote.getIp() + ":" + remote.getPort());
mli.transportEstablished(local, remote);
}
}
}
/**
* Trigger a Transport closed event.
*
* @param cand current TransportCandidate that is cancelled.
*/
private void triggerTransportClosed(TransportCandidate cand) {
List<JingleListener> listeners = getListenersList();
for (JingleListener li : listeners) {
if (li instanceof JingleTransportListener) {
JingleTransportListener mli = (JingleTransportListener) li;
mli.transportClosed(cand);
}
}
}
// Subclasses
/**
* Raw-UDP transport negotiator
*
* @author Alvaro Saurin <[email protected]>
*/
public static final class RawUdp extends TransportNegotiator {
/**
* Default constructor, with a JingleSession and transport manager.
*
* @param js The Jingle session this negotiation belongs to.
* @param res The transport resolver to use.
*/
public RawUdp(JingleSession js, final TransportResolver res, ContentNegotiator parentNegotiator) {
super(js, res, parentNegotiator);
}
/**
* Get a TransportNegotiator instance.
*/
public org.jivesoftware.smackx.jingleold.packet.JingleTransport getJingleTransport(TransportCandidate bestRemote) {
org.jivesoftware.smackx.jingleold.packet.JingleTransport.RawUdp jt = new org.jivesoftware.smackx.jingleold.packet.JingleTransport.RawUdp();
jt.addCandidate(new org.jivesoftware.smackx.jingleold.packet.JingleTransport.RawUdp.Candidate(bestRemote));
return jt;
}
/**
* Obtain the best common transport candidate obtained in the
* negotiation.
*
* @return the bestRemoteCandidate
*/
public TransportCandidate getBestRemoteCandidate() {
// Hopefully, we only have one validRemoteCandidate
ArrayList<TransportCandidate> cands = getValidRemoteCandidatesList();
if (!cands.isEmpty()) {
LOGGER.fine("RAW CAND");
return (TransportCandidate) cands.get(0);
} else {
LOGGER.fine("No Remote Candidate");
return null;
}
}
/**
* Return true for fixed candidates.
*/
public boolean acceptableTransportCandidate(TransportCandidate tc, List<TransportCandidate> localCandidates) {
return tc instanceof TransportCandidate.Fixed;
}
}
/**
* Ice transport negotiator.
*
* @author Alvaro Saurin <[email protected]>
*/
public static final class Ice extends TransportNegotiator {
/**
* Default constructor, with a JingleSession and transport manager.
*
* @param js The Jingle session this negotiation belongs to.
* @param res The transport manager to use.
*/
public Ice(JingleSession js, final TransportResolver res, ContentNegotiator parentNegotiator) {
super(js, res, parentNegotiator);
}
/**
* Get a TransportNegotiator instance.
*
* @param candidate
*/
public org.jivesoftware.smackx.jingleold.packet.JingleTransport getJingleTransport(TransportCandidate candidate) {
org.jivesoftware.smackx.jingleold.packet.JingleTransport.Ice jt = new org.jivesoftware.smackx.jingleold.packet.JingleTransport.Ice();
jt.addCandidate(new org.jivesoftware.smackx.jingleold.packet.JingleTransport.Ice.Candidate(candidate));
return jt;
}
/**
* Obtain the best remote candidate obtained in the negotiation so far.
*
* @return the bestRemoteCandidate
*/
public TransportCandidate getBestRemoteCandidate() {
ICECandidate result = null;
ArrayList<TransportCandidate> cands = getValidRemoteCandidatesList();
if (!cands.isEmpty()) {
int highest = -1;
ICECandidate chose = null;
for (TransportCandidate transportCandidate : cands) {
if (transportCandidate instanceof ICECandidate) {
ICECandidate icecandidate = (ICECandidate) transportCandidate;
if (icecandidate.getPreference() > highest) {
chose = icecandidate;
highest = icecandidate.getPreference();
}
}
}
result = chose;
}
if (result != null && result.getType().equals("relay"))
LOGGER.fine("Relay Type");
return result;
}
/**
* Return true for ICE candidates.
*/
public boolean acceptableTransportCandidate(TransportCandidate tc, List<TransportCandidate> localCandidates) {
return tc instanceof ICECandidate;
}
}
} |
Java | public static final class RawUdp extends TransportNegotiator {
/**
* Default constructor, with a JingleSession and transport manager.
*
* @param js The Jingle session this negotiation belongs to.
* @param res The transport resolver to use.
*/
public RawUdp(JingleSession js, final TransportResolver res, ContentNegotiator parentNegotiator) {
super(js, res, parentNegotiator);
}
/**
* Get a TransportNegotiator instance.
*/
public org.jivesoftware.smackx.jingleold.packet.JingleTransport getJingleTransport(TransportCandidate bestRemote) {
org.jivesoftware.smackx.jingleold.packet.JingleTransport.RawUdp jt = new org.jivesoftware.smackx.jingleold.packet.JingleTransport.RawUdp();
jt.addCandidate(new org.jivesoftware.smackx.jingleold.packet.JingleTransport.RawUdp.Candidate(bestRemote));
return jt;
}
/**
* Obtain the best common transport candidate obtained in the
* negotiation.
*
* @return the bestRemoteCandidate
*/
public TransportCandidate getBestRemoteCandidate() {
// Hopefully, we only have one validRemoteCandidate
ArrayList<TransportCandidate> cands = getValidRemoteCandidatesList();
if (!cands.isEmpty()) {
LOGGER.fine("RAW CAND");
return (TransportCandidate) cands.get(0);
} else {
LOGGER.fine("No Remote Candidate");
return null;
}
}
/**
* Return true for fixed candidates.
*/
public boolean acceptableTransportCandidate(TransportCandidate tc, List<TransportCandidate> localCandidates) {
return tc instanceof TransportCandidate.Fixed;
}
} |
Java | public static final class Ice extends TransportNegotiator {
/**
* Default constructor, with a JingleSession and transport manager.
*
* @param js The Jingle session this negotiation belongs to.
* @param res The transport manager to use.
*/
public Ice(JingleSession js, final TransportResolver res, ContentNegotiator parentNegotiator) {
super(js, res, parentNegotiator);
}
/**
* Get a TransportNegotiator instance.
*
* @param candidate
*/
public org.jivesoftware.smackx.jingleold.packet.JingleTransport getJingleTransport(TransportCandidate candidate) {
org.jivesoftware.smackx.jingleold.packet.JingleTransport.Ice jt = new org.jivesoftware.smackx.jingleold.packet.JingleTransport.Ice();
jt.addCandidate(new org.jivesoftware.smackx.jingleold.packet.JingleTransport.Ice.Candidate(candidate));
return jt;
}
/**
* Obtain the best remote candidate obtained in the negotiation so far.
*
* @return the bestRemoteCandidate
*/
public TransportCandidate getBestRemoteCandidate() {
ICECandidate result = null;
ArrayList<TransportCandidate> cands = getValidRemoteCandidatesList();
if (!cands.isEmpty()) {
int highest = -1;
ICECandidate chose = null;
for (TransportCandidate transportCandidate : cands) {
if (transportCandidate instanceof ICECandidate) {
ICECandidate icecandidate = (ICECandidate) transportCandidate;
if (icecandidate.getPreference() > highest) {
chose = icecandidate;
highest = icecandidate.getPreference();
}
}
}
result = chose;
}
if (result != null && result.getType().equals("relay"))
LOGGER.fine("Relay Type");
return result;
}
/**
* Return true for ICE candidates.
*/
public boolean acceptableTransportCandidate(TransportCandidate tc, List<TransportCandidate> localCandidates) {
return tc instanceof ICECandidate;
}
} |
Java | @Environment(EnvType.CLIENT)
public final class MaterialInfoImage {
public final int squareSizePixels;
private final int bufferSizeBytes;
private long pointer;
private FloatBuffer floatBuffer;
private boolean dirty = true;
public MaterialInfoImage(int squareSizePixels) {
if (Configurator.enableLifeCycleDebug) {
CanvasMod.LOG.info("Lifecycle Event: MaterialInfoImage init");
}
this.squareSizePixels = squareSizePixels;
bufferSizeBytes = squareSizePixels * squareSizePixels * BUFFER_BYTES_PER_SPRITE;
pointer = MemoryUtil.nmemAlloc(bufferSizeBytes);
floatBuffer = MemoryUtil.memFloatBuffer(pointer, bufferSizeBytes / 4);
}
public void close() {
if (pointer != 0L) {
floatBuffer = null;
MemoryUtil.nmemFree(pointer);
}
pointer = 0L;
}
void set(int materialIndex, float vertexId, float fragmentId, float programFlags, float conditionId) {
assert pointer != 0L : "Image not allocated.";
materialIndex *= 4;
floatBuffer.put(materialIndex, vertexId / MaterialShaderImpl.MAX_SHADERS);
floatBuffer.put(materialIndex + 1, fragmentId / MaterialShaderImpl.MAX_SHADERS);
floatBuffer.put(materialIndex + 2, programFlags / 255f);
floatBuffer.put(materialIndex + 3, conditionId);
dirty = true;
}
public void upload() {
if (dirty) {
dirty = false;
assert pointer != 0L : "Image not allocated.";
GlStateManager.pixelStore(GL11.GL_UNPACK_ROW_LENGTH, 0);
GlStateManager.pixelStore(GL11.GL_UNPACK_SKIP_ROWS, 0);
GlStateManager.pixelStore(GL11.GL_UNPACK_SKIP_PIXELS, 0);
GlStateManager.pixelStore(GL11.GL_UNPACK_ALIGNMENT, 4);
GL21.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL21.GL_RGBA16, squareSizePixels, squareSizePixels, 0, GL21.GL_RGBA, GL21.GL_FLOAT, pointer);
assert CanvasGlHelper.checkError();
}
}
// Four components per material, and four bytes per float
private static final int BUFFER_BYTES_PER_SPRITE = 4 * 4;
} |
Java | public class DeflateStreamTest {
private static void copyStream(Stream src, Stream dest) {
byte[] array = new byte[1024];
int bytes_read;
bytes_read = src.read(array, 0, 1024);
while (bytes_read != 0) {
dest.write(array, 0, bytes_read);
bytes_read = src.read(array, 0, 1024);
}
}
private static boolean compare_buffers(byte[] first, byte[] second, int length) {
if (first.length < length || second.length < length) {
return false;
}
for (int i = 0; i < length; i++) {
if (first[i] != second[i]) {
return false;
}
}
return true;
}
@Test
public void constructor_Null() {
assertThrows(NullPointerException.class, () -> {
DeflateStream ds = new DeflateStream(null, CompressionMode.Compress);
});
}
@Test
public void checkCompressDecompress() throws Exception {
byte[] data = new byte[100000];
for (int i = 0; i < 100000; i++) {
data[i] = (byte) i;
}
MemoryStream dataStream = new MemoryStream(data);
MemoryStream backing = new MemoryStream();
DeflateStream compressing = new DeflateStream(backing, CompressionMode.Compress, true);
copyStream(dataStream, compressing);
dataStream.close();
compressing.close();
backing.seek(0, SeekOrigin.Begin);
DeflateStream decompressing = new DeflateStream(backing, CompressionMode.Decompress);
MemoryStream output = new MemoryStream();
copyStream(decompressing, output);
assertTrue(compare_buffers(data, output.getBuffer(), (int) output.getLength()));
decompressing.close();
output.close();
}
@Test
public void checkDecompress() throws Exception {
MemoryStream backing = new MemoryStream(compressed_data);
DeflateStream decompressing = new DeflateStream(backing, CompressionMode.Decompress);
StreamReader reader = new StreamReader(decompressing);
assertEquals("Hello", reader.readLine());
decompressing.close();
}
@Test
public void checkNullRead() {
assertThrows(NullPointerException.class, () -> {
MemoryStream backing = new MemoryStream(compressed_data);
DeflateStream decompressing = new DeflateStream(backing, CompressionMode.Decompress);
decompressing.read(null, 0, 20);
});
}
@Test
public void checkCompressingRead() {
assertThrows(dotnet4j.io.IOException.class, () -> {
byte[] dummy = new byte[20];
MemoryStream backing = new MemoryStream();
DeflateStream compressing = new DeflateStream(backing, CompressionMode.Compress);
compressing.read(dummy, 0, 20);
});
}
@Test
public void checkRangeRead() {
assertThrows(IndexOutOfBoundsException.class, () -> {
byte[] dummy = new byte[20];
MemoryStream backing = new MemoryStream(compressed_data);
DeflateStream decompressing = new DeflateStream(backing, CompressionMode.Decompress);
decompressing.read(dummy, 10, 20);
});
}
@Test
@Tag("NotWorking")
public void checkInvalidDataRead() {
assertThrows(dotnet4j.io.IOException.class, () -> {
byte[] data = {
0x11, 0x78, (byte) 0x89, (byte) 0x91, (byte) 0xbe, (byte) 0xf3, 0x48, (byte) 0xcd, (byte) 0xc9, (byte) 0xc9,
(byte) 0xe7, 0x02, 0x00
};
byte[] dummy = new byte[20];
MemoryStream backing = new MemoryStream(data);
DeflateStream decompressing = new DeflateStream(backing, CompressionMode.Decompress);
decompressing.read(dummy, 0, 20);
});
}
@Test
public void checkClosedRead() {
assertThrows(dotnet4j.io.IOException.class, () -> {
byte[] dummy = new byte[20];
MemoryStream backing = new MemoryStream(compressed_data);
DeflateStream decompressing = new DeflateStream(backing, CompressionMode.Decompress);
decompressing.close();
decompressing.read(dummy, 0, 20);
});
}
@Test
public void checkClosedFlush() {
assertThrows(dotnet4j.io.IOException.class, () -> {
MemoryStream backing = new MemoryStream();
DeflateStream compressing = new DeflateStream(backing, CompressionMode.Compress);
compressing.close();
compressing.flush();
});
}
@Test
public void checkSeek() {
assertThrows(UnsupportedOperationException.class, () -> {
MemoryStream backing = new MemoryStream(compressed_data);
DeflateStream decompressing = new DeflateStream(backing, CompressionMode.Decompress);
decompressing.seek(20, SeekOrigin.Current);
});
}
@Test
public void checkSetLength() {
assertThrows(UnsupportedOperationException.class, () -> {
MemoryStream backing = new MemoryStream(compressed_data);
DeflateStream decompressing = new DeflateStream(backing, CompressionMode.Decompress);
decompressing.setLength(20);
});
}
@Test
public void checkGetCanSeekProp() throws Exception {
MemoryStream backing = new MemoryStream(compressed_data);
DeflateStream decompress = new DeflateStream(backing, CompressionMode.Decompress);
assertFalse(decompress.canSeek(), "#A1");
assertTrue(backing.canSeek(), "#A2");
decompress.close();
assertFalse(decompress.canSeek(), "#A3");
assertFalse(backing.canSeek(), "#A4");
backing = new MemoryStream();
DeflateStream compress = new DeflateStream(backing, CompressionMode.Compress);
assertFalse(compress.canSeek(), "#B1");
assertTrue(backing.canSeek(), "#B2");
compress.close();
assertFalse(decompress.canSeek(), "#B3");
assertFalse(backing.canSeek(), "#B4");
}
@Test
public void checkGetCanReadProp() throws Exception {
MemoryStream backing = new MemoryStream(compressed_data);
DeflateStream decompress = new DeflateStream(backing, CompressionMode.Decompress);
assertTrue(decompress.canRead(), "#A1");
assertTrue(backing.canRead(), "#A2");
decompress.close();
assertFalse(decompress.canRead(), "#A3");
assertFalse(backing.canRead(), "#A4");
backing = new MemoryStream();
DeflateStream compress = new DeflateStream(backing, CompressionMode.Compress);
assertFalse(compress.canRead(), "#B1");
assertTrue(backing.canRead(), "#B2");
compress.close();
assertFalse(decompress.canRead(), "#B3");
assertFalse(backing.canRead(), "#B4");
}
@Test
public void checkGetCanWriteProp() throws Exception {
MemoryStream backing = new MemoryStream();
DeflateStream decompress = new DeflateStream(backing, CompressionMode.Decompress);
assertFalse(decompress.canWrite(), "#A1");
assertTrue(backing.canWrite(), "#A2");
decompress.close();
assertFalse(decompress.canWrite(), "#A3");
assertFalse(backing.canWrite(), "#A4");
backing = new MemoryStream();
DeflateStream compress = new DeflateStream(backing, CompressionMode.Compress);
assertTrue(compress.canWrite(), "#B1");
assertTrue(backing.canWrite(), "#B2");
compress.close();
assertFalse(decompress.canWrite(), "#B3");
assertFalse(backing.canWrite(), "#B4");
}
@Test
public void checkSetLengthProp() {
assertThrows(UnsupportedOperationException.class, () -> {
MemoryStream backing = new MemoryStream(compressed_data);
DeflateStream decompressing = new DeflateStream(backing, CompressionMode.Decompress);
decompressing.setLength(20);
});
}
@Test
public void checkGetLengthProp() {
assertThrows(UnsupportedOperationException.class, () -> {
MemoryStream backing = new MemoryStream(compressed_data);
DeflateStream decompressing = new DeflateStream(backing, CompressionMode.Decompress);
long length = decompressing.getLength();
});
}
@Test
public void checkGetPositionProp() {
assertThrows(UnsupportedOperationException.class, () -> {
MemoryStream backing = new MemoryStream(compressed_data);
DeflateStream decompressing = new DeflateStream(backing, CompressionMode.Decompress);
long position = decompressing.getPosition();
});
}
@Test
public void disposeTest() throws Exception {
MemoryStream backing = new MemoryStream(compressed_data);
DeflateStream decompress = new DeflateStream(backing, CompressionMode.Decompress);
decompress.close();
decompress.close();
}
// *** WARNING ***
// this library's DeflateStream decompression needs zip header (0x78, 0x9c)
// so spec. is different from original C# DeflateStream
static byte[] compressed_data = {
(byte) 0x78, (byte) 0x9C,
(byte) 0xf3, 0x48, (byte) 0xcd, (byte) 0xc9, (byte) 0xc9, (byte) 0xe7, 0x02, 0x00
};
@Test
public void junkAtTheEnd() throws Exception {
// Write a deflated stream, then some additional data...
try (MemoryStream ms = new MemoryStream()) {
// The compressed stream
try (DeflateStream stream = new DeflateStream(ms, CompressionMode.Compress, true)) {
stream.writeByte((byte) 1);
stream.flush();
}
// Junk
ms.writeByte((byte) 2);
ms.setPosition(0);
// Reading: this should not hang
try (DeflateStream stream = new DeflateStream(ms, CompressionMode.Decompress)) {
byte[] buffer = new byte[512];
int len = stream.read(buffer, 0, buffer.length);
System.err.println(len == 1);
}
}
}
class Bug19313Stream extends MemoryStream {
public Bug19313Stream(byte[] buffer) {
super(buffer);
}
public int read(byte[] buffer, int offset, int count) {
// Thread was blocking when DeflateStream uses a NetworkStream.
// Because the NetworkStream.read calls Socket.Receive that
// blocks the thread waiting for at least a byte to return.
// This assert guarantees that Read is called only when there
// is something to be read.
assertTrue(getPosition() < getLength(), "Trying to read empty stream.");
return super.read(buffer, offset, count);
}
}
@Test
public void bug19313() throws Exception {
byte[] buffer = new byte[512];
try (Stream backing = new Bug19313Stream(compressed_data);
Stream decompressing = new DeflateStream(backing, CompressionMode.Decompress)) {
decompressing.read(buffer, 0, buffer.length);
}
}
} |
Java | public class StockMarketData {
private String stockName;
private float lastPrice;
private float volume;
/**
* A default constructor.
*/
public StockMarketData() {}
/**
* Create A stock market data item based on attributes.
*
* @param stockName stock symbol
* @param lastPrice last handle price
* @param volume handle volume
*/
public StockMarketData(String stockName, float lastPrice, float volume) {
this.stockName = stockName;
this.lastPrice = lastPrice;
this.volume = volume;
}
/**
* Getter method for stock name.
*
* @return stock name
*/
public String getStockName() {
return stockName;
}
/**
* A setter method for stock name.
*
* @param stockName stock symbol
*/
public void setStockName(String stockName) {
this.stockName = stockName;
}
/**
* Getter for the stock price
*
* @return last price
*/
public float getLastPrice() {
return lastPrice;
}
/**
* setter method for the last price.
*
* @param lastPrice latest price
*/
public void setLastPrice(float lastPrice) {
this.lastPrice = lastPrice;
}
/**
* Getter for handle volume.
*
* @return last volume
*/
public float getVolume() {
return volume;
}
/**
* setter method for the handle volume
*
* @param volume last handle volume
*/
public void setVolume(float volume) {
this.volume = volume;
}
} |
Java | public class DatabaseCompositeKeyTable extends DatabaseTable {
private String[] compositeKeyNames;
/**
* Creates an object representing a database table.
*
* <p>NOTE: This does NOT create a table in the database.</p>
*
* @param databaseClient the {@link DatabaseClient} used to query the database.
* @param tableName the name of the database table.
* @param cacheStrategy the cache strategy.
* @param primaryKeyName the table primary key name. Usually {@code _id}.
* @param compositeKeyNames the names of the attributes in the composite key.
*/
public DatabaseCompositeKeyTable(DatabaseClient databaseClient, String tableName, CacheStrategy cacheStrategy, String primaryKeyName, String ... compositeKeyNames) {
super(databaseClient, tableName, cacheStrategy, primaryKeyName);
this.compositeKeyNames = compositeKeyNames;
}
/**
* Returns the composite key values.
* @return the composite key values.
*/
public String[] getCompositeKeyNames() {
return this.compositeKeyNames;
}
/**
* @inheritDoc
*/
@Override
public CompositePrimaryKey getPrimaryKey(JSONObject json) {
String tablePrimaryKey = this.getPrimaryKeyName();
if (tablePrimaryKey == null) {
throw new IllegalStateException(String.format("The table %s has no primary key", this.getTableName()));
}
if (!json.has(tablePrimaryKey)) {
throw new IllegalArgumentException(String.format("JSON object doesn't contains the primary key %s:%n%s", tablePrimaryKey, json.toString(4)));
}
JSONObject primaryKeyValue = json.optJSONObject(tablePrimaryKey);
if (primaryKeyValue == null) {
throw new IllegalArgumentException(String.format("JSON object primary key %s is not a composite key", tablePrimaryKey));
}
if (this.compositeKeyNames == null || this.compositeKeyNames.length <= 0) {
throw new IllegalStateException(String.format("The table %s composite key is invalid", this.getTableName()));
}
Map<String, Object> compositeKeyValueMap = new HashMap<String, Object>();
for (String compositeKeyName : this.compositeKeyNames) {
if (primaryKeyValue.has(compositeKeyName)) {
compositeKeyValueMap.put(compositeKeyName, primaryKeyValue.opt(compositeKeyName));
} else {
throw new IllegalArgumentException(String.format("JSON object primary key %s doesn't contain the composite key %s", tablePrimaryKey, compositeKeyName));
}
}
return this.getPrimaryKey(compositeKeyValueMap);
}
/**
* Returns a primary key object for {@code Map} representing the composite primary key values.
* @param compositeKeyValueMap the primary key values.
* @return a primary key object.
*/
public CompositePrimaryKey getPrimaryKey(Map<String, Object> compositeKeyValueMap) {
return new CompositePrimaryKey(this.getPrimaryKeyName(), compositeKeyValueMap);
}
/**
* Returns a primary key object for composite primary key values.
* @param compositeKeyValues the primary key values.
* @return a primary key object.
*/
public CompositePrimaryKey getPrimaryKey(String ... compositeKeyValues) {
return this.getPrimaryKey((Object[]) compositeKeyValues);
}
/**
* Returns a primary key object for composite primary key values.
* @param compositeKeyValues the primary key values.
* @return a primary key object.
*/
public CompositePrimaryKey getPrimaryKey(Object ... compositeKeyValues) {
if (this.compositeKeyNames.length != compositeKeyValues.length) {
throw new IllegalArgumentException(String.format("Wrong number of composite key value. Expected %d, was %d", this.compositeKeyNames.length, compositeKeyValues.length));
}
Map<String, Object> compositeKeyValueMap = new HashMap<String, Object>();
for (int i=0; i<this.compositeKeyNames.length; i++) {
compositeKeyValueMap.put(compositeKeyNames[i], compositeKeyValues[i]);
}
return new CompositePrimaryKey(this.getPrimaryKeyName(), compositeKeyValueMap);
}
} |
Java | public class memMapFromBuffer {
// todo: this class does not need to 'store' image data. It can simply write based on passed parameters
private final Object temp_img;
private MappedByteBuffer buffer;
public memMapFromBuffer(Image temp_img_, MappedByteBuffer buffer_) {
temp_img = temp_img_;
buffer = buffer_;
}
public memMapFromBuffer(Object temp_img_, MappedByteBuffer buffer_) {
temp_img = temp_img_;
buffer = buffer_;
}
public void writeToMemMap() throws NoImageException, Exception{
byte[] byteimg;
byteimg = convertToByte(temp_img);
if (byteimg == null) {
throw new NoImageException("image not converted to byte[]");
}
try
{
buffer.put(byteimg);
buffer.force();
} catch (Exception ex) {
reporter.set_report_area("EXCEPTION DURING PUT OF BUFFER");
throw ex;
}
}
public void writeToMemMapAt(int position) throws NoImageException {
byte[] byteimg;
byteimg = convertToByte(temp_img);
if (byteimg == null) {
throw new NoImageException("image not converted to byte[]");
}
// long start = System.nanoTime();
try
{
buffer.position(position);
buffer.put(byteimg, 0, byteimg.length);
buffer.force();
} catch (Exception ex) {
reporter.set_report_area("!! Exception !! during write to memmap = "+ex);
throw ex;
}
// long stop = System.nanoTime();
// reporter.set_report_area("Time elapsed for FORCE TO BUFFER (ns): "+Long.toString(stop-start));
}
public void verifyMemMapAt(int position) {
byte[] byteimg;
byteimg = convertToByte(temp_img);
byte[] buf_bytes = new byte[buffer.capacity()];
buffer.position(position);
buffer.get(buf_bytes, 0, buf_bytes.length);
if(!Arrays.equals(byteimg,buf_bytes)) {
reporter.set_report_area("BYTE IMAGE NOT EQUAL");
Constants.data_mismatches += 1;
reporter.set_report_area("Constants mismatches = "+Integer.toString(Constants.data_mismatches));
} else {
reporter.set_report_area("Data verified = "+Integer.toString(Constants.data_mismatches));
}
}
private byte[] convertToByte(Object tempImg_) throws UnsupportedOperationException {
// long start = System.nanoTime();
try
{
byte[] bytes;
Object pixels;
if (tempImg_ instanceof Image) {
Image im = (Image) tempImg_;
pixels = im.getRawPixels();
} else if (tempImg_ instanceof TaggedImage) {
TaggedImage tim = (TaggedImage)tempImg_;
pixels = tim.pix;
} else {
pixels = tempImg_;
}
if (pixels instanceof byte[]) {
bytes = (byte[]) pixels;
} else if (pixels instanceof short[]) {
ShortBuffer shortPixels = ShortBuffer.wrap((short[]) pixels);
ByteBuffer dest = ByteBuffer.allocate(2 * ((short[]) pixels).length).order(ByteOrder.nativeOrder());
ShortBuffer shortDest = dest.asShortBuffer();
shortDest.put(shortPixels);
bytes = dest.array();
}
else {
throw new UnsupportedOperationException(String.format("Unsupported pixel type %s", pixels.getClass().toString()));
}
// long stop = System.nanoTime();
// reporter.set_report_area("Time elapsed for CONVERT TO BYTE (cast) (ns): "+Long.toString(stop-start));
return bytes;
} catch (Exception ex) {
System.out.println(ex);
}
// long stop = System.nanoTime();
// reporter.set_report_area("Time elapsed for CONVERT TO BYTE (null) (ns): "+Long.toString(stop-start));
return null;
}
} |
Java | public class MissingContainerTask extends ReconScmTask {
private static final Logger LOG =
LoggerFactory.getLogger(MissingContainerTask.class);
private ContainerManager containerManager;
private MissingContainersDao missingContainersDao;
private static final long INTERVAL = 5 * 60 * 1000L;
@Inject
public MissingContainerTask(
OzoneStorageContainerManager ozoneStorageContainerManager,
ReconTaskStatusDao reconTaskStatusDao,
MissingContainersDao missingContainersDao) {
super(reconTaskStatusDao);
this.missingContainersDao = missingContainersDao;
this.containerManager = ozoneStorageContainerManager.getContainerManager();
}
public synchronized void run() {
try {
while (canRun()) {
long start = Time.monotonicNow();
long currentTime = System.currentTimeMillis();
final Set<ContainerID> containerIds =
containerManager.getContainerIDs();
containerIds.forEach(containerID ->
processContainer(containerID, currentTime));
recordSingleRunCompletion();
LOG.info("Missing Container task Thread took {} milliseconds for" +
" processing {} containers.", Time.monotonicNow() - start,
containerIds.size());
wait(INTERVAL);
}
} catch (Throwable t) {
LOG.error("Exception in Missing Container task Thread.", t);
}
}
private void processContainer(ContainerID containerID, long currentTime) {
try {
Set<ContainerReplica> containerReplicas =
containerManager.getContainerReplicas(containerID);
// check if a container has 0 replicas or if all available replicas
// are marked UNHEALTHY.
boolean isAllUnhealthy =
containerReplicas.stream().allMatch(replica ->
replica.getState().equals(State.UNHEALTHY));
if (CollectionUtils.isEmpty(containerReplicas) || isAllUnhealthy) {
if (!missingContainersDao.existsById(containerID.getId())) {
LOG.info("Found a missing container with ID {}. Adding it to the " +
"database", containerID.getId());
MissingContainers newRecord =
new MissingContainers(containerID.getId(), currentTime);
missingContainersDao.insert(newRecord);
}
} else {
if (missingContainersDao.existsById(containerID.getId())) {
missingContainersDao.deleteById(containerID.getId());
}
}
} catch (ContainerNotFoundException e) {
LOG.error("Container not found while finding missing containers", e);
}
}
} |
Java | @Persistent
public class DirectoryModule
extends BaseFormatModule
{
/** Directory module version identifier. */
public static final String VERSION = "2.0.0";
/** Directory module release date. */
public static final String RELEASE = "2010-09-10";
/** Directory module rights statement. */
public static final String RIGHTS = "Copyright 2010 by The Regents of the University of California, "
+ "Ithaka Harbors, Inc., and The Board of Trustees of the Leland "
+ "Stanford Junior University. "
+ "Available under the terms of the BSD license.";
/**
* Instantiate a new <code>DirectoryModule</code>.
*
* @param format
* Directory format
* @param FormatModuleAccessor
* persistence manager
*/
public DirectoryModule(Format format,
FormatModuleAccessor formatModuleAccessor) {
super(VERSION, RELEASE, RIGHTS, Scope.Specific, format, formatModuleAccessor);
}
/**
* Instantiate a new <code>DirectoryModule</code>.
*
* @param format
* Directory format
*/
public DirectoryModule(Format format) {
this(format, null);
}
/**
*Instantiate a new <code>DirectoryModule</code>.
*/
public DirectoryModule(){
this(null, null);
}
/**
* Parse a directory source unit.
*
* @param jhove2
* JHOVE2 framework
* @param source
* Directory source unit
* @param input
* Directory source input, which will be null
* @return 0
* @throws EOFException
* If End-of-File is reached reading the source unit
* @throws IOException
* If an I/O exception is raised reading the source unit
* @throws JHOVE2Exception
* @see org.jhove2.module.format.FormatModule#parse(org.jhove2.core.JHOVE2,
* org.jhove2.core.source.Source, org.jhov2.core.io.Input)
*/
@Override
public long parse(JHOVE2 jhove2, Source source, Input input)
throws EOFException, IOException, JHOVE2Exception
{
if (source instanceof DirectorySource) {
List<Source> children =
((DirectorySource) source).getChildSources();
for (Source src : children) {
Input inpt = src.getInput(jhove2);
try {
jhove2.characterize(src, inpt);// will have been persisted by JHOVE2
}
finally {
if (inpt != null) {
inpt.close();
}
}
}
}
return 0;
}
} |
Java | @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
class TestWorkManagerImpl extends WorkManagerImpl implements TestDriver {
private TestScheduler mScheduler;
TestWorkManagerImpl(
@NonNull final Context context,
@NonNull final Configuration configuration) {
// Note: This implies that the call to ForceStopRunnable() actually does nothing.
// This is okay when testing.
// IMPORTANT: Leave the main thread executor as a Direct executor. This is very important.
// Otherwise we subtly change the order of callbacks. onExecuted() will execute after
// a call to StopWorkRunnable(). StopWorkRunnable() removes the pending WorkSpec and
// therefore the call to onExecuted() does not add the workSpecId to the list of
// terminated WorkSpecs. This is because internalWorkState == null.
// Also for PeriodicWorkRequests, Schedulers.schedule() will run before the call to
// onExecuted() and therefore PeriodicWorkRequests will always run twice.
super(
context,
configuration,
new TaskExecutor() {
Executor mSynchronousExecutor = new SynchronousExecutor();
SerialExecutor mSerialExecutor =
new SerialExecutor(configuration.getTaskExecutor());
@Override
public Executor getMainThreadExecutor() {
return mSynchronousExecutor;
}
@Override
public SerialExecutor getSerialTaskExecutor() {
return mSerialExecutor;
}
},
true);
// mScheduler is initialized in createSchedulers() called by super()
getProcessor().addExecutionListener(mScheduler);
}
@Override
@NonNull
public List<Scheduler> createSchedulers(@NonNull Context context,
@NonNull Configuration configuration, @NonNull Trackers trackers) {
mScheduler = new TestScheduler(context);
return Collections.singletonList((Scheduler) mScheduler);
}
@Override
public void setAllConstraintsMet(@NonNull UUID workSpecId) {
mScheduler.setAllConstraintsMet(workSpecId);
}
@Override
public void setInitialDelayMet(@NonNull UUID workSpecId) {
mScheduler.setInitialDelayMet(workSpecId);
}
@Override
public void setPeriodDelayMet(@NonNull UUID workSpecId) {
mScheduler.setPeriodDelayMet(workSpecId);
}
} |
Java | public class ObjectGraphTest extends TestCase {
private ObjectGraphFactory objectGraphFactory;
protected void setUp() throws Exception {
objectGraphFactory = ObjectGraphFactory.getInstance();
}
public void testSingetone() throws Exception{
assertSame(objectGraphFactory, ObjectGraphFactory.getInstance());
}
/**
* Source : gov.nih.nci.cabig.caaers.domain.Study
* Target : gov.nih.nci.cabig.caaers.domain.InvestigationalNewDrug
*/
public void testNavigationPath_Study_IND(){
String sourceObjectType = "gov.nih.nci.cabig.caaers.domain.Study";
String targetObjectType = "gov.nih.nci.cabig.caaers.domain.InvestigationalNewDrug";
NavigationPath np = objectGraphFactory.findNavigationPath(sourceObjectType, targetObjectType);
assertNotNull(np);
}
/**
* Source : gov.nih.nci.cabig.caaers.domain.LocalStudy
* Target : gov.nih.nci.cabig.caaers.domain.InvestigationalNewDrug
*/
public void testNavigationPath_LocalStudy_IND(){
String sourceObjectType = "gov.nih.nci.cabig.caaers.domain.LocalStudy";
String targetObjectType = "gov.nih.nci.cabig.caaers.domain.InvestigationalNewDrug";
NavigationPath np = objectGraphFactory.findNavigationPath(sourceObjectType, targetObjectType);
assertNotNull(np);
}
/**
* Source : gov.nih.nci.cabig.caaers.domain.RemoteStudy
* Target : gov.nih.nci.cabig.caaers.domain.InvestigationalNewDrug
*/
public void testNavigationPath_RemoteStudy_IND(){
String sourceObjectType = "gov.nih.nci.cabig.caaers.domain.RemoteStudy";
String targetObjectType = "gov.nih.nci.cabig.caaers.domain.InvestigationalNewDrug";
NavigationPath np = objectGraphFactory.findNavigationPath(sourceObjectType, targetObjectType);
assertNotNull(np);
}
} |
Java | public class Vreg extends javax.swing.JFrame {
/**
* Creates new form Vreg
*/
public Vreg() {
initComponents();
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenSize.width-890)/2, (screenSize.height-540)/2, 890, 540);
printpaper.setVisible(false);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel3 = new javax.swing.JPanel();
i = new javax.swing.JButton();
refresh = new javax.swing.JButton();
back = new javax.swing.JButton();
exit = new javax.swing.JButton();
label3 = new java.awt.Label();
jPanel1 = new javax.swing.JPanel();
jLabel5 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
vname = new javax.swing.JTextField();
jLabel14 = new javax.swing.JLabel();
vmail = new javax.swing.JTextField();
jLabel15 = new javax.swing.JLabel();
vcon = new javax.swing.JTextField();
jLabel16 = new javax.swing.JLabel();
vaadhaar = new javax.swing.JTextField();
vpass = new javax.swing.JTextField();
jLabel17 = new javax.swing.JLabel();
jLabel18 = new javax.swing.JLabel();
takepic = new javax.swing.JButton();
back5 = new javax.swing.JButton();
printpaper = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jLabel20 = new javax.swing.JLabel();
jLabel21 = new javax.swing.JLabel();
jLabel22 = new javax.swing.JLabel();
jLabel23 = new javax.swing.JLabel();
jLabel24 = new javax.swing.JLabel();
pname = new javax.swing.JLabel();
pid = new javax.swing.JLabel();
pcon = new javax.swing.JLabel();
paadhaar = new javax.swing.JLabel();
pmail = new javax.swing.JLabel();
cpic_p = new javax.swing.JLabel();
jLabel30 = new javax.swing.JLabel();
jLabel31 = new javax.swing.JLabel();
jLabel32 = new javax.swing.JLabel();
pqr = new javax.swing.JLabel();
jLabel33 = new javax.swing.JLabel();
jLabel34 = new javax.swing.JLabel();
jLabel35 = new javax.swing.JLabel();
canphoto = new javax.swing.JLabel();
print = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setResizable(false);
setUndecorated(true);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jPanel3.setBackground(new java.awt.Color(0, 51, 51));
jPanel3.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
i.setBackground(new java.awt.Color(0, 204, 204));
i.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
i.setForeground(new java.awt.Color(0, 153, 153));
i.setIcon(new javax.swing.ImageIcon(getClass().getResource("/vote/ABOUT1.png"))); // NOI18N
i.setBorder(null);
i.setContentAreaFilled(false);
i.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
iMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
iMouseExited(evt);
}
});
i.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
iActionPerformed(evt);
}
});
jPanel3.add(i, new org.netbeans.lib.awtextra.AbsoluteConstraints(738, 11, -1, 39));
refresh.setBackground(new java.awt.Color(0, 204, 204));
refresh.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
refresh.setForeground(new java.awt.Color(0, 153, 153));
refresh.setIcon(new javax.swing.ImageIcon(getClass().getResource("/vote/REFRESH.png"))); // NOI18N
refresh.setBorder(null);
refresh.setContentAreaFilled(false);
refresh.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
refreshMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
refreshMouseExited(evt);
}
});
refresh.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
refreshActionPerformed(evt);
}
});
jPanel3.add(refresh, new org.netbeans.lib.awtextra.AbsoluteConstraints(775, 11, -1, 39));
back.setBackground(new java.awt.Color(0, 204, 204));
back.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
back.setForeground(new java.awt.Color(0, 153, 153));
back.setIcon(new javax.swing.ImageIcon(getClass().getResource("/vote/BACK.png"))); // NOI18N
back.setBorder(null);
back.setContentAreaFilled(false);
back.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
backMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
backMouseExited(evt);
}
});
back.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
backActionPerformed(evt);
}
});
jPanel3.add(back, new org.netbeans.lib.awtextra.AbsoluteConstraints(812, 11, -1, 39));
exit.setBackground(new java.awt.Color(0, 204, 204));
exit.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
exit.setForeground(new java.awt.Color(0, 153, 153));
exit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/vote/EXIT.png"))); // NOI18N
exit.setBorder(null);
exit.setContentAreaFilled(false);
exit.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
exitMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
exitMouseExited(evt);
}
});
exit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitActionPerformed(evt);
}
});
jPanel3.add(exit, new org.netbeans.lib.awtextra.AbsoluteConstraints(849, 11, -1, 39));
label3.setFont(new java.awt.Font("DotumChe", 0, 14)); // NOI18N
label3.setForeground(new java.awt.Color(204, 204, 0));
label3.setText("VOTER REGESTRATION FORM");
jPanel3.add(label3, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 11, 222, -1));
getContentPane().add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 890, 50));
jPanel1.setBackground(new java.awt.Color(0, 102, 102));
jLabel5.setFont(new java.awt.Font("SansSerif", 0, 18)); // NOI18N
jLabel5.setForeground(new java.awt.Color(0, 204, 255));
jLabel5.setText("VOTER REGESTRATION");
jLabel13.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel13.setForeground(new java.awt.Color(255, 255, 255));
jLabel13.setText("NAME");
vname.setBackground(new java.awt.Color(0, 102, 102));
vname.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
vname.setForeground(new java.awt.Color(204, 204, 0));
vname.setName("adminid");
vname.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
vnameActionPerformed(evt);
}
});
jLabel14.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel14.setForeground(new java.awt.Color(255, 255, 255));
jLabel14.setText("E-MAIL");
vmail.setBackground(new java.awt.Color(0, 102, 102));
vmail.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
vmail.setForeground(new java.awt.Color(204, 204, 0));
vmail.setName("adminid");
vmail.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
vmailActionPerformed(evt);
}
});
jLabel15.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel15.setForeground(new java.awt.Color(255, 255, 255));
jLabel15.setText("CONTACT");
vcon.setBackground(new java.awt.Color(0, 102, 102));
vcon.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
vcon.setForeground(new java.awt.Color(204, 204, 0));
vcon.setName("adminid");
vcon.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
vconActionPerformed(evt);
}
});
jLabel16.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel16.setForeground(new java.awt.Color(255, 255, 255));
jLabel16.setText("AADHAAR NO");
vaadhaar.setBackground(new java.awt.Color(0, 102, 102));
vaadhaar.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
vaadhaar.setForeground(new java.awt.Color(204, 204, 0));
vaadhaar.setName("adminid");
vaadhaar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
vaadhaarActionPerformed(evt);
}
});
vpass.setBackground(new java.awt.Color(0, 102, 102));
vpass.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
vpass.setForeground(new java.awt.Color(204, 204, 0));
vpass.setName("adminid");
vpass.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
vpassActionPerformed(evt);
}
});
jLabel17.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel17.setForeground(new java.awt.Color(255, 255, 255));
jLabel17.setText("4 DIGIT PASSWORD");
jLabel18.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel18.setForeground(new java.awt.Color(255, 255, 255));
jLabel18.setText("CANDIDATE PHOTO");
takepic.setBackground(new java.awt.Color(0, 204, 204));
takepic.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
takepic.setForeground(new java.awt.Color(153, 255, 102));
takepic.setText("TAKE PICTURE");
takepic.setBorder(javax.swing.BorderFactory.createEtchedBorder());
takepic.setContentAreaFilled(false);
takepic.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
takepicMouseEntered(evt);
}
});
takepic.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
takepicActionPerformed(evt);
}
});
back5.setBackground(new java.awt.Color(0, 204, 204));
back5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
back5.setForeground(new java.awt.Color(51, 204, 255));
back5.setText("GENERATE TOKEN");
back5.setBorder(javax.swing.BorderFactory.createEtchedBorder());
back5.setContentAreaFilled(false);
back5.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
back5MouseClicked(evt);
}
});
back5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
back5ActionPerformed(evt);
}
});
printpaper.setBackground(new java.awt.Color(204, 255, 204));
printpaper.setLayout(null);
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/vote/logomini.png"))); // NOI18N
printpaper.add(jLabel3);
jLabel3.setBounds(10, 0, 100, 60);
jLabel20.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel20.setText("NAME");
printpaper.add(jLabel20);
jLabel20.setBounds(170, 70, 88, 16);
jLabel21.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel21.setText("E-MAIL");
printpaper.add(jLabel21);
jLabel21.setBounds(170, 160, 88, 15);
jLabel22.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel22.setText("CONTACT");
printpaper.add(jLabel22);
jLabel22.setBounds(170, 120, 88, 15);
jLabel23.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel23.setText("AADHAAR NO");
printpaper.add(jLabel23);
jLabel23.setBounds(170, 140, 88, 15);
jLabel24.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel24.setText("VOTER ID");
printpaper.add(jLabel24);
jLabel24.setBounds(170, 90, 88, 15);
pname.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
pname.setText("NAME");
printpaper.add(pname);
pname.setBounds(270, 70, 197, 16);
pid.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
pid.setText("VOTER ID");
printpaper.add(pid);
pid.setBounds(270, 90, 197, 15);
pcon.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
pcon.setText("CONTACT");
printpaper.add(pcon);
pcon.setBounds(270, 120, 197, 13);
paadhaar.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
paadhaar.setText("AADHAAR NO");
printpaper.add(paadhaar);
paadhaar.setBounds(270, 140, 197, 13);
pmail.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
pmail.setText("E-MAIL");
printpaper.add(pmail);
pmail.setBounds(270, 160, 197, 13);
cpic_p.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
printpaper.add(cpic_p);
cpic_p.setBounds(27, 71, 120, 101);
jLabel30.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel30.setText("VOTING TITLE");
printpaper.add(jLabel30);
jLabel30.setBounds(141, 11, 366, 15);
jLabel31.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
jLabel31.setText("VOTING SUBTITLE");
printpaper.add(jLabel31);
jLabel31.setBounds(141, 32, 366, 13);
jLabel32.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel32.setText("THIS IS A COMPUTER GENERATED QR CODE");
printpaper.add(jLabel32);
jLabel32.setBounds(167, 196, 321, 10);
pqr.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
printpaper.add(pqr);
pqr.setBounds(20, 190, 130, 100);
jLabel33.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel33.setText("FOR PASSWORD AUTHENTICATION.");
printpaper.add(jLabel33);
jLabel33.setBounds(167, 212, 321, 15);
jLabel34.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel34.setText("THIS IS A COMPUTER GENERATED QR CODE");
printpaper.add(jLabel34);
jLabel34.setBounds(167, 238, 321, 15);
jLabel35.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel35.setText("FOR PASSWORD AUTHENTICATION.");
printpaper.add(jLabel35);
jLabel35.setBounds(167, 259, 321, 10);
canphoto.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
print.setBackground(new java.awt.Color(0, 204, 204));
print.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
print.setForeground(new java.awt.Color(51, 204, 255));
print.setText("PRINT");
print.setBorder(javax.swing.BorderFactory.createEtchedBorder());
print.setContentAreaFilled(false);
print.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
printMouseClicked(evt);
}
});
print.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
printActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(canphoto, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(takepic, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(jLabel18))))
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 354, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabel17, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel16, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel15, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel14, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel13, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(vpass, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(10, 10, 10)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(vname, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(vmail, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(vcon, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(vaadhaar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE))))))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(back5, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(print, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 243, Short.MAX_VALUE))
.addComponent(printpaper, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel5)
.addGap(24, 24, 24)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel13, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(vname, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel14, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(vmail, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel15, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(vcon, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel16, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(vaadhaar, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel17, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(vpass, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(26, 49, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(canphoto, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel18, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(takepic, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addComponent(printpaper, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(back5, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(print, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(55, 55, 55))
);
getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 50, 890, 490));
pack();
}// </editor-fold>//GEN-END:initComponents
private void iMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_iMouseEntered
// TODO add your handling code here:
i.setSize(38, 33);
}//GEN-LAST:event_iMouseEntered
private void iMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_iMouseExited
// TODO add your handling code here:
i.setSize(30, 33);
}//GEN-LAST:event_iMouseExited
private void iActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_iActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_iActionPerformed
private void refreshMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_refreshMouseEntered
// TODO add your handling code here:
refresh.setSize(38, 33);
}//GEN-LAST:event_refreshMouseEntered
private void refreshMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_refreshMouseExited
// TODO add your handling code here:
refresh.setSize(30, 33);
}//GEN-LAST:event_refreshMouseExited
private void refreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshActionPerformed
// TODO add your handling code here:
Vreg vrg = new Vreg();
vrg.setVisible(true);
dispose();
}//GEN-LAST:event_refreshActionPerformed
private void backMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_backMouseEntered
// TODO add your handling code here:
back.setSize(38, 33);
}//GEN-LAST:event_backMouseEntered
private void backMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_backMouseExited
// TODO add your handling code here:
back.setSize(30, 33);
}//GEN-LAST:event_backMouseExited
private void backActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backActionPerformed
// TODO add your handling code here:
admin ad = new admin();
ad.setVisible(true);
dispose();
}//GEN-LAST:event_backActionPerformed
private void exitMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_exitMouseEntered
exit.setSize(38, 33);
}//GEN-LAST:event_exitMouseEntered
private void exitMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_exitMouseExited
// TODO add your handling code here:
exit.setSize(30, 33);
}//GEN-LAST:event_exitMouseExited
private void exitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitActionPerformed
dispose();
}//GEN-LAST:event_exitActionPerformed
private void vnameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_vnameActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_vnameActionPerformed
private void vmailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_vmailActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_vmailActionPerformed
private void vconActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_vconActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_vconActionPerformed
private void vaadhaarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_vaadhaarActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_vaadhaarActionPerformed
private void vpassActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_vpassActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_vpassActionPerformed
private void takepicActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_takepicActionPerformed
// TODO add your handling code here:
audioclass ac = new audioclass();
Webcam webcam = Webcam.getDefault();
ac.lkcamera.play();
webcam.open();
ImageIcon icon2 = new ImageIcon(webcam.getImage());
canphoto.setIcon(icon2);
ac.btncrf.play();
webcam.close();
ac.rtk.play();
}//GEN-LAST:event_takepicActionPerformed
private void back5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_back5ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_back5ActionPerformed
private void back5MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_back5MouseClicked
printpaper.setVisible(true);
cpic_p.setIcon(canphoto.getIcon());
pname.setText(vname.getText());
pcon.setText(vcon.getText());
paadhaar.setText(vaadhaar.getText());
pmail.setText(vmail.getText());
pid.setText("SVS."+vmail.getText());
String QRpass = "SVS20"+pcon.getText()+vpass.getText();
try
{
File file = new File("C:\\SVS1.0\\data\\voter\\qrcode\\"+"SVS20"+pcon.getText()+vpass.getText()+"defQR.jpg");
ByteArrayOutputStream out = QRCode.from(QRpass).to(ImageType.JPG).stream();
try (FileOutputStream fos = new FileOutputStream(file))
{
fos.write(out.toByteArray());
}
ImageIcon icqr = new ImageIcon("C:\\SVS1.0\\data\\voter\\qrcode\\"+"SVS20"+pcon.getText()+vpass.getText()+"defQR.jpg");
pqr.setIcon(icqr);
System.out.println("QR generation completed");
}
catch(Exception e){}
}//GEN-LAST:event_back5MouseClicked
private void takepicMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_takepicMouseEntered
// TODO add your handling code here:
audioclass ac = new audioclass();
ac.scam.play();
}//GEN-LAST:event_takepicMouseEntered
private void printMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_printMouseClicked
try {
// TODO add your handling code here:
Rectangle screenrect2 = new Rectangle(printpaper.getLocationOnScreen().x, printpaper.getLocationOnScreen().y, printpaper.getWidth(), printpaper.getHeight());
BufferedImage capture2 = new Robot().createScreenCapture(screenrect2);
try {
ImageIO.write(capture2,"png", new File("C:\\SVS1.0\\data\\voter\\token\\"+vcon.getText()+"voter"+vname.getText()+"token"+".png"));
audioclass ac = new audioclass();
ac.tkprntd.play();
} catch (IOException ex) {
Logger.getLogger(Vreg.class.getName()).log(Level.SEVERE, null, ex);
}
JOptionPane.showMessageDialog(this,"TOKEN SAVED");
} catch (AWTException ex) {
Logger.getLogger(Vreg.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_printMouseClicked
private void printActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_printActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_printActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the
* default look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Vreg.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Vreg.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Vreg.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Vreg.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Vreg().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton back;
private javax.swing.JButton back5;
private javax.swing.JLabel canphoto;
private javax.swing.JLabel cpic_p;
private javax.swing.JButton exit;
private javax.swing.JButton i;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel20;
private javax.swing.JLabel jLabel21;
private javax.swing.JLabel jLabel22;
private javax.swing.JLabel jLabel23;
private javax.swing.JLabel jLabel24;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel30;
private javax.swing.JLabel jLabel31;
private javax.swing.JLabel jLabel32;
private javax.swing.JLabel jLabel33;
private javax.swing.JLabel jLabel34;
private javax.swing.JLabel jLabel35;
private javax.swing.JLabel jLabel5;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel3;
private java.awt.Label label3;
private javax.swing.JLabel paadhaar;
private javax.swing.JLabel pcon;
private javax.swing.JLabel pid;
private javax.swing.JLabel pmail;
private javax.swing.JLabel pname;
private javax.swing.JLabel pqr;
private javax.swing.JButton print;
private javax.swing.JPanel printpaper;
private javax.swing.JButton refresh;
private javax.swing.JButton takepic;
private javax.swing.JTextField vaadhaar;
private javax.swing.JTextField vcon;
private javax.swing.JTextField vmail;
private javax.swing.JTextField vname;
private javax.swing.JTextField vpass;
// End of variables declaration//GEN-END:variables
} |
Java | public class SentToVO {
@SerializedName("send-to-id")
private String sentToId;
@SerializedName("sent-date")
private String sentDate;
@SerializedName("acted-user")
private ActedUserVO actedUser;
@SerializedName("received-user")
private ActedUserVO recievedUser;
public String getSentToId() {
return sentToId;
}
public String getSentDate() {
return sentDate;
}
public ActedUserVO getActedUser() {
return actedUser;
}
public ActedUserVO getRecievedUser() {
return recievedUser;
}
} |
Java | class IssuerCommonInput {
private GroupElement gamma;
private ZqElement y0;
public IssuerCommonInput() {
}
public GroupElement getGamma() {
return gamma;
}
public void setGamma(GroupElement gamma) {
this.gamma = gamma;
}
public ZqElement getY0() {
return y0;
}
public void setY0(ZqElement y0) {
this.y0 = y0;
}
} |
Java | public final class Preconditions {
public static final String EMPTY_ARGUMENTS = "";
private Preconditions() {
// Non-instantiable.
}
/**
* Ensures the truth of an expression.
*/
public static void checkArgument(boolean expression) {
checkArgumentInternal(expression, true, "Illegal argument.", EMPTY_ARGUMENTS);
}
/**
* Ensures the truth of an expression, with an error message.
*/
public static void checkArgument(boolean expression, String errorMessage) {
checkArgumentInternal(expression, true, errorMessage, EMPTY_ARGUMENTS);
}
/**
* Ensures the truth of an expression, with an error message that takes arguments.
*/
public static void checkArgument(boolean expression,
String errorMessageTemplate, Object... errorMessageArgs) {
checkArgumentInternal(expression, true, errorMessageTemplate, errorMessageArgs);
}
/**
* Ensures the truth of an expression involving the state of the caller.
*/
public static void checkState(boolean expression) {
checkStateInternal(expression, true, "Illegal state.", EMPTY_ARGUMENTS);
}
/**
* Ensures the truth of an expression involving the state of the caller, with an error message.
*/
public static void checkState(boolean expression, String errorMessage) {
checkStateInternal(expression, true, errorMessage, EMPTY_ARGUMENTS);
}
/**
* Ensures the truth of an expression involving the state of the caller, with an error message
* that takes arguments.
*/
public static void checkState(boolean expression,
String errorMessageTemplate, Object... errorMessageArgs) {
checkStateInternal(expression, true, errorMessageTemplate, errorMessageArgs);
}
/**
* Ensures that an object reference is not null.
*/
public static void checkNotNull(Object reference) {
checkNotNullInternal(reference, true, "Object can not be null.", EMPTY_ARGUMENTS);
}
/**
* Ensures that an object reference is not null, with an error message.
*/
public static void checkNotNull(Object reference, String errorMessage) {
checkNotNullInternal(reference, true, errorMessage, EMPTY_ARGUMENTS);
}
/**
* Ensures that an object reference is not null, with an error message that takes arguments.
*/
public static void checkNotNull(Object reference,
String errorMessageTemplate, Object... errorMessageArgs) {
checkNotNullInternal(reference, true, errorMessageTemplate, errorMessageArgs);
}
/**
* Ensures that the current thread is the UI thread.
*/
public static void checkUiThread() {
checkUiThreadInternal(true, "This method must be called from the UI thread.",
EMPTY_ARGUMENTS);
}
/**
* Ensures that the current thread is the UI thread, with an error message.
*/
public static void checkUiThread(String errorMessage) {
checkUiThreadInternal(true, errorMessage, EMPTY_ARGUMENTS);
}
/**
* Ensures that the current thread is the UI thread, with an error message that takes
* arguments.
*/
public static void checkUiThread(String errorMessageTemplate, Object... errorMessageArgs) {
checkUiThreadInternal(true, errorMessageTemplate, errorMessageArgs);
}
/**
* Preconditions checks that avoid throwing and exception in release mode. These versions return
* a boolean which the caller should check.
*/
public final static class NoThrow {
private static volatile boolean sStrictMode = false;
/**
* Enables or disables strict mode.
*
* In strict mode, this class will throw anyway. For example, you could set strict mode to
* BuildConfig.DEBUG to always get exceptions when in the IDE.
*
* @param strictMode Whether to use strict mode.
*/
public static void setStrictMode(boolean strictMode) {
sStrictMode = strictMode;
}
/**
* Ensures the truth of an expression.
*/
public static boolean checkArgument(boolean expression) {
return checkArgumentInternal(expression, sStrictMode, "Illegal argument",
EMPTY_ARGUMENTS);
}
/**
* Ensures the truth of an expression, with an error message.
*/
public static boolean checkArgument(boolean expression, String errorMessage) {
return checkArgumentInternal(expression, sStrictMode, errorMessage, EMPTY_ARGUMENTS);
}
/**
* Ensures the truth of an expression, with an error message that takes arguments.
*/
public static boolean checkArgument(boolean expression,
String errorMessageTemplate, Object... errorMessageArgs) {
return checkArgumentInternal(expression, sStrictMode, errorMessageTemplate,
errorMessageArgs);
}
/**
* Ensures the truth of an expression involving the state of the caller.
*/
public static boolean checkState(boolean expression) {
return checkStateInternal(expression, sStrictMode, "Illegal state.", EMPTY_ARGUMENTS);
}
/**
* Ensures the truth of an expression involving the state of the caller, with an error
* message.
*/
public static boolean checkState(boolean expression, String errorMessage) {
return checkStateInternal(expression, sStrictMode, errorMessage, EMPTY_ARGUMENTS);
}
/**
* Ensures the truth of an expression involving the state of the caller, with an error
* message that takes arguments.
*/
public static boolean checkState(boolean expression,
String errorMessageTemplate, Object... errorMessageArgs) {
return checkStateInternal(expression, sStrictMode, errorMessageTemplate,
errorMessageArgs);
}
/**
* Ensures that an object reference is not null.
*/
public static boolean checkNotNull(Object reference) {
return checkNotNullInternal(reference, sStrictMode, "Object can not be null.",
EMPTY_ARGUMENTS);
}
/**
* Ensures that an object reference is not null, with an error message.
*/
public static boolean checkNotNull(Object reference, String errorMessage) {
return checkNotNullInternal(reference, sStrictMode, errorMessage, EMPTY_ARGUMENTS);
}
/**
* Ensures that an object reference is not null, with an error message that takes
* arguments.
*/
public static boolean checkNotNull(Object reference,
String errorMessageTemplate, Object... errorMessageArgs) {
return checkNotNullInternal(reference, sStrictMode, errorMessageTemplate,
errorMessageArgs);
}
/**
* Ensures that the current thread is the UI thread.
*/
public static boolean checkUiThread() {
return checkUiThreadInternal(sStrictMode,
"This method must be called from the UI thread.", EMPTY_ARGUMENTS);
}
/**
* Ensures that the current thread is the UI thread, with an error message.
*/
public static boolean checkUiThread(String errorMessage) {
return checkUiThreadInternal(sStrictMode, errorMessage, EMPTY_ARGUMENTS);
}
/**
* Ensures that the current thread is the UI thread, with an error message that takes
* arguments.
*/
public static boolean checkUiThread(String errorMessageTemplate,
Object... errorMessageArgs) {
return checkUiThreadInternal(false, errorMessageTemplate, errorMessageArgs);
}
}
private static boolean checkArgumentInternal(boolean expression, boolean allowThrow,
String errorMessageTemplate, Object... errorMessageArgs) {
if (expression) {
return true;
}
String errorMessage = format(errorMessageTemplate, errorMessageArgs);
if (allowThrow) {
throw new IllegalArgumentException(errorMessage);
}
MoPubLog.log(CUSTOM, errorMessage);
return false;
}
private static boolean checkStateInternal(boolean expression, boolean allowThrow,
String errorMessageTemplate, Object... errorMessageArgs) {
if (expression) {
return true;
}
String errorMessage = format(errorMessageTemplate, errorMessageArgs);
if (allowThrow) {
throw new IllegalStateException(errorMessage);
}
MoPubLog.log(CUSTOM, errorMessage);
return false;
}
private static boolean checkNotNullInternal(Object reference, boolean allowThrow,
String errorMessageTemplate, Object... errorMessageArgs) {
if (reference != null) {
return true;
}
String errorMessage = format(errorMessageTemplate, errorMessageArgs);
if (allowThrow) {
throw new NullPointerException(errorMessage);
}
MoPubLog.log(CUSTOM, errorMessage);
return false;
}
private static boolean checkUiThreadInternal(boolean allowThrow,
String errorMessageTemplate, Object... errorMessageArgs) {
// Check that the main looper is the current looper.
if (Looper.getMainLooper().equals(Looper.myLooper())) {
return true;
}
String errorMessage = format(errorMessageTemplate, errorMessageArgs);
if (allowThrow) {
throw new IllegalStateException(errorMessage);
}
MoPubLog.log(CUSTOM, errorMessage);
return false;
}
/**
* Substitutes each {@code %s} in {@code template} with an argument. These are matched by
* position - the first {@code %s} gets {@code args[0]}, etc.
*/
private static String format(String template, Object... args) {
template = String.valueOf(template); // null -> "null"
try {
return String.format(template, args);
} catch (IllegalFormatException exception) {
MoPubLog.log(CUSTOM, "MoPub preconditions had a format exception: " + exception.getMessage());
return template;
}
}
} |
Java | public final static class NoThrow {
private static volatile boolean sStrictMode = false;
/**
* Enables or disables strict mode.
*
* In strict mode, this class will throw anyway. For example, you could set strict mode to
* BuildConfig.DEBUG to always get exceptions when in the IDE.
*
* @param strictMode Whether to use strict mode.
*/
public static void setStrictMode(boolean strictMode) {
sStrictMode = strictMode;
}
/**
* Ensures the truth of an expression.
*/
public static boolean checkArgument(boolean expression) {
return checkArgumentInternal(expression, sStrictMode, "Illegal argument",
EMPTY_ARGUMENTS);
}
/**
* Ensures the truth of an expression, with an error message.
*/
public static boolean checkArgument(boolean expression, String errorMessage) {
return checkArgumentInternal(expression, sStrictMode, errorMessage, EMPTY_ARGUMENTS);
}
/**
* Ensures the truth of an expression, with an error message that takes arguments.
*/
public static boolean checkArgument(boolean expression,
String errorMessageTemplate, Object... errorMessageArgs) {
return checkArgumentInternal(expression, sStrictMode, errorMessageTemplate,
errorMessageArgs);
}
/**
* Ensures the truth of an expression involving the state of the caller.
*/
public static boolean checkState(boolean expression) {
return checkStateInternal(expression, sStrictMode, "Illegal state.", EMPTY_ARGUMENTS);
}
/**
* Ensures the truth of an expression involving the state of the caller, with an error
* message.
*/
public static boolean checkState(boolean expression, String errorMessage) {
return checkStateInternal(expression, sStrictMode, errorMessage, EMPTY_ARGUMENTS);
}
/**
* Ensures the truth of an expression involving the state of the caller, with an error
* message that takes arguments.
*/
public static boolean checkState(boolean expression,
String errorMessageTemplate, Object... errorMessageArgs) {
return checkStateInternal(expression, sStrictMode, errorMessageTemplate,
errorMessageArgs);
}
/**
* Ensures that an object reference is not null.
*/
public static boolean checkNotNull(Object reference) {
return checkNotNullInternal(reference, sStrictMode, "Object can not be null.",
EMPTY_ARGUMENTS);
}
/**
* Ensures that an object reference is not null, with an error message.
*/
public static boolean checkNotNull(Object reference, String errorMessage) {
return checkNotNullInternal(reference, sStrictMode, errorMessage, EMPTY_ARGUMENTS);
}
/**
* Ensures that an object reference is not null, with an error message that takes
* arguments.
*/
public static boolean checkNotNull(Object reference,
String errorMessageTemplate, Object... errorMessageArgs) {
return checkNotNullInternal(reference, sStrictMode, errorMessageTemplate,
errorMessageArgs);
}
/**
* Ensures that the current thread is the UI thread.
*/
public static boolean checkUiThread() {
return checkUiThreadInternal(sStrictMode,
"This method must be called from the UI thread.", EMPTY_ARGUMENTS);
}
/**
* Ensures that the current thread is the UI thread, with an error message.
*/
public static boolean checkUiThread(String errorMessage) {
return checkUiThreadInternal(sStrictMode, errorMessage, EMPTY_ARGUMENTS);
}
/**
* Ensures that the current thread is the UI thread, with an error message that takes
* arguments.
*/
public static boolean checkUiThread(String errorMessageTemplate,
Object... errorMessageArgs) {
return checkUiThreadInternal(false, errorMessageTemplate, errorMessageArgs);
}
} |
Java | class Pipeline extends OpenCvPipeline {
Mat matrix = new Mat();
Mat croppedImage = new Mat();
Mat croppedImageUpper = new Mat();
Mat croppedImageLower = new Mat();
Mat HSVImage = new Mat();
Mat mergedImage = new Mat();
Mat maskedImage = new Mat();
Mat blackAndWhite = new Mat();
Mat thresholded = new Mat();
Mat contourImage = new Mat();
final Scalar BLUE = new Scalar(0, 0, 255);
final Scalar GREEN = new Scalar(0, 255, 0);
final Point REGION1_TOPLEFT_ANCHOR_POINT = new Point(300, 300);
static final int REGION_WIDTH = 150;
static final int REGION_HEIGHT = 150;
final int FOUR_RING_THRESHOLD = 140;
final int ONE_RING_THRESHOLD = 130;
/*Point region1_pointA = new Point(
REGION1_TOPLEFT_ANCHOR_POINT.x,
REGION1_TOPLEFT_ANCHOR_POINT.y);
Point region1_pointB = new Point(
REGION1_TOPLEFT_ANCHOR_POINT.x + REGION_WIDTH,
REGION1_TOPLEFT_ANCHOR_POINT.y + REGION_HEIGHT);*/
Point region1_pointA = new Point(camX, camY);
Point region1_pointB = new Point(camX + camWidth, camY + camHeight);
/*Point region1_pointA = new Point(300, 250);
Point region1_pointB = new Point(450, 400);*/
Mat region1_Cb;
Mat YCrCb = new Mat();
Mat Cb = new Mat();
int avg1;
void inputToCb(Mat input) {
Imgproc.cvtColor(input, YCrCb, Imgproc.COLOR_RGB2YCrCb);
Core.extractChannel(YCrCb, Cb, 1);
}
@Override
public void init(Mat firstFrame) {
inputToCb(firstFrame);
region1_Cb = Cb.submat(new Rect(region1_pointA, region1_pointB));
}
@Override
public Mat processFrame(Mat input) {
inputToCb(input);
avg1 = (int) Core.mean(region1_Cb).val[0];
Imgproc.rectangle(
input, // Buffer to draw on
region1_pointA, // First point which defines the rectangle
region1_pointB, // Second point which defines the rectangle
BLUE, // The color the rectangle is drawn in
2); // Thickness of the rectangle lines
numRings = -1; // Record our analysis
if(avg1 > FOUR_RING_THRESHOLD) {
numRings = 4;
} else if (avg1 > ONE_RING_THRESHOLD) {
numRings = 1;
} else{
numRings = 0;
}
opMode.telemetry.addData("value",avg1 );
opMode.telemetry.addData("rings", numRings);
/* opMode.telemetry.addData("x", camX);
opMode.telemetry.addData("y", camY);
opMode.telemetry.addData("w", camWidth);
opMode.telemetry.addData("h", camHeight);*/
opMode.telemetry.update();
Imgproc.rectangle(
input, // Buffer to draw on
region1_pointA, // First point which defines the rectangle
region1_pointB, // Second point which defines the rectangle
GREEN, // The color the rectangle is drawn in
-1); // Negative thickness means solid fill
return input;
}
/*public Mat processFrame(Mat input){
// Imgproc.cvtColor(input, gray, Imgproc.COLOR_BGR2GRAY);
// cropping the input to the following dimensions
// x: 0 -> 720
// y: 0 -> 1280
// (0, 0): top right
// lets say the orange rings are around hex 184, 104, 0
// if robot is located on right red strip, the rings are located near the top of the middle.
Rect imageCrop = new Rect(new Point(250, 160), new Point(410, 440));
croppedImage = new Mat(input, imageCrop);
Rect upperCrop = new Rect(new Point(330,160), new Point(410, 440));
croppedImageUpper = new Mat(input, upperCrop);
Rect lowerCrop = new Rect(new Point(250, 160), new Point(330, 440));
croppedImageLower = new Mat(input, lowerCrop);
double avgR = 0;
double avgG = 0;
double avgB = 0;
int numPixels = 0;
Imgproc.cvtColor(croppedImage, HSVImage, Imgproc.COLOR_BGR2HSV);
// https://stackoverflow.com/questions/48528754/what-are-recommended-color-spaces-for-detecting-orange-color-in-open-cv
// h value: [8, 25]
// s value: [100, 255]
// v value: [20, 255]
//Core.inRange(HSVImage, new Scalar(8, 100, 20), new Scalar(25, 255, 255), maskedImage);
ArrayList<Mat> split = new ArrayList<Mat>();
// from my understand, split gives an arraylist of 3 matrices, each that just contain scalars for each channel
Core.split(HSVImage, split);
// https://stackoverflow.com/questions/38998402/opencv-split-and-change-value-in-that-channel-in-android
// add to saturation (S of HSV)
Mat changedSChannel = new Mat();
Core.add(split.get(1), new Scalar(50), changedSChannel);
split.set(1, changedSChannel);
// https://stackoverflow.com/questions/52107379/intensify-or-increase-saturation-of-an-image
Core.merge(split, mergedImage);
*//*for (int y = 0; y < croppedImage.rows(); y += 2) {
for (int x = 0; x < croppedImage.cols(); x += 2) {
double[] rgb = croppedImage.get(y, x); // NOTE:: apparently, the double[] returned by get is [r, g, b]
avgR += rgb[0];
avgG += rgb[1];
avgB += rgb[2];
numPixels++;
}
}
avgR /= numPixels;
avgG /= numPixels;
avgB /= numPixels;
// converting the cropped image to black and whtie and storing it in blackAndWhite
// Imgproc.cvtColor(croppedImage, blackAndWhite, Imgproc.COLOR_BGR2GRAY);
opMode.telemetry.addData("r", avgR);
opMode.telemetry.addData("g", avgG);
opMode.telemetry.addData("b", avgB);
opMode.telemetry.addData("all averages", (avgR + avgG + avgB) / 3);
opMode.telemetry.addData("numRings", numRings);
opMode.telemetry.update();*//*
*//* for (int y = 0; y < croppedImageUpper.rows(); y += 2) {
for (int x = 0; x < croppedImageUpper.cols(); x += 2) {
double[] rgb = croppedImageUpper.get(y, x); // NOTE:: apparently, the double[] returned by get is [r, g, b]
avgR += rgb[0];
avgG += rgb[1];
avgB += rgb[2];
numPixels++;
}
}
avgR /= numPixels;
avgG /= numPixels;
avgB /= numPixels;
// converting the cropped image to black and whtie and storing it in blackAndWhite
// Imgproc.cvtColor(croppedImage, blackAndWhite, Imgproc.COLOR_BGR2GRAY);
opMode.telemetry.addData("r", avgR);
opMode.telemetry.addData("g", avgG);
opMode.telemetry.addData("b", avgB);
opMode.telemetry.addData("all averages", (avgR + avgG + avgB) / 3);
//opMode.telemetry.addData("numRings", numRings);
//---------------------------------------------------------------------------------------------------------------------
avgR = 0;
avgB = 0;
avgG = 0;
for (int y = 0; y < croppedImageLower.rows(); y += 2) {
for (int x = 0; x < croppedImageLower.cols(); x += 2) {
double[] rgb = croppedImageLower.get(y, x); // NOTE:: apparently, the double[] returned by get is [r, g, b]
avgR += rgb[0];
avgG += rgb[1];
avgB += rgb[2];
numPixels++;
}
}
avgR /= numPixels;
avgG /= numPixels;
avgB /= numPixels;
// converting the cropped image to black and whtie and storing it in blackAndWhite
// Imgproc.cvtColor(croppedImage, blackAndWhite, Imgproc.COLOR_BGR2GRAY);
opMode.telemetry.addData("r", avgR);
opMode.telemetry.addData("g", avgG);
opMode.telemetry.addData("b", avgB);
opMode.telemetry.addData("all averages", (avgR + avgG + avgB) / 3);
//opMode.telemetry.addData("numRings", numRings);
opMode.telemetry.update();*//*
return mergedImage; // what gets returned is showed on the robot phone screen
}*/
/* int threshold = 70;
public Mat processFrame(Mat input){ // http://creativemorphometrics.co.vu/blog/2014/08/05/automated-outlines-with-opencv-in-python/
// cropping image
// TODO: change the cropping dimensions
Rect crop = new Rect(new Point(0, 0), new Point(600, 600));
croppedImage = new Mat(input, crop);
// Turn image to black and white
Imgproc.cvtColor(input, blackAndWhite, Imgproc.COLOR_BGR2GRAY);
// Get the "binary image" using a color threshold
// https://stackoverflow.com/questions/31289895/threshold-image-using-opencv-java
// TODO: change thresh (70) val to something during testing
if (opMode.gamepad1.dpad_up) {
threshold += 1;
} else if (opMode.gamepad1.dpad_down) {
threshold -= 1;
}
Imgproc.threshold(blackAndWhite, thresholded, threshold, 225, Imgproc.THRESH_BINARY);
ArrayList<MatOfPoint> listOfContours = new ArrayList<MatOfPoint>();
// find contours from binary image, https://docs.opencv.org/3.4/d3/dc0/group__imgproc__shape.html#ga17ed9f5d79ae97bd4c7cf18403e1689a
// RETR_TREE: https://docs.opencv.org/3.4/d3/dc0/group__imgproc__shape.html#ga819779b9857cc2f8601e6526a3a5bc71 (retrieval modes)
// RETR_TREE and CHAIN_APPROX_SIMPLE from the article clink above
Imgproc.findContours(thresholded, listOfContours, contourImage, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE);
// TODO: Determine size of contour to see how many rings there are
// (if there are multiple contours, you gotta get rid of them somehow by (or by more cropping)
numRings = -1;
for (MatOfPoint contour: listOfContours) {
double area = Imgproc.contourArea(contour);
// do stuff with this :)
}
opMode.telemetry.addData("threshold", threshold);
opMode.telemetry.update();
return thresholded;
}*/
} |
Java | public class DelimitedInputWriter extends AbstractRecordWriter {
private final boolean reorderingNeeded;
private String delimiter;
private char serdeSeparator;
private int[] fieldToColMapping;
private final ArrayList<String> tableColumns;
private AbstractSerDe serde = null;
static final private Log LOG = LogFactory.getLog(DelimitedInputWriter.class.getName());
/** Constructor. Uses default separator of the LazySimpleSerde
* @param colNamesForFields Column name assignment for input fields. nulls or empty
* strings in the array indicates the fields to be skipped
* @param delimiter input field delimiter
* @param endPoint Hive endpoint
* @throws ConnectionError Problem talking to Hive
* @throws ClassNotFoundException Serde class not found
* @throws SerializationError Serde initialization/interaction failed
* @throws StreamingException Problem acquiring file system path for partition
* @throws InvalidColumn any element in colNamesForFields refers to a non existing column
*/
public DelimitedInputWriter(String[] colNamesForFields, String delimiter,
HiveEndPoint endPoint)
throws ClassNotFoundException, ConnectionError, SerializationError,
InvalidColumn, StreamingException {
this(colNamesForFields, delimiter, endPoint, null);
}
/** Constructor. Uses default separator of the LazySimpleSerde
* @param colNamesForFields Column name assignment for input fields. nulls or empty
* strings in the array indicates the fields to be skipped
* @param delimiter input field delimiter
* @param endPoint Hive endpoint
* @param conf a Hive conf object. Can be null if not using advanced hive settings.
* @throws ConnectionError Problem talking to Hive
* @throws ClassNotFoundException Serde class not found
* @throws SerializationError Serde initialization/interaction failed
* @throws StreamingException Problem acquiring file system path for partition
* @throws InvalidColumn any element in colNamesForFields refers to a non existing column
*/
public DelimitedInputWriter(String[] colNamesForFields, String delimiter,
HiveEndPoint endPoint, HiveConf conf)
throws ClassNotFoundException, ConnectionError, SerializationError,
InvalidColumn, StreamingException {
this(colNamesForFields, delimiter, endPoint, conf,
(char) LazySerDeParameters.DefaultSeparators[0]);
}
/**
* Constructor. Allows overriding separator of the LazySimpleSerde
* @param colNamesForFields Column name assignment for input fields
* @param delimiter input field delimiter
* @param endPoint Hive endpoint
* @param conf a Hive conf object. Set to null if not using advanced hive settings.
* @param serdeSeparator separator used when encoding data that is fed into the
* LazySimpleSerde. Ensure this separator does not occur
* in the field data
* @throws ConnectionError Problem talking to Hive
* @throws ClassNotFoundException Serde class not found
* @throws SerializationError Serde initialization/interaction failed
* @throws StreamingException Problem acquiring file system path for partition
* @throws InvalidColumn any element in colNamesForFields refers to a non existing column
*/
public DelimitedInputWriter(String[] colNamesForFields, String delimiter,
HiveEndPoint endPoint, HiveConf conf, char serdeSeparator)
throws ClassNotFoundException, ConnectionError, SerializationError,
InvalidColumn, StreamingException {
super(endPoint, conf);
this.tableColumns = getCols(tbl);
this.serdeSeparator = serdeSeparator;
this.delimiter = delimiter;
this.fieldToColMapping = getFieldReordering(colNamesForFields, getTableColumns());
this.reorderingNeeded = isReorderingNeeded(delimiter, getTableColumns());
LOG.debug("Field reordering needed = " + this.reorderingNeeded + ", for endpoint " + endPoint);
this.serdeSeparator = serdeSeparator;
}
private boolean isReorderingNeeded(String delimiter, ArrayList<String> tableColumns) {
return !( delimiter.equals(String.valueOf(getSerdeSeparator()))
&& areFieldsInColOrder(fieldToColMapping)
&& tableColumns.size()>=fieldToColMapping.length );
}
private static boolean areFieldsInColOrder(int[] fieldToColMapping) {
for(int i=0; i<fieldToColMapping.length; ++i) {
if(fieldToColMapping[i]!=i) {
return false;
}
}
return true;
}
@VisibleForTesting
static int[] getFieldReordering(String[] colNamesForFields, List<String> tableColNames)
throws InvalidColumn {
int[] result = new int[ colNamesForFields.length ];
for(int i=0; i<colNamesForFields.length; ++i) {
result[i] = -1;
}
int i=-1, fieldLabelCount=0;
for( String col : colNamesForFields ) {
++i;
if(col == null) {
continue;
}
if( col.trim().isEmpty() ) {
continue;
}
++fieldLabelCount;
int loc = tableColNames.indexOf(col);
if(loc == -1) {
throw new InvalidColumn("Column '" + col + "' not found in table for input field " + i+1);
}
result[i] = loc;
}
if(fieldLabelCount>tableColNames.size()) {
throw new InvalidColumn("Number of field names exceeds the number of columns in table");
}
return result;
}
// Reorder fields in record based on the order of columns in the table
protected byte[] reorderFields(byte[] record) throws UnsupportedEncodingException {
if(!reorderingNeeded) {
return record;
}
String[] reorderedFields = new String[getTableColumns().size()];
String decoded = new String(record);
String[] fields = decoded.split(delimiter);
for (int i=0; i<fieldToColMapping.length; ++i) {
int newIndex = fieldToColMapping[i];
if(newIndex != -1) {
reorderedFields[newIndex] = fields[i];
}
}
return join(reorderedFields,getSerdeSeparator());
}
// handles nulls in items[]
// TODO: perhaps can be made more efficient by creating a byte[] directly
private static byte[] join(String[] items, char separator) {
StringBuilder buff = new StringBuilder(100);
if(items.length == 0)
return "".getBytes();
int i=0;
for(; i<items.length-1; ++i) {
if(items[i]!=null) {
buff.append(items[i]);
}
buff.append(separator);
}
if(items[i]!=null) {
buff.append(items[i]);
}
return buff.toString().getBytes();
}
protected ArrayList<String> getTableColumns() {
return tableColumns;
}
@Override
public void write(long transactionId, byte[] record)
throws SerializationError, StreamingIOFailure {
try {
byte[] orderedFields = reorderFields(record);
Object encodedRow = encode(orderedFields);
updater.insert(transactionId, encodedRow);
} catch (IOException e) {
throw new StreamingIOFailure("Error writing record in transaction ("
+ transactionId + ")", e);
}
}
@Override
SerDe getSerde() throws SerializationError {
if(serde!=null) {
return serde;
}
serde = createSerde(tbl, conf);
return serde;
}
private Object encode(byte[] record) throws SerializationError {
try {
BytesWritable blob = new BytesWritable();
blob.set(record, 0, record.length);
return serde.deserialize(blob);
} catch (SerDeException e) {
throw new SerializationError("Unable to convert byte[] record into Object", e);
}
}
/**
* Creates LazySimpleSerde
* @return
* @throws SerializationError if serde could not be initialized
* @param tbl
*/
protected LazySimpleSerDe createSerde(Table tbl, HiveConf conf)
throws SerializationError {
try {
Properties tableProps = MetaStoreUtils.getTableMetadata(tbl);
tableProps.setProperty("field.delim", String.valueOf(serdeSeparator));
LazySimpleSerDe serde = new LazySimpleSerDe();
SerDeUtils.initializeSerDe(serde, conf, tableProps, null);
return serde;
} catch (SerDeException e) {
throw new SerializationError("Error initializing serde", e);
}
}
private ArrayList<String> getCols(Table table) {
List<FieldSchema> cols = table.getSd().getCols();
ArrayList<String> colNames = new ArrayList<String>(cols.size());
for (FieldSchema col : cols) {
colNames.add(col.getName().toLowerCase());
}
return colNames;
}
public char getSerdeSeparator() {
return serdeSeparator;
}
} |
Java | public final class KFFT<T, S extends SimpleObject>
implements SimpleUniqueKeyFactory<T, UniqueKey<T>, S> {
private ValueObject.Field[] fields = null;
private int[] fieldIndexes = null;
private boolean byFields = false;
private int size = 0;
private S prototype = null;
public KFFT(ValueObject.Field[] argFields) {
fields = argFields;
size = argFields.length;
byFields = true;
}
public KFFT(int[] argFieldIndexes) {
fieldIndexes = argFieldIndexes;
size = argFieldIndexes.length;
byFields = false;
}
/**
* Sets the prototype - object that is used to manipulate S.VO objects.
*
* @param argPrototype
*/
public void setPrototype(S argPrototype) {
prototype = argPrototype;
}
@Override
public UniqueKey<T> create(S argSO) {
T[] attribs = (T[]) new Object[size];
for (int i = 0; i < size; i++) {
attribs[i] = get(i, argSO);
}
return new UniqueKey<T>(attribs);
}
@Override
public UniqueKey<T> create(ValueObject argTO) {
T[] attribs = (T[]) new Object[size];
if (prototype == null) {
// If we do not have a prototype, KFFT will always return an UniqueKey object filled with
// null attributes.
for (int i = 0; i < size; i++) {
attribs[i] = null;
}
} else {
// If we do have a prototype, we will use it to extract fields.
for (int i = 0; i < size; i++) {
S so = (S) prototype.create();
so.setValue(argTO);
attribs[i] = get(i, so);
}
} // else
return new UniqueKey<T>(attribs);
}
private T get(int argIndex, S argSO) {
if (byFields) {
return (T) argSO.get(fieldIndexes[argIndex]);
} else {
return (T) argSO.get(fields[argIndex]);
}
} // get() method
} |
Java | @ThreadSafe
public final class Util {
private static final Logger LOG = LoggerFactory.getLogger(Util.class);
private Util() {
}
/**
* Sleeps for the specified number of milliseconds.
*
* @param ms
* How long to sleep
*/
public static void sleep(long ms) {
try {
LOG.trace("Sleeping for {} ms", ms);
Thread.sleep(ms);
} catch (InterruptedException e) { // NOSONAR squid:S2142
LOG.warn("Interrupted while sleeping for {} ms: {}", ms, e.getMessage());
Thread.currentThread().interrupt();
}
}
/**
* Tests if a String matches another String with a wildcard pattern.
*
* @param text
* The String to test
* @param pattern
* The String containing a wildcard pattern where ? represents a
* single character and * represents any number of characters. If the
* first character of the pattern is a carat (^) the test is
* performed against the remaining characters and the result of the
* test is the opposite.
* @return True if the String matches or if the first character is ^ and the
* remainder of the String does not match.
*/
public static boolean wildcardMatch(String text, String pattern) {
if (pattern.length() > 0 && pattern.charAt(0) == '^') {
return !wildcardMatch(text, pattern.substring(1));
}
return text.matches(pattern.replace("?", ".?").replace("*", ".*?"));
}
/**
* Tests if a String is either null or empty.
*
* @param s
* The string to test
* @return True if the String is either null or empty.
*/
public static boolean isBlank(String s) {
return s == null || s.isEmpty();
}
/**
* Tests if a String is either null or empty or the unknown constant.
*
* @param s
* The string to test
* @return True if the String is either null or empty or the unknown constant.
*/
public static boolean isBlankOrUnknown(String s) {
return isBlank(s) || Constants.UNKNOWN.equals(s);
}
} |
Java | public class AsSupplierExample {
private static final Logger LOGGER = Logger.getLogger(AsSupplierExample.class.getName());
private final AtomicReference<String> lastPrinted = new AtomicReference<>();
private final ScheduledExecutorService executor = initExecutor();
/**
* Executes the example.
*/
public void run() {
Config config = Config
.from(file("conf/dev.yaml")
.optional()
.pollingStrategy(PollingStrategies::watch),
file("conf/config.yaml")
.optional()
.pollingStrategy(regular(ofSeconds(2))),
classpath("default.yaml")
.pollingStrategy(regular(ofSeconds(10))));
// greeting.get() always return up-to-date value
final Supplier<String> greeting = config.get("app.greeting").asStringSupplier();
// name.get() always return up-to-date value
final Supplier<String> name = config.get("app.name").asStringSupplier();
// first greeting
printIfChanged(greeting.get() + " " + name.get() + ".");
// use same Supplier instances to get up-to-date value
executor.scheduleWithFixedDelay(
() -> printIfChanged(greeting.get() + " " + name.get() + "."),
// check every 1 second for changes
0, 1, TimeUnit.SECONDS);
}
/**
* Utility to print same message just once.
*/
private void printIfChanged(String message) {
lastPrinted.accumulateAndGet(message, (origValue, newValue) -> {
//print MESSAGE only if changed since the last print
if (!Objects.equals(origValue, newValue)) {
LOGGER.info("[AsSupplier] " + newValue);
}
return newValue;
});
}
private static ScheduledExecutorService initExecutor() {
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
Runtime.getRuntime().addShutdownHook(new Thread(executor::shutdown));
return executor;
}
/**
* Shutdowns executor.
*/
public void shutdown() {
executor.shutdown();
}
} |
Java | public class GetGeoTargetConstantByName {
public static void main(String[] args) {
GoogleAdsClient googleAdsClient;
try {
googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
} catch (FileNotFoundException fnfe) {
System.err.printf(
"Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe);
return;
} catch (IOException ioe) {
System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe);
return;
}
try {
new GetGeoTargetConstantByName().runExample(googleAdsClient);
} catch (GoogleAdsException gae) {
// GoogleAdsException is the base class for most exceptions thrown by an API request.
// Instances of this exception have a message and a GoogleAdsFailure that contains a
// collection of GoogleAdsErrors that indicate the underlying causes of the
// GoogleAdsException.
System.err.printf(
"Request ID %s failed due to GoogleAdsException. Underlying errors:%n",
gae.getRequestId());
int i = 0;
for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) {
System.err.printf(" Error %d: %s%n", i++, googleAdsError);
}
}
}
private void runExample(GoogleAdsClient googleAdsClient) {
GeoTargetConstantServiceClient geoTargetClient =
googleAdsClient.getLatestVersion().createGeoTargetConstantServiceClient();
SuggestGeoTargetConstantsRequest.Builder requestBuilder =
SuggestGeoTargetConstantsRequest.newBuilder();
// Locale is using ISO 639-1 format. If an invalid locale is given, 'en' is used by default.
requestBuilder.setLocale(StringValue.of("en"));
// A list of country codes can be referenced here:
// https://developers.google.com/adwords/api/docs/appendix/geotargeting
requestBuilder.setCountryCode(StringValue.of("FR"));
requestBuilder
.getLocationNamesBuilder()
.addAllNames(
Stream.of("Paris", "Quebec", "Spain", "Deutschland")
.map(StringValue::of)
.collect(Collectors.toList()));
SuggestGeoTargetConstantsResponse response =
geoTargetClient.suggestGeoTargetConstants(requestBuilder.build());
for (GeoTargetConstantSuggestion suggestion : response.getGeoTargetConstantSuggestionsList()) {
System.out.printf(
"%s (%s,%s,%s,%s) is found in locale (%s) with reach (%d) for search term (%s).%n",
suggestion.getGeoTargetConstant().getResourceName(),
suggestion.getGeoTargetConstant().getName().getValue(),
suggestion.getGeoTargetConstant().getCountryCode().getValue(),
suggestion.getGeoTargetConstant().getTargetType().getValue(),
suggestion.getGeoTargetConstant().getStatus().name(),
suggestion.getLocale().getValue(),
suggestion.getReach().getValue(),
suggestion.getSearchTerm().getValue());
}
}
} |
Java | @SuppressWarnings( "serial")
public class SuiteWrapper extends Suite {
private Map<String, List<Testcase>> testcasesMap = new HashMap<>();
private Testcase lastTestcase;
private boolean dataLoadedFromDb;
/**
* Used when attached to some run. All data is captured on the fly
*/
public SuiteWrapper() {
}
/**
* Used when loading data from the database.
* All data comes ready, no calculation is needed in this case.
*
* @param suite database suite
*/
public SuiteWrapper( Suite suite ) {
dataLoadedFromDb = true;
scenariosTotal = suite.scenariosTotal;
scenariosFailed = suite.scenariosFailed;
scenariosSkipped = suite.scenariosSkipped;
testcasesTotal = suite.testcasesTotal;
testcasesFailed = suite.testcasesFailed;
testcasesSkipped = suite.testcasesSkipped;
}
public Testcase getLastTestcase() {
return this.lastTestcase;
}
public void addTestcase(
Testcase testcase ) {
List<Testcase> testcasesPerScenario = testcasesMap.get(testcase.scenarioName);
if (testcasesPerScenario == null) {
testcasesPerScenario = new ArrayList<>();
}
testcasesPerScenario.add(testcase);
this.testcasesMap.put(testcase.scenarioName, testcasesPerScenario);
this.lastTestcase = testcase;
}
public void calculateFinalStatistics() {
if (dataLoadedFromDb) {
// all statistics came calculated
return;
}
for (Entry<String, List<Testcase>> scenarioEntry : testcasesMap.entrySet()) {
++scenariosTotal;
ScenarioResult scenarioResult = ScenarioResult.PASSED;
Collection<Testcase> testcasesPerScenario = scenarioEntry.getValue();
for (Testcase testcase : testcasesPerScenario) {
++testcasesTotal;
switch (testcase.result) {
case 0: // FAILED
++testcasesFailed;
scenarioResult = ScenarioResult.FAILED;
break;
case 2: // SKIPPED
++testcasesSkipped;
if (scenarioResult == ScenarioResult.PASSED) {
scenarioResult = ScenarioResult.SKIPPED;
}
break;
default:
break;
}
}
if (scenarioResult == ScenarioResult.FAILED) {
++scenariosFailed;
} else if (scenarioResult == ScenarioResult.SKIPPED) {
++scenariosSkipped;
}
}
}
} |
Java | public final class LazySoftDeletesDirectoryReaderWrapper extends FilterDirectoryReader {
private final CacheHelper readerCacheHelper;
/**
* Creates a new soft deletes wrapper.
* @param in the incoming directory reader
* @param field the soft deletes field
*/
public LazySoftDeletesDirectoryReaderWrapper(DirectoryReader in, String field) throws IOException {
super(in, new LazySoftDeletesSubReaderWrapper(field));
readerCacheHelper = in.getReaderCacheHelper() == null ? null : new DelegatingCacheHelper(in.getReaderCacheHelper());
}
@Override
protected DirectoryReader doWrapDirectoryReader(DirectoryReader in) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public CacheHelper getReaderCacheHelper() {
return readerCacheHelper;
}
private static class LazySoftDeletesSubReaderWrapper extends SubReaderWrapper {
private final String field;
LazySoftDeletesSubReaderWrapper(String field) {
Objects.requireNonNull(field, "Field must not be null");
this.field = field;
}
@Override
protected LeafReader[] wrap(List<? extends LeafReader> readers) {
List<LeafReader> wrapped = new ArrayList<>(readers.size());
for (LeafReader reader : readers) {
LeafReader wrap = wrap(reader);
assert wrap != null;
if (wrap.numDocs() != 0) {
wrapped.add(wrap);
}
}
return wrapped.toArray(new LeafReader[0]);
}
@Override
public LeafReader wrap(LeafReader reader) {
return LazySoftDeletesDirectoryReaderWrapper.wrap(reader, field);
}
}
static LeafReader wrap(LeafReader reader, String field) {
final SegmentReader segmentReader = Lucene.segmentReader(reader);
assert segmentReader.isNRT == false : "expected non-NRT reader";
final SegmentCommitInfo segmentInfo = segmentReader.getSegmentInfo();
final int numSoftDeletes = segmentInfo.getSoftDelCount();
if (numSoftDeletes == 0) {
return reader;
}
final int maxDoc = reader.maxDoc();
final int numDocs = maxDoc - segmentInfo.getDelCount() - segmentInfo.getSoftDelCount();
final LazyBits lazyBits = new LazyBits(maxDoc, field, reader, numSoftDeletes, numDocs);
return reader instanceof CodecReader
? new LazySoftDeletesFilterCodecReader((CodecReader) reader, lazyBits, numDocs)
: new LazySoftDeletesFilterLeafReader(reader, lazyBits, numDocs);
}
public static final class LazySoftDeletesFilterLeafReader extends FilterLeafReader {
private final LeafReader reader;
private final LazyBits bits;
private final int numDocs;
private final CacheHelper readerCacheHelper;
public LazySoftDeletesFilterLeafReader(LeafReader reader, LazyBits bits, int numDocs) {
super(reader);
this.reader = reader;
this.bits = bits;
this.numDocs = numDocs;
this.readerCacheHelper = reader.getReaderCacheHelper() == null
? null
: new DelegatingCacheHelper(reader.getReaderCacheHelper());
}
@Override
public LazyBits getLiveDocs() {
return bits;
}
@Override
public int numDocs() {
return numDocs;
}
@Override
public CacheHelper getCoreCacheHelper() {
return reader.getCoreCacheHelper();
}
@Override
public CacheHelper getReaderCacheHelper() {
return readerCacheHelper;
}
}
public static final class LazySoftDeletesFilterCodecReader extends FilterCodecReader {
private final LeafReader reader;
private final LazyBits bits;
private final int numDocs;
private final CacheHelper readerCacheHelper;
public LazySoftDeletesFilterCodecReader(CodecReader reader, LazyBits bits, int numDocs) {
super(reader);
this.reader = reader;
this.bits = bits;
this.numDocs = numDocs;
this.readerCacheHelper = reader.getReaderCacheHelper() == null
? null
: new DelegatingCacheHelper(reader.getReaderCacheHelper());
}
@Override
public LazyBits getLiveDocs() {
return bits;
}
@Override
public int numDocs() {
return numDocs;
}
@Override
public CacheHelper getCoreCacheHelper() {
return reader.getCoreCacheHelper();
}
@Override
public CacheHelper getReaderCacheHelper() {
return readerCacheHelper;
}
}
private static class DelegatingCacheHelper implements CacheHelper {
private final CacheHelper delegate;
private final CacheKey cacheKey = new CacheKey();
DelegatingCacheHelper(CacheHelper delegate) {
this.delegate = delegate;
}
@Override
public CacheKey getKey() {
return cacheKey;
}
@Override
public void addClosedListener(ClosedListener listener) {
// here we wrap the listener and call it with our cache key
// this is important since this key will be used to cache the reader and otherwise we won't free caches etc.
delegate.addClosedListener(unused -> listener.onClose(cacheKey));
}
}
public static class LazyBits implements Bits {
private final int maxDoc;
private final String field;
private final LeafReader reader;
private final int numSoftDeletes;
private final int numDocs;
volatile Bits materializedBits;
public LazyBits(int maxDoc, String field, LeafReader reader, int numSoftDeletes, int numDocs) {
this.maxDoc = maxDoc;
this.field = field;
this.reader = reader;
this.numSoftDeletes = numSoftDeletes;
this.numDocs = numDocs;
materializedBits = null;
assert numSoftDeletes > 0;
}
@Override
public boolean get(int index) {
if (materializedBits == null) {
synchronized (this) {
try {
if (materializedBits == null) {
materializedBits = init();
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
return materializedBits.get(index);
}
@Override
public int length() {
return maxDoc;
}
private Bits init() throws IOException {
assert Thread.holdsLock(this);
DocIdSetIterator iterator = DocValuesFieldExistsQuery.getDocValuesDocIdSetIterator(field, reader);
assert iterator != null;
Bits liveDocs = reader.getLiveDocs();
final FixedBitSet bits;
if (liveDocs != null) {
bits = FixedBitSet.copyOf(liveDocs);
} else {
bits = new FixedBitSet(maxDoc);
bits.set(0, maxDoc);
}
int numComputedSoftDeletes = PendingSoftDeletes.applySoftDeletes(iterator, bits);
assert numComputedSoftDeletes == numSoftDeletes
: "numComputedSoftDeletes: " + numComputedSoftDeletes + " expected: " + numSoftDeletes;
int numDeletes = reader.numDeletedDocs() + numComputedSoftDeletes;
int computedNumDocs = reader.maxDoc() - numDeletes;
assert computedNumDocs == numDocs : "computedNumDocs: " + computedNumDocs + " expected: " + numDocs;
return bits;
}
public boolean initialized() {
return materializedBits != null;
}
}
} |
Java | public class BuildingDataDAO {
@Inject
public BuildingDataDAO() {
}
public Optional<BuildingData> findById(final Long buildingId) {
// return ofNullable(currentSession().find(BuildingData.class, buildingId));
return Optional.empty();
}
public BuildingData persist(final BuildingData entity) {
// return super.persist(entity);
return null;
}
} |
Java | @WebServlet(name = "XtextServices", urlPatterns = "/xtext-service/*")
@SuppressWarnings("all")
public class MyDslServlet extends XtextServlet {
private final List<ExecutorService> executorServices = CollectionLiterals.<ExecutorService>newArrayList();
@Override
public void init() {
try {
super.init();
final Provider<ExecutorService> _function = new Provider<ExecutorService>() {
@Override
public ExecutorService get() {
ExecutorService _newCachedThreadPool = Executors.newCachedThreadPool();
final Procedure1<ExecutorService> _function = new Procedure1<ExecutorService>() {
@Override
public void apply(final ExecutorService it) {
MyDslServlet.this.executorServices.add(it);
}
};
return ObjectExtensions.<ExecutorService>operator_doubleArrow(_newCachedThreadPool, _function);
}
};
final Provider<ExecutorService> executorServiceProvider = _function;
MyDslWebSetup _myDslWebSetup = new MyDslWebSetup(executorServiceProvider);
_myDslWebSetup.createInjectorAndDoEMFRegistration();
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
@Override
public void destroy() {
final Consumer<ExecutorService> _function = new Consumer<ExecutorService>() {
@Override
public void accept(final ExecutorService it) {
it.shutdown();
}
};
this.executorServices.forEach(_function);
this.executorServices.clear();
super.destroy();
}
} |
Java | public class EdifattoFileService extends AbstractAludraService implements EdifactFileService {
private FileService fileService;
/** The action object that implements all EdifactService action interfaces */
private EdifattoFileAction action;
/** Initializes the service */
@Override
public void initService() {
this.fileService = aludraServiceContext.getNonLoggingService(FileService.class);
EdifactContent contentHandler = aludraServiceContext.newComponentInstance(EdifactContent.class);
this.action = new EdifattoFileAction(contentHandler, fileService);
}
// AludraService interface implementation ----------------------------------
/** Provides a description of the service */
@Override
public String getDescription() {
return getClass().getSimpleName();
}
/** Provides an object to parses and save EDIFACT and X12 documents from and to streams. */
@Override
public EdifactFileInteraction perform() {
return action;
}
/** Provides an object to verify EDIFACT or X12 documents. */
@Override
public EdifactFileVerification verify() {
return action;
}
/** Provides an object for performing queries on EDIFACT or X12 interchanges
* and analyze their differences. */
@Override
public EdifactFileCondition check() {
return action;
}
/** Closes the service */
@Override
public void close() {
// nothing to do
}
} |
Java | class RedisQueryEngine extends QueryEngine<RedisKeyValueAdapter, RedisOperationChain, Comparator<?>> {
/**
* Creates new {@link RedisQueryEngine} with defaults.
*/
RedisQueryEngine() {
this(new RedisCriteriaAccessor(), new SpelSortAccessor(new SpelExpressionParser()));
}
/**
* Creates new {@link RedisQueryEngine}.
*
* @param criteriaAccessor
* @param sortAccessor
* @see QueryEngine#QueryEngine(CriteriaAccessor, SortAccessor)
*/
private RedisQueryEngine(CriteriaAccessor<RedisOperationChain> criteriaAccessor,
@Nullable SortAccessor<Comparator<?>> sortAccessor) {
super(criteriaAccessor, sortAccessor);
}
@Override
@SuppressWarnings("unchecked")
public <T> Collection<T> execute(RedisOperationChain criteria, Comparator<?> sort, long offset, int rows,
String keyspace, Class<T> type) {
List<T> result = doFind(criteria, offset, rows, keyspace, type);
if (sort != null) {
result.sort((Comparator<? super T>) sort);
}
return result;
}
private <T> List<T> doFind(RedisOperationChain criteria, long offset, int rows, String keyspace, Class<T> type) {
if (criteria == null
|| (CollectionUtils.isEmpty(criteria.getOrSismember()) && CollectionUtils.isEmpty(criteria.getSismember()))
&& criteria.getNear() == null) {
return getAdapter().getAllOf(keyspace, type, offset, rows);
}
RedisCallback<Map<byte[], Map<byte[], byte[]>>> callback = connection -> {
List<byte[]> allKeys = new ArrayList<>();
if (!criteria.getSismember().isEmpty()) {
allKeys.addAll(connection.sInter(keys(keyspace + ":", criteria.getSismember())));
}
if (!criteria.getOrSismember().isEmpty()) {
allKeys.addAll(connection.sUnion(keys(keyspace + ":", criteria.getOrSismember())));
}
if (criteria.getNear() != null) {
GeoResults<GeoLocation<byte[]>> x = connection.geoRadius(geoKey(keyspace + ":", criteria.getNear()),
new Circle(criteria.getNear().getPoint(), criteria.getNear().getDistance()));
for (GeoResult<GeoLocation<byte[]>> y : x) {
allKeys.add(y.getContent().getName());
}
}
byte[] keyspaceBin = getAdapter().getConverter().getConversionService().convert(keyspace + ":", byte[].class);
Map<byte[], Map<byte[], byte[]>> rawData = new LinkedHashMap<>();
if (allKeys.isEmpty() || allKeys.size() < offset) {
return Collections.emptyMap();
}
int offsetToUse = Math.max(0, (int) offset);
if (rows > 0) {
allKeys = allKeys.subList(Math.max(0, offsetToUse), Math.min(offsetToUse + rows, allKeys.size()));
}
for (byte[] id : allKeys) {
byte[] singleKey = ByteUtils.concat(keyspaceBin, id);
rawData.put(id, connection.hGetAll(singleKey));
}
return rawData;
};
Map<byte[], Map<byte[], byte[]>> raw = this.getAdapter().execute(callback);
List<T> result = new ArrayList<>(raw.size());
for (Map.Entry<byte[], Map<byte[], byte[]>> entry : raw.entrySet()) {
if (CollectionUtils.isEmpty(entry.getValue())) {
continue;
}
RedisData data = new RedisData(entry.getValue());
data.setId(getAdapter().getConverter().getConversionService().convert(entry.getKey(), String.class));
data.setKeyspace(keyspace);
T converted = this.getAdapter().getConverter().read(type, data);
result.add(converted);
}
return result;
}
@Override
public Collection<?> execute(RedisOperationChain criteria, Comparator<?> sort, long offset, int rows,
String keyspace) {
return execute(criteria, sort, offset, rows, keyspace, Object.class);
}
@Override
public long count(RedisOperationChain criteria, String keyspace) {
if (criteria == null || criteria.isEmpty()) {
return this.getAdapter().count(keyspace);
}
return this.getAdapter().execute(connection -> {
long result = 0;
if (!criteria.getOrSismember().isEmpty()) {
result += connection.sUnion(keys(keyspace + ":", criteria.getOrSismember())).size();
}
if (!criteria.getSismember().isEmpty()) {
result += connection.sInter(keys(keyspace + ":", criteria.getSismember())).size();
}
return result;
});
}
private byte[][] keys(String prefix, Collection<PathAndValue> source) {
byte[][] keys = new byte[source.size()][];
int i = 0;
for (PathAndValue pathAndValue : source) {
byte[] convertedValue = getAdapter().getConverter().getConversionService().convert(pathAndValue.getFirstValue(),
byte[].class);
byte[] fullPath = getAdapter().getConverter().getConversionService()
.convert(prefix + pathAndValue.getPath() + ":", byte[].class);
keys[i] = ByteUtils.concat(fullPath, convertedValue);
i++;
}
return keys;
}
private byte[] geoKey(String prefix, NearPath source) {
String path = GeoIndexedPropertyValue.geoIndexName(source.getPath());
return getAdapter().getConverter().getConversionService().convert(prefix + path, byte[].class);
}
/**
* @author Christoph Strobl
* @since 1.7
*/
static class RedisCriteriaAccessor implements CriteriaAccessor<RedisOperationChain> {
@Override
public RedisOperationChain resolve(KeyValueQuery<?> query) {
return (RedisOperationChain) query.getCriteria();
}
}
} |
Java | static class RedisCriteriaAccessor implements CriteriaAccessor<RedisOperationChain> {
@Override
public RedisOperationChain resolve(KeyValueQuery<?> query) {
return (RedisOperationChain) query.getCriteria();
}
} |
Java | public class CropperMainView extends LinearLayout implements CropImageView.OnSetImageUriCompleteListener, CropImageView.OnCropImageCompleteListener {
private static final String TAG = CropperMainView.class.getSimpleName();
private CropImageView mCropImageView;
Activity mActivity;
Context mContext;
Uri uri;
String folderName = "";
private CropperMainView(Context context){
super(context);
}
public CropperMainView(Context context, Activity activity) {
super(context);
mActivity = activity;
mContext = context;
Log.e(TAG, "Load CropperMainView");
inflate(context, R.layout.crop_image_activity, this);
int SDK_INT = Build.VERSION.SDK_INT;
if (SDK_INT > 8) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
mCropImageView = (CropImageView) findViewById(R.id.cropImageMainView);
mCropImageView.setOnSetImageUriCompleteListener(this);
mCropImageView.setOnCropImageCompleteListener(this);
}
public void setFolderName(String folderName) {
this.folderName = folderName;
}
public void setImageURI(String uri) {
Uri source = getImageUrl(mContext, uri, this.folderName);
Log.e(TAG, ""+source);
if(source != null){
this.uri = source;
mCropImageView.setImageUriAsync(source);
mCropImageView.setCropShape(CropImageView.CropShape.RECTANGLE);
mCropImageView.setGuidelines(CropImageView.Guidelines.ON);
mCropImageView.setFixedAspectRatio(false);
mCropImageView.setMultiTouchEnabled(false);
mCropImageView.setShowCropOverlay(true);
mCropImageView.setShowProgressBar(false);
mCropImageView.setAutoZoomEnabled(false);
}
else {
sendEmiterEvent("", "could not load image");
}
}
@Override
public void onSetImageUriComplete(CropImageView view, Uri uri, Exception error) {
if (error == null) {
Log.e(TAG, "image loaded: " + uri);
}
else {
Log.e(TAG, "Failed to load image: " + error);
sendEmiterEvent("", error.getMessage());
}
}
public void cropImage() {
Log.e(TAG, "Crop image");
mCropImageView.getCroppedImageAsync();
}
@Override
public void onCropImageComplete(CropImageView view, CropImageView.CropResult result) {
if (result.getError() == null && result.isSuccessful()) {
try {
File image = saveImageFromBitmap(mContext, result.getBitmap(), this.folderName);
Log.e(TAG, "image cropped: " + "file://" + image.getPath());
sendEmiterEvent("file://" + image.getPath(), "");
} catch (Exception e) {
e.printStackTrace();
sendEmiterEvent("", e.getMessage());
}
Log.e(TAG, "image cropped: " + result.getCropRect().toShortString());
} else {
Log.e(TAG, "Failed to crop image: " + result.getError());
sendEmiterEvent("", result.getError().getMessage());
}
}
private void sendEmiterEvent(String imageUri, String error) {
WritableMap event = Arguments.createMap();
event.putString("uri", imageUri);
event.putString("error", error);
ReactContext reactContext = (ReactContext) getContext();
reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(getId(),"topChange", event);
}
} |
Java | public class BackgroundDataSend extends Service {
// Handling WiFi connectivity
private boolean network;
private BroadcastReceiver receiver;
private volatile boolean isWifiConnected = false;
// Wakelock
private PowerManager.WakeLock wakeLock;
// Data interaction
private DataSender dataSender;
private String UID;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
// TODO(david soller) : fix these comments
// Step 1. Extract necessary information
UID = MultiprocessPreferences.getDefaultSharedPreferences(this).getString("uid", "");
// Step 3. Initialize necessary data.
dataSender = new DataSender(UID);
// Step 4. Create a listener to handle wifi connectivity.
network = isDataConnected();
receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
network = isDataConnected();
handleWifiChange();
}
};
registerReceiver(receiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
// Step 5. Acquire a lock on the CPU for computation during sleep.
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakelockTag");
wakeLock.acquire();
// Step 6. Begin this service as a foreground service.
Intent notificationIntent = new Intent(this, Login.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this)
.setSmallIcon(android.R.drawable.stat_notify_sync)
.setContentTitle("Background Service Running")
.setContentText("Processing data")
.setContentIntent(pendingIntent).build();
/*
* NOTE: A foreground service is used to decouple the service from the application. When a
* user exits from the application view (the Login activity), using a foreground service
* prevents this service from restarting. The number supplied below is arbitrary but must be
* > 0.
* */
startForeground(1337, notification);
}
private boolean isDataConnected() {
try {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
//TODO: See if making sure it's not a metered connection would be better? Consult: https://developer.android.com/reference/android/net/ConnectivityManager.html#isActiveNetworkMetered
if (info.getType() == ConnectivityManager.TYPE_WIFI) {
return cm.getActiveNetworkInfo().isConnectedOrConnecting();
} else {
return false;
}
} catch (Exception e) {
return false;
}
}
private void handleWifiChange() {
if (network) {
// Step 3. Check if wifi was previously disconnected.
if (!isWifiConnected) {
if (BuildConfig.DEBUG) {
Log.d("handleMessage", "Handling wifi connect.");
}
isWifiConnected = true;
dataSender.addFirebaseListeners();
}
} else {
// Step 3. Check if wifi was previously connected.
if (isWifiConnected) {
dataSender.stopWorkThread();
if (BuildConfig.DEBUG) {
Log.d("handleMessage", "Handling wifi disconnect.");
}
isWifiConnected = false;
dataSender.setWifiDisconnect();
dataSender.removeFirebaseListeners();
}
}
}
@Override
public void onDestroy() {
Log.d("onDestroy", "Stopping the worker thread.");
// Step 1. End the worker thread, if running.
dataSender.stopWorkThread();
Log.d("onDestroy", "Removing Listeners.");
// Step 2. Remove listeners.
dataSender.removeFirebaseListeners();
Log.d("onDestroy", "Unregister Wifi receiver.");
// Step 3. End the wifi receiver.
unregisterReceiver(receiver);
Log.d("onDestroy", "Stopping foreground service.");
// Step 4. Remove this service from the foreground.
stopForeground(true);
Log.d("onDestroy", "Releasing wakelock.");
// Step 5. Release the wakelock.
wakeLock.release();
// Step 6. Stop the service.
stopSelf();
// Step 7. Let Android destroy the rest.
super.onDestroy();
}
} |
Java | public class ConsumerRequestDefragmenterInterceptor extends InterceptorSupport<MllpTransactionEndpoint<?>> {
private static final transient Logger LOG = LoggerFactory.getLogger(ConsumerRequestDefragmenterInterceptor.class);
// keys consist of: continuation pointer, MSH-3-1, MSH-3-2, and MSH-3-3
private UnsolicitedFragmentationStorage storage;
@Override
public void setEndpoint(MllpTransactionEndpoint<?> endpoint) {
super.setEndpoint(endpoint);
this.storage = getEndpoint().getUnsolicitedFragmentationStorage();
requireNonNull(storage);
}
/**
* Accumulates fragments and passes the "big" message to the processing route.
*/
@Override
public void process(Exchange exchange) throws Exception {
String requestString = exchange.getIn().getBody(String.class);
Parser parser = getEndpoint().getHl7v2TransactionConfiguration().getParser();
Message requestMessage = parser.parse(requestString);
Terser requestTerser = new Terser(requestMessage);
String msh14 = requestTerser.get("MSH-14");
String dsc1 = null;
try {
if (! "I".equals(requestTerser.get("DSC-2"))) {
dsc1 = requestTerser.get("DSC-1");
}
} catch (HL7Exception e) {
// segment DSC does not exist in cancel requests
}
// pass when the message is not fragmented
if (isEmpty(msh14) && isEmpty(dsc1)) {
getWrappedProcessor().process(exchange);
return;
}
// get pieces of the accumulator's key
String msh31 = requestTerser.get("MSH-3-1");
String msh32 = requestTerser.get("MSH-3-2");
String msh33 = requestTerser.get("MSH-3-3");
// create an accumulator (on the arrival of the first fragment)
// or get an existing one (on the arrival of fragments 2..n)
StringBuilder accumulator;
if (isEmpty(msh14)) {
accumulator = new StringBuilder();
} else {
accumulator = storage.getAndRemove(keyString(msh14, msh31, msh32, msh33));
if (accumulator == null) {
LOG.warn("Pass unknown fragment with MSH-14=={} to the route", msh14);
getWrappedProcessor().process(exchange);
return;
}
}
// append current fragment to the accumulator
int beginIndex = isEmpty(msh14) ? 0 : requestString.indexOf('\r');
int endIndex = isEmpty(dsc1) ? requestString.length() : (requestString.indexOf("\rDSC") + 1);
accumulator.append(requestString, beginIndex, endIndex);
// DSC-1 is empty -- finish accumulation, pass message to the marshaller
if (isEmpty(dsc1)) {
LOG.debug("Finished fragment chain {}", msh14);
exchange.getIn().setBody(accumulator.toString());
getWrappedProcessor().process(exchange);
return;
}
// DSC-1 is not empty -- update accumulators map, request the next fragment
LOG.debug("Processed fragment {} requesting {}", msh14, dsc1);
storage.put(keyString(dsc1, msh31, msh32, msh33), accumulator);
Message ack = MessageUtils.response(
requestMessage, "ACK",
requestTerser.get("MSH-9-2"));
Terser ackTerser = new Terser(ack);
ackTerser.set("MSA-1", "CA");
ackTerser.set("MSA-2", requestTerser.get("MSH-10"));
Exchanges.resultMessage(exchange).setBody(parser.encode(ack));
}
} |
Java | public class GeneralDateTimeRenderer extends AbstractRenderer<Date> {
private static final DateTimeFormat format = DateTimeFormat.getFormat("yyyy-MMM-dd, HH:mm"); //$NON-NLS-1$
@Override
public String render(Date object) {
if (object != null) {
return format.format(object);
}
return "";
}
} |
Java | public class UIInputFile extends UIInput implements NamingContainer {
public static final String COMPONENT_TYPE = UIInputFile.class.getName();
public static final String COMPONENT_FAMILY = "javax.faces.Input";
protected static final String CHOICE_FACET_NAME = "choice";
protected static final String UPLOAD_FACET_NAME = "upload";
protected static final String DEFAULT_DOWNLOAD_FACET_NAME = "default_download";
protected static final String DOWNLOAD_FACET_NAME = "download";
protected static final String EDIT_FILENAME_FACET_NAME = "edit_filename";
protected static final Log log = LogFactory.getLog(UIInputFile.class);
protected final JSFBlobUploaderService uploaderService;
// value for filename, will disappear when it's part of the blob
protected String filename;
// used to decide whether filename can be edited
protected Boolean editFilename;
protected String onchange;
protected String onclick;
protected String onselect;
public UIInputFile() {
// initiate sub components
FacesContext faces = FacesContext.getCurrentInstance();
Application app = faces.getApplication();
ComponentUtils.initiateSubComponent(this, DEFAULT_DOWNLOAD_FACET_NAME,
app.createComponent(UIOutputFile.COMPONENT_TYPE));
ComponentUtils.initiateSubComponent(this, EDIT_FILENAME_FACET_NAME,
app.createComponent(HtmlInputText.COMPONENT_TYPE));
uploaderService = Framework.getService(JSFBlobUploaderService.class);
for (JSFBlobUploader uploader : uploaderService.getJSFBlobUploaders()) {
uploader.hookSubComponent(this);
}
}
// component will render itself
@Override
public String getRendererType() {
return null;
}
// getters and setters
/**
* Override value so that an {@link InputFileInfo} structure is given instead of the "value" attribute resolution.
*/
@Override
public Object getValue() {
Object localValue = getLocalValue();
if (localValue != null) {
return localValue;
} else {
Blob blob = null;
Object originalValue = super.getValue();
String mimeType = null;
if (originalValue instanceof Blob) {
blob = (Blob) originalValue;
mimeType = blob.getMimeType();
}
List<String> choices = getAvailableChoices(blob, false);
String choice = choices.get(0);
return new InputFileInfo(choice, blob, getFilename(), mimeType);
}
}
public String getFilename() {
if (filename != null) {
return filename;
}
ValueExpression ve = getValueExpression("filename");
if (ve != null) {
try {
return (String) ve.getValue(getFacesContext().getELContext());
} catch (ELException e) {
throw new FacesException(e);
}
} else {
return null;
}
}
public void setFilename(String filename) {
this.filename = filename;
}
public Boolean getEditFilename() {
if (editFilename != null) {
return editFilename;
}
ValueExpression ve = getValueExpression("editFilename");
if (ve != null) {
try {
return !Boolean.FALSE.equals(ve.getValue(getFacesContext().getELContext()));
} catch (ELException e) {
throw new FacesException(e);
}
} else {
// default value
return false;
}
}
public void setEditFilename(Boolean editFilename) {
this.editFilename = editFilename;
}
public InputFileInfo getFileInfoValue() {
return (InputFileInfo) getValue();
}
public InputFileInfo getFileInfoLocalValue() {
return (InputFileInfo) getLocalValue();
}
public InputFileInfo getFileInfoSubmittedValue() {
return (InputFileInfo) getSubmittedValue();
}
protected String getStringValue(String name, String defaultValue) {
ValueExpression ve = getValueExpression(name);
if (ve != null) {
try {
return (String) ve.getValue(getFacesContext().getELContext());
} catch (ELException e) {
throw new FacesException(e);
}
} else {
return defaultValue;
}
}
public String getOnchange() {
if (onchange != null) {
return onchange;
}
return getStringValue("onchange", null);
}
public void setOnchange(String onchange) {
this.onchange = onchange;
}
public String getOnclick() {
if (onclick != null) {
return onclick;
}
return getStringValue("onclick", null);
}
public void setOnclick(String onclick) {
this.onclick = onclick;
}
public String getOnselect() {
if (onselect != null) {
return onselect;
}
return getStringValue("onselect", null);
}
public void setOnselect(String onselect) {
this.onselect = onselect;
}
// handle submitted values
@Override
public void decode(FacesContext context) {
if (context == null) {
throw new IllegalArgumentException();
}
// Force validity back to "true"
setValid(true);
// decode the radio button, other input components will decode
// themselves
Map<String, String> requestMap = context.getExternalContext().getRequestParameterMap();
String radioClientId = getClientId(context) + NamingContainer.SEPARATOR_CHAR + CHOICE_FACET_NAME;
String choice = requestMap.get(radioClientId);
// other submitted values will be handled at validation time
InputFileInfo submitted = new InputFileInfo(choice, null, null, null);
setSubmittedValue(submitted);
}
/**
* Process validation. Sub components are already validated.
*/
@Override
public void validate(FacesContext context) {
if (context == null) {
throw new IllegalArgumentException();
}
// Submitted value == null means "the component was not submitted
// at all"; validation should not continue
InputFileInfo submitted = getFileInfoSubmittedValue();
if (submitted == null) {
return;
}
InputFileInfo previous = getFileInfoValue();
// validate choice
String choice;
try {
choice = submitted.getConvertedChoice();
} catch (ConverterException ce) {
ComponentUtils.addErrorMessage(context, this, ce.getMessage());
setValid(false);
return;
}
if (choice == null) {
ComponentUtils.addErrorMessage(context, this, "error.inputFile.choiceRequired");
setValid(false);
return;
}
submitted.setChoice(choice);
String previousChoice = previous.getConvertedChoice();
boolean temp = InputFileChoice.isUploadOrKeepTemp(previousChoice);
List<String> choices = getAvailableChoices(previous.getBlob(), temp);
if (!choices.contains(choice)) {
ComponentUtils.addErrorMessage(context, this, "error.inputFile.invalidChoice");
setValid(false);
return;
}
// validate choice in respect to other submitted values
if (InputFileChoice.KEEP_TEMP.equals(choice) || InputFileChoice.KEEP.equals(choice)) {
if (isLocalValueSet() || InputFileChoice.KEEP.equals(choice)) {
// re-submit stored values
submitted.setInfo(previous);
}
if (getEditFilename()) {
validateFilename(context, submitted);
}
} else if (InputFileChoice.isUpload(choice)) {
try {
uploaderService.getJSFBlobUploader(choice).validateUpload(this, context, submitted);
if (isValid()) {
submitted.setChoice(InputFileChoice.KEEP_TEMP);
} else {
// re-submit stored values
submitted.setInfo(previous);
}
} catch (ValidatorException e) {
// re-submit stored values
submitted.setInfo(previous);
}
} else if (InputFileChoice.DELETE.equals(choice) || InputFileChoice.NONE.equals(choice)) {
submitted.setInfo(null);
}
// will need this to call declared validators
super.validateValue(context, submitted);
// If our value is valid, store the new value, erase the
// "submitted" value, and emit a ValueChangeEvent if appropriate
if (isValid()) {
setValue(submitted);
setSubmittedValue(null);
if (compareValues(previous, submitted)) {
queueEvent(new ValueChangeEvent(this, previous, submitted));
}
}
}
public void validateFilename(FacesContext context, InputFileInfo submitted) {
// validate filename
UIComponent filenameFacet = getFacet(EDIT_FILENAME_FACET_NAME);
if (filenameFacet instanceof EditableValueHolder) {
EditableValueHolder filenameComp = (EditableValueHolder) filenameFacet;
submitted.setFilename(filenameComp.getLocalValue());
String filename;
try {
filename = submitted.getConvertedFilename();
} catch (ConverterException ce) {
ComponentUtils.addErrorMessage(context, this, ce.getMessage());
setValid(false);
return;
}
submitted.setFilename(filename);
}
}
public void updateFilename(FacesContext context, String newFilename) {
// set filename by hand after validation
ValueExpression ve = getValueExpression("filename");
if (ve != null) {
ve.setValue(context.getELContext(), newFilename);
}
}
@Override
public void updateModel(FacesContext context) {
if (context == null) {
throw new IllegalArgumentException();
}
if (!isValid() || !isLocalValueSet()) {
return;
}
ValueExpression ve = getValueExpression("value");
if (ve == null) {
return;
}
try {
InputFileInfo local = getFileInfoLocalValue();
String choice = local.getConvertedChoice();
// set blob and filename
if (InputFileChoice.DELETE.equals(choice)) {
// set filename first to avoid error in case it maps the blob filename
ValueExpression vef = getValueExpression("filename");
if (vef != null) {
vef.setValue(context.getELContext(), local.getConvertedFilename());
}
ve.setValue(context.getELContext(), local.getConvertedBlob());
setValue(null);
setLocalValueSet(false);
} else if (InputFileChoice.isUploadOrKeepTemp(choice)) {
// set blob first to avoid error in case the filename maps the blob filename
ve.setValue(context.getELContext(), local.getConvertedBlob());
setValue(null);
setLocalValueSet(false);
ValueExpression vef = getValueExpression("filename");
if (vef != null) {
vef.setValue(context.getELContext(), local.getConvertedFilename());
}
} else if (InputFileChoice.KEEP.equals(choice)) {
// reset local value
setValue(null);
setLocalValueSet(false);
if (getEditFilename()) {
// set filename
ValueExpression vef = getValueExpression("filename");
if (vef != null) {
vef.setValue(context.getELContext(), local.getConvertedFilename());
}
}
}
return;
} catch (ELException e) {
String messageStr = e.getMessage();
Throwable result = e.getCause();
while (result != null && result instanceof ELException) {
messageStr = result.getMessage();
result = result.getCause();
}
FacesMessage message;
if (messageStr == null) {
message = MessageFactory.getMessage(context, UPDATE_MESSAGE_ID, MessageFactory.getLabel(context, this));
} else {
message = new FacesMessage(FacesMessage.SEVERITY_ERROR, messageStr, messageStr);
}
context.addMessage(getClientId(context), message);
setValid(false);
} catch (IllegalArgumentException | ConverterException e) {
FacesMessage message = MessageFactory.getMessage(context, UPDATE_MESSAGE_ID,
MessageFactory.getLabel(context, this));
context.addMessage(getClientId(context), message);
setValid(false);
}
}
// rendering methods
protected List<String> getAvailableChoices(Blob blob, boolean temp) {
List<String> choices = new ArrayList<String>(3);
boolean isRequired = isRequired();
if (blob != null) {
choices.add(temp ? InputFileChoice.KEEP_TEMP : InputFileChoice.KEEP);
} else if (!isRequired) {
choices.add(InputFileChoice.NONE);
}
boolean allowUpdate = true;
if (blob != null) {
BlobManager blobManager = Framework.getService(BlobManager.class);
BlobProvider blobProvider = blobManager.getBlobProvider(blob);
if (blobProvider != null && !blobProvider.supportsUserUpdate()) {
allowUpdate = false;
}
}
if (allowUpdate) {
for (JSFBlobUploader uploader : uploaderService.getJSFBlobUploaders()) {
choices.add(uploader.getChoice());
}
if (blob != null && !isRequired) {
choices.add(InputFileChoice.DELETE);
}
}
return choices;
}
public Blob getCurrentBlob() {
Blob blob = null;
InputFileInfo submittedFileInfo = getFileInfoSubmittedValue();
if (submittedFileInfo != null) {
String choice = submittedFileInfo.getConvertedChoice();
if (InputFileChoice.isKeepOrKeepTemp(choice)) {
// rebuild other info from current value
InputFileInfo fileInfo = getFileInfoValue();
blob = fileInfo.getConvertedBlob();
} else {
blob = submittedFileInfo.getConvertedBlob();
}
} else {
InputFileInfo fileInfo = getFileInfoValue();
blob = fileInfo.getConvertedBlob();
}
return blob;
}
public String getCurrentFilename() {
String filename = null;
InputFileInfo submittedFileInfo = getFileInfoSubmittedValue();
if (submittedFileInfo != null) {
String choice = submittedFileInfo.getConvertedChoice();
if (InputFileChoice.isKeepOrKeepTemp(choice)) {
// rebuild it in case it's supposed to be kept
InputFileInfo fileInfo = getFileInfoValue();
filename = fileInfo.getConvertedFilename();
} else {
filename = submittedFileInfo.getConvertedFilename();
}
} else {
InputFileInfo fileInfo = getFileInfoValue();
filename = fileInfo.getConvertedFilename();
}
return filename;
}
@Override
public void encodeBegin(FacesContext context) throws IOException {
notifyPreviousErrors(context);
// not ours to close
ResponseWriter writer = context.getResponseWriter();
Blob blob = null;
try {
blob = getCurrentBlob();
} catch (ConverterException e) {
// can happen -> ignore, don't break rendering
}
String filename = null;
try {
filename = getCurrentFilename();
} catch (ConverterException e) {
// can happen -> ignore, don't break rendering
}
InputFileInfo fileInfo = getFileInfoSubmittedValue();
if (fileInfo == null) {
fileInfo = getFileInfoValue();
}
String currentChoice = fileInfo.getConvertedChoice();
boolean temp = InputFileChoice.KEEP_TEMP.equals(currentChoice);
List<String> choices = getAvailableChoices(blob, temp);
String radioClientId = getClientId(context) + NamingContainer.SEPARATOR_CHAR + CHOICE_FACET_NAME;
writer.startElement("table", this);
writer.writeAttribute("class", "dataInput", null);
writer.startElement("tbody", this);
writer.writeAttribute("class", getAttributes().get("styleClass"), null);
for (String radioChoice : choices) {
String id = radioClientId + radioChoice;
writer.startElement("tr", this);
writer.startElement("td", this);
writer.writeAttribute("class", "radioColumn", null);
Map<String, String> props = new HashMap<String, String>();
props.put("type", "radio");
props.put("name", radioClientId);
props.put("id", id);
props.put("value", radioChoice);
if (radioChoice.equals(currentChoice)) {
props.put("checked", "checked");
}
String onchange = getOnchange();
if (onchange != null) {
props.put("onchange", onchange);
}
String onclick = getOnclick();
if (onclick != null) {
props.put("onclick", onclick);
}
String onselect = getOnselect();
if (onselect != null) {
props.put("onselect", onselect);
}
StringBuffer htmlBuffer = new StringBuffer();
htmlBuffer.append("<input");
for (Map.Entry<String, String> prop : props.entrySet()) {
htmlBuffer.append(" " + prop.getKey() + "=\"" + prop.getValue() + "\"");
}
htmlBuffer.append(" />");
writer.write(htmlBuffer.toString());
writer.endElement("td");
writer.startElement("td", this);
writer.writeAttribute("class", "fieldColumn", null);
String label = (String) ComponentUtils.getAttributeValue(this, radioChoice + "Label", null);
if (label == null) {
label = ComponentUtils.translate(context, "label.inputFile." + radioChoice + "Choice");
}
writer.write("<label for=\"" + id + "\" style=\"float:left\">" + label + "</label>");
writer.write(ComponentUtils.WHITE_SPACE_CHARACTER);
if (InputFileChoice.isKeepOrKeepTemp(radioChoice)) {
UIComponent downloadFacet = getFacet(DOWNLOAD_FACET_NAME);
if (downloadFacet != null) {
// redefined in template
ComponentUtils.encodeComponent(context, downloadFacet);
} else {
downloadFacet = getFacet(DEFAULT_DOWNLOAD_FACET_NAME);
if (downloadFacet != null) {
UIOutputFile downloadComp = (UIOutputFile) downloadFacet;
downloadComp.setQueryParent(true);
ComponentUtils.copyValues(this, downloadComp, new String[] { "downloadLabel", "iconRendered" });
ComponentUtils.copyLinkValues(this, downloadComp);
ComponentUtils.encodeComponent(context, downloadComp);
}
}
if (getEditFilename()) {
writer.write("<br />");
UIComponent filenameFacet = getFacet(EDIT_FILENAME_FACET_NAME);
if (filenameFacet instanceof HtmlInputText) {
HtmlInputText filenameComp = (HtmlInputText) filenameFacet;
filenameComp.setValue(filename);
filenameComp.setLocalValueSet(false);
String onClick = "document.getElementById('%s').checked='checked'";
filenameComp.setOnclick(String.format(onClick, id));
writer.write(ComponentUtils.WHITE_SPACE_CHARACTER);
label = (String) ComponentUtils.getAttributeValue(this, "editFilenameLabel", null);
if (label == null) {
label = ComponentUtils.translate(context, "label.inputFile.editFilename");
}
writer.write("<label for=\"" + filenameComp.getId() + "\">" + label + "</label>");
writer.write(ComponentUtils.WHITE_SPACE_CHARACTER);
ComponentUtils.encodeComponent(context, filenameComp);
}
}
} else if (InputFileChoice.isUpload(radioChoice)) {
String onChange = String.format("document.getElementById('%s').checked='checked'", id);
uploaderService.getJSFBlobUploader(radioChoice).encodeBeginUpload(this, context, onChange);
}
writer.endElement("td");
writer.endElement("tr");
}
writer.endElement("tbody");
writer.endElement("table");
writer.flush();
}
/**
* @since 6.1.1
*/
private void notifyPreviousErrors(FacesContext context) {
final Object hasError = context.getAttributes().get(NuxeoResponseStateManagerImpl.MULTIPART_SIZE_ERROR_FLAG);
final String componentId = (String) context.getAttributes().get(
NuxeoResponseStateManagerImpl.MULTIPART_SIZE_ERROR_COMPONENT_ID);
if (Boolean.TRUE.equals(hasError)) {
if (StringUtils.isBlank(componentId)) {
ComponentUtils.addErrorMessage(context, this, "error.inputFile.maxRequestSize",
new Object[] { Framework.getProperty("nuxeo.jsf.maxRequestSize") });
} else if (componentId.equals(getFacet(UPLOAD_FACET_NAME).getClientId())) {
ComponentUtils.addErrorMessage(context, this, "error.inputFile.maxSize",
new Object[] { Framework.getProperty("nuxeo.jsf.maxFileSize") });
}
}
}
// state holder
@Override
public Object saveState(FacesContext context) {
Object[] values = new Object[6];
values[0] = super.saveState(context);
values[1] = filename;
values[2] = editFilename;
values[3] = onchange;
values[4] = onclick;
values[5] = onselect;
return values;
}
@Override
public void restoreState(FacesContext context, Object state) {
Object[] values = (Object[]) state;
super.restoreState(context, values[0]);
filename = (String) values[1];
editFilename = (Boolean) values[2];
onchange = (String) values[3];
onclick = (String) values[4];
onselect = (String) values[5];
}
} |
Java | class BlazeCreateResourceUtils {
private static final String PLACEHOLDER_TEXT =
"choose a res/ directory with dropdown or browse button";
static void setupResDirectoryChoices(
Project project,
@Nullable VirtualFile contextFile,
JBLabel resDirLabel,
ComboboxWithBrowseButton resDirComboAndBrowser) {
// Reset the item list before filling it back up.
resDirComboAndBrowser.getComboBox().removeAllItems();
BlazeProjectData blazeProjectData =
BlazeProjectDataManager.getInstance(project).getBlazeProjectData();
if (blazeProjectData != null) {
BlazeAndroidSyncData syncData =
blazeProjectData.getSyncState().get(BlazeAndroidSyncData.class);
if (syncData != null) {
ImmutableCollection<TargetKey> rulesRelatedToContext = null;
File fileFromContext = null;
if (contextFile != null) {
fileFromContext = VfsUtilCore.virtualToIoFile(contextFile);
rulesRelatedToContext =
SourceToTargetMap.getInstance(project).getRulesForSourceFile(fileFromContext);
if (rulesRelatedToContext.isEmpty()) {
rulesRelatedToContext = null;
}
}
ArtifactLocationDecoder artifactLocationDecoder =
blazeProjectData.getArtifactLocationDecoder();
// Sort:
// - contextFile/res if contextFile is a directory,
// to optimize the right click on directory case, or the "closest" string
// match to the contextFile from the res directories known to blaze
// - the rest of the direct dirs, then transitive dirs of the context rules,
// then any known res dir in the project
// as a backup, in alphabetical order.
Set<File> resourceDirs = Sets.newTreeSet();
Set<File> transitiveDirs = Sets.newTreeSet();
Set<File> allResDirs = Sets.newTreeSet();
for (AndroidResourceModule androidResourceModule :
syncData.importResult.androidResourceModules) {
Collection<File> resources =
OutputArtifactResolver.resolveAll(
project, artifactLocationDecoder, androidResourceModule.resources);
Collection<File> transitiveResources =
OutputArtifactResolver.resolveAll(
project, artifactLocationDecoder, androidResourceModule.transitiveResources);
// labelsRelatedToContext should include deps,
// but as a first pass we only check the rules themselves
// for resources. If we come up empty, then have anyResDir as a backup.
allResDirs.addAll(transitiveResources);
if (rulesRelatedToContext != null
&& !rulesRelatedToContext.contains(androidResourceModule.targetKey)) {
continue;
}
resourceDirs.addAll(resources);
transitiveDirs.addAll(transitiveResources);
}
// No need to show some directories twice.
transitiveDirs.removeAll(resourceDirs);
JComboBox resDirCombo = resDirComboAndBrowser.getComboBox();
// Allow the user to browse and overwrite some of the entries,
// in case our inference is wrong.
resDirCombo.setEditable(true);
// Optimize the right-click on a non-res directory (consider res directory right under that)
// After the use confirms the choice, a directory will be created if it is missing.
if (fileFromContext != null && fileFromContext.isDirectory()) {
File closestDirToContext = new File(fileFromContext.getPath(), "res");
resDirCombo.setSelectedItem(closestDirToContext);
} else {
// If we're not completely sure, let people know there are options
// via the placeholder text, and put the most likely on top.
String placeHolder = PLACEHOLDER_TEXT;
resDirCombo.addItem(placeHolder);
resDirCombo.setSelectedItem(placeHolder);
if (fileFromContext != null) {
File closestDirToContext =
findClosestDirToContext(fileFromContext.getPath(), resourceDirs);
closestDirToContext =
closestDirToContext != null
? closestDirToContext
: findClosestDirToContext(fileFromContext.getPath(), transitiveDirs);
if (closestDirToContext != null) {
resDirCombo.addItem(closestDirToContext);
resourceDirs.remove(closestDirToContext);
transitiveDirs.remove(closestDirToContext);
}
}
}
if (!resourceDirs.isEmpty() || !transitiveDirs.isEmpty()) {
for (File resourceDir : resourceDirs) {
resDirCombo.addItem(resourceDir);
}
for (File resourceDir : transitiveDirs) {
resDirCombo.addItem(resourceDir);
}
} else {
for (File resourceDir : allResDirs) {
resDirCombo.addItem(resourceDir);
}
}
resDirComboAndBrowser.setVisible(true);
resDirLabel.setVisible(true);
}
}
}
private static File findClosestDirToContext(String contextPath, Set<File> resourceDirs) {
File closestDirToContext = null;
int curStringDistance = Integer.MAX_VALUE;
for (File resDir : resourceDirs) {
int distance = StringUtil.difference(contextPath, resDir.getPath());
if (distance < curStringDistance) {
curStringDistance = distance;
closestDirToContext = resDir;
}
}
return closestDirToContext;
}
static PsiDirectory getResDirFromUI(Project project, ComboboxWithBrowseButton directoryCombo) {
PsiManager psiManager = PsiManager.getInstance(project);
Object selectedItem = directoryCombo.getComboBox().getEditor().getItem();
File selectedFile = null;
if (selectedItem instanceof File) {
selectedFile = (File) selectedItem;
} else if (selectedItem instanceof String) {
String selectedDir = (String) selectedItem;
if (!selectedDir.equals(PLACEHOLDER_TEXT)) {
selectedFile = new File(selectedDir);
}
}
if (selectedFile == null) {
return null;
}
final File finalSelectedFile = selectedFile;
return ApplicationManager.getApplication()
.runWriteAction(
new Computable<PsiDirectory>() {
@Override
public PsiDirectory compute() {
return DirectoryUtil.mkdirs(psiManager, finalSelectedFile.getPath());
}
});
}
static VirtualFile getResDirFromDataContext(VirtualFile contextFile) {
// Check if the contextFile is somewhere in
// the <path>/res/resType/foo.xml hierarchy and return <path>/res/.
if (contextFile.isDirectory()) {
if (contextFile.getName().equalsIgnoreCase(SdkConstants.FD_RES)) {
return contextFile;
}
if (ResourceFolderType.getFolderType(contextFile.getName()) != null) {
VirtualFile parent = contextFile.getParent();
if (parent != null && parent.getName().equalsIgnoreCase(SdkConstants.FD_RES)) {
return parent;
}
}
} else {
VirtualFile parent = contextFile.getParent();
if (parent != null && ResourceFolderType.getFolderType(parent.getName()) != null) {
// Otherwise, the contextFile is a file w/ a parent that is plausible.
// Recurse one level, on the parent.
return getResDirFromDataContext(parent);
}
}
// Otherwise, it may be too ambiguous to figure out (e.g., we're in a .java file).
return null;
}
} |
Java | public class Sort012inOneIteration {
// Binary sorting
public static void sort012(int a[]) {
int lo = 0;
int hi = a.length - 1;
int mid = 0, temp = 0;
while (mid <= hi) {
switch (a[mid]) {
case 0: {
if(a[lo] != a[mid]) {
temp = a[lo];
a[lo] = a[mid];
a[mid] = temp;
}
lo++; mid++;
break;
}
case 1:
mid++;
break;
case 2: {
if(a[hi] != a[mid]) {
temp = a[mid];
a[mid] = a[hi];
a[hi] = temp;
}
hi--;
break;
}
}
}
System.out.println(Arrays.toString(a));
}
public static void main(String args[]) {
sort012(new int[]{0, 1, 2, 1, 0, 2, 0});
}
} |
Java | @RunnerHttpClass(runner=RunnerHttpSetProperty.class)
@RunnerRestClass(runner=RunnerRestSetProperty.class)
public class CommandSetProperty extends Command {
////////////////////////////////////////////////////////////////////////////
// Class attributes //
////////////////////////////////////////////////////////////////////////////
/** Command string for create-cluster command. */
private static final String COMMAND = "set";
/** Error message prefix for administration command execution exception .*/
private static final String ERROR_MESSAGE_PREFIX
= "Could not set value ";
/** Error message middle part for administration command execution
* exception .*/
private static final String ERROR_MESSAGE_MIDDLE
= " of property ";
////////////////////////////////////////////////////////////////////////////
// Static methods //
////////////////////////////////////////////////////////////////////////////
/**
* Build error message from command property name and it's value.
* <p/>
* @param command Command used to build error message.
* @return Error message for administration command execution exception.
*/
private static String errorMessage(final CommandSetProperty command) {
int valueLen = command.value != null
? command.value.length() : 0;
int propertyLen = command.property != null
? command.property.length() : 0;
StringBuilder sb = new StringBuilder(ERROR_MESSAGE_PREFIX.length()
+ ERROR_MESSAGE_MIDDLE.length() + valueLen + propertyLen);
sb.append(ERROR_MESSAGE_PREFIX);
sb.append(valueLen > 0 ? command.value : "");
sb.append(ERROR_MESSAGE_MIDDLE);
sb.append(propertyLen > 0 ? command.property : "");
return sb.toString();
}
/**
* Put property to server.
* <p/>
* @param server GlassFish server entity.
* @param command Command to set property value.
* @return GlassFish command result containing <code>String</code> with
* result message.
* @throws GlassFishIdeException When error occurred during administration
* command execution.
*/
public static ResultString setProperty(
final GlassFishServer server, final CommandSetProperty command)
throws GlassFishIdeException {
Future<ResultString> future =
ServerAdmin.<ResultString>exec(server, command);
try {
return future.get();
} catch (ExecutionException | InterruptedException
| CancellationException ee) {
throw new GlassFishIdeException(errorMessage(command), ee);
}
}
/**
* Put property to server.
* <p/>
* @param server GlassFish server entity.
* @param command Command to set property value.
* @param timeout Administration command execution timeout [ms].
* @return GlassFish command result containing <code>String</code> with
* result message.
* @throws GlassFishIdeException When error occurred during administration
* command execution.
*/
public static ResultString setProperty(
final GlassFishServer server, final CommandSetProperty command,
final long timeout) throws GlassFishIdeException {
Future<ResultString> future =
ServerAdmin.<ResultString>exec(server, command);
try {
return future.get(timeout, TimeUnit.MILLISECONDS);
} catch (ExecutionException | InterruptedException
| CancellationException ee) {
throw new GlassFishIdeException(errorMessage(command), ee);
} catch (TimeoutException te) {
throw new GlassFishIdeException(errorMessage(command)
+ " in " + timeout + "ms", te);
}
}
////////////////////////////////////////////////////////////////////////////
// Instance attributes //
////////////////////////////////////////////////////////////////////////////
/** Name of the property to set. */
final String property;
/** Value of the property to set. */
final String value;
/** Format for the query string. */
final String format;
////////////////////////////////////////////////////////////////////////////
// Constructors //
////////////////////////////////////////////////////////////////////////////
/**
* Constructs an instance of GlassFish server set property command entity.
* <p/>
* @param property Name of the property to set.
* @param value Value of the property to set.
* @param format Format for the query string.
*/
public CommandSetProperty(final String property, final String value,
final String format) {
super(COMMAND);
this.property = property;
this.value = value;
this.format = format;
}
/**
* Constructs an instance of GlassFish server set property command entity.
* <p/>
* @param property Name of the property to set.
* @param value Value of the property to set.
*/
public CommandSetProperty(final String property, final String value) {
super(COMMAND);
this.property = property;
this.value = value;
this.format = "DEFAULT={0}={1}";
}
////////////////////////////////////////////////////////////////////////////
// Getters //
////////////////////////////////////////////////////////////////////////////
/**
* Get name of the property to set.
* <p/>
* @return Name of the property to set.
*/
public String getProperty() {
return property;
}
/**
* Get value of the property to set.
* <p/>
* @return Value of the property to set.
*/
public String getValue() {
return value;
}
} |
Java | public class PolicyCreatorUtil {
/**
* Creates XML request from RequestDTO object
*
* @param requestDTO
* @return
*/
public static RequestElementDTO createRequestElementDTO(RequestDTO requestDTO) {
RequestElementDTO requestElement = new RequestElementDTO();
List<RowDTO> rowDTOs = requestDTO.getRowDTOs();
if (rowDTOs == null || rowDTOs.size() < 1) {
return requestElement;
}
Map<String, AttributesElementDTO> dtoMap = new HashMap<String, AttributesElementDTO>();
List<AttributesElementDTO> dtoList = new ArrayList<AttributesElementDTO>();
for (RowDTO rowDTO : rowDTOs) {
String category = rowDTO.getCategory();
String value = rowDTO.getAttributeValue();
String attributeId = rowDTO.getAttributeId();
if (category != null && category.trim().length() > 0 && value != null &&
value.trim().length() > 0 && attributeId != null && attributeId.trim().length() > 0) {
if (requestDTO.isMultipleRequest()) {
String[] values = value.split(EntitlementPolicyConstants.ATTRIBUTE_SEPARATOR);
for (String attributeValue : values) {
AttributesElementDTO attributesElementDTO = new AttributesElementDTO();
attributesElementDTO.setCategory(category);
AttributeElementDTO attributeElementDTO = new AttributeElementDTO();
attributeElementDTO.addAttributeValue(attributeValue);
attributeElementDTO.setAttributeId(attributeId);
attributeElementDTO.setIncludeInResult(rowDTO.isNotCompleted());
attributesElementDTO.addAttributeElementDTO(attributeElementDTO);
if (rowDTO.getAttributeDataType() != null && rowDTO.
getAttributeDataType().trim().length() > 0) {
attributeElementDTO.setDataType(rowDTO.getAttributeDataType());
} else {
attributeElementDTO.setDataType(EntitlementPolicyConstants.STRING_DATA_TYPE);
}
dtoList.add(attributesElementDTO);
}
} else {
AttributesElementDTO attributesElementDTO = dtoMap.get(category);
if (attributesElementDTO == null) {
attributesElementDTO = new AttributesElementDTO();
attributesElementDTO.setCategory(category);
}
String[] values = value.split(EntitlementPolicyConstants.ATTRIBUTE_SEPARATOR);
AttributeElementDTO attributeElementDTO = new AttributeElementDTO();
attributeElementDTO.setAttributeValues(Arrays.asList(values));
attributeElementDTO.setAttributeId(attributeId);
attributeElementDTO.setIncludeInResult(rowDTO.isNotCompleted());
attributesElementDTO.addAttributeElementDTO(attributeElementDTO);
if (rowDTO.getAttributeDataType() != null && rowDTO.
getAttributeDataType().trim().length() > 0) {
attributeElementDTO.setDataType(rowDTO.getAttributeDataType());
} else {
attributeElementDTO.setDataType(EntitlementPolicyConstants.STRING_DATA_TYPE);
}
dtoMap.put(category, attributesElementDTO);
}
}
}
requestElement.setMultipleRequest(requestDTO.isMultipleRequest());
requestElement.setCombinedDecision(requestDTO.isCombinedDecision());
requestElement.setReturnPolicyIdList(requestDTO.isReturnPolicyIdList());
if (!requestDTO.isMultipleRequest()) {
dtoList = new ArrayList<AttributesElementDTO>();
for (Map.Entry<String, AttributesElementDTO> entry : dtoMap.entrySet()) {
dtoList.add(entry.getValue());
}
}
requestElement.setAttributesElementDTOs(dtoList);
return requestElement;
}
} |
Java | public class AdressePreviewPresenter extends AbstractPresenter<AdressePreviewView> {
@Inject
public AdressePreviewPresenter(final NavigationManager navigationManager,
final AdressePreviewView view) {
super(navigationManager, view);
}
@Override
public void start(BorderPane container) {
bind();
}
@Override
public void bind() {
}
/**
* Adresse preview event from eventBus.
*
* @param adresse adresse entity
*/
public void onModelChanged(Adresse adresse) {
if (adresse == null) {
cleanLabels();
} else {
setLabels(adresse);
}
}
private void cleanLabels() {
view.getLblAnredeTitelName().setText("");
view.getLblFirma1().setText("");
view.getLblFirma2().setText("");
view.getLblPostfachPlz().setText("");
view.getLblPostfach().setText("");
view.getLblStrasse().setText("");
view.getLblPlzOrt().setText("");
view.getLblLand().setText("");
setVisibility(view.getLblPostfachPlz(), "");
setVisibility(view.getLblStrasse(), "");
view.getLblMobiltelefon().setText("");
view.getLblTelefonPrivat().setText("");
view.getLblTelefonDienst().setText("");
view.getLblFaxPrivat().setText("");
view.getLblFaxDienst().setText("");
view.getLblSkype().setText("");
setVisibility(view.getLblMobiltelefon(), "");
setVisibility(view.getLblTelefonPrivat(), "");
setVisibility(view.getLblTelefonDienst(), "");
setVisibility(view.getLblFaxPrivat(), "");
setVisibility(view.getLblFaxDienst(), "");
setVisibility(view.getLblSkype(), "");
view.getLblEmail().setText("");
view.getLblHomepage().setText("");
view.getLblFacebook().setText("");
view.getLblTwitter().setText("");
view.getLblXing().setText("");
view.getLblLinkedin().setText("");
view.getLblGooglePlus().setText("");
setVisibility(view.getLblEmail(), "");
setVisibility(view.getLblHomepage(), "");
setVisibility(view.getLblFacebook(), "");
setVisibility(view.getLblTwitter(), "");
setVisibility(view.getLblXing(), "");
setVisibility(view.getLblLinkedin(), "");
setVisibility(view.getLblGooglePlus(), "");
}
private void setLabels(Adresse adresse) {
if (adresse.getTitel() != null) {
view.getLblAnredeTitelName().setText(
adresse.getAnrede().getBezeichnung() + " " +
adresse.getTitel().getBezeichnung() + " " +
adresse.getVorname() + " " + adresse.getNachname());
} else {
view.getLblAnredeTitelName().setText(
adresse.getAnrede().getBezeichnung() + " " +
adresse.getVorname() + " " + adresse.getNachname());
}
view.getLblFirma1().setText(adresse.getFirma1());
view.getLblFirma2().setText(adresse.getFirma2());
view.getLblPostfachPlz().setText(adresse.getPostfachPlz());
view.getLblPostfach().setText(adresse.getPostfach());
view.getLblStrasse().setText(adresse.getStrasse());
if (adresse.getOrt() != null) {
view.getLblPlzOrt().setText(adresse.getPlz() + " " + adresse.getOrt());
} else {
view.getLblPlzOrt().setText(adresse.getPlz());
}
view.getLblLand().setText(adresse.getLand().getName());
setVisibility(view.getLblPostfachPlz(), adresse.getPostfachPlz());
setVisibility(view.getLblStrasse(), adresse.getStrasse());
view.getLblMobiltelefon().setText(adresse.getMobiltelefon());
view.getLblTelefonPrivat().setText(adresse.getTelefonPrivat());
view.getLblTelefonDienst().setText(adresse.getTelefonDienst());
view.getLblFaxPrivat().setText(adresse.getFaxPrivat());
view.getLblFaxDienst().setText(adresse.getFaxDienst());
view.getLblSkype().setText(adresse.getSkype());
setVisibility(view.getLblMobiltelefon(), adresse.getMobiltelefon());
setVisibility(view.getLblTelefonPrivat(), adresse.getTelefonPrivat());
setVisibility(view.getLblTelefonDienst(), adresse.getTelefonDienst());
setVisibility(view.getLblFaxPrivat(), adresse.getFaxPrivat());
setVisibility(view.getLblFaxDienst(), adresse.getFaxDienst());
setVisibility(view.getLblSkype(), adresse.getSkype());
view.getLblEmail().setText(adresse.getEmail());
view.getLblHomepage().setText(adresse.getHomepage());
view.getLblFacebook().setText(adresse.getFacebook());
view.getLblTwitter().setText(adresse.getTwitter());
view.getLblXing().setText(adresse.getXing());
view.getLblLinkedin().setText(adresse.getLinkedin());
view.getLblGooglePlus().setText(adresse.getGooglePlus());
setVisibility(view.getLblEmail(), adresse.getEmail());
setVisibility(view.getLblHomepage(), adresse.getHomepage());
setVisibility(view.getLblFacebook(), adresse.getFacebook());
setVisibility(view.getLblTwitter(), adresse.getTwitter());
setVisibility(view.getLblXing(), adresse.getXing());
setVisibility(view.getLblLinkedin(), adresse.getLinkedin());
setVisibility(view.getLblGooglePlus(), adresse.getGooglePlus());
}
private void setVisibility(Label label, String value) {
if (StringUtils.isEmpty(value)) {
label.setVisible(false);
} else {
label.setVisible(true);
}
}
} |
Java | @RestController
@ExposesResourceFor(Sample.class)
@RequestMapping("/samples/{accession}")
@CrossOrigin
public class SampleRestController {
private Logger log = LoggerFactory.getLogger(getClass());
private final SampleService sampleService;
private final BioSamplesAapService bioSamplesAapService;
private final BioSamplesWebinAuthenticationService bioSamplesWebinAuthenticationService;
private final SampleManipulationService sampleManipulationService;
private final SampleResourceAssembler sampleResourceAssembler;
private PhenopacketConverter phenopacketConverter;
private final SchemaValidationService schemaValidationService;
private final ENATaxonClientService enaTaxonClientService;
public SampleRestController(
SampleService sampleService,
BioSamplesAapService bioSamplesAapService,
BioSamplesWebinAuthenticationService bioSamplesWebinAuthenticationService,
SampleManipulationService sampleManipulationService,
SampleResourceAssembler sampleResourceAssembler,
PhenopacketConverter phenopacketConverter,
SchemaValidationService schemaValidationService,
ENATaxonClientService enaTaxonClientService) {
this.sampleService = sampleService;
this.bioSamplesAapService = bioSamplesAapService;
this.bioSamplesWebinAuthenticationService = bioSamplesWebinAuthenticationService;
this.sampleManipulationService = sampleManipulationService;
this.sampleResourceAssembler = sampleResourceAssembler;
this.phenopacketConverter = phenopacketConverter;
this.schemaValidationService = schemaValidationService;
this.enaTaxonClientService = enaTaxonClientService;
}
@PreAuthorize("isAuthenticated()")
@CrossOrigin(methods = RequestMethod.GET)
@GetMapping(produces = {MediaTypes.HAL_JSON_VALUE, MediaType.APPLICATION_JSON_VALUE})
public Resource<Sample> getSampleHal(
HttpServletRequest request,
@PathVariable String accession,
@RequestParam(name = "legacydetails", required = false) String legacydetails,
@RequestParam(name = "curationdomain", required = false) String[] curationdomain,
@RequestParam(name = "curationrepo", required = false) String curationRepo,
@RequestParam(name = "authProvider", required = false, defaultValue = "AAP")
String authProvider) {
final boolean webinAuth = authProvider.equalsIgnoreCase("WEBIN");
// decode percent-encoding from curation domains
final Optional<List<String>> decodedCurationDomains =
LinkUtils.decodeTextsToArray(curationdomain);
final Optional<Boolean> decodedLegacyDetails;
if ("true".equals(legacydetails)) {
decodedLegacyDetails = Optional.of(Boolean.TRUE);
} else {
decodedLegacyDetails = Optional.empty();
}
// convert it into the format to return
Optional<Sample> sample = sampleService.fetch(accession, decodedCurationDomains, curationRepo);
if (sample.isPresent()) {
if (webinAuth) {
final BearerTokenExtractor bearerTokenExtractor = new BearerTokenExtractor();
final Authentication authentication = bearerTokenExtractor.extract(request);
final SubmissionAccount webinAccount =
bioSamplesWebinAuthenticationService
.getWebinSubmissionAccount(String.valueOf(authentication.getPrincipal()))
.getBody();
bioSamplesWebinAuthenticationService.checkSampleAccessibility(
sample.get(), webinAccount.getId());
} else {
bioSamplesAapService.checkAccessible(sample.get());
}
// TODO If user is not Read super user, reduce the fields to show
if (decodedLegacyDetails.isPresent() && decodedLegacyDetails.get()) {
sample = Optional.of(sampleManipulationService.removeLegacyFields(sample.get()));
}
// TODO cache control
return sampleResourceAssembler.toResource(
sample.get(), decodedLegacyDetails, decodedCurationDomains);
} else {
throw new SampleNotFoundException();
}
}
@RequestMapping(produces = "application/phenopacket+json")
@PreAuthorize("isAuthenticated()")
@CrossOrigin(methods = RequestMethod.GET)
@GetMapping()
public String getSamplePhenopacket(
@PathVariable String accession,
@RequestParam(name = "legacydetails", required = false) String legacydetails,
@RequestParam(name = "curationdomain", required = false) String[] curationdomain,
@RequestParam(name = "curationrepo", required = false) final String curationRepo) {
log.trace("starting call");
// decode percent-encoding from curation domains
Optional<List<String>> decodedCurationDomains = LinkUtils.decodeTextsToArray(curationdomain);
Optional<Boolean> decodedLegacyDetails;
if ("true".equals(legacydetails)) {
decodedLegacyDetails = Optional.of(Boolean.TRUE);
} else {
decodedLegacyDetails = Optional.empty();
}
// convert it into the format to return
Optional<Sample> sample = sampleService.fetch(accession, decodedCurationDomains, curationRepo);
if (sample.isPresent()) {
bioSamplesAapService.checkAccessible(sample.get());
// TODO If user is not Read super user, reduce the fields to show
if (decodedLegacyDetails.isPresent() && decodedLegacyDetails.get()) {
sample = Optional.of(sampleManipulationService.removeLegacyFields(sample.get()));
}
return phenopacketConverter.convertToJsonPhenopacket(sample.get());
} else {
throw new SampleNotFoundException();
}
}
@PreAuthorize("isAuthenticated()")
@CrossOrigin(methods = RequestMethod.GET)
@GetMapping(produces = {MediaType.APPLICATION_XML_VALUE, MediaType.TEXT_XML_VALUE})
public Sample getSampleXml(
@PathVariable String accession,
@RequestParam(name = "curationrepo", required = false) final String curationRepo) {
Sample sample =
this.getSampleHal(null, accession, "true", null, curationRepo, "AAP").getContent();
if (!sample.getAccession().matches("SAMEG\\d+")) {
sample =
Sample.Builder.fromSample(sample)
.withNoOrganisations()
.withNoPublications()
.withNoContacts()
.build();
}
return sample;
}
@PreAuthorize("isAuthenticated()")
@PutMapping(consumes = {MediaType.APPLICATION_JSON_VALUE})
public Resource<Sample> put(
HttpServletRequest request,
@PathVariable String accession,
@RequestBody Sample sample,
@RequestParam(name = "setfulldetails", required = false, defaultValue = "true")
boolean setFullDetails,
@RequestParam(name = "authProvider", required = false, defaultValue = "AAP")
String authProvider) {
final boolean webinAuth = authProvider.equalsIgnoreCase("WEBIN");
final SortedSet<AbstractData> abstractData = sample.getData();
boolean isWebinSuperUser = false;
if (sample.getAccession() == null || !sample.getAccession().equals(accession)) {
throw new SampleAccessionMismatchException();
}
log.debug("Received PUT for " + accession);
if (webinAuth) {
final BearerTokenExtractor bearerTokenExtractor = new BearerTokenExtractor();
final Authentication authentication = bearerTokenExtractor.extract(request);
final SubmissionAccount webinAccount =
bioSamplesWebinAuthenticationService
.getWebinSubmissionAccount(String.valueOf(authentication.getPrincipal()))
.getBody();
final String webinAccountId = webinAccount.getId();
isWebinSuperUser = bioSamplesWebinAuthenticationService.isWebinSuperUser(webinAccountId);
if (sampleService.isNotExistingAccession(accession) && !isWebinSuperUser) {
throw new SampleAccessionDoesNotExistException();
}
sample = bioSamplesWebinAuthenticationService.handleWebinUser(sample, webinAccountId);
if (abstractData != null && abstractData.size() > 0) {
if (bioSamplesWebinAuthenticationService.findIfOriginalSampleWebinSubmitter(
sample, webinAccountId)) {
sample = Sample.Builder.fromSample(sample).build();
} else {
sample = Sample.Builder.fromSample(sample).withNoData().build();
}
}
} else {
if (sampleService.isNotExistingAccession(accession)
&& !(bioSamplesAapService.isWriteSuperUser()
|| bioSamplesAapService.isIntegrationTestUser())) {
throw new SampleAccessionDoesNotExistException();
}
sample = bioSamplesAapService.handleSampleDomain(sample);
if (abstractData != null && abstractData.size() > 0) {
if (bioSamplesAapService.checkIfOriginalAAPSubmitter(sample)) {
sample = Sample.Builder.fromSample(sample).build();
} else if (bioSamplesAapService.isWriteSuperUser()
|| bioSamplesAapService.isIntegrationTestUser()) {
sample = Sample.Builder.fromSample(sample).build();
} else {
sample = Sample.Builder.fromSample(sample).withNoData().build();
}
}
}
// now date is system generated field
Instant now = Instant.now();
SubmittedViaType submittedVia =
sample.getSubmittedVia() == null ? SubmittedViaType.JSON_API : sample.getSubmittedVia();
sample =
Sample.Builder.fromSample(sample).withUpdate(now).withSubmittedVia(submittedVia).build();
// Dont validate superuser samples, this helps to submit external (eg. NCBI, ENA) samples
if (webinAuth && !isWebinSuperUser) {
schemaValidationService.validate(sample);
} else if (!webinAuth && !bioSamplesAapService.isWriteSuperUser()) {
schemaValidationService.validate(sample);
}
if (submittedVia == SubmittedViaType.FILE_UPLOADER) {
schemaValidationService.validate(sample);
}
if (webinAuth && !isWebinSuperUser) {
sample = enaTaxonClientService.performTaxonomyValidation(sample);
}
final boolean isFirstTimeMetadataAdded = sampleService.beforeStore(sample, isWebinSuperUser);
if (isFirstTimeMetadataAdded) {
sample = Sample.Builder.fromSample(sample).withSubmitted(now).build();
}
if (!setFullDetails) {
log.trace("Removing contact legacy fields for " + accession);
sample = sampleManipulationService.removeLegacyFields(sample);
}
sample = sampleService.store(sample, isFirstTimeMetadataAdded, authProvider);
// assemble a resource to return
// create the response object with the appropriate status
return sampleResourceAssembler.toResource(sample);
}
/*At this moment this patching is only for structured data*/
@PreAuthorize("isAuthenticated()")
@PatchMapping(consumes = {MediaType.APPLICATION_JSON_VALUE})
public Resource<Sample> patchStructuredData(
HttpServletRequest request,
@PathVariable String accession,
@RequestBody Sample sample,
@RequestParam(name = "structuredData", required = false, defaultValue = "false")
boolean structuredData,
@RequestParam(name = "authProvider", required = false, defaultValue = "AAP")
String authProvider) {
if (!structuredData) throw new SampleDataPatchMethodNotSupportedException();
if (sample.getAccession() == null || !sample.getAccession().equals(accession)) {
throw new SampleAccessionMismatchException();
}
if (authProvider.equalsIgnoreCase("WEBIN")) {
final BearerTokenExtractor bearerTokenExtractor = new BearerTokenExtractor();
final Authentication authentication = bearerTokenExtractor.extract(request);
final SubmissionAccount webinAccount =
bioSamplesWebinAuthenticationService
.getWebinSubmissionAccount(String.valueOf(authentication.getPrincipal()))
.getBody();
sample =
bioSamplesWebinAuthenticationService.handleStructuredDataAccesibility(
sample, webinAccount.getId());
sample = sampleService.storeSampleStructuredData(sample, authProvider);
return sampleResourceAssembler.toResource(sample);
} else {
if (sampleService.isNotExistingAccession(accession)
&& !(bioSamplesAapService.isWriteSuperUser()
|| bioSamplesAapService.isIntegrationTestUser())) {
throw new SampleAccessionDoesNotExistException();
}
log.debug("Received PATCH for " + accession);
sample = bioSamplesAapService.handleStructuredDataDomain(sample);
sample = sampleService.storeSampleStructuredData(sample, authProvider);
return sampleResourceAssembler.toResource(sample);
}
}
@ResponseStatus(
value = HttpStatus.BAD_REQUEST,
reason = "Sample accession must match URL accession") // 400
public static class SampleAccessionMismatchException extends RuntimeException {}
@ResponseStatus(
value = HttpStatus.METHOD_NOT_ALLOWED,
reason = "Pass argument structuredData=true if you want to PATCH data to sample") // 400
public static class SampleDataPatchMethodNotSupportedException extends RuntimeException {}
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "Sample accession does not exist") // 400
public static class SampleAccessionDoesNotExistException extends RuntimeException {}
} |
Java | public class Hcs12DisassembleCommand extends DisassembleCommand {
private boolean xgMode;
/**
* Constructor for Hcs12DisassembleCommand.
* @param startSet set of addresses to be the start of a disassembly. The
* Command object will attempt to start a disassembly at each address in this set.
* @param restrictedSet addresses that can be disassembled.
* a null set implies no restrictions
* @param xgMode pass true if the disassembling in XGATE Mode
*/
public Hcs12DisassembleCommand(AddressSetView startSet, AddressSetView restrictedSet,
boolean xgMode) {
super("Disassemble " + (xgMode ? "XGate" : "HCS12"), startSet, restrictedSet, true);
this.xgMode = xgMode;
}
/**
* Constructor for Hcs12DisassembleCommand.
* @param start address to be the start of a disassembly.
* @param restrictedSet addresses that can be disassembled.
* a null set implies no restrictions
* @param xgMode pass true if the disassembling in XGATE Mode
*/
public Hcs12DisassembleCommand(Address start, AddressSetView restrictedSet, boolean xgMode) {
this(new AddressSet(start, start), restrictedSet, xgMode);
useDefaultRepeatPatternBehavior = true;
}
@Override
public void setSeedContext(DisassemblerContextImpl seedContext) {
throw new UnsupportedOperationException();
}
@Override
public void setInitialContext(RegisterValue initialContextValue) {
throw new UnsupportedOperationException();
}
@Override
synchronized public boolean applyTo(DomainObject obj, TaskMonitor monitor) {
Program program = (Program) obj;
disassemblyPerformed = false;
unalignedStart = false;
// get the XGATE mode register and set accordingly
Register xgmodeReg = program.getProgramContext().getRegister("XGATE");
RegisterValue xgmodeValue = null;
// if doing xgate, and have no XGmode reg, no way to do disassemble in xgate
if (xgmodeReg == null) {
if (xgMode) {
return false;
}
}
else {
xgmodeValue = new RegisterValue(xgmodeReg, BigInteger.valueOf(xgMode ? 0x1 : 0x0));
super.setInitialContext(xgmodeValue);
}
int alignment = 1;
// Set XGate Mode context on undefined code units only
try {
if (startSet != null) {
// Align startSet so that context only affected at possible instruction starts
AddressSet alignedSet = new AddressSet();
for (AddressRange range : startSet) {
Address min = range.getMinAddress();
long minOfffset = min.getOffset();
if (minOfffset != min.getOffset()) {
min = min.getNewAddress(minOfffset);
}
Address max = range.getMaxAddress();
long maxOffset = max.getOffset();
if (maxOffset < minOfffset) {
// skip short unaligned range
continue;
}
if (maxOffset != max.getOffset()) {
max = max.getNewAddress(maxOffset);
}
alignedSet.addRange(min, max);
}
if (alignedSet.isEmpty()) {
unalignedStart = true;
return false; // alignedSet does not contain any aligned starts
}
startSet = program.getListing().getUndefinedRanges(alignedSet, true, monitor);
if (startSet.isEmpty()) {
return true; // startSet does not contain any aligned undefined starts
}
}
}
catch (CancelledException e) {
return true;
}
return doDisassembly(monitor, program, alignment);
}
} |
Java | public class EditListCostComparator implements Comparator<EditList> {
boolean ascending = true;
/**
* default constructor
*/
public EditListCostComparator() {
super();
}
/**
* @return true if the comparator returns -1 when degree1 smallest, false if -1 returned when degree2 is smallest
*/
public boolean getAscending() {return ascending;}
/**
* @param if set to true the comparator returns -1 when degree1 smallest, if set to true -1 returned when degree2 is smallest
*/
public void setAscending(boolean ascending) {this.ascending = ascending;}
/**
* Just compares the costs via standard Double comparison
*
* @return a negative integer, zero, or a positive integer if the first argument is less than, equal to, or greater than the second,
* unless ascending is set to false in which case negative and positive are swapped.
*/
@Override
public int compare(EditList el1, EditList el2) {
if(ascending) {
return Double.compare(el1.getCost(), el2.getCost());
}
return Double.compare(el2.getCost(), el1.getCost());
}
} |
Java | public class EventProcessorBuilderJavaDocCodeSamples {
/**
* Code snippet for showing how to create a new instance of {@link EventProcessor}.
*
* @return A new instance of {@link EventProcessor}
*/
// BEGIN: com.azure.messaging.eventhubs.eventprocessorbuilder.instantiation
public EventProcessor createEventProcessor() {
String connectionString = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};"
+ "SharedAccessKey={sharedAccessKey};EntityPath={eventHubName}";
EventHubAsyncClient eventHubAsyncClient = new EventHubClientBuilder()
.connectionString(connectionString)
.buildAsyncClient();
EventProcessor eventProcessor = new EventProcessorBuilder()
.consumerGroup("consumer-group")
.eventHubClient(eventHubAsyncClient)
.partitionProcessorFactory((PartitionProcessorImpl::new))
.partitionManager(new InMemoryPartitionManager())
.buildEventProcessor();
return eventProcessor;
}
/**
* A partition processor to demo creating an instance of {@link EventProcessor}.
*/
public static final class PartitionProcessorImpl extends PartitionProcessor {
/**
* Processes the event data.
*
* @return a representation of deferred processing of events.
*/
@Override
public Mono<Void> processEvent(PartitionContext partitionContext, EventData eventData) {
System.out.println("Processing event with sequence number " + eventData.getSequenceNumber());
return partitionContext.updateCheckpoint(eventData);
}
}
// END: com.azure.messaging.eventhubs.eventprocessorbuilder.instantiation
} |
Java | public static final class PartitionProcessorImpl extends PartitionProcessor {
/**
* Processes the event data.
*
* @return a representation of deferred processing of events.
*/
@Override
public Mono<Void> processEvent(PartitionContext partitionContext, EventData eventData) {
System.out.println("Processing event with sequence number " + eventData.getSequenceNumber());
return partitionContext.updateCheckpoint(eventData);
}
} |
Java | public class SnomedSimpleTypeRefSetDSVExporter implements IRefSetDSVExporter {
private static final String HEADER_EXPAND = "descriptions(active:true),"
+ "relationships(active:true),"
+ "members()";
private static final String DATA_EXPAND = "pt(),"
+ "descriptions(active:true),"
+ "relationships(active:true,expand(destination(expand(pt())))),"
+ "members()";
private static final Map<String, Integer> NO_OCCURRENCES = ImmutableMap.of();
private final BranchContext context;
private String refSetId;
private boolean includeDescriptionId;
private boolean includeRelationshipId;
private boolean includeInactiveMembers;
private List<AbstractSnomedDsvExportItem> exportItems;
private List<ExtendedLocale> locales;
private Joiner joiner;
private String lineSeparator;
private Map<String, Integer> descriptionCount; // maximum number of descriptions by type
private Map<Integer, Map<String, Integer>> propertyCountByGroup; // maximum number of properties by group and type
/**
* Creates a new instance with the export parameters.
*
* @param exportSetting
*/
public SnomedSimpleTypeRefSetDSVExporter(final BranchContext context, final SnomedRefSetDSVExportModel exportSetting) {
this.refSetId = exportSetting.getRefSetId();
this.includeDescriptionId = exportSetting.includeDescriptionId();
this.includeRelationshipId = exportSetting.includeRelationshipTargetId();
this.includeInactiveMembers = exportSetting.includeInactiveMembers();
this.exportItems = exportSetting.getExportItems();
this.locales = exportSetting.getLocales();
this.context = context;
this.joiner = Joiner.on(exportSetting.getDelimiter());
this.lineSeparator = System.lineSeparator();
}
/**
* Executes the export to delimiter separated values.
*
* @param monitor
* @return The file with the exported values.
*/
@Override
public File executeDSVExport(IProgressMonitor monitor) throws IOException {
monitor.beginTask("Export RefSet to DSV...", 100);
Path exportPath = Files.createTempFile("dsv-export-" + refSetId + Dates.now(), ".csv");
try {
try (BufferedWriter writer = Files.newBufferedWriter(exportPath, Charsets.UTF_8)) {
computeHeader();
writeHeader(writer);
writeValues(monitor, writer);
}
return exportPath.toFile();
} finally {
if (null != monitor) {
monitor.done();
}
}
}
/*
* Fetches members of the specified reference set, ignoring items where the referenced concept is inactive.
*/
private SearchResourceRequestIterator<SnomedConceptSearchRequestBuilder, SnomedConcepts> getMemberConceptIterator(String expand) {
SnomedConceptSearchRequestBuilder builder = SnomedRequests.prepareSearchConcept()
.setLocales(locales)
.setExpand(expand)
.filterByActive(true)
.sortBy(SortField.ascending(SnomedConceptDocument.Fields.ID))
.setScroll("15m")
.setLimit(10_000);
if (includeInactiveMembers) {
builder.isMemberOf(refSetId);
} else {
builder.isActiveMemberOf(refSetId);
}
return new SearchResourceRequestIterator<>(builder, b -> b.build().execute(context));
}
/*
* Finds the maximum number of occurrences for each description, relationship and concrete data type; generates headers.
*/
private void computeHeader() {
descriptionCount = newHashMap();
propertyCountByGroup = newHashMap();
SearchResourceRequestIterator<SnomedConceptSearchRequestBuilder, SnomedConcepts> conceptIterator = getMemberConceptIterator(HEADER_EXPAND);
while (conceptIterator.hasNext()) {
computeHeader(conceptIterator.next());
}
}
private void computeHeader(SnomedConcepts chunk) {
for (SnomedConcept concept : chunk) {
for (AbstractSnomedDsvExportItem exportItem : exportItems) {
switch (exportItem.getType()) {
case DESCRIPTION:
ComponentIdSnomedDsvExportItem descriptionItem = (ComponentIdSnomedDsvExportItem) exportItem;
String descriptionTypeId = descriptionItem.getComponentId();
Integer matchingDescriptions = concept.getDescriptions()
.stream()
.filter(d -> descriptionTypeId.equals(d.getTypeId()))
.collect(Collectors.reducing(0, description -> 1, Integer::sum));
descriptionCount.merge(descriptionTypeId, matchingDescriptions, Math::max);
break;
case RELATIONSHIP:
ComponentIdSnomedDsvExportItem relationshipItem = (ComponentIdSnomedDsvExportItem) exportItem;
String relationshipTypeId = relationshipItem.getComponentId();
Map<Integer, Integer> matchingRelationships = concept.getRelationships()
.stream()
.filter(r -> relationshipTypeId.equals(r.getTypeId())
&& (CharacteristicType.INFERRED_RELATIONSHIP.equals(r.getCharacteristicType())
|| CharacteristicType.ADDITIONAL_RELATIONSHIP.equals(r.getCharacteristicType())))
.collect(Collectors.groupingBy(
SnomedRelationship::getGroup,
Collectors.reducing(0, relationship -> 1, Integer::sum)));
matchingRelationships.entrySet()
.stream()
.forEach(entry -> {
propertyCountByGroup.compute(entry.getKey(), (key, oldValue) -> {
Map<String, Integer> propertyCountForGroup = ofNullable(oldValue).orElseGet(HashMap::new);
propertyCountForGroup.merge(relationshipTypeId, entry.getValue(), Math::max);
return propertyCountForGroup;
});
});
break;
case DATAYPE:
ComponentIdSnomedDsvExportItem dataTypeItem = (ComponentIdSnomedDsvExportItem) exportItem;
String dataTypeId = dataTypeItem.getComponentId();
Map<Integer, Integer> matchingMembers = concept.getMembers()
.stream()
.filter(m -> SnomedRefSetType.CONCRETE_DATA_TYPE.equals(m.type())
&& m.isActive()
&& dataTypeId.equals(m.getProperties().get(SnomedRf2Headers.FIELD_TYPE_ID))
&& (Concepts.INFERRED_RELATIONSHIP.equals(m.getProperties().get(SnomedRf2Headers.FIELD_CHARACTERISTIC_TYPE_ID))
|| Concepts.ADDITIONAL_RELATIONSHIP.equals(m.getProperties().get(SnomedRf2Headers.FIELD_CHARACTERISTIC_TYPE_ID))))
.collect(Collectors.groupingBy(
m -> (Integer) m.getProperties().get(SnomedRf2Headers.FIELD_RELATIONSHIP_GROUP),
Collectors.reducing(0, relationship -> 1, Integer::sum)));
matchingMembers.entrySet()
.stream()
.forEach(entry -> {
propertyCountByGroup.compute(entry.getKey(), (key, oldValue) -> {
Map<String, Integer> propertyCountForGroup = ofNullable(oldValue).orElseGet(HashMap::new);
propertyCountForGroup.merge(dataTypeId, entry.getValue(), Math::max);
return propertyCountForGroup;
});
});
break;
default:
// Single-use fields don't need to be counted in advance
break;
}
}
}
}
private void writeHeader(BufferedWriter writer) throws IOException {
Map<String, String> descriptionTypeIdMap = createTypeIdMap(Concepts.DESCRIPTION_TYPE_ROOT_CONCEPT);
Map<String, String> propertyTypeIdMap = createTypeIdMap(Concepts.CONCEPT_MODEL_ATTRIBUTE); // includes object and data attributes
List<String> propertyHeader = newArrayList();
List<String> detailHeader = newArrayList();
for (AbstractSnomedDsvExportItem exportItem : exportItems) {
switch (exportItem.getType()) {
case DESCRIPTION: {
ComponentIdSnomedDsvExportItem descriptionItem = (ComponentIdSnomedDsvExportItem) exportItem;
String typeId = descriptionItem.getComponentId();
String displayName = descriptionTypeIdMap.getOrDefault(typeId, descriptionItem.getDisplayName());
int occurrences = descriptionCount.get(typeId);
if (occurrences < 2) {
if (includeDescriptionId) {
propertyHeader.add(displayName);
propertyHeader.add(displayName);
detailHeader.add("ID");
detailHeader.add("Term");
} else {
propertyHeader.add(displayName);
detailHeader.add("");
}
} else {
for (int j = 1; j <= occurrences; j++) {
String numberedDisplayName = String.format("%s (%s)", displayName, j);
if (includeDescriptionId) {
propertyHeader.add(numberedDisplayName);
propertyHeader.add(numberedDisplayName);
detailHeader.add("ID");
detailHeader.add("Term");
} else {
propertyHeader.add(numberedDisplayName);
detailHeader.add("");
}
}
}
break;
}
case RELATIONSHIP: {
ComponentIdSnomedDsvExportItem relationshipItem = (ComponentIdSnomedDsvExportItem) exportItem;
String typeId = relationshipItem.getComponentId();
String displayName = propertyTypeIdMap.getOrDefault(typeId, relationshipItem.getDisplayName());
for (Integer group : propertyCountByGroup.keySet() ) {
Map<String, Integer> occurrencesByType = propertyCountByGroup.getOrDefault(group, NO_OCCURRENCES);
int occurrences = occurrencesByType.getOrDefault(typeId, 0);
if (occurrences < 1) {
continue;
}
String groupTag = group == 0 ? "" : String.format(" (AG%s)", group);
if (occurrences < 2) {
if (includeRelationshipId) {
String groupedDisplayName = displayName + groupTag;
propertyHeader.add(groupedDisplayName);
propertyHeader.add(groupedDisplayName);
detailHeader.add("ID");
detailHeader.add("Destination");
} else {
propertyHeader.add(displayName);
detailHeader.add("");
}
} else {
for (int j = 1; j <= occurrences; j++) {
String numberedDisplayName = String.format("%s (%s)%s", displayName, j, groupTag);
if (includeRelationshipId) {
propertyHeader.add(numberedDisplayName);
propertyHeader.add(numberedDisplayName);
detailHeader.add("ID");
detailHeader.add("Destination");
} else {
propertyHeader.add(numberedDisplayName);
detailHeader.add("");
}
}
}
}
break;
}
case DATAYPE: {
ComponentIdSnomedDsvExportItem dataTypeItem = (ComponentIdSnomedDsvExportItem) exportItem;
String typeId = dataTypeItem.getComponentId();
String displayName = propertyTypeIdMap.getOrDefault(typeId, dataTypeItem.getDisplayName());
for (Integer groupId : propertyCountByGroup.keySet() ) {
Map<String, Integer> occurrencesByType = propertyCountByGroup.getOrDefault(groupId, NO_OCCURRENCES);
int occurrences = occurrencesByType.getOrDefault(typeId, 0);
if (occurrences < 1) {
continue;
}
String groupTag = groupId == 0 ? "" : String.format(" (AG%s)", groupId);
if (occurrences < 2) {
String groupedDisplayName = displayName + groupTag;
propertyHeader.add(groupedDisplayName);
detailHeader.add("");
} else {
for (int j = 1; j <= occurrences; j++) {
String numberedDisplayName = String.format("%s (%s)%s", displayName, j, groupTag);
propertyHeader.add(numberedDisplayName);
detailHeader.add("");
}
}
}
break;
}
case PREFERRED_TERM:
if (includeDescriptionId) {
propertyHeader.add(exportItem.getDisplayName());
propertyHeader.add(exportItem.getDisplayName());
detailHeader.add("ID");
detailHeader.add("Term");
} else {
propertyHeader.add(exportItem.getDisplayName());
detailHeader.add("");
}
break;
default:
propertyHeader.add(exportItem.getDisplayName());
detailHeader.add("");
break;
}
}
// write the header to the file
writer.write(joiner.join(propertyHeader));
writer.write(lineSeparator);
if (includeDescriptionId || includeRelationshipId) {
writer.write(joiner.join(detailHeader));
writer.write(lineSeparator);
}
}
private Map<String, String> createTypeIdMap(String ancestorId) {
return createTypeIdMap(SnomedRequests.prepareSearchConcept()
.all()
.setLocales(locales)
.filterByAncestor(ancestorId)
.setExpand("pt()")
.build()
.execute(context));
}
private Map<String, String> createTypeIdMap(SnomedConcepts concepts) {
return concepts.stream()
.collect(Collectors.toMap(
SnomedConcept::getId,
c -> getPreferredTerm(c)));
}
private void writeValues(IProgressMonitor monitor, BufferedWriter writer) throws IOException {
SearchResourceRequestIterator<SnomedConceptSearchRequestBuilder, SnomedConcepts> conceptIterator = getMemberConceptIterator(DATA_EXPAND);
while (conceptIterator.hasNext()) {
SnomedConcepts chunk = conceptIterator.next();
writeValues(writer, chunk);
monitor.worked(chunk.getItems().size());
}
}
private void writeValues(BufferedWriter writer, SnomedConcepts chunk) throws IOException {
List<String> dataRow = newArrayList();
for (SnomedConcept concept : chunk) {
dataRow.clear();
for (AbstractSnomedDsvExportItem exportItem : exportItems) {
switch (exportItem.getType()) {
case DESCRIPTION: {
final ComponentIdSnomedDsvExportItem descriptionItem = (ComponentIdSnomedDsvExportItem) exportItem;
final String typeId = descriptionItem.getComponentId();
int occurrences = descriptionCount.get(typeId);
final Map<String, String> termsById = concept.getDescriptions()
.stream()
.filter(d -> typeId.equals(d.getTypeId()))
.collect(Collectors.toMap(
SnomedDescription::getId,
SnomedDescription::getTerm));
addCells(dataRow, occurrences, includeDescriptionId, termsById);
break;
}
case RELATIONSHIP: {
final ComponentIdSnomedDsvExportItem relationshipItem = (ComponentIdSnomedDsvExportItem) exportItem;
for (Integer propertyGroup : propertyCountByGroup.keySet()) {
final String typeId = relationshipItem.getComponentId();
Map<String, Integer> groupOccurrences = propertyCountByGroup.getOrDefault(propertyGroup, NO_OCCURRENCES);
int occurrences = groupOccurrences.getOrDefault(typeId, 0);
final Map<String, String> destinationsById = concept.getRelationships()
.stream()
.filter(r -> typeId.equals(r.getTypeId())
&& r.getGroup() == propertyGroup
&& (CharacteristicType.INFERRED_RELATIONSHIP.equals(r.getCharacteristicType())
|| CharacteristicType.ADDITIONAL_RELATIONSHIP.equals(r.getCharacteristicType())))
.collect(Collectors.toMap(
SnomedRelationship::getDestinationId,
r -> getPreferredTerm(r.getDestination())));
addCells(dataRow, occurrences, includeRelationshipId, destinationsById);
}
break;
}
case DATAYPE: {
final DatatypeSnomedDsvExportItem datatypeItem = (DatatypeSnomedDsvExportItem) exportItem;
for (Integer propertyGroup : propertyCountByGroup.keySet()) {
Map<String, Integer> groupedOccurrences = propertyCountByGroup.getOrDefault(propertyGroup, NO_OCCURRENCES);
final String typeId = datatypeItem.getComponentId();
int occurrences = groupedOccurrences.getOrDefault(typeId, 0);
if (occurrences < 1) {
break;
}
final List<String> properties = concept.getMembers()
.stream()
.filter(m -> SnomedRefSetType.CONCRETE_DATA_TYPE.equals(m.type())
&& m.isActive()
&& typeId.equals(m.getProperties().get(SnomedRf2Headers.FIELD_TYPE_ID))
&& (Integer) m.getProperties().get(SnomedRf2Headers.FIELD_RELATIONSHIP_GROUP) == propertyGroup
&& (Concepts.INFERRED_RELATIONSHIP.equals(m.getProperties().get(SnomedRf2Headers.FIELD_CHARACTERISTIC_TYPE_ID))
|| Concepts.ADDITIONAL_RELATIONSHIP.equals(m.getProperties().get(SnomedRf2Headers.FIELD_CHARACTERISTIC_TYPE_ID))))
.map(m -> m.getProperties().get(SnomedRf2Headers.FIELD_VALUE))
.map(p -> {
if (datatypeItem.isBooleanDatatype()) {
return "1".equals(p) ? "Yes" : "No";
} else {
return p.toString();
}
})
.sorted()
.collect(Collectors.toList());
for (String value : properties) {
dataRow.add(value);
occurrences--;
}
while (occurrences > 0) {
dataRow.add("");
occurrences--;
}
}
break;
}
case PREFERRED_TERM:
if (includeDescriptionId) {
dataRow.add(getPreferredTermId(concept));
dataRow.add(getPreferredTerm(concept));
} else {
dataRow.add(getPreferredTerm(concept));
}
break;
case CONCEPT_ID:
dataRow.add(concept.getId());
break;
case MODULE:
dataRow.add(concept.getModuleId());
break;
case EFFECTIVE_TIME:
dataRow.add(EffectiveTimes.format(concept.getEffectiveTime()));
break;
case STATUS_LABEL:
dataRow.add(concept.isActive() ? "Active" : "Inactive");
break;
case DEFINITION_STATUS:
dataRow.add(concept.getDefinitionStatus().toString());
break;
default:
break;
}
}
writer.write(joiner.join(dataRow));
writer.write(lineSeparator);
}
}
private void addCells(List<String> dataRow, int occurrences, boolean includeIds, Map<String, String> idValuePairs) {
if (includeIds) {
SortedSet<String> sortedIds = ImmutableSortedSet.copyOf(idValuePairs.keySet());
for (String id : sortedIds) {
dataRow.add(id);
dataRow.add(idValuePairs.get(id));
occurrences--;
}
while (occurrences > 0) {
dataRow.add("");
dataRow.add("");
occurrences--;
}
} else {
List<String> sortedValues = Ordering.natural().sortedCopy(idValuePairs.values());
for (String value : sortedValues) {
dataRow.add(value);
occurrences--;
}
while (occurrences > 0) {
dataRow.add("");
occurrences--;
}
}
}
private String getPreferredTerm(SnomedConcept concept) {
return (concept.getPt() == null) ? "" : concept.getPt().getTerm();
}
private String getPreferredTermId(SnomedConcept concept) {
return (concept.getPt() == null) ? "" : concept.getPt().getId();
}
} |
Java | public class IndexRecordManager
{
private static final Logger LOG = Logger.get(IndexRecordManager.class);
private final HetuMetastore metastore;
public IndexRecordManager(HetuMetastore metastore)
{
this.metastore = metastore;
}
/**
* List all parameters at table level and filter those with hindex prefix.
*
* Construct {@code IndexRecord} objects from them.
*
* @return a list of deserialized {@code IndexRecord} objects.
*/
public List<IndexRecord> getIndexRecords()
{
List<IndexRecord> records = new ArrayList<>();
for (CatalogEntity catalogEntity : metastore.getCatalogs()) {
for (DatabaseEntity databaseEntity : metastore.getAllDatabases(catalogEntity.getName())) {
for (TableEntity tableEntity : metastore.getAllTables(catalogEntity.getName(), databaseEntity.getName())) {
for (Map.Entry<String, String> param : tableEntity.getParameters().entrySet()) {
if (param.getKey().startsWith(IndexRecord.INDEX_METASTORE_PREFIX)) {
records.add(new IndexRecord(tableEntity, param));
}
}
}
}
}
return records;
}
/**
* Look up index record according to name.
*/
public IndexRecord lookUpIndexRecord(String name)
{
return getIndexRecords().stream().filter(indexRecord -> indexRecord.name.equals(name)).findFirst().orElse(null);
}
/**
* Look up index record according to what it is for (triplet of [table, column, type]).
*/
public IndexRecord lookUpIndexRecord(String table, String[] columns, String indexType)
{
String[] tableQualified = table.split("\\.");
if (tableQualified.length != 3) {
throw new IllegalArgumentException(String.format("Illegal table name: %s", table));
}
Optional<TableEntity> tableEntity = metastore.getTable(tableQualified[0], tableQualified[1], tableQualified[2]);
if (tableEntity.isPresent()) {
for (Map.Entry<String, String> parameter : tableEntity.get().getParameters().entrySet()) {
IndexRecord read = new IndexRecord(tableEntity.get(), parameter);
if (Arrays.equals(read.columns, columns) && read.indexType.equals(indexType)) {
return read;
}
}
}
return null;
}
/**
* Add IndexRecord into record file. If the method is called with a name that already exists,
*
* it will OVERWRITE the existing entry but COMBINE the partition columns (if it previously was partitioned)
*/
public synchronized void addIndexRecord(String name, String user, String table, String[] columns, String indexType, long indexSize, List<String> indexProperties, List<String> partitions)
{
IndexRecord record = new IndexRecord(name, user, table, columns, indexType, indexSize, indexProperties, partitions);
IndexRecord old = lookUpIndexRecord(name);
if (old != null) {
record.partitions.addAll(0, old.partitions);
}
Optional<CatalogEntity> oldCatalog = metastore.getCatalog(record.catalog);
if (!oldCatalog.isPresent()) {
CatalogEntity newCatalog = CatalogEntity.builder()
.setCatalogName(record.catalog)
.build();
metastore.createCatalogIfNotExist(newCatalog);
}
Optional<DatabaseEntity> oldSchema = metastore.getDatabase(record.catalog, record.schema);
if (!oldSchema.isPresent()) {
DatabaseEntity newSchema = DatabaseEntity.builder()
.setCatalogName(record.catalog)
.setDatabaseName(record.schema)
.build();
metastore.createDatabaseIfNotExist(newSchema);
}
Optional<TableEntity> oldTable = metastore.getTable(record.catalog, record.schema, record.table);
if (!oldTable.isPresent()) {
TableEntity newTable = TableEntity.builder()
.setCatalogName(record.catalog)
.setDatabaseName(record.schema)
.setTableName(record.table)
.setTableType(TableEntityType.TABLE.toString())
.build();
metastore.createTableIfNotExist(newTable);
}
metastore.alterTableParameter(record.catalog,
record.schema,
record.table,
record.serializeKey(),
record.serializeValue());
}
/**
* Delete index record from metastore according to name. Also allows partial deletion.
*
* @param name name of index to delete
* @param partitionsToRemove the partitions to remove. If this list is empty, remove all.
*/
public synchronized void deleteIndexRecord(String name, List<String> partitionsToRemove)
{
getIndexRecords().stream().filter(record -> record.name.equals(name))
.forEach(record -> {
if (partitionsToRemove.isEmpty()) {
metastore.alterTableParameter(
record.catalog,
record.schema,
record.table,
record.serializeKey(),
null);
}
else {
record.partitions.removeAll(partitionsToRemove);
IndexRecord newRecord = new IndexRecord(record.name, record.user, record.qualifiedTable, record.columns,
record.indexType, record.indexSize, record.propertiesAsList, record.partitions);
metastore.alterTableParameter(
record.catalog,
record.schema,
record.table,
newRecord.serializeKey(),
newRecord.partitions.isEmpty() ? null : newRecord.serializeValue()); // if the last partition of the index has been dropped, remove the record
}
});
}
} |
Java | public class IntegrationEventFilter implements GenericSelector<Message> {
private static final Logger LOGGER = LoggerFactory.getLogger(IntegrationEventFilter.class);
private final EventFilter eventFilter;
private IntegrationEventFilter(final EventFilter eventFilter) {
this.eventFilter = Objects.requireNonNull(eventFilter);
}
/**
* Obtain a {@link IntegrationEventFilter} that filters following the conditions of a {@link EventFilter}.
*
* @param eventFilter given {@link EventFilter} to be applied
* @return created {@link IntegrationEventFilter}
*/
public static IntegrationEventFilter of(final EventFilter eventFilter) {
return new IntegrationEventFilter(eventFilter);
}
@Override
public boolean accept(final Message source) {
LOGGER.debug("Checking event filter {} for message {}", eventFilter, source);
return eventFilter.test((RepoEvent<DataAttributes<Resource>>) source.getPayload());
}
} |
Java | @Service
public class UserService {
@Autowired
private UserRepository userRepository;
public boolean isUserAlreadyRegistered(User user)
{
User savedUser = userRepository.findById(user.getEmailAddress()).orElse(null);
return savedUser != null;
}
public void saveNewUser(User user) {
userRepository.save(user);
}
} |
Java | public class ConcreteArrayOfObjectsNode extends AbstractContainerNode
implements ArrayOfObjectsNode {
private final MultiValuedAccessorFactory accessorFactory;
private final String elementName;
private MultiValuedAccessor multiValuedAccessor;
/**
* Constructs a new instance.
* @param name node name
* @param elementName name for the elements of the array
* @param namespace namespace for {@code name} and {@code elementName}
* @param modelType model type of the array elements
*/
public ConcreteArrayOfObjectsNode(String name, String elementName,
String namespace, Class<?> modelType) {
this(name, elementName, namespace, modelType,
ConcreteMultiValuedAccessorFactory.INSTANCE
);
}
ConcreteArrayOfObjectsNode(String name, String elementName,
String namespace, Class<?> modelType,
MultiValuedAccessorFactory accessorFactory) {
super(name, namespace, modelType);
this.elementName = elementName;
this.accessorFactory = accessorFactory;
}
@Override
public void setAccessor(Accessor accessor) {
super.setAccessor(accessor);
this.multiValuedAccessor = accessorFactory.newAccessor(accessor, getModelType());
}
@Override
public String getPropertyName() {
return getAccessor().getName();
}
@Override
public Class<?> getComponentType() {
return multiValuedAccessor.getComponentType();
}
@Override
public String getElementName() {
if (elementName != null) return elementName;
return Introspector.decapitalize(getModelType().getSimpleName());
}
@Override
public EnumSet<AccessMode> getSupportedModes() {
return multiValuedAccessor != null ?
multiValuedAccessor.getSupportedModes() : EnumSet.allOf(AccessMode.class);
}
@Override
public ToManyAssociationManager<?, ?> getDefaultManager() {
return multiValuedAccessor;
}
@Override
public Iterator<?> iterator(Object model) throws Exception {
return getModelIterator(model);
}
protected Iterator<Object> getModelIterator(Object source) throws Exception {
return multiValuedAccessor.iterator(source);
}
@Override
public Object accept(ViewNodeVisitor visitor, Object state) {
return visitor.visitArrayOfObjects(this, state);
}
} |
Java | public class ColorModeOptionCriteria extends SingleValuePersistentCriteria
implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public final static String BMode = "Return Only Images With No Color";
public final static String ColorMode = "Return Colored Images";
public final static String NoCondition = "Return All Images";
private String colorModeOptionValue;
/**
*/
public ColorModeOptionCriteria() {
super();
}
/**
*/
public ColorModeOptionCriteria(String colorModeOptionValue) {
super();
this.colorModeOptionValue = colorModeOptionValue;
}
/**
* @return Returns the contrastAgentValue.
*/
public String getColorModeOptionValue() {
return colorModeOptionValue;
}
/**
*
*/
public void setColorModeOptionValue(String colorModeOptionValue) {
if (colorModeOptionValue != null) {
if (colorModeOptionValue
.equals(ColorModeOptionCriteria.BMode)) {
this.colorModeOptionValue = ColorModeOptionCriteria.BMode;
} else if (colorModeOptionValue
.equals(ColorModeOptionCriteria.ColorMode)) {
this.colorModeOptionValue = ColorModeOptionCriteria.ColorMode;
} else {
this.colorModeOptionValue = ColorModeOptionCriteria.NoCondition;
}
}
}
public void addValueFromQueryAttribute(QueryAttributeWrapper attr) {
setColorModeOptionValue(attr.getAttributeValue());
}
public String getSingleValue() {
return colorModeOptionValue;
}
public static final class BModeOption extends
ColorModeOptionCriteria {
public BModeOption() {
super(BMode);
}
}
public static final class ColorModeOption extends
ColorModeOptionCriteria {
public ColorModeOption() {
super(ColorMode);
}
}
public static final class NoConditionOption extends
ColorModeOptionCriteria {
public NoConditionOption() {
super(NoCondition);
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.