hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
cb854881bffb5cd2e32f9a9226c80fe925522396 | 68,179 | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 2.0.4
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package org.sbml.libsbml;
/**
* A token in libSBML's XML stream.
<p>
* <p style='color: #777; font-style: italic'>
This class of objects is defined by libSBML only and has no direct
equivalent in terms of SBML components. This class is not prescribed by
the SBML specifications, although it is used to implement features
defined in SBML.
</p>
*/
public class XMLToken {
private long swigCPtr;
protected boolean swigCMemOwn;
protected XMLToken(long cPtr, boolean cMemoryOwn)
{
swigCMemOwn = cMemoryOwn;
swigCPtr = cPtr;
}
protected static long getCPtr(XMLToken obj)
{
return (obj == null) ? 0 : obj.swigCPtr;
}
protected static long getCPtrAndDisown (XMLToken obj)
{
long ptr = 0;
if (obj != null)
{
ptr = obj.swigCPtr;
obj.swigCMemOwn = false;
}
return ptr;
}
protected void finalize() {
delete();
}
public synchronized void delete() {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
libsbmlJNI.delete_XMLToken(swigCPtr);
}
swigCPtr = 0;
}
}
/**
* Equality comparison method for XMLToken.
* <p>
* Because the Java methods for libSBML are actually wrappers around code
* implemented in C++ and C, certain operations will not behave as
* expected. Equality comparison is one such case. An instance of a
* libSBML object class is actually a <em>proxy object</em>
* wrapping the real underlying C/C++ object. The normal <code>==</code>
* equality operator in Java will <em>only compare the Java proxy objects</em>,
* not the underlying native object. The result is almost never what you
* want in practical situations. Unfortunately, Java does not provide a
* way to override <code>==</code>.
* <p>
* The alternative that must be followed is to use the
* <code>equals()</code> method. The <code>equals</code> method on this
* class overrides the default java.lang.Object one, and performs an
* intelligent comparison of instances of objects of this class. The
* result is an assessment of whether two libSBML Java objects are truly
* the same underlying native-code objects.
* <p>
* The use of this method in practice is the same as the use of any other
* Java <code>equals</code> method. For example,
* <em>a</em><code>.equals(</code><em>b</em><code>)</code> returns
* <code>true</code> if <em>a</em> and <em>b</em> are references to the
* same underlying object.
*
* @param sb a reference to an object to which the current object
* instance will be compared
*
* @return <code>true</code> if <code>sb</code> refers to the same underlying
* native object as this one, <code>false</code> otherwise
*/
public boolean equals(Object sb)
{
if ( this == sb )
{
return true;
}
return swigCPtr == getCPtr((XMLToken)(sb));
}
/**
* Returns a hashcode for this XMLToken object.
*
* @return a hash code usable by Java methods that need them.
*/
public int hashCode()
{
return (int)(swigCPtr^(swigCPtr>>>32));
}
/**
* Creates a new empty {@link XMLToken}.
*/ public
XMLToken() throws org.sbml.libsbml.XMLConstructorException {
this(libsbmlJNI.new_XMLToken__SWIG_0(), true);
}
/**
* Creates a start element {@link XMLToken} with the given set of attributes and
* namespace declarations.
<p>
* @param triple {@link XMLTriple}.
* @param attributes {@link XMLAttributes}, the attributes to set.
* @param namespaces {@link XMLNamespaces}, the namespaces to set.
* @param line a long integer, the line number (default = 0).
* @param column a long integer, the column number (default = 0).
<p>
*
</dl><dl class="docnote"><dt><b>Documentation note:</b></dt><dd>
The native C++ implementation of this method defines a default argument
value. In the documentation generated for different libSBML language
bindings, you may or may not see corresponding arguments in the method
declarations. For example, in Java and C#, a default argument is handled by
declaring two separate methods, with one of them having the argument and
the other one lacking the argument. However, the libSBML documentation will
be <em>identical</em> for both methods. Consequently, if you are reading
this and do not see an argument even though one is described, please look
for descriptions of other variants of this method near where this one
appears in the documentation.
</dd></dl>
*/ public
XMLToken(XMLTriple triple, XMLAttributes attributes, XMLNamespaces namespaces, long line, long column) throws org.sbml.libsbml.XMLConstructorException {
this(libsbmlJNI.new_XMLToken__SWIG_1(XMLTriple.getCPtr(triple), triple, XMLAttributes.getCPtr(attributes), attributes, XMLNamespaces.getCPtr(namespaces), namespaces, line, column), true);
}
/**
* Creates a start element {@link XMLToken} with the given set of attributes and
* namespace declarations.
<p>
* @param triple {@link XMLTriple}.
* @param attributes {@link XMLAttributes}, the attributes to set.
* @param namespaces {@link XMLNamespaces}, the namespaces to set.
* @param line a long integer, the line number (default = 0).
* @param column a long integer, the column number (default = 0).
<p>
*
</dl><dl class="docnote"><dt><b>Documentation note:</b></dt><dd>
The native C++ implementation of this method defines a default argument
value. In the documentation generated for different libSBML language
bindings, you may or may not see corresponding arguments in the method
declarations. For example, in Java and C#, a default argument is handled by
declaring two separate methods, with one of them having the argument and
the other one lacking the argument. However, the libSBML documentation will
be <em>identical</em> for both methods. Consequently, if you are reading
this and do not see an argument even though one is described, please look
for descriptions of other variants of this method near where this one
appears in the documentation.
</dd></dl>
*/ public
XMLToken(XMLTriple triple, XMLAttributes attributes, XMLNamespaces namespaces, long line) throws org.sbml.libsbml.XMLConstructorException {
this(libsbmlJNI.new_XMLToken__SWIG_2(XMLTriple.getCPtr(triple), triple, XMLAttributes.getCPtr(attributes), attributes, XMLNamespaces.getCPtr(namespaces), namespaces, line), true);
}
/**
* Creates a start element {@link XMLToken} with the given set of attributes and
* namespace declarations.
<p>
* @param triple {@link XMLTriple}.
* @param attributes {@link XMLAttributes}, the attributes to set.
* @param namespaces {@link XMLNamespaces}, the namespaces to set.
* @param line a long integer, the line number (default = 0).
* @param column a long integer, the column number (default = 0).
<p>
*
</dl><dl class="docnote"><dt><b>Documentation note:</b></dt><dd>
The native C++ implementation of this method defines a default argument
value. In the documentation generated for different libSBML language
bindings, you may or may not see corresponding arguments in the method
declarations. For example, in Java and C#, a default argument is handled by
declaring two separate methods, with one of them having the argument and
the other one lacking the argument. However, the libSBML documentation will
be <em>identical</em> for both methods. Consequently, if you are reading
this and do not see an argument even though one is described, please look
for descriptions of other variants of this method near where this one
appears in the documentation.
</dd></dl>
*/ public
XMLToken(XMLTriple triple, XMLAttributes attributes, XMLNamespaces namespaces) throws org.sbml.libsbml.XMLConstructorException {
this(libsbmlJNI.new_XMLToken__SWIG_3(XMLTriple.getCPtr(triple), triple, XMLAttributes.getCPtr(attributes), attributes, XMLNamespaces.getCPtr(namespaces), namespaces), true);
}
/**
* Creates a start element {@link XMLToken} with the given set of attributes.
<p>
* @param triple {@link XMLTriple}.
* @param attributes {@link XMLAttributes}, the attributes to set.
* @param line a long integer, the line number (default = 0).
* @param column a long integer, the column number (default = 0).
<p>
*
</dl><dl class="docnote"><dt><b>Documentation note:</b></dt><dd>
The native C++ implementation of this method defines a default argument
value. In the documentation generated for different libSBML language
bindings, you may or may not see corresponding arguments in the method
declarations. For example, in Java and C#, a default argument is handled by
declaring two separate methods, with one of them having the argument and
the other one lacking the argument. However, the libSBML documentation will
be <em>identical</em> for both methods. Consequently, if you are reading
this and do not see an argument even though one is described, please look
for descriptions of other variants of this method near where this one
appears in the documentation.
</dd></dl>
*/ public
XMLToken(XMLTriple triple, XMLAttributes attributes, long line, long column) throws org.sbml.libsbml.XMLConstructorException {
this(libsbmlJNI.new_XMLToken__SWIG_4(XMLTriple.getCPtr(triple), triple, XMLAttributes.getCPtr(attributes), attributes, line, column), true);
}
/**
* Creates a start element {@link XMLToken} with the given set of attributes.
<p>
* @param triple {@link XMLTriple}.
* @param attributes {@link XMLAttributes}, the attributes to set.
* @param line a long integer, the line number (default = 0).
* @param column a long integer, the column number (default = 0).
<p>
*
</dl><dl class="docnote"><dt><b>Documentation note:</b></dt><dd>
The native C++ implementation of this method defines a default argument
value. In the documentation generated for different libSBML language
bindings, you may or may not see corresponding arguments in the method
declarations. For example, in Java and C#, a default argument is handled by
declaring two separate methods, with one of them having the argument and
the other one lacking the argument. However, the libSBML documentation will
be <em>identical</em> for both methods. Consequently, if you are reading
this and do not see an argument even though one is described, please look
for descriptions of other variants of this method near where this one
appears in the documentation.
</dd></dl>
*/ public
XMLToken(XMLTriple triple, XMLAttributes attributes, long line) throws org.sbml.libsbml.XMLConstructorException {
this(libsbmlJNI.new_XMLToken__SWIG_5(XMLTriple.getCPtr(triple), triple, XMLAttributes.getCPtr(attributes), attributes, line), true);
}
/**
* Creates a start element {@link XMLToken} with the given set of attributes.
<p>
* @param triple {@link XMLTriple}.
* @param attributes {@link XMLAttributes}, the attributes to set.
* @param line a long integer, the line number (default = 0).
* @param column a long integer, the column number (default = 0).
<p>
*
</dl><dl class="docnote"><dt><b>Documentation note:</b></dt><dd>
The native C++ implementation of this method defines a default argument
value. In the documentation generated for different libSBML language
bindings, you may or may not see corresponding arguments in the method
declarations. For example, in Java and C#, a default argument is handled by
declaring two separate methods, with one of them having the argument and
the other one lacking the argument. However, the libSBML documentation will
be <em>identical</em> for both methods. Consequently, if you are reading
this and do not see an argument even though one is described, please look
for descriptions of other variants of this method near where this one
appears in the documentation.
</dd></dl>
*/ public
XMLToken(XMLTriple triple, XMLAttributes attributes) throws org.sbml.libsbml.XMLConstructorException {
this(libsbmlJNI.new_XMLToken__SWIG_6(XMLTriple.getCPtr(triple), triple, XMLAttributes.getCPtr(attributes), attributes), true);
}
/**
* Creates an end element {@link XMLToken}.
<p>
* @param triple {@link XMLTriple}.
* @param line a long integer, the line number (default = 0).
* @param column a long integer, the column number (default = 0).
<p>
*
</dl><dl class="docnote"><dt><b>Documentation note:</b></dt><dd>
The native C++ implementation of this method defines a default argument
value. In the documentation generated for different libSBML language
bindings, you may or may not see corresponding arguments in the method
declarations. For example, in Java and C#, a default argument is handled by
declaring two separate methods, with one of them having the argument and
the other one lacking the argument. However, the libSBML documentation will
be <em>identical</em> for both methods. Consequently, if you are reading
this and do not see an argument even though one is described, please look
for descriptions of other variants of this method near where this one
appears in the documentation.
</dd></dl>
*/ public
XMLToken(XMLTriple triple, long line, long column) throws org.sbml.libsbml.XMLConstructorException {
this(libsbmlJNI.new_XMLToken__SWIG_7(XMLTriple.getCPtr(triple), triple, line, column), true);
}
/**
* Creates an end element {@link XMLToken}.
<p>
* @param triple {@link XMLTriple}.
* @param line a long integer, the line number (default = 0).
* @param column a long integer, the column number (default = 0).
<p>
*
</dl><dl class="docnote"><dt><b>Documentation note:</b></dt><dd>
The native C++ implementation of this method defines a default argument
value. In the documentation generated for different libSBML language
bindings, you may or may not see corresponding arguments in the method
declarations. For example, in Java and C#, a default argument is handled by
declaring two separate methods, with one of them having the argument and
the other one lacking the argument. However, the libSBML documentation will
be <em>identical</em> for both methods. Consequently, if you are reading
this and do not see an argument even though one is described, please look
for descriptions of other variants of this method near where this one
appears in the documentation.
</dd></dl>
*/ public
XMLToken(XMLTriple triple, long line) throws org.sbml.libsbml.XMLConstructorException {
this(libsbmlJNI.new_XMLToken__SWIG_8(XMLTriple.getCPtr(triple), triple, line), true);
}
/**
* Creates an end element {@link XMLToken}.
<p>
* @param triple {@link XMLTriple}.
* @param line a long integer, the line number (default = 0).
* @param column a long integer, the column number (default = 0).
<p>
*
</dl><dl class="docnote"><dt><b>Documentation note:</b></dt><dd>
The native C++ implementation of this method defines a default argument
value. In the documentation generated for different libSBML language
bindings, you may or may not see corresponding arguments in the method
declarations. For example, in Java and C#, a default argument is handled by
declaring two separate methods, with one of them having the argument and
the other one lacking the argument. However, the libSBML documentation will
be <em>identical</em> for both methods. Consequently, if you are reading
this and do not see an argument even though one is described, please look
for descriptions of other variants of this method near where this one
appears in the documentation.
</dd></dl>
*/ public
XMLToken(XMLTriple triple) throws org.sbml.libsbml.XMLConstructorException {
this(libsbmlJNI.new_XMLToken__SWIG_9(XMLTriple.getCPtr(triple), triple), true);
}
/**
* Creates a text {@link XMLToken}.
<p>
* @param chars a string, the text to be added to the {@link XMLToken}
* @param line a long integer, the line number (default = 0).
* @param column a long integer, the column number (default = 0).
<p>
* @throws XMLConstructorException
* Thrown if the argument <code>orig</code> is <code>null.</code>
<p>
*
</dl><dl class="docnote"><dt><b>Documentation note:</b></dt><dd>
The native C++ implementation of this method defines a default argument
value. In the documentation generated for different libSBML language
bindings, you may or may not see corresponding arguments in the method
declarations. For example, in Java and C#, a default argument is handled by
declaring two separate methods, with one of them having the argument and
the other one lacking the argument. However, the libSBML documentation will
be <em>identical</em> for both methods. Consequently, if you are reading
this and do not see an argument even though one is described, please look
for descriptions of other variants of this method near where this one
appears in the documentation.
</dd></dl>
*/ public
XMLToken(String chars, long line, long column) throws org.sbml.libsbml.XMLConstructorException {
this(libsbmlJNI.new_XMLToken__SWIG_10(chars, line, column), true);
}
/**
* Creates a text {@link XMLToken}.
<p>
* @param chars a string, the text to be added to the {@link XMLToken}
* @param line a long integer, the line number (default = 0).
* @param column a long integer, the column number (default = 0).
<p>
* @throws XMLConstructorException
* Thrown if the argument <code>orig</code> is <code>null.</code>
<p>
*
</dl><dl class="docnote"><dt><b>Documentation note:</b></dt><dd>
The native C++ implementation of this method defines a default argument
value. In the documentation generated for different libSBML language
bindings, you may or may not see corresponding arguments in the method
declarations. For example, in Java and C#, a default argument is handled by
declaring two separate methods, with one of them having the argument and
the other one lacking the argument. However, the libSBML documentation will
be <em>identical</em> for both methods. Consequently, if you are reading
this and do not see an argument even though one is described, please look
for descriptions of other variants of this method near where this one
appears in the documentation.
</dd></dl>
*/ public
XMLToken(String chars, long line) throws org.sbml.libsbml.XMLConstructorException {
this(libsbmlJNI.new_XMLToken__SWIG_11(chars, line), true);
}
/**
* Creates a text {@link XMLToken}.
<p>
* @param chars a string, the text to be added to the {@link XMLToken}
* @param line a long integer, the line number (default = 0).
* @param column a long integer, the column number (default = 0).
<p>
* @throws XMLConstructorException
* Thrown if the argument <code>orig</code> is <code>null.</code>
<p>
*
</dl><dl class="docnote"><dt><b>Documentation note:</b></dt><dd>
The native C++ implementation of this method defines a default argument
value. In the documentation generated for different libSBML language
bindings, you may or may not see corresponding arguments in the method
declarations. For example, in Java and C#, a default argument is handled by
declaring two separate methods, with one of them having the argument and
the other one lacking the argument. However, the libSBML documentation will
be <em>identical</em> for both methods. Consequently, if you are reading
this and do not see an argument even though one is described, please look
for descriptions of other variants of this method near where this one
appears in the documentation.
</dd></dl>
*/ public
XMLToken(String chars) throws org.sbml.libsbml.XMLConstructorException {
this(libsbmlJNI.new_XMLToken__SWIG_12(chars), true);
}
/**
* Copy constructor; creates a copy of this {@link XMLToken}.
<p>
* @param orig the {@link XMLToken} object to copy.
<p>
* @throws XMLConstructorException
* Thrown if the argument <code>orig</code> is <code>null.</code>
*/ public
XMLToken(XMLToken orig) throws org.sbml.libsbml.XMLConstructorException {
this(libsbmlJNI.new_XMLToken__SWIG_13(XMLToken.getCPtr(orig), orig), true);
}
/**
* Creates and returns a deep copy of this {@link XMLToken} object.
<p>
* @return the (deep) copy of this {@link XMLToken} object.
*/ public
XMLToken cloneObject() {
long cPtr = libsbmlJNI.XMLToken_cloneObject(swigCPtr, this);
return (cPtr == 0) ? null : new XMLToken(cPtr, true);
}
/**
* Returns the attributes of this element.
<p>
* @return the {@link XMLAttributes} of this XML element.
*/ public
XMLAttributes getAttributes() {
return new XMLAttributes(libsbmlJNI.XMLToken_getAttributes(swigCPtr, this), false);
}
/**
* Sets an {@link XMLAttributes} to this {@link XMLToken}.
* Nothing will be done if this {@link XMLToken} is not a start element.
<p>
* @param attributes {@link XMLAttributes} to be set to this {@link XMLToken}.
<p>
* @return integer value indicating success/failure of the
* function. The possible values
* returned by this function are:
* <ul>
* <li> {@link libsbmlConstants#LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS}
* <li> {@link libsbmlConstants#LIBSBML_OPERATION_FAILED LIBSBML_OPERATION_FAILED}
* <li> {@link libsbmlConstants#LIBSBML_INVALID_XML_OPERATION LIBSBML_INVALID_XML_OPERATION}
* <li> {@link libsbmlConstants#LIBSBML_INVALID_OBJECT LIBSBML_INVALID_OBJECT}
*
* </ul> <p>
* @note This function replaces the existing {@link XMLAttributes} with the new one.
*/ public
int setAttributes(XMLAttributes attributes) {
return libsbmlJNI.XMLToken_setAttributes(swigCPtr, this, XMLAttributes.getCPtr(attributes), attributes);
}
/**
* Adds an attribute to the attribute set in this {@link XMLToken} optionally
* with a prefix and URI defining a namespace.
* Nothing will be done if this {@link XMLToken} is not a start element.
<p>
* @param name a string, the local name of the attribute.
* @param value a string, the value of the attribute.
* @param namespaceURI a string, the namespace URI of the attribute.
* @param prefix a string, the prefix of the namespace
<p>
* @return integer value indicating success/failure of the
* function. The possible values
* returned by this function are:
* <ul>
* <li> {@link libsbmlConstants#LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS}
* <li> {@link libsbmlConstants#LIBSBML_INVALID_XML_OPERATION LIBSBML_INVALID_XML_OPERATION}
*
* </ul> <p>
* @note if local name with the same namespace URI already exists in the
* attribute set, its value and prefix will be replaced.
<p>
*
</dl><dl class="docnote"><dt><b>Documentation note:</b></dt><dd>
The native C++ implementation of this method defines a default argument
value. In the documentation generated for different libSBML language
bindings, you may or may not see corresponding arguments in the method
declarations. For example, in Java and C#, a default argument is handled by
declaring two separate methods, with one of them having the argument and
the other one lacking the argument. However, the libSBML documentation will
be <em>identical</em> for both methods. Consequently, if you are reading
this and do not see an argument even though one is described, please look
for descriptions of other variants of this method near where this one
appears in the documentation.
</dd></dl>
*/ public
int addAttr(String name, String value, String namespaceURI, String prefix) {
return libsbmlJNI.XMLToken_addAttr__SWIG_0(swigCPtr, this, name, value, namespaceURI, prefix);
}
/**
* Adds an attribute to the attribute set in this {@link XMLToken} optionally
* with a prefix and URI defining a namespace.
* Nothing will be done if this {@link XMLToken} is not a start element.
<p>
* @param name a string, the local name of the attribute.
* @param value a string, the value of the attribute.
* @param namespaceURI a string, the namespace URI of the attribute.
* @param prefix a string, the prefix of the namespace
<p>
* @return integer value indicating success/failure of the
* function. The possible values
* returned by this function are:
* <ul>
* <li> {@link libsbmlConstants#LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS}
* <li> {@link libsbmlConstants#LIBSBML_INVALID_XML_OPERATION LIBSBML_INVALID_XML_OPERATION}
*
* </ul> <p>
* @note if local name with the same namespace URI already exists in the
* attribute set, its value and prefix will be replaced.
<p>
*
</dl><dl class="docnote"><dt><b>Documentation note:</b></dt><dd>
The native C++ implementation of this method defines a default argument
value. In the documentation generated for different libSBML language
bindings, you may or may not see corresponding arguments in the method
declarations. For example, in Java and C#, a default argument is handled by
declaring two separate methods, with one of them having the argument and
the other one lacking the argument. However, the libSBML documentation will
be <em>identical</em> for both methods. Consequently, if you are reading
this and do not see an argument even though one is described, please look
for descriptions of other variants of this method near where this one
appears in the documentation.
</dd></dl>
*/ public
int addAttr(String name, String value, String namespaceURI) {
return libsbmlJNI.XMLToken_addAttr__SWIG_1(swigCPtr, this, name, value, namespaceURI);
}
/**
* Adds an attribute to the attribute set in this {@link XMLToken} optionally
* with a prefix and URI defining a namespace.
* Nothing will be done if this {@link XMLToken} is not a start element.
<p>
* @param name a string, the local name of the attribute.
* @param value a string, the value of the attribute.
* @param namespaceURI a string, the namespace URI of the attribute.
* @param prefix a string, the prefix of the namespace
<p>
* @return integer value indicating success/failure of the
* function. The possible values
* returned by this function are:
* <ul>
* <li> {@link libsbmlConstants#LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS}
* <li> {@link libsbmlConstants#LIBSBML_INVALID_XML_OPERATION LIBSBML_INVALID_XML_OPERATION}
*
* </ul> <p>
* @note if local name with the same namespace URI already exists in the
* attribute set, its value and prefix will be replaced.
<p>
*
</dl><dl class="docnote"><dt><b>Documentation note:</b></dt><dd>
The native C++ implementation of this method defines a default argument
value. In the documentation generated for different libSBML language
bindings, you may or may not see corresponding arguments in the method
declarations. For example, in Java and C#, a default argument is handled by
declaring two separate methods, with one of them having the argument and
the other one lacking the argument. However, the libSBML documentation will
be <em>identical</em> for both methods. Consequently, if you are reading
this and do not see an argument even though one is described, please look
for descriptions of other variants of this method near where this one
appears in the documentation.
</dd></dl>
*/ public
int addAttr(String name, String value) {
return libsbmlJNI.XMLToken_addAttr__SWIG_2(swigCPtr, this, name, value);
}
/**
* Adds an attribute with the given {@link XMLTriple}/value pair to the attribute set
* in this {@link XMLToken}.
* Nothing will be done if this {@link XMLToken} is not a start element.
<p>
* @note if local name with the same namespace URI already exists in the
* attribute set, its value and prefix will be replaced.
<p>
* @param triple an {@link XMLTriple}, the XML triple of the attribute.
* @param value a string, the value of the attribute.
<p>
* @return integer value indicating success/failure of the
* function. The possible values
* returned by this function are:
* <ul>
* <li> {@link libsbmlConstants#LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS}
* <li> {@link libsbmlConstants#LIBSBML_INVALID_XML_OPERATION LIBSBML_INVALID_XML_OPERATION}
* </ul>
*/ public
int addAttr(XMLTriple triple, String value) {
return libsbmlJNI.XMLToken_addAttr__SWIG_3(swigCPtr, this, XMLTriple.getCPtr(triple), triple, value);
}
/**
* Removes an attribute with the given index from the attribute set in
* this {@link XMLToken}.
* Nothing will be done if this {@link XMLToken} is not a start element.
<p>
* @param n an integer the index of the resource to be deleted
<p>
* @return integer value indicating success/failure of the
* function. The possible values
* returned by this function are:
* <ul>
* <li> {@link libsbmlConstants#LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS}
* <li> {@link libsbmlConstants#LIBSBML_INVALID_XML_OPERATION LIBSBML_INVALID_XML_OPERATION}
* <li> {@link libsbmlConstants#LIBSBML_INDEX_EXCEEDS_SIZE LIBSBML_INDEX_EXCEEDS_SIZE}
* </ul>
*/ public
int removeAttr(int n) {
return libsbmlJNI.XMLToken_removeAttr__SWIG_0(swigCPtr, this, n);
}
/**
* Removes an attribute with the given local name and namespace URI from
* the attribute set in this {@link XMLToken}.
* Nothing will be done if this {@link XMLToken} is not a start element.
<p>
* @param name a string, the local name of the attribute.
* @param uri a string, the namespace URI of the attribute.
<p>
* @return integer value indicating success/failure of the
* function. The possible values
* returned by this function are:
* <ul>
* <li> {@link libsbmlConstants#LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS}
* <li> {@link libsbmlConstants#LIBSBML_INVALID_XML_OPERATION LIBSBML_INVALID_XML_OPERATION}
* <li> {@link libsbmlConstants#LIBSBML_INDEX_EXCEEDS_SIZE LIBSBML_INDEX_EXCEEDS_SIZE}
* </ul>
*/ public
int removeAttr(String name, String uri) {
return libsbmlJNI.XMLToken_removeAttr__SWIG_1(swigCPtr, this, name, uri);
}
/**
* Removes an attribute with the given local name and namespace URI from
* the attribute set in this {@link XMLToken}.
* Nothing will be done if this {@link XMLToken} is not a start element.
<p>
* @param name a string, the local name of the attribute.
* @param uri a string, the namespace URI of the attribute.
<p>
* @return integer value indicating success/failure of the
* function. The possible values
* returned by this function are:
* <ul>
* <li> {@link libsbmlConstants#LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS}
* <li> {@link libsbmlConstants#LIBSBML_INVALID_XML_OPERATION LIBSBML_INVALID_XML_OPERATION}
* <li> {@link libsbmlConstants#LIBSBML_INDEX_EXCEEDS_SIZE LIBSBML_INDEX_EXCEEDS_SIZE}
* </ul>
*/ public
int removeAttr(String name) {
return libsbmlJNI.XMLToken_removeAttr__SWIG_2(swigCPtr, this, name);
}
/**
* Removes an attribute with the given {@link XMLTriple} from the attribute set
* in this {@link XMLToken}.
* Nothing will be done if this {@link XMLToken} is not a start element.
<p>
* @param triple an {@link XMLTriple}, the XML triple of the attribute.
<p>
* @return integer value indicating success/failure of the
* function. The possible values
* returned by this function are:
* <ul>
* <li> {@link libsbmlConstants#LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS}
* <li> {@link libsbmlConstants#LIBSBML_INVALID_XML_OPERATION LIBSBML_INVALID_XML_OPERATION}
* <li> {@link libsbmlConstants#LIBSBML_INDEX_EXCEEDS_SIZE LIBSBML_INDEX_EXCEEDS_SIZE}
* </ul>
*/ public
int removeAttr(XMLTriple triple) {
return libsbmlJNI.XMLToken_removeAttr__SWIG_3(swigCPtr, this, XMLTriple.getCPtr(triple), triple);
}
/**
* Clears (deletes) all attributes in this {@link XMLToken}.
* Nothing will be done if this {@link XMLToken} is not a start element.
<p>
* @return integer value indicating success/failure of the
* function. The possible values
* returned by this function are:
* <ul>
* <li> {@link libsbmlConstants#LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS}
* <li> {@link libsbmlConstants#LIBSBML_INVALID_XML_OPERATION LIBSBML_INVALID_XML_OPERATION}
* </ul>
*/ public
int clearAttributes() {
return libsbmlJNI.XMLToken_clearAttributes(swigCPtr, this);
}
/**
* Return the index of an attribute with the given local name and namespace URI.
<p>
* @param name a string, the local name of the attribute.
* @param uri a string, the namespace URI of the attribute.
<p>
* @return the index of an attribute with the given local name and namespace URI,
* or <code>-1</code> if not present.
<p>
*
</dl><dl class="docnote"><dt><b>Documentation note:</b></dt><dd>
The native C++ implementation of this method defines a default argument
value. In the documentation generated for different libSBML language
bindings, you may or may not see corresponding arguments in the method
declarations. For example, in Java and C#, a default argument is handled by
declaring two separate methods, with one of them having the argument and
the other one lacking the argument. However, the libSBML documentation will
be <em>identical</em> for both methods. Consequently, if you are reading
this and do not see an argument even though one is described, please look
for descriptions of other variants of this method near where this one
appears in the documentation.
</dd></dl>
*/ public
int getAttrIndex(String name, String uri) {
return libsbmlJNI.XMLToken_getAttrIndex__SWIG_0(swigCPtr, this, name, uri);
}
/**
* Return the index of an attribute with the given local name and namespace URI.
<p>
* @param name a string, the local name of the attribute.
* @param uri a string, the namespace URI of the attribute.
<p>
* @return the index of an attribute with the given local name and namespace URI,
* or <code>-1</code> if not present.
<p>
*
</dl><dl class="docnote"><dt><b>Documentation note:</b></dt><dd>
The native C++ implementation of this method defines a default argument
value. In the documentation generated for different libSBML language
bindings, you may or may not see corresponding arguments in the method
declarations. For example, in Java and C#, a default argument is handled by
declaring two separate methods, with one of them having the argument and
the other one lacking the argument. However, the libSBML documentation will
be <em>identical</em> for both methods. Consequently, if you are reading
this and do not see an argument even though one is described, please look
for descriptions of other variants of this method near where this one
appears in the documentation.
</dd></dl>
*/ public
int getAttrIndex(String name) {
return libsbmlJNI.XMLToken_getAttrIndex__SWIG_1(swigCPtr, this, name);
}
/**
* Return the index of an attribute with the given {@link XMLTriple}.
<p>
* @param triple an {@link XMLTriple}, the XML triple of the attribute for which
* the index is required.
<p>
* @return the index of an attribute with the given {@link XMLTriple}, or <code>-1</code> if not present.
*/ public
int getAttrIndex(XMLTriple triple) {
return libsbmlJNI.XMLToken_getAttrIndex__SWIG_2(swigCPtr, this, XMLTriple.getCPtr(triple), triple);
}
/**
* Return the number of attributes in the attributes set.
<p>
* @return the number of attributes in the attributes set in this {@link XMLToken}.
*/ public
int getAttributesLength() {
return libsbmlJNI.XMLToken_getAttributesLength(swigCPtr, this);
}
/**
* Return the local name of an attribute in the attributes set in this
* {@link XMLToken} (by position).
<p>
* @param index an integer, the position of the attribute whose local name
* is required.
<p>
* @return the local name of an attribute in this list (by position).
<p>
* @note If index
* is out of range, an empty string will be returned. Use
* {@link XMLToken#hasAttr(int)}
* to test for the attribute existence.
*/ public
String getAttrName(int index) {
return libsbmlJNI.XMLToken_getAttrName(swigCPtr, this, index);
}
/**
* Return the prefix of an attribute in the attribute set in this
* {@link XMLToken} (by position).
<p>
* @param index an integer, the position of the attribute whose prefix is
* required.
<p>
* @return the namespace prefix of an attribute in the attribute set
* (by position).
<p>
* @note If index is out of range, an empty string will be returned. Use
* {@link XMLToken#hasAttr(int)} to test
* for the attribute existence.
*/ public
String getAttrPrefix(int index) {
return libsbmlJNI.XMLToken_getAttrPrefix(swigCPtr, this, index);
}
/**
* Return the prefixed name of an attribute in the attribute set in this
* {@link XMLToken} (by position).
<p>
* @param index an integer, the position of the attribute whose prefixed
* name is required.
<p>
* @return the prefixed name of an attribute in the attribute set
* (by position).
<p>
* @note If index is out of range, an empty string will be returned. Use
* {@link XMLToken#hasAttr(int)} to test
* for attribute existence.
*/ public
String getAttrPrefixedName(int index) {
return libsbmlJNI.XMLToken_getAttrPrefixedName(swigCPtr, this, index);
}
/**
* Return the namespace URI of an attribute in the attribute set in this
* {@link XMLToken} (by position).
<p>
* @param index an integer, the position of the attribute whose namespace
* URI is required.
<p>
* @return the namespace URI of an attribute in the attribute set (by position).
<p>
* @note If index is out of range, an empty string will be returned. Use
* {@link XMLToken#hasAttr(int)} to test
* for attribute existence.
*/ public
String getAttrURI(int index) {
return libsbmlJNI.XMLToken_getAttrURI(swigCPtr, this, index);
}
/**
* Return the value of an attribute in the attribute set in this {@link XMLToken}
* (by position).
<p>
* @param index an integer, the position of the attribute whose value is
* required.
<p>
* @return the value of an attribute in the attribute set (by position).
<p>
* @note If index is out of range, an empty string will be returned. Use
* {@link XMLToken#hasAttr(int)} to test
* for attribute existence.
*/ public
String getAttrValue(int index) {
return libsbmlJNI.XMLToken_getAttrValue__SWIG_0(swigCPtr, this, index);
}
/**
* Return a value of an attribute with the given local name and namespace URI.
<p>
* @param name a string, the local name of the attribute whose value is required.
* @param uri a string, the namespace URI of the attribute.
<p>
* @return The attribute value as a string.
<p>
* @note If an attribute with the
* given local name and namespace URI does not exist, an empty string will be
* returned.
* Use {@link XMLToken#hasAttr(String, String)}
* to test for attribute existence.
<p>
*
</dl><dl class="docnote"><dt><b>Documentation note:</b></dt><dd>
The native C++ implementation of this method defines a default argument
value. In the documentation generated for different libSBML language
bindings, you may or may not see corresponding arguments in the method
declarations. For example, in Java and C#, a default argument is handled by
declaring two separate methods, with one of them having the argument and
the other one lacking the argument. However, the libSBML documentation will
be <em>identical</em> for both methods. Consequently, if you are reading
this and do not see an argument even though one is described, please look
for descriptions of other variants of this method near where this one
appears in the documentation.
</dd></dl>
*/ public
String getAttrValue(String name, String uri) {
return libsbmlJNI.XMLToken_getAttrValue__SWIG_1(swigCPtr, this, name, uri);
}
/**
* Return a value of an attribute with the given local name and namespace URI.
<p>
* @param name a string, the local name of the attribute whose value is required.
* @param uri a string, the namespace URI of the attribute.
<p>
* @return The attribute value as a string.
<p>
* @note If an attribute with the
* given local name and namespace URI does not exist, an empty string will be
* returned.
* Use {@link XMLToken#hasAttr(String, String)}
* to test for attribute existence.
<p>
*
</dl><dl class="docnote"><dt><b>Documentation note:</b></dt><dd>
The native C++ implementation of this method defines a default argument
value. In the documentation generated for different libSBML language
bindings, you may or may not see corresponding arguments in the method
declarations. For example, in Java and C#, a default argument is handled by
declaring two separate methods, with one of them having the argument and
the other one lacking the argument. However, the libSBML documentation will
be <em>identical</em> for both methods. Consequently, if you are reading
this and do not see an argument even though one is described, please look
for descriptions of other variants of this method near where this one
appears in the documentation.
</dd></dl>
*/ public
String getAttrValue(String name) {
return libsbmlJNI.XMLToken_getAttrValue__SWIG_2(swigCPtr, this, name);
}
/**
* Return a value of an attribute with the given {@link XMLTriple}.
<p>
* @param triple an {@link XMLTriple}, the XML triple of the attribute whose
* value is required.
<p>
* @return The attribute value as a string.
<p>
* @note If an attribute with the
* given {@link XMLTriple} does not exist, an empty string will be returned.
* Use {@link XMLToken#hasAttr(XMLTriple)}
* to test for attribute existence.
*/ public
String getAttrValue(XMLTriple triple) {
return libsbmlJNI.XMLToken_getAttrValue__SWIG_3(swigCPtr, this, XMLTriple.getCPtr(triple), triple);
}
/**
* Predicate returning <code>true</code> or <code>false</code> depending on whether
* an attribute with the given index exists in the attribute set in this
* {@link XMLToken}.
<p>
* @param index an integer, the position of the attribute.
<p>
* @return <code>true</code> if an attribute with the given index exists in the attribute
* set in this {@link XMLToken}, <code>false</code> otherwise.
*/ public
boolean hasAttr(int index) {
return libsbmlJNI.XMLToken_hasAttr__SWIG_0(swigCPtr, this, index);
}
/**
* Predicate returning <code>true</code> or <code>false</code> depending on whether
* an attribute with the given local name and namespace URI exists
* in the attribute set in this {@link XMLToken}.
<p>
* @param name a string, the local name of the attribute.
* @param uri a string, the namespace URI of the attribute.
<p>
* @return <code>true</code> if an attribute with the given local name and namespace
* URI exists in the attribute set in this {@link XMLToken}, <code>false</code> otherwise.
<p>
*
</dl><dl class="docnote"><dt><b>Documentation note:</b></dt><dd>
The native C++ implementation of this method defines a default argument
value. In the documentation generated for different libSBML language
bindings, you may or may not see corresponding arguments in the method
declarations. For example, in Java and C#, a default argument is handled by
declaring two separate methods, with one of them having the argument and
the other one lacking the argument. However, the libSBML documentation will
be <em>identical</em> for both methods. Consequently, if you are reading
this and do not see an argument even though one is described, please look
for descriptions of other variants of this method near where this one
appears in the documentation.
</dd></dl>
*/ public
boolean hasAttr(String name, String uri) {
return libsbmlJNI.XMLToken_hasAttr__SWIG_1(swigCPtr, this, name, uri);
}
/**
* Predicate returning <code>true</code> or <code>false</code> depending on whether
* an attribute with the given local name and namespace URI exists
* in the attribute set in this {@link XMLToken}.
<p>
* @param name a string, the local name of the attribute.
* @param uri a string, the namespace URI of the attribute.
<p>
* @return <code>true</code> if an attribute with the given local name and namespace
* URI exists in the attribute set in this {@link XMLToken}, <code>false</code> otherwise.
<p>
*
</dl><dl class="docnote"><dt><b>Documentation note:</b></dt><dd>
The native C++ implementation of this method defines a default argument
value. In the documentation generated for different libSBML language
bindings, you may or may not see corresponding arguments in the method
declarations. For example, in Java and C#, a default argument is handled by
declaring two separate methods, with one of them having the argument and
the other one lacking the argument. However, the libSBML documentation will
be <em>identical</em> for both methods. Consequently, if you are reading
this and do not see an argument even though one is described, please look
for descriptions of other variants of this method near where this one
appears in the documentation.
</dd></dl>
*/ public
boolean hasAttr(String name) {
return libsbmlJNI.XMLToken_hasAttr__SWIG_2(swigCPtr, this, name);
}
/**
* Predicate returning <code>true</code> or <code>false</code> depending on whether
* an attribute with the given XML triple exists in the attribute set in
* this {@link XMLToken}
<p>
* @param triple an {@link XMLTriple}, the XML triple of the attribute
<p>
* @return <code>true</code> if an attribute with the given XML triple exists
* in the attribute set in this {@link XMLToken}, <code>false</code> otherwise.
*/ public
boolean hasAttr(XMLTriple triple) {
return libsbmlJNI.XMLToken_hasAttr__SWIG_3(swigCPtr, this, XMLTriple.getCPtr(triple), triple);
}
/**
* Predicate returning <code>true</code> or <code>false</code> depending on whether
* the attribute set in this {@link XMLToken} set is empty.
<p>
* @return <code>true</code> if the attribute set in this {@link XMLToken} is empty,
* <code>false</code> otherwise.
*/ public
boolean isAttributesEmpty() {
return libsbmlJNI.XMLToken_isAttributesEmpty(swigCPtr, this);
}
/**
* Returns the XML namespace declarations for this XML element.
<p>
* @return the XML namespace declarations for this XML element.
*/ public
XMLNamespaces getNamespaces() {
return new XMLNamespaces(libsbmlJNI.XMLToken_getNamespaces(swigCPtr, this), false);
}
/**
* Sets an XMLnamespaces to this XML element.
* Nothing will be done if this {@link XMLToken} is not a start element.
<p>
* @param namespaces {@link XMLNamespaces} to be set to this {@link XMLToken}.
<p>
* @return integer value indicating success/failure of the
* function. The possible values
* returned by this function are:
* <ul>
* <li> {@link libsbmlConstants#LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS}
* <li> {@link libsbmlConstants#LIBSBML_OPERATION_FAILED LIBSBML_OPERATION_FAILED}
* <li> {@link libsbmlConstants#LIBSBML_INVALID_XML_OPERATION LIBSBML_INVALID_XML_OPERATION}
* <li> {@link libsbmlConstants#LIBSBML_INVALID_OBJECT LIBSBML_INVALID_OBJECT}
*
* </ul> <p>
* @note This function replaces the existing {@link XMLNamespaces} with the new one.
*/ public
int setNamespaces(XMLNamespaces namespaces) {
return libsbmlJNI.XMLToken_setNamespaces(swigCPtr, this, XMLNamespaces.getCPtr(namespaces), namespaces);
}
/**
* Appends an XML namespace prefix and URI pair to this {@link XMLToken}.
* If there is an XML namespace with the given prefix in this {@link XMLToken},
* then the existing XML namespace will be overwritten by the new one.
<p>
* Nothing will be done if this {@link XMLToken} is not a start element.
<p>
* @param uri a string, the uri for the namespace
* @param prefix a string, the prefix for the namespace
<p>
* @return integer value indicating success/failure of the
* function. The possible values
* returned by this function are:
* <ul>
* <li> {@link libsbmlConstants#LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS}
* <li> {@link libsbmlConstants#LIBSBML_INVALID_XML_OPERATION LIBSBML_INVALID_XML_OPERATION}
*
* </ul> <p>
*
</dl><dl class="docnote"><dt><b>Documentation note:</b></dt><dd>
The native C++ implementation of this method defines a default argument
value. In the documentation generated for different libSBML language
bindings, you may or may not see corresponding arguments in the method
declarations. For example, in Java and C#, a default argument is handled by
declaring two separate methods, with one of them having the argument and
the other one lacking the argument. However, the libSBML documentation will
be <em>identical</em> for both methods. Consequently, if you are reading
this and do not see an argument even though one is described, please look
for descriptions of other variants of this method near where this one
appears in the documentation.
</dd></dl>
*/ public
int addNamespace(String uri, String prefix) {
return libsbmlJNI.XMLToken_addNamespace__SWIG_0(swigCPtr, this, uri, prefix);
}
/**
* Appends an XML namespace prefix and URI pair to this {@link XMLToken}.
* If there is an XML namespace with the given prefix in this {@link XMLToken},
* then the existing XML namespace will be overwritten by the new one.
<p>
* Nothing will be done if this {@link XMLToken} is not a start element.
<p>
* @param uri a string, the uri for the namespace
* @param prefix a string, the prefix for the namespace
<p>
* @return integer value indicating success/failure of the
* function. The possible values
* returned by this function are:
* <ul>
* <li> {@link libsbmlConstants#LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS}
* <li> {@link libsbmlConstants#LIBSBML_INVALID_XML_OPERATION LIBSBML_INVALID_XML_OPERATION}
*
* </ul> <p>
*
</dl><dl class="docnote"><dt><b>Documentation note:</b></dt><dd>
The native C++ implementation of this method defines a default argument
value. In the documentation generated for different libSBML language
bindings, you may or may not see corresponding arguments in the method
declarations. For example, in Java and C#, a default argument is handled by
declaring two separate methods, with one of them having the argument and
the other one lacking the argument. However, the libSBML documentation will
be <em>identical</em> for both methods. Consequently, if you are reading
this and do not see an argument even though one is described, please look
for descriptions of other variants of this method near where this one
appears in the documentation.
</dd></dl>
*/ public
int addNamespace(String uri) {
return libsbmlJNI.XMLToken_addNamespace__SWIG_1(swigCPtr, this, uri);
}
/**
* Removes an XML Namespace stored in the given position of the {@link XMLNamespaces}
* of this {@link XMLToken}.
* Nothing will be done if this {@link XMLToken} is not a start element.
<p>
* @param index an integer, position of the removed namespace.
<p>
* @return integer value indicating success/failure of the
* function. The possible values
* returned by this function are:
* <ul>
* <li> {@link libsbmlConstants#LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS}
* <li> {@link libsbmlConstants#LIBSBML_INVALID_XML_OPERATION LIBSBML_INVALID_XML_OPERATION}
* <li> {@link libsbmlConstants#LIBSBML_INDEX_EXCEEDS_SIZE LIBSBML_INDEX_EXCEEDS_SIZE}
* </ul>
*/ public
int removeNamespace(int index) {
return libsbmlJNI.XMLToken_removeNamespace__SWIG_0(swigCPtr, this, index);
}
/**
* Removes an XML Namespace with the given prefix.
* Nothing will be done if this {@link XMLToken} is not a start element.
<p>
* @param prefix a string, prefix of the required namespace.
<p>
* @return integer value indicating success/failure of the
* function. The possible values
* returned by this function are:
* <ul>
* <li> {@link libsbmlConstants#LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS}
* <li> {@link libsbmlConstants#LIBSBML_INVALID_XML_OPERATION LIBSBML_INVALID_XML_OPERATION}
* <li> {@link libsbmlConstants#LIBSBML_INDEX_EXCEEDS_SIZE LIBSBML_INDEX_EXCEEDS_SIZE}
* </ul>
*/ public
int removeNamespace(String prefix) {
return libsbmlJNI.XMLToken_removeNamespace__SWIG_1(swigCPtr, this, prefix);
}
/**
* Clears (deletes) all XML namespace declarations in the {@link XMLNamespaces} of
* this {@link XMLToken}.
* Nothing will be done if this {@link XMLToken} is not a start element.
<p>
* @return integer value indicating success/failure of the
* function. The possible values
* returned by this function are:
* <ul>
* <li> {@link libsbmlConstants#LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS}
* <li> {@link libsbmlConstants#LIBSBML_INVALID_XML_OPERATION LIBSBML_INVALID_XML_OPERATION}
* </ul>
*/ public
int clearNamespaces() {
return libsbmlJNI.XMLToken_clearNamespaces(swigCPtr, this);
}
/**
* Look up the index of an XML namespace declaration by URI.
<p>
* @param uri a string, uri of the required namespace.
<p>
* @return the index of the given declaration, or <code>-1</code> if not present.
*/ public
int getNamespaceIndex(String uri) {
return libsbmlJNI.XMLToken_getNamespaceIndex(swigCPtr, this, uri);
}
/**
* Look up the index of an XML namespace declaration by prefix.
<p>
* @param prefix a string, prefix of the required namespace.
<p>
* @return the index of the given declaration, or <code>-1</code> if not present.
*/ public
int getNamespaceIndexByPrefix(String prefix) {
return libsbmlJNI.XMLToken_getNamespaceIndexByPrefix(swigCPtr, this, prefix);
}
/**
* Returns the number of XML namespaces stored in the {@link XMLNamespaces}
* of this {@link XMLToken}.
<p>
* @return the number of namespaces in this list.
*/ public
int getNamespacesLength() {
return libsbmlJNI.XMLToken_getNamespacesLength(swigCPtr, this);
}
/**
* Look up the prefix of an XML namespace declaration by position.
<p>
* Callers should use getNamespacesLength() to find out how many
* namespaces are stored in the {@link XMLNamespaces}.
<p>
* @param index an integer, position of the required prefix.
<p>
* @return the prefix of an XML namespace declaration in the {@link XMLNamespaces}
* (by position).
<p>
* @note If index is out of range, an empty string will be
* returned.
<p>
* @see #getNamespacesLength()
*/ public
String getNamespacePrefix(int index) {
return libsbmlJNI.XMLToken_getNamespacePrefix__SWIG_0(swigCPtr, this, index);
}
/**
* Look up the prefix of an XML namespace declaration by its URI.
<p>
* @param uri a string, the URI of the prefix being sought
<p>
* @return the prefix of an XML namespace declaration given its URI.
<p>
* @note If <code>uri</code> does not exist, an empty string will be returned.
*/ public
String getNamespacePrefix(String uri) {
return libsbmlJNI.XMLToken_getNamespacePrefix__SWIG_1(swigCPtr, this, uri);
}
/**
* Look up the URI of an XML namespace declaration by its position.
<p>
* @param index an integer, position of the required URI.
<p>
* @return the URI of an XML namespace declaration in the {@link XMLNamespaces}
* (by position).
<p>
* @note If <code>index</code> is out of range, an empty string will be
* returned.
<p>
* @see #getNamespacesLength()
*/ public
String getNamespaceURI(int index) {
return libsbmlJNI.XMLToken_getNamespaceURI__SWIG_0(swigCPtr, this, index);
}
/**
* Look up the URI of an XML namespace declaration by its prefix.
<p>
* @param prefix a string, the prefix of the required URI
<p>
* @return the URI of an XML namespace declaration given its prefix.
<p>
* @note If <code>prefix</code> does not exist, an empty string will be returned.
<p>
*
</dl><dl class="docnote"><dt><b>Documentation note:</b></dt><dd>
The native C++ implementation of this method defines a default argument
value. In the documentation generated for different libSBML language
bindings, you may or may not see corresponding arguments in the method
declarations. For example, in Java and C#, a default argument is handled by
declaring two separate methods, with one of them having the argument and
the other one lacking the argument. However, the libSBML documentation will
be <em>identical</em> for both methods. Consequently, if you are reading
this and do not see an argument even though one is described, please look
for descriptions of other variants of this method near where this one
appears in the documentation.
</dd></dl>
*/ public
String getNamespaceURI(String prefix) {
return libsbmlJNI.XMLToken_getNamespaceURI__SWIG_1(swigCPtr, this, prefix);
}
/**
* Look up the URI of an XML namespace declaration by its prefix.
<p>
* @param prefix a string, the prefix of the required URI
<p>
* @return the URI of an XML namespace declaration given its prefix.
<p>
* @note If <code>prefix</code> does not exist, an empty string will be returned.
<p>
*
</dl><dl class="docnote"><dt><b>Documentation note:</b></dt><dd>
The native C++ implementation of this method defines a default argument
value. In the documentation generated for different libSBML language
bindings, you may or may not see corresponding arguments in the method
declarations. For example, in Java and C#, a default argument is handled by
declaring two separate methods, with one of them having the argument and
the other one lacking the argument. However, the libSBML documentation will
be <em>identical</em> for both methods. Consequently, if you are reading
this and do not see an argument even though one is described, please look
for descriptions of other variants of this method near where this one
appears in the documentation.
</dd></dl>
*/ public
String getNamespaceURI() {
return libsbmlJNI.XMLToken_getNamespaceURI__SWIG_2(swigCPtr, this);
}
/**
* Predicate returning <code>true</code> or <code>false</code> depending on whether
* the {@link XMLNamespaces} of this {@link XMLToken} is empty.
<p>
* @return <code>true</code> if the {@link XMLNamespaces} of this {@link XMLToken} is empty,
* <code>false</code> otherwise.
*/ public
boolean isNamespacesEmpty() {
return libsbmlJNI.XMLToken_isNamespacesEmpty(swigCPtr, this);
}
/**
* Predicate returning <code>true</code> or <code>false</code> depending on whether
* an XML Namespace with the given URI is contained in the {@link XMLNamespaces} of
* this {@link XMLToken}.
<p>
* @param uri a string, the uri for the namespace
<p>
* @return <code>true</code> if an XML Namespace with the given URI is contained in the
* {@link XMLNamespaces} of this {@link XMLToken}, <code>false</code> otherwise.
*/ public
boolean hasNamespaceURI(String uri) {
return libsbmlJNI.XMLToken_hasNamespaceURI(swigCPtr, this, uri);
}
/**
* Predicate returning <code>true</code> or <code>false</code> depending on whether
* an XML Namespace with the given prefix is contained in the {@link XMLNamespaces} of
* this {@link XMLToken}.
<p>
* @param prefix a string, the prefix for the namespace
<p>
* @return <code>true</code> if an XML Namespace with the given URI is contained in the
* {@link XMLNamespaces} of this {@link XMLToken}, <code>false</code> otherwise.
*/ public
boolean hasNamespacePrefix(String prefix) {
return libsbmlJNI.XMLToken_hasNamespacePrefix(swigCPtr, this, prefix);
}
/**
* Predicate returning <code>true</code> or <code>false</code> depending on whether
* an XML Namespace with the given uri/prefix pair is contained in the
* {@link XMLNamespaces} ofthis {@link XMLToken}.
<p>
* @param uri a string, the uri for the namespace
* @param prefix a string, the prefix for the namespace
<p>
* @return <code>true</code> if an XML Namespace with the given uri/prefix pair is
* contained in the {@link XMLNamespaces} of this {@link XMLToken}, <code>false</code> otherwise.
*/ public
boolean hasNamespaceNS(String uri, String prefix) {
return libsbmlJNI.XMLToken_hasNamespaceNS(swigCPtr, this, uri, prefix);
}
/**
* Sets the XMLTripe (name, uri and prefix) of this XML element.
* Nothing will be done if this XML element is a text node.
<p>
* @param triple {@link XMLTriple} to be added to this XML element.
<p>
* @return integer value indicating success/failure of the
* function. The possible values
* returned by this function are:
* <ul>
* <li> {@link libsbmlConstants#LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS}
* <li> {@link libsbmlConstants#LIBSBML_OPERATION_FAILED LIBSBML_OPERATION_FAILED}
* <li> {@link libsbmlConstants#LIBSBML_INVALID_XML_OPERATION LIBSBML_INVALID_XML_OPERATION}
* <li> {@link libsbmlConstants#LIBSBML_INVALID_OBJECT LIBSBML_INVALID_OBJECT}
* </ul>
*/ public
int setTriple(XMLTriple triple) {
return libsbmlJNI.XMLToken_setTriple(swigCPtr, this, XMLTriple.getCPtr(triple), triple);
}
/**
* Returns the (unqualified) name of this XML element.
<p>
* @return the (unqualified) name of this XML element.
*/ public
String getName() {
return libsbmlJNI.XMLToken_getName(swigCPtr, this);
}
/**
* Returns the namespace prefix of this XML element.
<p>
* @return the namespace prefix of this XML element.
<p>
* @note If no prefix
* exists, an empty string will be return.
*/ public
String getPrefix() {
return libsbmlJNI.XMLToken_getPrefix(swigCPtr, this);
}
/**
* Returns the namespace URI of this XML element.
<p>
* @return the namespace URI of this XML element.
*/ public
String getURI() {
return libsbmlJNI.XMLToken_getURI(swigCPtr, this);
}
/**
* Returns the text of this element.
<p>
* @return the characters of this XML text.
*/ public
String getCharacters() {
return libsbmlJNI.XMLToken_getCharacters(swigCPtr, this);
}
/**
* Appends characters to this XML text content.
<p>
* @param chars string, characters to append
<p>
* @return integer value indicating success/failure of the
* function. The possible values
* returned by this function are:
* <ul>
* <li> {@link libsbmlConstants#LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS}
* <li> {@link libsbmlConstants#LIBSBML_OPERATION_FAILED LIBSBML_OPERATION_FAILED}
* </ul>
*/ public
int append(String chars) {
return libsbmlJNI.XMLToken_append(swigCPtr, this, chars);
}
/**
* Returns the column at which this {@link XMLToken} occurred in the input
* document or data stream.
<p>
* @return the column at which this {@link XMLToken} occurred.
*/ public
long getColumn() {
return libsbmlJNI.XMLToken_getColumn(swigCPtr, this);
}
/**
* Returns the line at which this {@link XMLToken} occurred in the input document
* or data stream.
<p>
* @return the line at which this {@link XMLToken} occurred.
*/ public
long getLine() {
return libsbmlJNI.XMLToken_getLine(swigCPtr, this);
}
/**
* Predicate returning <code>true</code> or <code>false</code> depending on whether
* this {@link XMLToken} is an XML element.
<p>
* @return <code>true</code> if this {@link XMLToken} is an XML element, <code>false</code> otherwise.
*/ public
boolean isElement() {
return libsbmlJNI.XMLToken_isElement(swigCPtr, this);
}
/**
* Predicate returning <code>true</code> or <code>false</code> depending on whether
* this {@link XMLToken} is an XML end element.
<p>
* @return <code>true</code> if this {@link XMLToken} is an XML end element, <code>false</code> otherwise.
*/ public
boolean isEnd() {
return libsbmlJNI.XMLToken_isEnd(swigCPtr, this);
}
/**
* Predicate returning <code>true</code> or <code>false</code> depending on whether
* this {@link XMLToken} is an XML end element for the given start element.
<p>
* @param element {@link XMLToken}, element for which query is made.
<p>
* @return <code>true</code> if this {@link XMLToken} is an XML end element for the given
* {@link XMLToken} start element, <code>false</code> otherwise.
*/ public
boolean isEndFor(XMLToken element) {
return libsbmlJNI.XMLToken_isEndFor(swigCPtr, this, XMLToken.getCPtr(element), element);
}
/**
* Predicate returning <code>true</code> or <code>false</code> depending on whether
* this {@link XMLToken} is an end of file marker.
<p>
* @return <code>true</code> if this {@link XMLToken} is an end of file (input) marker, <code>false</code>
* otherwise.
*/ public
boolean isEOF() {
return libsbmlJNI.XMLToken_isEOF(swigCPtr, this);
}
/**
* Predicate returning <code>true</code> or <code>false</code> depending on whether
* this {@link XMLToken} is an XML start element.
<p>
* @return <code>true</code> if this {@link XMLToken} is an XML start element, <code>false</code> otherwise.
*/ public
boolean isStart() {
return libsbmlJNI.XMLToken_isStart(swigCPtr, this);
}
/**
* Predicate returning <code>true</code> or <code>false</code> depending on whether
* this {@link XMLToken} is an XML text element.
<p>
* @return <code>true</code> if this {@link XMLToken} is an XML text element, <code>false</code> otherwise.
*/ public
boolean isText() {
return libsbmlJNI.XMLToken_isText(swigCPtr, this);
}
/**
* Declares this XML start element is also an end element.
<p>
* @return integer value indicating success/failure of the
* function. The possible values
* returned by this function are:
* <ul>
* <li> {@link libsbmlConstants#LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS}
* <li> {@link libsbmlConstants#LIBSBML_OPERATION_FAILED LIBSBML_OPERATION_FAILED}
* </ul>
*/ public
int setEnd() {
return libsbmlJNI.XMLToken_setEnd(swigCPtr, this);
}
/**
* Declares this {@link XMLToken} is an end-of-file (input) marker.
<p>
* @return integer value indicating success/failure of the
* function. The possible values
* returned by this function are:
* <ul>
* <li> {@link libsbmlConstants#LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS}
* <li> {@link libsbmlConstants#LIBSBML_OPERATION_FAILED LIBSBML_OPERATION_FAILED}
* </ul>
*/ public
int setEOF() {
return libsbmlJNI.XMLToken_setEOF(swigCPtr, this);
}
/**
* Declares this XML start/end element is no longer an end element.
<p>
* @return integer value indicating success/failure of the
* function. The possible values
* returned by this function are:
* <ul>
* <li> {@link libsbmlConstants#LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS}
* <li> {@link libsbmlConstants#LIBSBML_OPERATION_FAILED LIBSBML_OPERATION_FAILED}
* </ul>
*/ public
int unsetEnd() {
return libsbmlJNI.XMLToken_unsetEnd(swigCPtr, this);
}
/**
* Prints a string representation of the underlying token stream, for
* debugging purposes.
*/ public
String toString() {
return libsbmlJNI.XMLToken_toString(swigCPtr, this);
}
}
| 39.093463 | 191 | 0.718814 |
0c66710f2c25a0d803aebc7eaeccdeea886793d4 | 2,629 | package com.zackehh.jackson.stream.collectors;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.IntNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.TextNode;
import com.zackehh.jackson.stream.JiveCollectors;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.stream.Collector;
public class ArrayNodeCollectorTest {
private final ArrayNodeCollector arrayNodeCollector = JiveCollectors.toArrayNode();
@Test
public void testSupplier() {
ArrayNode actual = arrayNodeCollector.supplier().get();
ArrayNode expected = JsonNodeFactory.instance.arrayNode();
Assert.assertEquals(actual, expected);
}
@Test
public void testAccumulator() {
BiConsumer<ArrayNode, JsonNode> consumer = arrayNodeCollector.accumulator();
ArrayNode base = JsonNodeFactory.instance.arrayNode();
JsonNode value = TextNode.valueOf("test");
consumer.accept(base, value);
Assert.assertEquals(base.size(), 1);
Assert.assertEquals(base.path(0), value);
}
@Test
public void testCombiner() {
BinaryOperator<ArrayNode> combiner = arrayNodeCollector.combiner();
ArrayNode left = JsonNodeFactory.instance.arrayNode()
.add(1).add(2);
ArrayNode right = JsonNodeFactory.instance.arrayNode()
.add(3).add(4);
combiner.apply(left, right);
Assert.assertEquals(left.size(), 4);
Assert.assertEquals(left.path(0), IntNode.valueOf(1));
Assert.assertEquals(left.path(1), IntNode.valueOf(2));
Assert.assertEquals(left.path(2), IntNode.valueOf(3));
Assert.assertEquals(left.path(3), IntNode.valueOf(4));
}
@Test
public void testFinisher() {
Function<ArrayNode, ArrayNode> finisher = arrayNodeCollector.finisher();
ArrayNode base = JsonNodeFactory.instance.arrayNode()
.add(1).add(2).add(3);
ArrayNode kept = finisher.apply(base);
Assert.assertEquals(kept, base);
}
@Test
public void testCharacteristics() {
Set<Collector.Characteristics> characteristics = arrayNodeCollector.characteristics();
Assert.assertEquals(characteristics.size(), 1);
Assert.assertTrue(characteristics.contains(Collector.Characteristics.IDENTITY_FINISH));
}
}
| 32.060976 | 95 | 0.701788 |
e38dba3d699f9c94717c0e38c2b15b6b2cd61f30 | 3,055 | package gov.cms.mat.qdmqicore.conversion.dto;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import gov.cms.mat.qdmqicore.mapping.model.google.GoogleMatAttributes;
import gov.cms.mat.qdmqicore.mapping.model.google.GoogleMatAttributesData;
import gov.cms.mat.qdmqicore.mapping.model.google.GoogleMatAttributesFeed;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import static gov.cms.mat.qdmqicore.mapping.utils.SpreadSheetUtils.getData;
import static org.junit.Assert.assertEquals;
class ConversionDataTest {
@Test
void getFeed() throws JsonProcessingException {
GoogleMatAttributesData googleMatAtttributes = createConversionDataFromFile();
GoogleMatAttributesFeed feed = googleMatAtttributes.getFeed();
assertEquals(595, feed.getEntry().size());
GoogleMatAttributes entry = feed.getEntry().get(0);
// no null safe Data mapping method implementation
assertEquals("1", entry.getMatDataTypeId().getData());
assertEquals("398", entry.getMatAttributeId().getData());
assertEquals("2019-11-06T14:39:34.529Z", entry.getUpdated().getData());
assertEquals("Patient Care Experience", entry.getTitle().getData());
assertEquals(entry.getTitle().getData(), getData(entry.getTitle()));
assertEquals("Patient Care Experience", entry.getMatDataTypeDescription().getData());
assertEquals(entry.getMatDataTypeDescription().getData(), getData(entry.getMatDataTypeDescription()));
assertEquals("authorDatetime", entry.getMatAttributeName().getData());
assertEquals(entry.getMatAttributeName().getData(), getData(entry.getMatAttributeName()));
assertEquals("Observation.issued", entry.getFhirR4QiCoreMapping().getData());
assertEquals(entry.getFhirR4QiCoreMapping().getData(), getData(entry.getFhirR4QiCoreMapping()));
assertEquals("Observation", entry.getFhirResource().getData());
assertEquals(entry.getFhirResource().getData(), getData(entry.getFhirResource()));
assertEquals("issued", entry.getFhirElement().getData());
assertEquals(entry.getFhirElement().getData(), getData(entry.getFhirElement()));
assertEquals("instant", entry.getFhirType().getData());
assertEquals(entry.getFhirType().getData(), getData(entry.getFhirType()));
}
private GoogleMatAttributesData createConversionDataFromFile() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(getJson(), GoogleMatAttributesData.class);
}
private String getJson() {
File inputXmlFile = new File(this.getClass().getResource("/spread_sheet_data.json").getFile());
try {
return new String(Files.readAllBytes(inputXmlFile.toPath()));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
} | 43.642857 | 110 | 0.730606 |
ac2366c96ae108f4485f51ef19a30ecbf14d5940 | 1,754 | package com.cqupt.model;
public class Task {
private String createUser;
private String title;
private String remark;
private String startDate;
private String endDate;
private String isDiscuss;
private String content;
private int taskID;
private int students;
private int exams;
public String getCreateUser() {
return createUser;
}
public void setCreateUser(String createUser) {
this.createUser = createUser;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public String getIsDiscuss() {
return isDiscuss;
}
public void setIsDiscuss(String isDiscuss) {
this.isDiscuss = isDiscuss;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getTaskID() {
return taskID;
}
public void setTaskID(int taskID) {
this.taskID = taskID;
}
public int getStudents() {
return students;
}
public void setStudents(int students) {
this.students = students;
}
public int getExams() {
return exams;
}
public void setExams(int exams) {
this.exams = exams;
}
@Override
public boolean equals(Object o) {
if(o == null) return false;
if(o == this) return true;
if(o instanceof Task){
Task other = (Task)o;
return this.taskID == other.taskID;
}else{
return false;
}
}
}
| 18.659574 | 47 | 0.697834 |
2be4a5f701cb77c3f16fcdfff4882d34db02eeb1 | 7,339 | /*
* Copyright (C) 2015 The Async HBase Authors. All rights reserved.
* This file is part of Async HBase.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the StumbleUpon nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.hbase.async;
import com.google.protobuf.CodedOutputStream;
import org.hbase.async.generated.RPCPB;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.Channels;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.security.sasl.Sasl;
import java.io.IOException;
import java.net.SocketAddress;
/**
* Implementation for security on HBase servers version 96 and up
*
* See {@link SecureRpcHelper} for configuration
*/
class SecureRpcHelper96 extends SecureRpcHelper {
private static final Logger LOG = LoggerFactory.getLogger(
SecureRpcHelper96.class);
/** The array to send as the first hello */
final byte[] connection_header;
/**
* Ctor that instantiates the authentication provider and attempts to
* authenticate at the same time.
* @param hbase_client The Hbase client we belong to
* @param region_client The region client we're dealing with
* @param remote_endpoint The remote endpoint of the HBase Region server.
*/
public SecureRpcHelper96(final HBaseClient hbase_client,
final RegionClient region_client, final SocketAddress remote_endpoint) {
super(hbase_client, region_client, remote_endpoint);
connection_header = new byte[] { 'H', 'B', 'a', 's',
0, // RPC version.
client_auth_provider.getAuthMethodCode() //authmethod
};
}
@Override
public void sendHello(final Channel channel) {
ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(connection_header);
Channels.write(channel, buffer);
// sasl_client is null for Simple Auth case
if (sasl_client != null) {
byte[] challenge_bytes = null;
if (sasl_client.hasInitialResponse()) {
challenge_bytes = processChallenge(new byte[0]);
}
if (challenge_bytes != null) {
final byte[] buf = new byte[4 + challenge_bytes.length];
buffer = ChannelBuffers.wrappedBuffer(buf);
buffer.clear();
buffer.writeInt(challenge_bytes.length);
buffer.writeBytes(challenge_bytes);
//if (LOG.isDebugEnabled()) {
// LOG.debug("Sending initial SASL Challenge: " + Bytes.pretty(buf));
//}
Channels.write(channel, buffer);
} else {
// TODO - is this exception worthy? We'll never get back here
LOG.error("Missing initial Sasl response on client " + region_client);
}
} else {
sendRPCHeader(channel);
}
}
@Override
public ChannelBuffer handleResponse(final ChannelBuffer buf,
final Channel chan) {
if (sasl_client == null) {
return buf;
}
if (!sasl_client.isComplete()) {
final int read_index = buf.readerIndex();
final int state = buf.readInt();
//0 is success
//If unsuccessful let common exception handling do the work
if (state != 0) {
LOG.error("Sasl initialization failed with a status of [" + state +
"]: " + this);
buf.readerIndex(read_index);
return buf;
}
final int len = buf.readInt();
final byte[] b = new byte[len];
buf.readBytes(b);
//if (LOG.isDebugEnabled()) {
// LOG.debug("Got SASL challenge: "+Bytes.pretty(b));
//}
final byte[] challenge_bytes = processChallenge(b);
if (challenge_bytes != null) {
final byte[] out_bytes = new byte[4 + challenge_bytes.length];
//if (LOG.isDebugEnabled()) {
// LOG.debug("Sending SASL response: "+Bytes.pretty(out_bytes));
//}
final ChannelBuffer out_buffer = ChannelBuffers.wrappedBuffer(out_bytes);
out_buffer.clear();
out_buffer.writeInt(challenge_bytes.length);
out_buffer.writeBytes(challenge_bytes);
Channels.write(chan, out_buffer);
}
if (sasl_client.isComplete()) {
final String qop = (String)sasl_client.getNegotiatedProperty(Sasl.QOP);
LOG.info("SASL client context established. Negotiated QoP: " + qop +
" on for: " + region_client);
sendRPCHeader(chan);
} else {
// TODO is this an issue?
}
return null;
}
return unwrap(buf);
}
/**
* Writes a header to the region server with the authenticated username.
* It will also mark the region client as ready to process so that any
* pending RPCs will be flushed to the server.
* @param chan The channel to write to
*/
private void sendRPCHeader(final Channel chan) {
final RPCPB.UserInformation user = RPCPB.UserInformation.newBuilder()
.setEffectiveUser(client_auth_provider.getClientUsername())
.build();
final RPCPB.ConnectionHeader pb = RPCPB.ConnectionHeader.newBuilder()
.setUserInfo(user)
.setServiceName("ClientService")
.setCellBlockCodecClass("org.apache.hadoop.hbase.codec.KeyValueCodec")
.build();
final int pblen = pb.getSerializedSize();
final byte[] buf = new byte[4 + pblen];
final ChannelBuffer header = ChannelBuffers.wrappedBuffer(buf);
header.clear();
header.writeInt(pblen); // 4 bytes
try {
final CodedOutputStream output =
CodedOutputStream.newInstance(buf, 4, pblen);
pb.writeTo(output);
output.checkNoSpaceLeft();
} catch (IOException e) {
throw new RuntimeException("Should never happen", e);
}
// We wrote to the underlying buffer but Netty didn't see the writes,
// so move the write index forward.
header.writerIndex(buf.length);
Channels.write(chan, header);
region_client.becomeReady(chan, RegionClient.SERVER_VERSION_095_OR_ABOVE);
}
}
| 38.025907 | 81 | 0.685516 |
e0243f2b32cec652e5f8482b007a340ee2692161 | 4,093 | package qouteall.imm_ptl.core.mixin.client.sound;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.client.resources.sounds.SimpleSoundInstance;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.phys.Vec3;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import qouteall.imm_ptl.core.teleportation.CrossPortalSound;
@Mixin(ClientLevel.class)
public class MixinClientWorld_Sound {
@Shadow
@Final
private Minecraft minecraft;
@Inject(
method = "Lnet/minecraft/client/multiplayer/ClientLevel;playLocalSound(DDDLnet/minecraft/sounds/SoundEvent;Lnet/minecraft/sounds/SoundSource;FFZ)V",
at = @At("HEAD"),
cancellable = true
)
private void onPlaySound(
double x, double y, double z,
SoundEvent sound, SoundSource category, float volume, float pitch, boolean repeat,
CallbackInfo ci
) {
ClientLevel this_ = (ClientLevel) (Object) this;
Vec3 soundPos = new Vec3(x, y, z);
if (!portal_isPosNearPlayer(soundPos)) {
SimpleSoundInstance crossPortalSound = CrossPortalSound.createCrossPortalSound(
this_, sound, category, soundPos, volume, pitch
);
if (crossPortalSound != null) {
portal_playSound(crossPortalSound, repeat);
ci.cancel();
}
else if (!CrossPortalSound.isPlayerWorld(this_)) {
// do not play remote sound when no portal can transfer the sound
ci.cancel();
}
}
}
@Inject(
method = "Lnet/minecraft/client/multiplayer/ClientLevel;playSound(Lnet/minecraft/world/entity/player/Player;Lnet/minecraft/world/entity/Entity;Lnet/minecraft/sounds/SoundEvent;Lnet/minecraft/sounds/SoundSource;FF)V",
at = @At("HEAD"),
cancellable = true
)
private void onPlaySoundFromEntity(
Player player, Entity entity,
SoundEvent sound, SoundSource category, float volume, float pitch, CallbackInfo ci
) {
ClientLevel this_ = (ClientLevel) (Object) this;
if (!portal_isPosNearPlayer(entity.position())) {
SimpleSoundInstance crossPortalSound = CrossPortalSound.createCrossPortalSound(
this_, sound, category, entity.position(), volume, pitch
);
if (crossPortalSound != null) {
minecraft.getSoundManager().play(crossPortalSound);
ci.cancel();
}
else if (!CrossPortalSound.isPlayerWorld(this_)) {
// do not play remote sound when no portal can transfer the sound
ci.cancel();
}
}
}
private void portal_playSound(SimpleSoundInstance sound, boolean repeat) {
double d = minecraft.gameRenderer.getMainCamera().getPosition().distanceToSqr(sound.getX(), sound.getY(), sound.getZ());
if (repeat && d > 100.0D) {
double e = Math.sqrt(d) / 40.0D;
minecraft.getSoundManager().playDelayed(sound, (int) (e * 20.0D));
}
else {
minecraft.getSoundManager().play(sound);
}
}
private boolean portal_isPosNearPlayer(Vec3 pos) {
ClientLevel this_ = (ClientLevel) (Object) this;
LocalPlayer player = minecraft.player;
if (player == null) {
return false;
}
if (this_ != player.level) {
return false;
}
return pos.distanceToSqr(player.position()) < 64 * 64;
}
}
| 37.209091 | 224 | 0.640362 |
6f5def9c054ddf48483c6f478b869ddea262a4ee | 1,818 | /**
*
*/
package binarytrees;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import entities.TreeNode;
import util.Utility;
/**
* @author PRATAP LeetCode 199
*
*/
public class RightViewBinaryTree {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
while (t-- > 0) {
String[] input = br.readLine().split("\\s+");
TreeNode root = Utility.createBinaryTree(input);
List<Integer> list = rightSideView(root);
StringBuilder sb = new StringBuilder();
for (int i : list)
sb.append(i + " ");
System.out.println(sb.toString());
}
}
public static List<Integer> rightSideView(TreeNode root) {
List<RNode> list = new ArrayList<RNode>();
List<Integer> res = new ArrayList<Integer>();
if (root == null)
return res;
Queue<RNode> q = new LinkedList<RNode>();
q.add(new RNode(root, 0));
while (!q.isEmpty()) {
RNode curr = q.remove();
if (list.size() == 0) {
list.add(curr);
} else if (list.size() > 0 && list.get(list.size() - 1).level != curr.level) {
list.add(curr);
}
if (curr.node.right != null) {
q.add(new RNode(curr.node.right, curr.level + 1));
}
if (curr.node.left != null) {
q.add(new RNode(curr.node.left, curr.level + 1));
}
}
for (RNode node : list)
res.add(node.node.data);
return res;
}
}
class RNode {
public TreeNode node;
public int level;
public RNode(TreeNode node, int level) {
super();
this.node = node;
this.level = level;
}
}
| 22.444444 | 81 | 0.649615 |
f21c143ab019961760fa36751f64961e1a39ac55 | 6,503 | /*
* Copyright (C) 2012 The CyanogenMod Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cyanogenmod.settings.device;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.TwoStatePreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
public class DeviceSettings extends PreferenceActivity {
public static final String KEY_S2WSWITCH = "s2w_switch";
public static final String KEY_S2WSTROKE = "s2w_stroke";
public static final String KEY_S2WLENGTH = "s2w_length";
public static final String KEY_DOUBLETAB2WAKE_SWITCH = "s2w_double_tap_wake";
public static final String KEY_DOUBLETAP2WAKE_DURATION = "s2w_double_tap_duration";
public static final String KEY_DOUBLETAP2WAKE_BARRIER = "s2w_double_tap_barrier";
public static final String KEY_VIBSTRENGTH = "vib_strength";
private TwoStatePreference mS2WSwitch;
private ListPreference mS2WStroke;
private ListPreference mS2WLength;
private TwoStatePreference mDoubleTap2WakeSwitch;
private ListPreference mDoubleTap2WakeDuration;
private ListPreference mDoubleTap2WakeBarrier;
private VibratorStrengthPreference mVibratorStrength;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.main);
mS2WSwitch = (TwoStatePreference) findPreference(KEY_S2WSWITCH);
mS2WSwitch.setEnabled(Sweep2WakeSwitch.isSupported());
mS2WSwitch.setChecked(Sweep2WakeSwitch.isEnabled(this));
mS2WSwitch.setOnPreferenceChangeListener(new Sweep2WakeSwitch());
mS2WStroke = (ListPreference) findPreference(KEY_S2WSTROKE);
mS2WStroke.setEnabled(Sweep2WakeStroke.isSupported());
mS2WStroke.setValue(Sweep2WakeStroke.getValue(this));
mS2WStroke.setOnPreferenceChangeListener(new Sweep2WakeStroke());
mS2WLength = (ListPreference) findPreference(KEY_S2WLENGTH);
mS2WLength.setEnabled(Sweep2WakeMinLength.isSupported());
mS2WLength.setValue(squashLengthValue(Sweep2WakeMinLength.getValue(this)));
mS2WLength.setOnPreferenceChangeListener(new Sweep2WakeMinLength());
mDoubleTap2WakeSwitch = (TwoStatePreference) findPreference(KEY_DOUBLETAB2WAKE_SWITCH);
mDoubleTap2WakeSwitch.setEnabled(DoubleTap2WakeSwitch.isSupported());
mDoubleTap2WakeSwitch.setChecked(DoubleTap2WakeSwitch.isEnabled(this));
mDoubleTap2WakeSwitch.setOnPreferenceChangeListener(new DoubleTap2WakeSwitch());
mDoubleTap2WakeDuration = (ListPreference) findPreference(KEY_DOUBLETAP2WAKE_DURATION);
mDoubleTap2WakeDuration.setEnabled(DoubleTap2WakeDuration.isSupported());
mDoubleTap2WakeDuration.setValue(squashDurationValue(DoubleTap2WakeDuration.getValue(this)));
mDoubleTap2WakeDuration.setOnPreferenceChangeListener(new DoubleTap2WakeDuration());
mDoubleTap2WakeBarrier = (ListPreference) findPreference(KEY_DOUBLETAP2WAKE_BARRIER);
mDoubleTap2WakeBarrier.setEnabled(DoubleTap2WakeBarrier.isSupported());
mDoubleTap2WakeBarrier.setValue(DoubleTap2WakeBarrier.getValue(this));
mDoubleTap2WakeBarrier.setOnPreferenceChangeListener(new DoubleTap2WakeBarrier());
mVibratorStrength = (VibratorStrengthPreference) findPreference(KEY_VIBSTRENGTH);
mVibratorStrength.setEnabled(VibratorStrengthPreference.isSupported());
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
private String squashLengthValue(String value) {
// map it to 325, 500, 850 if not exact value
int intValue=new Integer(value).intValue();
if(intValue==325 || intValue==500 || intValue==850){
return value;
}
// we found a different value in sysfs
// map it to our 3 possible length
if(intValue<325)
return "325";
if(intValue>850)
return "850";
if(intValue>325 && intValue <500){
int diff1=intValue-325;
int diff2=500-intValue;
return (diff1<diff2)?"325":"500";
}
if(intValue>500 && intValue <850){
int diff1=intValue-500;
int diff2=850-intValue;
return (diff1<diff2)?"500":"850";
}
return value;
}
private String squashDurationValue(String value) {
// map it to 150, 200, 250, 300, 350 if not exact value
int intValue=new Integer(value).intValue();
if(intValue==150 || intValue==200 || intValue==250 || intValue==300 || intValue==350){
return value;
}
// we found a different value in sysfs
// map it to our 5 possible durations
if(intValue<150)
return "150";
if(intValue>350)
return "350";
if(intValue>300 && intValue <350){
int diff1=intValue-300;
int diff2=350-intValue;
return (diff1<diff2)?"300":"350";
}
if(intValue>250 && intValue <300){
int diff1=intValue-250;
int diff2=300-intValue;
return (diff1<diff2)?"250":"300";
}
if(intValue>200 && intValue <250){
int diff1=intValue-200;
int diff2=250-intValue;
return (diff1<diff2)?"200":"250";
}
if(intValue>150 && intValue <200){
int diff1=intValue-150;
int diff2=200-intValue;
return (diff1<diff2)?"150":"200";
}
return value;
}
}
| 39.895706 | 101 | 0.69614 |
0c01d6e4f746a2d9202073b534476814d17958a6 | 85 | package com.company.Strategy;
public interface PaymentStrategy {
void pay();
}
| 12.142857 | 34 | 0.729412 |
f58063e834971863d4f7d98e140994397155b9ef | 1,128 | package IB;
import java.util.ArrayList;
public class MergeTwoLists {
public void merge(ArrayList<Integer> a, ArrayList<Integer> b) {
int j=a.size()-1;
int k=b.size()-1;
int length = a.size()+ b.size();
System.out.println(length);
ArrayList<Integer> a1 = new ArrayList<>(length);
for (int i=length-1; i >=0 ; i-- ){
if (a.get(j) > b.get(k)){
System.out.println("sdgfd"+i+" "+j);
a1.add(i, a.get(j));
j--;
}
else{
System.out.println(b.get(k));
System.out.println("rrrrr"+i+" "+k);
a1.add(i, b.get(k));
k--;
}
}
a =a1 ;
a1 =null;
System.out.println(a);
}
public static void main(String[] args) {
MergeTwoLists mr = new MergeTwoLists();
ArrayList<Integer> arr = new ArrayList<>();
arr.add(-4);
arr.add(-3);
ArrayList<Integer> arr1 = new ArrayList<>();
arr1.add(-2);
arr1.add(-2);
mr.merge(arr , arr1);
}
}
| 25.636364 | 67 | 0.460993 |
de50ddf62f97ffb6598dfdb3eb1afeb26fa48914 | 2,164 | package middleware;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/* so that the cell does not have to keep track of all these game-wide values
* initialized in Initializer
* string to hashmap. similar to dfv but dfv never changes
* currentparameters change based on user input/choice
*/
public class CurrentParameters {
private HashMap<String, HashMap<String, String>> currentParams = new HashMap<String, HashMap<String, String>>();
private DefaultValues dfv;
private Map<String, String> gameLevelParams;
public CurrentParameters(ArrayList<HashMap<String, String>> currentMaps, DefaultValues defaults, Map<String, String> gameLevelParams) {
for (HashMap<String, String> df_map : currentMaps) {
currentParams.put(df_map.get("state"), df_map);
}
System.out.println("keyset of currentParams: ");
for (String key : currentParams.keySet()) {
System.out.println("Key: " + key + "; " + currentParams.get(key));
}
dfv = defaults;
this.gameLevelParams = gameLevelParams;
}
public Map<String, String> getGameLevelParameterMap() {
return gameLevelParams;
}
public Map<String, String> getCurrentParameterMap(String state) {
HashMap<String, String> val = currentParams.get(state);
return val;
}
public void setGameLevelParameter(String param, String value) throws IllegalArgumentException {
if (!gameLevelParams.containsKey(param)) {
throw new IllegalArgumentException();
}
gameLevelParams.put(param, value);
}
/*
* @param state: cell state that should be affected
*
* @param parameterToChange: specific parameter that should change
*
* @param newValue: String value that parameter should change to
*/
public void changeOrAddParameterValues(String state, String parameterToChangeOrAdd, String newValue) {
HashMap<String, String> mapChange = currentParams.get(state);
mapChange.put(parameterToChangeOrAdd, newValue); // will either replace existing k,v pair or add a new one
currentParams.put(state, mapChange);
}
public void revertToDefaultValues() {
for (String state : currentParams.keySet()) {
currentParams.put(state, dfv.getDefaultMap(state));
}
}
}
| 33.8125 | 136 | 0.748614 |
1c2a70e21143f62ea67102eb3079d2e9a4b6e93a | 1,230 | package com.github.ponser2000.inside_test.to;
import java.time.LocalDateTime;
public class MessageTo {
int id;
LocalDateTime dateTime;
String message;
int user_id;
public MessageTo(int id, LocalDateTime dateTime, String message, int user_id) {
this.id = id;
this.dateTime = dateTime;
this.message = message;
this.user_id = user_id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public LocalDateTime getDateTime() {
return dateTime;
}
public void setDateTime(LocalDateTime dateTime) {
this.dateTime = dateTime;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
@Override
public String toString() {
return "MessageTo{" +
"id=" + id +
", dateTime=" + dateTime +
", message='" + message + '\'' +
", user_id=" + user_id +
'}';
}
}
| 20.5 | 83 | 0.549593 |
9dcc00bb4b364b573d9368a7d7ae9e41a2f2c05f | 1,856 | /*
* #%L
* wcm.io
* %%
* Copyright (C) 2017 wcm.io
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package io.wcm.devops.maven.aembinariesproxy;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.dropwizard.Configuration;
import io.dropwizard.client.HttpClientConfiguration;
/**
* Configuration for Maven AEM Binaries Proxy.
*/
public class MavenProxyConfiguration extends Configuration {
@NotEmpty
private String groupId;
@NotEmpty
private String aemDispatcherArtifactId;
@NotEmpty
private String aemBinariesRootUrl;
@NotEmpty
private String aemBinariesUrlParts;
@Valid
@NotNull
private HttpClientConfiguration httpClient = new HttpClientConfiguration();
@JsonProperty
public String getGroupId() {
return this.groupId;
}
@JsonProperty
public String getAemDispatcherArtifactId() {
return this.aemDispatcherArtifactId;
}
@JsonProperty
public String getAemBinariesRootUrl() {
return this.aemBinariesRootUrl;
}
@JsonProperty
public String getAemBinariesUrlParts() {
return this.aemBinariesUrlParts;
}
@JsonProperty("httpClient")
public HttpClientConfiguration getHttpClient() {
return httpClient;
}
}
| 24.421053 | 77 | 0.753772 |
2840e933986cf62d3d420b4a90a70da9a526b25b | 357 | package com.puppycrawl.tools.checkstyle.checks.whitespace.nowhitespaceafter;
import java.util.function.Function;
import java.util.function.IntFunction;
public class InputNoWhitespaceAfterMethodRef
{
IntFunction<int[]> arrayMaker = int []::new;//incorrect 10:40
Function<Integer, String[]> messageArrayFactory = String []::new;//incorrect 11:63
}
| 29.75 | 86 | 0.778711 |
3c0aec67378f18093b8ba87ea38aa456456634cb | 3,952 | package io.renren.modules.Excel;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import io.renren.modules.eir.until.FileUtil;
import org.apache.poi.ss.usermodel.Workbook;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by timmy.deng on 2018/11/30.
*/
public class compareExcelN4b {
public List<StaffEntity> loadStaff() {
List<StaffEntity> list = FileUtil.importExcel("C:\\Users\\timmy.deng.DCB1\\Desktop\\新账号\\active_staff.xlsx",
0, 1, StaffEntity.class);
return list;
}
public static void main(String[] args) {
compareExcelN4b excelN4b = new compareExcelN4b();
List<N4bEntity> newentities = FileUtil.importExcel("C:\\Users\\timmy.deng.DCB1\\Desktop\\excel1\\N4B-2018.xlsx",
0,1,N4bEntity.class);
List<N4bEntity> oldentities = FileUtil.importExcel("C:\\Users\\timmy.deng.DCB1\\Desktop\\excel1\\N4B-2017.xlsx",0,1,N4bEntity.class);
System.out.println("newentities共:"+newentities.size()+"条数据");
System.out.println("oldentities.size() = " + oldentities.size());
List<N4bEntity> list = new ArrayList<>();
List<StaffEntity> staffEntities = excelN4b.loadStaff();
//比较新老excel
for (N4bEntity newentity : newentities) {
// System.out.println("newentity.getECN4_USER_ID() = " + newentity.getECN4_USER_ID());
boolean flag=false;
//先在部门员工表找
for (StaffEntity staffEntity : staffEntities) {
if (newentity.getUSER_ID().equals(staffEntity.getNo())){
newentity.setDepartment(staffEntity.getDepartment());
flag=true;
break;
}
}
if (!flag) {
System.out.println();
// 员工表未找到部门,在去年的表找
for (N4bEntity oldentity : oldentities) {
if (newentity.getUSER_ID().equals(oldentity.getUSER_ID())
//&& newentity.getROLE_NAME().equals(oldentity.getROLE_NAME())
) {
newentity.setDepartment(oldentity.getDepartment());
flag = true;
break;
}
}
}
newentity.setUSER_NAME(newentity.getUSER_LAST_NAME()+" "+newentity.getUSER_FIRST_NAME());
if (flag==false){ //未找到与去年一样的账号
list.add(newentity);
}
}
for (N4bEntity entity : list) {
System.out.println("账号:"+entity.getUSER_ID()+"系统名:"+entity.getROLE_NAME()+"用户名:"+entity.getUSER_LAST_NAME()+" "+entity.getUSER_FIRST_NAME());
}
System.out.println("异常数据共:"+list.size()+"条.");
//导出到文件
try {
Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("2018年新增账号","N4b"),N4bEntity.class,list);
File outFile = new File("C:\\Users\\timmy.deng.DCB1\\Desktop\\excel1\\2018-N4B新增账号.xls");
outFile.createNewFile();
FileOutputStream outputStream = new FileOutputStream(outFile);
workbook.write(outputStream);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("2018年账号带部门","N4b"),N4bEntity.class,newentities);
File outFile = new File("C:\\Users\\timmy.deng.DCB1\\Desktop\\excel1\\2018-N4B账号带部门.xls");
outFile.createNewFile();
FileOutputStream outputStream = new FileOutputStream(outFile);
workbook.write(outputStream);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 29.714286 | 153 | 0.585273 |
26f8f60bc8692bd08f0a526d019f385591092e89 | 19,189 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.dubbo.remoting.exchange.codec;
import com.alibaba.dubbo.common.io.Bytes;
import com.alibaba.dubbo.common.io.StreamUtils;
import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import com.alibaba.dubbo.common.serialize.Cleanable;
import com.alibaba.dubbo.common.serialize.ObjectInput;
import com.alibaba.dubbo.common.serialize.ObjectOutput;
import com.alibaba.dubbo.common.serialize.Serialization;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.remoting.Channel;
import com.alibaba.dubbo.remoting.RemotingException;
import com.alibaba.dubbo.remoting.buffer.ChannelBuffer;
import com.alibaba.dubbo.remoting.buffer.ChannelBufferInputStream;
import com.alibaba.dubbo.remoting.buffer.ChannelBufferOutputStream;
import com.alibaba.dubbo.remoting.exchange.Request;
import com.alibaba.dubbo.remoting.exchange.Response;
import com.alibaba.dubbo.remoting.exchange.support.DefaultFuture;
import com.alibaba.dubbo.remoting.telnet.codec.TelnetCodec;
import com.alibaba.dubbo.remoting.transport.CodecSupport;
import com.alibaba.dubbo.remoting.transport.ExceedPayloadLimitException;
import java.io.IOException;
import java.io.InputStream;
/**
* ExchangeCodec.
* <p>
* 信息交换编解码器
*/
public class ExchangeCodec extends TelnetCodec {
private static final Logger logger = LoggerFactory.getLogger(ExchangeCodec.class);
// header length.
protected static final int HEADER_LENGTH = 16;
// magic header.
protected static final short MAGIC = (short) 0xdabb;
protected static final byte MAGIC_HIGH = Bytes.short2bytes(MAGIC)[0];
protected static final byte MAGIC_LOW = Bytes.short2bytes(MAGIC)[1];
// message flag.
protected static final byte FLAG_REQUEST = (byte) 0x80; // 128
protected static final byte FLAG_TWOWAY = (byte) 0x40; // 64
protected static final byte FLAG_EVENT = (byte) 0x20; // 32
protected static final int SERIALIZATION_MASK = 0x1f; // 31
public Short getMagicCode() {
return MAGIC;
}
@Override
public void encode(Channel channel, ChannelBuffer buffer, Object msg) throws IOException {
if (msg instanceof Request) { // 请求
encodeRequest(channel, buffer, (Request) msg);
} else if (msg instanceof Response) { // 响应
encodeResponse(channel, buffer, (Response) msg);
} else { // 提交给父类( Telnet ) 处理,目前是 Telnet 命令的结果。
super.encode(channel, buffer, msg);
}
}
@Override
public Object decode(Channel channel, ChannelBuffer buffer) throws IOException {
// 读取 Header 数组
int readable = buffer.readableBytes();
byte[] header = new byte[Math.min(readable, HEADER_LENGTH)];
buffer.readBytes(header);
// 解码
return decode(channel, buffer, readable, header);
}
@Override
protected Object decode(Channel channel, ChannelBuffer buffer, int readable, byte[] header) throws IOException {
// 非 Dubbo 协议,目前是 Telnet 命令。
// check magic number.
if (readable > 0 && header[0] != MAGIC_HIGH || readable > 1 && header[1] != MAGIC_LOW) {
// 将 buffer 完全复制到 `header` 数组中。因为,上面的 `#decode(channel, buffer)` 方法,可能未读全
int length = header.length;
if (header.length < readable) {
header = Bytes.copyOf(header, readable);
buffer.readBytes(header, length, readable - length);
}
// 【TODO 8026 】header[i] == MAGIC_HIGH && header[i + 1] == MAGIC_LOW ?
for (int i = 1; i < header.length - 1; i++) {
if (header[i] == MAGIC_HIGH && header[i + 1] == MAGIC_LOW) {
buffer.readerIndex(buffer.readerIndex() - header.length + i);
header = Bytes.copyOf(header, i);
break;
}
}
// 提交给父类( Telnet ) 处理,目前是 Telnet 命令。
return super.decode(channel, buffer, readable, header);
}
// Header 长度不够,返回需要更多的输入
// check length.
if (readable < HEADER_LENGTH) {
return DecodeResult.NEED_MORE_INPUT;
}
// `[96 - 127]`:Body 的**长度**。通过该长度,读取 Body 。
// get data length.
int len = Bytes.bytes2int(header, 12);
checkPayload(channel, len);
// 总长度不够,返回需要更多的输入
int tt = len + HEADER_LENGTH;
if (readable < tt) {
return DecodeResult.NEED_MORE_INPUT;
}
// 解析 Header + Body
// limit input stream.
ChannelBufferInputStream is = new ChannelBufferInputStream(buffer, len);
try {
return decodeBody(channel, is, header);
} finally {
// skip 未读完的流,并打印错误日志
if (is.available() > 0) {
try {
if (logger.isWarnEnabled()) {
logger.warn("Skip input stream " + is.available());
}
StreamUtils.skipUnusedStream(is);
} catch (IOException e) {
logger.warn(e.getMessage(), e);
}
}
}
}
/**
* 解析,返回 Request 或 Response
*
* @param channel 通道
* @param is 输出
* @param header Header
* @return 结果
* @throws IOException 当发生 IO 异常时
*/
protected Object decodeBody(Channel channel, InputStream is, byte[] header) throws IOException {
byte flag = header[2], proto = (byte) (flag & SERIALIZATION_MASK);
Serialization s = CodecSupport.getSerialization(channel.getUrl(), proto);
ObjectInput in = s.deserialize(channel.getUrl(), is);
// Response
// get request id.
long id = Bytes.bytes2long(header, 4);
if ((flag & FLAG_REQUEST) == 0) { // Response
// decode response.
Response res = new Response(id);
if ((flag & FLAG_EVENT) != 0) {
res.setEvent(Response.HEARTBEAT_EVENT);
}
// get status.
byte status = header[3];
res.setStatus(status);
if (status == Response.OK) {
try {
Object data;
if (res.isHeartbeat()) {
data = decodeHeartbeatData(channel, in);
} else if (res.isEvent()) {
data = decodeEventData(channel, in);
} else {
data = decodeResponseData(channel, in, getRequestData(id)); // `#getRequestData(id)` 的调用,是多余的
}
res.setResult(data);
} catch (Throwable t) {
res.setStatus(Response.CLIENT_ERROR);
res.setErrorMessage(StringUtils.toString(t));
}
} else {
res.setErrorMessage(in.readUTF());
}
return res;
// Request
} else { // Request
// decode request.
Request req = new Request(id);
req.setVersion("2.0.0");
req.setTwoWay((flag & FLAG_TWOWAY) != 0);
if ((flag & FLAG_EVENT) != 0) { // 心跳事件
req.setEvent(Request.HEARTBEAT_EVENT);
}
try {
Object data;
if (req.isHeartbeat()) {
data = decodeHeartbeatData(channel, in);
} else if (req.isEvent()) {
data = decodeEventData(channel, in);
} else {
data = decodeRequestData(channel, in);
}
req.setData(data);
} catch (Throwable t) {
// bad request
req.setBroken(true);
req.setData(t);
}
return req;
}
}
protected Object getRequestData(long id) {
DefaultFuture future = DefaultFuture.getFuture(id);
if (future == null) {
return null;
}
Request req = future.getRequest();
if (req == null) {
return null;
}
return req.getData();
}
/**
* 编码请求
*
* @param channel 通道
* @param buffer Buffer
* @param req 请求
* @throws IOException 当发生 IO 异常时
*/
protected void encodeRequest(Channel channel, ChannelBuffer buffer, Request req) throws IOException {
Serialization serialization = getSerialization(channel);
// `[0, 15]`:Magic Number
// header.
byte[] header = new byte[HEADER_LENGTH];
// set magic number.
Bytes.short2bytes(MAGIC, header);
// `[16, 20]`:Serialization 编号 && `[23]`:请求。
// set request and serialization flag.
header[2] = (byte) (FLAG_REQUEST | serialization.getContentTypeId());
// `[21]`:`event` 是否为事件。
if (req.isTwoWay()) header[2] |= FLAG_TWOWAY;
// `[22]`:`twoWay` 是否需要响应。
if (req.isEvent()) header[2] |= FLAG_EVENT;
// `[32 - 95]`:`id` 编号,Long 型。
// set request id.
Bytes.long2bytes(req.getId(), header, 4);
// 编码 `Request.data` 到 Body ,并写入到 Buffer
// encode request data.
int savedWriteIndex = buffer.writerIndex();
buffer.writerIndex(savedWriteIndex + HEADER_LENGTH);
ChannelBufferOutputStream bos = new ChannelBufferOutputStream(buffer);
ObjectOutput out = serialization.serialize(channel.getUrl(), bos); // 序列化 Output
if (req.isEvent()) {
encodeEventData(channel, out, req.getData());
} else {
encodeRequestData(channel, out, req.getData());
}
// 释放资源
out.flushBuffer();
if (out instanceof Cleanable) {
((Cleanable) out).cleanup();
}
bos.flush();
bos.close();
// 检查 Body 长度,是否超过消息上限。
int len = bos.writtenBytes();
checkPayload(channel, len);
// `[96 - 127]`:Body 的**长度**。
Bytes.int2bytes(len, header, 12);
// 写入 Header 到 Buffer
// write
buffer.writerIndex(savedWriteIndex);
buffer.writeBytes(header); // write header.
buffer.writerIndex(savedWriteIndex + HEADER_LENGTH + len);
}
/**
* 编码响应
*
* @param channel 通道
* @param buffer Buffer
* @param res 响应
* @throws IOException 当发生 IO 异常时
*/
protected void encodeResponse(Channel channel, ChannelBuffer buffer, Response res) throws IOException {
int savedWriteIndex = buffer.writerIndex();
try {
Serialization serialization = getSerialization(channel);
// `[0, 15]`:Magic Number
// header.
byte[] header = new byte[HEADER_LENGTH];
// set magic number.
Bytes.short2bytes(MAGIC, header);
// `[16, 20]`:Serialization 编号 && `[23]`:响应。
// set request and serialization flag.
header[2] = serialization.getContentTypeId();
// `[21]`:`event` 是否为事件。
if (res.isHeartbeat()) header[2] |= FLAG_EVENT;
// `[24 - 31]`:`status` 状态。
// set response status.
byte status = res.getStatus();
header[3] = status;
// `[32 - 95]`:`id` 编号,Long 型。
// set request id.
Bytes.long2bytes(res.getId(), header, 4);
// 编码 `Request.data` 到 Body ,并写入到 Buffer
buffer.writerIndex(savedWriteIndex + HEADER_LENGTH);
ChannelBufferOutputStream bos = new ChannelBufferOutputStream(buffer); // 序列化 Output
ObjectOutput out = serialization.serialize(channel.getUrl(), bos);
// encode response data or error message.
if (status == Response.OK) {
if (res.isHeartbeat()) {
encodeHeartbeatData(channel, out, res.getResult());
} else {
encodeResponseData(channel, out, res.getResult());
}
} else {
out.writeUTF(res.getErrorMessage());
}
// 释放资源
out.flushBuffer();
if (out instanceof Cleanable) {
((Cleanable) out).cleanup();
}
bos.flush();
bos.close();
// 检查 Body 长度,是否超过消息上限。
int len = bos.writtenBytes();
checkPayload(channel, len);
// `[96 - 127]`:Body 的**长度**。
Bytes.int2bytes(len, header, 12);
// 写入 Header 到 Buffer
// write
buffer.writerIndex(savedWriteIndex);
buffer.writeBytes(header); // write header.
buffer.writerIndex(savedWriteIndex + HEADER_LENGTH + len);
} catch (Throwable t) {
// clear buffer
// 重置写入进度,下面新的 Response 需要用到。
buffer.writerIndex(savedWriteIndex);
// send error message to Consumer, otherwise, Consumer will wait till timeout.
if (!res.isEvent() && res.getStatus() != Response.BAD_RESPONSE) {
Response r = new Response(res.getId(), res.getVersion());
r.setStatus(Response.BAD_RESPONSE);
// 过长异常
if (t instanceof ExceedPayloadLimitException) {
logger.warn(t.getMessage(), t);
try {
r.setErrorMessage(t.getMessage());
channel.send(r);
return;
} catch (RemotingException e) {
logger.warn("Failed to send bad_response info back: " + t.getMessage() + ", cause: " + e.getMessage(), e);
}
// 其他异常
} else {
// FIXME log error message in Codec and handle in caught() of IoHanndler?
logger.warn("Fail to encode response: " + res + ", send bad_response info instead, cause: " + t.getMessage(), t);
try {
r.setErrorMessage("Failed to send response: " + res + ", cause: " + StringUtils.toString(t));
channel.send(r);
return;
} catch (RemotingException e) {
logger.warn("Failed to send bad_response info back: " + res + ", cause: " + e.getMessage(), e);
}
}
}
// 抛出异常
// Rethrow exception
if (t instanceof IOException) {
throw (IOException) t;
} else if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else if (t instanceof Error) {
throw (Error) t;
} else {
throw new RuntimeException(t.getMessage(), t);
}
}
}
@Override
protected Object decodeData(ObjectInput in) throws IOException {
return decodeRequestData(in);
}
@Deprecated
protected Object decodeHeartbeatData(ObjectInput in) throws IOException {
try {
return in.readObject();
} catch (ClassNotFoundException e) {
throw new IOException(StringUtils.toString("Read object failed.", e));
}
}
protected Object decodeRequestData(ObjectInput in) throws IOException {
try {
return in.readObject();
} catch (ClassNotFoundException e) {
throw new IOException(StringUtils.toString("Read object failed.", e));
}
}
protected Object decodeResponseData(ObjectInput in) throws IOException {
try {
return in.readObject();
} catch (ClassNotFoundException e) {
throw new IOException(StringUtils.toString("Read object failed.", e));
}
}
@Override
protected void encodeData(ObjectOutput out, Object data) throws IOException {
encodeRequestData(out, data);
}
private void encodeEventData(ObjectOutput out, Object data) throws IOException {
out.writeObject(data);
}
@Deprecated
protected void encodeHeartbeatData(ObjectOutput out, Object data) throws IOException {
encodeEventData(out, data);
}
protected void encodeRequestData(ObjectOutput out, Object data) throws IOException {
out.writeObject(data);
}
protected void encodeResponseData(ObjectOutput out, Object data) throws IOException {
out.writeObject(data);
}
@Override
protected Object decodeData(Channel channel, ObjectInput in) throws IOException {
return decodeRequestData(channel, in);
}
protected Object decodeEventData(Channel channel, ObjectInput in) throws IOException {
try {
return in.readObject();
} catch (ClassNotFoundException e) {
throw new IOException(StringUtils.toString("Read object failed.", e));
}
}
@Deprecated
protected Object decodeHeartbeatData(Channel channel, ObjectInput in) throws IOException {
try {
return in.readObject();
} catch (ClassNotFoundException e) {
throw new IOException(StringUtils.toString("Read object failed.", e));
}
}
protected Object decodeRequestData(Channel channel, ObjectInput in) throws IOException {
return decodeRequestData(in);
}
protected Object decodeResponseData(Channel channel, ObjectInput in) throws IOException {
return decodeResponseData(in);
}
protected Object decodeResponseData(Channel channel, ObjectInput in, Object requestData) throws IOException {
return decodeResponseData(channel, in);
}
@Override
protected void encodeData(Channel channel, ObjectOutput out, Object data) throws IOException {
encodeRequestData(channel, out, data);
}
private void encodeEventData(Channel channel, ObjectOutput out, Object data) throws IOException {
encodeEventData(out, data);
}
@Deprecated
protected void encodeHeartbeatData(Channel channel, ObjectOutput out, Object data) throws IOException {
encodeHeartbeatData(out, data);
}
protected void encodeRequestData(Channel channel, ObjectOutput out, Object data) throws IOException {
encodeRequestData(out, data);
}
protected void encodeResponseData(Channel channel, ObjectOutput out, Object data) throws IOException {
encodeResponseData(out, data);
}
}
| 37.260194 | 133 | 0.579342 |
f6d8fe919d7cfa7c88ab4cb75231317a3f0e8313 | 2,224 | /*
* Tencent is pleased to support the open source community by making Tencent Shadow available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of
* the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.tencent.shadow.core.runtime;
import android.annotation.TargetApi;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
public class ShadowPendingIntent {
public static PendingIntent getService(Context context, int requestCode,
Intent intent, int flags) {
//todo #51 实现PendingIntent 中的 Service和广播
return PendingIntent.getService(context, requestCode, intent, flags);
}
public static PendingIntent getActivity(Context context, int requestCode,
Intent intent, int flags) {
return getActivity(context, requestCode, intent, flags, null);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static PendingIntent getActivity(Context context, int requestCode,
Intent intent, int flags, Bundle options) {
if (context instanceof ShadowContext && intent.getComponent() != null) {
ShadowContext shadowContext = (ShadowContext) context;
if(shadowContext.getPendingIntentConverter() != null){
intent = shadowContext.getPendingIntentConverter().convertPluginActivityIntent(intent);
}
context = shadowContext.getBaseContext();
}
return PendingIntent.getActivity(context, requestCode, intent, flags, options);
}
}
| 39.017544 | 103 | 0.688849 |
72bd04b9eef12522c5937110f4293a3313076590 | 3,056 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2020.02.04 at 03:24:13 PM EST
//
package com.github.edeandrea.xjcplugin.generated.schemadirwith2schemas;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for baseBuildFileBean complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="baseBuildFileBean">
* <complexContent>
* <extension base="{}baseBuildBean">
* <sequence>
* <element name="md5" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="sha1" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="type" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "baseBuildFileBean", propOrder = {
"md5",
"sha1",
"type"
})
@XmlSeeAlso({
Artifact.class,
Dependency.class
})
public abstract class BaseBuildFileBean
extends BaseBuildBean
implements Serializable
{
protected String md5;
protected String sha1;
protected String type;
/**
* Gets the value of the md5 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMd5() {
return md5;
}
/**
* Sets the value of the md5 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMd5(String value) {
this.md5 = value;
}
/**
* Gets the value of the sha1 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSha1() {
return sha1;
}
/**
* Sets the value of the sha1 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSha1(String value) {
this.sha1 = value;
}
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getType() {
return type;
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setType(String value) {
this.type = value;
}
}
| 23.328244 | 110 | 0.585079 |
1579948909630afca07c3913eccd82aba728b1c8 | 1,077 | package br.com.venzel.store.modules.payment.payment.use_cases.update_payment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import br.com.venzel.store.modules.payment.payment.dtos.PaymentDTO;
import br.com.venzel.store.modules.payment.payment.dtos.UpdatePaymentDTO;
@RestController
@RequestMapping("/payments")
public class UpdatePaymentController {
@Autowired
private UpdatePaymentService updatePaymentService;
@PutMapping("/{id}")
@ResponseStatus(HttpStatus.ACCEPTED)
public PaymentDTO handle(@RequestBody UpdatePaymentDTO dto, @PathVariable Long id) {
return updatePaymentService.execute(dto, id);
}
}
| 37.137931 | 88 | 0.816156 |
e57a6dda67dfbfdd80c907002701112613067890 | 1,404 | package com.p.model.repositories;
import java.util.Collection;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.p.model.Notificacion;
@Repository
public interface NotificacionRepository extends JpaRepository<Notificacion, Integer>{
@Query("select m from Notificacion m where m.propietario.id = ?1 order by fecha ASC ")
public Collection<Notificacion> getMensajesGrupo(Integer grupoId);
@Query("select m from Notificacion m where m.receptor.id = ?1 or m.emisor.id = ?1 and m.leido = false order by fecha ASC ")
public Collection<? extends Notificacion> findUltimasNoLeidas(Integer id);
@Query("select m from Notificacion m where m.receptor.id = ?1 or m.emisor.id = ?1 order by fecha ASC ")
public Page<Notificacion> findAll(Integer id,Pageable pageable);
@Query("select m from Notificacion m where m.leido = false and (m.receptor.id = ?1 or m.emisor.id = ?1) order by fecha DESC ")
public Collection<? extends Notificacion> findNoLeidas(Integer idUsuario);
@Query("select m from Notificacion m where m.leido = true and ( m.receptor.id = ?1 or m.emisor.id = ?1 ) order by fecha DESC ")
public Collection<? extends Notificacion> findLeidas(Integer idUsuario);
}
| 46.8 | 129 | 0.774217 |
22e7a6dccd253ef4e0b0f64b33bde82606915088 | 513 | package polybellum.widget;
import android.app.Activity;
import android.graphics.Canvas;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity implements GraphicsRenderer {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new GraphicsView(this).setRenderer(this));
}
@Override
public void onDraw(Canvas c) {
Log.v("test", ""+c.isHardwareAccelerated());
}
}
| 24.428571 | 72 | 0.725146 |
1e1f82dcd8b9948804c1f0efe8b8ff001aa71ec8 | 2,457 | /*
* Copyright 2015-2017 OpenCB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.opencb.opencga.app.cli.main.io;
import org.opencb.commons.datastore.core.DataResponse;
import org.opencb.commons.utils.ListUtils;
import java.io.PrintStream;
import java.util.List;
/**
* Created by pfurio on 28/07/16.
*/
public abstract class AbstractOutputWriter {
protected WriterConfiguration writerConfiguration;
protected PrintStream ps;
protected static final String ANSI_RESET = "\033[0m";
protected static final String ANSI_RED = "\033[31m";
protected static final String ANSI_YELLOW = "\033[33m";
public AbstractOutputWriter() {
this(new WriterConfiguration(), System.out);
}
public AbstractOutputWriter(WriterConfiguration writerConfiguration) {
this(writerConfiguration, System.out);
}
public AbstractOutputWriter(WriterConfiguration writerConfiguration, PrintStream ps) {
this.writerConfiguration = writerConfiguration;
this.ps = ps;
}
abstract public void print(DataResponse dataResponse);
/**
* Print errors or warnings and return true if any error was found.
*
* @param dataResponse dataResponse object
* @return true if the query gave an error.
*/
protected boolean checkErrors(DataResponse dataResponse) {
// Print warnings
if (ListUtils.isNotEmpty(dataResponse.getWarnings())) {
for (String warning : (List<String>) dataResponse.getWarnings()) {
System.err.println(ANSI_YELLOW + "WARNING: " + warning + ANSI_RESET);
}
}
boolean errors = false;
if (dataResponse.getError() != null) {
System.err.println(ANSI_RED + "ERROR " + dataResponse.getError().getCode() + ": " + dataResponse.getError().getDescription()
+ ANSI_RESET);
errors = true;
}
return errors;
}
}
| 31.909091 | 136 | 0.682133 |
78c78f29d2565f92d6c27e9a2fe48058cdd77c2a | 2,270 | package com.vission.mf.base.web.interceptors;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.vission.mf.base.enums.BaseConstants;
import com.vission.mf.base.model.bo.SessionInfo;
public class SessionInterceptor implements HandlerInterceptor {
private static final Logger logger = Logger
.getLogger(SessionInterceptor.class);
private List<String> excludeUrls;
public List<String> getExcludeUrls() {
return excludeUrls;
}
public void setExcludeUrls(List<String> excludeUrls) {
this.excludeUrls = excludeUrls;
}
/**
* 完成页面的render后调用
*/
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object object, Exception exception)
throws Exception {
}
/**
* 在调用controller具体方法后拦截
*/
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object object,
ModelAndView modelAndView) throws Exception {
}
/**
* 在调用controller具体方法前拦截
*/
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object object) throws Exception {
String requestUri = request.getRequestURI();
String contextPath = request.getContextPath();
String url = requestUri.substring(contextPath.length());
logger.debug(url);
if (excludeUrls.contains(url)) {
return true;
} else {
SessionInfo sessionInfo = (SessionInfo) request.getSession()
.getAttribute(BaseConstants.USER_SESSION_KEY);
if (sessionInfo != null && sessionInfo.getUser() != null) {
return true;
} else {
logger.debug("登录已超时");
// 如果是ajax请求响应头会有,x-requested-with;
if (request.getHeader("X-Requested-With") != null
&& request.getHeader("X-Requested-With")
.equalsIgnoreCase("XMLHttpRequest")){
request.setAttribute("message", "登录已超时,请重新登录!");
response.setHeader("sessionstatus", "timeout");// 在响应头设置session状态
return false;
} else {
request.setAttribute("message", "登录已超时,请重新登录!");
request.getRequestDispatcher("/login.jsp").forward(request, response);
return false;
}
}
}
}
}
| 27.349398 | 75 | 0.737445 |
f6aea7cfe9e4003c5248b710dedc130805efa6ac | 2,705 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pig.tools.parameters;
import org.apache.hadoop.util.Shell;
import org.apache.pig.impl.logicalLayer.FrontendException;
import org.junit.Assume;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Map;
import java.util.regex.Pattern;
public class TestPreprocessorContext {
@Test
public void testProcessShellCmd() throws ParameterSubstitutionException, FrontendException {
PreprocessorContext ctx = new PreprocessorContext(0);
String cmd = "echo hello";
ctx.processShellCmd("some_value", "`" + cmd + "`");
Map<String, String> paramVal = ctx.getParamVal();
assertEquals("hello", paramVal.get("some_value"));
}
@Test
public void testProcessShellCmdBigStderr() throws ParameterSubstitutionException, FrontendException {
// This test probably doesn't work on Windows, but should work elsewhere
Assume.assumeFalse(Shell.WINDOWS);
PreprocessorContext ctx = new PreprocessorContext(0);
String cmd = "bash -c 'i=0; while [ \"\\$i\" -lt 10000 ]; do echo long-stderr-output >&2; " +
"i=\\$((i+1)); done; echo hello'";
ctx.processShellCmd("some_value", "`" + cmd + "`");
Map<String, String> paramVal = ctx.getParamVal();
assertEquals("hello", paramVal.get("some_value"));
}
@Test
public void testFailingCommand() throws ParameterSubstitutionException, FrontendException {
try {
PreprocessorContext ctx = new PreprocessorContext(0);
String cmd = "exit 1";
ctx.processShellCmd("some_value", "`" + cmd + "`");
} catch (RuntimeException e) {
assertTrue(Pattern.compile("Error executing shell command:.*exit code.*")
.matcher(e.getMessage()).matches()
);
}
}
}
| 38.642857 | 105 | 0.683549 |
7ede0afc9b0d00f9a8ca622962d36c16ac5e2622 | 3,160 | /*
* Java
*
* Copyright 2018-2019 MicroEJ Corp. All rights reserved.
* For demonstration purpose only.
* MicroEJ Corp. PROPRIETARY. Use is subject to license terms.
*/
package com.microej.example.wifi.setup.rest;
import java.io.IOException;
import java.net.InetAddress;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.microej.example.wifi.setup.DefaultConfigurationManager;
import ej.ecom.network.IPConfiguration;
import ej.ecom.wifi.SecurityMode;
import ej.ecom.wifi.SoftAPConfiguration;
import ej.net.util.NetUtil;
/**
* Example of usage of a {@link RestSoftAPConnector}.
*/
public class Main {
private static final boolean USE_DHCP = false;
private static final String NET_MASK = "255.255.255.0"; //$NON-NLS-1$
private static final String IP_ADDR = "192.168.0.1"; //$NON-NLS-1$
private static final String SOFT_AP_SSID = "MicroEJ_SoftAP"; //$NON-NLS-1$
private static final String SOFT_AP_PASSPHRASE = "qwertyuiop"; //$NON-NLS-1$
private static final SecurityMode SOFT_AP_SECURITY = SecurityMode.WPA2;
private static final Logger LOGGER = Logger.getAnonymousLogger();
/**
* Entry Point.
*
* @param args
* not used.
*/
public static void main(String[] args) {
try {
start(new RestSoftAPConnector(), IP_ADDR, NET_MASK, USE_DHCP, SOFT_AP_SSID, SOFT_AP_PASSPHRASE,
SOFT_AP_SECURITY);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
}
}
/**
* Configures and starts the connector.
*
* @param connector
* the Connector
* @param ipAddr
* the IP adress.
* @param netMask
* the netmask.
* @param useDhcp
* Whether to use DHCP.
* @param softApSsid
* SSID to display.
* @param softApPassphrase
* Passphrase to use, <code>null</code> for none.
* @param softApSecurity
* SecurityMode to use.
*/
public static void start(RestSoftAPConnector connector, String ipAddr, String netMask, boolean useDhcp,
String softApSsid, String softApPassphrase, SecurityMode softApSecurity) {
SoftAPConfiguration softAPConfiguration = new SoftAPConfiguration();
softAPConfiguration.setSSID(softApSsid);
if (softApPassphrase != null) {
softAPConfiguration.setPassphrase(softApPassphrase);
}
softAPConfiguration.setSecurityMode(softApSecurity);
DefaultConfigurationManager configurationManager = new DefaultConfigurationManager(softAPConfiguration);
connector.setConfigurationManager(configurationManager);
try {
IPConfiguration iPConfiguration = new IPConfiguration();
iPConfiguration.setGateway(InetAddress.getByName(ipAddr));
iPConfiguration.setNetmask(InetAddress.getByName(netMask));
iPConfiguration.useDHCP(useDhcp);
connector.setIPConfiguration(null, iPConfiguration);
connector.start();
InetAddress hostAddress = NetUtil.getFirstHostAddress();
String ip = (hostAddress != null) ? hostAddress.getHostName() : "unknown"; //$NON-NLS-1$
LOGGER.info("Server started on " + ip + ':' + connector.getServerPort()); //$NON-NLS-1$
} catch (IOException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
}
}
}
| 33.263158 | 106 | 0.721519 |
794dcbf6ca4e639f9cd8a1d2c2064bf141210393 | 936 | package com.herman.gameserver.service.game;
import com.herman.gameserver.entity.game.Game;
import java.util.List;
/**
* 游戏信息缓存
* Created by herman on 2018/3/6.
*/
public interface IGameCache {
/**
* 通过code获取game信息
* @param code
* @return
*/
public Game getGameByCode(String code);
/**
* 通过code获取gameId
* @param code
* @return
*/
public Long getGameIdByCode(String code);
/**
* 通过gameId获取game信息
* @param gameId
* @return
*/
public Game getGameById(Long gameId);
/**
* 通过gameId获取code
* @param gameId
* @return
*/
public String getGameCodeById(Long gameId);
/**
* 获取所有游戏信息
*/
public List<Game> getGameList();
/**
*增加游戏信息
*/
public int add(Game game);
/**
* 更新游戏信息
*/
public int update(Game game);
}
| 15.864407 | 48 | 0.527778 |
c5303778cf1b9ca36c0ea2cf51118bfc46a3e867 | 1,943 | /*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.springframework.xd.tuple;
import org.springframework.core.convert.converter.Converter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
/**
* @author David Turanski
* @author Gunnar Hillert
*
*/
public class TupleToJsonStringConverter implements Converter<Tuple, String> {
private final ObjectMapper mapper = new ObjectMapper();
@Override
public String convert(Tuple source) {
ObjectNode root = toObjectNode(source);
String json = null;
try {
json = mapper.writeValueAsString(root);
}
catch (Exception e) {
throw new IllegalArgumentException("Tuple to string conversion failed", e);
}
return json;
}
private ObjectNode toObjectNode(Tuple source) {
ObjectNode root = mapper.createObjectNode();
root.put("id", source.getId().toString());
root.put("timestamp", source.getTimestamp());
for (int i = 0; i < source.size(); i++) {
Object value = source.getValues().get(i);
String name = source.getFieldNames().get(i);
if (value != null) {
if (value instanceof Tuple) {
root.putPOJO(name, toObjectNode((Tuple) value));
}
else if (!value.getClass().isPrimitive()) {
root.putPOJO(name, root.pojoNode(value));
}
else {
root.put(name, value.toString());
}
}
}
return root;
}
}
| 29.439394 | 118 | 0.711786 |
b7acdd33b6148cf662d0c5c02c9256c7b25e47de | 143 | package cn.pintia.zjo.practice.problem1951;
public class FileReaderTask implements Runnable {
@Override
public void run() {
}
}
| 14.3 | 49 | 0.706294 |
60d505c75ff01ffc9028c28e79fbe1a798f646f0 | 8,128 | package org.touchbit.buggy.testrail.listeners;
import org.touchbit.buggy.core.Buggy;
import org.touchbit.buggy.core.config.PrimaryConfig;
import org.touchbit.buggy.core.model.Details;
import org.touchbit.buggy.core.testng.listeners.BaseBuggyExecutionListener;
import org.testng.*;
import org.touchbit.buggy.testrail.BaseTestRailConfig;
import org.touchbit.buggy.testrail.RunsResultsStorage;
import org.touchbit.buggy.testrail.StatusMapper;
import org.touchbit.testrail4j.core.BasicAuth;
import org.touchbit.testrail4j.core.query.filter.GetCasesFilter;
import org.touchbit.testrail4j.jackson2.feign.client.TestRailClient;
import org.touchbit.testrail4j.jackson2.feign.client.TestRailClientBuilder;
import org.touchbit.testrail4j.jackson2.model.*;
import java.io.File;
import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.Collectors;
import static org.touchbit.buggy.core.test.TRProperty.RUN_ID;
/**
* Listener of the test methods to be followed for the subsequent translation of the results into the TestRail.
* <p>
* Created by Oleg Shaburov on 11.11.2018
* [email protected]
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public abstract class BaseTestRailListener<S> extends BaseBuggyExecutionListener
implements IExecutionListener, IInvokedMethodListener {
private TestRailClient client;
private static RunsResultsStorage runsResults = new RunsResultsStorage();
private StatusMapper<S> statusMapper;
private final PrimaryConfig config;
public BaseTestRailListener(StatusMapper<S> statusMapper) {
this.statusMapper = statusMapper;
this.config = Buggy.getPrimaryConfig();
BasicAuth interceptor = new BasicAuth(BaseTestRailConfig.getLogin(), BaseTestRailConfig.getPass());
client = TestRailClientBuilder.build(interceptor, BaseTestRailConfig.getTestRailHost());
}
protected void setTestRailClient(TestRailClient client) {
this.client = client;
}
@Override
public void onExecutionFinish() {
if (BaseTestRailConfig.isTestRailEnable()) {
long time = new Date().getTime();
// We get a list of run_id for which there are test results
for (Long rId : runsResults.getRunIDs()) {
try {
List<Long> caseIDsCheckList = new ArrayList<>(runsResults.getCaseIDsForRun(rId));
// Getting the list of cases for rId
List<Long> testRailCaseIds = getTestRailCasesByRunId(rId);
frameworkLog.info("List of case identifiers for run_id={} received.", rId);
ArrayList<TRResult> resultsForRun = new ArrayList<>();
// Be safe from remote test cases so as not to get the error when adding results.
runsResults.getResultsForRun(rId)
.stream()
.filter(result -> testRailCaseIds.contains(result.getCaseId()))
.forEach(r -> {
resultsForRun.add(r);
// Deletion occurs by reference to the Integer object.
caseIDsCheckList.remove(r.getCaseId());
});
frameworkLog.info("List of cases for run_id = {} filtered.", rId);
if (!resultsForRun.isEmpty()) {
frameworkLog.debug("List of cases for run_id={}:\n{}\n", rId, resultsForRun);
addResultsForCasesByRunId(rId, resultsForRun);
}
frameworkLog.info("Test results for run_id={} transferred.", rId);
if (!caseIDsCheckList.isEmpty()) {
caseIDsCheckList.forEach(cId -> {
Buggy.incrementBuggyErrors();
frameworkLog.error("In TestRail is absent or in the " +
"test the case with id={} is incorrectly specified", cId);
});
}
} catch (Exception e) {
Buggy.incrementBuggyErrors();
frameworkLog.error("Error getting data from TestRail.", e);
}
}
frameworkLog.info("Test results are translated into TestRail for {} ms.", new Date().getTime() - time);
}
}
protected void addResult(ITestResult result, Details details, S status, String comment) {
String msg = comment + addAttachments(result);
String strRunID = String.valueOf(result.getAttribute(RUN_ID.toString()));
if ("null".equals(String.valueOf(strRunID))) {
strRunID = String.valueOf(System.getProperty(RUN_ID.toString()));
}
try {
Long runID = Long.parseLong(strRunID);
for (Long caseId : details.id()) {
if (statusMapper.getId(status) > 0) {
StringJoiner defects = new StringJoiner(", ");
for (String bug : details.bug()) {
defects.add(bug);
}
TRResult trResult = new TRResult()
.withCaseId(caseId)
.withStatusId(statusMapper.getId(status))
.withComment(msg)
.withDefects(defects.toString());
runsResults.add(runID, trResult);
} else {
frameworkLog.warn("Result status {} is ignored. ID={}", status, statusMapper.getId(status));
}
}
} catch (Exception ignore) {
Buggy.incrementBuggyErrors();
frameworkLog.error("An incorrect value {} = {} was received", RUN_ID, strRunID);
}
}
protected String addAttachments(ITestResult testResult) {
Method method = testResult.getMethod().getConstructorOrMethod().getMethod();
Details trCase = method.getAnnotation(Details.class);
String caseIds = trCase != null ? Arrays.toString(trCase.id()) + "_" : "";
String prefix = caseIds + method.getName();
return "\n" + attachLogfile(prefix) + "\n" + attachScreenshots(prefix);
}
protected String attachLogfile(String prefix) {
String logfile = config.getArtifactsUrl() + "/tests/" + prefix + ".log";
return attachFile(logfile);
}
protected String attachScreenshots(String prefix) {
StringBuilder links = new StringBuilder();
File screenshotsDir = new File("target/screenshots");
File[] files = screenshotsDir.listFiles((dir, name) -> name.startsWith(prefix));
if (files != null) {
for (File f : files) {
links.append("!");
links.append(attachFile(f.getPath()));
}
}
return links.toString();
}
protected String attachFile(String filename) {
File sourceFile = new File(filename);
return "[" + sourceFile.getName() + "](" +
config.getArtifactsUrl() + "/tests/" + sourceFile.getName() + ")\n";
}
protected List<Long> getTestRailCasesByRunId(Long rId) {
TRRun run = client.getRun(rId);
GetCasesFilter getCasesQueryMap = new GetCasesFilter();
getCasesQueryMap.setSuiteId(run.getSuiteId());
return client.getCases(run.getProjectId(), getCasesQueryMap).stream()
.map(TRCase::getId)
.collect(Collectors.toList());
}
public void addResultsForCasesByRunId(Long rId, List<TRResult> resultList) {
TRResults results = new TRResults();
results.setResults(resultList);
client.addResultsForCases(results, rId);
}
public List<Long> getSuitesIds(Long pId) {
return client.getSuites(pId).stream()
.map(TRSuite::getId)
.collect(Collectors.toList());
}
public List<Long> getProjectsIds() {
return client.getProjects().stream()
.map(TRProject::getId)
.collect(Collectors.toList());
}
} | 44.415301 | 115 | 0.599532 |
62b61c6b24dc3963db9ebd1b94582e14baec3bb1 | 759 | package org.ovirt.engine.ui.uicommonweb.models.templates;
import org.ovirt.engine.core.common.businessentities.VmTemplate;
import org.ovirt.engine.core.common.queries.GetAllAuditLogsByVMTemplateNameParameters;
import org.ovirt.engine.core.common.queries.VdcQueryType;
public class UserPortalTemplateEventListModel extends TemplateEventListModel {
@Override
protected void refreshModel() {
if (getEntity() == null) {
return;
}
super.SyncSearch(VdcQueryType.GetAllAuditLogsByVMTemplateName,
new GetAllAuditLogsByVMTemplateNameParameters(getEntity().getname()));
}
@Override
protected void preSearchCalled(VmTemplate template) {
// no search string for the userportal
}
}
| 30.36 | 86 | 0.737813 |
71ef0208a96761001842db5eb9f77b97f0a893a4 | 5,342 | package us.ihmc.exampleSimulations.exampleContact;
import us.ihmc.euclid.Axis;
import us.ihmc.euclid.tuple3D.Point3D;
import us.ihmc.euclid.tuple3D.Vector3D;
import us.ihmc.graphicsDescription.Graphics3DObject;
import us.ihmc.graphicsDescription.appearance.YoAppearance;
import us.ihmc.graphicsDescription.yoGraphics.YoGraphicPosition;
import us.ihmc.graphicsDescription.yoGraphics.YoGraphicVector;
import us.ihmc.graphicsDescription.yoGraphics.YoGraphicsListRegistry;
import us.ihmc.simulationconstructionset.ExternalForcePoint;
import us.ihmc.simulationconstructionset.KinematicPoint;
import us.ihmc.simulationconstructionset.Link;
import us.ihmc.simulationconstructionset.PinJoint;
import us.ihmc.simulationconstructionset.Robot;
import us.ihmc.simulationconstructionset.SliderJoint;
public class PushStickRobot extends Robot
{
private static final long serialVersionUID = 6953401273041281579L;
private static final double MASS = 2.0;
private static final double Ixx = 5.0;
private static final double Iyy = 5.0;
private static final double Izz = 5.0;
private static final double LENGTH = 1.0;
private static final double RADIUS = 0.01;
private final SliderJoint xJoint, yJoint, zJoint;
private final PinJoint yawJoint, pitchJoint;
private final SliderJoint pushJoint;
private final KinematicPoint kp_PushStickBackEnd;
private final ExternalForcePoint ef_PushStickTip;
public PushStickRobot()
{
super("PushStickRobot");
this.setGravity(0.0);
xJoint = new SliderJoint("pushStickX", new Vector3D(), this, Axis.X);
Link xLink = new Link("xLink");
xJoint.setLink(xLink);
yJoint = new SliderJoint("pushStickY", new Vector3D(), this, Axis.Y);
Link yLink = new Link("yLink");
yJoint.setLink(yLink);
zJoint = new SliderJoint("pushStickZ", new Vector3D(), this, Axis.Z);
Link zLink = new Link("zLink");
zLink.setMass(100.0);
zLink.setMomentOfInertia(10.0, 10.0, 10.0);
Graphics3DObject zLinkLinkGraphics = new Graphics3DObject();
zLinkLinkGraphics.addCube(0.1, 0.1, 0.1, YoAppearance.Gray());
zLink.setLinkGraphics(zLinkLinkGraphics);
zJoint.setLink(zLink);
yawJoint = new PinJoint("pushStickYaw", new Vector3D(), this, Axis.Z);
Link yawLink = new Link("yawLink");
yawJoint.setLink(yawLink);
pitchJoint = new PinJoint("pushStickPitch", new Vector3D(), this, Axis.Y);
Link pitchLink = new Link("pitchLink");
pitchJoint.setLink(pitchLink);
pushJoint = new SliderJoint("pushStickPush", new Vector3D(), this, Axis.X);
Link link = new Link("pushStick");
link.setMass(MASS);
link.setComOffset(new Vector3D(-LENGTH/2.0, 0.0, 0.0));
link.setMomentOfInertia(Ixx, Iyy, Izz);
Graphics3DObject linkGraphics = new Graphics3DObject();
linkGraphics.rotate(Math.PI/2.0, Axis.Y);
linkGraphics.translate(0.0, 0.0, -LENGTH);
linkGraphics.addCylinder(LENGTH, RADIUS);
link.setLinkGraphics(linkGraphics);
// link.addCoordinateSystemToCOM(0.2);
pushJoint.setLink(link);
ef_PushStickTip = new ExternalForcePoint("ef_PushStickTip", new Vector3D(), this);
pushJoint.addExternalForcePoint(ef_PushStickTip);
kp_PushStickBackEnd = new ExternalForcePoint("kp_PushStickBackEnd", new Vector3D(-LENGTH/2.0, 0.0, 0.0), this);
pushJoint.addKinematicPoint(kp_PushStickBackEnd);
YoGraphicsListRegistry yoGraphicsListRegistry = new YoGraphicsListRegistry();
YoGraphicPosition pushStickForcePosition = new YoGraphicPosition("pushStickForce", ef_PushStickTip.getYoPosition(), 0.01, YoAppearance.Red());
YoGraphicVector pushStickForceVector = new YoGraphicVector("forceToPushOnSphere", ef_PushStickTip.getYoPosition(), ef_PushStickTip.getYoForce(), 0.1, YoAppearance.Red());
YoGraphicPosition pushStickBackEndGraphicPosition = new YoGraphicPosition("pushStickBackEnd", kp_PushStickBackEnd.getYoPosition(), 0.01, YoAppearance.Black());
yoGraphicsListRegistry.registerYoGraphic("PushStickRobot", pushStickForcePosition);
yoGraphicsListRegistry.registerYoGraphic("PushStickRobot", pushStickForceVector);
yoGraphicsListRegistry.registerYoGraphic("PushStickRobot", pushStickBackEndGraphicPosition);
this.addYoGraphicsListRegistry(yoGraphicsListRegistry);
addRootJoint(xJoint);
xJoint.addJoint(yJoint);
yJoint.addJoint(zJoint);
zJoint.addJoint(yawJoint);
yawJoint.addJoint(pitchJoint);
pitchJoint.addJoint(pushJoint);
xJoint.setInitialState(-1.0, 0.0);
yJoint.setInitialState(0.0, 0.0);
zJoint.setInitialState(0.3, 0.0);
yawJoint.setInitialState(0.0, 0.0);
pitchJoint.setInitialState(0.0, 0.0);
pushJoint.setInitialState(0.0, 0.0);
}
Point3D tempPoint3d = new Point3D();
public void getPushStickUnitDirectionInWorld(Vector3D directionInWorldToPack)
{
ef_PushStickTip.getPosition(directionInWorldToPack);
kp_PushStickBackEnd.getPosition(tempPoint3d);
directionInWorldToPack.sub(tempPoint3d);
directionInWorldToPack.normalize();
}
public ExternalForcePoint getPushStickTipPoint()
{
return ef_PushStickTip;
}
}
| 39.865672 | 176 | 0.725571 |
3d23335ecf6fb9181492d1f6626b7bd910e19ddd | 3,982 | package me.neznamy.tab.shared.features.layout;
import java.util.*;
import java.util.stream.Collectors;
import me.neznamy.tab.api.TabFeature;
import me.neznamy.tab.api.TabPlayer;
import me.neznamy.tab.api.chat.IChatBaseComponent;
import me.neznamy.tab.api.protocol.PacketPlayOutPlayerInfo;
import me.neznamy.tab.api.protocol.PacketPlayOutPlayerInfo.EnumGamemode;
import me.neznamy.tab.api.protocol.PacketPlayOutPlayerInfo.EnumPlayerInfoAction;
import me.neznamy.tab.api.protocol.PacketPlayOutPlayerInfo.PlayerInfoData;
import me.neznamy.tab.shared.TAB;
import me.neznamy.tab.shared.TabConstants;
import me.neznamy.tab.shared.placeholders.conditions.Condition;
public class Layout extends TabFeature {
private final String name;
private final LayoutManager manager;
private final Condition displayCondition;
private final Map<Integer, FixedSlot> fixedSlots;
private final List<Integer> emptySlots;
private final List<ParentGroup> groups;
private final Set<TabPlayer> viewers = Collections.newSetFromMap(new WeakHashMap<>());
public Layout(String name, LayoutManager manager, Condition displayCondition, Map<Integer, FixedSlot> fixedSlots, List<Integer> emptySlots, List<ParentGroup> groups) {
super(manager.getFeatureName(), "Updating player groups");
this.name = name;
this.manager = manager;
this.displayCondition = displayCondition;
this.fixedSlots = fixedSlots;
this.emptySlots = emptySlots;
this.groups = groups;
}
public void sendTo(TabPlayer p) {
if (viewers.contains(p)) return;
viewers.add(p);
List<PlayerInfoData> list = new ArrayList<>();
groups.forEach(g -> list.addAll(g.getSlots(p)));
for (FixedSlot slot : fixedSlots.values()) {
p.setProperty(slot, slot.getPropertyName(), slot.getText());
list.add(new PlayerInfoData("", slot.getId(), slot.getSkin(), slot.getPing(), EnumGamemode.CREATIVE, IChatBaseComponent.optimizedComponent(p.getProperty(slot.getPropertyName()).updateAndGet())));
}
for (int slot : emptySlots) {
list.add(new PlayerInfoData("", manager.getUUID(slot), manager.getSkinManager().getDefaultSkin(), manager.getEmptySlotPing(), EnumGamemode.CREATIVE, new IChatBaseComponent("")));
}
if (p.getVersion().getMinorVersion() < 8 || p.isBedrockPlayer()) return;
p.sendCustomPacket(new PacketPlayOutPlayerInfo(EnumPlayerInfoAction.ADD_PLAYER, list), this);
}
public void removeFrom(TabPlayer p) {
if (!viewers.contains(p)) return;
viewers.remove(p);
List<PlayerInfoData> list = new ArrayList<>();
for (UUID id : manager.getUuids().values()) {
list.add(new PlayerInfoData(id));
}
if (p.getVersion().getMinorVersion() < 8 || p.isBedrockPlayer()) return;
p.sendCustomPacket(new PacketPlayOutPlayerInfo(EnumPlayerInfoAction.REMOVE_PLAYER, list), this);
}
public boolean isConditionMet(TabPlayer p) {
return displayCondition == null || displayCondition.isMet(p);
}
public List<ParentGroup> getGroups(){
return groups;
}
public void tick() {
List<TabPlayer> players = manager.getSortedPlayers().keySet().stream().filter(player -> !player.isVanished()).collect(Collectors.toList());
for (ParentGroup group : groups) {
group.tick(players);
}
}
@Override
public void refresh(TabPlayer p, boolean force) {
tick();
}
public Set<TabPlayer> getViewers() {
return viewers;
}
public boolean containsViewer(TabPlayer viewer) {
return viewers.contains(viewer);
}
public LayoutManager getManager() {
return manager;
}
public PlayerSlot getSlot(TabPlayer p) {
for (ParentGroup group : groups) {
if (group.getPlayers().containsKey(p)) {
return group.getPlayers().get(p);
}
}
return null;
}
public String getName() {
return name;
}
@Override
public void onServerChange(TabPlayer player, String from, String to) {
if (TAB.getInstance().getFeatureManager().isFeatureEnabled(TabConstants.Feature.PIPELINE_INJECTION)) return;
//velocity clearing TabList on server switch
if (viewers.remove(player)){
sendTo(player);
}
}
} | 34.034188 | 198 | 0.750879 |
8f568115c6471374351aade4c9f0d67818ff5951 | 769 | package com.go2group.uservoice.bean;
public class Comment {
private String id;
private String feedbackId;
private String forumId;
private String text;
private User creator;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public User getCreator() {
return creator;
}
public void setCreator(User creator) {
this.creator = creator;
}
public String getFeedbackId() {
return feedbackId;
}
public void setFeedbackId(String feedbackId) {
this.feedbackId = feedbackId;
}
public String getForumId() {
return forumId;
}
public void setForumId(String forumId) {
this.forumId = forumId;
}
}
| 14.788462 | 47 | 0.69961 |
ed4b55be8edcf6886b063aec3bc676e0ec9907f9 | 12,678 | /*
* Copyright (C) 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.cloud.teleport.v2.clients;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.google.api.services.dataplex.v1.CloudDataplex;
import com.google.api.services.dataplex.v1.CloudDataplex.Projects.Locations.Lakes.Zones;
import com.google.api.services.dataplex.v1.CloudDataplex.Projects.Locations.Lakes.Zones.Assets;
import com.google.api.services.dataplex.v1.CloudDataplex.Projects.Locations.Lakes.Zones.Entities;
import com.google.api.services.dataplex.v1.CloudDataplex.Projects.Locations.Lakes.Zones.Entities.Partitions;
import com.google.api.services.dataplex.v1.model.GoogleCloudDataplexV1Asset;
import com.google.api.services.dataplex.v1.model.GoogleCloudDataplexV1AssetDiscoverySpec;
import com.google.api.services.dataplex.v1.model.GoogleCloudDataplexV1Entity;
import com.google.api.services.dataplex.v1.model.GoogleCloudDataplexV1ListEntitiesResponse;
import com.google.api.services.dataplex.v1.model.GoogleCloudDataplexV1ListPartitionsResponse;
import com.google.api.services.dataplex.v1.model.GoogleCloudDataplexV1Partition;
import com.google.api.services.dataplex.v1.model.GoogleCloudDataplexV1Schema;
import com.google.api.services.dataplex.v1.model.GoogleCloudDataplexV1StorageFormat;
import com.google.api.services.dataplex.v1.model.GoogleCloudDataplexV1Zone;
import com.google.api.services.dataplex.v1.model.GoogleCloudDataplexV1ZoneDiscoverySpec;
import com.google.cloud.teleport.v2.clients.DataplexClient.CreateBehavior;
import com.google.cloud.teleport.v2.values.EntityMetadata;
import com.google.cloud.teleport.v2.values.EntityMetadata.EntityType;
import com.google.cloud.teleport.v2.values.EntityMetadata.StorageSystem;
import com.google.cloud.teleport.v2.values.GetEntityRequestEntityView;
import com.google.common.collect.ImmutableList;
import java.io.IOException;
import org.junit.Test;
import org.mockito.Answers;
/**
* Test cases for the {@link DefaultDataplexClient} class. Inspired by {@link CsvConvertersTest}.
*/
public class DefaultDataplexClientTest {
private static final String ZONE_NAME =
"projects/project_1/locations/location_1/lakes/lake_1/zones/zone_1";
private static final String ASSET_NAME1 = ZONE_NAME + "/asset/asset_1";
private static final String ASSET_NAME2 = ZONE_NAME + "/asset/asset_2";
private static final String PAGE_TOKEN = "token_1";
// Metadata for use in tests where it doens't matter what the values are
private static final EntityMetadata UNUSED_METADATA =
EntityMetadata.builder()
.setDataPath("invalid")
.setSchema(new GoogleCloudDataplexV1Schema())
.setStorageFormat(new GoogleCloudDataplexV1StorageFormat())
.setEntityType(EntityType.TYPE_UNSPECIFIED)
.setStorageSystem(StorageSystem.STORAGE_SYSTEM_UNSPECIFIED)
.setAssetName("invalid")
.setId("invalid")
.build();
private static final GoogleCloudDataplexV1AssetDiscoverySpec ENABLED_ASSET_DISCOVERY_SPEC =
new GoogleCloudDataplexV1AssetDiscoverySpec().setEnabled(true);
private static final GoogleCloudDataplexV1AssetDiscoverySpec DISABLED_ASSET_DISCOVERY_SPEC =
new GoogleCloudDataplexV1AssetDiscoverySpec().setEnabled(false);
private static final GoogleCloudDataplexV1ZoneDiscoverySpec ENABLED_ZONE_DISCOVERY_SPEC =
new GoogleCloudDataplexV1ZoneDiscoverySpec().setEnabled(true);
private static final GoogleCloudDataplexV1ZoneDiscoverySpec DISABLED_ZONE_DISCOVERY_SPEC =
new GoogleCloudDataplexV1ZoneDiscoverySpec().setEnabled(false);
@Test
public void testGetGetCloudStorageEntitiesByAssetName() throws IOException {
CloudDataplex cloudDataplexClient = mock(CloudDataplex.class, Answers.RETURNS_DEEP_STUBS);
Entities.List entitiesListRequest = mock(Entities.List.class, Answers.RETURNS_DEEP_STUBS);
when(cloudDataplexClient.projects().locations().lakes().zones().entities().list(ZONE_NAME))
.thenReturn(entitiesListRequest);
GoogleCloudDataplexV1Entity entity1 =
new GoogleCloudDataplexV1Entity()
.setName("entity1")
.setAsset(ASSET_NAME1)
.setSystem(StorageSystem.CLOUD_STORAGE.name());
GoogleCloudDataplexV1Entity entity2 =
new GoogleCloudDataplexV1Entity()
.setName("entity2")
.setAsset(ASSET_NAME1)
.setSystem("BIGQUERY"); // storage mismatch
GoogleCloudDataplexV1Entity entity3 =
new GoogleCloudDataplexV1Entity()
.setName("entity3")
.setAsset(ASSET_NAME1)
.setSystem(StorageSystem.CLOUD_STORAGE.name());
GoogleCloudDataplexV1Entity entity4 =
new GoogleCloudDataplexV1Entity()
.setName("entity4")
.setAsset(ASSET_NAME2)
.setSystem(StorageSystem.CLOUD_STORAGE.name()); // schema mismatch
GoogleCloudDataplexV1Entity entity5 =
new GoogleCloudDataplexV1Entity()
.setName("entity5")
.setAsset(ASSET_NAME1)
.setSystem(StorageSystem.CLOUD_STORAGE.name());
GoogleCloudDataplexV1ListEntitiesResponse response1 =
new GoogleCloudDataplexV1ListEntitiesResponse();
response1.setEntities(ImmutableList.of(entity1, entity2, entity3));
response1.setNextPageToken(PAGE_TOKEN);
GoogleCloudDataplexV1ListEntitiesResponse response2 =
new GoogleCloudDataplexV1ListEntitiesResponse();
response2.setEntities(ImmutableList.of(entity4, entity5));
when(entitiesListRequest.setPageToken(any())).thenReturn(entitiesListRequest);
when(entitiesListRequest.execute()).thenReturn(response1, response2);
when(cloudDataplexClient
.projects()
.locations()
.lakes()
.zones()
.entities()
.get("entity1")
.setView(GetEntityRequestEntityView.FULL.name())
.execute())
.thenReturn(entity1);
when(cloudDataplexClient
.projects()
.locations()
.lakes()
.zones()
.entities()
.get("entity3")
.setView(GetEntityRequestEntityView.FULL.name())
.execute())
.thenReturn(entity3);
when(cloudDataplexClient
.projects()
.locations()
.lakes()
.zones()
.entities()
.get("entity5")
.setView(GetEntityRequestEntityView.FULL.name())
.execute())
.thenReturn(entity5);
assertEquals(
ImmutableList.of(entity1, entity3, entity5),
DefaultDataplexClient.withClient(cloudDataplexClient).getCloudStorageEntities(ASSET_NAME1));
}
@Test
public void testGetEntitiesByEntityNames() throws IOException {
CloudDataplex cloudDataplexClient = mock(CloudDataplex.class, Answers.RETURNS_DEEP_STUBS);
GoogleCloudDataplexV1Entity entity1 =
new GoogleCloudDataplexV1Entity()
.setName("entity1")
.setAsset(ASSET_NAME1)
.setSystem(StorageSystem.CLOUD_STORAGE.name());
GoogleCloudDataplexV1Entity entity2 =
new GoogleCloudDataplexV1Entity()
.setName("entity2")
.setAsset(ASSET_NAME1)
.setSystem(StorageSystem.CLOUD_STORAGE.name());
GoogleCloudDataplexV1Entity entity3 =
new GoogleCloudDataplexV1Entity()
.setName("entity3")
.setAsset(ASSET_NAME1)
.setSystem(StorageSystem.CLOUD_STORAGE.name());
when(cloudDataplexClient
.projects()
.locations()
.lakes()
.zones()
.entities()
.get("entity1")
.setView(GetEntityRequestEntityView.FULL.name())
.execute())
.thenReturn(entity1);
when(cloudDataplexClient
.projects()
.locations()
.lakes()
.zones()
.entities()
.get("entity2")
.setView(GetEntityRequestEntityView.FULL.name())
.execute())
.thenReturn(entity2);
when(cloudDataplexClient
.projects()
.locations()
.lakes()
.zones()
.entities()
.get("entity3")
.setView(GetEntityRequestEntityView.FULL.name())
.execute())
.thenReturn(entity3);
assertEquals(
ImmutableList.of(entity1, entity2, entity3),
DefaultDataplexClient.withClient(cloudDataplexClient)
.getEntities(ImmutableList.of("entity1", "entity2", "entity3")));
}
@Test
public void testGetPartitionsByEntityName() throws IOException {
CloudDataplex cloudDataplexClient = mock(CloudDataplex.class, Answers.RETURNS_DEEP_STUBS);
Partitions partitions = mock(Partitions.class, Answers.RETURNS_DEEP_STUBS);
when(cloudDataplexClient.projects().locations().lakes().zones().entities().partitions())
.thenReturn(partitions);
GoogleCloudDataplexV1Partition partition1 =
new GoogleCloudDataplexV1Partition().setName("partition1");
GoogleCloudDataplexV1Partition partition2 =
new GoogleCloudDataplexV1Partition().setName("partition2");
GoogleCloudDataplexV1Partition partition3 =
new GoogleCloudDataplexV1Partition().setName("partition2");
GoogleCloudDataplexV1ListPartitionsResponse response1 =
new GoogleCloudDataplexV1ListPartitionsResponse()
.setPartitions(ImmutableList.of(partition1, partition2))
.setNextPageToken(PAGE_TOKEN);
GoogleCloudDataplexV1ListPartitionsResponse response2 =
new GoogleCloudDataplexV1ListPartitionsResponse()
.setPartitions(ImmutableList.of(partition3));
when(partitions.list("entity0").execute()).thenReturn(response1);
when(partitions.list("entity0").setPageToken(eq(PAGE_TOKEN)).execute()).thenReturn(response2);
assertEquals(
ImmutableList.of(partition1, partition2, partition3),
DefaultDataplexClient.withClient(cloudDataplexClient).getPartitions("entity0"));
}
@Test
public void testCreateEntitiesWhenDiscoveryEnabled() throws IOException {
CloudDataplex dataplex = mock(CloudDataplex.class, Answers.RETURNS_DEEP_STUBS);
Zones zones = getZones(dataplex);
Assets assets = getAssets(dataplex);
// Don't care about the order they're checked, so set up for two calls.
when(assets.get(any()).execute())
.thenReturn(createAsset(ENABLED_ASSET_DISCOVERY_SPEC))
.thenReturn(createAsset(DISABLED_ASSET_DISCOVERY_SPEC));
when(zones.get(any()).execute())
.thenReturn(createZone(ENABLED_ZONE_DISCOVERY_SPEC))
.thenReturn(createZone(DISABLED_ZONE_DISCOVERY_SPEC));
DataplexClient client = DefaultDataplexClient.withClient(dataplex);
client.createMetadata(
ASSET_NAME1, ImmutableList.of(UNUSED_METADATA), CreateBehavior.UPDATE_IF_EXISTS);
client.createMetadata(
ASSET_NAME1, ImmutableList.of(UNUSED_METADATA), CreateBehavior.UPDATE_IF_EXISTS);
verify(assets, atLeastOnce()).get(ASSET_NAME1);
verify(zones, atLeastOnce()).get(ZONE_NAME);
verify(zones, never()).entities(); // Enough to know nothing was done with partitions
}
private static Zones getZones(CloudDataplex dataplex) {
return dataplex.projects().locations().lakes().zones();
}
private static Assets getAssets(CloudDataplex dataplex) {
return dataplex.projects().locations().lakes().zones().assets();
}
private static GoogleCloudDataplexV1Zone createZone(
GoogleCloudDataplexV1ZoneDiscoverySpec discoverySpec) {
return new GoogleCloudDataplexV1Zone().setDiscoverySpec(discoverySpec);
}
private static GoogleCloudDataplexV1Asset createAsset(
GoogleCloudDataplexV1AssetDiscoverySpec discoverySpec) {
return new GoogleCloudDataplexV1Asset().setDiscoverySpec(discoverySpec);
}
}
| 43.417808 | 108 | 0.722906 |
60893ac717a47ead0be704062f7d88cdc6400358 | 3,506 | package com.joaopimentel.esperancastats.Service.statistics;
import com.joaopimentel.esperancastats.DTO.statistics.TransitionDTO;
import com.joaopimentel.esperancastats.Entity.statistics.Statistic;
import com.joaopimentel.esperancastats.Entity.statistics.Transition;
import com.joaopimentel.esperancastats.Repository.statistics.StatisticRepository;
import com.joaopimentel.esperancastats.Repository.statistics.TransitionMapping;
import com.joaopimentel.esperancastats.Repository.statistics.TransitionRepository;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class TransitionService {
private final TransitionRepository transitionRepository;
private final TransitionMapping transitionMapping;
private final StatisticRepository statisticRepository;
public TransitionService(TransitionRepository transitionRepository, TransitionMapping transitionMapping, StatisticRepository statisticRepository) {
this.transitionRepository = transitionRepository;
this.transitionMapping = transitionMapping;
this.statisticRepository = statisticRepository;
}
public TransitionDTO getTransitionById(Long id) {
Optional<Transition> transition = transitionRepository.findById(id);
return transition.map(transitionMapping::toDto).orElse(null);
}
public List<TransitionDTO> getAllTransitions() {
return transitionMapping.toDto(transitionRepository.findAll());
}
public TransitionDTO createTransition(Long statisticId, TransitionDTO dto) {
Optional<Statistic> statistic = statisticRepository.findById(statisticId);
if(statistic.isPresent()) {
Transition transition = new Transition();
transition.setStatistic(statistic.get());
transition.setActionOutcome(dto.getActionOutcome());
transition.setTypeOfTransition(dto.getTypeOfTransition());
transition.setFieldThirds(dto.getFieldThirds());
transition.setFieldCorridors(dto.getFieldCorridors());
transition.setTimeStat(dto.getTimeStat());
statistic.get().addTransition(transition);
statisticRepository.save(statistic.get());
transitionRepository.save(transition);
return dto;
}
return null;
}
public TransitionDTO editTransition(Long id, TransitionDTO dto) {
Optional<Transition> transition = transitionRepository.findById(id);
if(transition.isPresent()) {
transition.get().setTimeStat(dto.getTimeStat());
transition.get().setFieldThirds(dto.getFieldThirds());
transition.get().setFieldCorridors(dto.getFieldCorridors());
transition.get().setTypeOfTransition(dto.getTypeOfTransition());
transition.get().setActionOutcome(dto.getActionOutcome());
transitionRepository.save(transition.get());
return transitionMapping.toDto(transition.get());
}
return null;
}
public String deleteTransitionById(Long id) {
Optional<Transition> transition = transitionRepository.findById(id);
if(transition.isPresent()) {
transitionRepository.delete(transition.get());
return "Transition deleted with success!";
} else
return null;
}
public String deleteAllTransitions() {
transitionRepository.deleteAll();
return "All transitions deleted!";
}
}
| 38.108696 | 151 | 0.722191 |
420d43d97d7352fbb9296df3834fb09bbdacab11 | 733 | package com.ymrs.spirit.ffx.util;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
/**
* 加密工具类
*
* @author dante
*
*/
public final class EncryptUtils {
private static final BCryptPasswordEncoder bcryptEncoder = new BCryptPasswordEncoder();
private EncryptUtils() {
throw new IllegalAccessError("EncryptUtils 工具类,不能实例化!");
}
/**
* 加密方法
*
* @param rawPassword
* @return
*/
public static String encrypt(String rawPassword) {
return bcryptEncoder.encode(rawPassword);
}
/**
* 密文比对
*
* @param rawPassword
* @param password
* @return
*/
public static boolean match(String rawPassword, String password) {
return bcryptEncoder.matches(rawPassword, password);
}
}
| 18.325 | 88 | 0.709413 |
e3dff199fda81e309aac8653eb41b9ba4dcbc09f | 3,820 | /*
* Copyright (C) 2010-2014 Hamburg Sud and the contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.aludratest.service.gui.web.selenium.selenium2;
import org.aludratest.config.ConfigProperties;
import org.aludratest.config.ConfigProperty;
import org.aludratest.service.Implementation;
import org.aludratest.service.gui.web.AludraWebGUI;
import org.aludratest.service.gui.web.WebGUICondition;
import org.aludratest.service.gui.web.WebGUIInteraction;
import org.aludratest.service.gui.web.WebGUIVerification;
import org.aludratest.service.gui.web.selenium.AbstractSeleniumService;
import org.aludratest.service.gui.web.selenium.SeleniumResourceService;
/**
* Implements the interface {@link AludraWebGUI} using Selenium 2 functionality
* to access the web GUI.
* @author Volker Bergmann
*/
@Implementation({ AludraWebGUI.class })
@ConfigProperties({
@ConfigProperty(name = "use.local.proxy", type = boolean.class, description = "If true, a local HTTP proxy will be used to allow adding custom HTTP headers. If set to false, no proxy will be used, but the method addCustomHttpHeaderCommand will have no effect.", defaultValue = "true"),
@ConfigProperty(name = "proxy.port.min", type = int.class, description = "The lowest port number to use for the authenticating proxy.", defaultValue = "19600"),
@ConfigProperty(name = "driver", type = String.class, description = "The Selenium 2 driver name. Have a look at the org.aludratest.service.gui.web.selenium.selenium2.Drivers enumeration for potential values", defaultValue = "FIREFOX"),
@ConfigProperty(name = "use.remotedriver", type = boolean.class, description = "If true, use Selenium Remote Driver (talk to Selenium RC), otherwise, directly use driver class.", defaultValue = "false") })
public class AludraSelenium2 extends AbstractSeleniumService implements AludraWebGUI {
private Selenium2Interaction interaction;
private Selenium2Verification verification;
private Selenium2Condition condition;
/** The {@link Selenium2Wrapper} to perform the actual invocations. */
private Selenium2Wrapper seleniumWrapper;
/** Used by the framework to configure the service */
@Override
public void initService() {
seleniumWrapper = new Selenium2Wrapper(configuration, getSeleniumResourceService());
interaction = new Selenium2Interaction(seleniumWrapper);
verification = new Selenium2Verification(seleniumWrapper);
condition = new Selenium2Condition(seleniumWrapper);
}
private SeleniumResourceService getSeleniumResourceService() {
return aludraServiceContext.newComponentInstance(SeleniumResourceService.class);
}
@Override
public String getDescription() {
return "Using Selenium host: " + seleniumWrapper.getUsedSeleniumHost() + ", AUT: " + configuration.getUrlOfAut();
}
@Override
public WebGUIInteraction perform() {
return this.interaction;
}
/** @see AludraWebGUI#verify() */
@Override
public WebGUIVerification verify() {
return this.verification;
}
/** @see AludraWebGUI#check() */
@Override
public WebGUICondition check() {
return this.condition;
}
@Override
public void close() {
seleniumWrapper.tearDown();
}
}
| 42.921348 | 289 | 0.744503 |
6dc7bba529bd4c90f63bdbf1486cc1f9d9f42dc6 | 446 | package com.so.w.config;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author zhangfeng542
* @date 5/14/19
*/
@Configuration
public class SSOConfig {
@Bean
public DefaultWebSecurityManager securityManager(){
DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
return manager;
}
}
| 19.391304 | 70 | 0.789238 |
f7cbe80f60ae1f7fdf59ad52d3d7a65972539a8c | 1,343 | package one.jodi.action;
import com.google.inject.Inject;
import one.jodi.base.bootstrap.ActionRunner;
import one.jodi.base.bootstrap.RunConfig;
import one.jodi.base.bootstrap.UsageException;
import one.jodi.etl.service.loadplan.LoadPlanExportService;
import java.io.File;
public class LoadPlanPrintActionRunner implements ActionRunner {
private final LoadPlanExportService loadPlanImportService;
@Inject
public LoadPlanPrintActionRunner(final LoadPlanExportService loadPlanImportService) {
this.loadPlanImportService = loadPlanImportService;
}
@Override
public void run(RunConfig config) {
validateRunConfig(config);
final boolean useDefaultNames = true;
this.loadPlanImportService.printLoadPlans(useDefaultNames);
}
@Override
public void validateRunConfig(RunConfig config) throws UsageException {
if (config.getPropertyFile() == null || !new File(config.getPropertyFile()).exists()) {
String msg = "Properties file should be specified and exist.";
throw new UsageException(msg);
}
if (config.getMetadataDirectory() == null || !new File(config.getMetadataDirectory()).exists()) {
String msg = "Metadata directory should be specified and exist.";
throw new UsageException(msg);
}
}
} | 35.342105 | 105 | 0.718541 |
bc81fa6e1d1cadc7a6cda65041ea4a5ffc6dc305 | 1,554 | package com.ex.es.test;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
/**
* @author yangzl 2021.05.07
* @version 1.00.00
* @Description:
* @Copyright: Copyright (c) 2017 HYKJ All Rights Reserved
* @Company: 福建互医科技有限公司
* @history:
*/
public class ES_04_Doc_Update {
public static void main(String[] args) throws IOException {
// 创建客户端对象
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
UpdateRequest request = new UpdateRequest();
request.index("user").id("1001");
User user = new User();
user.setAge(30);
user.setName("test");
user.setSex("同性");
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(user);
request.index("user").id("1001");//针对user的索引,id为1001的数据进行修改
request.doc(XContentType.JSON, "sex", "女");
UpdateResponse update = esClient.update(request, RequestOptions.DEFAULT);
System.out.println(update.getResult());
}
}
| 35.318182 | 81 | 0.714929 |
fee373ef510d621d6587796b2ac6adcad8f26d78 | 486 | package com.kimzing.restful.service;
import com.kimzing.utils.result.ApiResult;
import com.kimzing.restful.domain.dto.UserDTO;
import com.kimzing.restful.domain.dto.UserQueryDTO;
/**
* 用户模拟服务.
*
* @author KimZing - [email protected]
* @since 2019/12/28 16:16
*/
public interface UserService {
ApiResult save(UserDTO userDTO);
ApiResult remove(Long id);
ApiResult update(UserDTO userDTO);
ApiResult find(Long id);
ApiResult list(UserQueryDTO userQuery);
}
| 18.692308 | 51 | 0.730453 |
e86c0e6560cba965b0dfca261facbe98e638d0f6 | 1,077 | package nz.rafikn.movierates.akka;
import akka.actor.AbstractActor;
import akka.actor.ActorSystem;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import akka.japi.pf.ReceiveBuilder;
import nz.rafikn.movierates.model.Movie;
import nz.rafikn.movierates.model.RawSearch;
import nz.rafikn.movierates.services.UploadService;
import java.util.*;
/**
* Created by rafik on 3/07/16.
*/
public class UploadActor extends AbstractActor {
private final LoggingAdapter logger = Logging.getLogger(context().system(), this);
public UploadActor(UploadService uploader, ActorSystem system) {
receive(ReceiveBuilder.
match(Map.Entry.class, result -> {
if (result.getKey() instanceof Movie && result.getValue() instanceof RawSearch) {
uploader.process((Movie)result.getKey(), (RawSearch)result.getValue());
}
system.stop(this.self());
}).
matchAny(o -> logger.info("received unknown message")).build()
);
}
}
| 28.342105 | 101 | 0.653668 |
46b45dd4ef8a008f7677499f820d7dd0fb852257 | 1,602 | package br.com.caelum.vraptor.http;
import static br.com.caelum.vraptor.config.BasicConfiguration.ENCODING;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.UnsupportedEncodingException;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import br.com.caelum.vraptor.VRaptorException;
public class WebXmlEncodingHandlerTest {
private @Mock ServletContext context;
private @Mock HttpServletRequest request;
private @Mock HttpServletResponse response;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void shouldSetEncodingToUTF8() throws Exception {
when(context.getInitParameter(ENCODING)).thenReturn("UTF-8");
new WebXmlEncodingHandler("UTF-8").setEncoding(request, response);
verify(request).setCharacterEncoding("UTF-8");
verify(response).setCharacterEncoding("UTF-8");
}
@Test(expected=VRaptorException.class)
public void shouldThrowExceptionWhenAnUnsupportedEncodingExceptionOccurs() throws Exception {
doThrow(new UnsupportedEncodingException()).when(request).setCharacterEncoding(anyString());
new WebXmlEncodingHandler("UTF-8").setEncoding(request, response);
}
}
| 32.04 | 100 | 0.754057 |
86a6f4ed1e228799a6c292046c205e23c35d5f39 | 33,990 | package com.dji.sdk.sample.demo.flightcontroller;
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;
import androidx.annotation.NonNull;
import java.io.File;
import java.util.*;
import com.chaquo.python.Kwarg;
import com.chaquo.python.PyObject;
import com.chaquo.python.android.AndroidPlatform;
import com.chaquo.python.Python;
import com.dji.sdk.sample.R;
import com.dji.sdk.sample.internal.OnScreenJoystickListener;
import com.dji.sdk.sample.internal.controller.DJISampleApplication;
import com.dji.sdk.sample.internal.utils.CallbackHandlers;
import com.dji.sdk.sample.internal.utils.DialogUtils;
import com.dji.sdk.sample.internal.utils.DownloadHandler;
import com.dji.sdk.sample.internal.utils.ModuleVerificationUtil;
import com.dji.sdk.sample.internal.utils.OnScreenJoystick;
import com.dji.sdk.sample.internal.utils.ToastUtils;
import com.dji.sdk.sample.internal.view.PresentableView;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import androidx.annotation.Nullable;
import dji.common.camera.SettingsDefinitions;
import dji.common.error.DJIError;
import dji.common.gimbal.CapabilityKey;
import dji.common.gimbal.RotationMode;
import dji.common.util.DJIParamMinMaxCapability;
import dji.common.flightcontroller.LocationCoordinate3D;
import dji.common.flightcontroller.simulator.InitializationData;
import dji.common.flightcontroller.simulator.SimulatorState;
import dji.common.flightcontroller.virtualstick.FlightControlData;
import dji.common.flightcontroller.virtualstick.FlightCoordinateSystem;
import dji.common.flightcontroller.virtualstick.RollPitchControlMode;
import dji.common.flightcontroller.virtualstick.VerticalControlMode;
import dji.common.flightcontroller.virtualstick.YawControlMode;
import dji.common.gimbal.Rotation;
import dji.common.model.LocationCoordinate2D;
import dji.common.flightcontroller.FlightControllerState;
import dji.common.util.CommonCallbacks;
import dji.sdk.base.BaseProduct;
import dji.sdk.camera.Camera;
import dji.sdk.camera.PlaybackManager;
import dji.sdk.gimbal.Gimbal;
import dji.sdk.media.DownloadListener;
import dji.sdk.products.Aircraft;
import dji.sdk.media.MediaFile;
import dji.sdk.media.MediaManager;
import com.dji.sdk.sample.demo.flightcontroller.GPSRotateAngle;
import org.jetbrains.annotations.NotNull;
import dji.keysdk.FlightControllerKey;
import dji.keysdk.KeyManager;
import dji.sdk.flightcontroller.FlightController;
import dji.sdk.flightcontroller.Simulator;
import dji.sdk.sdkmanager.DJISDKManager;
//TODO: Refactor needed
/**
* Class for virtual stick.
*/
public class VirtualStickView extends RelativeLayout
implements View.OnClickListener, CompoundButton.OnCheckedChangeListener, PresentableView {
private boolean yawControlModeFlag = true;
private boolean rollPitchControlModeFlag = true;
private boolean verticalControlModeFlag = true;
private boolean horizontalCoordinateFlag = true;
private Gimbal gimbal = null;
private int currentGimbalId = 0;
private MediaFile media;
private MediaManager mediaManager ;
private int DownloadFlag = 0;
private Button btnEnableVirtualStick;
private Button btnDisableVirtualStick;
private Button btnHorizontalCoordinate;
private Button btnSetYawControlMode;
private Button btnSetVerticalControlMode;
private Button btnSetRollPitchControlMode;
private ToggleButton btnSimulator;
private Button btnTakeOff;
private Button btnSetZero;
private Button btnLeftUp;
private Button btnRoll;
private Button btnPitch;
private Button btnYaw;
private Button btnGetGps;
private Button btnCalAngle;
private Button btnCamera;
private Button btnGimbalReset;
private Button btnSDcardFile;
private Button btnPython;
private TextView textView;
private TextView timerView;
private OnScreenJoystick screenJoystickRight;
private OnScreenJoystick screenJoystickLeft;
private Timer sendVirtualStickDataTimer;
private SendVirtualStickDataTask sendVirtualStickDataTask;
//private Timer checkLocationArrivedTimer;
private CheckLocationArrivedTask checkLocationArrivedTask;
private float ArrivedFlag = 0;
private float pitch;
private float roll;
private float yaw;
private float throttle;
private double lat1;
private double lat2 = 22.0016;
private double lon1;
private double lon2 = 113.0015;
private FlightControllerKey isSimulatorActived;
public VirtualStickView(Context context) {
super(context);
init(context);
}
@NonNull
@Override
public String getHint() {
return this.getClass().getSimpleName() + ".java";
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
setUpListeners();
}
@Override
protected void onDetachedFromWindow() {
if (null != sendVirtualStickDataTimer) {
if (sendVirtualStickDataTask != null) {
sendVirtualStickDataTask.cancel();
}
sendVirtualStickDataTimer.cancel();
sendVirtualStickDataTimer.purge();
sendVirtualStickDataTimer = null;
sendVirtualStickDataTask = null;
}
tearDownListeners();
super.onDetachedFromWindow();
}
private void init(Context context) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Service.LAYOUT_INFLATER_SERVICE);
layoutInflater.inflate(R.layout.view_virtual_stick, this, true);
initAllKeys();
initUI();
}
private void PythonCode(){
Python py = Python.getInstance();
PyObject obj1 = py.getModule("hello").callAttr("add", 2,3);
// 将Python返回值换为Java中的Integer类型
Integer sum = obj1.toJava(Integer.class);
ToastUtils.setResultToToast("sum = "+sum);
}
private void initAllKeys() {
isSimulatorActived = FlightControllerKey.create(FlightControllerKey.IS_SIMULATOR_ACTIVE);
}
private void initUI() {
btnEnableVirtualStick = (Button) findViewById(R.id.btn_enable_virtual_stick);
btnDisableVirtualStick = (Button) findViewById(R.id.btn_disable_virtual_stick);
btnHorizontalCoordinate = (Button) findViewById(R.id.btn_horizontal_coordinate);
btnSetYawControlMode = (Button) findViewById(R.id.btn_yaw_control_mode);
btnSetVerticalControlMode = (Button) findViewById(R.id.btn_vertical_control_mode);
btnSetRollPitchControlMode = (Button) findViewById(R.id.btn_roll_pitch_control_mode);
btnTakeOff = (Button) findViewById(R.id.btn_take_off);
btnSetZero = (Button) findViewById(R.id.btn_set_zero);
btnLeftUp = (Button) findViewById(R.id.btn_left_up);
btnRoll = (Button) findViewById(R.id.btn_roll);
btnPitch = (Button) findViewById(R.id.btn_pitch);
btnYaw = (Button) findViewById(R.id.btn_yaw);
btnGetGps = (Button) findViewById(R.id.btn_get_gps);
btnCalAngle = (Button) findViewById(R.id.btn_cal_angle);
btnCamera = (Button) findViewById(R.id.btn_camera_shoot);
btnGimbalReset = (Button) findViewById(R.id.btn_gimbal_reset);
btnSDcardFile = (Button) findViewById(R.id.btn_get_sdfile);
btnSimulator = (ToggleButton) findViewById(R.id.btn_start_simulator);
btnPython = (Button) findViewById(R.id.btn_python);
textView = (TextView) findViewById(R.id.textview_simulator);
timerView = (TextView) findViewById(R.id.textview_timertask);
screenJoystickRight = (OnScreenJoystick) findViewById(R.id.directionJoystickRight);
screenJoystickLeft = (OnScreenJoystick) findViewById(R.id.directionJoystickLeft);
btnEnableVirtualStick.setOnClickListener(this);
btnDisableVirtualStick.setOnClickListener(this);
btnHorizontalCoordinate.setOnClickListener(this);
btnSetYawControlMode.setOnClickListener(this);
btnSetVerticalControlMode.setOnClickListener(this);
btnSetRollPitchControlMode.setOnClickListener(this);
btnTakeOff.setOnClickListener(this);
btnSetZero.setOnClickListener(this);
btnLeftUp.setOnClickListener(this);
btnRoll.setOnClickListener(this);
btnPitch.setOnClickListener(this);
btnYaw.setOnClickListener(this);
btnGetGps.setOnClickListener(this);
btnCalAngle.setOnClickListener(this);
btnCamera.setOnClickListener(this);
btnGimbalReset.setOnClickListener(this);
btnSDcardFile.setOnClickListener(this);
btnPython.setOnClickListener(this);
btnSimulator.setOnCheckedChangeListener(VirtualStickView.this);
Boolean isSimulatorOn = (Boolean) KeyManager.getInstance().getValue(isSimulatorActived);
if (isSimulatorOn != null && isSimulatorOn) {
btnSimulator.setChecked(true);
textView.setText("Simulator is On.");
}
}
private void setUpListeners() {
Simulator simulator = ModuleVerificationUtil.getSimulator();
if (simulator != null) {
simulator.setStateCallback(new SimulatorState.Callback() {
@Override
public void onUpdate(@NonNull final SimulatorState simulatorState) {
ToastUtils.setResultToText(textView,
"Yaw : "
+ simulatorState.getYaw()
+ ","
+ "X : "
+ simulatorState.getPositionX()
+ "\n"
+ "Y : "
+ simulatorState.getPositionY()
+ ","
+ "Z : "
+ simulatorState.getPositionZ());
}
});
} else {
ToastUtils.setResultToToast("Disconnected!");
}
}
private void tearDownListeners() {
Simulator simulator = ModuleVerificationUtil.getSimulator();
if (simulator != null) {
simulator.setStateCallback(null);
}
screenJoystickLeft.setJoystickListener(null);
screenJoystickRight.setJoystickListener(null);
}
private Gimbal getGimbalInstance() {
if (gimbal == null) {
initGimbal();
}
return gimbal;
}
private void initGimbal() {
if (DJISDKManager.getInstance() != null) {
BaseProduct product = DJISDKManager.getInstance().getProduct();
if (product != null) {
if (product instanceof Aircraft) {
gimbal = ((Aircraft) product).getGimbals().get(currentGimbalId);
} else {
gimbal = product.getGimbal();
}
}
}
}
private void sendRotateGimbalCommand(Rotation rotation) {
Gimbal gimbal = getGimbalInstance();
if (gimbal == null) {
return;
}
gimbal.rotate(rotation, new CallbackHandlers.CallbackToastHandler());
}
private boolean isModuleAvailable() {
return (null != DJISampleApplication.getProductInstance()) && (null != DJISampleApplication.getProductInstance()
.getCamera());
}
@Override
public void onClick(View v) {
FlightController flightController = ModuleVerificationUtil.getFlightController();
if (flightController == null) {
return;
}
switch (v.getId()) {
case R.id.btn_enable_virtual_stick:
flightController.setVirtualStickModeEnabled(true, new CommonCallbacks.CompletionCallback() {
@Override
public void onResult(DJIError djiError) {
DialogUtils.showDialogBasedOnError(getContext(), djiError);
}
});
DJISampleApplication.getAircraftInstance().getFlightController().
setRollPitchCoordinateSystem(FlightCoordinateSystem.GROUND);//roll body
DJISampleApplication.getAircraftInstance().getFlightController().
setVerticalControlMode(VerticalControlMode.POSITION);// vertical
DJISampleApplication.getAircraftInstance().getFlightController().
setYawControlMode(YawControlMode.ANGULAR_VELOCITY);//angular_velocity
DJISampleApplication.getAircraftInstance().getFlightController().
setRollPitchControlMode(RollPitchControlMode.VELOCITY);//angle
ToastUtils.setResultToToast(flightController.getRollPitchControlMode().name());
//定时器用来定时,200ms发送一次数据
if (null == sendVirtualStickDataTimer) {
sendVirtualStickDataTask = new SendVirtualStickDataTask();
sendVirtualStickDataTimer = new Timer();
sendVirtualStickDataTimer.schedule(sendVirtualStickDataTask, 100, 200);
}
break;
case R.id.btn_disable_virtual_stick:
flightController.setVirtualStickModeEnabled(false, new CommonCallbacks.CompletionCallback() {
@Override
public void onResult(DJIError djiError) {
DialogUtils.showDialogBasedOnError(getContext(), djiError);
}
});
break;
case R.id.btn_roll_pitch_control_mode:
if (rollPitchControlModeFlag) {
flightController.setRollPitchControlMode(RollPitchControlMode.ANGLE);
rollPitchControlModeFlag = false;
} else {
flightController.setRollPitchControlMode(RollPitchControlMode.VELOCITY);
rollPitchControlModeFlag = true;
}
try {
ToastUtils.setResultToToast(flightController.getRollPitchControlMode().name());
} catch (Exception ex) {
}
break;
case R.id.btn_yaw_control_mode:
if (yawControlModeFlag) {
flightController.setYawControlMode(YawControlMode.ANGLE);
yawControlModeFlag = false;
} else {
flightController.setYawControlMode(YawControlMode.ANGULAR_VELOCITY);
yawControlModeFlag = true;
}
try {
ToastUtils.setResultToToast(flightController.getYawControlMode().name());
} catch (Exception ex) {
}
break;
case R.id.btn_vertical_control_mode:
if (verticalControlModeFlag) {
flightController.setVerticalControlMode(VerticalControlMode.POSITION);
verticalControlModeFlag = false;
} else {
flightController.setVerticalControlMode(VerticalControlMode.VELOCITY);
verticalControlModeFlag = true;
}
try {
ToastUtils.setResultToToast(flightController.getVerticalControlMode().name());
} catch (Exception ex) {
}
break;
case R.id.btn_horizontal_coordinate:
if (horizontalCoordinateFlag) {
flightController.setRollPitchCoordinateSystem(FlightCoordinateSystem.GROUND);
horizontalCoordinateFlag = false;
} else {
flightController.setRollPitchCoordinateSystem(FlightCoordinateSystem.BODY);
horizontalCoordinateFlag = true;
}
try {
ToastUtils.setResultToToast(flightController.getRollPitchCoordinateSystem().name());
} catch (Exception ex) {
}
break;
case R.id.btn_take_off:
flightController.startTakeoff(new CommonCallbacks.CompletionCallback() {
@Override
public void onResult(DJIError djiError) {
DialogUtils.showDialogBasedOnError(getContext(), djiError);
}
});
break;
case R.id.btn_set_zero:
yaw = 0;
pitch = 0;
roll = 0;
throttle = 1f;
break;
case R.id.btn_left_up:
yaw = 0;
pitch = 0.02f;
roll = 0.02f;
throttle = 3f;
break;
case R.id.btn_roll:
yaw = 0;
pitch = 0;
roll = 0.5f;
throttle = 1.5f;
break;
case R.id.btn_pitch:
yaw = 0;
pitch = 0.5f;
roll = 0;
throttle = 1.5f;
break;
case R.id.btn_yaw:
yaw = 3f;
pitch = 0;
roll = 0;
throttle = 1.5f;
break;
case R.id.btn_get_gps:
double latitude = 22;
double longtitude = 113;
float altitude =1.5f;
FlightControllerState GPSLocation = new FlightControllerState();
GPSLocation = flightController.getState();
LocationCoordinate3D locationCoordinate3D = new LocationCoordinate3D(latitude,longtitude,altitude);
locationCoordinate3D = GPSLocation.getAircraftLocation();
lat1 = locationCoordinate3D.getLatitude();
lon1 = locationCoordinate3D.getLongitude();
//ToastUtils.setResultToToast( locationCoordinate3D.toString() );
double setGPSData[] = {lat2,lon2};//zhezhi
double reqGPSData_vice[] = {lat1,lon1};//yuan
double[] CalResult = GPSRotateAngle.CalAngle(reqGPSData_vice, setGPSData);
double Distance2Point = CalResult[0];
double RotateAngle = CalResult[1];
if(ArrivedFlag == 1){
checkLocationArrivedTask.cancel();
timerView.setText("arrived");
}
ToastUtils.setResultToToast( "location=" + locationCoordinate3D.toString() + "\n"
+ "ANGEL=" + RotateAngle + "\n"
+ " DISTANCE=" + Distance2Point + "\n"
+ " roll=" + roll + "\n"
+ " pitch=" + pitch
);
break;
case R.id.btn_cal_angle:
if (null == checkLocationArrivedTask) {
checkLocationArrivedTask = new CheckLocationArrivedTask();
sendVirtualStickDataTimer.schedule(checkLocationArrivedTask,100,500);
}
break;
case R.id.btn_camera_shoot:
Gimbal gimbal = getGimbalInstance();
if (gimbal == null) {
return;
}
Object key = CapabilityKey.ADJUST_PITCH;
Number minValue = ((DJIParamMinMaxCapability) (gimbal.getCapabilities().get(key))).getMin();
Rotation.Builder builder = new Rotation.Builder().mode(RotationMode.ABSOLUTE_ANGLE).time(2);
builder.pitch(minValue.floatValue());
sendRotateGimbalCommand(builder.build());
if (isModuleAvailable()) {
if (ModuleVerificationUtil.isMavicAir2()){
DJISampleApplication.getProductInstance()
.getCamera()
.setFlatMode(SettingsDefinitions.FlatCameraMode.PHOTO_SINGLE, new CommonCallbacks.CompletionCallback() {
@Override
public void onResult(DJIError djiError) {
if (djiError == null){
ToastUtils.setResultToToast("success set photo single");
}else {
ToastUtils.setResultToToast("faliure set photo single");
}
}
});
/*DJISampleApplication.getProductInstance()
.getCamera()
.setFlatMode(SettingsDefinitions.FlatCameraMode.PHOTO_SINGLE, djiError -> ToastUtils.setResultToToast("SetCameraMode to shootPhoto"));*/
}
DJISampleApplication.getProductInstance()
.getCamera()
.startShootPhoto(new CommonCallbacks.CompletionCallback() {
@Override
public void onResult(DJIError djiError) {
if (null == djiError) {
ToastUtils.setResultToToast("success shooting");
//ToastUtils.setResultToToast(getContext().getString(R.string.success));
} else {
ToastUtils.setResultToToast(djiError.getDescription());
}
}
});
}
break;
case R.id.btn_gimbal_reset:
Gimbal gimbal1 = getGimbalInstance();
if (gimbal1 != null) {
gimbal1.reset(null);
} else {
ToastUtils.setResultToToast("The gimbal is disconnected.");
}
break;
case R.id.btn_get_sdfile:
ToastUtils.setResultToToast("btnsdfile");
if (ModuleVerificationUtil.isCameraModuleAvailable()) {
if (ModuleVerificationUtil.isMediaManagerAvailable()) {
Camera myCamera = DJISampleApplication.getProductInstance().getCamera();
if (mediaManager == null) {
mediaManager = myCamera.getMediaManager();//DJISampleApplication.getProductInstance().getCamera().getMediaManager();
fetchMediaList();
ToastUtils.setResultToToast("media get success");
}
if (myCamera.isFlatCameraModeSupported()){
ToastUtils.setResultToToast("flat supported");
myCamera.setFlatMode(SettingsDefinitions.FlatCameraMode.PHOTO_SINGLE, new CommonCallbacks.CompletionCallback() {
@Override
public void onResult(DJIError djiError) {
ToastUtils.setResultToToast("setflatmode_success");
}
});
myCamera.enterPlayback(new CommonCallbacks.CompletionCallback() {
@Override
public void onResult(DJIError djiError) {
if (djiError == null){
ToastUtils.setResultToToast("entermode_success_playback");
myCamera.getMode(new CommonCallbacks.CompletionCallbackWith<SettingsDefinitions.CameraMode>() {
@Override
public void onSuccess(SettingsDefinitions.CameraMode cameraMode) {
if (cameraMode == SettingsDefinitions.CameraMode.PLAYBACK){
fetchMediaList();
if (media == null){
fetchMediaList();
}else if (media != null){
ToastUtils.setResultToToast("media is not null"+media.getFileName());
File destDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/");
//media.fetchFileData(destDir,"djiphoto",new DownloadHandler<>());
media.fetchFileData(destDir, "testName_djiphoto", new DownloadListener<String>() {
@Override
public void onStart() {
}
@Override
public void onRateUpdate(long l, long l1, long l2) {
}
@Override
public void onRealtimeDataUpdate(byte[] bytes, long l, boolean b) {
}
@Override
public void onProgress(long l, long l1) {
}
@Override
public void onSuccess(String s) {
ToastUtils.setResultToToast("download success");
}
@Override
public void onFailure(DJIError djiError) {
ToastUtils.setResultToToast("download fail" + djiError);
}
});
}
}
}
@Override
public void onFailure(DJIError djiError) {
}
});
}
else {
ToastUtils.setResultToToast("setmodeerror"+djiError);
}
}
});
//fetchMediaList();
}else {
ToastUtils.setResultToToast("playback not supported");
}
} else {
ToastUtils.setResultToToast("not supported");
}
}
break;
case R.id.btn_python:
PythonCode();
break;
default:
break;
}
}
private void fetchMediaList() {
ToastUtils.setResultToToast("fetchmeadialist");
if (ModuleVerificationUtil.isMediaManagerAvailable()) {
if (mediaManager != null) {
mediaManager.refreshFileListOfStorageLocation(SettingsDefinitions.StorageLocation.SDCARD, new CommonCallbacks.CompletionCallback() {
@Override
public void onResult(DJIError djiError) {
String str;
if (null == djiError) {
List<MediaFile> djiMedias = mediaManager.getSDCardFileListSnapshot();
if (null != djiMedias) {
if (!djiMedias.isEmpty()) {
media = djiMedias.get(1);
str = media.getFileName();
if (media == null){
ToastUtils.setResultToToast("media is null:" + (media == null));
}
else {
ToastUtils.setResultToToast("media is not null, get file:" + str + media.getFileSize());
}
//ToastUtils.setResultToToast("get file: " + str);
} else {
str = "No Media in SD Card";
ToastUtils.setResultToToast(str);
}
}
} else {
ToastUtils.setResultToToast("refresh fail" + djiError);
}
}
});
}
}
}
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (compoundButton == btnSimulator) {
onClickSimulator(b);
}
}
private void onClickSimulator(boolean isChecked) {
Simulator simulator = ModuleVerificationUtil.getSimulator();
if (simulator == null) {
return;
}
if (isChecked) {
textView.setVisibility(VISIBLE);
simulator.start(InitializationData.createInstance(new LocationCoordinate2D(23, 113), 10, 10),
new CommonCallbacks.CompletionCallback() {
@Override
public void onResult(DJIError djiError) {
}
});
} else {
textView.setVisibility(INVISIBLE);
simulator.stop(new CommonCallbacks.CompletionCallback() {
@Override
public void onResult(DJIError djiError) {
}
});
}
}
@Override
public int getDescription() {
return R.string.flight_controller_listview_virtual_stick;
}
private class SendVirtualStickDataTask extends TimerTask {
@Override
public void run() {
if (ModuleVerificationUtil.isFlightControllerAvailable()) {
DJISampleApplication.getAircraftInstance()
.getFlightController()
.sendVirtualStickFlightControlData(new FlightControlData(pitch,
roll,
yaw,
throttle),
new CommonCallbacks.CompletionCallback() {
@Override
public void onResult(DJIError djiError) {
}
});
}
}
}
private class CheckLocationArrivedTask extends TimerTask {
double PresentLatitude ;
double PresentLongtitude;
float PresentAltitude;
@Override
public void run() {
FlightController flightController2 = ModuleVerificationUtil.getFlightController();
FlightControllerState GPSLocation = new FlightControllerState();
GPSLocation = flightController2.getState();
LocationCoordinate3D locationCoordinate3D2 = new LocationCoordinate3D(PresentLatitude, PresentLongtitude, PresentAltitude);
locationCoordinate3D2 = GPSLocation.getAircraftLocation();
PresentLatitude = locationCoordinate3D2.getLatitude();
PresentLongtitude = locationCoordinate3D2.getLongitude();
double[] PresentLocation = {PresentLatitude,PresentLongtitude};
double[] SetGPSData = {lat2,lon2};
double[] CalRes = GPSRotateAngle.CalAngle(PresentLocation, SetGPSData);
double[] FlyData = GPSRotateAngle.CalControlData(CalRes);
if(CalRes[0]<50){
GPSRotateAngle.BaseVer = 10.0;
if (CalRes[0]<30){
GPSRotateAngle.BaseVer = 8.0;
if (CalRes[0]<10){
GPSRotateAngle.BaseVer = 5.0;
if (CalRes[0]<5){
GPSRotateAngle.BaseVer = 2.0;
if (CalRes[0]<2){
GPSRotateAngle.BaseVer = 0.1;
}
}
}
}
}
if(CalRes[0]<0.2){
yaw = 0;
pitch = 0;
roll = 0;
throttle = 1.5f;
//timerView.setText("arrived");
ArrivedFlag = 1;
//checkLocationArrivedTask.cancel();
}
else {
yaw = 0;
pitch = (float)FlyData[1];
roll = (float)FlyData[0];
throttle = 1.5f;
}
}
}
}
| 41.050725 | 168 | 0.532068 |
813e00adb4c736b5a2e9a903ce804cc9c4108da6 | 1,223 | package WayofTime.alchemicalWizardry.common.block;
import WayofTime.alchemicalWizardry.AlchemicalWizardry;
import WayofTime.alchemicalWizardry.common.tileEntity.TESchematicSaver;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
public class BlockSchematicSaver extends BlockContainer
{
public BlockSchematicSaver()
{
super(Material.rock);
setHardness(2.0F);
setResistance(5.0F);
// setCreativeTab(AlchemicalWizardry.tabBloodMagic);
this.setBlockName("schematicSaver");
}
@Override
public TileEntity createNewTileEntity(World var1, int var2)
{
return new TESchematicSaver();
}
@Override
public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float what, float these, float are)
{
if (world.isRemote)
{
return false;
}
TESchematicSaver tileEntity = (TESchematicSaver) world.getTileEntity(x, y, z);
tileEntity.rightClickBlock(player, side);
return false;
}
}
| 28.44186 | 136 | 0.713818 |
09e79f89c5a4cb478ed468c7d673a97b481bed7d | 356 | package com.gioov.structural.decorator;
/**
* @author godcheese [[email protected]]
* @date 2020-02-25
*/
public class ManDecoratorA extends Decorator {
@Override
public void eat() {
super.eat();
reEat();
System.out.println("ManDecoratorA 类");
}
private void reEat() {
System.out.println("再吃一顿饭");
}
}
| 17.8 | 46 | 0.620787 |
4a4614d9c738fe63034bab8e271d4685d67f293f | 2,362 | package net.newsmth.dirac.data;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
public class TextOrImage implements Parcelable {
public static final int TYPE_TEXT = 0;
public static final int TYPE_IMAGE = 1;
public static final int TYPE_AUDIO = 2; // 音频附件
public static final Parcelable.Creator<TextOrImage> CREATOR = new Parcelable.Creator<TextOrImage>() {
@Override
public TextOrImage createFromParcel(Parcel in) {
return new TextOrImage(in);
}
@Override
public TextOrImage[] newArray(int size) {
return new TextOrImage[size];
}
};
public final int type;
public CharSequence data;
public boolean parsed;
public String url;
public Author artist; // 音频作者,实际是上传者
public TextOrImage(int type, CharSequence data) {
this.type = type;
this.data = data;
}
private TextOrImage(Parcel in) {
type = in.readInt();
data = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
parsed = in.readInt() > 0;
url = in.readString();
artist = in.readParcelable(getClass().getClassLoader());
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(type);
TextUtils.writeToParcel(data, dest, flags);
dest.writeInt(parsed ? 1 : 0);
dest.writeString(url);
dest.writeParcelable(artist, flags);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TextOrImage that = (TextOrImage) o;
if (type != that.type) return false;
if (data != null ? !data.equals(that.data) : that.data != null) return false;
if (url != null ? !url.equals(that.url) : that.url != null) return false;
return artist != null ? artist.equals(that.artist) : that.artist == null;
}
@Override
public int hashCode() {
int result = type;
result = 31 * result + (data != null ? data.hashCode() : 0);
result = 31 * result + (url != null ? url.hashCode() : 0);
result = 31 * result + (artist != null ? artist.hashCode() : 0);
return result;
}
} | 31.078947 | 105 | 0.609229 |
2581c28bf5586ea7103f5e8795f6e750311aa44f | 1,388 | /**
* Copyright (c) 2013, Cloudera, Inc. All Rights Reserved.
*
* Cloudera, Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for
* the specific language governing permissions and limitations under the
* License.
*/
package com.cloudera.science.ml.hcatalog;
import org.apache.hcatalog.data.schema.HCatFieldSchema;
import org.apache.hcatalog.data.schema.HCatSchema;
import com.cloudera.science.ml.core.records.FieldSpec;
import com.cloudera.science.ml.core.records.RecordSpec;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
public class HCatalogSpec extends RecordSpec {
private final HCatSchema schema;
public HCatalogSpec(final HCatSchema schema) {
super(Lists.transform(schema.getFields(), new Function<HCatFieldSchema, FieldSpec>() {
@Override
public FieldSpec apply(HCatFieldSchema fs) {
return new HCatalogFieldSpec(fs, schema.getPosition(fs.getName()));
}
}));
this.schema = schema;
}
public HCatSchema getImpl() {
return schema;
}
}
| 33.047619 | 90 | 0.737032 |
c48a6aafd5bae6798f91d1edf545fe8b8347534d | 1,213 | package catchat.data.source.entities.message;
import java.util.List;
public abstract class Message {
private String id;
private String senderAvatar;
private String sourceGUID;
private String text;
private String senderName;
private long createdAt;
private List<String> likes;
protected Message(String id, String senderAvatar, String sourceGUID, String text, String senderName, long createdAt, List<String> likes) {
this.id = id;
this.senderAvatar = senderAvatar;
this.sourceGUID = sourceGUID;
this.text = text;
this.senderName = senderName;
this.createdAt = createdAt;
this.likes = likes;
}
public String getId() {
return id;
}
public String getSenderAvatar() {
return senderAvatar;
}
public String getSourceGUID() {
return sourceGUID;
}
public String getText() {
return text;
}
public String getSenderName() {
return senderName;
}
public long getCreatedAt() {
return createdAt;
}
public int getLikeCount() {
return likes.size();
}
public List<String> getLikes() {
return likes;
}
} | 22.054545 | 142 | 0.62737 |
d109239670c9cb6e0cb0323689ccb17cb5905b49 | 16,541 | package com.github.phylogeny.boundtotems;
import com.github.phylogeny.boundtotems.Config.Server.InventorySearch;
import com.github.phylogeny.boundtotems.block.BlockStrippedOakLog;
import com.github.phylogeny.boundtotems.block.BlockTotemShelf;
import com.github.phylogeny.boundtotems.block.PositionsTotemShelf;
import com.github.phylogeny.boundtotems.item.ItemBoundTotem;
import com.github.phylogeny.boundtotems.item.ItemBoundTotemTeleporting;
import com.github.phylogeny.boundtotems.item.ItemCarvingKnife;
import com.github.phylogeny.boundtotems.network.PacketNetwork;
import com.github.phylogeny.boundtotems.network.packet.PacketTotemAnimation;
import com.github.phylogeny.boundtotems.network.packet.PacketTotemParticlesAndSound;
import com.github.phylogeny.boundtotems.blockentity.BlockEntityTotemShelf;
import com.github.phylogeny.boundtotems.util.LangUtil;
import com.github.phylogeny.boundtotems.util.NBTUtil;
import com.github.phylogeny.boundtotems.util.ReflectionUtil;
import net.minecraft.Util;
import net.minecraft.advancements.CriteriaTriggers;
import net.minecraft.core.BlockPos;
import net.minecraft.core.NonNullList;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.Tag;
import net.minecraft.network.chat.TranslatableComponent;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.level.ServerPlayerGameMode;
import net.minecraft.stats.Stats;
import net.minecraft.world.ContainerHelper;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.effect.MobEffect;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.ShulkerBoxBlock;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.event.entity.living.LivingDeathEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.event.world.BlockEvent.BreakEvent;
import net.minecraftforge.eventbus.api.EventPriority;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.util.ObfuscationReflectionHelper;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.ItemStackHandler;
import net.minecraftforge.registries.ForgeRegistries;
import javax.annotation.Nullable;
import java.lang.reflect.Field;
import java.util.Hashtable;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
@EventBusSubscriber
public class ServerEvents {
private static final Field LAST_SENT_STATE = ObfuscationReflectionHelper.findField(ServerPlayerGameMode.class, "f_9256_");
private static final Hashtable<BlockPos, Boolean> BREAKING_SHELVES = new Hashtable<>();
private static final Set<Runnable> END_OF_TICK_TASKS = ConcurrentHashMap.newKeySet();
@SubscribeEvent
public static void addTotemShelfBreakingOverlay(PlayerInteractEvent.LeftClickBlock event) {
PositionsTotemShelf positions = getPositionsTotemShelf(event.getPlayer(), event.getWorld().getBlockState(event.getPos()), event.getPos());
if (positions == null)
return;
BlockPos pos = positions.getPosOffset();
Boolean initialized = BREAKING_SHELVES.get(pos);
if (initialized == null)
BREAKING_SHELVES.put(pos, false);
else
BREAKING_SHELVES.remove(pos);
event.getPlayer().level.destroyBlockProgress(-1, pos, -1);
}
@SubscribeEvent
public static void addTotemShelfBreakingOverlay(PlayerEvent.BreakSpeed event) {
PositionsTotemShelf positions = getPositionsTotemShelf(event.getPlayer(), event.getState(), event.getPos());
if (positions == null)
return;
BlockPos pos = positions.getPosOffset();
Boolean initialized = BREAKING_SHELVES.get(pos);
if (initialized == null)
return;
if (!initialized) {
BREAKING_SHELVES.put(pos, true);
return;
}
ServerPlayer player = (ServerPlayer) event.getPlayer();
int progress = (int) ReflectionUtil.getValue(LAST_SENT_STATE, player.gameMode);
player.level.destroyBlockProgress(-1, pos, progress - 1);
}
@Nullable
public static PositionsTotemShelf getPositionsTotemShelf(Player player, BlockState state, BlockPos pos2) {
if (!(player instanceof ServerPlayer) || !(state.getBlock() instanceof BlockTotemShelf || state.getBlock() instanceof BlockStrippedOakLog))
return null;
return BlockTotemShelf.getTotemShelfPositions(state, player.level, pos2);
}
@SubscribeEvent(receiveCanceled = true)
public static void sculptTotemShelf(BreakEvent event) {
ItemStack knife = event.getPlayer().getMainHandItem();
if (!(knife.getItem() instanceof ItemCarvingKnife) || !(event.getWorld() instanceof ServerLevel serverWorld))
return;
PositionsTotemShelf positions = BlockTotemShelf.getTotemShelfPositions(event.getState(), event.getWorld(), event.getPos(), event.getPlayer());
if (positions == null)
return;
Integer stage = positions.getNextStage();
if (stage == null || stage > 6)
return;
event.setCanceled(true);
positions.advanceStage(serverWorld);
knife.hurtAndBreak(1, event.getPlayer(), p -> p.broadcastBreakEvent(InteractionHand.MAIN_HAND));
}
@SubscribeEvent
public static void performEndOfTickTasks(TickEvent.ServerTickEvent event) {
if (event.phase == TickEvent.Phase.END && !END_OF_TICK_TASKS.isEmpty()) {
END_OF_TICK_TASKS.forEach(Runnable::run);
END_OF_TICK_TASKS.clear();
}
}
/**
* Mimics LivingEntity#checkTotemDeathProtection to allow totems of
* undying to prevent death from anywhere in a player's inventory.
*/
@SubscribeEvent(priority = EventPriority.HIGHEST)
public static void preventDeath(LivingDeathEvent event) {
LivingEntity entity = event.getEntityLiving();
DamageSource source = event.getSource();
if (!Config.SERVER.preventCreativeModeDeath.get() && source.isBypassInvul())
return;
ItemStack totem = findBoundTotem(entity);
if (totem.isEmpty())
return;
ServerPlayer player = entity instanceof ServerPlayer ? (ServerPlayer) entity : null;
if (player != null) {
player.awardStat(Stats.ITEM_USED.get(totem.getItem()));
CriteriaTriggers.USED_TOTEM.trigger(player, totem);
}
float heath = Config.SERVER.health.get().floatValue();
entity.setHealth(Config.SERVER.setHealthToPercentageOfMax.get() ? heath * entity.getMaxHealth() : heath);
if (Config.SERVER.clearPotionEffects.get())
entity.removeAllEffects();
for (String potionEffect : Config.SERVER.potionEffects.get()) {
try {
addPotionEffect(entity, potionEffect);
} catch (IllegalPotionEffectArgumentException e) {
entity.sendMessage(new TranslatableComponent(LangUtil.getKey("potion_effect", "error"), potionEffect, e.getMessage()), Util.NIL_UUID);
}
}
boolean teleporting = totem.getItem() instanceof ItemBoundTotemTeleporting;
if (teleporting)
END_OF_TICK_TASKS.add(() -> NBTUtil.teleportEntity(totem, entity));
if (Config.SERVER.spawnParticles.get() || Config.SERVER.playSound.get())
PacketNetwork.sendToAllTrackingAndSelf(new PacketTotemParticlesAndSound(entity), entity);
if (player != null && Config.SERVER.playAnimation.get())
PacketNetwork.sendTo(new PacketTotemAnimation(teleporting), player);
event.setCanceled(true);
}
/**
* Mimics part of CommandEffect#execute in MC 1.12 to convert a config-specified string into a potion effect that is then applied to the player.
*/
private static void addPotionEffect(LivingEntity entity, String potionEffect) throws IllegalPotionEffectArgumentException {
String[] args = potionEffect.split(" ");
MobEffect potion = ForgeRegistries.MOB_EFFECTS.getValue(new ResourceLocation(args[0]));
if (potion == null)
throw new IllegalPotionEffectArgumentException("not_found", args[0]);
int duration = potion.isInstantenous() ? 1 : 600;
if (args.length >= 2) {
duration = parseInt(args[1], 0, 1000000);
if (!potion.isInstantenous())
duration *= 20;
}
int amplifier = args.length >= 3 ? parseInt(args[2], 0, 255) : 0;
if (duration > 0)
entity.addEffect(new MobEffectInstance(potion, duration, amplifier, false, !(args.length >= 4 && "true".equalsIgnoreCase(args[3]))));
}
public static int parseInt(String input, int min, int max) throws IllegalPotionEffectArgumentException {
int i;
try {
i = Integer.parseInt(input);
} catch (NumberFormatException e) {
throw new IllegalPotionEffectArgumentException("num.invalid", input);
}
if (i < min)
throw new IllegalPotionEffectArgumentException("num.too_small", i, min);
else if (i > max)
throw new IllegalPotionEffectArgumentException("num.too_big", i, max);
return i;
}
private static class IllegalPotionEffectArgumentException extends IllegalArgumentException {
private final TranslatableComponent message;
public IllegalPotionEffectArgumentException(String translationKeySuffix, Object... args) {
message = new TranslatableComponent(LangUtil.getKey("potion_effect", translationKeySuffix), args);
}
@Override
public String getMessage() {
return message.getString();
}
}
private static boolean isValidTotem(ItemStack stack, LivingEntity entity) {
return stack.getItem() instanceof ItemBoundTotem && NBTUtil.matchesBoundEntity(stack, entity);
}
/**
* Searches the player's inventory slots -- as well as the slots of shulker boxes (using code from
* {@link net.minecraft.world.level.block.ShulkerBoxBlock#appendHoverText appendHoverText}
* in ShulkerBoxBlock) and other inventory-containing items -- for totems of undying.
*
* @return if found, the totem removed from the players's inventory; if not, an empty stack
*/
private static ItemStack findBoundTotem(LivingEntity entity) {
ItemStack totem;
if (!(entity instanceof ServerPlayer player) || Config.SERVER.inventorySearch.get() == InventorySearch.HELD_ONLY)
totem = getHeldTotem(entity);
else
totem = getTotemFromInventory(player);
if (totem.isEmpty())
totem = getTotemFromShelf(entity);
return totem;
}
private static ItemStack getTotemFromInventory(ServerPlayer player) {
boolean hotbarOnly = Config.SERVER.inventorySearch.get() == InventorySearch.HOTBAR_ONLY;
ItemStack totem = ItemStack.EMPTY;
ItemStack stack;
// Check inventory for totems in slots
for (int i = 0; i < player.getInventory().getContainerSize(); i++) {
if (hotbarOnly && !Inventory.isHotbarSlot(i))
continue;
stack = player.getInventory().getItem(i);
if (isValidTotem(stack, player)) {
totem = stack.copy();
player.getInventory().setItem(i, ItemStack.EMPTY);
return totem;
}
}
// Check inventory for totems in stacks with inventories
for (int i = 0; i < player.getInventory().getContainerSize(); i++) {
if (hotbarOnly && !Inventory.isHotbarSlot(i))
continue;
totem = getTotemFromStack(player, player.getInventory().getItem(i));
if (!totem.isEmpty())
return totem;
}
return totem;
}
private static ItemStack getHeldTotem(LivingEntity entity) {
// Check inventory for totems in slots
for (InteractionHand hand : InteractionHand.values()) {
ItemStack stack = entity.getItemInHand(hand);
if (isValidTotem(stack, entity)) {
ItemStack totem = stack.copy();
stack.shrink(1);
return totem;
}
}
// Check inventory for totems in stacks with inventories
for (InteractionHand hand : InteractionHand.values()) {
ItemStack totem = getTotemFromStack(entity, entity.getItemInHand(hand));
if (!totem.isEmpty())
return totem;
}
return ItemStack.EMPTY;
}
private static ItemStack getTotemFromStack(LivingEntity entity, ItemStack stack) {
CompoundTag nbt;
NonNullList<ItemStack> stacks;
ItemStack stack2;
// Check inventory for totems in shulker boxes
if (stack.getItem() instanceof BlockItem blockItem && blockItem.getBlock() instanceof ShulkerBoxBlock) {
nbt = stack.getTagElement("BlockEntityTag");
if (nbt != null && nbt.contains("Items", Tag.TAG_LIST)) {
stacks = NonNullList.withSize(27, ItemStack.EMPTY);
ContainerHelper.loadAllItems(nbt, stacks);
for (int j = 0; j < stacks.size(); j++) {
stack2 = stacks.get(j);
if (isValidTotem(stack2, entity)) {
ItemStack totem = stack2.copy();
stacks.set(j, ItemStack.EMPTY);
boolean isEmpty = true;
for (int k = 0; k < stacks.size(); k++) {
if (!stacks.get(k).isEmpty()) {
ContainerHelper.saveAllItems(nbt, stacks, false);
isEmpty = false;
break;
}
}
if (isEmpty)
nbt.remove("Items");
return totem;
}
}
}
}
// Check inventory for totems in mod-added items with inventories
IItemHandler itemInventory = stack.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null).orElse(null);
if (itemInventory != null) {
for (int j = 0; j < itemInventory.getSlots(); j++) {
stack2 = itemInventory.getStackInSlot(j);
if (isValidTotem(stack2, entity)) {
ItemStack totem = stack2.copy();
stack2 = itemInventory.extractItem(j, 1, false);
if (!stack2.isEmpty())
return totem;
}
}
}
return ItemStack.EMPTY;
}
private static ItemStack getTotemFromShelf(LivingEntity entity) {
AtomicReference<ItemStack> stackRef = new AtomicReference<>(ItemStack.EMPTY);
boolean performAudit = entity.level.random.nextInt(20) == 0;
BlockEntityTotemShelf.visitTotemShelves(entity, (world, shelf) -> {
if (stackRef.get().isEmpty()) {
ItemStackHandler inventory = shelf.getInventory();
ItemStack stack;
for (int i = 0; i < inventory.getSlots(); i++) {
stack = inventory.extractItem(i, 1, true);
if (stack.getItem() instanceof ItemBoundTotem && entity.getUUID().equals(NBTUtil.getBoundEntityId(stack))) {
stackRef.set(inventory.extractItem(i, 1, false));
if (!performAudit)
return new BlockEntityTotemShelf.ShelfVisitationResult(false, false);
}
}
}
return new BlockEntityTotemShelf.ShelfVisitationResult(false, true);
});
return stackRef.get();
}
} | 44.705405 | 150 | 0.660782 |
350025eff533f8fbfc4ed4d03e46f747f63807a3 | 12,405 | package com.idan.calendar;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
/**
* This class represents an event editor, which handles the event user input.
*
* @author Idan Perry
* @version 24.05.2020
*/
@SuppressWarnings("serial")
public class EventEditor extends JFrame implements ActionListener {
private static final int WIDTH = 390;
private static final int HEIGHT = 180;
private static final int EXPANSION_HEIGHT = 380;
private static final int DETAILS_ROWS = 8;
private static final int DETAILS_COLS = 20;
private static final int MAX_EMPTY_LBLS = 4;
private static final Font EVENT_FONT = new Font("Sans Serif", Font.PLAIN, 18);
private static final Font BTN_FONT = new Font("Calibri", Font.BOLD, 16);
private static final Font TIME_FONT = new Font("Sans Serif", Font.BOLD, 16);
private static final Dimension EDIT_FIELD_SIZE = new Dimension(230, 28);
private static final Dimension SAVE_BTN_SIZE = new Dimension(70, 30);
private static final Dimension DET_BTN_SIZE = new Dimension(110, 30);
private static final Color RED = new Color(153, 0, 0);
private static final Insets MARGIN = new Insets(0, 10, 0, 10);
private static final String[] TIME = { "06:00", "06:30", "07:00", "07:30", "08:00", "08:30", "09:00", "09:30",
"10:00", "10:30", "11:00", "11:30", "12:00", "12:30", "13:00", "13:30", "14:00", "14:30", "15:00", "15:30",
"16:00", "16:30", "17:00", "17:30", "18:00", "18:30", "19:00", "19:30", "20:00", "20:30", "21:00", "21:30",
"22:00", "22:30", "23:00", "23:30" };
private JScrollPane scroll;
private JPanel mainEditPanel; // main panel - holding all north region of the editor
private JPanel iconsPanel; // holds the icons representing the edit fields
private JPanel eventPanel; // holds the event haeder and time editabels
private JPanel eventEditPanel; // sub-panel holds the event textField
private JPanel eventTimePanel; // sub-panel holds the event time edit
private JPanel btnsPanel; // sub-panel holds the buttons
private JPanel detailsPanel; // holds the details text area
private JTextField eventField;
private JLabel calendarIconLbl;
private JLabel eventTimeFromLbl;
private JLabel eventTimeToLbl;
private JLabel clockIconLbl;
private JLabel emptyLbl[];
private JComboBox<String> timeFrom;
private JComboBox<String> timeTo;
private JTextArea detailsArea;
private JButton saveBtn;
private JButton detailsBtn;
private CalendarDay caller; // the day panel in the calendar which called this editor
private MyCalendar calendar;
private ImageIcon clockIcon;
private ImageIcon calendarIcon;
private String date;
private int eventIndex;
private boolean newEvent;
/**
* Constructs an event editor window, which handles the event
* user input.
*
* @param calendar the calendar in which to add or edit an event.
*/
public EventEditor(MyCalendar calendar) {
super("Event Editor");
this.calendar = calendar;
mainEditPanel = new JPanel(new BorderLayout());
iconsPanel = new JPanel(new GridLayout(2, 3));
eventPanel = new JPanel(new GridLayout(2, 1));
eventEditPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
eventTimePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
detailsPanel = new JPanel();
btnsPanel = new JPanel();
eventField = new JTextField("Add an event");
calendarIconLbl = new JLabel();
eventTimeFromLbl = new JLabel("From ");
eventTimeToLbl = new JLabel(" to ");
clockIconLbl = new JLabel();
emptyLbl = new JLabel[MAX_EMPTY_LBLS];
timeFrom = new JComboBox<String>(TIME);
timeTo = new JComboBox<String>(TIME);
detailsArea = new JTextArea("Add more details", DETAILS_ROWS, DETAILS_COLS);
scroll = new JScrollPane(detailsArea);
saveBtn = new JButton("Save");
detailsBtn = new JButton("Add details");
MouseHandler mouseHandler = new MouseHandler();
for(int i = 0; i < MAX_EMPTY_LBLS; i++)
emptyLbl[i] = new JLabel();
try {
clockIcon = new ImageIcon(ImageIO.read(getClass().getResourceAsStream("/clock.png")));
calendarIcon = new ImageIcon(ImageIO.read(getClass().getResourceAsStream("/calendar.png")));
} catch (IOException e) {
e.printStackTrace();
}
setSize(WIDTH, HEIGHT);
getContentPane().setBackground(MyCalendar.LIGHT_BLACK);
setResizable(false);
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/calendar.png")));
addWindowListener(new WindowHandler());
detailsBtn.addActionListener(this);
detailsBtn.addMouseListener(mouseHandler);
saveBtn.addActionListener(this);
saveBtn.addMouseListener(mouseHandler);
eventField.addMouseListener(mouseHandler);
buildComponentsHierarchy();
customizeComponents();
validate();
}
/**
* Returns the event title field text of this window.
*
* @return the event title field text of this window
*/
public JTextField getEventField() {
return eventField;
}
/**
* Returns the event details text area of this window.
*
* @return the event details text area of this window
*/
public JTextArea getDetailsArea() {
return detailsArea;
}
/**
* Sets the CalendarDay object which called this event editor.
*
* @param caller the CalendarDay object which called this event editor
*/
public void setCaller(CalendarDay caller) {
this.caller = caller;
}
/**
* Returns true if the added event is new, otherwise returns false.
*
* @return true if the added event is new, otherwise returns false.
*/
public boolean isNewEvent() {
return newEvent;
}
/**
* Changes whether the added event is new or not, in which case is being edited.
*
* @param newEvent true if the added event is new, false otherwise
*/
public void setNewEvent(boolean newEvent) {
this.newEvent = newEvent;
}
/**
* Initializes a new event display.
*/
public void displayNewEvent() {
eventField.setText("Add an event");
timeFrom.setSelectedItem("06:00");
timeTo.setSelectedItem("06:00");
detailsArea.setText("Add more details");
setVisible(true);
}
/**
* Displays an event in a calendar from a specified date and event index.
*
* @param date the date from which to retrieve the event
* @param i the index of the event in the event list of the specified date
*/
public void displayEvent(String date, int i) {
this.date = date;
this.eventIndex = i;
eventField.setText(calendar.getEvants(date)[i].getHeader());
timeFrom.setSelectedItem((String) calendar.getEvants(date)[i].getStartTime());
timeTo.setSelectedItem((String) calendar.getEvants(date)[i].getEndTime());
detailsArea.setText(calendar.getEvants(date)[i].getDetails());
setVisible(true);
}
/*
* Builds the structure of this window's components.
*/
private void buildComponentsHierarchy() {
// add components to sub-panels
eventEditPanel.add(eventField);
eventTimePanel.add(eventTimeFromLbl);
eventTimePanel.add(timeFrom);
eventTimePanel.add(eventTimeToLbl);
eventTimePanel.add(timeTo);
iconsPanel.add(emptyLbl[0]);
iconsPanel.add(calendarIconLbl);
iconsPanel.add(emptyLbl[1]);
iconsPanel.add(emptyLbl[2]);
iconsPanel.add(clockIconLbl);
iconsPanel.add(emptyLbl[3]);
detailsPanel.add(scroll);
btnsPanel.add(detailsBtn);
btnsPanel.add(saveBtn);
// add sub-panels to main panels
eventPanel.add(eventEditPanel);
eventPanel.add(eventTimePanel);
mainEditPanel.add(eventPanel, BorderLayout.CENTER);
mainEditPanel.add(iconsPanel, BorderLayout.WEST);
// add main panels to this frame
add(mainEditPanel, BorderLayout.NORTH);
add(btnsPanel, BorderLayout.SOUTH);
}
/*
* Sets the properties for this window's components.
*/
private void customizeComponents() {
// buttons sizes
saveBtn.setPreferredSize(SAVE_BTN_SIZE);
detailsBtn.setPreferredSize(DET_BTN_SIZE);
eventField.setPreferredSize(EDIT_FIELD_SIZE);
// background colors
mainEditPanel.setBackground(MyCalendar.LIGHT_BLACK);
iconsPanel.setBackground(MyCalendar.LIGHT_BLACK);
eventPanel.setBackground(MyCalendar.LIGHT_BLACK);
eventEditPanel.setBackground(MyCalendar.LIGHT_BLACK);
eventTimePanel.setBackground(MyCalendar.LIGHT_BLACK);
btnsPanel.setBackground(MyCalendar.LIGHT_BLACK);
detailsPanel.setBackground(MyCalendar.LIGHT_BLACK);
detailsBtn.setBackground(Color.GRAY);
saveBtn.setBackground(RED);
eventField.setBackground(Color.DARK_GRAY);
detailsArea.setBackground(Color.DARK_GRAY);
// text colors
eventTimeToLbl.setForeground(Color.LIGHT_GRAY);
eventTimeFromLbl.setForeground(Color.LIGHT_GRAY);
detailsBtn.setForeground(Color.WHITE);
saveBtn.setForeground(Color.WHITE);
eventField.setForeground(Color.GRAY);
detailsArea.setForeground(Color.WHITE);
timeFrom.setForeground(Color.DARK_GRAY);
timeTo.setForeground(Color.DARK_GRAY);
// fonts
eventField.setFont(EVENT_FONT);
eventTimeFromLbl.setFont(TIME_FONT);
eventTimeToLbl.setFont(TIME_FONT);
timeFrom.setFont(TIME_FONT);
timeTo.setFont(TIME_FONT);
detailsArea.setFont(EVENT_FONT);
detailsBtn.setFont(BTN_FONT);
saveBtn.setFont(BTN_FONT);
// transparency
saveBtn.setContentAreaFilled(false);
saveBtn.setOpaque(true);
detailsBtn.setContentAreaFilled(false);
detailsBtn.setOpaque(true);
// other properties
scroll.setForeground(Color.WHITE);
eventField.setCaretColor(Color.WHITE);
detailsArea.setCaretColor(Color.WHITE);
eventField.setMargin(MARGIN);
detailsArea.setMargin(MARGIN);
clockIconLbl.setIcon(clockIcon);
calendarIconLbl.setIcon(calendarIcon);
eventField.setEditable(false);
}
/*
* Creates a new CalendarEvent object once the save button is clicked,
* if a new event has been added. otherwise modifies an existing event.
*/
private void saveEvent() {
String date = calendar.getYear() + "." + calendar.getMonth() + "." + caller.getDayOfMonth();
CalendarEvent event = new CalendarEvent(eventField.getText(), detailsArea.getText(),
(String) timeFrom.getSelectedItem(), (String) timeTo.getSelectedItem());
if (newEvent) {
calendar.addCalendarEvent(date, event);
caller.setEvent(event);
} else {
calendar.modifyCalendarEvent(this.date, eventIndex, event);
caller.modifyEvent(event, eventIndex);
}
}
/*
* Restores the original size of this window.
*/
private void shrink() {
remove(detailsPanel);
setSize(WIDTH, HEIGHT);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == saveBtn) {
saveEvent();
shrink();
setVisible(false);
} else if (e.getSource() == detailsBtn) {
add(detailsPanel, BorderLayout.CENTER);
setSize(WIDTH, EXPANSION_HEIGHT);
}
calendar.validate();
calendar.repaint();
}
/*
* This class handles the EventEditor window visibility and size.
*/
private class WindowHandler extends WindowAdapter {
@Override
public void windowClosing(WindowEvent e) {
shrink();
setVisible(false);
validate();
}
}
/*
* This class only extends the MouseAdapter to handle mouse events.
*/
private class MouseHandler extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getSource() == eventField) {
eventField.setEditable(true);
eventField.setForeground(Color.WHITE);
validate();
}
}
@Override
public void mouseEntered(MouseEvent e) {
if(e.getSource() == saveBtn)
saveBtn.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
else if(e.getSource() == detailsBtn)
detailsBtn.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
}
@Override
public void mouseExited(MouseEvent e) {
if(e.getSource() == saveBtn)
saveBtn.setBorder(null);
else if(e.getSource() == detailsBtn)
detailsBtn.setBorder(null);
}
}
}
| 30.935162 | 111 | 0.732205 |
d0f783a4a59b5ad9a58646355a2e7a75841e8fbc | 6,240 | package edu.harvard.liblab.ecru;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrInputDocument;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import edu.harvard.liblab.ecru.data.Course;
import edu.harvard.liblab.ecru.data.EcruBase;
import edu.harvard.liblab.ecru.data.Reading;
public class TestCourseAndReading {
//TODO: when we rename the collection, this needs to be changed
private static String url ;
private static HttpSolrServer solrSrvr;
private static DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
@BeforeClass
public static void setUp() throws Exception {
Properties props = new Properties();
try {
props.load(new FileInputStream("conf/test_ecru.properties"));
//System.out.println("Application config set to " + ClassLoader.getSystemResource(propertyFile));
} catch (Exception e) {
throw new RuntimeException("Couldn't load project configuration!", e);
}
url = props.getProperty("solr.url");
solrSrvr = new HttpSolrServer(url);
Date startDate = new Date();
Date endDate = new Date();
startDate = dateFormat.parse("09/01/2003");
endDate = dateFormat.parse("12/30/2003");
Course course = new Course("c_x328182",
"Diversity in New Testament Interpretation: 1 Peter. (Elisabeth Schssler Fiorenza )",
"HDS 1883",endDate, "HDS",new ArrayList<String>(),
"Diversity in New Testament Interpretation: 1 Peter", startDate,
"Fall 2003","http://isites.harvard.edu/icb/icb.do?keyword=k96364");
solrSrvr.addBean(course);
Reading r = Reading.createNonJournal("r_x309482",
"Schussler Fiorenza, Elisabeth. Rhetoric and ethic: the politics of biblical studies. xi, 220 p. (1999) ",
"Here's a student annotation",
Arrays.asList("Schussler Fiorenza, Elizabeth"), "http://webservices.lib.harvard.edu/mobile/catalog/xmlAvailability/008296451",
"008296451", null, "c_328182", null, null, endDate,
"0800627954 (alk. paper)", "1234-5687",
null, null, "DIV",-1, true, "Available", startDate, "HVD01", "Fall 2003",
"Rhetoric and ethic: the politics of biblical studies");
solrSrvr.addBean(r);
r = Reading.createJournal("r_x309192",
"Hochstetler, Kathryn. Crisis and Rapid Reequilibration: The Consequences of Presidential Challenge and Failure in Latin America.. Comparative politics43.2 JAN 2011: 127-146",
"another student annotation",
Arrays.asList("Hochstetler, Kathryn"), null, null,"c_314515", null,
"10.5129/001041511793931834",
endDate, "Comparative politics",null,
"LAM", 2, null, false, "Available", startDate, null,"Fall 2003",
"Crisis and Rapid Reequilibration: The Consequences of Presidential Challenge and Failure in Latin America");
solrSrvr.addBean(r);
UpdateResponse usp = solrSrvr.commit();
}
@Test
public void testFederatedSearch() {
// example testing update at http://svn.apache.org/viewvc/lucene/dev/trunk/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExampleTests.java?view=markup
try {
QueryResponse rsp = getQueryResponse( "(fiorenza AND Fall 2003)");
List<EcruBase> beans = rsp.getBeans(EcruBase.class);
if (beans == null || beans.size() == 0) {
fail("couldn't find anything with fiorenza AND Fall 2003");
}
else {
Reading r = null;
Course c = null;
boolean hasReading = false;
boolean hasCourse = false;
ArrayList<EcruBase> bs = new ArrayList<EcruBase>();
for (EcruBase bean: beans){
if (hasReading = bean.isReading())
bs.add(bean.toReading());
if (hasCourse = bean.isCourse()) {
bs.add(bean.toCourse());
}
if (hasReading && hasCourse) {
break;
}
}
assertTrue("Got at least one course and one reading", isAMatch(bs, "fiorenza"));
}
} catch (SolrServerException e) {
fail("got SolrServer exception! " + e.getMessage());
}
}
private static boolean isAMatch(List<EcruBase> beans, String... fragments) {
boolean retVal = false;
boolean hasCourse = false;
boolean hasReading = false;
try {
for (EcruBase eb: beans) {
if (!hasReading && eb.getType().equals(EcruBase.T_READING)) {
Reading r = eb.toReading();
System.out.println(r);
hasReading = matchFrags(eb.getDisplayLabel().toLowerCase(),fragments);
}
else if (!hasCourse && eb .getType().equals(EcruBase.T_COURSE)) {
Course c = eb.toCourse();
System.out.println(c);
hasCourse = matchFrags(eb.getDisplayLabel().toLowerCase(),fragments);
}
}
} catch (Exception e) {
e.printStackTrace();
}
retVal = hasCourse && hasReading;
return retVal;
}
@AfterClass
public static void tearDown() {
try {
solrSrvr.deleteByQuery("id:c_x328182");
solrSrvr.deleteByQuery("id:r_x309482");
solrSrvr.deleteByQuery("id:r_x309192");
solrSrvr.commit();
} catch (SolrServerException e) {
fail("exception: " + e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
fail("exception: " + e.getMessage());
}
}
private static boolean matchFrags(String display, String... fragments) {
boolean retVal = true;
for (String frag: fragments) {
if (display.indexOf(frag.toLowerCase()) <0) {
retVal = false;
break;
}
}
return retVal;
}
// TODO: move this to some central test class
protected QueryResponse getQueryResponse(String qryStr) throws SolrServerException {
SolrQuery query = new SolrQuery();
query.setQuery(qryStr);
QueryResponse rsp = solrSrvr.query( query );
return rsp;
}
}
| 34.475138 | 179 | 0.709615 |
52ea61c39b0605f646434b1f8a2c95d45e8fa9f3 | 205 | package intraprocedural.arithmetic;
public class Arithmetic6 {
public static void main(String[] args) {
int a = 0;
int b = 1;
int c = a ^ b;
int d = a >>> b;
}
}
| 15.769231 | 44 | 0.517073 |
a317a64ba11d2d16a34db7902f103037aea27c1e | 2,050 | package br.com.deveficiente.bolaoapi.services.championship.api.model.match;
import br.com.deveficiente.bolaoapi.services.championship.Championship;
import br.com.deveficiente.bolaoapi.services.championship.Match;
import br.com.deveficiente.bolaoapi.services.team.Team;
import br.com.deveficiente.bolaoapi.services.team.TeamRepository;
import br.com.deveficiente.bolaoapi.shared.validator.Exists;
import br.com.deveficiente.bolaoapi.shared.validator.MatchTeamsRequest;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Getter;
import lombok.ToString;
import org.springframework.format.annotation.DateTimeFormat;
import javax.validation.Valid;
import javax.validation.constraints.Future;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Positive;
import java.time.LocalTime;
@ToString
@MatchTeamsRequest
public class CreateMatchRequest {
@NotNull
@Positive
private Integer round;
@Getter
@NotNull
@Exists(entityClass = Team.class)
private Long homeTeamId;
@Getter
@NotNull
@Exists(entityClass = Team.class)
private Long visitingTeamId;
@Getter
@NotNull
@Future
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
@JsonFormat(pattern = "HH:mm")
private LocalTime startTime;
public CreateMatchRequest(@NotNull Long homeTeamId, @NotNull Long visitingTeamId, @NotNull @Future LocalTime startTime, @NotNull @Positive Integer round) {
this.homeTeamId = homeTeamId;
this.visitingTeamId = visitingTeamId;
this.startTime = startTime;
this.round = round;
}
@Valid
public Match toMatch(TeamRepository teamRepository, Championship championship) {
Team homeTeam = teamRepository.findById(this.homeTeamId).get();
Team visitingTeam = teamRepository.findById(this.visitingTeamId).get();
return new Match(championship, round, homeTeam, visitingTeam, startTime);
}
public boolean validMatchTeams() {
return this.homeTeamId != this.visitingTeamId;
}
}
| 32.03125 | 159 | 0.759512 |
6ed6011326859f0e8679610041ac505beda282d7 | 1,025 | /**
*
*/
package org.open.application.databean;
import java.util.Calendar;
/**
* @author SandeepRaju
*
*/
public class Product {
private int id;
private String productName;
private double price;
private Calendar dateOfManufacture;
public Product() {
}
public Product(int id, String productName, double price, Calendar dateOfManufacture) {
this.id = id;
this.productName = productName;
this.price = price;
this.dateOfManufacture = dateOfManufacture;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Calendar getDateOfManufacture() {
return dateOfManufacture;
}
public void setDateOfManufacture(Calendar dateOfManufacture) {
this.dateOfManufacture = dateOfManufacture;
}
}
| 16.269841 | 88 | 0.712195 |
7e175e8975b6e5deb8dcec2f4b8383248046ded0 | 633 | import java.util.Scanner;
public class Count_the_item {
public static void main(String[] args) {
int count = 0;
double price;
Scanner input = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
System.out.println(
"Please Entre the prices of the item of person " + (+i + 1) + ": "
);
for (int j = 0; j < 3; j++) {
price = input.nextDouble();
if (price > 300) {
count++;
}
}
System.out.println(
"Person " +(+ i + 1) + " will get 20% discount on " + count + " item !"
);
count = 0;
}
}
}
| 23.444444 | 80 | 0.467615 |
e130fbf8a321c955a72746e84812608f06e48097 | 1,592 | /*
* Copyright (C) 2021 xuexiangjys([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.xuexiang.xtask.core;
import androidx.annotation.NonNull;
import com.xuexiang.xtask.core.param.ITaskResult;
/**
* 任务链执行回调
*
* @author xuexiang
* @since 2021/10/18 10:32 PM
*/
public interface ITaskChainCallback {
/**
* 回调是否返回主线程
*
* @return 是否返回主线程
*/
boolean isCallBackOnMainThread();
/**
* 任务步骤开始执行
*
* @param engine 任务链
*/
void onTaskChainStart(@NonNull ITaskChainEngine engine);
/**
* 任务步骤执行完毕
*
* @param engine 任务链
* @param result 任务执行结果
*/
void onTaskChainCompleted(@NonNull ITaskChainEngine engine, @NonNull ITaskResult result);
/**
* 任务步骤执行发生异常
*
* @param engine 任务链
* @param result 任务执行结果
*/
void onTaskChainError(@NonNull ITaskChainEngine engine, @NonNull ITaskResult result);
/**
* 任务步骤执行被取消
*
* @param engine 任务链
*/
void onTaskChainCancelled(@NonNull ITaskChainEngine engine);
}
| 22.742857 | 93 | 0.665201 |
815dfb26cd6e3a932256e62500c7a16b6f396416 | 2,857 | package com.hoasen.studio.dailymailfeed.Utilities;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.transition.Fade;
import android.transition.TransitionInflater;
import android.view.View;
import com.hoasen.studio.dailymailfeed.R;
import java.util.HashMap;
/**
* Created by Harry Nguyen on 01-Mar-16.
*/
public class DMFragmentManager {
int holderContainerID;
AppCompatActivity context;
static DMFragmentManager instance = null;
HashMap<String,Fragment> fragmentDictionary;
FragmentManager fragmentManager;
public static DMFragmentManager getInstance(){
instance = instance == null ? new DMFragmentManager() : instance;
return instance;
}
DMFragmentManager(){
fragmentDictionary = new HashMap<>();
}
public void settupHolderContainer(int resID){
holderContainerID = resID;
}
public void setContext(AppCompatActivity context){
this.context = context;
fragmentManager = context.getSupportFragmentManager();
}
public FragmentManager getFragmentManager(){
return fragmentManager;
}
public void addFragment(String name, Fragment fragment){
fragmentDictionary.put(name,fragment);
}
public Fragment getFragment(String name){
return fragmentDictionary.get(name);
}
public void transactionTo(Fragment destinationFragment){
goTo(destinationFragment);
}
public void transactionTo(String fragmentName){
Fragment fragment = fragmentDictionary.get(fragmentName);
goTo(fragment);
}
public void transactionWithAnimationTo(Fragment destinationFragment,View shareElement, String animName){
goToWithSharedAnimation(destinationFragment,shareElement,animName);
}
public void transactionWithAnimationTo(String fragmentName,View shareElement, String animName){
Fragment fragment = fragmentDictionary.get(fragmentName);
goToWithSharedAnimation(fragment,shareElement,animName);
}
void goTo(Fragment destinationFragment){
FragmentTransaction transaction = fragmentManager.beginTransaction();
doTransaction(transaction,destinationFragment);
}
void goToWithSharedAnimation(Fragment destinationFragment, View shareElement, String animName){
FragmentTransaction transaction = fragmentManager.beginTransaction().addSharedElement(shareElement,animName);
doTransaction(transaction,destinationFragment);
}
void doTransaction(FragmentTransaction transaction,Fragment destinationFragment){
transaction.replace(holderContainerID, destinationFragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
| 31.744444 | 117 | 0.744487 |
75042c83cb437e692c47000bb6b7f4a3a526bb89 | 282 | package arthur.dy.lee.red.envelope;
public class RedPackage {
public int remainSize;
public double remainMoney;//生产用BigDecimal
public RedPackage(int remainSize, double remainMoney){
this.remainSize = remainSize;
this.remainMoney = remainMoney;
}
}
| 23.5 | 58 | 0.712766 |
44471720487ea04bba08ad191d086b120ea353fe | 3,551 | /*
* -\-\-
* Mobius
* --
* Copyright (c) 2017-2020 Spotify AB
* --
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* -/-/-
*/
package com.spotify.mobius.rx3;
import com.spotify.mobius.MobiusLoop;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.core.ObservableSource;
import io.reactivex.rxjava3.core.ObservableTransformer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Cancellable;
import io.reactivex.rxjava3.functions.Consumer;
import java.util.Set;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Wraps a MobiusLoop into an observable transformer.
*
* <p>Compose it on top of an event of streams to convert it into a stream of models.
*/
class RxMobiusLoop<E, M, F> implements ObservableTransformer<E, M> {
@Nonnull private final MobiusLoop.Factory<M, E, F> loopFactory;
@Nonnull private final M startModel;
@Nullable private final Set<F> startEffects;
RxMobiusLoop(
MobiusLoop.Factory<M, E, F> loopFactory, M startModel, @Nullable Set<F> startEffects) {
this.loopFactory = loopFactory;
this.startModel = startModel;
this.startEffects = startEffects;
}
@Override
public ObservableSource<M> apply(@NonNull Observable<E> upstream) {
return Observable.create(
new ObservableOnSubscribe<M>() {
@Override
public void subscribe(@NonNull ObservableEmitter<M> emitter) throws Throwable {
final MobiusLoop<M, E, ?> loop;
if (startEffects == null) {
loop = loopFactory.startFrom(startModel);
} else {
loop = loopFactory.startFrom(startModel, startEffects);
}
loop.observe(
new com.spotify.mobius.functions.Consumer<M>() {
@Override
public void accept(M value) {
emitter.onNext(value);
}
});
final Disposable eventsDisposable =
upstream.subscribe(
new Consumer<E>() {
@Override
public void accept(E event) throws Throwable {
loop.dispatchEvent(event);
}
},
new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Throwable {
emitter.onError(new UnrecoverableIncomingException(throwable));
}
});
emitter.setCancellable(
new Cancellable() {
@Override
public void cancel() throws Throwable {
loop.dispose();
eventsDisposable.dispose();
}
});
}
});
}
}
| 35.158416 | 93 | 0.61363 |
c6164a02bae5e04718e585b3b369dc1fad0334fe | 905 | package imapi2 ;
import com4j.*;
/**
* Provides notification of the arrival/removal of CD/DVD (optical) devices.
*/
@IID("{27354131-7F64-5B0F-8F00-5D77AFBE261E}")
public interface DDiscMaster2Events extends Com4jObject {
// Methods:
/**
* <p>
* A device was added to the system
* </p>
* @param object Mandatory com4j.Com4jObject parameter.
* @param uniqueId Mandatory java.lang.String parameter.
*/
@VTID(7)
void notifyDeviceAdded(
@MarshalAs(NativeType.Dispatch) com4j.Com4jObject object,
java.lang.String uniqueId);
/**
* <p>
* A device was removed from the system
* </p>
* @param object Mandatory com4j.Com4jObject parameter.
* @param uniqueId Mandatory java.lang.String parameter.
*/
@VTID(8)
void notifyDeviceRemoved(
@MarshalAs(NativeType.Dispatch) com4j.Com4jObject object,
java.lang.String uniqueId);
// Properties:
}
| 22.073171 | 76 | 0.688398 |
4774dd1eab87fe94cbf590492a64bdeac74f9117 | 1,154 | package com.example.mobserv.remoteapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class LogActivity extends DrawerActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log);
textView = (TextView)findViewById(R.id.logTextId);
try {
FileInputStream fin = getApplicationContext().openFileInput(MyConstants.LOG_FILENAME);
int c;
String temp="";
while( (c = fin.read()) != -1){
temp = temp + Character.toString((char)c);
}
//string temp contains all the data of the file.
textView.setText(temp);
fin.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
textView.setText("Nothing to show");
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 29.589744 | 98 | 0.629116 |
fe19bf21d528b92f78cb3fceebce8bf2e6181d56 | 1,317 | /*
* Copyright 2014 dc-square GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hivemq.spi.callback.events.broker;
import com.hivemq.spi.callback.SynchronousCallback;
/**
* This callback gets executed when the broker shuts down.
* At the time this callback gets executed, all connections are already closed
* and there is no way to prevent HiveMQ from shutting down.
* <p/>
* It is recommended to do <b>blocking actions</b> in this callback because the VM
* could quit before your asynchronous actions are finished
*
* @author Dominik Obermaier
* @since 1.4
*/
public interface OnBrokerStop extends SynchronousCallback {
/**
* Called when the broker shuts down
* <p/>
* You can use blocking actions in this callback.
*/
void onBrokerStop();
}
| 32.121951 | 82 | 0.726651 |
e3366eec4cb317451106b2bebdab073b6826c4f8 | 35 | class BaseClass {
Integer id;
} | 11.666667 | 17 | 0.657143 |
0d167c11b2622e604156b349780be86f7af6d390 | 14,325 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.statefun.flink.core.jsonmodule;
import static java.lang.String.format;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toMap;
import static org.apache.flink.statefun.flink.core.common.Maps.transformValues;
import com.google.protobuf.Any;
import com.google.protobuf.Descriptors;
import com.google.protobuf.Message;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URL;
import java.time.Duration;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.StreamSupport;
import javax.annotation.Nullable;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.JsonNode;
import org.apache.flink.statefun.flink.common.ResourceLocator;
import org.apache.flink.statefun.flink.common.json.NamespaceNamePair;
import org.apache.flink.statefun.flink.common.json.Selectors;
import org.apache.flink.statefun.flink.common.protobuf.ProtobufDescriptorMap;
import org.apache.flink.statefun.flink.core.grpcfn.GrpcFunctionProvider;
import org.apache.flink.statefun.flink.core.grpcfn.GrpcFunctionSpec;
import org.apache.flink.statefun.flink.core.httpfn.HttpFunctionProvider;
import org.apache.flink.statefun.flink.core.httpfn.HttpFunctionSpec;
import org.apache.flink.statefun.flink.core.jsonmodule.FunctionSpec.Kind;
import org.apache.flink.statefun.flink.core.jsonmodule.Pointers.Functions;
import org.apache.flink.statefun.flink.core.protorouter.AutoRoutableProtobufRouter;
import org.apache.flink.statefun.flink.core.protorouter.ProtobufRouter;
import org.apache.flink.statefun.flink.io.kafka.ProtobufKafkaIngressTypes;
import org.apache.flink.statefun.flink.io.kinesis.PolyglotKinesisIOTypes;
import org.apache.flink.statefun.flink.io.spi.JsonEgressSpec;
import org.apache.flink.statefun.flink.io.spi.JsonIngressSpec;
import org.apache.flink.statefun.sdk.EgressType;
import org.apache.flink.statefun.sdk.FunctionType;
import org.apache.flink.statefun.sdk.IngressType;
import org.apache.flink.statefun.sdk.StatefulFunctionProvider;
import org.apache.flink.statefun.sdk.io.EgressIdentifier;
import org.apache.flink.statefun.sdk.io.IngressIdentifier;
import org.apache.flink.statefun.sdk.io.Router;
import org.apache.flink.statefun.sdk.spi.StatefulFunctionModule;
import org.apache.flink.util.TimeUtils;
final class JsonModule implements StatefulFunctionModule {
private static final Duration DEFAULT_HTTP_TIMEOUT = Duration.ofMinutes(1);
private static final Integer DEFAULT_MAX_NUM_BATCH_REQUESTS = 1000;
private final JsonNode spec;
private final URL moduleUrl;
public JsonModule(JsonNode spec, URL moduleUrl) {
this.spec = Objects.requireNonNull(spec);
this.moduleUrl = Objects.requireNonNull(moduleUrl);
}
public void configure(Map<String, String> conf, Binder binder) {
try {
configureFunctions(binder, Selectors.listAt(spec, Pointers.FUNCTIONS_POINTER));
configureRouters(binder, Selectors.listAt(spec, Pointers.ROUTERS_POINTER));
configureIngress(binder, Selectors.listAt(spec, Pointers.INGRESSES_POINTER));
configureEgress(binder, Selectors.listAt(spec, Pointers.EGRESSES_POINTER));
} catch (Throwable t) {
throw new ModuleConfigurationException(
format("Error while parsing module at %s", moduleUrl), t);
}
}
private void configureFunctions(Binder binder, Iterable<? extends JsonNode> functions) {
final Map<Kind, Map<FunctionType, FunctionSpec>> definedFunctions =
StreamSupport.stream(functions.spliterator(), false)
.map(JsonModule::parseFunctionSpec)
.collect(groupingBy(FunctionSpec::kind, groupByFunctionType()));
for (Entry<Kind, Map<FunctionType, FunctionSpec>> entry : definedFunctions.entrySet()) {
StatefulFunctionProvider provider = functionProvider(entry.getKey(), entry.getValue());
Set<FunctionType> functionTypes = entry.getValue().keySet();
for (FunctionType type : functionTypes) {
binder.bindFunctionProvider(type, provider);
}
}
}
private static StatefulFunctionProvider functionProvider(
Kind kind, Map<FunctionType, FunctionSpec> definedFunctions) {
switch (kind) {
case HTTP:
return new HttpFunctionProvider(
transformValues(definedFunctions, HttpFunctionSpec.class::cast));
case GRPC:
return new GrpcFunctionProvider(
transformValues(definedFunctions, GrpcFunctionSpec.class::cast));
default:
throw new IllegalStateException("Unexpected value: " + kind);
}
}
private void configureRouters(Binder binder, Iterable<? extends JsonNode> routerNodes) {
for (JsonNode router : routerNodes) {
// currently the only type of router supported in a module.yaml, is a protobuf dynamicMessage
// router once we will introduce further router types we should refactor this to be more
// dynamic.
requireProtobufRouterType(router);
IngressIdentifier<Message> id = targetRouterIngress(router);
binder.bindIngressRouter(id, dynamicRouter(router));
}
}
private void configureIngress(Binder binder, Iterable<? extends JsonNode> ingressNode) {
for (JsonNode ingress : ingressNode) {
IngressIdentifier<Message> id = ingressId(ingress);
IngressType type = ingressType(ingress);
JsonIngressSpec<Message> ingressSpec = new JsonIngressSpec<>(type, id, ingress);
binder.bindIngress(ingressSpec);
if (isAutoRoutableIngress(type)) {
binder.bindIngressRouter(id, new AutoRoutableProtobufRouter());
}
}
}
private void configureEgress(Binder binder, Iterable<? extends JsonNode> egressNode) {
for (JsonNode egress : egressNode) {
EgressIdentifier<Any> id = egressId(egress);
EgressType type = egressType(egress);
JsonEgressSpec<Any> egressSpec = new JsonEgressSpec<>(type, id, egress);
binder.bindEgress(egressSpec);
}
}
// ----------------------------------------------------------------------------------------------------------
// Ingresses
// ----------------------------------------------------------------------------------------------------------
private static IngressType ingressType(JsonNode spec) {
String typeString = Selectors.textAt(spec, Pointers.Ingress.META_TYPE);
NamespaceNamePair nn = NamespaceNamePair.from(typeString);
return new IngressType(nn.namespace(), nn.name());
}
private static IngressIdentifier<Message> ingressId(JsonNode ingress) {
String ingressId = Selectors.textAt(ingress, Pointers.Ingress.META_ID);
NamespaceNamePair nn = NamespaceNamePair.from(ingressId);
return new IngressIdentifier<>(Message.class, nn.namespace(), nn.name());
}
private static boolean isAutoRoutableIngress(IngressType ingressType) {
return ingressType.equals(ProtobufKafkaIngressTypes.ROUTABLE_PROTOBUF_KAFKA_INGRESS_TYPE)
|| ingressType.equals(PolyglotKinesisIOTypes.ROUTABLE_PROTOBUF_KINESIS_INGRESS_TYPE);
}
// ----------------------------------------------------------------------------------------------------------
// Egresses
// ----------------------------------------------------------------------------------------------------------
private static EgressType egressType(JsonNode spec) {
String typeString = Selectors.textAt(spec, Pointers.Egress.META_TYPE);
NamespaceNamePair nn = NamespaceNamePair.from(typeString);
return new EgressType(nn.namespace(), nn.name());
}
private static EgressIdentifier<Any> egressId(JsonNode spec) {
String egressId = Selectors.textAt(spec, Pointers.Egress.META_ID);
NamespaceNamePair nn = NamespaceNamePair.from(egressId);
return new EgressIdentifier<>(nn.namespace(), nn.name(), Any.class);
}
// ----------------------------------------------------------------------------------------------------------
// Routers
// ----------------------------------------------------------------------------------------------------------
private static Router<Message> dynamicRouter(JsonNode router) {
String addressTemplate = Selectors.textAt(router, Pointers.Routers.SPEC_TARGET);
String descriptorSetPath = Selectors.textAt(router, Pointers.Routers.SPEC_DESCRIPTOR);
String messageType = Selectors.textAt(router, Pointers.Routers.SPEC_MESSAGE_TYPE);
ProtobufDescriptorMap descriptorPath = protobufDescriptorMap(descriptorSetPath);
Optional<Descriptors.GenericDescriptor> maybeDescriptor =
descriptorPath.getDescriptorByName(messageType);
if (!maybeDescriptor.isPresent()) {
throw new IllegalStateException(
"Error while processing a router definition. Unable to locate a message "
+ messageType
+ " in a descriptor set "
+ descriptorSetPath);
}
return ProtobufRouter.forAddressTemplate(
(Descriptors.Descriptor) maybeDescriptor.get(), addressTemplate);
}
private static ProtobufDescriptorMap protobufDescriptorMap(String descriptorSetPath) {
try {
URL url = ResourceLocator.findNamedResource(descriptorSetPath);
if (url == null) {
throw new IllegalArgumentException(
"Unable to locate a Protobuf descriptor set at " + descriptorSetPath);
}
return ProtobufDescriptorMap.from(url);
} catch (IOException e) {
throw new IllegalStateException(
"Error while processing a router definition. Unable to read the descriptor set at "
+ descriptorSetPath,
e);
}
}
private static IngressIdentifier<Message> targetRouterIngress(JsonNode routerNode) {
String targetIngress = Selectors.textAt(routerNode, Pointers.Routers.SPEC_INGRESS);
NamespaceNamePair nn = NamespaceNamePair.from(targetIngress);
return new IngressIdentifier<>(Message.class, nn.namespace(), nn.name());
}
private static void requireProtobufRouterType(JsonNode routerNode) {
String routerType = Selectors.textAt(routerNode, Pointers.Routers.META_TYPE);
if (!routerType.equalsIgnoreCase("org.apache.flink.statefun.sdk/protobuf-router")) {
throw new IllegalStateException("Invalid router type " + routerType);
}
}
// ----------------------------------------------------------------------------------------------------------
// Functions
// ----------------------------------------------------------------------------------------------------------
private static FunctionSpec parseFunctionSpec(JsonNode functionNode) {
String functionKind = Selectors.textAt(functionNode, Pointers.Functions.META_KIND);
FunctionSpec.Kind kind = Kind.valueOf(functionKind.toUpperCase(Locale.getDefault()));
FunctionType functionType = functionType(functionNode);
switch (kind) {
case HTTP:
return new HttpFunctionSpec(
functionType,
functionUri(functionNode),
functionStates(functionNode),
maxRequestDuration(functionNode),
maxNumBatchRequests(functionNode));
case GRPC:
return new GrpcFunctionSpec(functionType, functionAddress(functionNode));
default:
throw new IllegalArgumentException("Unrecognized function kind " + functionKind);
}
}
private static int maxNumBatchRequests(JsonNode functionNode) {
return Selectors.optionalIntegerAt(functionNode, Functions.FUNCTION_MAX_NUM_BATCH_REQUESTS)
.orElse(DEFAULT_MAX_NUM_BATCH_REQUESTS);
}
private static Duration maxRequestDuration(JsonNode functionNode) {
return Selectors.optionalTextAt(functionNode, Functions.FUNCTION_TIMEOUT)
.map(TimeUtils::parseDuration)
.orElse(DEFAULT_HTTP_TIMEOUT);
}
private static List<String> functionStates(JsonNode functionNode) {
return Selectors.textListAt(functionNode, Pointers.Functions.FUNCTION_STATES);
}
private static FunctionType functionType(JsonNode functionNode) {
String namespaceName = Selectors.textAt(functionNode, Pointers.Functions.META_TYPE);
NamespaceNamePair nn = NamespaceNamePair.from(namespaceName);
return new FunctionType(nn.namespace(), nn.name());
}
private static InetSocketAddress functionAddress(JsonNode functionNode) {
String host = Selectors.textAt(functionNode, Pointers.Functions.FUNCTION_HOSTNAME);
int port = Selectors.integerAt(functionNode, Pointers.Functions.FUNCTION_PORT);
return new InetSocketAddress(host, port);
}
private static URI functionUri(JsonNode functionNode) {
String uri = Selectors.textAt(functionNode, Pointers.Functions.FUNCTION_ENDPOINT);
URI typedUri = URI.create(uri);
@Nullable String scheme = typedUri.getScheme();
if (scheme == null) {
throw new IllegalArgumentException(
"Missing scheme in function endpoint "
+ uri
+ "; an http or https scheme must be provided.");
}
if (scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("https")) {
return typedUri;
}
throw new IllegalArgumentException(
"Missing scheme in function endpoint "
+ uri
+ "; an http or https scheme must be provided.");
}
private static Collector<FunctionSpec, ?, Map<FunctionType, FunctionSpec>> groupByFunctionType() {
return toMap(FunctionSpec::functionType, Function.identity());
}
}
| 45.04717 | 111 | 0.702897 |
e187fad470d2099683e791212bf438e4f6e5d5eb | 435 | package leecode;
public class MaximumSubarray {
public int maxSubArray(int[] nums) {
int maxSoFar = nums[0];
int maxEndingHere = nums[0];
for (int i = 1; i < nums.length; i++) {
maxEndingHere = Math.max(maxEndingHere + nums[i], nums[i]);
maxSoFar = Math.max(maxEndingHere, maxSoFar);
}
return maxSoFar;
}
public static void main(String[] args) {
}
}
| 21.75 | 71 | 0.567816 |
70a5b141b2b3b64e8818afff9204a28e467fb20f | 2,372 | package com.intellect.spring.boot.cud.exception;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class ApplicationExceptionFactory {
ErrorCodesConfig exceptionInfo = ErrorCodesConfig.getInstance();
@Autowired
ApplicationExceptionsList list;
public ApplicationException createNewAppexception(String exceptionCode){
String errorCode = exceptionInfo.getExceptionCode(exceptionCode);
String errorMsg = exceptionInfo.getExceptionMsg(exceptionCode);
String errorDetails = exceptionInfo.getExceptionDetails(exceptionCode);
String type = exceptionInfo.getExceptionType(exceptionCode);
String httpStatus = exceptionInfo.getHttpStatusCode(exceptionCode);
return new ApplicationException(type,errorCode,errorMsg,errorDetails,httpStatus);
}
public ApplicationException createNewAppexceptionWithErrorDetails(String exceptionCode, String errorDetails){
String errorCode = exceptionInfo.getExceptionCode(exceptionCode);
String errorMsg = exceptionInfo.getExceptionMsg(exceptionCode);
String type = exceptionInfo.getExceptionType(exceptionCode);
String httpStatus = exceptionInfo.getHttpStatusCode(exceptionCode);
return new ApplicationException(type,errorCode,errorMsg,errorDetails,httpStatus);
}
public ApplicationException createNewAppexception(String exceptionCode,String exceptionDetail){
String errorCode = exceptionInfo.getExceptionCode(exceptionCode);
String errorMsg = exceptionInfo.getExceptionMsg(exceptionCode);
String type = exceptionInfo.getExceptionType(exceptionCode);
String httpStatus = exceptionInfo.getHttpStatusCode(exceptionCode);
String errorDetails = (exceptionDetail!=null)?exceptionDetail:exceptionInfo.getExceptionDetails(exceptionCode);
return new ApplicationException(type,errorCode,errorMsg,errorDetails,httpStatus);
}
public void addException(String exceptionCode){
list.addAppExceptionsList(createNewAppexception(exceptionCode));
}
public void addException(String exceptionCode,String exceptionDetail){
if(exceptionDetail!=null){
list.addAppExceptionsList(createNewAppexception(exceptionCode,exceptionDetail));
}else{
addException(exceptionCode);
}
}
public void throwApplicationExceptionsList() throws ApplicationExceptionsList{
throw list;
}
}
| 33.885714 | 113 | 0.818718 |
9f1ea3264e136b0557cdfb7e902de031db0b0681 | 1,391 | /**
*
*/
package repast.simphony.data2.engine;
import repast.simphony.data2.ConsoleDataSink;
import repast.simphony.data2.FormatType;
import repast.simphony.data2.ConsoleDataSink.OutputStream;
/**
* Sink for outputting text data to the console.
*
* @author Nick Collier
*/
public class ConsoleSinkDescriptor extends AbstractTextSinkDescriptor {
private boolean enabled = true;
private ConsoleDataSink.OutputStream outputStream = OutputStream.OUT;
/**
* Creates a ConsoleSinkDescriptor.
*
* @param name
*/
public ConsoleSinkDescriptor(String name) {
super(name);
format = FormatType.LINE;
}
/**
* @return the enabled
*/
public boolean isEnabled() {
return enabled;
}
/**
* @param enabled
* the enabled to set
*/
public void setEnabled(boolean enabled) {
if (this.enabled != enabled) {
this.enabled = enabled;
scs.fireScenarioChanged(this, "enabled");
}
}
/**
* @return the outputStream
*/
public ConsoleDataSink.OutputStream getOutputStream() {
return outputStream;
}
/**
* @param outputStream
* the outputStream to set
*/
public void setOutputStream(ConsoleDataSink.OutputStream outputStream) {
if (this.outputStream != outputStream) {
this.outputStream = outputStream;
scs.fireScenarioChanged(this, "outputStream");
}
}
}
| 20.761194 | 74 | 0.672178 |
3d34ac92042aa9f2b477e4a7964ebe164de13585 | 1,830 | /*******************************************************************************
* * Copyright 2014 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.client.schemamanager.entites;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import com.impetus.kundera.index.Index;
import com.impetus.kundera.index.IndexCollection;
@Embeddable
@IndexCollection(columns = { @Index(name = "tweetDate"), @Index(name = "firstName") })
public class CompositeUser
{
@Column
private String user_id;
@Column
private Date tweetDate;
@Column
private String firstName;
public CompositeUser()
{
}
public String getUser_id()
{
return user_id;
}
public void setUser_id(String user_id)
{
this.user_id = user_id;
}
public Date getTweetDate()
{
return tweetDate;
}
public void setTweetDate(Date tweetDate)
{
this.tweetDate = tweetDate;
}
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
}
| 24.078947 | 86 | 0.606557 |
f42b0aa444738799dc6183668edf558b1fad7467 | 6,563 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright 2007-2009 SSAC(Systems of Social Accounting Consortium)
* <author> Yasunari Ishizuka (PieCake,Inc.)
* <author> Hiroshi Deguchi (TOKYO INSTITUTE OF TECHNOLOGY)
* <author> Yuji Onuki (Statistics Bureau)
* <author> Shungo Sakaki (Tokyo University of Technology)
* <author> Akira Sasaki (HOSEI UNIVERSITY)
* <author> Hideki Tanuma (TOKYO INSTITUTE OF TECHNOLOGY)
*/
/*
* @(#)ModuleFileInfoView.java 1.14 2009/12/09
* - created by Y.Ishizuka(PieCake.inc,)
*/
package ssac.aadl.manager.view;
import java.awt.BorderLayout;
import javax.swing.JEditorPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import ssac.aadl.common.CommonMessages;
import ssac.aadl.module.ModuleFileManager;
import ssac.aadl.module.setting.AadlJarProfile;
import ssac.aadl.module.setting.AbstractSettings;
import ssac.aadl.module.setting.PackageSettings;
import ssac.aadl.module.swing.tree.ModuleFileTreeNode;
import ssac.util.io.VirtualFile;
import ssac.util.logging.AppLogger;
/**
* モジュールファイルの情報を表示するビュー
*
* @version 1.14 2009/12/09
* @since 1.14
*/
public class ModuleFileInfoView extends JPanel
{
//------------------------------------------------------------
// Constants
//------------------------------------------------------------
//------------------------------------------------------------
// Fields
//------------------------------------------------------------
/** 表示対象のモジュールアイテム **/
private ModuleFileTreeNode _target;
/** 情報表示タブ **/
private final JTabbedPane _tabInfo;
/** パッケージの情報を表示するコンポーネント **/
private final JEditorPane _cInfoPackage;
/** メインモジュールの情報を表示するコンポーネント **/
private final JEditorPane _cInfoMainModule;
/** パッケージの情報を表示するコンポーネントのスクロール **/
private final JScrollPane _scForPackage;
/** メインモジュールの情報を表示するコンポーネントのスクロール **/
private final JScrollPane _scForMainModule;
//------------------------------------------------------------
// Constructions
//------------------------------------------------------------
public ModuleFileInfoView() {
super(new BorderLayout());
this._tabInfo = createInfoTab();
this._cInfoPackage = createInfoEditorPane();
this._cInfoMainModule = createInfoEditorPane();
this._scForPackage = createInfoScrollPane();
this._scForMainModule = createInfoScrollPane();
setupComponents();
}
private void setupComponents() {
// setup Package Info
_scForPackage.setViewportView(_cInfoPackage);
// setup MainModule Info
_scForMainModule.setViewportView(_cInfoMainModule);
// set tab to panel
this.add(_tabInfo, BorderLayout.CENTER);
}
//------------------------------------------------------------
// Public interfaces
//------------------------------------------------------------
/**
* 情報表示対象のパスを表すツリーノードを返す。
* 表示対象が設定されていない場合は <tt>null</tt> を返す。
*/
public ModuleFileTreeNode getTargetNode() {
return _target;
}
/**
* 情報表示対象のパスを表すツリーノードを設定する。
* @param newTarget 情報を表示するツリーノードを指定する。
* 表示しない場合は <tt>null</tt> を指定する。
*/
public void setTargetNode(ModuleFileTreeNode newTarget) {
if (newTarget != this._target) {
this._target = newTarget;
refreshInfo();
}
}
//------------------------------------------------------------
// Internal methods
//------------------------------------------------------------
protected void refreshInfo() {
// パッケージルートではないディレクトリの場合は、何も表示しない
if (_target == null
|| !_target.exists()
|| !_target.isDirectory()
|| !_target.isModulePackageRoot())
{
_tabInfo.removeAll();
return;
}
// パッケージ情報を取得
PackageSettings packSettings = _target.getModulePackageProperties();
StringBuilder sb = new StringBuilder();
sb.append("<html><body>");
ModuleFileManager.appendDisplayFilePropertyBlock(sb, _target.getFileObject(), packSettings);
sb.append("</body></html>");
_cInfoPackage.setText(sb.toString());
_cInfoPackage.setCaretPosition(0);
if (_tabInfo.indexOfComponent(_scForPackage) < 0) {
_tabInfo.addTab(CommonMessages.getInstance().ModuleInfoTabTitle_Package, _scForPackage);
}
// メインモジュール情報を取得
VirtualFile vfMain = packSettings.getMainModuleFile();
if (vfMain != null && vfMain.exists() && vfMain.isFile()) {
sb.setLength(0);
//--- Jar ファイル専用の解析
if (ModuleFileManager.isJarFile(vfMain)) {
AadlJarProfile jarprop = null;
try {
jarprop = new AadlJarProfile(vfMain);
}
catch (Throwable ex) {
AppLogger.warn("Failed to read profile from jar : \"" + vfMain.getPath() + "\"", ex);
jarprop = null;
}
if (jarprop != null) {
sb.append("<html><body>");
ModuleFileManager.appendDisplayJarFilePropertyBlock(sb, vfMain, jarprop);
sb.append("</body></html>");
}
}
//--- それ以外の場合は、設定情報ファイルを参照
if (sb.length() == 0) {
// another file types
AbstractSettings settings = ModuleFileManager.getModuleFileSettings(vfMain);
sb.setLength(0);
sb.append("<html><body>");
ModuleFileManager.appendDisplayFilePropertyBlock(sb, vfMain, settings);
sb.append("</body></html>");
}
_cInfoMainModule.setText(sb.toString());
_cInfoMainModule.setCaretPosition(0);
if (_tabInfo.indexOfComponent(_scForMainModule) < 0) {
_tabInfo.addTab(CommonMessages.getInstance().ModuleInfoTabTitle_MainModule, _scForMainModule);
}
} else {
int index = _tabInfo.indexOfComponent(_scForMainModule);
if (index >= 0) {
_tabInfo.removeTabAt(index);
}
}
if (_tabInfo.getTabCount() > 0) {
_tabInfo.setSelectedIndex(0);
}
}
protected JTabbedPane createInfoTab() {
JTabbedPane tab = new JTabbedPane();
tab.setFocusable(false);
return tab;
}
protected JEditorPane createInfoEditorPane() {
JEditorPane pane = new JEditorPane();
pane.setContentType("text/html");
pane.setEditable(false);
return pane;
}
protected JScrollPane createInfoScrollPane() {
JScrollPane pane = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
return pane;
}
}
| 30.525581 | 98 | 0.649855 |
f12299a95cd118b0f7dbbbbc717064f02912dc6f | 453 | package eu.xenit.alfred.initializr.start.sdk.alfred.compose.config;
import eu.xenit.alfred.initializr.start.sdk.alfred.compose.config.DockerComposeGradlePluginConfiguration;
import org.springframework.core.Ordered;
@FunctionalInterface
public interface DockerComposeGradlePluginConfigurationCustomizer extends Ordered {
void customize(DockerComposeGradlePluginConfiguration configuration);
default int getOrder() {
return 0;
}
}
| 30.2 | 105 | 0.818985 |
03519286c88693298965e50167d94a1360ab495d | 959 | package br.dev.rodrigocury.forum.controller;
import br.dev.rodrigocury.forum.dtos.CursoDto;
import br.dev.rodrigocury.forum.models.Curso;
import br.dev.rodrigocury.forum.repositories.CursoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
@RestController
@RequestMapping("/cursos")
public class CursoController {
CursoRepository cursoRepository;
@Autowired
public CursoController(CursoRepository cursoRepository){
this.cursoRepository = cursoRepository;
}
@PostMapping
public Curso criaCurso(@Valid @RequestBody CursoDto requestCurso){
Curso curso = requestCurso.toCurso();
cursoRepository.save(curso);
return curso;
}
}
| 29.060606 | 68 | 0.812304 |
510f0222f3949179191568dffd0554788536f024 | 6,078 | package com.fbla.atlas.atlas.reviewFragments;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.fbla.atlas.atlas.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link ReviewDoneFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link ReviewDoneFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class ReviewDoneFragment extends Fragment {
DatabaseReference databaseReference;
FirebaseAuth auth;
TextView date, rating, comment;
String user_id, book_id;
ImageView image;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public ReviewDoneFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ReviewDoneFragment.
*/
// TODO: Rename and change types and number of parameters
public static ReviewDoneFragment newInstance(String param1, String param2) {
ReviewDoneFragment fragment = new ReviewDoneFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Bundle bundle = getArguments();
book_id = bundle.getString("book_id");
System.out.println(book_id);
auth = FirebaseAuth.getInstance();
user_id = auth.getCurrentUser().getUid();
databaseReference = FirebaseDatabase.getInstance().getReference().child("Reviews").child(user_id).child(book_id);
image = (ImageView) view.findViewById(R.id.user_image);
rating = (TextView) view.findViewById(R.id.review_rating);
comment = (TextView) view.findViewById(R.id.review_comment);
date = (TextView) view.findViewById(R.id.review_date);
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String imageURL = dataSnapshot.child("image").getValue().toString().trim();
String Comment = dataSnapshot.child("comment").getValue().toString().trim();
String Date = dataSnapshot.child("date").getValue().toString().trim();
String Rating = dataSnapshot.child("rating").getValue().toString().trim();
if (imageURL.equals("default")){
Picasso.with(getContext()).load(R.drawable.logoatlas).into(image);
}else{
Picasso.with(getContext()).load(imageURL).into(image);
}
date.setText("Rated on: " + Date);
rating.setText("Rating: " + Rating);
comment.setText(Comment);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_review_done, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
| 34.146067 | 121 | 0.674893 |
26e25da79f191ca3014d0fa49701cc2b1c316cbe | 5,162 | /**
* Copyright © 2016-2019 The Thingsboard Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thingsboard.rule.engine.metadata;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import org.apache.commons.collections.CollectionUtils;
import org.thingsboard.rule.engine.api.TbContext;
import org.thingsboard.rule.engine.api.TbNode;
import org.thingsboard.rule.engine.api.TbNodeConfiguration;
import org.thingsboard.rule.engine.api.TbNodeException;
import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.kv.AttributeKvEntry;
import org.thingsboard.server.common.data.kv.TsKvEntry;
import org.thingsboard.server.common.msg.TbMsg;
import java.util.List;
import static org.thingsboard.rule.engine.api.util.DonAsynchron.withCallback;
import static org.thingsboard.rule.engine.api.TbRelationTypes.FAILURE;
import static org.thingsboard.rule.engine.api.TbRelationTypes.SUCCESS;
import static org.thingsboard.server.common.data.DataConstants.CLIENT_SCOPE;
import static org.thingsboard.server.common.data.DataConstants.SERVER_SCOPE;
import static org.thingsboard.server.common.data.DataConstants.SHARED_SCOPE;
public abstract class TbAbstractGetAttributesNode<C extends TbGetAttributesNodeConfiguration, T extends EntityId> implements TbNode {
protected C config;
@Override
public void init(TbContext ctx, TbNodeConfiguration configuration) throws TbNodeException {
this.config = loadGetAttributesNodeConfig(configuration);
}
protected abstract C loadGetAttributesNodeConfig(TbNodeConfiguration configuration) throws TbNodeException;
@Override
public void onMsg(TbContext ctx, TbMsg msg) throws TbNodeException {
try {
withCallback(
findEntityIdAsync(ctx, msg),
entityId -> safePutAttributes(ctx, msg, entityId),
t -> ctx.tellFailure(msg, t), ctx.getDbCallbackExecutor());
} catch (Throwable th) {
ctx.tellFailure(msg, th);
}
}
private void safePutAttributes(TbContext ctx, TbMsg msg, T entityId) {
if (entityId == null || entityId.isNullUid()) {
ctx.tellNext(msg, FAILURE);
return;
}
ListenableFuture<List<Void>> allFutures = Futures.allAsList(
putLatestTelemetry(ctx, entityId, msg, config.getLatestTsKeyNames()),
putAttrAsync(ctx, entityId, msg, CLIENT_SCOPE, config.getClientAttributeNames(), "cs_"),
putAttrAsync(ctx, entityId, msg, SHARED_SCOPE, config.getSharedAttributeNames(), "shared_"),
putAttrAsync(ctx, entityId, msg, SERVER_SCOPE, config.getServerAttributeNames(), "ss_")
);
withCallback(allFutures, i -> ctx.tellNext(msg, SUCCESS), t -> ctx.tellFailure(msg, t), ctx.getDbCallbackExecutor());
}
private ListenableFuture<Void> putAttrAsync(TbContext ctx, EntityId entityId, TbMsg msg, String scope, List<String> keys, String prefix) {
if (CollectionUtils.isEmpty(keys)) {
return Futures.immediateFuture(null);
}
ListenableFuture<List<AttributeKvEntry>> latest = ctx.getAttributesService().find(ctx.getTenantId(), entityId, scope, keys);
return Futures.transform(latest, l -> {
l.forEach(r -> {
if (r.getValue() != null) {
msg.getMetaData().putValue(prefix + r.getKey(), r.getValueAsString());
} else {
throw new RuntimeException("[" + scope + "][" + r.getKey() + "] attribute value is not present in the DB!");
}
});
return null;
});
}
private ListenableFuture<Void> putLatestTelemetry(TbContext ctx, EntityId entityId, TbMsg msg, List<String> keys) {
if (CollectionUtils.isEmpty(keys)) {
return Futures.immediateFuture(null);
}
ListenableFuture<List<TsKvEntry>> latest = ctx.getTimeseriesService().findLatest(ctx.getTenantId(), entityId, keys);
return Futures.transform(latest, l -> {
l.forEach(r -> {
if (r.getValue() != null) {
msg.getMetaData().putValue(r.getKey(), r.getValueAsString());
} else {
throw new RuntimeException("[" + r.getKey() + "] telemetry value is not present in the DB!");
}
});
return null;
});
}
@Override
public void destroy() {
}
protected abstract ListenableFuture<T> findEntityIdAsync(TbContext ctx, TbMsg msg);
}
| 44.119658 | 142 | 0.678613 |
f47ea1e3af81cece55067df02793135e9334864e | 178 | package net.minecraft.src;
import net.minecraft.entity.player.EntityPlayer;
/**
*
* @author Gregory
*/
public class NetServerHandler {
public EntityPlayer playerEntity;
}
| 14.833333 | 48 | 0.752809 |
c642d4459b6e51b30f33e3b0a2ac0a4137a4193e | 4,641 | package org.mikuclub.app.utils;
import android.content.Context;
import android.content.DialogInterface;
import android.view.KeyEvent;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import mikuclub.app.R;
/**
* 自定义弹窗管理器
* 用来快速创建特定的弹窗 (加载进度条, 重试窗口等等)
* Custom AlertDialog manager
* Used to quickly create specific popup
*/
public class AlertDialogUtils
{
/**
* 创建进度条弹窗
*/
public static AlertDialog createProgressDialog(Context context, boolean cancelable, boolean forceFinish)
{
AlertDialog.Builder builder = new MaterialAlertDialogBuilder(context);
builder.setView(R.layout.alert_dialog_progress_bar);
builder.setCancelable(cancelable);
AlertDialog dialog = builder.create();
//禁止通过触摸屏幕关闭弹窗
//禁止通过触摸屏幕关闭弹窗
dialog.setCanceledOnTouchOutside(cancelable);
//只有在可取消的情况下
if (cancelable)
{
//需要重写弹窗的按钮监听
dialog.setOnKeyListener((dialog1, keyCode, event) -> {
if (keyCode == KeyEvent.KEYCODE_BACK)
{
dialog.dismiss();
//如果是 活动上下文的话
if (forceFinish && context instanceof AppCompatActivity)
{
//结束相关活动
((AppCompatActivity) context).finish();
}
}
return true;
});
}
return dialog;
}
/**
* 创建通用询问弹窗
*
* @param context
* @param title
* @param content
* @param positiveButtonText
* @param positiveClickListener
* @return
*/
public static AlertDialog createConfirmDialog(Context context, String title, String
content, boolean cancelable, boolean forceFinish, String
positiveButtonText, DialogInterface.OnClickListener positiveClickListener, String negativeButtonText, DialogInterface.OnClickListener negativeClickListener)
{
AlertDialog.Builder builder = new MaterialAlertDialogBuilder(context);
builder.setCancelable(cancelable);
builder.setTitle(title);
if (content != null)
{
builder.setMessage(content);
}
//设置确认按钮
builder.setPositiveButton(positiveButtonText, positiveClickListener);
//设置取消按钮
builder.setNegativeButton(negativeButtonText, negativeClickListener);
//创建弹窗
AlertDialog dialog = builder.create();
//禁止通过触摸屏幕关闭弹窗
dialog.setCanceledOnTouchOutside(cancelable);
//只有在可取消的情况下
if (cancelable)
{
//需要重写弹窗的按钮监听
dialog.setOnKeyListener((dialog1, keyCode, event) -> {
if (keyCode == KeyEvent.KEYCODE_BACK)
{
dialog.dismiss();
//如果 可以强制取消 而且 是活动上下文的话
if (forceFinish && context instanceof AppCompatActivity)
{
//结束相关活动
((AppCompatActivity) context).finish();
}
}
return true;
});
}
return dialog;
}
/**
* 创建删除确认弹窗
*
* @return
*/
public static AlertDialog createDeleteConfirmDialog(Context context, DialogInterface.OnClickListener positiveClickListener)
{
return createConfirmDialog(context, ResourcesUtils.getString(R.string.confirm_delete), null, true, false, ResourcesUtils.getString(R.string.confirm), positiveClickListener, ResourcesUtils.getString(R.string.cancel), null);
}
}
| 38.675 | 238 | 0.481793 |
544f67b7c2eb105d1a075f5bfe3b7356107f3131 | 2,724 | /*
* Copyright (C) 2017 Oracle
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.xml.xsom.impl.parser;
import java.text.MessageFormat;
import java.util.ResourceBundle;
/**
* Formats error messages.
*/
public class Messages
{
/** Loads a string resource and formats it with specified arguments. */
public static String format( String property, Object... args ) {
String text = ResourceBundle.getBundle(
Messages.class.getName()).getString(property);
return MessageFormat.format(text,args);
}
//
//
// Message resources
//
//
public static final String ERR_UNDEFINED_SIMPLETYPE =
"UndefinedSimpleType"; // arg:1
public static final String ERR_UNDEFINED_COMPLEXTYPE =
"UndefinedCompplexType"; // arg:1
public static final String ERR_UNDEFINED_TYPE =
"UndefinedType"; // arg:1
public static final String ERR_UNDEFINED_ELEMENT =
"UndefinedElement"; // arg:1
public static final String ERR_UNDEFINED_MODELGROUP =
"UndefinedModelGroup"; // arg:1
public static final String ERR_UNDEFINED_ATTRIBUTE =
"UndefinedAttribute"; // arg:1
public static final String ERR_UNDEFINED_ATTRIBUTEGROUP =
"UndefinedAttributeGroup"; // arg:1
public static final String ERR_UNDEFINED_IDENTITY_CONSTRAINT =
"UndefinedIdentityConstraint"; // arg:1
public static final String ERR_UNDEFINED_PREFIX =
"UndefinedPrefix"; // arg:1
public static final String ERR_DOUBLE_DEFINITION =
"DoubleDefinition"; // arg:1
public static final String ERR_DOUBLE_DEFINITION_ORIGINAL =
"DoubleDefinition.Original"; // arg:0
public static final String ERR_MISSING_SCHEMALOCATION =
"MissingSchemaLocation"; // arg:0
public static final String ERR_ENTITY_RESOLUTION_FAILURE =
"EntityResolutionFailure"; // arg:2
public static final String ERR_SIMPLE_CONTENT_EXPECTED =
"SimpleContentExpected"; // arg:2
public static final String JAXP_UNSUPPORTED_PROPERTY =
"JAXPUnsupportedProperty"; // arg:1
public static final String JAXP_SUPPORTED_PROPERTY =
"JAXPSupportedProperty"; // arg:1
}
| 35.376623 | 75 | 0.708517 |
cfc447880fefe920222cbf6cb2d4fa07fc190859 | 1,157 | package org.brailleblaster.perspectives;
import nu.xom.Document;
import org.brailleblaster.wordprocessor.BBStatusBar;
import org.brailleblaster.wordprocessor.WPManager;
public interface DocumentManager {
//reset values or focus of a SWT component after switching perspectives
public void restore(WPManager wp);
//used to properly dispose of SWT components within the tab area when switching perspectives
public void dispose();
//Used when closing a tab and when closing a tab when the program exits. The controller is responsible for checking and saving a document and performing necessary clean-up
public void close();
//returns a XOM document, which is passed to another controller when switching perspectives
public Document getDoc();
//Resets the status bar for a perspective dependent message
public void setStatusBarText(BBStatusBar statusBar);
//check before opening a new document whether it should reuse the current tab or open in a new tab
public boolean canReuseTab();
//performs any necessary clean-up before opening a document within the current tab
public void reuseTab(String file);
} | 39.896552 | 174 | 0.779602 |
53c30d06b9a87ad612a8adbfdbe762ba8b6d3bfa | 3,145 | package com.codetaylor.mc.dropt.modules.dropt.rule.parse;
import com.codetaylor.mc.athenaeum.parser.recipe.item.MalformedRecipeItemException;
import com.codetaylor.mc.athenaeum.parser.recipe.item.ParseResult;
import com.codetaylor.mc.athenaeum.parser.recipe.item.RecipeItemParser;
import com.codetaylor.mc.dropt.modules.dropt.rule.data.Rule;
import com.codetaylor.mc.dropt.modules.dropt.rule.data.RuleList;
import com.codetaylor.mc.dropt.modules.dropt.rule.log.ILogger;
import com.codetaylor.mc.dropt.modules.dropt.rule.log.DebugFileWrapper;
import com.codetaylor.mc.dropt.modules.dropt.rule.match.BlockMatchEntry;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.common.registry.ForgeRegistries;
import net.minecraftforge.oredict.OreDictionary;
public class ParserRuleMatchBlocks
implements IRuleListParser {
@Override
public void parse(
RecipeItemParser parser, RuleList ruleList, Rule rule, ILogger logger, DebugFileWrapper debugFileWrapper
) {
if (rule.match == null) {
if (rule.debug) {
debugFileWrapper.debug("[PARSE] Match object not defined, skipped parsing block match");
}
return;
}
if (rule.match.blocks == null || rule.match.blocks.blocks.length == 0) {
if (rule.debug) {
debugFileWrapper.debug("[PARSE] No block matches defined, skipped parsing block match");
}
return;
}
for (String string : rule.match.blocks.blocks) {
String[] split = string.split(",");
ParseResult parse;
try {
parse = parser.parse(split[0]);
} catch (MalformedRecipeItemException e) {
logger.error("[PARSE] Unable to parse block [" + split[0] + "] in file: " + ruleList._filename, e);
continue;
}
if (rule.debug) {
debugFileWrapper.debug("[PARSE] Parsed block match: " + parse);
}
Block block = ForgeRegistries.BLOCKS.getValue(new ResourceLocation(parse.getDomain(), parse.getPath()));
if (block == null || block == Blocks.AIR) {
logger.error("[PARSE] Unable to find registered block: " + parse.toString());
continue;
}
if (rule.debug) {
debugFileWrapper.debug("[PARSE] Found registered block: " + block);
}
int meta = parse.getMeta();
int[] metas = new int[Math.max(split.length - 1, 0)];
for (int i = 1; i < split.length; i++) {
if ("*".equals(split[i].trim())) {
meta = OreDictionary.WILDCARD_VALUE;
metas = new int[0];
break;
}
try {
metas[i - 1] = Integer.parseInt(split[i].trim());
} catch (Exception e) {
logger.error("[PARSE] Unable to parse extra meta for [" + string + "] in file: " + ruleList._filename, e);
}
}
BlockMatchEntry blockMatchEntry = new BlockMatchEntry(parse.getDomain(), parse.getPath(), meta, metas);
rule.match.blocks._blocks.add(blockMatchEntry);
if (rule.debug) {
debugFileWrapper.debug("[PARSE] Added block matcher: " + blockMatchEntry);
}
}
}
}
| 32.091837 | 116 | 0.659459 |
492f00421f7546d9d02fed47a170c6cc164a4c92 | 2,133 | /**
* This class is generated by jOOQ
*/
package com.parallax.server.blocklyprop.db.generated.tables.pojos;
import java.io.Serializable;
import java.sql.Timestamp;
import javax.annotation.Generated;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.7.4"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class Admin implements Serializable {
private static final long serialVersionUID = 1538385417;
private Long id;
private Integer dbVersion;
private String dbScript;
private String notes;
private Timestamp lastChangeDate;
public Admin() {}
public Admin(Admin value) {
this.id = value.id;
this.dbVersion = value.dbVersion;
this.dbScript = value.dbScript;
this.notes = value.notes;
this.lastChangeDate = value.lastChangeDate;
}
public Admin(
Long id,
Integer dbVersion,
String dbScript,
String notes,
Timestamp lastChangeDate
) {
this.id = id;
this.dbVersion = dbVersion;
this.dbScript = dbScript;
this.notes = notes;
this.lastChangeDate = lastChangeDate;
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getDbVersion() {
return this.dbVersion;
}
public void setDbVersion(Integer dbVersion) {
this.dbVersion = dbVersion;
}
public String getDbScript() {
return this.dbScript;
}
public void setDbScript(String dbScript) {
this.dbScript = dbScript;
}
public String getNotes() {
return this.notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public Timestamp getLastChangeDate() {
return this.lastChangeDate;
}
public void setLastChangeDate(Timestamp lastChangeDate) {
this.lastChangeDate = lastChangeDate;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("Admin (");
sb.append(id);
sb.append(", ").append(dbVersion);
sb.append(", ").append(dbScript);
sb.append(", ").append(notes);
sb.append(", ").append(lastChangeDate);
sb.append(")");
return sb.toString();
}
}
| 19.044643 | 66 | 0.693858 |
5b686cf2646748bd0a003146f33abc255333d44e | 394 | package io.jenkins.tools.pluginmanager.util;
public class Source {
private String version;
private String url;
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
| 17.130435 | 44 | 0.606599 |
d3304860751e44a4adff5976ca2a34f83cab8605 | 1,077 | package com.zbiljic.resterror;
import org.testng.annotations.Test;
import com.zbiljic.resterror.http.HttpStatus;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
/**
* @author Nemanja Zbiljic
*/
public class RestErrorFactoryTest {
@Test
public void shouldCreateGenericRestError() {
final RestError error = RestErrorFactory.valueOf(HttpStatus.NOT_FOUND);
assertThat(error.getStatus(), equalTo(404));
assertThat(error.getCode(), equalTo(404));
assertThat(error.getMessage(), equalTo("Not Found"));
assertThat(error.getMoreInfo(), equalTo("http://httpstatus.es/404"));
}
@Test
public void shouldCreateGenericRestErrorWithDetail() {
final RestError error = RestErrorFactory.valueOf(HttpStatus.NOT_FOUND, "Resource could not be found");
assertThat(error.getStatus(), equalTo(404));
assertThat(error.getCode(), equalTo(404));
assertThat(error.getMessage(), equalTo("Resource could not be found"));
assertThat(error.getMoreInfo(), equalTo("http://httpstatus.es/404"));
}
} | 30.771429 | 106 | 0.742804 |
7902206d95e48d6eb6b05a49db566b90a56503f1 | 6,976 | /**
* The MIT License
* Copyright © 2021 Heinz Nixdorf Chair for Distributed Information Systems, Friedrich Schiller University Jena
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package de.uni_jena.cs.fusion.experiment.rdf_datatype_usage.measure;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import de.uni_jena.cs.fusion.experiment.rdf_datatype_usage.ScanThread;
import de.uni_jena.cs.fusion.experiment.rdf_datatype_usage.utils.FileIterator;
import de.uni_jena.cs.fusion.experiment.rdf_datatype_usage.utils.ModelUtil;
public class FileMeasure {
/**
* List of all measures performed on the file
*/
private List<Measure> measures;
private org.slf4j.Logger log;
/**
* Iterator over the statements of the file
*/
private FileIterator fileIter;
/**
* Connection to the database
*/
private Connection con;
/**
* ID of the file in the file organisation database
*/
private Long fileID;
private String url;
/**
* Viewing a file from a database
*
* @param fileID Identifier of the file in the database
* @param url location of the file
* @param con Connection to the database
* @param log Logging information
*/
public FileMeasure(Long fileID, String url, Connection con, org.slf4j.Logger log) throws SQLException {
this.con = con;
this.fileID = fileID;
initaliseMeasures();
this.log = log;
this.url = url;
this.fileIter = ModelUtil.parseURLlineByLine(url, log);
}
/**
* Viewing a file from a database - multithreaded context
*
* @param fileID Identifier of the file in the database
* @param url location of the file
* @param con Connection to the database
* @param log Logging information
* @param thread Thread which is working on the file
*/
public FileMeasure(Long fileID, String url, Connection con, org.slf4j.Logger log, ScanThread thread)
throws SQLException {
this.con = con;
this.fileID = fileID;
initaliseMeasures();
this.log = log;
this.url = url;
this.fileIter = ModelUtil.parseURLlineByLine(url, log, thread);
}
/**
* No database context
*
* @param dataPath where to find the file, must be from the form file:///<path>
* @param measures which measures should be conducted
* @param log logging information
*/
public FileMeasure(String dataPath, List<Measure> measures, org.slf4j.Logger log) {
this.log = log;
this.measures = measures;
this.fileIter = ModelUtil.parseURLlineByLine(dataPath, log);
}
/**
* calls {@link ModelUtil#conductMeasurement(Measures, FileIterator, Logger)
* which conducts all measures on each statement of the file
*/
public void startMeasurements() {
ModelUtil.conductMeasurements(measures, fileIter, log);
}
/**
* Writes the results into the respective database table after the measures have
* been carried out.
*
* <p>
* The total number of lines, if applicable the parsing errors and the results
* of the measures
* </p>
* <p>
* Also set the end time to mark the file as processed
* </p>
*
* @throws SQLException when an error occurs during writing to the database
*/
public void writeToDatabase() throws SQLException {
writeNumLines();
writeToErrorDatabaseTable();
writeToResultDatabaseTable();
con.createStatement().execute("UPDATE files SET end_time = '"
+ new Timestamp(System.currentTimeMillis()) + "' WHERE file_id = " + fileID);
// commit all the changes and new lines to the database
con.commit();
}
/**
* writes the errors that occurred while parsing the file to the error table
*
* @throws SQLException when an error occurs
*/
private void writeToErrorDatabaseTable() throws SQLException {
Map<Long, List<String>> errors = fileIter.getErrors();
try (PreparedStatement ps = con.prepareStatement("INSERT INTO errors VALUES (?,?,?)");) {
ps.setLong(1, fileID);
for (Long line : errors.keySet()) {
ps.setLong(2, line);
for (String errorMsg : errors.get(line)) {
ps.setString(3, errorMsg);
ps.execute();
}
}
}
}
/**
* writes the results of the different measurements to the result table
*
* @throws SQLException when an error occurs
*/
private void writeToResultDatabaseTable() throws SQLException {
try (PreparedStatement ps = con.prepareStatement("INSERT INTO measurements VALUES (?,?,?,?,?)");) {
ps.setLong(1, fileID);
for (Measure measure : measures) {
for (MeasureResult result : measure.writeToDatabase()) {
ps.setString(2, result.getProperty());
ps.setString(3, result.getMeasure());
ps.setString(4, result.getDatatype());
ps.setLong(5, result.getQuantity());
ps.execute();
}
}
}
}
/**
* writes the total number of lines in the file organization table
*
* @throws SQLException when an error occurs
*/
private void writeNumLines() throws SQLException {
con.createStatement().execute(
"UPDATE files SET total_number_of_lines = " + fileIter.getNumLines() + " WHERE file_id = " + fileID);
}
/**
* Configure, which measurements will be conducted
*/
private void initaliseMeasures() {
measures = new ArrayList<Measure>();
measures.add(new UnpreciseRepresentableInDouble());
measures.add(new UnpreciseRepresentableInFloat());
measures.add(new UsedAsDatatype());
measures.add(new UsedAsPropertyRange());
measures.add(new ValidDateNotation());
measures.add(new ValidDateTimeNotation());
measures.add(new ValidDecimalNotation());
measures.add(new ValidExponentialNotation());
measures.add(new ValidInfOrNaNNotation());
measures.add(new ValidIntegerNotation());
measures.add(new ValidTimeNotation());
measures.add(new ValidTrueOrFalseNotation());
measures.add(new ValidZeroOrOneNotation());
}
public long getFileID() {
return fileID;
}
public String getUrl() {
return url;
}
}
| 31.423423 | 111 | 0.71961 |
40ca25b23e7766ae9d733b2ee6401bc1da796eb9 | 13,511 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|oak
operator|.
name|plugins
operator|.
name|blob
package|;
end_package
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|collect
operator|.
name|ImmutableList
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|core
operator|.
name|data
operator|.
name|DataIdentifier
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|core
operator|.
name|data
operator|.
name|DataRecord
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|core
operator|.
name|data
operator|.
name|DataStoreException
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|oak
operator|.
name|api
operator|.
name|jmx
operator|.
name|CheckpointMBean
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|oak
operator|.
name|commons
operator|.
name|concurrent
operator|.
name|ExecutorCloser
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|oak
operator|.
name|plugins
operator|.
name|blob
operator|.
name|datastore
operator|.
name|SharedDataStoreUtils
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|oak
operator|.
name|spi
operator|.
name|blob
operator|.
name|GarbageCollectableBlobStore
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|oak
operator|.
name|spi
operator|.
name|whiteboard
operator|.
name|Tracker
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|oak
operator|.
name|spi
operator|.
name|whiteboard
operator|.
name|Whiteboard
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|oak
operator|.
name|stats
operator|.
name|DefaultStatisticsProvider
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|After
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Before
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Rule
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Test
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|rules
operator|.
name|ExpectedException
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|runner
operator|.
name|RunWith
import|;
end_import
begin_import
import|import
name|org
operator|.
name|mockito
operator|.
name|Mock
import|;
end_import
begin_import
import|import
name|org
operator|.
name|mockito
operator|.
name|junit
operator|.
name|MockitoJUnitRunner
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|ByteArrayInputStream
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|IOException
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|List
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|concurrent
operator|.
name|Executors
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|concurrent
operator|.
name|ScheduledExecutorService
import|;
end_import
begin_import
import|import static
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|oak
operator|.
name|plugins
operator|.
name|blob
operator|.
name|SharedDataStore
operator|.
name|Type
operator|.
name|SHARED
import|;
end_import
begin_import
import|import static
name|org
operator|.
name|hamcrest
operator|.
name|CoreMatchers
operator|.
name|is
import|;
end_import
begin_import
import|import static
name|org
operator|.
name|junit
operator|.
name|Assert
operator|.
name|assertThat
import|;
end_import
begin_import
import|import static
name|org
operator|.
name|mockito
operator|.
name|Mockito
operator|.
name|mock
import|;
end_import
begin_import
import|import static
name|org
operator|.
name|mockito
operator|.
name|Mockito
operator|.
name|when
import|;
end_import
begin_class
annotation|@
name|RunWith
argument_list|(
name|MockitoJUnitRunner
operator|.
name|class
argument_list|)
specifier|public
class|class
name|SharedDataStoreMarkSweepGarbageCollectorTest
block|{
annotation|@
name|Mock
specifier|private
name|MockGarbageCollectableSharedDataStore
name|blobStore
decl_stmt|;
annotation|@
name|Mock
specifier|private
name|BlobReferenceRetriever
name|marker
decl_stmt|;
annotation|@
name|Mock
specifier|private
name|Whiteboard
name|whiteboard
decl_stmt|;
annotation|@
name|Mock
specifier|private
name|Tracker
argument_list|<
name|CheckpointMBean
argument_list|>
name|tracker
decl_stmt|;
annotation|@
name|Rule
specifier|public
name|ExpectedException
name|exception
init|=
name|ExpectedException
operator|.
name|none
argument_list|()
decl_stmt|;
specifier|private
name|MarkSweepGarbageCollector
name|collector
decl_stmt|;
annotation|@
name|Mock
specifier|private
name|CheckpointMBean
name|checkpointMBean
decl_stmt|;
specifier|private
name|ScheduledExecutorService
name|executor
init|=
name|Executors
operator|.
name|newSingleThreadScheduledExecutor
argument_list|()
decl_stmt|;
annotation|@
name|Before
specifier|public
name|void
name|setUp
parameter_list|()
throws|throws
name|IOException
block|{
name|when
argument_list|(
name|whiteboard
operator|.
name|track
argument_list|(
name|CheckpointMBean
operator|.
name|class
argument_list|)
argument_list|)
operator|.
name|thenReturn
argument_list|(
name|tracker
argument_list|)
expr_stmt|;
name|when
argument_list|(
name|tracker
operator|.
name|getServices
argument_list|()
argument_list|)
operator|.
name|thenReturn
argument_list|(
name|ImmutableList
operator|.
name|of
argument_list|(
name|checkpointMBean
argument_list|)
argument_list|)
expr_stmt|;
name|when
argument_list|(
name|blobStore
operator|.
name|getType
argument_list|()
argument_list|)
operator|.
name|thenReturn
argument_list|(
name|SHARED
argument_list|)
expr_stmt|;
name|collector
operator|=
operator|new
name|MarkSweepGarbageCollector
argument_list|(
name|marker
argument_list|,
name|blobStore
argument_list|,
name|executor
argument_list|,
name|MarkSweepGarbageCollector
operator|.
name|TEMP_DIR
argument_list|,
literal|1
argument_list|,
literal|0L
argument_list|,
literal|false
argument_list|,
literal|"repo"
argument_list|,
name|whiteboard
argument_list|,
operator|new
name|DefaultStatisticsProvider
argument_list|(
name|executor
argument_list|)
argument_list|)
expr_stmt|;
block|}
annotation|@
name|After
specifier|public
name|void
name|tear
parameter_list|()
block|{
operator|new
name|ExecutorCloser
argument_list|(
name|executor
argument_list|)
operator|.
name|close
argument_list|()
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|markAndSweepShouldFailIfNotAllRepositoriesHaveMarkedReferencesAvailable
parameter_list|()
throws|throws
name|Exception
block|{
name|setupSharedDataRecords
argument_list|(
literal|"REPO1"
argument_list|,
literal|"REPO2"
argument_list|)
expr_stmt|;
name|collector
operator|.
name|markAndSweep
argument_list|(
literal|false
argument_list|,
literal|true
argument_list|)
expr_stmt|;
name|assertThat
argument_list|(
name|collector
operator|.
name|getOperationStats
argument_list|()
operator|.
name|numDeleted
argument_list|()
argument_list|,
name|is
argument_list|(
literal|0L
argument_list|)
argument_list|)
expr_stmt|;
name|assertThat
argument_list|(
name|collector
operator|.
name|getOperationStats
argument_list|()
operator|.
name|getFailureCount
argument_list|()
argument_list|,
name|is
argument_list|(
literal|1L
argument_list|)
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|markAndSweepShouldSucceedWhenAllRepositoriesAreAvailable
parameter_list|()
throws|throws
name|Exception
block|{
name|setupSharedDataRecords
argument_list|(
literal|"REPO1"
argument_list|,
literal|"REPO1"
argument_list|)
expr_stmt|;
name|when
argument_list|(
name|blobStore
operator|.
name|getAllChunkIds
argument_list|(
literal|0L
argument_list|)
argument_list|)
operator|.
name|thenReturn
argument_list|(
name|ImmutableList
operator|.
expr|<
name|String
operator|>
name|of
argument_list|()
operator|.
name|iterator
argument_list|()
argument_list|)
expr_stmt|;
name|collector
operator|.
name|markAndSweep
argument_list|(
literal|false
argument_list|,
literal|true
argument_list|)
expr_stmt|;
name|assertThat
argument_list|(
name|collector
operator|.
name|getOperationStats
argument_list|()
operator|.
name|numDeleted
argument_list|()
argument_list|,
name|is
argument_list|(
literal|0L
argument_list|)
argument_list|)
expr_stmt|;
name|assertThat
argument_list|(
name|collector
operator|.
name|getOperationStats
argument_list|()
operator|.
name|getFailureCount
argument_list|()
argument_list|,
name|is
argument_list|(
literal|0L
argument_list|)
argument_list|)
expr_stmt|;
block|}
specifier|private
name|void
name|setupSharedDataRecords
parameter_list|(
specifier|final
name|String
name|refRepoId
parameter_list|,
specifier|final
name|String
name|repoRepoId
parameter_list|)
throws|throws
name|DataStoreException
block|{
name|DataRecord
name|refDataRecord
init|=
name|mock
argument_list|(
name|DataRecord
operator|.
name|class
argument_list|)
decl_stmt|;
name|when
argument_list|(
name|refDataRecord
operator|.
name|getIdentifier
argument_list|()
argument_list|)
operator|.
name|thenReturn
argument_list|(
operator|new
name|DataIdentifier
argument_list|(
literal|"references-"
operator|+
name|refRepoId
argument_list|)
argument_list|)
expr_stmt|;
name|when
argument_list|(
name|refDataRecord
operator|.
name|getStream
argument_list|()
argument_list|)
operator|.
name|thenReturn
argument_list|(
operator|new
name|ByteArrayInputStream
argument_list|(
operator|new
name|byte
index|[
literal|0
index|]
argument_list|)
argument_list|)
expr_stmt|;
name|when
argument_list|(
name|refDataRecord
operator|.
name|getLastModified
argument_list|()
argument_list|)
operator|.
name|thenReturn
argument_list|(
literal|10L
argument_list|)
expr_stmt|;
name|DataRecord
name|repoDataRecord
init|=
name|mock
argument_list|(
name|DataRecord
operator|.
name|class
argument_list|)
decl_stmt|;
name|when
argument_list|(
name|repoDataRecord
operator|.
name|getIdentifier
argument_list|()
argument_list|)
operator|.
name|thenReturn
argument_list|(
operator|new
name|DataIdentifier
argument_list|(
literal|"repository-"
operator|+
name|repoRepoId
argument_list|)
argument_list|)
expr_stmt|;
name|List
argument_list|<
name|DataRecord
argument_list|>
name|refs
init|=
name|ImmutableList
operator|.
name|of
argument_list|(
name|refDataRecord
argument_list|)
decl_stmt|;
name|List
argument_list|<
name|DataRecord
argument_list|>
name|repos
init|=
name|ImmutableList
operator|.
name|of
argument_list|(
name|repoDataRecord
argument_list|)
decl_stmt|;
name|when
argument_list|(
name|blobStore
operator|.
name|getAllMetadataRecords
argument_list|(
name|SharedDataStoreUtils
operator|.
name|SharedStoreRecordType
operator|.
name|REFERENCES
operator|.
name|getType
argument_list|()
argument_list|)
argument_list|)
operator|.
name|thenReturn
argument_list|(
name|refs
argument_list|)
expr_stmt|;
name|when
argument_list|(
name|blobStore
operator|.
name|getAllMetadataRecords
argument_list|(
name|SharedDataStoreUtils
operator|.
name|SharedStoreRecordType
operator|.
name|REPOSITORY
operator|.
name|getType
argument_list|()
argument_list|)
argument_list|)
operator|.
name|thenReturn
argument_list|(
name|repos
argument_list|)
expr_stmt|;
name|when
argument_list|(
name|blobStore
operator|.
name|getAllMetadataRecords
argument_list|(
name|SharedDataStoreUtils
operator|.
name|SharedStoreRecordType
operator|.
name|MARKED_START_MARKER
operator|.
name|getType
argument_list|()
argument_list|)
argument_list|)
operator|.
name|thenReturn
argument_list|(
name|refs
argument_list|)
expr_stmt|;
block|}
specifier|private
interface|interface
name|MockGarbageCollectableSharedDataStore
extends|extends
name|GarbageCollectableBlobStore
extends|,
name|SharedDataStore
block|{ }
block|}
end_class
end_unit
| 14.237092 | 815 | 0.816076 |
cfcf12fa767069e7e9419e4c9c2d052de283ab0d | 1,558 | /*
* Copyright (c) 2010, Isode Limited, London, England.
* All rights reserved.
*/
/*
* Copyright (c) 2010, Remko Tronçon.
* All rights reserved.
*/
package com.isode.stroke.client;
/**
*
*/
public class ClientError {
private final Type type_;
public enum Type {
UnknownError,
DomainNameResolveError,
ConnectionError,
ConnectionReadError,
ConnectionWriteError,
XMLError,
AuthenticationFailedError,
CompressionFailedError,
ServerVerificationFailedError,
NoSupportedAuthMechanismsError,
UnexpectedElementError,
ResourceBindError,
SessionStartError,
StreamError,
TLSError,
ClientCertificateLoadError,
ClientCertificateError,
// Certifate on smartcard was removed
CertificateCardRemoved,
// Certificate verification errors
UnknownCertificateError,
CertificateExpiredError,
CertificateNotYetValidError,
CertificateSelfSignedError,
CertificateRejectedError,
CertificateUntrustedError,
InvalidCertificatePurposeError,
CertificatePathLengthExceededError,
InvalidCertificateSignatureError,
InvalidCAError,
InvalidServerIdentityError,
RevokedError,
RevocationCheckFailedError
};
public ClientError() {
type_ = Type.UnknownError;
}
public ClientError(final Type type) {
type_ = type;
}
public Type getType() {
return type_;
}
}
| 22.57971 | 54 | 0.652118 |
73223fafa9453dc7fff2868863493cbc1660cc60 | 112 | package com.base.java.generics;
public interface Pair<K,V> {
public K getKey();
public V getValue();
}
| 16 | 32 | 0.669643 |
9ec869193e3f82321e2898227b5d23435dcade27 | 2,348 | package me.aichina.strategy.move;
import me.aichina.board.ChessBoard;
import me.aichina.board.PieceType;
import me.aichina.game.GameState;
import me.aichina.game.Move;
/**
* 走子策略基类,getMove方法为核心方法,用于生成走子动作
*
* @author 陆梦轩
*
*/
abstract public class MoveStrategy{
/**
* 标签
*/
private String label;
/**
* 该策略预测的价值,用于界面显示
*/
protected double value;
/**
* 搜索深度,用于界面显示
*/
protected int maxDepth;
/**
* 迭代次数,用于界面显示,一般用不到
*/
protected int visitNum;
/**
* 策略执行时间,用于界面显示
*/
protected long runTime;
/**
* 获取标签
*
* @return 标签
*/
public String getLabel(){
return this.label;
}
/**
* 设置标签
*
* @param label 标签
*/
public void setLabel(String label){
this.label=label;
}
@Override
public String toString(){
return label;
}
/**
* 获得当前游戏状态下的一步走子动作
*
* @param gameState
* 当前游戏状态,包含了对弈的全部信息
* @param dice
* 骰子数
* @return Move 走子动作
*/
abstract public Move getMove(GameState gameState,byte dice);
abstract public Move getMove(PieceType turn, ChessBoard board,byte dice);
/**
* 处理敌方下棋动作
*
* @param move 敌方的下棋动作
*/
abstract public void processEnemyMove(Move move);
/**
* 初始化,仅游戏开始时调用
*
* @param gameState 游戏状态
* @param myTurn 我方棋子颜色
*/
abstract public void processStart(GameState gameState,PieceType myTurn);
/**
* 处理悔棋动作
*
* @param gameState 悔棋后的游戏状态
* @param move 悔的动作
*/
abstract public void processBack(GameState gameState,Move move);
/**
* 游戏结束时调用
*/
abstract public void processEnd();
/**
* 获取策略预测的价值
*
* @return double 价值
*/
public double getMoveValue(){
return this.value;
}
/**
* 获取搜索深度
*
* @return int 搜索深度
*/
public int getMaxDepth() {
return this.maxDepth;
}
/**
* 获取迭代次数
*
* @return 迭代次数
*/
public int getVisitNum() {
return this.visitNum;
}
/**
* 获取运行时间
*
* @return 运行时间
*/
public long getRunTime() {
return this.runTime;
}
/**
* 偷懒写法
* @see java.lang.Object#clone()
*/
@Override
public MoveStrategy clone(){
return this.clone();
}
}
| 15.864865 | 77 | 0.549404 |
9651b81be73db5655f4d8e67c28812ed9b932e7e | 5,723 | package com.builtbroken.mc.lib.asm;
import com.builtbroken.mc.core.Engine;
import cpw.mods.fml.common.asm.transformers.deobf.FMLDeobfuscatingRemapper;
import net.minecraft.launchwrapper.IClassTransformer;
import net.minecraft.launchwrapper.LaunchClassLoader;
import org.objectweb.asm.tree.ClassNode;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
/**
* This is added as a class transformer if CodeChickenCore is installed. Adding it as a class
* transformer will speed evaluation up slightly by automatically caching superclasses when they are
* first loaded.
*/
public class ClassHeirachyManager implements IClassTransformer
{
public static HashMap<String, SuperCache> superclasses = new HashMap<>();
private static LaunchClassLoader cl = (LaunchClassLoader) ClassHeirachyManager.class.getClassLoader();
static
{
cl.addTransformerExclusion("codechicken.lib.asm");
}
public static String toKey(String name)
{
if (ObfMapping.obfuscated)
{
name = FMLDeobfuscatingRemapper.INSTANCE.map(name.replace('.', '/')).replace('/', '.');
}
return name;
}
public static String unKey(String name)
{
if (ObfMapping.obfuscated)
{
name = FMLDeobfuscatingRemapper.INSTANCE.unmap(name.replace('.', '/')).replace('/', '.');
}
return name;
}
/**
* Returns true if clazz extends, either directly or indirectly, superclass.
*
* @param name The class in question
* @param superclass The class being extended
* @return
*/
public static boolean classExtends(String name, String superclass)
{
name = toKey(name);
superclass = toKey(superclass);
if (name.equals(superclass))
{
return true;
}
SuperCache cache = declareClass(name);
if (cache == null)// just can't handle this
{
return false;
}
cache.flatten();
return cache.parents.contains(superclass);
}
private static SuperCache declareClass(String name)
{
name = toKey(name);
SuperCache cache = superclasses.get(name);
if (cache != null)
{
return cache;
}
try
{
byte[] bytes = cl.getClassBytes(unKey(name));
if (bytes != null)
{
cache = declareASM(bytes);
}
} catch (IOException e)
{
Engine.instance.logger().catching(e);
}
if (cache != null)
{
return cache;
}
try
{
cache = declareReflection(name);
} catch (ClassNotFoundException e)
{
Engine.instance.logger().catching(e);
}
return cache;
}
private static SuperCache declareReflection(String name) throws ClassNotFoundException
{
Class<?> aclass = Class.forName(name);
SuperCache cache = getOrCreateCache(name);
if (aclass.isInterface())
{
cache.superclass = "java.lang.Object";
}
else if (name.equals("java.lang.Object"))
{
return cache;
}
else
{
cache.superclass = toKey(aclass.getSuperclass().getName());
}
cache.add(cache.superclass);
for (Class<?> iclass : aclass.getInterfaces())
{
cache.add(toKey(iclass.getName()));
}
return cache;
}
private static SuperCache declareASM(byte[] bytes)
{
ClassNode node = ASMHelper.createClassNode(bytes);
String name = toKey(node.name);
SuperCache cache = getOrCreateCache(name);
cache.superclass = toKey(node.superName.replace('/', '.'));
cache.add(cache.superclass);
for (String iclass : node.interfaces)
{
cache.add(toKey(iclass.replace('/', '.')));
}
return cache;
}
public static SuperCache getOrCreateCache(String name)
{
SuperCache cache = superclasses.get(name);
if (cache == null)
{
superclasses.put(name, cache = new SuperCache());
}
return cache;
}
public static String getSuperClass(String name, boolean runtime)
{
name = toKey(name);
SuperCache cache = declareClass(name);
if (cache == null)
{
return "java.lang.Object";
}
cache.flatten();
String s = cache.superclass;
if (!runtime)
{
s = FMLDeobfuscatingRemapper.INSTANCE.unmap(s);
}
return s;
}
@Override
public byte[] transform(String name, String tname, byte[] bytes)
{
if (bytes == null)
{
return null;
}
if (!superclasses.containsKey(tname))
{
declareASM(bytes);
}
return bytes;
}
public static class SuperCache
{
public HashSet<String> parents = new HashSet<>();
String superclass;
private boolean flattened;
public void add(String parent)
{
parents.add(parent);
}
public void flatten()
{
if (flattened)
{
return;
}
for (String s : new ArrayList<>(parents))
{
SuperCache c = declareClass(s);
if (c != null)
{
c.flatten();
parents.addAll(c.parents);
}
}
flattened = true;
}
}
}
| 24.882609 | 106 | 0.550411 |
7cddb124a5025f3ffddcc5b8e55107faec12476f | 3,184 | package com.fc.cps.action;
import com.fc.cps.global.*;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//@WebServlet("/VerifyCodeAction")
public class VerifyCodeAction extends HttpServlet {
private static final long serialVersionUID = 1L;
private String codeNumber = "";
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
BufferedImage bufferedImage = new BufferedImage(VerifyCodeConstants.getImageWidth(), VerifyCodeConstants.getImageHeight(), BufferedImage.TYPE_INT_RGB);
Graphics graphics = bufferedImage.getGraphics();
graphics.setColor(createRandomColor(200, 250));
graphics.fillRect(0, 0, VerifyCodeConstants.getImageWidth(), VerifyCodeConstants.getImageHeight());
for(int i = 0; i < 4; i++)
drawCode(graphics, i);
drawNoise(graphics, 12);
ServletOutputStream servletOutputStream = response.getOutputStream();
ImageIO.write(bufferedImage, "GIF", servletOutputStream);
servletOutputStream.close();
System.out.println("执行CodeAction方法,生成的验证码为:"+codeNumber);
VerifyCodeConstants.setCodeNumber(codeNumber);
codeNumber = "";
}
private void drawCode(Graphics graphics, int i) {
Random random = new Random();
int subBegin = random.nextInt(VerifyCodeConstants.getImageChar().length());
String number = VerifyCodeConstants.getImageChar().substring(subBegin, subBegin+1);
graphics.setFont(VerifyCodeConstants.getCodeFont()[i]);
graphics.setColor(VerifyCodeConstants.getColor()[i]);
graphics.drawString(number, 20 + i * 20, 30);
codeNumber += number;
}
private Color createRandomColor(int fc, int bc) {// 给定范围获得随机颜色
// 随机对象
Random random = new Random();
// 随机初始数值不得大于255
if (fc > 255)
fc = 255;
// 随机初始数值不得大于255
if (bc > 255)
bc = 255;
// 产生随机红蓝绿色调
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
private void drawNoise(Graphics graphics, int lineNumber) {
// 干扰线颜色
graphics.setColor(createRandomColor(160, 200));
for (int i = 0; i < lineNumber; i++) {
// 线的启示X轴(只在80,20的范围内随机,由于从零开始,所以要加一)
int pointX1 = 1 + (int) (Math.random() * 120);
// 线的启示Y轴(只在80,20的范围内随机,由于从零开始,所以要加一)
int pointY1 = 1 + (int) (Math.random() * 40);
// 线的终止X轴(只在80,20的范围内随机,由于从零开始,所以要加一)
int pointX2 = 1 + (int) (Math.random() * 120);
// 线的终止Y轴(只在80,20的范围内随机,由于从零开始,所以要加一)
int pointY2 = 1 + (int) (Math.random() * 40);
graphics.drawLine(pointX1, pointY1, pointX2, pointY2);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
| 32.824742 | 154 | 0.709799 |
d4340675a9e907416a2f16b3cd464dbbc5f5761a | 1,060 | package cn.smile.smilemall.gateway.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import java.time.Duration;
/**
* @author Smile
* @Documents
* @date 2021-01-2021/1/7
*/
@Configuration
public class SmileMallCorsConfig {
@Bean
public CorsWebFilter corsWebFilter() {
UrlBasedCorsConfigurationSource configurationSource = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.setAllowCredentials(true);
corsConfiguration.setMaxAge(Duration.ofHours(1));
configurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsWebFilter(configurationSource);
}
}
| 33.125 | 94 | 0.814151 |
442ce883baf5e0abf8ab96e539552a56647869d2 | 1,963 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.kylin.rest.security;
import java.util.List;
import java.util.Set;
import org.apache.kylin.common.KylinConfig;
import org.apache.kylin.metadata.acl.TableACLManager;
import org.apache.kylin.query.relnode.OLAPContext;
import org.apache.kylin.query.security.QueryIntercept;
import org.apache.kylin.query.security.QueryInterceptUtil;
public class TableIntercept extends QueryIntercept{
@Override
protected boolean isEnabled() {
return KylinConfig.getInstanceFromEnv().isTableACLEnabled();
}
@Override
public Set<String> getQueryIdentifiers(List<OLAPContext> contexts) {
return QueryInterceptUtil.getAllTblsWithSchema(contexts);
}
@Override
protected Set<String> getIdentifierBlackList(List<OLAPContext> contexts) {
String project = getProject(contexts);
String username = getUser(contexts);
return TableACLManager
.getInstance(KylinConfig.getInstanceFromEnv())
.getTableACLByCache(project)
.getTableBlackList(username);
}
@Override
protected String getIdentifierType() {
return "table";
}
}
| 33.844828 | 78 | 0.733571 |
8aeeede492b3ddd8e1fae71a5f64c63d30079fa2 | 4,318 | package com.wendyomollo.nipate;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
@BindView(R.id.buttonView) Button mGoToLogin;
@BindView(R.id.userName) EditText mEditName;
@BindView(R.id.userEmail) EditText mEditEmail;
@BindView(R.id.userPassword) EditText mEditPassword;
@BindView(R.id.loginLink) TextView login;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private ProgressDialog mProgress;
private DatabaseReference mDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProgress = new ProgressDialog(this);
mAuth = FirebaseAuth.getInstance();
ButterKnife.bind(this);
mGoToLogin.setOnClickListener(this);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, loginActivity.class);
startActivity(intent);
}
});
}
@Override
public void onClick(View view) {
startRegister();
}
private void startRegister() {
final String name = mEditName.getText().toString().trim();
final String email = mEditEmail.getText().toString().trim();
String password = mEditPassword.getText().toString().trim();
boolean validEmail = isValidEmail(email);
boolean validName = isValidName(name);
boolean validPassword = isValidPassword(password);
if (!validEmail || !validName || !validPassword) return;
if(!TextUtils.isEmpty(name) && !TextUtils.isEmpty(email) && !TextUtils.isEmpty(password)){
mProgress.setMessage("Signing Up");
mProgress.show();
mAuth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
mProgress.dismiss();
Toast.makeText(MainActivity.this,"Authentication successful",Toast.LENGTH_LONG).show();
Intent intent = new Intent(MainActivity.this, loginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}else{
Toast.makeText(MainActivity.this,"Authentication failed",Toast.LENGTH_SHORT).show();
}
}
});
}
}
private boolean isValidEmail(String email) {
boolean isGoodEmail =
(email != null && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches());
if (!isGoodEmail) {
mEditEmail.setError("Please enter a valid email address");
return false;
}
return isGoodEmail;
}
private boolean isValidName(String name) {
if (name.equals("")) {
mEditName.setError("Please enter your name");
return false;
}
return true;
}
private boolean isValidPassword(String password) {
if (password.length() < 6) {
mEditPassword.setError("Please create a password containing at least 6 characters");
return false;
}
return true;
}
}
| 33.215385 | 111 | 0.646364 |
0796fcb0b40e3d3929e33ce78bad64408d8d232b | 1,273 | package com.simibubi.create.foundation.utility;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import com.simibubi.create.Create;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.TranslatableComponent;
import net.minecraft.world.entity.player.Player;
public class Lang {
public static TranslatableComponent translate(String key, Object... args) {
return createTranslationTextComponent(key, args);
}
public static TranslatableComponent createTranslationTextComponent(String key, Object... args) {
return new TranslatableComponent(Create.ID + "." + key, args);
}
public static void sendStatus(Player player, String key, Object... args) {
player.displayClientMessage(createTranslationTextComponent(key, args), true);
}
public static List<Component> translatedOptions(String prefix, String... keys) {
List<Component> result = new ArrayList<>(keys.length);
for (String key : keys)
result.add(translate(prefix + "." + key));
return result;
}
public static String asId(String name) {
return name.toLowerCase(Locale.ROOT);
}
public static String nonPluralId(String name) {
String asId = asId(name);
return asId.endsWith("s") ? asId.substring(0, asId.length() - 1) : asId;
}
}
| 28.288889 | 97 | 0.752553 |
29f4f5704268e4572ed9265568a5bbfec7af11a1 | 1,705 |
package com.wavemaker.tools.deployment.cloudfoundry.archive;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.cloudfoundry.client.lib.archive.ApplicationArchive.Entry;
import org.junit.Test;
import org.springframework.util.FileCopyUtils;
/**
* Tests for {@link StringReplaceContentModifier}.
*
* @author Phillip Webb
*/
public class StringReplaceContentModifierTest {
@Test
public void shouldModifyMatchingEntries() throws Exception {
StringReplaceContentModifier modifier = new StringReplaceContentModifier().forEntryName("a", "c");
assertThat(modifier.canModify(mockEntry("a")), is(true));
assertThat(modifier.canModify(mockEntry("b")), is(false));
assertThat(modifier.canModify(mockEntry("c")), is(true));
}
@Test
public void shouldModifyContent() throws Exception {
StringReplaceContentModifier modifier = new StringReplaceContentModifier().forEntryName("a").replaceAll("a", "b").replaceAll("b", "c");
Entry entry = mockEntry("a");
given(entry.getInputStream()).willReturn(new ByteArrayInputStream("abc".getBytes()));
InputStream modified = modifier.modify(entry.getInputStream());
String actual = FileCopyUtils.copyToString(new InputStreamReader(modified));
assertThat(actual, is("ccc"));
}
private Entry mockEntry(String name) {
Entry entry = mock(Entry.class);
given(entry.getName()).willReturn(name);
return entry;
}
}
| 34.795918 | 143 | 0.725513 |
9da7925d1ab3268f00b348a1bf26ade26a22f1ae | 772 | package com.sicdlib.controller;
import com.sicdlib.service.IArticleSimiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
/**
* Created by YH on 2017/6/5.
*/
@Controller
public class ArticleSimiController {
@Autowired
@Qualifier("articleSimiService")
private IArticleSimiService articleSimiService;
@RequestMapping("setArticleSimi")
public void ArticleSimi(HttpServletRequest req) {
String eventID = req.getParameter("eventID");
articleSimiService.setEventArticleSimi(eventID);
}
}
| 28.592593 | 62 | 0.787565 |
bec1d82c5086add7686d9d9184f6a3fb00d9fd7c | 4,714 | package yokohama.yellow_man.sena.jobs;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import play.Play;
import yokohama.yellow_man.common_tools.CheckUtils;
import yokohama.yellow_man.sena.components.db.FinancesComponent;
import yokohama.yellow_man.sena.components.db.StocksComponent;
import yokohama.yellow_man.sena.core.components.AppLogger;
import yokohama.yellow_man.sena.core.definitions.AppConsts;
import yokohama.yellow_man.sena.core.models.Finances;
import yokohama.yellow_man.sena.core.models.Stocks;
import yokohama.yellow_man.sena.jobs.JobExecutor.JobArgument;
/**
* 企業財務情報前年比更新バッチクラス。
* <p>財務(finances)テーブルの下記情報を更新する。
* <ul>
* <li>売上高(前年比)sales_rate
* <li>営業益(前年比)operating_profit_rate
* <li>純利益(前年比)net_profit_rate
* </ul>
*
* @author yellow-man
* @since 1.0.0-1.0
* @version 1.1.0-1.2
*/
public class UpdateFinancesSetRate extends AppLoggerMailJob {
/**
* メールタイトル
* {@code application.conf}ファイル{@code update_finances_set_rate.mail_title}キーにて値の変更可。
*/
private static final String UPDATE_FINANCES_SET_RATE_MAIL_TITLE = Play.application().configuration().getString("update_finances_set_rate.mail_title", "[sena]企業財務情報前年比更新バッチ実行結果");
/**
* 企業財務情報前年比更新バッチクラスコンストラクタ。
* @since 1.0.0-1.0
*/
public UpdateFinancesSetRate() {
// メールタイトル
this.emailTitle = UPDATE_FINANCES_SET_RATE_MAIL_TITLE;
// ログファイル名
this.logFileName = getClass().getName() + "." + this.logDateFormat.format(new Date()) + ".log";
// ログファイルpath
this.logFilePath = LOG_FILE_PATH + getClass().getName() + "/" + this.logFileName;
}
/**
* @see yokohama.yellow_man.sena.jobs.AppJob#run(yokohama.yellow_man.sena.jobs.JobExecutor.JobArgument)
* @since 1.1.0-1.2
*/
@Override
protected void run(JobArgument args) {
AppLogger.info("企業財務情報前年比更新バッチ 開始");
// 成功件数
int success = 0;
// エラー件数
int error = 0;
// 銘柄情報取得
List<Stocks> stocksList = StocksComponent.getStocksList();
if (CheckUtils.isEmpty(stocksList)) {
AppLogger.warn("銘柄情報が取得できませんでした。");
} else {
for (Stocks stocks : stocksList) {
Integer stockCode = stocks.stockCode;
String stockName = stocks.stockName;
boolean isError = false;
for (Integer settlementTypesId : AppConsts.SETTLEMENT_TYPES_ID_LIST) {
try {
// 企業財務を取得
List<Finances> financesList = FinancesComponent.getFinancesByStockCodeSettlementTypesIdList(stockCode, settlementTypesId);
if (CheckUtils.isEmpty(financesList)) {
AppLogger.warn(new StringBuffer("財務リストが取得できませんでした。:")
.append(stockCode).append(":").append(stockName).append(":").append(AppConsts.SETTLEMENT_TYPES_ID_MAP_STR.get(settlementTypesId))
.toString());
} else {
int size = financesList.size();
if(size > 1){
for(int j = 0; j + 1 < size; j++){
Finances finance = financesList.get(j);
Finances nextYearFinance = financesList.get(j + 1);
if (finance.salesRate == null) {
BigDecimal financeSales = new BigDecimal(finance.sales);
BigDecimal nextYearFinanceSales = new BigDecimal(nextYearFinance.sales);
finance.salesRate = financeSales.subtract(nextYearFinanceSales).divide(nextYearFinanceSales, 25, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100"));;
}
if (finance.operatingProfitRate == null) {
BigDecimal financeOperatingProfit = new BigDecimal(finance.operatingProfit);
BigDecimal nextYearFinanceOperatingProfit = new BigDecimal(nextYearFinance.operatingProfit);
finance.operatingProfitRate = financeOperatingProfit.subtract(nextYearFinanceOperatingProfit).divide(nextYearFinanceOperatingProfit, 25, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100"));;
}
if (finance.netProfitRate == null) {
BigDecimal financeNetProfit = new BigDecimal(finance.netProfit);
BigDecimal nextYearFinanceNetProfit = new BigDecimal(nextYearFinance.netProfit);
finance.netProfitRate = financeNetProfit.subtract(nextYearFinanceNetProfit).divide(nextYearFinanceNetProfit, 25, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100"));;
}
finance.save();
}
}
}
} catch (Exception e) {
AppLogger.error(new StringBuffer("財務DB保存時にエラーが発生しました。:")
.append(stockCode).append(":").append(stockName).append(":").append(AppConsts.SETTLEMENT_TYPES_ID_MAP_STR.get(settlementTypesId))
.toString(), e);
isError = true;
continue;
}
}
if (isError) {
error++;
} else {
success++;
}
}
}
AppLogger.info("企業財務情報前年比更新バッチ 終了:処理件数=" + String.valueOf(success + error) + ", 成功件数=" + success + ", 失敗件数=" + error);
}
}
| 35.179104 | 206 | 0.70577 |
6010f103df19a3975112022bce0f4cae2ae6c307 | 17,509 | /*
* Copyright (c) Microsoft Corporation.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.playwright;
import com.sun.net.httpserver.*;
import java.io.*;
import java.net.InetSocketAddress;
import java.nio.file.FileSystems;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.zip.GZIPOutputStream;
import static com.microsoft.playwright.Utils.copy;
public class Server implements HttpHandler {
private final HttpServer server;
public final String PREFIX;
public final String CROSS_PROCESS_PREFIX;
public final int PORT;
public final String EMPTY_PAGE;
private final File resourcesDir;
private final Map<String, CompletableFuture<Request>> requestSubscribers = Collections.synchronizedMap(new HashMap<>());
private final Map<String, Auth> auths = Collections.synchronizedMap(new HashMap<>());
private final Map<String, String> csp = Collections.synchronizedMap(new HashMap<>());
private final Map<String, HttpHandler> routes = Collections.synchronizedMap(new HashMap<>());
private final Set<String> gzipRoutes = Collections.synchronizedSet(new HashSet<>());
private static class Auth {
public final String user;
public final String password;
private Auth(String user, String password) {
this.user = user;
this.password = password;
}
}
static Server createHttp(int port) throws IOException {
return new Server(port, false);
}
static Server createHttps(int port) throws IOException {
return new Server(port, true);
}
private Server(int port, boolean https) throws IOException {
PORT = port;
PREFIX = "http" + (https ? "s" : "") + "://localhost:" + PORT;
CROSS_PROCESS_PREFIX = "http" + (https ? "s" : "") + "://127.0.0.1:" + PORT;
EMPTY_PAGE = PREFIX + "/empty.html";
if (https) {
HttpsServer httpsServer = HttpsServer.create(new InetSocketAddress("localhost", port), 0);
httpsServer.setHttpsConfigurator(HttpsConfiguratorImpl.create());
server = httpsServer;
} else {
server = HttpServer.create(new InetSocketAddress("localhost", port), 0);
}
server.createContext("/", this);
server.setExecutor(null); // creates a default executor
File cwd = FileSystems.getDefault().getPath(".").toFile();
resourcesDir = new File(cwd, "src/test/resources");
server.start();
}
void stop() {
server.stop(0);
}
void setAuth(String path, String user, String password) {
auths.put(path, new Auth(user, password));
}
void setCSP(String path, String csp) {
this.csp.put(path, csp);
}
void enableGzip(String path) {
gzipRoutes.add(path);
}
static class Request {
public final String method;
// TODO: make a copy to ensure thread safety?
public final Headers headers;
public final byte[] postBody;
Request(HttpExchange exchange) throws IOException {
method = exchange.getRequestMethod();
headers = exchange.getRequestHeaders();
ByteArrayOutputStream out = new ByteArrayOutputStream();
copy(exchange.getRequestBody(), out);
postBody = out.toByteArray();
}
}
Future<Request> futureRequest(String path) {
CompletableFuture<Request> future = requestSubscribers.get(path);
if (future == null) {
future = new CompletableFuture<>();
requestSubscribers.put(path, future);
}
return future;
}
void setRoute(String path, HttpHandler handler) {
routes.put(path, handler);
}
void setRedirect(String from, String to) {
setRoute(from, exchange -> {
exchange.getResponseHeaders().put("location", Arrays.asList(to));
exchange.sendResponseHeaders(302, -1);
exchange.getResponseBody().close();
});
}
void reset() {
requestSubscribers.clear();
auths.clear();
csp.clear();
routes.clear();
gzipRoutes.clear();
}
@Override
public void handle(HttpExchange exchange) throws IOException {
String path = exchange.getRequestURI().getPath();
if (auths.containsKey(path)) {
List<String> header = exchange.getRequestHeaders().get("authorization");
boolean authorized = false;
if (header != null) {
String v = header.get(0);
String[] splits = v.split(" ");
if (splits.length == 2) {
String credentials = new String(Base64.getDecoder().decode(splits[1]));
Auth auth = auths.get(path);
authorized = credentials.equals(auth.user + ":" + auth.password);
}
}
if (!authorized) {
exchange.getResponseHeaders().add("WWW-Authenticate", "Basic realm=\"Secure Area\"");
exchange.sendResponseHeaders(401, 0);
try (Writer writer = new OutputStreamWriter(exchange.getResponseBody())) {
writer.write("HTTP Error 401 Unauthorized: Access is denied");
// TODO: notify subscriber?
exchange.getResponseBody().close();
}
return;
}
}
synchronized (requestSubscribers) {
CompletableFuture<Request> subscriber = requestSubscribers.get(path);
if (subscriber != null) {
requestSubscribers.remove(path);
subscriber.complete(new Request(exchange));
}
}
HttpHandler handler = routes.get(path);
if (handler != null) {
handler.handle(exchange);
return;
}
if (csp.containsKey(path)) {
exchange.getResponseHeaders().add("Content-Security-Policy", csp.get(path));
}
if ("/".equals(path)) {
path = "/index.html";
}
File file = new File(resourcesDir, path.substring(1));
if (!file.exists()) {
exchange.sendResponseHeaders(404, 0);
try (Writer writer = new OutputStreamWriter(exchange.getResponseBody())) {
writer.write("File not found: " + file.getCanonicalPath());
}
return;
}
exchange.getResponseHeaders().add("Content-Type", mimeType(file));
ByteArrayOutputStream body = new ByteArrayOutputStream();
OutputStream output = body;
if (gzipRoutes.contains(path)) {
exchange.getResponseHeaders().add("Content-Encoding", "gzip");
}
try (FileInputStream input = new FileInputStream(file)) {
if (gzipRoutes.contains(path)) {
output = new GZIPOutputStream(output);
}
copy(input, output);
output.close();
} catch (IOException e) {
body.reset();
try (Writer writer = new OutputStreamWriter(output)) {
writer.write("Exception: " + e);
}
}
long contentLength = body.size();
// -1 means no body, 0 means chunked encoding.
exchange.sendResponseHeaders(200, contentLength == 0 ? -1 : contentLength);
if (contentLength > 0) {
exchange.getResponseBody().write(body.toByteArray());
}
exchange.getResponseBody().close();
}
private static String mimeType(File file) {
String name = file.getName();
int lastDotPos = name.lastIndexOf('.');
String extension = lastDotPos == -1 ? name : name.substring(lastDotPos + 1);
String mimeType = extensionToMime.get(extension);
if (mimeType == null) {
mimeType = "application/octet-stream";
}
return mimeType;
}
private static Map<String, String> extensionToMime = new HashMap<>();
static {
extensionToMime.put("ai", "application/postscript");
extensionToMime.put("apng", "image/apng");
extensionToMime.put("appcache", "text/cache-manifest");
extensionToMime.put("au", "audio/basic");
extensionToMime.put("bmp", "image/bmp");
extensionToMime.put("cer", "application/pkix-cert");
extensionToMime.put("cgm", "image/cgm");
extensionToMime.put("coffee", "text/coffeescript");
extensionToMime.put("conf", "text/plain");
extensionToMime.put("crl", "application/pkix-crl");
extensionToMime.put("css", "text/css");
extensionToMime.put("csv", "text/csv");
extensionToMime.put("def", "text/plain");
extensionToMime.put("doc", "application/msword");
extensionToMime.put("dot", "application/msword");
extensionToMime.put("drle", "image/dicom-rle");
extensionToMime.put("dtd", "application/xml-dtd");
extensionToMime.put("ear", "application/java-archive");
extensionToMime.put("emf", "image/emf");
extensionToMime.put("eps", "application/postscript");
extensionToMime.put("exr", "image/aces");
extensionToMime.put("fits", "image/fits");
extensionToMime.put("g3", "image/g3fax");
extensionToMime.put("gbr", "application/rpki-ghostbusters");
extensionToMime.put("gif", "image/gif");
extensionToMime.put("glb", "model/gltf-binary");
extensionToMime.put("gltf", "model/gltf+json");
extensionToMime.put("gz", "application/gzip");
extensionToMime.put("h261", "video/h261");
extensionToMime.put("h263", "video/h263");
extensionToMime.put("h264", "video/h264");
extensionToMime.put("heic", "image/heic");
extensionToMime.put("heics", "image/heic-sequence");
extensionToMime.put("heif", "image/heif");
extensionToMime.put("heifs", "image/heif-sequence");
extensionToMime.put("htm", "text/html");
extensionToMime.put("html", "text/html");
extensionToMime.put("ics", "text/calendar");
extensionToMime.put("ief", "image/ief");
extensionToMime.put("ifb", "text/calendar");
extensionToMime.put("iges", "model/iges");
extensionToMime.put("igs", "model/iges");
extensionToMime.put("in", "text/plain");
extensionToMime.put("ini", "text/plain");
extensionToMime.put("jade", "text/jade");
extensionToMime.put("jar", "application/java-archive");
extensionToMime.put("jls", "image/jls");
extensionToMime.put("jp2", "image/jp2");
extensionToMime.put("jpe", "image/jpeg");
extensionToMime.put("jpeg", "image/jpeg");
extensionToMime.put("jpf", "image/jpx");
extensionToMime.put("jpg", "image/jpeg");
extensionToMime.put("jpg2", "image/jp2");
extensionToMime.put("jpgm", "video/jpm");
extensionToMime.put("jpgv", "video/jpeg");
extensionToMime.put("jpm", "image/jpm");
extensionToMime.put("jpx", "image/jpx");
extensionToMime.put("js", "application/javascript");
extensionToMime.put("json", "application/json");
extensionToMime.put("json5", "application/json5");
extensionToMime.put("jsx", "text/jsx");
extensionToMime.put("jxr", "image/jxr");
extensionToMime.put("kar", "audio/midi");
extensionToMime.put("ktx", "image/ktx");
extensionToMime.put("less", "text/less");
extensionToMime.put("list", "text/plain");
extensionToMime.put("litcoffee", "text/coffeescript");
extensionToMime.put("log", "text/plain");
extensionToMime.put("m1v", "video/mpeg");
extensionToMime.put("m21", "application/mp21");
extensionToMime.put("m2a", "audio/mpeg");
extensionToMime.put("m2v", "video/mpeg");
extensionToMime.put("m3a", "audio/mpeg");
extensionToMime.put("m4a", "audio/mp4");
extensionToMime.put("m4p", "application/mp4");
extensionToMime.put("man", "text/troff");
extensionToMime.put("manifest", "text/cache-manifest");
extensionToMime.put("markdown", "text/markdown");
extensionToMime.put("mathml", "application/mathml+xml");
extensionToMime.put("md", "text/markdown");
extensionToMime.put("mdx", "text/mdx");
extensionToMime.put("me", "text/troff");
extensionToMime.put("mesh", "model/mesh");
extensionToMime.put("mft", "application/rpki-manifest");
extensionToMime.put("mid", "audio/midi");
extensionToMime.put("midi", "audio/midi");
extensionToMime.put("mj2", "video/mj2");
extensionToMime.put("mjp2", "video/mj2");
extensionToMime.put("mjs", "application/javascript");
extensionToMime.put("mml", "text/mathml");
extensionToMime.put("mov", "video/quicktime");
extensionToMime.put("mp2", "audio/mpeg");
extensionToMime.put("mp21", "application/mp21");
extensionToMime.put("mp2a", "audio/mpeg");
extensionToMime.put("mp3", "audio/mpeg");
extensionToMime.put("mp4", "video/mp4");
extensionToMime.put("mp4a", "audio/mp4");
extensionToMime.put("mp4s", "application/mp4");
extensionToMime.put("mp4v", "video/mp4");
extensionToMime.put("mpe", "video/mpeg");
extensionToMime.put("mpeg", "video/mpeg");
extensionToMime.put("mpg", "video/mpeg");
extensionToMime.put("mpg4", "video/mp4");
extensionToMime.put("mpga", "audio/mpeg");
extensionToMime.put("mrc", "application/marc");
extensionToMime.put("ms", "text/troff");
extensionToMime.put("msh", "model/mesh");
extensionToMime.put("n3", "text/n3");
extensionToMime.put("oga", "audio/ogg");
extensionToMime.put("ogg", "audio/ogg");
extensionToMime.put("ogv", "video/ogg");
extensionToMime.put("ogx", "application/ogg");
extensionToMime.put("otf", "font/otf");
extensionToMime.put("p10", "application/pkcs10");
extensionToMime.put("p7c", "application/pkcs7-mime");
extensionToMime.put("p7m", "application/pkcs7-mime");
extensionToMime.put("p7s", "application/pkcs7-signature");
extensionToMime.put("p8", "application/pkcs8");
extensionToMime.put("pdf", "application/pdf");
extensionToMime.put("pki", "application/pkixcmp");
extensionToMime.put("pkipath", "application/pkix-pkipath");
extensionToMime.put("png", "image/png");
extensionToMime.put("ps", "application/postscript");
extensionToMime.put("pskcxml", "application/pskc+xml");
extensionToMime.put("qt", "video/quicktime");
extensionToMime.put("rmi", "audio/midi");
extensionToMime.put("rng", "application/xml");
extensionToMime.put("roa", "application/rpki-roa");
extensionToMime.put("roff", "text/troff");
extensionToMime.put("rsd", "application/rsd+xml");
extensionToMime.put("rss", "application/rss+xml");
extensionToMime.put("rtf", "application/rtf");
extensionToMime.put("rtx", "text/richtext");
extensionToMime.put("s3m", "audio/s3m");
extensionToMime.put("sgi", "image/sgi");
extensionToMime.put("sgm", "text/sgml");
extensionToMime.put("sgml", "text/sgml");
extensionToMime.put("shex", "text/shex");
extensionToMime.put("shtml", "text/html");
extensionToMime.put("sil", "audio/silk");
extensionToMime.put("silo", "model/mesh");
extensionToMime.put("slim", "text/slim");
extensionToMime.put("slm", "text/slim");
extensionToMime.put("snd", "audio/basic");
extensionToMime.put("spx", "audio/ogg");
extensionToMime.put("stl", "model/stl");
extensionToMime.put("styl", "text/stylus");
extensionToMime.put("stylus", "text/stylus");
extensionToMime.put("svg", "image/svg+xml");
extensionToMime.put("svgz", "image/svg+xml");
extensionToMime.put("t", "text/troff");
extensionToMime.put("t38", "image/t38");
extensionToMime.put("text", "text/plain");
extensionToMime.put("tfx", "image/tiff-fx");
extensionToMime.put("tif", "image/tiff");
extensionToMime.put("tiff", "image/tiff");
extensionToMime.put("tr", "text/troff");
extensionToMime.put("ts", "video/mp2t");
extensionToMime.put("tsv", "text/tab-separated-values");
extensionToMime.put("ttc", "font/collection");
extensionToMime.put("ttf", "font/ttf");
extensionToMime.put("ttl", "text/turtle");
extensionToMime.put("txt", "text/plain");
extensionToMime.put("uri", "text/uri-list");
extensionToMime.put("uris", "text/uri-list");
extensionToMime.put("urls", "text/uri-list");
extensionToMime.put("vcard", "text/vcard");
extensionToMime.put("vrml", "model/vrml");
extensionToMime.put("vtt", "text/vtt");
extensionToMime.put("war", "application/java-archive");
extensionToMime.put("wasm", "application/wasm");
extensionToMime.put("wav", "audio/wav");
extensionToMime.put("weba", "audio/webm");
extensionToMime.put("webm", "video/webm");
extensionToMime.put("webmanifest", "application/manifest+json");
extensionToMime.put("webp", "image/webp");
extensionToMime.put("wmf", "image/wmf");
extensionToMime.put("woff", "font/woff");
extensionToMime.put("woff2", "font/woff2");
extensionToMime.put("wrl", "model/vrml");
extensionToMime.put("x3d", "model/x3d+xml");
extensionToMime.put("x3db", "model/x3d+fastinfoset");
extensionToMime.put("x3dbz", "model/x3d+binary");
extensionToMime.put("x3dv", "model/x3d-vrml");
extensionToMime.put("x3dvz", "model/x3d+vrml");
extensionToMime.put("x3dz", "model/x3d+xml");
extensionToMime.put("xaml", "application/xaml+xml");
extensionToMime.put("xht", "application/xhtml+xml");
extensionToMime.put("xhtml", "application/xhtml+xml");
extensionToMime.put("xm", "audio/xm");
extensionToMime.put("xml", "text/xml");
extensionToMime.put("xsd", "application/xml");
extensionToMime.put("xsl", "application/xml");
extensionToMime.put("xslt", "application/xslt+xml");
extensionToMime.put("yaml", "text/yaml");
extensionToMime.put("yml", "text/yaml");
extensionToMime.put("zip", "application/zip");
}
}
| 39.613122 | 122 | 0.668628 |
01f40efb14017abcc99ad60612502858033a8e13 | 697 | package com.github.rich.base.feign.factory;
import com.github.rich.base.feign.GatewayRouteServiceFeignClient;
import com.github.rich.base.feign.fallback.GatewayRouteServiceFeignClientFallbackImpl;
import feign.hystrix.FallbackFactory;
/**
* @author Petty
*/
public class GatewayRouteServiceFallbackFactory implements FallbackFactory<GatewayRouteServiceFeignClient> {
@Override
public GatewayRouteServiceFeignClient create(Throwable throwable) {
GatewayRouteServiceFeignClientFallbackImpl gatewayRouteServiceFallback = new GatewayRouteServiceFeignClientFallbackImpl();
gatewayRouteServiceFallback.setCause(throwable);
return gatewayRouteServiceFallback;
}
}
| 38.722222 | 130 | 0.824964 |
311a72a9925a2cc7cb62d142f3e6d3a5e3ca9467 | 9,552 | package com.sequenceiq.authorization.service;
import static com.sequenceiq.authorization.resource.AuthorizationResourceAction.DELETE_DATAHUB;
import static com.sequenceiq.authorization.resource.AuthorizationResourceAction.EDIT_CREDENTIAL;
import static com.sequenceiq.authorization.resource.AuthorizationVariableType.CRN;
import static com.sequenceiq.authorization.resource.AuthorizationVariableType.CRN_LIST;
import static com.sequenceiq.authorization.resource.AuthorizationVariableType.NAME;
import static com.sequenceiq.authorization.resource.AuthorizationVariableType.NAME_LIST;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyCollection;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.lang.annotation.Annotation;
import java.util.List;
import java.util.Optional;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.security.access.AccessDeniedException;
import com.sequenceiq.authorization.annotation.CheckPermissionByRequestProperty;
import com.sequenceiq.authorization.annotation.RequestObject;
import com.sequenceiq.authorization.resource.AuthorizationResourceAction;
import com.sequenceiq.authorization.resource.AuthorizationVariableType;
import com.sequenceiq.authorization.service.model.AuthorizationRule;
import com.sequenceiq.authorization.service.model.HasRight;
import com.sequenceiq.authorization.service.model.HasRightOnAll;
import com.sequenceiq.authorization.utils.CrnAccountValidator;
@RunWith(MockitoJUnitRunner.class)
public class RequestPropertyAuthorizationFactoryTest {
private static final String USER_CRN = "crn:cdp:iam:us-west-1:1234:user:5678";
private static final String RESOURCE_CRN = "crn:cdp:credential:us-west-1:1234:credential:5678";
private static final String RESOURCE_NAME = "resource";
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Mock
private CommonPermissionCheckingUtils commonPermissionCheckingUtils;
@Mock
private ResourceCrnAthorizationFactory resourceCrnAthorizationFactory;
@Mock
private ResourceNameAuthorizationFactory resourceNameAuthorizationFactory;
@Mock
private ResourceCrnListAuthorizationFactory resourceCrnListAuthorizationFactory;
@Mock
private ResourceNameListAuthorizationFactory resourceNameListAuthorizationFactory;
@Mock
private CrnAccountValidator crnAccountValidator;
@InjectMocks
private RequestPropertyAuthorizationFactory underTest;
@AfterEach
public void after() {
verify(commonPermissionCheckingUtils).getParameter(any(), any(), eq(RequestObject.class), eq(Object.class));
}
@Test
public void testOnCrn() {
when(commonPermissionCheckingUtils.getParameter(any(), any(), any(), any())).thenReturn(new SampleRequestObject(RESOURCE_CRN));
Optional<AuthorizationRule> expected = Optional.of(new HasRight(EDIT_CREDENTIAL, RESOURCE_CRN));
when(resourceCrnAthorizationFactory.calcAuthorization(anyString(), any()))
.thenReturn(expected);
Optional<AuthorizationRule> authorization = underTest.getAuthorization(getAnnotation(CRN, EDIT_CREDENTIAL, false, "field"), USER_CRN, null, null);
verify(resourceCrnAthorizationFactory).calcAuthorization(RESOURCE_CRN, EDIT_CREDENTIAL);
assertEquals(expected, authorization);
}
@Test
public void testOnCrnList() {
when(commonPermissionCheckingUtils.getParameter(any(), any(), any(), any())).thenReturn(new SampleRequestObject(List.of(RESOURCE_CRN)));
Optional<AuthorizationRule> expected = Optional.of(new HasRightOnAll(EDIT_CREDENTIAL, List.of(RESOURCE_CRN)));
when(resourceCrnListAuthorizationFactory.calcAuthorization(anyCollection(), any()))
.thenReturn(expected);
Optional<AuthorizationRule> authorization = underTest.getAuthorization(getAnnotation(CRN_LIST, EDIT_CREDENTIAL, false, "field"), USER_CRN, null, null);
verify(resourceCrnListAuthorizationFactory).calcAuthorization(List.of(RESOURCE_CRN), EDIT_CREDENTIAL);
assertEquals(expected, authorization);
}
@Test
public void testOnName() {
when(commonPermissionCheckingUtils.getParameter(any(), any(), any(), any())).thenReturn(new SampleRequestObject(RESOURCE_NAME));
Optional<AuthorizationRule> expected = Optional.of(new HasRight(DELETE_DATAHUB, RESOURCE_CRN));
when(resourceNameAuthorizationFactory.calcAuthorization(anyString(), any()))
.thenReturn(expected);
Optional<AuthorizationRule> authorization = underTest.getAuthorization(getAnnotation(NAME, DELETE_DATAHUB, false, "field"), USER_CRN, null, null);
verify(resourceNameAuthorizationFactory).calcAuthorization(RESOURCE_NAME, DELETE_DATAHUB);
assertEquals(expected, authorization);
}
@Test
public void testOnNameList() {
when(commonPermissionCheckingUtils.getParameter(any(), any(), any(), any())).thenReturn(new SampleRequestObject(List.of(RESOURCE_NAME)));
Optional<AuthorizationRule> expected = Optional.of(new HasRightOnAll(EDIT_CREDENTIAL, List.of(RESOURCE_CRN)));
when(resourceNameListAuthorizationFactory.calcAuthorization(anyCollection(), any()))
.thenReturn(expected);
Optional<AuthorizationRule> authorization = underTest.getAuthorization(getAnnotation(NAME_LIST, EDIT_CREDENTIAL, false, "field"), USER_CRN, null, null);
verify(resourceNameListAuthorizationFactory).calcAuthorization(List.of(RESOURCE_NAME), EDIT_CREDENTIAL);
assertEquals(expected, authorization);
}
@Test
public void testOnNullWhenNullAllowed() {
when(commonPermissionCheckingUtils.getParameter(any(), any(), any(), any())).thenReturn(new SampleRequestObject());
Optional<AuthorizationRule> authorization = underTest.getAuthorization(getAnnotation(CRN_LIST, EDIT_CREDENTIAL, true, "field"), USER_CRN, null, null);
assertEquals(Optional.empty(), authorization);
}
@Test
public void testOnNullWhenRequired() {
when(commonPermissionCheckingUtils.getParameter(any(), any(), any(), any())).thenReturn(new SampleRequestObject());
thrown.expect(AccessDeniedException.class);
thrown.expectMessage("Property [field] of request object is null and it should be authorized, thus should be filled in.");
underTest.getAuthorization(getAnnotation(CRN_LIST, EDIT_CREDENTIAL, false, "field"), USER_CRN, null, null);
}
@Test
public void testOnNestedNullWhenNullAllowed() {
when(commonPermissionCheckingUtils.getParameter(any(), any(), any(), any())).thenReturn(new SampleRequestObject(new SampleRequestObject()));
Optional<AuthorizationRule> authorization =
underTest.getAuthorization(getAnnotation(CRN_LIST, EDIT_CREDENTIAL, true, "field.field"), USER_CRN, null, null);
assertEquals(Optional.empty(), authorization);
}
@Test
public void testOnNestedNullWhenRequired() {
when(commonPermissionCheckingUtils.getParameter(any(), any(), any(), any())).thenReturn(new SampleRequestObject());
thrown.expect(AccessDeniedException.class);
thrown.expectMessage("Property [field.field] of request object is null and it should be authorized, thus should be filled in.");
underTest.getAuthorization(getAnnotation(CRN_LIST, EDIT_CREDENTIAL, false, "field.field"), USER_CRN, null, null);
}
@Test
public void testOnNonStringRequestField() {
when(commonPermissionCheckingUtils.getParameter(any(), any(), any(), any())).thenReturn(new SampleRequestObject(Integer.valueOf(0)));
thrown.expect(AccessDeniedException.class);
thrown.expectMessage("Referred property within request object is not string, thus access is denied!");
underTest.getAuthorization(getAnnotation(CRN, EDIT_CREDENTIAL, false, "field"), USER_CRN, null, null);
}
private CheckPermissionByRequestProperty getAnnotation(AuthorizationVariableType type, AuthorizationResourceAction action,
Boolean skipOnNull, String path) {
return new CheckPermissionByRequestProperty() {
@Override
public AuthorizationVariableType type() {
return type;
}
@Override
public AuthorizationResourceAction action() {
return action;
}
@Override
public boolean skipOnNull() {
return skipOnNull;
}
@Override
public String path() {
return path;
}
@Override
public Class<? extends Annotation> annotationType() {
return CheckPermissionByRequestProperty.class;
}
};
}
public static class SampleRequestObject {
private Object field;
public SampleRequestObject() {
}
public SampleRequestObject(Object field) {
this.field = field;
}
public Object getField() {
return field;
}
}
}
| 42.265487 | 160 | 0.738798 |
4da63ef10ad87cd2cbf8537afee09792832aeaff | 1,608 | /*
Copyright 2003 The Apache Software Foundation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.apache.batik.svggen;
import java.awt.geom.Rectangle2D;
import org.apache.batik.test.AbstractTest;
import org.apache.batik.test.TestReport;
import org.apache.batik.dom.GenericDOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.DOMImplementation;
/**
* Checks that no NullPointerException is thrown by default
*
* @author <a href="mailto:[email protected]">Vincent Hardy</a>
* @version $Id$
*/
public class DoubleString extends AbstractTest {
public TestReport runImpl() throws Exception {
// Get a DOMImplementation
DOMImplementation domImpl =
GenericDOMImplementation.getDOMImplementation();
// Create an instance of org.w3c.dom.Document
Document document = domImpl.createDocument(null, "svg", null);
SVGGraphics2D g = new SVGGraphics2D(document);
Rectangle2D r = new Rectangle2D.Float(0.5f, 0.5f, 2.33f, 2.33f);
g.fill(r);
return reportSuccess();
}
}
| 30.923077 | 75 | 0.714552 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.